diff --git a/chia/_tests/blockchain/blockchain_test_utils.py b/chia/_tests/blockchain/blockchain_test_utils.py index 3de9ff90553d..4bc137e5c258 100644 --- a/chia/_tests/blockchain/blockchain_test_utils.py +++ b/chia/_tests/blockchain/blockchain_test_utils.py @@ -116,11 +116,10 @@ async def _validate_and_add_block( if err is not None: # Got an error raise AssertionError(err) - else: - # Here we will enforce checking of the exact error - if err != expected_error: - # Did not get the right error, or did not get an error - raise AssertionError(f"Expected {expected_error} but got {err}") + # Here we will enforce checking of the exact error + elif err != expected_error: + # Did not get the right error, or did not get an error + raise AssertionError(f"Expected {expected_error} but got {err}") if expected_result is not None and expected_result != result: raise AssertionError(f"Expected {expected_result} but got {result}") diff --git a/chia/_tests/blockchain/test_augmented_chain.py b/chia/_tests/blockchain/test_augmented_chain.py index c9d751950ef7..cb7a729e5258 100644 --- a/chia/_tests/blockchain/test_augmented_chain.py +++ b/chia/_tests/blockchain/test_augmented_chain.py @@ -1,5 +1,6 @@ from __future__ import annotations +import re from dataclasses import dataclass, field from typing import TYPE_CHECKING, ClassVar, Optional, cast @@ -93,7 +94,7 @@ async def test_augmented_chain(default_10000_blocks: list[FullBlock]) -> None: with pytest.raises(KeyError): await abc.prev_block_hash([blocks[2].header_hash]) - with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"): + with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)): await abc.lookup_block_generators(blocks[3].header_hash, {uint32(3)}) block_records = [] @@ -105,11 +106,11 @@ async def test_augmented_chain(default_10000_blocks: list[FullBlock]) -> None: assert abc.height_to_block_record(uint32(1)) == block_records[1] - with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"): + with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)): await abc.lookup_block_generators(blocks[10].header_hash, {uint32(3), uint32(10)}) # block 1 exists in the chain, but it doesn't have a generator - with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"): + with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)): await abc.lookup_block_generators(blocks[1].header_hash, {uint32(1)}) expect_gen = blocks[2].transactions_generator diff --git a/chia/_tests/blockchain/test_blockchain.py b/chia/_tests/blockchain/test_blockchain.py index 0b8d639a6d87..0d144968bf27 100644 --- a/chia/_tests/blockchain/test_blockchain.py +++ b/chia/_tests/blockchain/test_blockchain.py @@ -4,6 +4,7 @@ import copy import logging import random +import re import time from collections.abc import AsyncIterator, Awaitable from contextlib import asynccontextmanager @@ -4158,24 +4159,24 @@ async def test_lookup_block_generators( # make sure we don't cross the forks if clear_cache: b.clean_block_records() - with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"): + with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)): await b.lookup_block_generators(peak_1.prev_header_hash, {uint32(516)}) if clear_cache: b.clean_block_records() - with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"): + with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)): await b.lookup_block_generators(peak_2.prev_header_hash, {uint32(503)}) # make sure we fail when looking up a non-transaction block from the main # chain, regardless of which chain we start at if clear_cache: b.clean_block_records() - with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"): + with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)): await b.lookup_block_generators(peak_1.prev_header_hash, {uint32(8)}) if clear_cache: b.clean_block_records() - with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"): + with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)): await b.lookup_block_generators(peak_2.prev_header_hash, {uint32(8)}) # if we try to look up generators starting from a disconnected block, we diff --git a/chia/_tests/conftest.py b/chia/_tests/conftest.py index 68fb9338194e..acb3fd332035 100644 --- a/chia/_tests/conftest.py +++ b/chia/_tests/conftest.py @@ -232,8 +232,8 @@ def blockchain_constants(consensus_mode: ConsensusMode) -> ConsensusConstants: @pytest.fixture(scope="session", name="bt") async def block_tools_fixture(get_keychain, blockchain_constants, anyio_backend) -> BlockTools: # Note that this causes a lot of CPU and disk traffic - disk, DB, ports, process creation ... - _shared_block_tools = await create_block_tools_async(constants=blockchain_constants, keychain=get_keychain) - return _shared_block_tools + shared_block_tools = await create_block_tools_async(constants=blockchain_constants, keychain=get_keychain) + return shared_block_tools # if you have a system that has an unusual hostname for localhost and you want diff --git a/chia/_tests/core/data_layer/test_data_rpc.py b/chia/_tests/core/data_layer/test_data_rpc.py index 4ee942e50229..0e06204480c4 100644 --- a/chia/_tests/core/data_layer/test_data_rpc.py +++ b/chia/_tests/core/data_layer/test_data_rpc.py @@ -2277,7 +2277,7 @@ async def test_unsubscribe_unknown( bare_data_layer_api: DataLayerRpcApi, seeded_random: random.Random, ) -> None: - with pytest.raises(RuntimeError, match="No subscription found for the given store_id."): + with pytest.raises(RuntimeError, match="No subscription found for the given store_id"): await bare_data_layer_api.unsubscribe(request={"id": bytes32.random(seeded_random).hex(), "retain": False}) diff --git a/chia/_tests/core/data_layer/test_data_store.py b/chia/_tests/core/data_layer/test_data_store.py index 35777e8a7b1c..a61862ee576e 100644 --- a/chia/_tests/core/data_layer/test_data_store.py +++ b/chia/_tests/core/data_layer/test_data_store.py @@ -594,7 +594,7 @@ async def test_ancestor_table_unique_inserts(data_store: DataStore, store_id: by hash_2 = bytes32.from_hexstr("924be8ff27e84cba17f5bc918097f8410fab9824713a4668a21c8e060a8cab40") await data_store._insert_ancestor_table(hash_1, hash_2, store_id, 2) await data_store._insert_ancestor_table(hash_1, hash_2, store_id, 2) - with pytest.raises(Exception, match="^Requested insertion of ancestor"): + with pytest.raises(Exception, match=r"^Requested insertion of ancestor"): await data_store._insert_ancestor_table(hash_1, hash_1, store_id, 2) await data_store._insert_ancestor_table(hash_1, hash_2, store_id, 2) @@ -2385,11 +2385,10 @@ async def test_get_leaf_at_minimum_height( if isinstance(node, InternalNode): heights[node.left_hash] = heights[node.hash] + 1 heights[node.right_hash] = heights[node.hash] + 1 + elif min_leaf_height is not None: + min_leaf_height = min(min_leaf_height, heights[node.hash]) else: - if min_leaf_height is not None: - min_leaf_height = min(min_leaf_height, heights[node.hash]) - else: - min_leaf_height = heights[node.hash] + min_leaf_height = heights[node.hash] assert min_leaf_height is not None if pre > 0: diff --git a/chia/_tests/core/full_node/stores/test_block_store.py b/chia/_tests/core/full_node/stores/test_block_store.py index 0bf2ba048f5a..5cb22d158f7d 100644 --- a/chia/_tests/core/full_node/stores/test_block_store.py +++ b/chia/_tests/core/full_node/stores/test_block_store.py @@ -418,8 +418,8 @@ def generator(i: int) -> SerializedProgram: store = await BlockStore.create(db_wrapper, use_cache=use_cache) new_blocks = [] - for i, block in enumerate(blocks): - block = block.replace(transactions_generator=generator(i)) + for i, original_block in enumerate(blocks): + block = original_block.replace(transactions_generator=generator(i)) block_record = header_block_to_sub_block_record( DEFAULT_CONSTANTS, uint64(0), block, uint64(0), False, uint8(0), uint32(max(0, block.height - 1)), None ) diff --git a/chia/_tests/core/full_node/test_address_manager.py b/chia/_tests/core/full_node/test_address_manager.py index 7163f98c7764..ef791ddd7469 100644 --- a/chia/_tests/core/full_node/test_address_manager.py +++ b/chia/_tests/core/full_node/test_address_manager.py @@ -560,7 +560,7 @@ async def check_retrieved_peers(self, wanted_peers: list[ExtendedPeerInfo], addr # use tmp_path pytest fixture to create a temporary directory async def test_serialization(self, tmp_path: Path): addrman = AddressManagerTest() - now = int(math.floor(time.time())) + now = math.floor(time.time()) t_peer1 = TimestampedPeerInfo("250.7.1.1", uint16(8333), uint64(now - 10000)) t_peer2 = TimestampedPeerInfo("1050:0000:0000:0000:0005:0600:300c:326b", uint16(9999), uint64(now - 20000)) t_peer3 = TimestampedPeerInfo("250.7.3.3", uint16(9999), uint64(now - 30000)) @@ -587,7 +587,7 @@ async def test_serialization(self, tmp_path: Path): @pytest.mark.anyio async def test_bad_ip_encoding(self, tmp_path: Path): addrman = AddressManagerTest() - now = int(math.floor(time.time())) + now = math.floor(time.time()) t_peer1 = TimestampedPeerInfo("250.7.1.1", uint16(8333), uint64(now - 10000)) t_peer2 = TimestampedPeerInfo("1050:0000:0000:0000:0005:0600:300c:326b", uint16(9999), uint64(now - 20000)) t_peer3 = TimestampedPeerInfo("250.7.3.3", uint16(9999), uint64(now - 30000)) @@ -725,7 +725,7 @@ async def old_serialize(address_manager: AddressManager, peers_file_path: Path) # create a file with the old serialization, then migrate to new serialization addrman = AddressManagerTest() - now = int(math.floor(time.time())) + now = math.floor(time.time()) t_peer1 = TimestampedPeerInfo("250.7.1.1", uint16(8333), uint64(now - 10000)) t_peer2 = TimestampedPeerInfo("1050:0000:0000:0000:0005:0600:300c:326b", uint16(9999), uint64(now - 20000)) t_peer3 = TimestampedPeerInfo("250.7.3.3", uint16(9999), uint64(now - 30000)) diff --git a/chia/_tests/core/full_node/test_full_node.py b/chia/_tests/core/full_node/test_full_node.py index 268a270b9306..89022b8f8c13 100644 --- a/chia/_tests/core/full_node/test_full_node.py +++ b/chia/_tests/core/full_node/test_full_node.py @@ -2678,16 +2678,15 @@ async def test_long_reorg_nodes( blocks = default_10000_blocks[: 1600 - chain_length] reorg_blocks = test_long_reorg_blocks_light[: 1600 - chain_length] reorg_height = 2000 - else: - if fork_point == 1500: - blocks = default_10000_blocks[: 1900 - chain_length] - reorg_blocks = test_long_reorg_1500_blocks[: 1900 - chain_length] - reorg_height = 2300 - else: # pragma: no cover - pytest.skip("We rely on the light-blocks test for a 0 forkpoint") - blocks = default_10000_blocks[: 1100 - chain_length] - # reorg_blocks = test_long_reorg_blocks[: 1100 - chain_length] - reorg_height = 1600 + elif fork_point == 1500: + blocks = default_10000_blocks[: 1900 - chain_length] + reorg_blocks = test_long_reorg_1500_blocks[: 1900 - chain_length] + reorg_height = 2300 + else: # pragma: no cover + pytest.skip("We rely on the light-blocks test for a 0 forkpoint") + blocks = default_10000_blocks[: 1100 - chain_length] + # reorg_blocks = test_long_reorg_blocks[: 1100 - chain_length] + reorg_height = 1600 # this is a pre-requisite for a reorg to happen assert default_10000_blocks[reorg_height].weight > reorg_blocks[-1].weight @@ -3163,15 +3162,14 @@ async def declare_pos_unfinished_block( challenge_chain_sp = block.reward_chain_block.challenge_chain_sp_vdf.output.get_hash() if block.reward_chain_block.reward_chain_sp_vdf is not None: reward_chain_sp = block.reward_chain_block.reward_chain_sp_vdf.output.get_hash() + elif len(block.finished_sub_slots) > 0: + reward_chain_sp = block.finished_sub_slots[-1].reward_chain.get_hash() else: - if len(block.finished_sub_slots) > 0: - reward_chain_sp = block.finished_sub_slots[-1].reward_chain.get_hash() - else: - curr = blockchain.block_record(block.prev_header_hash) - while not curr.first_in_sub_slot: - curr = blockchain.block_record(curr.prev_hash) - assert curr.finished_reward_slot_hashes is not None - reward_chain_sp = curr.finished_reward_slot_hashes[-1] + curr = blockchain.block_record(block.prev_header_hash) + while not curr.first_in_sub_slot: + curr = blockchain.block_record(curr.prev_hash) + assert curr.finished_reward_slot_hashes is not None + reward_chain_sp = curr.finished_reward_slot_hashes[-1] farmer_reward_address = block.foliage.foliage_block_data.farmer_reward_puzzle_hash pool_target = block.foliage.foliage_block_data.pool_target pool_target_signature = block.foliage.foliage_block_data.pool_signature diff --git a/chia/_tests/core/mempool/test_mempool_fee_estimator.py b/chia/_tests/core/mempool/test_mempool_fee_estimator.py index b18f7c109294..91f0f12b9de6 100644 --- a/chia/_tests/core/mempool/test_mempool_fee_estimator.py +++ b/chia/_tests/core/mempool/test_mempool_fee_estimator.py @@ -23,7 +23,6 @@ async def test_basics() -> None: cost = uint64(5000000) for i in range(300, 700): - i = uint32(i) items = [] for _ in range(2, 100): fee = uint64(10000000) @@ -50,7 +49,7 @@ async def test_basics() -> None: ) items.append(mempool_item2) - fee_tracker.process_block(i, items) + fee_tracker.process_block(uint32(i), items) short, med, long = fee_tracker.estimate_fees() @@ -72,7 +71,6 @@ async def test_fee_increase() -> None: estimator = SmartFeeEstimator(fee_tracker, uint64(test_constants.MAX_BLOCK_COST_CLVM)) random = Random(x=1) for i in range(300, 700): - i = uint32(i) items = [] for _ in range(20): fee = uint64(0) @@ -85,7 +83,7 @@ async def test_fee_increase() -> None: ) items.append(mempool_item) - fee_tracker.process_block(i, items) + fee_tracker.process_block(uint32(i), items) short, med, long = fee_tracker.estimate_fees() mempool_info = mempool_manager.mempool.fee_estimator.get_mempool_info() diff --git a/chia/_tests/core/mempool/test_singleton_fast_forward.py b/chia/_tests/core/mempool/test_singleton_fast_forward.py index ccbb367cbc39..1debc4ff6f12 100644 --- a/chia/_tests/core/mempool/test_singleton_fast_forward.py +++ b/chia/_tests/core/mempool/test_singleton_fast_forward.py @@ -79,7 +79,7 @@ def test_process_fast_forward_spends_unknown_ff() -> None: singleton_ff = SingletonFastForward() # We have no fast forward records yet, so we'll process this coin for the # first time here, but the item's latest singleton lineage returns None - with pytest.raises(ValueError, match="Cannot proceed with singleton spend fast forward."): + with pytest.raises(ValueError, match="Cannot proceed with singleton spend fast forward"): singleton_ff.process_fast_forward_spends( mempool_item=internal_mempool_item, height=TEST_HEIGHT, constants=DEFAULT_CONSTANTS ) diff --git a/chia/_tests/core/test_full_node_rpc.py b/chia/_tests/core/test_full_node_rpc.py index 4a26baced6f5..8bde0aea2b04 100644 --- a/chia/_tests/core/test_full_node_rpc.py +++ b/chia/_tests/core/test_full_node_rpc.py @@ -457,9 +457,9 @@ async def test_signage_points( full_node_service_1.config, ) as client: # Only provide one - with pytest.raises(ValueError, match="sp_hash or challenge_hash must be provided."): + with pytest.raises(ValueError, match="sp_hash or challenge_hash must be provided"): await client.get_recent_signage_point_or_eos(None, None) - with pytest.raises(ValueError, match="Either sp_hash or challenge_hash must be provided, not both."): + with pytest.raises(ValueError, match="Either sp_hash or challenge_hash must be provided, not both"): await client.get_recent_signage_point_or_eos(std_hash(b"0"), std_hash(b"1")) # Not found with pytest.raises(ValueError, match="in cache"): diff --git a/chia/_tests/core/util/test_keychain.py b/chia/_tests/core/util/test_keychain.py index c0ba58e99886..b252667c5f21 100644 --- a/chia/_tests/core/util/test_keychain.py +++ b/chia/_tests/core/util/test_keychain.py @@ -220,9 +220,9 @@ def test_bip39_test_vectors_short(self): test_vectors_path = importlib_resources.files(chia._tests.util.__name__).joinpath("bip39_test_vectors.json") all_vectors = json.loads(test_vectors_path.read_text(encoding="utf-8")) - for idx, [entropy_hex, full_mnemonic, seed, short_mnemonic] in enumerate(all_vectors["english"]): + for idx, [entropy_hex, full_mnemonic, seed_hex, short_mnemonic] in enumerate(all_vectors["english"]): entropy_bytes = bytes.fromhex(entropy_hex) - seed = bytes.fromhex(seed) + seed = bytes.fromhex(seed_hex) assert mnemonic_from_short_words(short_mnemonic) == full_mnemonic assert bytes_from_mnemonic(short_mnemonic) == entropy_bytes diff --git a/chia/_tests/fee_estimation/test_fee_estimation_unit_tests.py b/chia/_tests/fee_estimation/test_fee_estimation_unit_tests.py index 27830d0b791f..cd91c3def305 100644 --- a/chia/_tests/fee_estimation/test_fee_estimation_unit_tests.py +++ b/chia/_tests/fee_estimation/test_fee_estimation_unit_tests.py @@ -68,8 +68,7 @@ def test_steady_fee_pressure() -> None: estimates_during = [] start_from = 250 for height in range(start, end): - height = uint32(height) - items = make_block(height, 1, cost, fee, num_blocks_wait_in_mempool) + items = make_block(uint32(height), 1, cost, fee, num_blocks_wait_in_mempool) estimator.new_block(FeeBlockInfo(uint32(height), items)) if height >= start_from: estimation = estimator.estimate_fee_rate(time_offset_seconds=time_offset_seconds * (height - start_from)) diff --git a/chia/_tests/plotting/test_plot_manager.py b/chia/_tests/plotting/test_plot_manager.py index 3108da756943..15ea5c2e3886 100644 --- a/chia/_tests/plotting/test_plot_manager.py +++ b/chia/_tests/plotting/test_plot_manager.py @@ -117,10 +117,9 @@ def refresh_callback(self, event: PlotRefreshEvents, refresh_result: PlotRefresh if plot_info.prover.get_filename() == value.prover.get_filename(): values_found += 1 continue - else: - if value in expected_list: - values_found += 1 - continue + elif value in expected_list: + values_found += 1 + continue if values_found != len(expected_list): log.error(f"{name} invalid: values_found {values_found} expected {len(expected_list)}") return diff --git a/chia/_tests/pools/test_pool_cmdline.py b/chia/_tests/pools/test_pool_cmdline.py index 2dd84d1cbb5e..5684c2a11ce5 100644 --- a/chia/_tests/pools/test_pool_cmdline.py +++ b/chia/_tests/pools/test_pool_cmdline.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import re from dataclasses import dataclass from io import StringIO from typing import Optional, cast @@ -484,7 +485,7 @@ async def test_plotnft_cli_join( wallet_id = await create_new_plotnft(wallet_environments) # Test joining the same pool again - with pytest.raises(click.ClickException, match="already farming to pool http://pool.example.com"): + with pytest.raises(click.ClickException, match=re.escape("already farming to pool http://pool.example.com")): await JoinPlotNFTCMD( rpc_info=NeedsWalletRPC( client_info=client_info, diff --git a/chia/_tests/pools/test_pool_puzzles_lifecycle.py b/chia/_tests/pools/test_pool_puzzles_lifecycle.py index 2838bc790741..ea3a7dc73275 100644 --- a/chia/_tests/pools/test_pool_puzzles_lifecycle.py +++ b/chia/_tests/pools/test_pool_puzzles_lifecycle.py @@ -1,6 +1,7 @@ from __future__ import annotations import copy +import re from unittest import TestCase import pytest @@ -31,6 +32,7 @@ from chia.types.blockchain_format.coin import Coin from chia.types.blockchain_format.program import Program from chia.types.coin_spend import make_spend +from chia.util.errors import Err from chia.wallet.puzzles import singleton_top_layer from chia.wallet.puzzles.p2_conditions import puzzle_for_conditions from chia.wallet.puzzles.p2_delegated_puzzle_or_hidden_puzzle import ( @@ -242,7 +244,8 @@ def test_pool_lifecycle(self): ) # Spend it and hope it fails! with pytest.raises( - BadSpendBundleError, match="condition validation failure Err.ASSERT_ANNOUNCE_CONSUMED_FAILED" + BadSpendBundleError, + match=re.escape(f"condition validation failure {Err.ASSERT_ANNOUNCE_CONSUMED_FAILED!s}"), ): coin_db.update_coin_store_for_spend_bundle( SpendBundle([singleton_coinsol], G2Element()), time, DEFAULT_CONSTANTS.MAX_BLOCK_COST_CLVM @@ -269,7 +272,8 @@ def test_pool_lifecycle(self): ) # Spend it and hope it fails! with pytest.raises( - BadSpendBundleError, match="condition validation failure Err.ASSERT_ANNOUNCE_CONSUMED_FAILED" + BadSpendBundleError, + match=re.escape(f"condition validation failure {Err.ASSERT_ANNOUNCE_CONSUMED_FAILED!s}"), ): coin_db.update_coin_store_for_spend_bundle( SpendBundle([singleton_coinsol, bad_coinsol], G2Element()), time, DEFAULT_CONSTANTS.MAX_BLOCK_COST_CLVM @@ -320,7 +324,10 @@ def test_pool_lifecycle(self): (data + singleton.name() + DEFAULT_CONSTANTS.AGG_SIG_ME_ADDITIONAL_DATA), ) # Spend it and hope it fails! - with pytest.raises(BadSpendBundleError, match="condition validation failure Err.ASSERT_HEIGHT_RELATIVE_FAILED"): + with pytest.raises( + BadSpendBundleError, + match=re.escape(f"condition validation failure {Err.ASSERT_HEIGHT_RELATIVE_FAILED!s}"), + ): coin_db.update_coin_store_for_spend_bundle( SpendBundle([return_coinsol], sig), time, DEFAULT_CONSTANTS.MAX_BLOCK_COST_CLVM ) diff --git a/chia/_tests/pools/test_pool_rpc.py b/chia/_tests/pools/test_pool_rpc.py index 2c26382dd345..04334ae5fb6c 100644 --- a/chia/_tests/pools/test_pool_rpc.py +++ b/chia/_tests/pools/test_pool_rpc.py @@ -1259,7 +1259,7 @@ async def test_join_pool_unsynced( mock.return_value = False # Test joining the same pool via the RPC client - with pytest.raises(ResponseFailureError, match="Wallet needs to be fully synced."): + with pytest.raises(ResponseFailureError, match="Wallet needs to be fully synced"): await wallet_rpc.pw_join_pool( PWJoinPool( wallet_id=uint32(wallet_id), diff --git a/chia/_tests/util/test_misc.py b/chia/_tests/util/test_misc.py index 7978eb19881d..62556508de56 100644 --- a/chia/_tests/util/test_misc.py +++ b/chia/_tests/util/test_misc.py @@ -182,7 +182,7 @@ def test_split_manager_raises_on_second_entry() -> None: split = SplitManager(manager=sync_manager(y=x), object=None) split.enter() - with pytest.raises(Exception, match="^already entered$"): + with pytest.raises(Exception, match=r"^already entered$"): split.enter() @@ -193,7 +193,7 @@ def test_split_manager_raises_on_second_entry_after_exiting() -> None: split.enter() split.exit() - with pytest.raises(Exception, match="^already entered, already exited$"): + with pytest.raises(Exception, match=r"^already entered, already exited$"): split.enter() @@ -204,7 +204,7 @@ def test_split_manager_raises_on_second_exit() -> None: split.enter() split.exit() - with pytest.raises(Exception, match="^already exited$"): + with pytest.raises(Exception, match=r"^already exited$"): split.exit() @@ -213,7 +213,7 @@ def test_split_manager_raises_on_exit_without_entry() -> None: split = SplitManager(manager=sync_manager(y=x), object=None) - with pytest.raises(Exception, match="^not yet entered$"): + with pytest.raises(Exception, match=r"^not yet entered$"): split.exit() @@ -274,7 +274,7 @@ async def test_split_async_manager_raises_on_second_entry() -> None: split = SplitAsyncManager(manager=async_manager(y=x), object=None) await split.enter() - with pytest.raises(Exception, match="^already entered$"): + with pytest.raises(Exception, match=r"^already entered$"): await split.enter() @@ -286,7 +286,7 @@ async def test_split_async_manager_raises_on_second_entry_after_exiting() -> Non await split.enter() await split.exit() - with pytest.raises(Exception, match="^already entered, already exited$"): + with pytest.raises(Exception, match=r"^already entered, already exited$"): await split.enter() @@ -298,7 +298,7 @@ async def test_split_async_manager_raises_on_second_exit() -> None: await split.enter() await split.exit() - with pytest.raises(Exception, match="^already exited$"): + with pytest.raises(Exception, match=r"^already exited$"): await split.exit() @@ -308,7 +308,7 @@ async def test_split_async_manager_raises_on_exit_without_entry() -> None: split = SplitAsyncManager(manager=async_manager(y=x), object=None) - with pytest.raises(Exception, match="^not yet entered$"): + with pytest.raises(Exception, match=r"^not yet entered$"): await split.exit() @@ -390,7 +390,7 @@ async def test_valued_event_set_again_raises_and_does_not_change_value() -> None value = 37 valued_event.set(value) - with pytest.raises(Exception, match="^Value already set$"): + with pytest.raises(Exception, match=r"^Value already set$"): valued_event.set(value + 1) with anyio.fail_after(adjusted_timeout(10)): @@ -404,7 +404,7 @@ async def test_valued_event_wait_raises_if_not_set() -> None: valued_event = ValuedEvent[int]() valued_event._event.set() - with pytest.raises(Exception, match="^Value not set despite event being set$"): + with pytest.raises(Exception, match=r"^Value not set despite event being set$"): with anyio.fail_after(adjusted_timeout(10)): await valued_event.wait() diff --git a/chia/_tests/wallet/cat_wallet/test_cat_wallet.py b/chia/_tests/wallet/cat_wallet/test_cat_wallet.py index 93d04a608149..e60047df6d57 100644 --- a/chia/_tests/wallet/cat_wallet/test_cat_wallet.py +++ b/chia/_tests/wallet/cat_wallet/test_cat_wallet.py @@ -1153,7 +1153,7 @@ async def check_all_there() -> bool: assert action_scope.side_effects.transactions[0].amount == uint64(max_sent_amount) # 3) Generate transaction that is greater than limit - with pytest.raises(ValueError, match="Can't select amount higher than our spendable balance."): + with pytest.raises(ValueError, match="Can't select amount higher than our spendable balance"): async with cat_wallet.wallet_state_manager.new_action_scope( wallet_environments.tx_config, push=False ) as action_scope: diff --git a/chia/_tests/wallet/did_wallet/test_did.py b/chia/_tests/wallet/did_wallet/test_did.py index 0fe6677d7990..ccb12e81f786 100644 --- a/chia/_tests/wallet/did_wallet/test_did.py +++ b/chia/_tests/wallet/did_wallet/test_did.py @@ -791,7 +791,7 @@ async def test_get_info(wallet_environments: WalletTestFramework): coin = (await wallet_0.select_coins(uint64(1), action_scope)).pop() assert coin.amount % 2 == 1 coin_id = coin.name() - with pytest.raises(ValueError, match="The coin is not a DID."): + with pytest.raises(ValueError, match="The coin is not a DID"): await api_0.get_did_info(DIDGetInfo(coin_id.hex())) # Test multiple odd coins @@ -845,7 +845,7 @@ async def test_get_info(wallet_environments: WalletTestFramework): ] ) - with pytest.raises(ValueError, match="This is not a singleton, multiple children coins found."): + with pytest.raises(ValueError, match=r"This is not a singleton, multiple children coins found."): await api_0.get_did_info(DIDGetInfo(coin_1.name().hex())) diff --git a/chia/_tests/wallet/nft_wallet/test_nft_wallet.py b/chia/_tests/wallet/nft_wallet/test_nft_wallet.py index 87d793bd5273..0e81cb9f6e41 100644 --- a/chia/_tests/wallet/nft_wallet/test_nft_wallet.py +++ b/chia/_tests/wallet/nft_wallet/test_nft_wallet.py @@ -528,7 +528,7 @@ async def test_nft_wallet_creation_and_transfer(wallet_environments: WalletTestF await time_out_assert(30, get_nft_count, 1, nft_wallet_1) # Test an error case - with pytest.raises(ResponseFailureError, match="The NFT doesn't support setting a DID."): + with pytest.raises(ResponseFailureError, match="The NFT doesn't support setting a DID"): await env_1.rpc_client.set_nft_did( NFTSetNFTDID( wallet_id=uint32(env_1.wallet_aliases["nft"]), @@ -659,7 +659,7 @@ async def test_nft_wallet_rpc_creation_and_list(wallet_environments: WalletTestF # test counts assert (await env.rpc_client.count_nfts(NFTCountNFTs(uint32(env.wallet_aliases["nft"])))).count == 2 assert (await env.rpc_client.count_nfts(NFTCountNFTs())).count == 2 - with pytest.raises(ResponseFailureError, match="Wallet 50 not found."): + with pytest.raises(ResponseFailureError, match="Wallet 50 not found"): await env.rpc_client.count_nfts(NFTCountNFTs(uint32(50))) diff --git a/chia/_tests/wallet/test_signer_protocol.py b/chia/_tests/wallet/test_signer_protocol.py index 29668eec8d48..c1d7a0dc590e 100644 --- a/chia/_tests/wallet/test_signer_protocol.py +++ b/chia/_tests/wallet/test_signer_protocol.py @@ -848,8 +848,8 @@ def run(self) -> None: with open("some file", "wb") as file: file.write(byte_serialize_clvm_streamable(coin, translation_layer=FOO_COIN_TRANSLATION)) - with open("some file2", "wb") as file: - file.write(byte_serialize_clvm_streamable(coin, translation_layer=FOO_COIN_TRANSLATION)) + with open("some file2", "wb") as file2: + file2.write(byte_serialize_clvm_streamable(coin, translation_layer=FOO_COIN_TRANSLATION)) result = runner.invoke( cmd, ["temp_cmd", "--signer-protocol-input", "some file", "--signer-protocol-input", "some file2"] diff --git a/chia/_tests/wallet/test_singleton_lifecycle_fast.py b/chia/_tests/wallet/test_singleton_lifecycle_fast.py index bc92c86ff59b..4f9e0b708748 100644 --- a/chia/_tests/wallet/test_singleton_lifecycle_fast.py +++ b/chia/_tests/wallet/test_singleton_lifecycle_fast.py @@ -65,10 +65,9 @@ def satisfies_hint(obj: T, type_hint: type[T]) -> bool: object_hint_pairs.extend((v, args[1]) for v in obj.values()) else: raise NotImplementedError(f"Type {origin} is not yet supported") - else: - # Handle concrete types - if type(obj) is not type_hint: - return False + # Handle concrete types + elif type(obj) is not type_hint: + return False return True diff --git a/chia/cmds/cmd_classes.py b/chia/cmds/cmd_classes.py index 4f9dc5ed5e79..e52e1421066d 100644 --- a/chia/cmds/cmd_classes.py +++ b/chia/cmds/cmd_classes.py @@ -181,10 +181,10 @@ def _generate_command_parser(cls: type[ChiaCommand]) -> _CommandParsingStage: needs_context: bool = False hints = get_type_hints(cls) - _fields = fields(cls) # type: ignore[arg-type] + cls_fields = fields(cls) # type: ignore[arg-type] - for _field in _fields: - field_name = _field.name + for cls_field in cls_fields: + field_name = cls_field.name if getattr(hints[field_name], COMMAND_HELPER_ATTRIBUTE_NAME, False): members[field_name] = _generate_command_parser(hints[field_name]) elif field_name == "context": @@ -193,9 +193,9 @@ def _generate_command_parser(cls: type[ChiaCommand]) -> _CommandParsingStage: else: needs_context = True kwarg_names.append(field_name) - elif "option_args" in _field.metadata: + elif "option_args" in cls_field.metadata: option_args: dict[str, Any] = {"multiple": False, "required": False} - option_args.update(_field.metadata["option_args"]) + option_args.update(cls_field.metadata["option_args"]) if "type" not in option_args: origin = get_origin(hints[field_name]) diff --git a/chia/cmds/keys_funcs.py b/chia/cmds/keys_funcs.py index 5b0eef7b7a3f..c4ad0053f7d5 100644 --- a/chia/cmds/keys_funcs.py +++ b/chia/cmds/keys_funcs.py @@ -743,11 +743,10 @@ def derive_child_key( if non_observer_derivation: assert current_sk is not None # semantics above guarantee this current_sk = _derive_path(current_sk, path_indices) + elif current_sk is not None: + current_sk = _derive_path_unhardened(current_sk, path_indices) else: - if current_sk is not None: - current_sk = _derive_path_unhardened(current_sk, path_indices) - else: - current_pk = _derive_pk_unhardened(current_pk, path_indices) + current_pk = _derive_pk_unhardened(current_pk, path_indices) derivation_root_sk = current_sk derivation_root_pk = current_pk @@ -768,13 +767,12 @@ def derive_child_key( assert derivation_root_sk is not None # semantics above guarantee this sk = _derive_path(derivation_root_sk, [i]) pk = sk.get_g1() + elif derivation_root_sk is not None: + sk = _derive_path_unhardened(derivation_root_sk, [i]) + pk = sk.get_g1() else: - if derivation_root_sk is not None: - sk = _derive_path_unhardened(derivation_root_sk, [i]) - pk = sk.get_g1() - else: - sk = None - pk = _derive_pk_unhardened(derivation_root_pk, [i]) + sk = None + pk = _derive_pk_unhardened(derivation_root_pk, [i]) hd_path: str = ( " (" + hd_path_root + str(i) + ("n" if non_observer_derivation else "") + ")" if show_hd_path else "" ) diff --git a/chia/cmds/plotnft_funcs.py b/chia/cmds/plotnft_funcs.py index 09204896bed1..6cc003c88748 100644 --- a/chia/cmds/plotnft_funcs.py +++ b/chia/cmds/plotnft_funcs.py @@ -445,8 +445,10 @@ async def change_payout_instructions(launcher_id: bytes32, address: CliAddress, for pool_config in old_configs: if pool_config.launcher_id == launcher_id: id_found = True - pool_config = replace(pool_config, payout_instructions=puzzle_hash.hex()) - new_pool_configs.append(pool_config) + new_pool_config = replace(pool_config, payout_instructions=puzzle_hash.hex()) + else: + new_pool_config = pool_config + new_pool_configs.append(new_pool_config) if id_found: print(f"Launcher Id: {launcher_id.hex()} Found, Updating Config.") await update_pool_config(root_path, new_pool_configs) diff --git a/chia/cmds/wallet_funcs.py b/chia/cmds/wallet_funcs.py index f0b712a63080..b46c31bdb7ac 100644 --- a/chia/cmds/wallet_funcs.py +++ b/chia/cmds/wallet_funcs.py @@ -179,7 +179,7 @@ async def get_unit_name_for_wallet_id( async def get_transaction( *, root_path: pathlib.Path, wallet_rpc_port: Optional[int], fingerprint: Optional[int], tx_id: str, verbose: int ) -> None: - async with get_wallet_client(root_path, wallet_rpc_port, fingerprint) as (wallet_client, fingerprint, config): + async with get_wallet_client(root_path, wallet_rpc_port, fingerprint) as (wallet_client, _, config): transaction_id = bytes32.from_hexstr(tx_id) address_prefix = selected_network_address_prefix(config) tx: TransactionRecord = await wallet_client.get_transaction(transaction_id=transaction_id) @@ -265,7 +265,9 @@ async def get_transactions( if len(coin_records["coin_records"]) > 0: coin_record = coin_records["coin_records"][0] else: - j -= 1 + # Ignoring this because it seems useful to the loop + # But we should probably consider a better loop + j -= 1 # noqa: PLW2901 skipped += 1 continue print_transaction( @@ -1244,9 +1246,8 @@ async def mint_nft( raise ValueError("Disabling DID ownership is not supported for this NFT wallet, it does have a DID") else: did_id = None - else: - if not wallet_has_did: - did_id = "" + elif not wallet_has_did: + did_id = "" mint_response = await wallet_client.mint_nft( request=NFTMintNFTRequest( @@ -1865,7 +1866,7 @@ async def approve_r_cats( push: bool, condition_valid_times: ConditionValidTimes, ) -> list[TransactionRecord]: - async with get_wallet_client(root_path, wallet_rpc_port, fingerprint) as (wallet_client, fingerprint, config): + async with get_wallet_client(root_path, wallet_rpc_port, fingerprint) as (wallet_client, fp, config): if wallet_client is None: return txs = await wallet_client.crcat_approve_pending( @@ -1876,7 +1877,7 @@ async def approve_r_cats( min_coin_amount=min_coin_amount, max_coin_amount=max_coin_amount, reuse_puzhash=reuse, - ).to_tx_config(units["cat"], config, fingerprint), + ).to_tx_config(units["cat"], config, fp), push=push, timelock_info=condition_valid_times, ) diff --git a/chia/consensus/block_body_validation.py b/chia/consensus/block_body_validation.py index f68adaf09398..c113184cf9c6 100644 --- a/chia/consensus/block_body_validation.py +++ b/chia/consensus/block_body_validation.py @@ -334,9 +334,8 @@ async def validate_block_body( if block.transactions_generator is not None: if std_hash(bytes(block.transactions_generator)) != block.transactions_info.generator_root: return Err.INVALID_TRANSACTIONS_GENERATOR_HASH - else: - if block.transactions_info.generator_root != bytes([0] * 32): - return Err.INVALID_TRANSACTIONS_GENERATOR_HASH + elif block.transactions_info.generator_root != bytes([0] * 32): + return Err.INVALID_TRANSACTIONS_GENERATOR_HASH # 8a. The generator_ref_list must be the hash of the serialized bytes of # the generator ref list for this block (or 'one' bytes [0x01] if no generator) diff --git a/chia/consensus/block_creation.py b/chia/consensus/block_creation.py index 7ad94421aea2..45b14f63feb9 100644 --- a/chia/consensus/block_creation.py +++ b/chia/consensus/block_creation.py @@ -354,17 +354,16 @@ def create_unfinished_block( else: if new_sub_slot: rc_sp_hash = finished_sub_slots[-1].reward_chain.get_hash() + elif is_genesis: + rc_sp_hash = constants.GENESIS_CHALLENGE else: - if is_genesis: - rc_sp_hash = constants.GENESIS_CHALLENGE - else: - assert prev_block is not None - assert blocks is not None - curr = prev_block - while not curr.first_in_sub_slot: - curr = blocks.block_record(curr.prev_hash) - assert curr.finished_reward_slot_hashes is not None - rc_sp_hash = curr.finished_reward_slot_hashes[-1] + assert prev_block is not None + assert blocks is not None + curr = prev_block + while not curr.first_in_sub_slot: + curr = blocks.block_record(curr.prev_hash) + assert curr.finished_reward_slot_hashes is not None + rc_sp_hash = curr.finished_reward_slot_hashes[-1] signage_point = SignagePoint(None, None, None, None) cc_sp_signature: Optional[G2Element] = get_plot_signature(cc_sp_hash, proof_of_space.plot_public_key) diff --git a/chia/consensus/block_header_validation.py b/chia/consensus/block_header_validation.py index 9fb5174a8d8b..3ec214a04736 100644 --- a/chia/consensus/block_header_validation.py +++ b/chia/consensus/block_header_validation.py @@ -138,13 +138,12 @@ def validate_unfinished_header_block( if not curr.finished_challenge_slot_hashes[-1] == challenge_hash: print(curr.finished_challenge_slot_hashes[-1], challenge_hash) return None, ValidationError(Err.INVALID_PREV_CHALLENGE_SLOT_HASH) - else: - # 2c. check sub-slot challenge hash for empty slot - if ( - not header_block.finished_sub_slots[finished_sub_slot_n - 1].challenge_chain.get_hash() - == challenge_hash - ): - return None, ValidationError(Err.INVALID_PREV_CHALLENGE_SLOT_HASH) + # 2c. check sub-slot challenge hash for empty slot + elif ( + not header_block.finished_sub_slots[finished_sub_slot_n - 1].challenge_chain.get_hash() + == challenge_hash + ): + return None, ValidationError(Err.INVALID_PREV_CHALLENGE_SLOT_HASH) if genesis_block: # 2d. Validate that genesis block has no ICC @@ -176,20 +175,19 @@ def validate_unfinished_header_block( icc_vdf_input = ClassgroupElement.get_default_element() else: icc_vdf_input = prev_b.infused_challenge_vdf_output - else: - # This is not the first sub slot after the last block, so we might not have an ICC - if ( - header_block.finished_sub_slots[finished_sub_slot_n - 1].reward_chain.deficit - < constants.MIN_BLOCKS_PER_CHALLENGE_BLOCK - ): - finished_ss = header_block.finished_sub_slots[finished_sub_slot_n - 1] - assert finished_ss.infused_challenge_chain is not None + # This is not the first sub slot after the last block, so we might not have an ICC + elif ( + header_block.finished_sub_slots[finished_sub_slot_n - 1].reward_chain.deficit + < constants.MIN_BLOCKS_PER_CHALLENGE_BLOCK + ): + finished_ss = header_block.finished_sub_slots[finished_sub_slot_n - 1] + assert finished_ss.infused_challenge_chain is not None - # Only sets the icc iff the previous sub slots deficit is 4 or less - icc_challenge_hash = finished_ss.infused_challenge_chain.get_hash() - icc_iters_committed = prev_b.sub_slot_iters - icc_iters_proof = icc_iters_committed - icc_vdf_input = ClassgroupElement.get_default_element() + # Only sets the icc iff the previous sub slots deficit is 4 or less + icc_challenge_hash = finished_ss.infused_challenge_chain.get_hash() + icc_iters_committed = prev_b.sub_slot_iters + icc_iters_proof = icc_iters_committed + icc_vdf_input = ClassgroupElement.get_default_element() # 2e. Validate that there is not icc iff icc_challenge hash is None assert (sub_slot.infused_challenge_chain is None) == (icc_challenge_hash is None) @@ -241,10 +239,9 @@ def validate_unfinished_header_block( != sub_slot.challenge_chain.infused_challenge_chain_sub_slot_hash ): return None, ValidationError(Err.INVALID_ICC_HASH_CC) - else: - # 2h. Check infused challenge sub-slot hash not included for other deficits - if sub_slot.challenge_chain.infused_challenge_chain_sub_slot_hash is not None: - return None, ValidationError(Err.INVALID_ICC_HASH_CC) + # 2h. Check infused challenge sub-slot hash not included for other deficits + elif sub_slot.challenge_chain.infused_challenge_chain_sub_slot_hash is not None: + return None, ValidationError(Err.INVALID_ICC_HASH_CC) # 2i. Check infused challenge sub-slot hash in reward sub-slot if ( @@ -396,10 +393,9 @@ def validate_unfinished_header_block( f"{sub_slot.reward_chain.deficit}", ), ) - else: - # 2t. Otherwise, deficit stays the same at the slot ends, cannot reset until 0 - if sub_slot.reward_chain.deficit != prev_b.deficit: - return None, ValidationError(Err.INVALID_DEFICIT, "deficit is wrong at slot end") + # 2t. Otherwise, deficit stays the same at the slot ends, cannot reset until 0 + elif sub_slot.reward_chain.deficit != prev_b.deficit: + return None, ValidationError(Err.INVALID_DEFICIT, "deficit is wrong at slot end") # 3. Check sub-epoch summary # Note that the subepoch summary is the summary of the previous subepoch (not the one that just finished) @@ -635,16 +631,15 @@ def validate_unfinished_header_block( return None, ValidationError(Err.INVALID_RC_SP_VDF) if new_sub_slot: rc_sp_hash = header_block.finished_sub_slots[-1].reward_chain.get_hash() + elif genesis_block: + rc_sp_hash = constants.GENESIS_CHALLENGE else: - if genesis_block: - rc_sp_hash = constants.GENESIS_CHALLENGE - else: - assert prev_b is not None - curr = prev_b - while not curr.first_in_sub_slot: - curr = blocks.block_record(curr.prev_hash) - assert curr.finished_reward_slot_hashes is not None - rc_sp_hash = curr.finished_reward_slot_hashes[-1] + assert prev_b is not None + curr = prev_b + while not curr.first_in_sub_slot: + curr = blocks.block_record(curr.prev_hash) + assert curr.finished_reward_slot_hashes is not None + rc_sp_hash = curr.finished_reward_slot_hashes[-1] # 12. Check reward chain sp signature if not AugSchemeMPL.verify( @@ -761,25 +756,24 @@ def validate_unfinished_header_block( != constants.GENESIS_PRE_FARM_FARMER_PUZZLE_HASH ): return None, ValidationError(Err.INVALID_PREFARM) + # 20b. If pospace has a pool pk, heck pool target signature. Should not check this for genesis block. + elif header_block.reward_chain_block.proof_of_space.pool_public_key is not None: + assert header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash is None + assert header_block.foliage.foliage_block_data.pool_signature is not None + if not AugSchemeMPL.verify( + header_block.reward_chain_block.proof_of_space.pool_public_key, + bytes(header_block.foliage.foliage_block_data.pool_target), + header_block.foliage.foliage_block_data.pool_signature, + ): + return None, ValidationError(Err.INVALID_POOL_SIGNATURE) else: - # 20b. If pospace has a pool pk, heck pool target signature. Should not check this for genesis block. - if header_block.reward_chain_block.proof_of_space.pool_public_key is not None: - assert header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash is None - assert header_block.foliage.foliage_block_data.pool_signature is not None - if not AugSchemeMPL.verify( - header_block.reward_chain_block.proof_of_space.pool_public_key, - bytes(header_block.foliage.foliage_block_data.pool_target), - header_block.foliage.foliage_block_data.pool_signature, - ): - return None, ValidationError(Err.INVALID_POOL_SIGNATURE) - else: - # 20c. Otherwise, the plot is associated with a contract puzzle hash, not a public key - assert header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash is not None - if ( - header_block.foliage.foliage_block_data.pool_target.puzzle_hash - != header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash - ): - return None, ValidationError(Err.INVALID_POOL_TARGET) + # 20c. Otherwise, the plot is associated with a contract puzzle hash, not a public key + assert header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash is not None + if ( + header_block.foliage.foliage_block_data.pool_target.puzzle_hash + != header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash + ): + return None, ValidationError(Err.INVALID_POOL_TARGET) # 21. Check extension data if applicable. None for mainnet. # 22. Check if foliage block is present @@ -928,18 +922,17 @@ def validate_finished_header_block( # 29. Check challenge chain infusion point VDF if new_sub_slot: cc_vdf_challenge = header_block.finished_sub_slots[-1].challenge_chain.get_hash() + # Not first block in slot + elif genesis_block: + # genesis block + cc_vdf_challenge = constants.GENESIS_CHALLENGE else: - # Not first block in slot - if genesis_block: - # genesis block - cc_vdf_challenge = constants.GENESIS_CHALLENGE - else: - assert prev_b is not None - # Not genesis block, go back to first block in slot - curr = prev_b - while curr.finished_challenge_slot_hashes is None: - curr = blocks.block_record(curr.prev_hash) - cc_vdf_challenge = curr.finished_challenge_slot_hashes[-1] + assert prev_b is not None + # Not genesis block, go back to first block in slot + curr = prev_b + while curr.finished_challenge_slot_hashes is None: + curr = blocks.block_record(curr.prev_hash) + cc_vdf_challenge = curr.finished_challenge_slot_hashes[-1] cc_target_vdf_info = VDFInfo( cc_vdf_challenge, @@ -1047,9 +1040,8 @@ def validate_finished_header_block( icc_target_vdf_info, ): return None, ValidationError(Err.INVALID_ICC_VDF, "invalid icc proof") - else: - if header_block.infused_challenge_chain_ip_proof is not None: - return None, ValidationError(Err.INVALID_ICC_VDF) + elif header_block.infused_challenge_chain_ip_proof is not None: + return None, ValidationError(Err.INVALID_ICC_VDF) # 32. Check reward block hash if header_block.foliage.reward_block_hash != header_block.reward_chain_block.get_hash(): diff --git a/chia/consensus/blockchain.py b/chia/consensus/blockchain.py index 2117f963f308..00d9df5d1a4c 100644 --- a/chia/consensus/blockchain.py +++ b/chia/consensus/blockchain.py @@ -708,9 +708,8 @@ async def validate_unfinished_block_header( if block.transactions_generator is not None: if std_hash(bytes(block.transactions_generator)) != block.transactions_info.generator_root: return None, Err.INVALID_TRANSACTIONS_GENERATOR_HASH - else: - if block.transactions_info.generator_root != bytes([0] * 32): - return None, Err.INVALID_TRANSACTIONS_GENERATOR_HASH + elif block.transactions_info.generator_root != bytes([0] * 32): + return None, Err.INVALID_TRANSACTIONS_GENERATOR_HASH if ( block.foliage_transaction_block is None diff --git a/chia/consensus/get_block_challenge.py b/chia/consensus/get_block_challenge.py index de4a6952f040..9064218d104f 100644 --- a/chia/consensus/get_block_challenge.py +++ b/chia/consensus/get_block_challenge.py @@ -72,34 +72,33 @@ def get_block_challenge( else: # No overflow, new slot with a new challenge challenge = header_block.finished_sub_slots[-1].challenge_chain.get_hash() + elif genesis_block: + challenge = constants.GENESIS_CHALLENGE else: - if genesis_block: - challenge = constants.GENESIS_CHALLENGE - else: - if overflow: - if skip_overflow_last_ss_validation: - # Overflow infusion without the new slot, so get the last challenge - challenges_to_look_for = 1 - else: - # Overflow infusion, so get the second to last challenge. skip_overflow_last_ss_validation is False, - # Which means no sub slots are omitted - challenges_to_look_for = 2 - else: + if overflow: + if skip_overflow_last_ss_validation: + # Overflow infusion without the new slot, so get the last challenge challenges_to_look_for = 1 - reversed_challenge_hashes: list[bytes32] = [] - curr: BlockRecord = blocks.block_record(header_block.prev_header_hash) - while len(reversed_challenge_hashes) < challenges_to_look_for: - if curr.first_in_sub_slot: - assert curr.finished_challenge_slot_hashes is not None - reversed_challenge_hashes += reversed(curr.finished_challenge_slot_hashes) - if len(reversed_challenge_hashes) >= challenges_to_look_for: - break - if curr.height == 0: - assert curr.finished_challenge_slot_hashes is not None - assert len(curr.finished_challenge_slot_hashes) > 0 + else: + # Overflow infusion, so get the second to last challenge. skip_overflow_last_ss_validation is False, + # Which means no sub slots are omitted + challenges_to_look_for = 2 + else: + challenges_to_look_for = 1 + reversed_challenge_hashes: list[bytes32] = [] + curr: BlockRecord = blocks.block_record(header_block.prev_header_hash) + while len(reversed_challenge_hashes) < challenges_to_look_for: + if curr.first_in_sub_slot: + assert curr.finished_challenge_slot_hashes is not None + reversed_challenge_hashes += reversed(curr.finished_challenge_slot_hashes) + if len(reversed_challenge_hashes) >= challenges_to_look_for: break - curr = blocks.block_record(curr.prev_hash) - challenge = reversed_challenge_hashes[challenges_to_look_for - 1] + if curr.height == 0: + assert curr.finished_challenge_slot_hashes is not None + assert len(curr.finished_challenge_slot_hashes) > 0 + break + curr = blocks.block_record(curr.prev_hash) + challenge = reversed_challenge_hashes[challenges_to_look_for - 1] return challenge diff --git a/chia/daemon/server.py b/chia/daemon/server.py index c03fdecf5ff9..0189650cd47b 100644 --- a/chia/daemon/server.py +++ b/chia/daemon/server.py @@ -1373,9 +1373,8 @@ async def register_service(self, websocket: WebSocketResponse, request: dict[str "service": service, "queue": self.extract_plot_queue(), } - else: - if self.ping_job is None: - self.ping_job = create_referenced_task(self.ping_task()) + elif self.ping_job is None: + self.ping_job = create_referenced_task(self.ping_task()) self.log.info(f"registered for service {service}") log.info(f"{response}") return response diff --git a/chia/data_layer/data_layer_wallet.py b/chia/data_layer/data_layer_wallet.py index 8876b81d1b11..847b6e8c0116 100644 --- a/chia/data_layer/data_layer_wallet.py +++ b/chia/data_layer/data_layer_wallet.py @@ -590,15 +590,14 @@ async def generate_signed_transaction( if coins is None or len(coins) == 0: if launcher_id is None: raise ValueError("Not enough info to know which DL coin to send") + elif len(coins) != 1: + raise ValueError("The wallet can only send one DL coin at a time") else: - if len(coins) != 1: - raise ValueError("The wallet can only send one DL coin at a time") + record = await self.wallet_state_manager.dl_store.get_singleton_record(next(iter(coins)).name()) + if record is None: + raise ValueError("The specified coin is not a tracked DL") else: - record = await self.wallet_state_manager.dl_store.get_singleton_record(next(iter(coins)).name()) - if record is None: - raise ValueError("The specified coin is not a tracked DL") - else: - launcher_id = record.launcher_id + launcher_id = record.launcher_id if len(amounts) != 1 or len(puzzle_hashes) != 1: raise ValueError("The wallet can only send one DL coin to one place at a time") @@ -1090,12 +1089,13 @@ async def finish_graftroot_solutions(offer: Offer, solver: Solver) -> Offer: # Create all of the new solutions new_spends: list[CoinSpend] = [] for spend in offer.coin_spends(): + spend_to_add = spend solution = Program.from_serialized(spend.solution) if match_dl_singleton(spend.puzzle_reveal)[0]: try: graftroot: Program = solution.at("rrffrf") except EvalError: - new_spends.append(spend) + new_spends.append(spend_to_add) continue mod, curried_args_prg = graftroot.uncurry() if mod == GRAFTROOT_DL_OFFERS: @@ -1138,9 +1138,9 @@ async def finish_graftroot_solutions(offer: Offer, solver: Solver) -> Offer: ] ) ) - new_spend: CoinSpend = spend.replace(solution=new_solution.to_serialized()) - spend = new_spend - new_spends.append(spend) + spend_to_add = spend.replace(solution=new_solution.to_serialized()) + + new_spends.append(spend_to_add) return Offer({}, WalletSpendBundle(new_spends, offer.aggregated_signature()), offer.driver_dict) diff --git a/chia/data_layer/data_store.py b/chia/data_layer/data_store.py index 039b68973693..c2357aa52e5e 100644 --- a/chia/data_layer/data_store.py +++ b/chia/data_layer/data_store.py @@ -1172,8 +1172,8 @@ async def update_ancestor_hashes_on_insert( ) if status == Status.COMMITTED: - for left_hash, right_hash, store_id in insert_ancestors_cache: - await self._insert_ancestor_table(left_hash, right_hash, store_id, new_generation) + for left_hash, right_hash, cache_store_id in insert_ancestors_cache: + await self._insert_ancestor_table(left_hash, right_hash, cache_store_id, new_generation) return new_root @@ -1329,8 +1329,8 @@ async def delete( generation=new_generation, ) if status == Status.COMMITTED: - for left_hash, right_hash, store_id in insert_ancestors_cache: - await self._insert_ancestor_table(left_hash, right_hash, store_id, new_generation) + for left_hash, right_hash, cache_store_id in insert_ancestors_cache: + await self._insert_ancestor_table(left_hash, right_hash, cache_store_id, new_generation) return new_root @@ -1428,8 +1428,8 @@ async def clean_node_table(self, writer: Optional[aiosqlite.Connection] = None) """ params = {"pending_status": Status.PENDING.value, "pending_batch_status": Status.PENDING_BATCH.value} if writer is None: - async with self.db_wrapper.writer(foreign_key_enforcement_enabled=False) as writer: - await writer.execute(query, params) + async with self.db_wrapper.writer(foreign_key_enforcement_enabled=False) as sub_writer: + await sub_writer.execute(query, params) else: await writer.execute(query, params) @@ -1497,16 +1497,15 @@ async def insert_batch( pending_root = await self.get_pending_root(store_id=store_id) if pending_root is None: latest_local_root: Optional[Root] = old_root - else: - if pending_root.status == Status.PENDING_BATCH: - # We have an unfinished batch, continue the current batch on top of it. - if pending_root.generation != old_root.generation + 1: - raise Exception("Internal error") - await self.change_root_status(pending_root, Status.COMMITTED) - await self.build_ancestor_table_for_latest_root(store_id=store_id) - latest_local_root = pending_root - else: + elif pending_root.status == Status.PENDING_BATCH: + # We have an unfinished batch, continue the current batch on top of it. + if pending_root.generation != old_root.generation + 1: raise Exception("Internal error") + await self.change_root_status(pending_root, Status.COMMITTED) + await self.build_ancestor_table_for_latest_root(store_id=store_id) + latest_local_root = pending_root + else: + raise Exception("Internal error") assert latest_local_root is not None @@ -1548,11 +1547,10 @@ async def insert_batch( if old_node is None: pending_autoinsert_hashes.append(terminal_node_hash) + elif key_hash_frequency[hash] == 1: + raise Exception(f"Key already present: {key.hex()}") else: - if key_hash_frequency[hash] == 1: - raise Exception(f"Key already present: {key.hex()}") - else: - pending_upsert_new_hashes[old_node.hash] = terminal_node_hash + pending_upsert_new_hashes[old_node.hash] = terminal_node_hash continue insert_result = await self.autoinsert( key, value, store_id, True, Status.COMMITTED, root=latest_local_root @@ -1878,8 +1876,12 @@ async def get_tree_as_nodes(self, store_id: bytes32) -> Node: hash_to_node: dict[bytes32, Node] = {} for node in reversed(nodes): if isinstance(node, InternalNode): - node = replace(node, left=hash_to_node[node.left_hash], right=hash_to_node[node.right_hash]) - hash_to_node[node.hash] = node + node_entry: Node = replace( + node, left=hash_to_node[node.left_hash], right=hash_to_node[node.right_hash] + ) + else: + node_entry = node + hash_to_node[node_entry.hash] = node_entry root_node = hash_to_node[root_node.hash] @@ -2228,13 +2230,12 @@ async def get_subscriptions(self) -> list[Subscription]: ) else: subscriptions.append(Subscription(store_id, [])) - else: - if url is not None and num_consecutive_failures is not None and ignore_till is not None: - new_servers_info = subscription.servers_info - new_servers_info.append(ServerInfo(url, num_consecutive_failures, ignore_till)) - new_subscription = replace(subscription, servers_info=new_servers_info) - subscriptions.remove(subscription) - subscriptions.append(new_subscription) + elif url is not None and num_consecutive_failures is not None and ignore_till is not None: + new_servers_info = subscription.servers_info + new_servers_info.append(ServerInfo(url, num_consecutive_failures, ignore_till)) + new_subscription = replace(subscription, servers_info=new_servers_info) + subscriptions.remove(subscription) + subscriptions.append(new_subscription) return subscriptions diff --git a/chia/full_node/full_node_api.py b/chia/full_node/full_node_api.py index dc435c436ced..4d0a5dd1b2c8 100644 --- a/chia/full_node/full_node_api.py +++ b/chia/full_node/full_node_api.py @@ -1393,14 +1393,11 @@ async def send_transaction( error_name = error.name if error is not None else None if status == MempoolInclusionStatus.SUCCESS: response = wallet_protocol.TransactionAck(spend_name, uint8(status.value), error_name) + # If it failed/pending, but it previously succeeded (in mempool), this is idempotence, return SUCCESS + elif self.full_node.mempool_manager.get_spendbundle(spend_name) is not None: + response = wallet_protocol.TransactionAck(spend_name, uint8(MempoolInclusionStatus.SUCCESS.value), None) else: - # If it failed/pending, but it previously succeeded (in mempool), this is idempotence, return SUCCESS - if self.full_node.mempool_manager.get_spendbundle(spend_name) is not None: - response = wallet_protocol.TransactionAck( - spend_name, uint8(MempoolInclusionStatus.SUCCESS.value), None - ) - else: - response = wallet_protocol.TransactionAck(spend_name, uint8(status.value), error_name) + response = wallet_protocol.TransactionAck(spend_name, uint8(status.value), error_name) return make_msg(ProtocolMessageTypes.transaction_ack, response) @metadata.request() diff --git a/chia/full_node/weight_proof.py b/chia/full_node/weight_proof.py index 71886ad759fe..24b45b0694db 100644 --- a/chia/full_node/weight_proof.py +++ b/chia/full_node/weight_proof.py @@ -411,17 +411,16 @@ async def __first_sub_slot_vdfs( while not curr_sub_rec.sub_epoch_summary_included: curr_sub_rec = blocks[curr_sub_rec.prev_hash] first_rc_end_of_slot_vdf = self.first_rc_end_of_slot_vdf(header_block, blocks, header_blocks) + elif header_block_sub_rec.overflow and header_block_sub_rec.first_in_sub_slot: + sub_slots_num = 2 + while sub_slots_num > 0 and curr_sub_rec.height > 0: + if curr_sub_rec.first_in_sub_slot: + assert curr_sub_rec.finished_challenge_slot_hashes is not None + sub_slots_num -= len(curr_sub_rec.finished_challenge_slot_hashes) + curr_sub_rec = blocks[curr_sub_rec.prev_hash] else: - if header_block_sub_rec.overflow and header_block_sub_rec.first_in_sub_slot: - sub_slots_num = 2 - while sub_slots_num > 0 and curr_sub_rec.height > 0: - if curr_sub_rec.first_in_sub_slot: - assert curr_sub_rec.finished_challenge_slot_hashes is not None - sub_slots_num -= len(curr_sub_rec.finished_challenge_slot_hashes) - curr_sub_rec = blocks[curr_sub_rec.prev_hash] - else: - while not curr_sub_rec.first_in_sub_slot and curr_sub_rec.height > 0: - curr_sub_rec = blocks[curr_sub_rec.prev_hash] + while not curr_sub_rec.first_in_sub_slot and curr_sub_rec.height > 0: + curr_sub_rec = blocks[curr_sub_rec.prev_hash] curr = header_blocks[curr_sub_rec.header_hash] sub_slots_data: list[SubSlotData] = [] @@ -1533,10 +1532,10 @@ def _get_last_ses_hash( ) -> tuple[Optional[bytes32], uint32]: for idx, block in enumerate(reversed(recent_reward_chain)): if (block.reward_chain_block.height % constants.SUB_EPOCH_BLOCKS) == 0: - idx = len(recent_reward_chain) - 1 - idx # reverse + original_idx = len(recent_reward_chain) - 1 - idx # reverse # find first block after sub slot end - while idx < len(recent_reward_chain): - curr = recent_reward_chain[idx] + while original_idx < len(recent_reward_chain): + curr = recent_reward_chain[original_idx] if len(curr.finished_sub_slots) > 0: for slot in curr.finished_sub_slots: if slot.challenge_chain.subepoch_summary_hash is not None: @@ -1544,7 +1543,7 @@ def _get_last_ses_hash( slot.challenge_chain.subepoch_summary_hash, curr.reward_chain_block.height, ) - idx += 1 + original_idx += 1 return None, uint32(0) diff --git a/chia/plotting/check_plots.py b/chia/plotting/check_plots.py index 0fe7c2567fa5..f4d2a7ab61b0 100644 --- a/chia/plotting/check_plots.py +++ b/chia/plotting/check_plots.py @@ -170,9 +170,9 @@ def process_plot(plot_path: Path, plot_info: PlotInfo, num_start: int, num_end: challenge = std_hash(i.to_bytes(32, "big")) # Some plot errors cause get_qualities_for_challenge to throw a RuntimeError try: - quality_start_time = int(round(time() * 1000)) + quality_start_time = round(time() * 1000) for index, quality_str in enumerate(pr.get_qualities_for_challenge(challenge)): - quality_spent_time = int(round(time() * 1000)) - quality_start_time + quality_spent_time = round(time() * 1000) - quality_start_time if quality_spent_time > 8000: log.warning( f"\tLooking up qualities took: {quality_spent_time} ms. This should be below 8 seconds " @@ -183,9 +183,9 @@ def process_plot(plot_path: Path, plot_info: PlotInfo, num_start: int, num_end: # Other plot errors cause get_full_proof or validate_proof to throw an AssertionError try: - proof_start_time = int(round(time() * 1000)) + proof_start_time = round(time() * 1000) proof = pr.get_full_proof(challenge, index, parallel_read) - proof_spent_time = int(round(time() * 1000)) - proof_start_time + proof_spent_time = round(time() * 1000) - proof_start_time if proof_spent_time > 15000: log.warning( f"\tFinding proof took: {proof_spent_time} ms. This should be below 15 seconds " @@ -207,7 +207,7 @@ def process_plot(plot_path: Path, plot_info: PlotInfo, num_start: int, num_end: f"{type(e)}: {e} error in proving/verifying for plot {plot_path}. Filepath: {plot_path}" ) caught_exception = True - quality_start_time = int(round(time() * 1000)) + quality_start_time = round(time() * 1000) except KeyboardInterrupt: log.warning("Interrupted, closing") return diff --git a/chia/plotting/create_plots.py b/chia/plotting/create_plots.py index 08369c9c2c54..14b056c88046 100644 --- a/chia/plotting/create_plots.py +++ b/chia/plotting/create_plots.py @@ -83,10 +83,9 @@ async def resolve(self) -> PlotKeys: if self.pool_contract_address is not None: raise RuntimeError("Choose one of pool_contract_address and pool_public_key") pool_public_key = G1Element.from_bytes(bytes.fromhex(self.pool_public_key)) - else: - if self.pool_contract_address is None: - # If nothing is set, farms to the provided key (or the first key) - pool_public_key = await self.get_pool_public_key(keychain_proxy) + elif self.pool_contract_address is None: + # If nothing is set, farms to the provided key (or the first key) + pool_public_key = await self.get_pool_public_key(keychain_proxy) self.resolved_keys = PlotKeys(farmer_public_key, pool_public_key, self.pool_contract_address) finally: diff --git a/chia/seeder/crawl_store.py b/chia/seeder/crawl_store.py index dde1a7a18df8..be565efcea81 100644 --- a/chia/seeder/crawl_store.py +++ b/chia/seeder/crawl_store.py @@ -195,11 +195,10 @@ async def get_peers_to_crawl(self, min_batch_size: int, max_batch_size: int) -> counter += 1 if reliability.ignore_till < now and reliability.ban_till < now: add = True - else: - if reliability.ban_till >= now: - self.banned_peers += 1 - elif reliability.ignore_till >= now: - self.ignored_peers += 1 + elif reliability.ban_till >= now: + self.banned_peers += 1 + elif reliability.ignore_till >= now: + self.ignored_peers += 1 record = self.host_to_records[peer_id] if record.last_try_timestamp == 0 and record.connected_timestamp == 0: add = True @@ -342,9 +341,6 @@ def load_host_to_version(self) -> tuple[dict[str, str], dict[str, uint64]]: handshake = {} for host, record in self.host_to_records.items(): - if host not in self.host_to_records: - continue - record = self.host_to_records[host] if record.version == "undefined": continue if record.handshake_time < time.time() - 5 * 24 * 3600: diff --git a/chia/server/address_manager.py b/chia/server/address_manager.py index 4a3cb6f9f913..3a3130f03f90 100644 --- a/chia/server/address_manager.py +++ b/chia/server/address_manager.py @@ -177,7 +177,7 @@ def get_bucket_position(self, key: int, is_new: bool, nBucket: int) -> int: def is_terrible(self, now: Optional[int] = None) -> bool: if now is None: - now = int(math.floor(time.time())) + now = math.floor(time.time()) # never remove things tried in the last minute if self.last_try > 0 and self.last_try >= now - 60: return False @@ -202,7 +202,7 @@ def is_terrible(self, now: Optional[int] = None) -> bool: def get_selection_chance(self, now: Optional[int] = None) -> float: if now is None: - now = int(math.floor(time.time())) + now = math.floor(time.time()) chance = 1.0 since_last_try = max(now - self.last_try, 0) # deprioritize very recent attempts away @@ -371,9 +371,8 @@ def _set_new_matrix(self, row: int, col: int, value: int) -> None: if value == -1: if (row, col) in self.used_new_matrix_positions: self.used_new_matrix_positions.remove((row, col)) - else: - if (row, col) not in self.used_new_matrix_positions: - self.used_new_matrix_positions.add((row, col)) + elif (row, col) not in self.used_new_matrix_positions: + self.used_new_matrix_positions.add((row, col)) # Use only this method for modifying tried matrix. def _set_tried_matrix(self, row: int, col: int, value: int) -> None: @@ -381,9 +380,8 @@ def _set_tried_matrix(self, row: int, col: int, value: int) -> None: if value == -1: if (row, col) in self.used_tried_matrix_positions: self.used_tried_matrix_positions.remove((row, col)) - else: - if (row, col) not in self.used_tried_matrix_positions: - self.used_tried_matrix_positions.add((row, col)) + elif (row, col) not in self.used_tried_matrix_positions: + self.used_tried_matrix_positions.add((row, col)) def load_used_table_positions(self) -> None: self.used_new_matrix_positions = set() @@ -587,10 +585,9 @@ def add_to_new_table_(self, addr: TimestampedPeerInfo, source: Optional[PeerInfo info.ref_count += 1 if node_id is not None: self._set_new_matrix(new_bucket, new_bucket_pos, node_id) - else: - if info.ref_count == 0: - if node_id is not None: - self.delete_new_entry_(node_id) + elif info.ref_count == 0: + if node_id is not None: + self.delete_new_entry_(node_id) return is_unique def attempt_(self, addr: PeerInfo, count_failures: bool, timestamp: int) -> None: @@ -737,7 +734,7 @@ def get_peers_(self) -> list[TimestampedPeerInfo]: return addr def cleanup(self, max_timestamp_difference: int, max_consecutive_failures: int) -> None: - now = int(math.floor(time.time())) + now = math.floor(time.time()) for bucket in range(NEW_BUCKET_COUNT): for pos in range(BUCKET_SIZE): if self.new_matrix[bucket][pos] != -1: diff --git a/chia/server/node_discovery.py b/chia/server/node_discovery.py index b34c4bbb0d02..2d5593cca2f2 100644 --- a/chia/server/node_discovery.py +++ b/chia/server/node_discovery.py @@ -228,12 +228,11 @@ async def start_client_async(self, addr: PeerInfo, is_feeler: bool) -> None: if self.server.is_duplicate_or_self_connection(addr): # Mark it as a softer attempt, without counting the failures. await self.address_manager.attempt(addr, False) + elif client_connected is True: + await self.address_manager.mark_good(addr) + await self.address_manager.connect(addr) else: - if client_connected is True: - await self.address_manager.mark_good(addr) - await self.address_manager.connect(addr) - else: - await self.address_manager.attempt(addr, True) + await self.address_manager.attempt(addr, True) self.pending_outbound_connections.remove(addr.host) except Exception as e: if addr.host in self.pending_outbound_connections: diff --git a/chia/server/server.py b/chia/server/server.py index 7b64c7877afa..876e79406a36 100644 --- a/chia/server/server.py +++ b/chia/server/server.py @@ -260,9 +260,8 @@ async def garbage_collect_connections_task(self) -> None: if is_crawler is not None: if time.time() - connection.creation_time > 5: to_remove.append(connection) - else: - if time.time() - connection.last_message_time > 1800: - to_remove.append(connection) + elif time.time() - connection.last_message_time > 1800: + to_remove.append(connection) for connection in to_remove: self.log.debug(f"Garbage collecting connection {connection.peer_info.host} due to inactivity") if connection.closed: diff --git a/chia/simulator/block_tools.py b/chia/simulator/block_tools.py index e51143c08e16..79678a4924fe 100644 --- a/chia/simulator/block_tools.py +++ b/chia/simulator/block_tools.py @@ -898,11 +898,10 @@ def get_consecutive_blocks( # address, so continue until a proof of space tied to a pk is found continue pool_target = PoolTarget(proof_of_space.pool_contract_puzzle_hash, uint32(0)) + elif pool_reward_puzzle_hash is not None: + pool_target = PoolTarget(pool_reward_puzzle_hash, uint32(0)) else: - if pool_reward_puzzle_hash is not None: - pool_target = PoolTarget(pool_reward_puzzle_hash, uint32(0)) - else: - pool_target = PoolTarget(self.pool_ph, uint32(0)) + pool_target = PoolTarget(self.pool_ph, uint32(0)) new_gen = self.setup_new_gen( tx_block_heights, @@ -1193,11 +1192,10 @@ def get_consecutive_blocks( # address, so continue until a proof of space tied to a pk is found continue pool_target = PoolTarget(proof_of_space.pool_contract_puzzle_hash, uint32(0)) + elif pool_reward_puzzle_hash is not None: + pool_target = PoolTarget(pool_reward_puzzle_hash, uint32(0)) else: - if pool_reward_puzzle_hash is not None: - pool_target = PoolTarget(pool_reward_puzzle_hash, uint32(0)) - else: - pool_target = PoolTarget(self.pool_ph, uint32(0)) + pool_target = PoolTarget(self.pool_ph, uint32(0)) new_gen = self.setup_new_gen( tx_block_heights, diff --git a/chia/timelord/timelord.py b/chia/timelord/timelord.py index f9f490cb9f55..aa559a32f2c5 100644 --- a/chia/timelord/timelord.py +++ b/chia/timelord/timelord.py @@ -160,20 +160,19 @@ async def manage(self) -> AsyncIterator[None]: slow_bluebox = self.config.get("slow_bluebox", False) if not self.bluebox_mode: self.main_loop = create_referenced_task(self._manage_chains()) + elif os.name == "nt" or slow_bluebox: + # `vdf_client` doesn't build on windows, use `prove()` from chiavdf. + workers = self.config.get("slow_bluebox_process_count", 1) + self._executor_shutdown_tempfile = _create_shutdown_file() + self.bluebox_pool = ThreadPoolExecutor( + max_workers=workers, + thread_name_prefix="blue-box-", + ) + self.main_loop = create_referenced_task( + self._start_manage_discriminant_queue_sanitizer_slow(self.bluebox_pool, workers) + ) else: - if os.name == "nt" or slow_bluebox: - # `vdf_client` doesn't build on windows, use `prove()` from chiavdf. - workers = self.config.get("slow_bluebox_process_count", 1) - self._executor_shutdown_tempfile = _create_shutdown_file() - self.bluebox_pool = ThreadPoolExecutor( - max_workers=workers, - thread_name_prefix="blue-box-", - ) - self.main_loop = create_referenced_task( - self._start_manage_discriminant_queue_sanitizer_slow(self.bluebox_pool, workers) - ) - else: - self.main_loop = create_referenced_task(self._manage_discriminant_queue_sanitizer()) + self.main_loop = create_referenced_task(self._manage_discriminant_queue_sanitizer()) log.info(f"Started timelord, listening on port {self.get_vdf_server_port()}") try: yield diff --git a/chia/util/db_wrapper.py b/chia/util/db_wrapper.py index da19b0db961f..2591eb637865 100644 --- a/chia/util/db_wrapper.py +++ b/chia/util/db_wrapper.py @@ -124,15 +124,14 @@ def get_host_parameter_limit() -> int: limit_number = sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER host_parameter_limit = connection.getlimit(limit_number) - else: - # guessing based on defaults, seems you can't query + # guessing based on defaults, seems you can't query - # https://www.sqlite.org/changes.html#version_3_32_0 - # Increase the default upper bound on the number of parameters from 999 to 32766. - if sqlite3.sqlite_version_info >= (3, 32, 0): - host_parameter_limit = 32766 - else: - host_parameter_limit = 999 + # https://www.sqlite.org/changes.html#version_3_32_0 + # Increase the default upper bound on the number of parameters from 999 to 32766. + elif sqlite3.sqlite_version_info >= (3, 32, 0): + host_parameter_limit = 32766 + else: + host_parameter_limit = 999 return host_parameter_limit diff --git a/chia/wallet/cat_wallet/cat_outer_puzzle.py b/chia/wallet/cat_wallet/cat_outer_puzzle.py index 1b20cd2d829f..f5a83d9f8581 100644 --- a/chia/wallet/cat_wallet/cat_outer_puzzle.py +++ b/chia/wallet/cat_wallet/cat_outer_puzzle.py @@ -105,8 +105,11 @@ def solve(self, constructor: PuzzleInfo, solver: Solver, inner_puzzle: Program, parent_coin: Coin = parent_spend.coin also = constructor.also() if also is not None: - solution = self._solve(also, solver, puzzle, solution) - puzzle = self._construct(also, puzzle) + constructed_solution = self._solve(also, solver, puzzle, solution) + constructed_puzzle = self._construct(also, puzzle) + else: + constructed_solution = solution + constructed_puzzle = puzzle args = match_cat_puzzle(uncurry_puzzle(parent_spend.puzzle_reveal)) assert args is not None _, _, parent_inner_puzzle = args @@ -114,8 +117,8 @@ def solve(self, constructor: PuzzleInfo, solver: Solver, inner_puzzle: Program, SpendableCAT( coin, tail_hash, - puzzle, - solution, + constructed_puzzle, + constructed_solution, lineage_proof=LineageProof( parent_coin.parent_coin_info, parent_inner_puzzle.get_tree_hash(), uint64(parent_coin.amount) ), diff --git a/chia/wallet/nft_wallet/nft_wallet.py b/chia/wallet/nft_wallet/nft_wallet.py index 81a2e8017fd0..631d4c6cacb2 100644 --- a/chia/wallet/nft_wallet/nft_wallet.py +++ b/chia/wallet/nft_wallet/nft_wallet.py @@ -550,9 +550,9 @@ async def create_from_puzzle_info( name: Optional[str] = None, ) -> Any: # Off the bat we don't support multiple profile but when we do this will have to change - for wallet in wallet_state_manager.wallets.values(): - if wallet.type() == WalletType.NFT.value: - return wallet + for wsm_wallet in wallet_state_manager.wallets.values(): + if wsm_wallet.type() == WalletType.NFT.value: + return wsm_wallet # TODO: These are not the arguments to this function yet but they will be return await cls.create_new_nft_wallet( diff --git a/chia/wallet/puzzle_drivers.py b/chia/wallet/puzzle_drivers.py index 746c304f9efc..f99f60de7322 100644 --- a/chia/wallet/puzzle_drivers.py +++ b/chia/wallet/puzzle_drivers.py @@ -65,15 +65,14 @@ def check_type(self, types: list[str]) -> bool: return True else: return False - else: - if self.type() == types[0]: - types.pop(0) - if self.also(): - return self.also().check_type(types) # type: ignore - else: - return self.check_type(types) + elif self.type() == types[0]: + types.pop(0) + if self.also(): + return self.also().check_type(types) # type: ignore else: - return False + return self.check_type(types) + else: + return False @dataclass(frozen=True) diff --git a/chia/wallet/util/merkle_utils.py b/chia/wallet/util/merkle_utils.py index 9a8df4adc711..d15569479d7c 100644 --- a/chia/wallet/util/merkle_utils.py +++ b/chia/wallet/util/merkle_utils.py @@ -39,9 +39,9 @@ def build_merkle_tree_from_binary_tree(tuples: TupleTree) -> tuple[bytes32, dict proof.append(right_root) new_proofs[name] = (path, proof) for name, (path, proof) in right_proofs.items(): - path |= 1 << len(proof) + appended_path = path | (1 << len(proof)) proof.append(left_root) - new_proofs[name] = (path, proof) + new_proofs[name] = (appended_path, proof) return new_root, new_proofs diff --git a/chia/wallet/vc_wallet/vc_wallet.py b/chia/wallet/vc_wallet/vc_wallet.py index e56578484afe..bf37b2bd57a2 100644 --- a/chia/wallet/vc_wallet/vc_wallet.py +++ b/chia/wallet/vc_wallet/vc_wallet.py @@ -455,12 +455,10 @@ async def add_vc_authorization( crcat_spends.append(crcat_spend) if spend in offer._bundle.coin_spends: spends_to_fix[spend.coin.name()] = spend - else: - if spend in offer._bundle.coin_spends: # pragma: no cover - other_spends.append(spend) - else: - if spend in offer._bundle.coin_spends: + elif spend in offer._bundle.coin_spends: # pragma: no cover other_spends.append(spend) + elif spend in offer._bundle.coin_spends: + other_spends.append(spend) # Figure out what VC announcements are needed announcements_to_make: dict[bytes32, list[CreatePuzzleAnnouncement]] = {} diff --git a/chia/wallet/wallet_node.py b/chia/wallet/wallet_node.py index 88dee1ef39b1..99a87c50b57a 100644 --- a/chia/wallet/wallet_node.py +++ b/chia/wallet/wallet_node.py @@ -911,14 +911,13 @@ async def add_states_from_peer( ): # only one peer told us to rollback so only clear for that peer await self.perform_atomic_rollback(fork_height, cache=cache) - else: - if fork_height is not None: - # only one peer told us to rollback so only clear for that peer - cache.clear_after_height(fork_height) - self.log.info(f"clear_after_height {fork_height} for peer {peer}") - if not trusted: - # Rollback race_cache not in clear_after_height to avoid applying rollbacks from new peak processing - cache.rollback_race_cache(fork_height=fork_height) + elif fork_height is not None: + # only one peer told us to rollback so only clear for that peer + cache.clear_after_height(fork_height) + self.log.info(f"clear_after_height {fork_height} for peer {peer}") + if not trusted: + # Rollback race_cache not in clear_after_height to avoid applying rollbacks from new peak processing + cache.rollback_race_cache(fork_height=fork_height) all_tasks: list[asyncio.Task[None]] = [] target_concurrent_tasks: int = 30 @@ -989,18 +988,17 @@ async def validate_and_add(inner_states: list[CoinState], inner_idx_start: int) ) if not await self.wallet_state_manager.add_coin_states(batch.entries, peer, fork_height): return False + elif fork_height is not None: + cache.add_states_to_race_cache(batch.entries) else: - if fork_height is not None: - cache.add_states_to_race_cache(batch.entries) - else: - while len(all_tasks) >= target_concurrent_tasks: - all_tasks = [task for task in all_tasks if not task.done()] - await asyncio.sleep(0.1) - if self._shut_down: - self.log.info("Terminating receipt and validation due to shut down request") - await asyncio.gather(*all_tasks) - return False - all_tasks.append(create_referenced_task(validate_and_add(batch.entries, idx))) + while len(all_tasks) >= target_concurrent_tasks: + all_tasks = [task for task in all_tasks if not task.done()] + await asyncio.sleep(0.1) + if self._shut_down: + self.log.info("Terminating receipt and validation due to shut down request") + await asyncio.gather(*all_tasks) + return False + all_tasks.append(create_referenced_task(validate_and_add(batch.entries, idx))) idx += len(batch.entries) still_connected = self._server is not None and peer.peer_node_id in self.server.all_connections @@ -1158,9 +1156,8 @@ async def new_peak_wallet(self, new_peak: NewPeakWallet, peer: WSChiaConnection) await self.new_peak_from_trusted( new_peak_hb, latest_timestamp, peer, new_peak.fork_point_with_previous_peak ) - else: - if not await self.new_peak_from_untrusted(new_peak_hb, peer): - return + elif not await self.new_peak_from_untrusted(new_peak_hb, peer): + return # todo why do we call this if there was an exception / the sync is not finished async with self.wallet_state_manager.lock: @@ -1272,10 +1269,9 @@ async def sync_from_untrusted_close_to_peak(self, new_peak_hb: HeaderBlock, peer ) if success: self.synced_peers.add(peer.peer_node_id) - else: - if peak_hb is not None and new_peak_hb.weight <= peak_hb.weight: - # Don't process blocks at the same weight - return False + elif peak_hb is not None and new_peak_hb.weight <= peak_hb.weight: + # Don't process blocks at the same weight + return False # For every block, we need to apply the cache from race_cache for potential_height in range(backtrack_fork_height + 1, new_peak_hb.height + 1): @@ -1663,10 +1659,9 @@ async def validate_block_inclusion( if not prev_block_rc_hash == reversed_slots[-1].reward_chain.end_of_slot_vdf.challenge: self.log.error("Failed validation 7") return False - else: - if not prev_block_rc_hash == reward_chain_hash: - self.log.error("Failed validation 8") - return False + elif not prev_block_rc_hash == reward_chain_hash: + self.log.error("Failed validation 8") + return False blocks_to_cache.append((reward_chain_hash, en_block.height)) agg_sig: G2Element = AugSchemeMPL.aggregate([sig for (_, _, sig) in pk_m_sig]) diff --git a/chia/wallet/wallet_state_manager.py b/chia/wallet/wallet_state_manager.py index a71f6e0473f7..ba09ea83a206 100644 --- a/chia/wallet/wallet_state_manager.py +++ b/chia/wallet/wallet_state_manager.py @@ -1428,14 +1428,16 @@ async def handle_nft( nft_data.parent_coin_spend.solution, ) if uncurried_nft.supports_did: - _new_did_id = get_new_owner_did(uncurried_nft, Program.from_serialized(nft_data.parent_coin_spend.solution)) + parsed_did_id = get_new_owner_did( + uncurried_nft, Program.from_serialized(nft_data.parent_coin_spend.solution) + ) old_did_id = uncurried_nft.owner_did - if _new_did_id is None: + if parsed_did_id is None: new_did_id = old_did_id - elif _new_did_id == b"": + elif parsed_did_id == b"": new_did_id = None else: - new_did_id = _new_did_id + new_did_id = parsed_did_id self.log.debug( "Handling NFT: %s, old DID:%s, new DID:%s, old P2:%s, new P2:%s", nft_data.parent_coin_spend, @@ -1945,8 +1947,8 @@ async def _add_coin_states( # No more singleton (maybe destroyed?) break - coin_name = new_singleton_coin.name() - existing = await self.coin_store.get_coin_record(coin_name) + new_singleton_name = new_singleton_coin.name() + existing = await self.coin_store.get_coin_record(new_singleton_name) if existing is None: await self.coin_added( new_singleton_coin, @@ -1955,7 +1957,7 @@ async def _add_coin_states( uint32(record.wallet_id), record.wallet_type, peer, - coin_name, + new_singleton_name, coin_data, ) await self.coin_store.set_spent( @@ -1963,7 +1965,7 @@ async def _add_coin_states( ) await self.add_interested_coin_ids([new_singleton_coin.name()]) new_coin_state: list[CoinState] = await self.wallet_node.get_coin_state( - [coin_name], peer=peer, fork_height=fork_height + [new_singleton_name], peer=peer, fork_height=fork_height ) assert len(new_coin_state) == 1 curr_coin_state = new_coin_state[0] @@ -2039,8 +2041,8 @@ async def _add_coin_states( launcher_spend_additions = compute_additions(launcher_spend) assert len(launcher_spend_additions) == 1 coin_added = launcher_spend_additions[0] - coin_name = coin_added.name() - existing = await self.coin_store.get_coin_record(coin_name) + coin_added_name = coin_added.name() + existing = await self.coin_store.get_coin_record(coin_added_name) if existing is None: await self.coin_added( coin_added, @@ -2049,10 +2051,10 @@ async def _add_coin_states( pool_wallet.id(), pool_wallet.type(), peer, - coin_name, + coin_added_name, coin_data, ) - await self.add_interested_coin_ids([coin_name]) + await self.add_interested_coin_ids([coin_added_name]) else: raise RuntimeError("All cases already handled") # Logic error, all cases handled @@ -2611,20 +2613,20 @@ async def key_hints_for_pubkeys(self, pks: list[bytes]) -> KeyHints: [path_hint for pk in pks for path_hint in (await self.path_hint_for_pubkey(pk),) if path_hint is not None], ) - async def gather_signing_info(self, coin_spends: list[Spend]) -> SigningInstructions: + async def gather_signing_info(self, spends: list[Spend]) -> SigningInstructions: pks: list[bytes] = [] signing_targets: list[SigningTarget] = [] - for coin_spend in coin_spends: - _coin_spend = coin_spend.as_coin_spend() + for spend in spends: + coin_spend = spend.as_coin_spend() # Get AGG_SIG conditions conditions_dict = conditions_dict_for_solution( - Program.from_serialized(_coin_spend.puzzle_reveal), - Program.from_serialized(_coin_spend.solution), + Program.from_serialized(coin_spend.puzzle_reveal), + Program.from_serialized(coin_spend.solution), self.constants.MAX_BLOCK_COST_CLVM, ) # Create signature for pk, msg in pkm_pairs_for_conditions_dict( - conditions_dict, _coin_spend.coin, self.constants.AGG_SIG_ME_ADDITIONAL_DATA + conditions_dict, coin_spend.coin, self.constants.AGG_SIG_ME_ADDITIONAL_DATA ): pk_bytes = bytes(pk) pks.append(pk_bytes) diff --git a/chia/wallet/wallet_transaction_store.py b/chia/wallet/wallet_transaction_store.py index 9e1b764306e2..30c0e8c13749 100644 --- a/chia/wallet/wallet_transaction_store.py +++ b/chia/wallet/wallet_transaction_store.py @@ -262,10 +262,9 @@ async def get_not_sent(self, *, include_accepted_txs=False) -> list[TransactionR if time_submitted < current_time - (60 * 10): records.append(record) self.tx_submitted[record.name] = current_time, 1 - else: - if count < minimum_send_attempts: - records.append(record) - self.tx_submitted[record.name] = time_submitted, (count + 1) + elif count < minimum_send_attempts: + records.append(record) + self.tx_submitted[record.name] = time_submitted, (count + 1) else: records.append(record) self.tx_submitted[record.name] = current_time, 1 diff --git a/ruff.toml b/ruff.toml index d05f462a1bd4..2b29977f9794 100644 --- a/ruff.toml +++ b/ruff.toml @@ -61,13 +61,10 @@ ignore = [ # Should probably fix these "PLR6301", # no-self-use "PLR2004", # magic-value-comparison - "PLR1704", # redefined-argument-from-local - "PLR5501", # collapsible-else-if # Pylint warning "PLW1641", # eq-without-hash # Should probably fix these - "PLW2901", # redefined-loop-name "PLW1514", # unspecified-encoding "PLW0603", # global-statement @@ -80,10 +77,6 @@ ignore = [ # flake8-implicit-str-concat "ISC003", # explicit-string-concatenation - # pyupgrade - # Should probably fix these - "UP006", # non-pep585-annotation - # Ruff Specific # This code is problematic because using instantiated types as defaults is so common across the codebase. @@ -93,9 +86,6 @@ ignore = [ "RUF056", # falsy-dict-get-fallback # Should probably fix this "RUF029", # unused-async - "RUF043", # pytest-raises-ambiguous-pattern - "RUF046", # unnecessary-cast-to-int - "RUF052", # used-dummy-variable # Security linter "S603", # subprocess-without-shell-equals-true diff --git a/tools/cpu_utilization.py b/tools/cpu_utilization.py index 41333f014c68..960e11c2807b 100644 --- a/tools/cpu_utilization.py +++ b/tools/cpu_utilization.py @@ -83,7 +83,6 @@ def main(pid: int, output: str, threads: bool) -> None: out.write(f" {(c[row].system_time - c[row - 1].system_time) * 100 / time_delta:6.2f}% ") else: out.write(" 0.00% 0.00% ") - row += 1 out.write("\n") with open("plot-cpu.gnuplot", "w+") as out: