diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ef6088bd6a..fd3acb83bc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -56,7 +56,6 @@ repos: - id: trailing-whitespace - id: check-merge-conflict - id: check-ast - - id: debug-statements - repo: local hooks: - id: chialispp diff --git a/benchmarks/utils.py b/benchmarks/utils.py index 759c526990..97b1b20660 100644 --- a/benchmarks/utils.py +++ b/benchmarks/utils.py @@ -64,7 +64,7 @@ def get_commit_hash() -> str: sys.exit("Failed to get the commit hash") try: if len(subprocess.run(["git", "status", "-s"], check=True, stdout=subprocess.PIPE).stdout) > 0: - raise Exception() + raise Exception except Exception: commit_hash += "-dirty" return commit_hash diff --git a/chia/_tests/clvm/test_spend_sim.py b/chia/_tests/clvm/test_spend_sim.py index 66a1f3e702..7dab6eb66e 100644 --- a/chia/_tests/clvm/test_spend_sim.py +++ b/chia/_tests/clvm/test_spend_sim.py @@ -14,7 +14,7 @@ from chia.wallet.util.compute_additions import compute_additions @pytest.mark.anyio async def test_farming(): async with sim_and_client(pass_prefarm=False) as (sim, _): - for i in range(0, 5): + for i in range(5): await sim.farm_block() assert len(sim.blocks) == 5 @@ -25,7 +25,7 @@ async def test_farming(): @pytest.mark.anyio async def test_rewind(): async with sim_and_client() as (sim, _): - for i in range(0, 5): + for i in range(5): await sim.farm_block() save_height = sim.get_height() @@ -39,11 +39,11 @@ async def test_rewind(): @pytest.mark.anyio async def test_all_endpoints(): async with sim_and_client() as (sim, sim_client): - for i in range(0, 5): + for i in range(5): await sim.farm_block() await sim.farm_block(bytes32.zeros) await sim.farm_block(bytes32([1] * 32)) - for i in range(0, 5): + for i in range(5): await sim.farm_block() # get_coin_records_by_hint diff --git a/chia/_tests/core/data_layer/test_data_rpc.py b/chia/_tests/core/data_layer/test_data_rpc.py index e873c219fe..d476268fd2 100644 --- a/chia/_tests/core/data_layer/test_data_rpc.py +++ b/chia/_tests/core/data_layer/test_data_rpc.py @@ -734,7 +734,7 @@ async def test_get_owned_stores( await wallet_node.server.start_client(PeerInfo(self_hostname, full_node_api.server.get_port()), None) async with wallet_node.wallet_state_manager.new_action_scope(DEFAULT_TX_CONFIG, push=True) as action_scope: ph = await action_scope.get_puzzle_hash(wallet_node.wallet_state_manager) - for i in range(0, num_blocks): + for i in range(num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks) @@ -752,7 +752,7 @@ async def test_get_owned_stores( expected_store_ids.append(launcher_id) await time_out_assert(4, check_mempool_spend_count, True, full_node_api, 3) - for i in range(0, num_blocks): + for i in range(num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await asyncio.sleep(0.5) diff --git a/chia/_tests/core/data_layer/test_data_store.py b/chia/_tests/core/data_layer/test_data_store.py index 46b917b532..8f65ae76c3 100644 --- a/chia/_tests/core/data_layer/test_data_store.py +++ b/chia/_tests/core/data_layer/test_data_store.py @@ -107,7 +107,7 @@ async def test_create_tree_accepts_bytes32(raw_data_store: DataStore) -> None: await raw_data_store.create_tree(store_id=store_id) -@pytest.mark.parametrize(argnames=["length"], argvalues=[[length] for length in [*range(0, 32), *range(33, 48)]]) +@pytest.mark.parametrize(argnames=["length"], argvalues=[[length] for length in [*range(32), *range(33, 48)]]) @pytest.mark.anyio async def test_create_store_fails_for_not_bytes32(raw_data_store: DataStore, length: int) -> None: bad_store_id = b"\0" * length @@ -1361,7 +1361,7 @@ async def test_server_http_ban( log: logging.Logger, ) -> None: if error: - raise aiohttp.ClientConnectionError() + raise aiohttp.ClientConnectionError start_timestamp = int(time.time()) with monkeypatch.context() as m: diff --git a/chia/_tests/core/full_node/stores/test_hint_store.py b/chia/_tests/core/full_node/stores/test_hint_store.py index d732b2be00..d9ed165114 100644 --- a/chia/_tests/core/full_node/stores/test_hint_store.py +++ b/chia/_tests/core/full_node/stores/test_hint_store.py @@ -91,7 +91,7 @@ async def test_duplicates(db_version: int) -> None: hint_0 = 32 * b"\0" coin_id_0 = bytes32(32 * b"\4") - for i in range(0, 2): + for i in range(2): hints = [(coin_id_0, hint_0), (coin_id_0, hint_0)] await hint_store.add_hints(hints) coins_for_hint_0 = await hint_store.get_coin_ids(hint_0) diff --git a/chia/_tests/core/full_node/test_block_height_map.py b/chia/_tests/core/full_node/test_block_height_map.py index 1f9c856725..ae20bfa8bf 100644 --- a/chia/_tests/core/full_node/test_block_height_map.py +++ b/chia/_tests/core/full_node/test_block_height_map.py @@ -511,7 +511,7 @@ class TestBlockHeightMap: assert len(new_heights) == 4000 * 32 # pytest doesn't behave very well comparing large buffers # (when the test fails). Compare small portions at a time instead - for idx in range(0, 2000): + for idx in range(2000): assert new_heights[idx * 32 : idx * 32 + 32] == gen_block_hash(idx) diff --git a/chia/_tests/core/full_node/test_full_node.py b/chia/_tests/core/full_node/test_full_node.py index b2309ca8c0..e0930be441 100644 --- a/chia/_tests/core/full_node/test_full_node.py +++ b/chia/_tests/core/full_node/test_full_node.py @@ -683,7 +683,7 @@ async def test_respond_end_of_sub_slot_no_reorg( # First get two blocks in the same sub slot blocks = await full_node_1.get_all_full_blocks() - for i in range(0, 9999999): + for i in range(9999999): blocks = bt.get_consecutive_blocks(5, block_list_input=blocks, skip_slots=1, seed=i.to_bytes(4, "big")) if len(blocks[-1].finished_sub_slots) == 0: break @@ -1468,7 +1468,7 @@ async def test_new_unfinished_block2_forward_limit( unf_blocks: list[UnfinishedBlock] = [] last_reward_hash: Optional[bytes32] = None - for idx in range(0, 6): + for idx in range(6): # we include a different transaction in each block. This makes the # foliage different in each of them, but the reward block (plot) the same tx = wallet_a.generate_signed_transaction(uint64(100 * (idx + 1)), puzzle_hash, coin) @@ -1765,7 +1765,7 @@ async def test_request_unfinished_block2( # deterministically best_unf: Optional[UnfinishedBlock] = None - for idx in range(0, 6): + for idx in range(6): # we include a different transaction in each block. This makes the # foliage different in each of them, but the reward block (plot) the same tx = wallet_a.generate_signed_transaction(uint64(100 * (idx + 1)), puzzle_hash, coin) diff --git a/chia/_tests/core/mempool/test_mempool.py b/chia/_tests/core/mempool/test_mempool.py index 8ff6aabb23..4808c8bc8c 100644 --- a/chia/_tests/core/mempool/test_mempool.py +++ b/chia/_tests/core/mempool/test_mempool.py @@ -1152,7 +1152,7 @@ class TestMempoolManager: assert sb1 is None assert status == MempoolInclusionStatus.FAILED - for i in range(0, 4): + for i in range(4): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(bytes32(32 * b"0"))) tx2: full_node_protocol.RespondTransaction = full_node_protocol.RespondTransaction(spend_bundle1) diff --git a/chia/_tests/core/mempool/test_mempool_fee_estimator.py b/chia/_tests/core/mempool/test_mempool_fee_estimator.py index 0e7e604a8f..7331317037 100644 --- a/chia/_tests/core/mempool/test_mempool_fee_estimator.py +++ b/chia/_tests/core/mempool/test_mempool_fee_estimator.py @@ -74,7 +74,7 @@ async def test_fee_increase() -> None: for i in range(300, 700): i = uint32(i) items = [] - for _ in range(0, 20): + for _ in range(20): fee = uint64(0) included_height = uint32(random.randint(i - 60, i - 1)) cost = uint64(5000000) diff --git a/chia/_tests/core/mempool/test_mempool_manager.py b/chia/_tests/core/mempool/test_mempool_manager.py index 390306c0bb..fddfbe1f96 100644 --- a/chia/_tests/core/mempool/test_mempool_manager.py +++ b/chia/_tests/core/mempool/test_mempool_manager.py @@ -1205,7 +1205,7 @@ async def test_total_mempool_fees() -> None: async def test_create_bundle_from_mempool(reverse_tx_order: bool) -> None: async def make_coin_spends(coins: list[Coin], *, high_fees: bool = True) -> list[CoinSpend]: spends_list = [] - for i in range(0, len(coins)): + for i in range(len(coins)): coin_spend = make_spend( coins[i], IDENTITY_PUZZLE, diff --git a/chia/_tests/core/server/flood.py b/chia/_tests/core/server/flood.py index 1782579f41..4dcfe78969 100644 --- a/chia/_tests/core/server/flood.py +++ b/chia/_tests/core/server/flood.py @@ -69,7 +69,7 @@ async def main() -> None: logger = create_logger(file=file) async def f() -> None: - await asyncio.gather(*[tcp_echo_client(task_counter=f"{i}", logger=logger) for i in range(0, NUM_CLIENTS)]) + await asyncio.gather(*[tcp_echo_client(task_counter=f"{i}", logger=logger) for i in range(NUM_CLIENTS)]) task = create_referenced_task(f()) try: diff --git a/chia/_tests/core/test_cost_calculation.py b/chia/_tests/core/test_cost_calculation.py index a4e34f7c85..7011199d43 100644 --- a/chia/_tests/core/test_cost_calculation.py +++ b/chia/_tests/core/test_cost_calculation.py @@ -275,7 +275,7 @@ async def test_standard_tx(benchmark_runner: BenchmarkRunner) -> None: with benchmark_runner.assert_runtime(seconds=0.1): total_cost = 0 - for i in range(0, 1000): + for i in range(1000): cost, _result = run_with_cost(puzzle_program, test_constants.MAX_BLOCK_COST_CLVM, solution_program) total_cost += cost diff --git a/chia/_tests/core/test_db_validation.py b/chia/_tests/core/test_db_validation.py index 740cc0c5a3..144e2e9924 100644 --- a/chia/_tests/core/test_db_validation.py +++ b/chia/_tests/core/test_db_validation.py @@ -116,7 +116,7 @@ def test_db_validate_in_main_chain(invalid_in_chain: bool, default_config: dict[ make_block_table(conn) prev = bytes32(DEFAULT_CONSTANTS.AGG_SIG_ME_ADDITIONAL_DATA) - for height in range(0, 100): + for height in range(100): header_hash = rand_hash() add_block(conn, header_hash, prev, height, True) if height % 4 == 0: diff --git a/chia/_tests/core/test_farmer_harvester_rpc.py b/chia/_tests/core/test_farmer_harvester_rpc.py index a14384a49a..1adcef7a6c 100644 --- a/chia/_tests/core/test_farmer_harvester_rpc.py +++ b/chia/_tests/core/test_farmer_harvester_rpc.py @@ -397,7 +397,7 @@ async def test_farmer_get_harvester_plots_endpoints( plots = harvester_plots elif endpoint == FarmerRpcClient.get_harvester_plots_invalid: invalid_paths = add_plot_directories("invalid", 3) - for dir_index, r in [(0, range(0, 6)), (1, range(6, 8)), (2, range(8, 13))]: + for dir_index, r in [(0, range(6)), (1, range(6, 8)), (2, range(8, 13))]: plots += [str(invalid_paths[dir_index] / f"{i}.plot") for i in r] for plot in plots: with open(plot, "w"): @@ -412,7 +412,7 @@ async def test_farmer_get_harvester_plots_endpoints( elif endpoint == FarmerRpcClient.get_harvester_plots_duplicates: duplicate_paths = add_plot_directories("duplicates", 2) - for dir_index, r in [(0, range(0, 3)), (1, range(3, 7))]: + for dir_index, r in [(0, range(3)), (1, range(3, 7))]: for i in r: plot_path = Path(harvester_plots[i]["filename"]) plots.append(str(duplicate_paths[dir_index] / plot_path.name)) diff --git a/chia/_tests/core/util/test_keychain.py b/chia/_tests/core/util/test_keychain.py index a024e0e201..c0ba58e998 100644 --- a/chia/_tests/core/util/test_keychain.py +++ b/chia/_tests/core/util/test_keychain.py @@ -355,7 +355,7 @@ async def test_get_key(include_secrets: bool, get_temp_keyring: Keychain): keychain: Keychain = get_temp_keyring expected_keys = [] # Add 10 keys and validate the result `get_key` for each of them after each addition - for _ in range(0, 10): + for _ in range(10): key_data = KeyData.generate() mnemonic_str = key_data.mnemonic_str() if not include_secrets: @@ -385,7 +385,7 @@ async def test_get_keys(include_secrets: bool, get_temp_keyring: Keychain): assert keychain.get_keys(include_secrets) == [] expected_keys = [] # Add 10 keys and validate the result of `get_keys` after each addition - for _ in range(0, 10): + for _ in range(10): key_data = KeyData.generate() mnemonic_str = key_data.mnemonic_str() if not include_secrets: diff --git a/chia/_tests/core/util/test_lockfile.py b/chia/_tests/core/util/test_lockfile.py index fd54a94fc7..fd502ff758 100644 --- a/chia/_tests/core/util/test_lockfile.py +++ b/chia/_tests/core/util/test_lockfile.py @@ -75,7 +75,7 @@ def child_writer_dispatch_with_readiness_check( except LockfileError: attempts -= 1 if attempts == 0: - raise LockfileError() + raise LockfileError except Exception as e: log.warning( f"[pid:{os.getpid()}] caught exception in child_writer_dispatch_with_readiness_check: " diff --git a/chia/_tests/core/util/test_log_exceptions.py b/chia/_tests/core/util/test_log_exceptions.py index bf2bb2a874..2311307bc7 100644 --- a/chia/_tests/core/util/test_log_exceptions.py +++ b/chia/_tests/core/util/test_log_exceptions.py @@ -41,7 +41,7 @@ def test_consumes_exception( caplog: pytest.LogCaptureFixture, ) -> None: with log_exceptions(log=logger, consume=True): - raise Exception() + raise Exception def test_propagates_exception( @@ -67,7 +67,7 @@ def test_passed_message_is_used( caplog: pytest.LogCaptureFixture, ) -> None: with log_exceptions(log=logger, consume=True, message=log_message): - raise Exception() + raise Exception assert len(caplog.records) == 1, caplog.records @@ -87,7 +87,7 @@ def test_specified_level_is_used( ) -> None: caplog.set_level(min(all_levels.values())) with log_exceptions(level=level, log=logger, consume=True): - raise Exception() + raise Exception assert len(caplog.records) == 1, caplog.records @@ -100,7 +100,7 @@ def test_traceback_is_logged( caplog: pytest.LogCaptureFixture, ) -> None: with log_exceptions(log=logger, consume=True, show_traceback=True): - raise Exception() + raise Exception assert len(caplog.records) == 1, caplog.records @@ -113,7 +113,7 @@ def test_traceback_is_not_logged( caplog: pytest.LogCaptureFixture, ) -> None: with log_exceptions(log=logger, consume=True, show_traceback=False): - raise Exception() + raise Exception assert len(caplog.records) == 1, caplog.records diff --git a/chia/_tests/core/util/test_streamable.py b/chia/_tests/core/util/test_streamable.py index 9b401fc7dc..27ea75dd56 100644 --- a/chia/_tests/core/util/test_streamable.py +++ b/chia/_tests/core/util/test_streamable.py @@ -800,7 +800,7 @@ class TestFromBytes: class FailFromBytes: @classmethod def from_bytes(cls, b: bytes) -> FailFromBytes: - raise ValueError() + raise ValueError def test_parse_str() -> None: diff --git a/chia/_tests/db/test_db_wrapper.py b/chia/_tests/db/test_db_wrapper.py index 5597469d27..76d6b4e606 100644 --- a/chia/_tests/db/test_db_wrapper.py +++ b/chia/_tests/db/test_db_wrapper.py @@ -24,8 +24,6 @@ if TYPE_CHECKING: class UniqueError(Exception): """Used to uniquely trigger the exception path out of the context managers.""" - pass - async def increment_counter(db_wrapper: DBWrapper2) -> None: async with db_wrapper.writer_maybe_transaction() as connection: @@ -427,7 +425,7 @@ async def test_cancelled_reader_does_not_cancel_writer() -> None: with pytest.raises(UniqueError): async with db_wrapper.reader() as _: - raise UniqueError() + raise UniqueError assert await query_value(connection=writer) == 1 diff --git a/chia/_tests/farmer_harvester/test_farmer.py b/chia/_tests/farmer_harvester/test_farmer.py index 64b3b9e7ab..fa5a0f125f 100644 --- a/chia/_tests/farmer_harvester/test_farmer.py +++ b/chia/_tests/farmer_harvester/test_farmer.py @@ -13,6 +13,7 @@ from chia_rs import AugSchemeMPL, G1Element, G2Element, PrivateKey, ProofOfSpace from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint8, uint16, uint32, uint64 from pytest_mock import MockerFixture +from typing_extensions import Self from yarl import URL from chia import __version__ @@ -680,7 +681,7 @@ class DummyPoolResponse: return json.dumps(json_dict) - async def __aenter__(self) -> DummyPoolResponse: + async def __aenter__(self) -> Self: return self async def __aexit__( @@ -1004,7 +1005,7 @@ class DummyPoolInfoResponse: return json.dumps(self.pool_info) - async def __aenter__(self) -> DummyPoolInfoResponse: + async def __aenter__(self) -> Self: return self async def __aexit__( 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 6de5d6b5d6..27830d0b79 100644 --- a/chia/_tests/fee_estimation/test_fee_estimation_unit_tests.py +++ b/chia/_tests/fee_estimation/test_fee_estimation_unit_tests.py @@ -80,7 +80,7 @@ def test_steady_fee_pressure() -> None: estimation = estimator.estimate_fee_rate(time_offset_seconds=time_offset_seconds * (height - start_from)) estimates_after.append(estimation) - block_estimates = [estimator.estimate_fee_rate_for_block(uint32(h + 1)) for h in range(0, 50)] + block_estimates = [estimator.estimate_fee_rate_for_block(uint32(h + 1)) for h in range(50)] for idx, es_after in enumerate(estimates_after): assert abs(es_after.mojos_per_clvm_cost - estimates_during[idx].mojos_per_clvm_cost) < 0.001 assert es_after.mojos_per_clvm_cost == block_estimates[idx].mojos_per_clvm_cost diff --git a/chia/_tests/plot_sync/test_plot_sync.py b/chia/_tests/plot_sync/test_plot_sync.py index 746ef13463..9e76d26b7a 100644 --- a/chia/_tests/plot_sync/test_plot_sync.py +++ b/chia/_tests/plot_sync/test_plot_sync.py @@ -537,7 +537,7 @@ async def test_farmer_restart(environment: Environment) -> None: # Load all directories for both harvesters await add_and_validate_all_directories(env) last_sync_ids: list[uint64] = [] - for i in range(0, len(env.harvesters)): + for i in range(len(env.harvesters)): last_sync_ids.append(env.harvesters[i].plot_sync_sender._last_sync_id) # Stop the farmer and make sure both receivers get dropped and refreshing gets stopped on the harvesters await env.split_farmer_service_manager.exit() @@ -551,7 +551,7 @@ async def test_farmer_restart(environment: Environment) -> None: assert len(env.farmer.plot_sync_receivers) == 2 # Do not use run_sync_test here, to have a more realistic test scenario just # wait for the harvesters to be synced. The handshake should trigger re-sync. - for i in range(0, len(env.harvesters)): + for i in range(len(env.harvesters)): harvester: Harvester = env.harvesters[i] assert harvester.server is not None receiver = env.farmer.plot_sync_receivers[harvester.server.node_id] diff --git a/chia/_tests/plot_sync/test_receiver.py b/chia/_tests/plot_sync/test_receiver.py index 9f62a53973..489d916af7 100644 --- a/chia/_tests/plot_sync/test_receiver.py +++ b/chia/_tests/plot_sync/test_receiver.py @@ -137,7 +137,7 @@ async def run_sync_step(receiver: Receiver, sync_step: SyncStepData) -> None: assert len(step_data) == 10 # Invoke batches of: 1, 2, 3, 4 items and validate the data against plot store before and after indexes = [0, 1, 3, 6, 10] - for i in range(0, len(indexes) - 1): + for i in range(len(indexes) - 1): plots_processed_before = receiver.current_sync().plots_processed invoke_data = step_data[indexes[i] : indexes[i + 1]] pre_function_validate(receiver, invoke_data, sync_step.state) @@ -166,7 +166,7 @@ def plot_sync_setup(seeded_random: random.Random) -> tuple[Receiver, list[SyncSt receiver = Receiver(harvester_connection, dummy_callback) # type:ignore[arg-type] # Create example plot data - path_list = [str(x) for x in range(0, 40)] + path_list = [str(x) for x in range(40)] plot_info_list = [ Plot( filename=str(x), diff --git a/chia/_tests/plot_sync/test_sync_simulated.py b/chia/_tests/plot_sync/test_sync_simulated.py index 109fb4b05f..1be1b8a515 100644 --- a/chia/_tests/plot_sync/test_sync_simulated.py +++ b/chia/_tests/plot_sync/test_sync_simulated.py @@ -291,7 +291,7 @@ def create_example_plots(count: int, seeded_random: random.Random) -> list[PlotI file_size=uint64(0), time_modified=time.time(), ) - for x in range(0, count) + for x in range(count) ] diff --git a/chia/_tests/tools/test_full_sync.py b/chia/_tests/tools/test_full_sync.py index db2e57b076..3902b38537 100644 --- a/chia/_tests/tools/test_full_sync.py +++ b/chia/_tests/tools/test_full_sync.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python3 - from __future__ import annotations import asyncio diff --git a/chia/_tests/util/benchmark_cost.py b/chia/_tests/util/benchmark_cost.py index cba61982b8..5bb89ed858 100644 --- a/chia/_tests/util/benchmark_cost.py +++ b/chia/_tests/util/benchmark_cost.py @@ -115,7 +115,7 @@ if __name__ == "__main__": seeded_random = random.Random() seeded_random.seed(a=0, version=2) - for i in range(0, 1000): + for i in range(1000): private_key: PrivateKey = master_sk_to_wallet_sk(secret_key, uint32(i)) public_key = private_key.get_g1() solution = wallet_tool.make_solution( @@ -134,7 +134,7 @@ if __name__ == "__main__": # Run Puzzle 1000 times puzzle_start = time.time() clvm_cost = 0 - for i in range(0, 1000): + for i in range(1000): cost_run, _ = puzzles[i].run_with_cost(INFINITE_COST, solutions[i]) clvm_cost += cost_run @@ -152,7 +152,7 @@ if __name__ == "__main__": # Run AggSig 1000 times agg_sig_start = time.time() agg_sig_cost = 0 - for i in range(0, 1000): + for i in range(1000): valid = AugSchemeMPL.verify(public_key, message, signature) assert valid agg_sig_cost += 20 diff --git a/chia/_tests/util/misc.py b/chia/_tests/util/misc.py index 403346ff20..1e58ad8c69 100644 --- a/chia/_tests/util/misc.py +++ b/chia/_tests/util/misc.py @@ -31,6 +31,7 @@ from aiohttp import web from chia_rs import Coin from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint16, uint32, uint64 +from typing_extensions import Self import chia import chia._tests @@ -49,10 +50,10 @@ from chia.wallet.wallet_node import WalletNode class GcMode(enum.Enum): - nothing = enum.auto - precollect = enum.auto - disable = enum.auto - enable = enum.auto + nothing = enum.auto() + precollect = enum.auto() + disable = enum.auto() + enable = enum.auto() @contextlib.contextmanager @@ -613,37 +614,37 @@ T_ComparableEnum = TypeVar("T_ComparableEnum", bound="ComparableEnum") class ComparableEnum(Enum): - def __lt__(self: T_ComparableEnum, other: T_ComparableEnum) -> object: + def __lt__(self, other: Self) -> object: if self.__class__ is not other.__class__: return NotImplemented return self.value.__lt__(other.value) - def __le__(self: T_ComparableEnum, other: T_ComparableEnum) -> object: + def __le__(self, other: Self) -> object: if self.__class__ is not other.__class__: return NotImplemented return self.value.__le__(other.value) - def __eq__(self: T_ComparableEnum, other: object) -> bool: + def __eq__(self, other: object) -> bool: if self.__class__ is not other.__class__: return False - return cast(bool, self.value.__eq__(cast(T_ComparableEnum, other).value)) + return cast(bool, self.value.__eq__(cast(Self, other).value)) - def __ne__(self: T_ComparableEnum, other: object) -> bool: + def __ne__(self, other: object) -> bool: if self.__class__ is not other.__class__: return True - return cast(bool, self.value.__ne__(cast(T_ComparableEnum, other).value)) + return cast(bool, self.value.__ne__(cast(Self, other).value)) - def __gt__(self: T_ComparableEnum, other: T_ComparableEnum) -> object: + def __gt__(self, other: Self) -> object: if self.__class__ is not other.__class__: return NotImplemented return self.value.__gt__(other.value) - def __ge__(self: T_ComparableEnum, other: T_ComparableEnum) -> object: + def __ge__(self, other: Self) -> object: if self.__class__ is not other.__class__: return NotImplemented diff --git a/chia/_tests/util/setup_nodes.py b/chia/_tests/util/setup_nodes.py index b07fd6086d..f4e2fdbb9f 100644 --- a/chia/_tests/util/setup_nodes.py +++ b/chia/_tests/util/setup_nodes.py @@ -250,10 +250,10 @@ async def setup_simulators_and_wallets_inner( async with AsyncExitStack() as async_exit_stack: bt_tools: list[BlockTools] = [ await create_block_tools_async(consensus_constants, keychain=keychain1, config_overrides=config_overrides) - for _ in range(0, simulator_count) + for _ in range(simulator_count) ] if wallet_count > simulator_count: - for _ in range(0, wallet_count - simulator_count): + for _ in range(wallet_count - simulator_count): bt_tools.append( await create_block_tools_async( consensus_constants, keychain=keychain2, config_overrides=config_overrides @@ -273,7 +273,7 @@ async def setup_simulators_and_wallets_inner( disable_capabilities=disable_capabilities, ) ) - for index in range(0, simulator_count) + for index in range(simulator_count) ] wallets: list[WalletService] = [ @@ -289,7 +289,7 @@ async def setup_simulators_and_wallets_inner( initial_num_public_keys=initial_num_public_keys, ) ) - for index in range(0, wallet_count) + for index in range(wallet_count) ] yield bt_tools, simulators, wallets @@ -329,7 +329,7 @@ async def setup_farmer_multi_harvester( start_service=start_services, ) ) - for i in range(0, harvester_count) + for i in range(harvester_count) ] yield harvester_services, farmer_service, block_tools diff --git a/chia/_tests/util/spend_sim.py b/chia/_tests/util/spend_sim.py index 7a856ec1f5..4da9f45802 100644 --- a/chia/_tests/util/spend_sim.py +++ b/chia/_tests/util/spend_sim.py @@ -7,7 +7,7 @@ from collections.abc import AsyncIterator from contextlib import asynccontextmanager from dataclasses import dataclass from pathlib import Path -from typing import Any, Optional, TypeVar +from typing import Any, Optional import anyio from chia_rs import ( @@ -21,6 +21,7 @@ from chia_rs import ( ) from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint32, uint64 +from typing_extensions import Self from chia.consensus.block_rewards import calculate_base_farmer_reward, calculate_pool_reward from chia.consensus.coinbase import create_farmer_coin, create_pool_coin @@ -106,9 +107,6 @@ class SimFullBlock(Streamable): height: uint32 # Note that height is not on a regular FullBlock -_T_SimBlockRecord = TypeVar("_T_SimBlockRecord", bound="SimBlockRecord") - - @streamable @dataclass(frozen=True) class SimBlockRecord(Streamable): @@ -121,7 +119,7 @@ class SimBlockRecord(Streamable): prev_transaction_block_hash: bytes32 @classmethod - def create(cls: type[_T_SimBlockRecord], rci: list[Coin], height: uint32, timestamp: uint64) -> _T_SimBlockRecord: + def create(cls, rci: list[Coin], height: uint32, timestamp: uint64) -> Self: prev_transaction_block_height = uint32(height - 1 if height > 0 else 0) return cls( rci, @@ -143,9 +141,6 @@ class SimStore(Streamable): blocks: list[SimFullBlock] -_T_SpendSim = TypeVar("_T_SpendSim", bound="SpendSim") - - class SpendSim: db_wrapper: DBWrapper2 coin_store: CoinStore @@ -160,8 +155,8 @@ class SpendSim: @classmethod @contextlib.asynccontextmanager async def managed( - cls: type[_T_SpendSim], db_path: Optional[Path] = None, defaults: ConsensusConstants = DEFAULT_CONSTANTS - ) -> AsyncIterator[_T_SpendSim]: + cls, db_path: Optional[Path] = None, defaults: ConsensusConstants = DEFAULT_CONSTANTS + ) -> AsyncIterator[Self]: self = cls() if db_path is None: uri = f"file:db_{random.randint(0, 99999999)}?mode=memory&cache=shared" diff --git a/chia/_tests/util/test_misc.py b/chia/_tests/util/test_misc.py index 04e1c1652b..7978eb1988 100644 --- a/chia/_tests/util/test_misc.py +++ b/chia/_tests/util/test_misc.py @@ -98,7 +98,7 @@ def test_empty_lists() -> None: @pytest.mark.parametrize("collection_type", [list, set]) def test_valid(collection_type: type) -> None: for k in range(1, 10): - test_collection = collection_type([x for x in range(0, k)]) + test_collection = collection_type([x for x in range(k)]) for i in range(1, len(test_collection) + 1): # Test batch_size 1 to 11 (length + 1) checked = 0 for batch in to_batches(test_collection, i): diff --git a/chia/_tests/util/test_paginator.py b/chia/_tests/util/test_paginator.py index 9361436599..9de65e3279 100644 --- a/chia/_tests/util/test_paginator.py +++ b/chia/_tests/util/test_paginator.py @@ -35,8 +35,8 @@ def test_constructor_invalid_inputs(page_size: int, page_size_limit: int, except def test_page_count() -> None: for page_size in range(1, 10): - for i in range(0, 10): - assert Paginator.create(range(0, i), page_size).page_count() == max(1, ceil(i / page_size)) + for i in range(10): + assert Paginator.create(range(i), page_size).page_count() == max(1, ceil(i / page_size)) @pytest.mark.parametrize( @@ -62,10 +62,10 @@ def test_page_count() -> None: ], ) def test_get_page_valid(length: int, page: int, page_size: int, expected_data: list[int]) -> None: - assert Paginator.create(list(range(0, length)), page_size).get_page(page) == expected_data + assert Paginator.create(list(range(length)), page_size).get_page(page) == expected_data @pytest.mark.parametrize("page", [-1000, -10, -1, 5, 10, 1000]) def test_get_page_invalid(page: int) -> None: with pytest.raises(PageOutOfBoundsError): - Paginator.create(range(0, 17), 5).get_page(page) + Paginator.create(range(17), 5).get_page(page) diff --git a/chia/_tests/util/test_priority_mutex.py b/chia/_tests/util/test_priority_mutex.py index c8fab8e5fb..e835a7b6e1 100644 --- a/chia/_tests/util/test_priority_mutex.py +++ b/chia/_tests/util/test_priority_mutex.py @@ -128,7 +128,7 @@ class Request: def __lt__(self, other: Request) -> bool: if self.acquisition_order is None or other.acquisition_order is None: - raise RequestNotCompleteError() + raise RequestNotCompleteError return self.acquisition_order < other.acquisition_order @@ -152,7 +152,7 @@ class Request: def before(self, other: Request) -> bool: if self.release_order is None or other.acquisition_order is None: - raise RequestNotCompleteError() + raise RequestNotCompleteError return self.release_order < other.acquisition_order diff --git a/chia/_tests/util/time_out_assert.py b/chia/_tests/util/time_out_assert.py index e25e877619..3bbdf9c26d 100644 --- a/chia/_tests/util/time_out_assert.py +++ b/chia/_tests/util/time_out_assert.py @@ -11,6 +11,8 @@ from inspect import getframeinfo, stack from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, ClassVar, Protocol, TypeVar, cast, final +from typing_extensions import Self + import chia import chia._tests from chia._tests import ether @@ -37,7 +39,7 @@ class DataTypeProtocol(Protocol): __match_args__: ClassVar[tuple[str, ...]] = () @classmethod - def unmarshal(cls: type[T], marshalled: dict[str, Any]) -> T: ... + def unmarshal(cls, marshalled: dict[str, Any]) -> Self: ... def marshal(self) -> dict[str, Any]: ... diff --git a/chia/_tests/wallet/cat_wallet/test_cat_wallet.py b/chia/_tests/wallet/cat_wallet/test_cat_wallet.py index 2799e3787d..1c27872b34 100644 --- a/chia/_tests/wallet/cat_wallet/test_cat_wallet.py +++ b/chia/_tests/wallet/cat_wallet/test_cat_wallet.py @@ -1715,7 +1715,7 @@ async def test_cat_melt_balance(wallet_environments: WalletTestFramework) -> Non assert isinstance(cat_wallet, CATWallet) # Let's test that continuing to melt this CAT results in the correct balance changes - for _ in range(0, 5): + for _ in range(5): tx_amount -= 1 new_coin = (await cat_wallet.get_cat_spendable_coins())[0].coin new_spend = unsigned_spend_bundle_for_spendable_cats( diff --git a/chia/_tests/wallet/conftest.py b/chia/_tests/wallet/conftest.py index ffa2905838..5694d0a32c 100644 --- a/chia/_tests/wallet/conftest.py +++ b/chia/_tests/wallet/conftest.py @@ -5,7 +5,7 @@ import unittest from collections.abc import AsyncIterator, Awaitable from contextlib import AsyncExitStack from dataclasses import replace -from typing import Any, Callable, Literal, Optional +from typing import Any, Callable, Optional import pytest from chia_rs import ( @@ -64,7 +64,7 @@ async def ignore_block_validation( if "standard_block_tools" in request.keywords: return None - async def validate_block_body(*args: Any, **kwargs: Any) -> Literal[None]: + async def validate_block_body(*args: Any, **kwargs: Any) -> None: return None def create_wrapper(original_create: Any) -> Any: diff --git a/chia/_tests/wallet/db_wallet/test_db_graftroot.py b/chia/_tests/wallet/db_wallet/test_db_graftroot.py index 2d70307554..7d4c6680cd 100644 --- a/chia/_tests/wallet/db_wallet/test_db_graftroot.py +++ b/chia/_tests/wallet/db_wallet/test_db_graftroot.py @@ -38,7 +38,7 @@ NIL_PH = Program.to(None).get_tree_hash() async def test_graftroot(cost_logger: CostLogger) -> None: async with sim_and_client() as (sim, sim_client): # Create the coin we're testing - all_values: list[bytes32] = [bytes32([x] * 32) for x in range(0, 100)] + all_values: list[bytes32] = [bytes32([x] * 32) for x in range(100)] root, proofs = build_merkle_tree(all_values) p2_conditions = Program.to((1, [[51, ACS_PH, 0]])) # An coin to create to make sure this hits the blockchain desired_key_values = ((bytes32.zeros, bytes32([1] * 32)), (bytes32([7] * 32), bytes32([8] * 32))) diff --git a/chia/_tests/wallet/db_wallet/test_dl_offers.py b/chia/_tests/wallet/db_wallet/test_dl_offers.py index 86e79f8ae2..47be4d7a0a 100644 --- a/chia/_tests/wallet/db_wallet/test_dl_offers.py +++ b/chia/_tests/wallet/db_wallet/test_dl_offers.py @@ -61,8 +61,8 @@ async def test_dl_offers(wallet_environments: WalletTestFramework) -> None: await env_maker.change_balances({"dl": {"init": True}}) await env_taker.change_balances({"dl": {"init": True}}) - MAKER_ROWS = [bytes32([i] * 32) for i in range(0, 10)] - TAKER_ROWS = [bytes32([i] * 32) for i in range(0, 10)] + MAKER_ROWS = [bytes32([i] * 32) for i in range(10)] + TAKER_ROWS = [bytes32([i] * 32) for i in range(10)] maker_root, _ = build_merkle_tree(MAKER_ROWS) taker_root, _ = build_merkle_tree(TAKER_ROWS) @@ -364,7 +364,7 @@ async def test_dl_offer_cancellation(wallet_environments: WalletTestFramework) - dl_wallet = await DataLayerWallet.create_new_dl_wallet(env_maker.wallet_state_manager) await env_maker.change_balances({"dl": {"init": True}}) - ROWS = [bytes32([i] * 32) for i in range(0, 10)] + ROWS = [bytes32([i] * 32) for i in range(10)] root, _ = build_merkle_tree(ROWS) async with dl_wallet.wallet_state_manager.new_action_scope( @@ -535,7 +535,7 @@ async def test_multiple_dl_offers(wallet_environments: WalletTestFramework) -> N await env_maker.change_balances({"dl": {"init": True}}) await env_taker.change_balances({"dl": {"init": True}}) - MAKER_ROWS = [bytes32([i] * 32) for i in range(0, 10)] + MAKER_ROWS = [bytes32([i] * 32) for i in range(10)] TAKER_ROWS = [bytes32([i] * 32) for i in range(10, 20)] maker_root, _ = build_merkle_tree(MAKER_ROWS) taker_root, _ = build_merkle_tree(TAKER_ROWS) diff --git a/chia/_tests/wallet/did_wallet/test_did.py b/chia/_tests/wallet/did_wallet/test_did.py index dbecb345dc..82a936b493 100644 --- a/chia/_tests/wallet/did_wallet/test_did.py +++ b/chia/_tests/wallet/did_wallet/test_did.py @@ -1495,7 +1495,7 @@ async def test_did_auto_transfer_limit( await full_node_api.farm_blocks_to_wallet(1, wallet) # Check that we cap out at 10 DID Wallets automatically created upon transfer received - for i in range(0, 14): + for i in range(14): async with wallet.wallet_state_manager.new_action_scope(DEFAULT_TX_CONFIG, push=True) as action_scope: did_wallet_1: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node.wallet_state_manager, @@ -2389,7 +2389,7 @@ async def test_did_coin_records(wallet_environments: WalletTestFramework, use_al ] ) - for _ in range(0, 2): + for _ in range(2): async with did_wallet.wallet_state_manager.new_action_scope( wallet_environments.tx_config, push=True ) as action_scope: diff --git a/chia/_tests/wallet/rpc/test_dl_wallet_rpc.py b/chia/_tests/wallet/rpc/test_dl_wallet_rpc.py index 449d388849..71041ef56e 100644 --- a/chia/_tests/wallet/rpc/test_dl_wallet_rpc.py +++ b/chia/_tests/wallet/rpc/test_dl_wallet_rpc.py @@ -51,7 +51,7 @@ class TestWalletRpc: await server_2.start_client(PeerInfo(self_hostname, full_node_server.get_port()), None) await server_3.start_client(PeerInfo(self_hostname, full_node_server.get_port()), None) - for i in range(0, num_blocks): + for i in range(num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) initial_funds = sum( @@ -87,7 +87,7 @@ class TestWalletRpc: merkle_root: bytes32 = bytes32.zeros txs, launcher_id = await client.create_new_dl(merkle_root, uint64(50)) - for i in range(0, 5): + for i in range(5): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros)) await asyncio.sleep(0.5) @@ -105,7 +105,7 @@ class TestWalletRpc: new_root: bytes32 = bytes32([1] * 32) await client.dl_update_root(launcher_id, new_root, uint64(100)) - for i in range(0, 5): + for i in range(5): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros)) await asyncio.sleep(0.5) @@ -169,7 +169,7 @@ class TestWalletRpc: txs, launcher_id_2 = await client.create_new_dl(merkle_root, uint64(50)) txs, launcher_id_3 = await client.create_new_dl(merkle_root, uint64(50)) - for i in range(0, 5): + for i in range(5): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros)) await asyncio.sleep(0.5) @@ -186,7 +186,7 @@ class TestWalletRpc: uint64(0), ) - for i in range(0, 5): + for i in range(5): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros)) await asyncio.sleep(0.5) @@ -210,7 +210,7 @@ class TestWalletRpc: await full_node_api.wait_transaction_records_entered_mempool(txs) height = full_node_api.full_node.blockchain.get_peak_height() assert height is not None - for i in range(0, 5): + for i in range(5): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros)) await asyncio.sleep(0.5) additions = [] @@ -228,7 +228,7 @@ class TestWalletRpc: ) await time_out_assert(15, client.dl_get_mirrors, [mirror], launcher_id) await client.dl_delete_mirror(mirror_coin.name(), fee=uint64(2000000000000)) - for i in range(0, 5): + for i in range(5): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros)) await asyncio.sleep(0.5) await time_out_assert(15, client.dl_get_mirrors, [], launcher_id) diff --git a/chia/_tests/wallet/sync/test_wallet_sync.py b/chia/_tests/wallet/sync/test_wallet_sync.py index 6c13274ded..69d86f811a 100644 --- a/chia/_tests/wallet/sync/test_wallet_sync.py +++ b/chia/_tests/wallet/sync/test_wallet_sync.py @@ -1437,7 +1437,7 @@ async def test_retry_store( ) -> list[CoinState]: if flakiness_info.coin_state_flaky: flakiness_info.coin_state_flaky = False - raise PeerRequestException() + raise PeerRequestException else: return await func(coin_names, peer, fork_height) @@ -1470,7 +1470,7 @@ async def test_retry_store( ) -> list[CoinState]: if flakiness_info.fetch_children_flaky: flakiness_info.fetch_children_flaky = False - raise PeerRequestException() + raise PeerRequestException else: return await func(coin_name, peer, fork_height) @@ -1482,7 +1482,7 @@ async def test_retry_store( async def new_func(height: uint32) -> uint64: if flakiness_info.get_timestamp_flaky: flakiness_info.get_timestamp_flaky = False - raise PeerRequestException() + raise PeerRequestException else: return await func(height) @@ -1494,7 +1494,7 @@ async def test_retry_store( async def new_func(puzzle_hash: bytes32) -> Optional[WalletIdentifier]: if flakiness_info.db_flaky: flakiness_info.db_flaky = False - raise AIOSqliteError() + raise AIOSqliteError else: return await func(puzzle_hash) diff --git a/chia/_tests/wallet/test_coin_selection.py b/chia/_tests/wallet/test_coin_selection.py index 2c2f932723..fb23b6bf68 100644 --- a/chia/_tests/wallet/test_coin_selection.py +++ b/chia/_tests/wallet/test_coin_selection.py @@ -101,7 +101,7 @@ class TestCoinSelection: async def test_coin_selection_zero_coins(self, a_hash: bytes32) -> None: coin_list: list[WalletCoinRecord] = [ WalletCoinRecord(Coin(a_hash, a_hash, uint64(0)), uint32(1), uint32(1), False, True, WalletType(0), 1) - for _ in range(0, 100) + for _ in range(100) ] result: set[Coin] = await select_coins( diff --git a/chia/_tests/wallet/test_notifications.py b/chia/_tests/wallet/test_notifications.py index 5aa406e84a..f5877c5dbf 100644 --- a/chia/_tests/wallet/test_notifications.py +++ b/chia/_tests/wallet/test_notifications.py @@ -85,7 +85,7 @@ async def test_notifications( await server_0.start_client(PeerInfo(self_hostname, full_node_server.get_port()), None) await server_1.start_client(PeerInfo(self_hostname, full_node_server.get_port()), None) - for i in range(0, 2): + for i in range(2): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph_1)) await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph_token)) await full_node_api.wait_for_wallets_synced(wallet_nodes=[wallet_node_1, wallet_node_2], timeout=30) diff --git a/chia/_tests/wallet/test_util.py b/chia/_tests/wallet/test_util.py index 0bb9157b2d..5638e0b5d6 100644 --- a/chia/_tests/wallet/test_util.py +++ b/chia/_tests/wallet/test_util.py @@ -44,11 +44,11 @@ def test_compute_spend_hints_and_additions() -> None: with pytest.raises(ValidationError): compute_spend_hints_and_additions( - make_spend(parent_coin.coin, Program.to(1), Program.to([[51, bytes32.zeros, 0] for _ in range(0, 10000)])) + make_spend(parent_coin.coin, Program.to(1), Program.to([[51, bytes32.zeros, 0] for _ in range(10000)])) ) with pytest.raises(ValidationError): compute_spend_hints_and_additions( - make_spend(parent_coin.coin, Program.to(1), Program.to([[50, bytes48.zeros, b""] for _ in range(0, 10000)])) + make_spend(parent_coin.coin, Program.to(1), Program.to([[50, bytes48.zeros, b""] for _ in range(10000)])) ) diff --git a/chia/_tests/wallet/test_wallet.py b/chia/_tests/wallet/test_wallet.py index 5b484ce08a..f0feb93deb 100644 --- a/chia/_tests/wallet/test_wallet.py +++ b/chia/_tests/wallet/test_wallet.py @@ -191,7 +191,7 @@ class TestWalletSimulator: normal_puzhash = await action_scope.get_puzzle_hash(wallet_1.wallet_state_manager) # Transfer to normal wallet - for _ in range(0, number_of_coins): + for _ in range(number_of_coins): async with wallet.wallet_state_manager.new_action_scope(DEFAULT_TX_CONFIG, push=True) as action_scope: await wallet.generate_signed_transaction( [uint64(tx_amount)], diff --git a/chia/_tests/wallet/test_wallet_state_manager.py b/chia/_tests/wallet/test_wallet_state_manager.py index fddf035b18..5dae765a3f 100644 --- a/chia/_tests/wallet/test_wallet_state_manager.py +++ b/chia/_tests/wallet/test_wallet_state_manager.py @@ -398,7 +398,7 @@ async def test_puzzle_hash_requests(wallet_environments: WalletTestFramework) -> # Test transactionality previous_result = None - for _ in range(0, wsm.initial_num_public_keys): # all currently unused + for _ in range(wsm.initial_num_public_keys): # all currently unused previous_result = await wsm._get_unused_derivation_record(wsm.main_wallet.id(), previous_result=previous_result) assert previous_result is not None await previous_result.commit(wsm) diff --git a/chia/_tests/wallet/vc_wallet/test_vc_lifecycle.py b/chia/_tests/wallet/vc_wallet/test_vc_lifecycle.py index 3b1c00f85e..5b94818cba 100644 --- a/chia/_tests/wallet/vc_wallet/test_vc_lifecycle.py +++ b/chia/_tests/wallet/vc_wallet/test_vc_lifecycle.py @@ -399,7 +399,7 @@ async def test_revocation_layer(cost_logger: CostLogger) -> None: @pytest.mark.parametrize("num_proofs", range(1, 6)) async def test_proofs_checker(cost_logger: CostLogger, num_proofs: int) -> None: async with sim_and_client() as (sim, client): - flags: list[str] = [str(i) for i in range(0, num_proofs)] + flags: list[str] = [str(i) for i in range(num_proofs)] proofs_checker: ProofsChecker = ProofsChecker(flags) # (mod (PROOFS_CHECKER proofs) (if (a PROOFS_CHECKER (list proofs)) () (x))) diff --git a/chia/_tests/wallet/wallet_block_tools.py b/chia/_tests/wallet/wallet_block_tools.py index 302d1b738d..2985979cfe 100644 --- a/chia/_tests/wallet/wallet_block_tools.py +++ b/chia/_tests/wallet/wallet_block_tools.py @@ -94,7 +94,7 @@ class WalletBlockTools(BlockTools): latest_block = None last_timestamp = uint64((int(time.time()) if genesis_timestamp is None else genesis_timestamp) - 20) - for _ in range(0, num_blocks): + for _ in range(num_blocks): additions = [] removals = [] block_generator: Optional[BlockGenerator] = None diff --git a/chia/cmds/beta.py b/chia/cmds/beta.py index 19c689416b..6b44a5e2a8 100644 --- a/chia/cmds/beta.py +++ b/chia/cmds/beta.py @@ -138,7 +138,7 @@ def prepare_submission_cmd(ctx: click.Context) -> None: user_input = input("Select the version you want to prepare for submission: ") try: if int(user_input) <= 0: - raise IndexError() + raise IndexError prepare_result = available_results[int(user_input) - 1] except IndexError: raise click.ClickException(f"Invalid choice: {user_input}") diff --git a/chia/cmds/chia.py b/chia/cmds/chia.py index e30c30ed6c..f4cfe6a1d1 100644 --- a/chia/cmds/chia.py +++ b/chia/cmds/chia.py @@ -81,7 +81,7 @@ def cli( if Keychain.master_passphrase_is_valid(passphrase): cache_passphrase(passphrase) else: - raise KeychainCurrentPassphraseIsInvalid() + raise KeychainCurrentPassphraseIsInvalid except KeychainCurrentPassphraseIsInvalid: if Path(passphrase_file.name).is_file(): print(f'Invalid passphrase found in "{passphrase_file.name}"') diff --git a/chia/cmds/cmd_classes.py b/chia/cmds/cmd_classes.py index 1352f41693..4f9dc5ed5e 100644 --- a/chia/cmds/cmd_classes.py +++ b/chia/cmds/cmd_classes.py @@ -45,11 +45,11 @@ ChiaCommand = Union[SyncChiaCommand, AsyncChiaCommand] def option(*param_decls: str, **kwargs: Any) -> Any: - if sys.version_info < (3, 10): # versions < 3.10 don't know about kw_only and they complain about lacks of defaults + if sys.version_info >= (3, 10): + default_default = MISSING + else: # versions < 3.10 don't know about kw_only and they complain about lacks of defaults # Can't get coverage on this because we only test on one version default_default = None # pragma: no cover - else: - default_default = MISSING return field( metadata=dict( @@ -270,16 +270,16 @@ def chia_command( def _chia_command(cls: type[ChiaCommand]) -> type[ChiaCommand]: # The type ignores here are largely due to the fact that the class information is not preserved after being # passed through the dataclass wrapper. Not sure what to do about this right now. - if sys.version_info < (3, 10): # pragma: no cover - # stuff below 3.10 doesn't know about kw_only - wrapped_cls: type[ChiaCommand] = dataclass( - frozen=True, - )(cls) - else: + if sys.version_info >= (3, 10): wrapped_cls: type[ChiaCommand] = dataclass( frozen=True, kw_only=True, )(cls) + else: # pragma: no cover + # stuff below 3.10 doesn't know about kw_only + wrapped_cls: type[ChiaCommand] = dataclass( + frozen=True, + )(cls) metadata = Metadata( command=click.command( @@ -316,9 +316,9 @@ def get_chia_command_metadata(cls: type[ChiaCommand]) -> Metadata: @dataclass_transform(frozen_default=True) def command_helper(cls: type[Any]) -> type[Any]: - if sys.version_info < (3, 10): # stuff below 3.10 doesn't support kw_only - new_cls = dataclass(frozen=True)(cls) # pragma: no cover - else: + if sys.version_info >= (3, 10): new_cls = dataclass(frozen=True, kw_only=True)(cls) + else: # stuff below 3.10 doesn't support kw_only + new_cls = dataclass(frozen=True)(cls) # pragma: no cover setattr(new_cls, COMMAND_HELPER_ATTRIBUTE_NAME, True) return new_cls diff --git a/chia/cmds/cmds_util.py b/chia/cmds/cmds_util.py index 035c47fcc9..d8ebe2ec63 100644 --- a/chia/cmds/cmds_util.py +++ b/chia/cmds/cmds_util.py @@ -267,7 +267,7 @@ def cli_confirm(input_message: str, abort_message: str = "Did not confirm. Abort response = input(input_message).lower() if response not in {"y", "yes"}: print(abort_message) - raise click.Abort() + raise click.Abort def coin_selection_args(func: Callable[..., None]) -> Callable[..., None]: diff --git a/chia/cmds/coin_funcs.py b/chia/cmds/coin_funcs.py index bf45551a32..7712680265 100644 --- a/chia/cmds/coin_funcs.py +++ b/chia/cmds/coin_funcs.py @@ -92,7 +92,7 @@ def print_coins( return num_per_screen = 5 if paginate else len(coins) for i in range(0, len(coins), num_per_screen): - for j in range(0, num_per_screen): + for j in range(num_per_screen): if i + j >= len(coins): break coin, conf_height = coins[i + j] diff --git a/chia/cmds/data.py b/chia/cmds/data.py index da67c90e76..f3c759c245 100644 --- a/chia/cmds/data.py +++ b/chia/cmds/data.py @@ -13,8 +13,6 @@ from chia_rs.sized_ints import uint64 from chia.cmds import options from chia.cmds.param_types import Bytes32ParamType -_T = TypeVar("_T") - FC = TypeVar("FC", bound=Union[Callable[..., Any], click.Command]) logger = logging.getLogger(__name__) diff --git a/chia/cmds/dev/gh.py b/chia/cmds/dev/gh.py index b42cbc075a..b78d8fc016 100644 --- a/chia/cmds/dev/gh.py +++ b/chia/cmds/dev/gh.py @@ -8,7 +8,7 @@ import uuid import webbrowser from collections.abc import Sequence from pathlib import Path -from typing import Callable, ClassVar, Literal, Optional, Union, overload +from typing import Callable, ClassVar, Literal, Optional, overload import anyio import click @@ -21,9 +21,9 @@ class UnexpectedFormError(Exception): pass -Oses = Union[Literal["linux"], Literal["macos-arm"], Literal["macos-intel"], Literal["windows"]] -Method = Union[Literal["GET"], Literal["POST"]] -Per = Union[Literal["directory"], Literal["file"]] +Oses = Literal["linux", "macos-arm", "macos-intel", "windows"] +Method = Literal["GET", "POST"] +Per = Literal["directory", "file"] all_oses: Sequence[Oses] = ("linux", "macos-arm", "macos-intel", "windows") diff --git a/chia/cmds/keys.py b/chia/cmds/keys.py index 6d2a6ce5b7..530433d3f6 100644 --- a/chia/cmds/keys.py +++ b/chia/cmds/keys.py @@ -379,11 +379,11 @@ def _resolve_fingerprint_and_sk( if non_observer_derivation and resolved_sk is None: print("Could not resolve private key for non-observer derivation") - raise ResolutionError() + raise ResolutionError if reolved_fp is None: print("A fingerprint of a root key to derive from is required") - raise ResolutionError() + raise ResolutionError return reolved_fp, resolved_sk diff --git a/chia/cmds/rpc.py b/chia/cmds/rpc.py index 0a73c657c3..d04cdb41e3 100644 --- a/chia/cmds/rpc.py +++ b/chia/cmds/rpc.py @@ -131,7 +131,7 @@ def status_cmd(ctx: click.Context, json_output: bool) -> None: status = "ACTIVE" try: if not get_routes(service, config, root_path=root_path, quiet=True)["success"]: - raise Exception() + raise Exception except Exception: status = "INACTIVE" status_data[service] = status diff --git a/chia/cmds/sim_funcs.py b/chia/cmds/sim_funcs.py index b0d2a3c1fc..eda4efbb9f 100644 --- a/chia/cmds/sim_funcs.py +++ b/chia/cmds/sim_funcs.py @@ -363,7 +363,7 @@ async def print_coin_records( num_per_screen = 5 if paginate else len(coin_records) # ripped from cmds/wallet_funcs. for i in range(0, len(coin_records), num_per_screen): - for j in range(0, num_per_screen): + for j in range(num_per_screen): if i + j >= len(coin_records): break print_coin_record( diff --git a/chia/cmds/wallet_funcs.py b/chia/cmds/wallet_funcs.py index fce2953c3f..0e3d039623 100644 --- a/chia/cmds/wallet_funcs.py +++ b/chia/cmds/wallet_funcs.py @@ -234,7 +234,7 @@ async def get_transactions( skipped = 0 num_per_screen = 5 if paginate else len(txs) for i in range(0, len(txs), num_per_screen): - for j in range(0, num_per_screen): + for j in range(num_per_screen): if i + j + skipped >= len(txs): break coin_record: Optional[dict[str, Any]] = None diff --git a/chia/consensus/pot_iterations.py b/chia/consensus/pot_iterations.py index 96b50a1b66..d7dd3258a0 100644 --- a/chia/consensus/pot_iterations.py +++ b/chia/consensus/pot_iterations.py @@ -125,4 +125,4 @@ def calculate_iterations_quality( ) return max(iters, uint64(1)) else: - raise NotImplementedError() + raise NotImplementedError diff --git a/chia/daemon/keychain_proxy.py b/chia/daemon/keychain_proxy.py index 8e35b602d9..2f89dc0d57 100644 --- a/chia/daemon/keychain_proxy.py +++ b/chia/daemon/keychain_proxy.py @@ -97,7 +97,7 @@ class KeychainProxy(DaemonProxy): self.log.debug(f"Sending request to keychain command: {request['command']} from {request['origin']}.") return await super()._get(request) except asyncio.TimeoutError: - raise KeychainProxyConnectionTimeout() + raise KeychainProxyConnectionTimeout async def start(self, wait_for_start: bool = False) -> None: self.keychain_connection_task = create_referenced_task(self.connect_to_keychain()) @@ -156,11 +156,11 @@ class KeychainProxy(DaemonProxy): if error: error_details = response["data"].get("error_details", {}) if error == KEYCHAIN_ERR_LOCKED: - raise KeychainIsLocked() + raise KeychainIsLocked elif error == KEYCHAIN_ERR_NO_KEYS: - raise KeychainIsEmpty() + raise KeychainIsEmpty elif error == KEYCHAIN_ERR_KEY_NOT_FOUND: - raise KeychainKeyNotFound() + raise KeychainKeyNotFound elif error == KEYCHAIN_ERR_MALFORMED_REQUEST: message = error_details.get("message", "") raise KeychainMalformedRequest(message) @@ -356,7 +356,7 @@ class KeychainProxy(DaemonProxy): if self.use_local_keychain(): keys = self.keychain.get_keys(include_secrets=private) if len(keys) == 0: - raise KeychainIsEmpty() + raise KeychainIsEmpty else: selected_key = keys[0] if fingerprint is not None: diff --git a/chia/data_layer/data_layer_util.py b/chia/data_layer/data_layer_util.py index 3f3a520371..c20e08ff01 100644 --- a/chia/data_layer/data_layer_util.py +++ b/chia/data_layer/data_layer_util.py @@ -392,7 +392,7 @@ class Root: } -node_type_to_class: dict[NodeType, Union[type[InternalNode], type[TerminalNode]]] = { +node_type_to_class: dict[NodeType, type[Union[InternalNode, TerminalNode]]] = { NodeType.INTERNAL: InternalNode, NodeType.TERMINAL: TerminalNode, } diff --git a/chia/data_layer/dl_wallet_store.py b/chia/data_layer/dl_wallet_store.py index 3d7ec155c6..eec2fdfe5b 100644 --- a/chia/data_layer/dl_wallet_store.py +++ b/chia/data_layer/dl_wallet_store.py @@ -1,11 +1,12 @@ from __future__ import annotations import dataclasses -from typing import Optional, TypeVar, Union +from typing import Optional, Union from aiosqlite import Row from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint16, uint32, uint64 +from typing_extensions import Self from chia.data_layer.data_layer_wallet import Mirror from chia.data_layer.singleton_record import SingletonRecord @@ -13,8 +14,6 @@ from chia.types.blockchain_format.coin import Coin from chia.util.db_wrapper import DBWrapper2, execute_fetchone from chia.wallet.lineage_proof import LineageProof -_T_DataLayerStore = TypeVar("_T_DataLayerStore", bound="DataLayerStore") - def _row_to_singleton_record(row: Row) -> SingletonRecord: return SingletonRecord( @@ -49,7 +48,7 @@ class DataLayerStore: db_wrapper: DBWrapper2 @classmethod - async def create(cls: type[_T_DataLayerStore], db_wrapper: DBWrapper2) -> _T_DataLayerStore: + async def create(cls, db_wrapper: DBWrapper2) -> Self: self = cls() self.db_wrapper = db_wrapper diff --git a/chia/data_layer/s3_plugin_service.py b/chia/data_layer/s3_plugin_service.py index 95d0dbe0ab..0e1582dc88 100644 --- a/chia/data_layer/s3_plugin_service.py +++ b/chia/data_layer/s3_plugin_service.py @@ -384,7 +384,6 @@ def read_store_ids_from_config(config: dict[str, Any]) -> list[StoreConfig]: else: bad_store_id = "" log.info(f"Ignoring invalid store id: {bad_store_id}: {type(e).__name__} {e}") - pass return stores diff --git a/chia/farmer/farmer.py b/chia/farmer/farmer.py index e78e85ed8d..5c15be8a4f 100644 --- a/chia/farmer/farmer.py +++ b/chia/farmer/farmer.py @@ -226,7 +226,7 @@ class Farmer: else: self.keychain_proxy = await connect_to_keychain_and_validate(self._root_path, self.log) if not self.keychain_proxy: - raise KeychainProxyConnectionFailure() + raise KeychainProxyConnectionFailure return self.keychain_proxy async def get_all_private_keys(self) -> list[tuple[PrivateKey, bytes]]: diff --git a/chia/full_node/block_height_map.py b/chia/full_node/block_height_map.py index 4ea7a76e65..8a3bf38c4f 100644 --- a/chia/full_node/block_height_map.py +++ b/chia/full_node/block_height_map.py @@ -94,7 +94,6 @@ class BlockHeightMap: except Exception as e: # it's OK if this file doesn't exist, we can rebuild it log.info(f"Failed to load height-to-hash: {e}") - pass try: async with aiofiles.open(self.__ses_filename, "rb") as f: @@ -102,7 +101,6 @@ class BlockHeightMap: except Exception as e: # it's OK if this file doesn't exist, we can rebuild it log.info(f"Failed to load sub-epoch-summaries: {e}") - pass peak: bytes32 = row[0] prev_hash: bytes32 = row[1] diff --git a/chia/full_node/fee_estimator_interface.py b/chia/full_node/fee_estimator_interface.py index f429627938..9906d7abf2 100644 --- a/chia/full_node/fee_estimator_interface.py +++ b/chia/full_node/fee_estimator_interface.py @@ -11,32 +11,24 @@ from chia.types.fee_rate import FeeRateV2 class FeeEstimatorInterface(Protocol): def new_block_height(self, block_height: uint32) -> None: """Called immediately when block height changes. Can be called multiple times before `new_block`""" - pass def new_block(self, block_info: FeeBlockInfo) -> None: """A new transaction block has been added to the blockchain""" - pass def add_mempool_item(self, mempool_item_info: FeeMempoolInfo, mempool_item: MempoolItemInfo) -> None: """A MempoolItem (transaction and associated info) has been added to the mempool""" - pass def remove_mempool_item(self, mempool_info: FeeMempoolInfo, mempool_item: MempoolItemInfo) -> None: """A MempoolItem (transaction and associated info) has been removed from the mempool""" - pass def estimate_fee_rate(self, *, time_offset_seconds: int) -> FeeRateV2: """time_offset_seconds: number of seconds into the future for which to estimate fee""" - pass def mempool_size(self) -> CLVMCost: """Report last seen mempool size""" - pass def mempool_max_size(self) -> CLVMCost: """Report current mempool max "size" (i.e. CLVM cost)""" - pass def get_mempool_info(self) -> FeeMempoolInfo: """Report Mempool current configuration and state""" - pass diff --git a/chia/full_node/fee_tracker.py b/chia/full_node/fee_tracker.py index 661879606a..ad6b065870 100644 --- a/chia/full_node/fee_tracker.py +++ b/chia/full_node/fee_tracker.py @@ -107,8 +107,8 @@ class FeeStat: # TxConfirmStats my_type: str, ): self.buckets = buckets - self.confirmed_average = [[] for _ in range(0, max_periods)] - self.failed_average = [[] for _ in range(0, max_periods)] + self.confirmed_average = [[] for _ in range(max_periods)] + self.failed_average = [[] for _ in range(max_periods)] self.decay = decay self.scale = scale self.max_confirms = self.scale * len(self.confirmed_average) @@ -117,18 +117,18 @@ class FeeStat: # TxConfirmStats self.type = my_type self.max_periods = max_periods - for i in range(0, max_periods): - self.confirmed_average[i] = [0 for _ in range(0, len(buckets))] - self.failed_average[i] = [0 for _ in range(0, len(buckets))] + for i in range(max_periods): + self.confirmed_average[i] = [0 for _ in range(len(buckets))] + self.failed_average[i] = [0 for _ in range(len(buckets))] - self.tx_ct_avg = [0 for _ in range(0, len(buckets))] - self.m_fee_rate_avg = [0 for _ in range(0, len(buckets))] + self.tx_ct_avg = [0 for _ in range(len(buckets))] + self.m_fee_rate_avg = [0 for _ in range(len(buckets))] - self.unconfirmed_txs = [[] for _ in range(0, self.max_confirms)] - for i in range(0, self.max_confirms): - self.unconfirmed_txs[i] = [0 for _ in range(0, len(buckets))] + self.unconfirmed_txs = [[] for _ in range(self.max_confirms)] + for i in range(self.max_confirms): + self.unconfirmed_txs[i] = [0 for _ in range(len(buckets))] - self.old_unconfirmed_txs = [0 for _ in range(0, len(buckets))] + self.old_unconfirmed_txs = [0 for _ in range(len(buckets))] def tx_confirmed(self, blocks_to_confirm: int, item: MempoolItemInfo) -> None: if blocks_to_confirm < 1: @@ -147,8 +147,8 @@ class FeeStat: # TxConfirmStats self.m_fee_rate_avg[bucket_index] += fee_rate def update_moving_averages(self) -> None: - for j in range(0, len(self.buckets)): - for i in range(0, len(self.confirmed_average)): + for j in range(len(self.buckets)): + for i in range(len(self.confirmed_average)): self.confirmed_average[i][j] *= self.decay self.failed_average[i][j] *= self.decay @@ -156,7 +156,7 @@ class FeeStat: # TxConfirmStats self.m_fee_rate_avg[j] *= self.decay def clear_current(self, block_height: uint32) -> None: - for i in range(0, len(self.buckets)): + for i in range(len(self.buckets)): self.old_unconfirmed_txs[i] += self.unconfirmed_txs[block_height % len(self.unconfirmed_txs)][i] self.unconfirmed_txs[block_height % len(self.unconfirmed_txs)][i] = 0 @@ -186,7 +186,7 @@ class FeeStat: # TxConfirmStats if block_ago >= self.scale: periods_ago = block_ago / self.scale - for i in range(0, len(self.failed_average)): + for i in range(len(self.failed_average)): if i >= periods_ago: break self.failed_average[i][bucket_index] += 1 @@ -196,38 +196,38 @@ class FeeStat: # TxConfirmStats str_confirmed_average: list[list[str]] = [] str_failed_average: list[list[str]] = [] str_m_fee_rate_avg: list[str] = [] - for i in range(0, self.max_periods): + for i in range(self.max_periods): str_i_list_conf = [] - for j in range(0, len(self.confirmed_average[i])): + for j in range(len(self.confirmed_average[i])): str_i_list_conf.append(float.hex(float(self.confirmed_average[i][j]))) str_confirmed_average.append(str_i_list_conf) str_i_list_fail = [] - for j in range(0, len(self.failed_average[i])): + for j in range(len(self.failed_average[i])): str_i_list_fail.append(float.hex(float(self.failed_average[i][j]))) str_failed_average.append(str_i_list_fail) - for i in range(0, len(self.tx_ct_avg)): + for i in range(len(self.tx_ct_avg)): str_tx_ct_abg.append(float.hex(float(self.tx_ct_avg[i]))) - for i in range(0, len(self.m_fee_rate_avg)): + for i in range(len(self.m_fee_rate_avg)): str_m_fee_rate_avg.append(float.hex(float(self.m_fee_rate_avg[i]))) return FeeStatBackup(self.type, str_tx_ct_abg, str_confirmed_average, str_failed_average, str_m_fee_rate_avg) def import_backup(self, backup: FeeStatBackup) -> None: - for i in range(0, self.max_periods): - for j in range(0, len(self.confirmed_average[i])): + for i in range(self.max_periods): + for j in range(len(self.confirmed_average[i])): self.confirmed_average[i][j] = float.fromhex(backup.confirmed_average[i][j]) - for j in range(0, len(self.failed_average[i])): + for j in range(len(self.failed_average[i])): self.failed_average[i][j] = float.fromhex(backup.failed_average[i][j]) - for i in range(0, len(self.tx_ct_avg)): + for i in range(len(self.tx_ct_avg)): self.tx_ct_avg[i] = float.fromhex(backup.tx_ct_avg[i]) - for i in range(0, len(self.m_fee_rate_avg)): + for i in range(len(self.m_fee_rate_avg)): self.m_fee_rate_avg[i] = float.fromhex(backup.m_fee_rate_avg[i]) # See TxConfirmStats::EstimateMedianVal in https://github.com/bitcoin/bitcoin/blob/master/src/policy/fees.cpp diff --git a/chia/full_node/full_node.py b/chia/full_node/full_node.py index 811590dcfe..8bb20044c7 100644 --- a/chia/full_node/full_node.py +++ b/chia/full_node/full_node.py @@ -2154,7 +2154,7 @@ class FullNode: added = AddBlockResult.DISCONNECTED_BLOCK error_code: Optional[Err] = Err.INVALID_PREV_BLOCK_HASH elif Err(pre_validation_result.error) == Err.TIMESTAMP_TOO_FAR_IN_FUTURE: - raise TimestampError() + raise TimestampError else: raise ValueError( f"Failed to validate block {header_hash} height " @@ -2369,7 +2369,7 @@ class FullNode: _, header_error = await self.blockchain.validate_unfinished_block_header(block) if header_error is not None: if header_error == Err.TIMESTAMP_TOO_FAR_IN_FUTURE: - raise TimestampError() + raise TimestampError else: raise ConsensusError(header_error) validate_time = time.monotonic() - start_header_time diff --git a/chia/full_node/full_node_api.py b/chia/full_node/full_node_api.py index ed8870d3ea..b6fc76259d 100644 --- a/chia/full_node/full_node_api.py +++ b/chia/full_node/full_node_api.py @@ -301,7 +301,7 @@ class FullNodeAPI: if len(tips) > 4: # Remove old from cache - for i in range(0, 4): + for i in range(4): self.full_node.pow_creation.pop(tips[i]) if wp is None: diff --git a/chia/full_node/full_node_store.py b/chia/full_node/full_node_store.py index 765e527190..b2c4d82b22 100644 --- a/chia/full_node/full_node_store.py +++ b/chia/full_node/full_node_store.py @@ -882,7 +882,7 @@ class FullNodeStore: if cc_hash == challenge_hash: found_rc_hash = False - for i in range(0, index): + for i in range(index): sp: Optional[SignagePoint] = sps[i] if sp is not None and sp.rc_vdf is not None and sp.rc_vdf.challenge == last_rc_infusion: found_rc_hash = True diff --git a/chia/full_node/weight_proof.py b/chia/full_node/weight_proof.py index e8829e7440..e397ec4ba0 100644 --- a/chia/full_node/weight_proof.py +++ b/chia/full_node/weight_proof.py @@ -1149,7 +1149,7 @@ def sub_slot_data_vdf_input( if is_overflow and new_sub_slot: if sub_slot_idx >= 2: if sub_slots[sub_slot_idx - 2].cc_slot_end_info is None: - for ssd_idx in reversed(range(0, sub_slot_idx - 1)): + for ssd_idx in reversed(range(sub_slot_idx - 1)): ssd = sub_slots[ssd_idx] if ssd.cc_slot_end_info is not None: ssd = sub_slots[ssd_idx + 1] @@ -1164,7 +1164,7 @@ def sub_slot_data_vdf_input( return cc_input elif not is_overflow and not new_sub_slot: - for ssd_idx in reversed(range(0, sub_slot_idx)): + for ssd_idx in reversed(range(sub_slot_idx)): ssd = sub_slots[ssd_idx] if ssd.cc_slot_end_info is not None: ssd = sub_slots[ssd_idx + 1] @@ -1181,7 +1181,7 @@ def sub_slot_data_vdf_input( elif not new_sub_slot and is_overflow: slots_seen = 0 - for ssd_idx in reversed(range(0, sub_slot_idx)): + for ssd_idx in reversed(range(sub_slot_idx)): ssd = sub_slots[ssd_idx] if ssd.cc_slot_end_info is not None: slots_seen += 1 @@ -1474,7 +1474,7 @@ def __get_rc_sub_slot( def __get_cc_sub_slot(sub_slots: list[SubSlotData], idx: int, ses: Optional[SubEpochSummary]) -> ChallengeChainSubSlot: sub_slot: Optional[SubSlotData] = None - for i in reversed(range(0, idx)): + for i in reversed(range(idx)): sub_slot = sub_slots[i] if sub_slot.cc_slot_end_info is not None: break diff --git a/chia/plot_sync/sender.py b/chia/plot_sync/sender.py index fb80a54247..74be15cae2 100644 --- a/chia/plot_sync/sender.py +++ b/chia/plot_sync/sender.py @@ -125,7 +125,7 @@ class Sender: if not self._plot_manager.initial_refresh() or self._sync_id != 0: self._reset() else: - raise AlreadyStartedError() + raise AlreadyStartedError def stop(self) -> None: self._stop_requested = True diff --git a/chia/rpc/data_layer_rpc_util.py b/chia/rpc/data_layer_rpc_util.py index 014bd2235b..c98ddc6607 100644 --- a/chia/rpc/data_layer_rpc_util.py +++ b/chia/rpc/data_layer_rpc_util.py @@ -1,11 +1,8 @@ from __future__ import annotations -from typing import Any, TypeVar - -from typing_extensions import Protocol - -_T = TypeVar("_T") +from typing import Any +from typing_extensions import Protocol, Self # If accepted for general use then this should be moved to a common location # and probably implemented by the framework instead of manual decoration. @@ -13,7 +10,7 @@ _T = TypeVar("_T") class MarshallableProtocol(Protocol): @classmethod - def unmarshal(cls: type[_T], marshalled: dict[str, Any]) -> _T: ... + def unmarshal(cls, marshalled: dict[str, Any]) -> Self: ... def marshal(self) -> dict[str, Any]: ... diff --git a/chia/rpc/rpc_client.py b/chia/rpc/rpc_client.py index 80ceaad984..55bf3567e8 100644 --- a/chia/rpc/rpc_client.py +++ b/chia/rpc/rpc_client.py @@ -7,11 +7,12 @@ from contextlib import asynccontextmanager from dataclasses import dataclass from pathlib import Path from ssl import SSLContext -from typing import Any, Optional, TypeVar +from typing import Any, Optional import aiohttp from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint16 +from typing_extensions import Self from chia.protocols.outbound_message import NodeType from chia.server.server import ssl_context_for_client @@ -19,8 +20,6 @@ from chia.server.ssl_context import private_ssl_ca_paths from chia.util.byte_types import hexstr_to_bytes from chia.util.task_referencer import create_referenced_task -_T_RpcClient = TypeVar("_T_RpcClient", bound="RpcClient") - # It would be better to not inherit from ValueError. This is being done to separate # the possibility to identify these errors in new code from having to review and @@ -50,12 +49,12 @@ class RpcClient: @classmethod async def create( - cls: type[_T_RpcClient], + cls, self_hostname: str, port: uint16, root_path: Optional[Path], net_config: Optional[dict[str, Any]], - ) -> _T_RpcClient: + ) -> Self: if (root_path is not None) != (net_config is not None): raise ValueError("Either both or neither of root_path and net_config must be provided") @@ -89,12 +88,12 @@ class RpcClient: @classmethod @asynccontextmanager async def create_as_context( - cls: type[_T_RpcClient], + cls, self_hostname: str, port: uint16, root_path: Optional[Path] = None, net_config: Optional[dict[str, Any]] = None, - ) -> AsyncIterator[_T_RpcClient]: + ) -> AsyncIterator[Self]: self = await cls.create( self_hostname=self_hostname, port=port, diff --git a/chia/rpc/rpc_server.py b/chia/rpc/rpc_server.py index fbe9f6d847..400064c45b 100644 --- a/chia/rpc/rpc_server.py +++ b/chia/rpc/rpc_server.py @@ -303,7 +303,7 @@ class RpcServer(Generic[_T_RpcApiProtocol]): async def close_connection(self, request: dict[str, Any]) -> EndpointResult: node_id = hexstr_to_bytes(request["node_id"]) if self.rpc_api.service.server is None: - raise web.HTTPInternalServerError() + raise web.HTTPInternalServerError connections_to_close = [c for c in self.rpc_api.service.server.get_connections() if c.peer_node_id == node_id] if len(connections_to_close) == 0: raise ValueError(f"Connection with node_id {node_id.hex()} does not exist") diff --git a/chia/rpc/wallet_request_types.py b/chia/rpc/wallet_request_types.py index ba1f7262ee..db9b10f038 100644 --- a/chia/rpc/wallet_request_types.py +++ b/chia/rpc/wallet_request_types.py @@ -2,12 +2,12 @@ from __future__ import annotations import sys from dataclasses import dataclass, field -from typing import Any, Optional, TypeVar, final +from typing import Any, Optional, final from chia_rs import G1Element, G2Element, PrivateKey from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint16, uint32, uint64 -from typing_extensions import dataclass_transform +from typing_extensions import Self, dataclass_transform from chia.util.byte_types import hexstr_to_bytes from chia.util.streamable import Streamable, streamable @@ -28,15 +28,13 @@ from chia.wallet.util.tx_config import TXConfig from chia.wallet.vc_wallet.vc_store import VCProofs, VCRecord from chia.wallet.wallet_spend_bundle import WalletSpendBundle -_T_OfferEndpointResponse = TypeVar("_T_OfferEndpointResponse", bound="_OfferEndpointResponse") - @dataclass_transform(frozen_default=True, kw_only_default=True) def kw_only_dataclass(cls: type[Any]) -> type[Any]: - if sys.version_info < (3, 10): - return dataclass(frozen=True)(cls) # pragma: no cover - else: + if sys.version_info >= (3, 10): return dataclass(frozen=True, kw_only=True)(cls) + else: + return dataclass(frozen=True)(cls) # pragma: no cover def default_raise() -> Any: # pragma: no cover @@ -404,13 +402,10 @@ class VCProofsRPC(Streamable): return VCProofs({key: value for key, value in self.key_value_pairs}) @classmethod - def from_vc_proofs(cls: type[_T_VCProofsRPC], vc_proofs: VCProofs) -> _T_VCProofsRPC: + def from_vc_proofs(cls, vc_proofs: VCProofs) -> Self: return cls([(key, value) for key, value in vc_proofs.key_value_pairs.items()]) -_T_VCProofsRPC = TypeVar("_T_VCProofsRPC", bound=VCProofsRPC) - - # utility for VCGetListResponse @streamable @dataclass(frozen=True) @@ -471,13 +466,10 @@ class VCAddProofs(VCProofsRPC): return {"proofs": self.to_vc_proofs().key_value_pairs} @classmethod - def from_json_dict(cls: type[_T_VCAddProofs], json_dict: dict[str, Any]) -> _T_VCAddProofs: + def from_json_dict(cls, json_dict: dict[str, Any]) -> Self: return cls([(key, value) for key, value in json_dict["proofs"].items()]) -_T_VCAddProofs = TypeVar("_T_VCAddProofs", bound=VCAddProofs) - - @streamable @dataclass(frozen=True) class VCGetProofsForRoot(Streamable): @@ -771,7 +763,7 @@ class _OfferEndpointResponse(TransactionEndpointResponse): trade_record: TradeRecord @classmethod - def from_json_dict(cls: type[_T_OfferEndpointResponse], json_dict: dict[str, Any]) -> _T_OfferEndpointResponse: + def from_json_dict(cls, json_dict: dict[str, Any]) -> Self: tx_endpoint: TransactionEndpointResponse = json_deserialize_with_clvm_streamable( json_dict, TransactionEndpointResponse ) diff --git a/chia/seeder/dns_server.py b/chia/seeder/dns_server.py index 7a1faf822c..ab769b6e49 100644 --- a/chia/seeder/dns_server.py +++ b/chia/seeder/dns_server.py @@ -35,6 +35,8 @@ DnsCallback = Callable[[DNSRecord], Awaitable[DNSRecord]] class DomainName(str): + __slots__ = () + def __getattr__(self, item: str) -> DomainName: return DomainName(f"{item}.{self}") # DomainName.NS becomes DomainName("NS.DomainName") diff --git a/chia/server/address_manager.py b/chia/server/address_manager.py index c1a9303659..14ba11a6fd 100644 --- a/chia/server/address_manager.py +++ b/chia/server/address_manager.py @@ -313,7 +313,7 @@ class AddressManager: # deserialize new_table new_table_count = uint32.parse(data) new_table_nodes: list[tuple[uint64, uint64]] = [] - for i in range(0, new_table_count): + for i in range(new_table_count): node_id = uint64.parse(data) bucket = uint64.parse(data) new_table_nodes.append((node_id, bucket)) diff --git a/chia/simulator/block_tools.py b/chia/simulator/block_tools.py index 9abfd61ba2..2df648f3f8 100644 --- a/chia/simulator/block_tools.py +++ b/chia/simulator/block_tools.py @@ -824,7 +824,7 @@ class BlockTools: num_empty_slots_added += 1 else: # Loop over every signage point (Except for the last ones, which are used for overflows) - for signage_point_index in range(0, constants.NUM_SPS_SUB_SLOT - constants.NUM_SP_INTERVALS_EXTRA): + for signage_point_index in range(constants.NUM_SPS_SUB_SLOT - constants.NUM_SP_INTERVALS_EXTRA): curr = latest_block while curr.total_iters > sub_slot_start_total_iters + calculate_sp_iters( constants, sub_slot_iters, uint8(signage_point_index) @@ -1310,7 +1310,7 @@ class BlockTools: # Keep trying until we get a good proof of space that also passes sp filter while True: cc_challenge, rc_challenge = get_challenges(constants, {}, finished_sub_slots, None) - for signage_point_index in range(0, constants.NUM_SPS_SUB_SLOT): + for signage_point_index in range(constants.NUM_SPS_SUB_SLOT): signage_point: SignagePoint = get_signage_point( constants, BlockCache({}), diff --git a/chia/simulator/setup_services.py b/chia/simulator/setup_services.py index d1beb0052d..d7c299d33c 100644 --- a/chia/simulator/setup_services.py +++ b/chia/simulator/setup_services.py @@ -317,7 +317,6 @@ async def setup_wallet_node( # filesystem operations are async on windows # [WinError 32] The process cannot access the file because it is # being used by another process - pass keychain.delete_all_keys() diff --git a/chia/types/blockchain_format/program.py b/chia/types/blockchain_format/program.py index f3f3df92bb..9d70547b9d 100644 --- a/chia/types/blockchain_format/program.py +++ b/chia/types/blockchain_format/program.py @@ -10,6 +10,7 @@ from clvm.CLVMObject import CLVMStorage from clvm.EvalError import EvalError from clvm.serialize import sexp_from_stream, sexp_to_stream from clvm.SExp import SExp +from typing_extensions import Self from chia.types.blockchain_format.serialized_program import SerializedProgram from chia.types.blockchain_format.tree_hash import sha256_treehash @@ -30,14 +31,14 @@ class Program(SExp): """ @classmethod - def parse(cls: type[T_Program], f) -> T_Program: + def parse(cls, f) -> Self: return sexp_from_stream(f, cls.to) def stream(self, f) -> None: sexp_to_stream(self, f) @classmethod - def from_serialized(cls: type[T_Program], prg: SerializedProgram) -> T_Program: + def from_serialized(cls, prg: SerializedProgram) -> Self: """ Convert the SerializedProgram to a Program object. """ @@ -50,7 +51,7 @@ class Program(SExp): return SerializedProgram.from_bytes(bytes(self)) @classmethod - def from_bytes(cls: type[T_Program], blob: bytes) -> T_Program: + def from_bytes(cls, blob: bytes) -> Self: # this runs the program "1", which just returns the first argument. # the first argument is the buffer we want to parse. This effectively # leverages the rust parser and LazyNode, making it a lot faster to @@ -64,7 +65,7 @@ class Program(SExp): return cls.to(ret) @classmethod - def fromhex(cls: type[T_Program], hexstr: str) -> T_Program: + def fromhex(cls, hexstr: str) -> Self: return cls.from_bytes(hexstr_to_bytes(hexstr)) @classmethod @@ -104,7 +105,7 @@ class Program(SExp): raise ValueError(f"`at` got illegal character `{c}`. Only `f` & `r` allowed") return v - def replace(self: T_Program, **kwargs: Any) -> T_Program: + def replace(self, **kwargs: Any) -> Self: """ Create a new program replacing the given paths (using `at` syntax). Example: diff --git a/chia/types/blockchain_format/proof_of_space.py b/chia/types/blockchain_format/proof_of_space.py index 64df45c0d7..d3efe7445d 100644 --- a/chia/types/blockchain_format/proof_of_space.py +++ b/chia/types/blockchain_format/proof_of_space.py @@ -23,7 +23,7 @@ def get_plot_id(pos: ProofOfSpace) -> bytes32: def validate_proof_v2(plot_id: bytes32, size: uint8, challenge: bytes32, proof: bytes) -> Optional[bytes]: - raise NotImplementedError() + raise NotImplementedError def verify_and_get_quality_string( @@ -94,7 +94,7 @@ def verify_and_get_quality_string_v2( *, height: uint32, ) -> Optional[bytes32]: - raise NotImplementedError() + raise NotImplementedError def passes_plot_filter( diff --git a/chia/util/action_scope.py b/chia/util/action_scope.py index 7b3447087b..333480dd3a 100644 --- a/chia/util/action_scope.py +++ b/chia/util/action_scope.py @@ -6,6 +6,7 @@ from dataclasses import dataclass, field from typing import Callable, Generic, Optional, Protocol, TypeVar import aiosqlite +from typing_extensions import Self from chia.util.db_wrapper import DBWrapper2, execute_fetchone @@ -80,7 +81,7 @@ class SideEffects(Protocol): def __bytes__(self) -> bytes: ... @classmethod - def from_bytes(cls: type[_T_SideEffects], blob: bytes) -> _T_SideEffects: ... + def from_bytes(cls, blob: bytes) -> Self: ... _T_SideEffects = TypeVar("_T_SideEffects", bound=SideEffects) diff --git a/chia/util/byte_types.py b/chia/util/byte_types.py index 76864c5e49..5cce931a6b 100644 --- a/chia/util/byte_types.py +++ b/chia/util/byte_types.py @@ -7,6 +7,6 @@ def hexstr_to_bytes(input_str: str) -> bytes: """ Converts a hex string into bytes, removing the 0x if it's present. """ - if input_str.startswith("0x") or input_str.startswith("0X"): + if input_str.startswith(("0x", "0X")): return bytes.fromhex(input_str[2:]) return bytes.fromhex(input_str) diff --git a/chia/util/db_wrapper.py b/chia/util/db_wrapper.py index a8357206e1..da19b0db96 100644 --- a/chia/util/db_wrapper.py +++ b/chia/util/db_wrapper.py @@ -314,7 +314,7 @@ class DBWrapper2: # probably skip the nested foreign key check when exiting since # we don't have many foreign key errors and so it is likely ok # to save the extra time checking twice. - raise NestedForeignKeyDelayedRequestError() + raise NestedForeignKeyDelayedRequestError async with self._savepoint_ctx(): yield self._write_connection return diff --git a/chia/util/errors.py b/chia/util/errors.py index 2f832363bb..847775d3b8 100644 --- a/chia/util/errors.py +++ b/chia/util/errors.py @@ -349,5 +349,3 @@ class CliRpcConnectionError(ClickException): """ This error is raised when a rpc server cant be reached by the cli async generator """ - - pass diff --git a/chia/util/keychain.py b/chia/util/keychain.py index 8a86b1cac3..9332b9237f 100644 --- a/chia/util/keychain.py +++ b/chia/util/keychain.py @@ -79,12 +79,11 @@ def bytes_to_mnemonic(mnemonic_bytes: bytes) -> str: CS = len(mnemonic_bytes) // 4 checksum = BitArray(bytes(std_hash(mnemonic_bytes)))[:CS] - bitarray = BitArray(mnemonic_bytes) + checksum mnemonics = [] assert len(bitarray) % 11 == 0 - for i in range(0, len(bitarray) // 11): + for i in range(len(bitarray) // 11): start = i * 11 end = start + 11 bits = bitarray[start:end] @@ -127,7 +126,7 @@ def bytes_from_mnemonic(mnemonic_str: str) -> bytes: word_list = {word: i for i, word in enumerate(bip39_word_list().splitlines())} bit_array = BitArray() - for i in range(0, len(mnemonic)): + for i in range(len(mnemonic)): word = mnemonic[i] if word not in word_list: raise ValueError(f"'{word}' is not in the mnemonic dictionary; may be misspelled") @@ -264,24 +263,24 @@ class KeyData(Streamable): @property def mnemonic(self) -> list[str]: if self.secrets is None: - raise KeychainSecretsMissing() + raise KeychainSecretsMissing return self.secrets.mnemonic def mnemonic_str(self) -> str: if self.secrets is None: - raise KeychainSecretsMissing() + raise KeychainSecretsMissing return self.secrets.mnemonic_str() @property def entropy(self) -> bytes: if self.secrets is None: - raise KeychainSecretsMissing() + raise KeychainSecretsMissing return self.secrets.entropy @property def private_key(self) -> PrivateKey: if self.secrets is None: - raise KeychainSecretsMissing() + raise KeychainSecretsMissing return self.secrets.private_key diff --git a/chia/util/keyring_wrapper.py b/chia/util/keyring_wrapper.py index 66eedd6466..b51896de2e 100644 --- a/chia/util/keyring_wrapper.py +++ b/chia/util/keyring_wrapper.py @@ -112,7 +112,7 @@ def obtain_current_passphrase(prompt: str = DEFAULT_PASSPHRASE_PROMPT, use_passp time.sleep(FAILED_ATTEMPT_DELAY) print("Incorrect passphrase\n") - raise KeychainMaxUnlockAttempts() + raise KeychainMaxUnlockAttempts class KeyringWrapper: @@ -254,7 +254,7 @@ class KeyringWrapper: and current_passphrase is not None and not self.master_passphrase_is_valid(current_passphrase) ): - raise KeychainCurrentPassphraseIsInvalid() + raise KeychainCurrentPassphraseIsInvalid self.set_cached_master_passphrase(new_passphrase, validated=True) diff --git a/chia/util/limited_semaphore.py b/chia/util/limited_semaphore.py index 62b2ab0de1..5a3c1fb547 100644 --- a/chia/util/limited_semaphore.py +++ b/chia/util/limited_semaphore.py @@ -31,7 +31,7 @@ class LimitedSemaphore: @contextlib.asynccontextmanager async def acquire(self) -> AsyncIterator[int]: if self._available_count < 1: - raise LimitedSemaphoreFullError() + raise LimitedSemaphoreFullError self._available_count -= 1 try: diff --git a/chia/util/priority_mutex.py b/chia/util/priority_mutex.py index 3cab8c457c..60fe4964a5 100644 --- a/chia/util/priority_mutex.py +++ b/chia/util/priority_mutex.py @@ -66,7 +66,7 @@ class PriorityMutex(Generic[_T_Priority]): if task is None: raise Exception(f"unable to check current task, got: {task!r}") if self._active is not None and self._active.task is task: - raise NestedLockUnsupportedError() + raise NestedLockUnsupportedError element = _Element(task=task) diff --git a/chia/util/streamable.py b/chia/util/streamable.py index 3a2f337bbe..e54e218f30 100644 --- a/chia/util/streamable.py +++ b/chia/util/streamable.py @@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Any, BinaryIO, Callable, ClassVar, Optional, T from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint16, uint32, uint64 -from typing_extensions import Literal, get_args, get_origin +from typing_extensions import Literal, Self, get_args, get_origin from chia.util.byte_types import hexstr_to_bytes from chia.util.hash import std_hash @@ -575,9 +575,9 @@ class Streamable: raise @classmethod - def parse(cls: type[_T_Streamable], f: BinaryIO) -> _T_Streamable: + def parse(cls, f: BinaryIO) -> Self: # Create the object without calling __init__() to avoid unnecessary post-init checks in strictdataclass - obj: _T_Streamable = object.__new__(cls) + obj: Self = object.__new__(cls) for field in cls._streamable_fields: object.__setattr__(obj, field.name, field.parse_function(f)) return obj @@ -590,7 +590,7 @@ class Streamable: return std_hash(bytes(self), skip_bytes_conversion=True) @classmethod - def from_bytes(cls: type[_T_Streamable], blob: bytes) -> _T_Streamable: + def from_bytes(cls, blob: bytes) -> Self: f = io.BytesIO(blob) parsed = cls.parse(f) assert f.read() == b"" @@ -617,7 +617,7 @@ class Streamable: return ret @classmethod - def from_json_dict(cls: type[_T_Streamable], json_dict: dict[str, Any]) -> _T_Streamable: + def from_json_dict(cls, json_dict: dict[str, Any]) -> Self: return streamable_from_dict(cls, json_dict) diff --git a/chia/wallet/conditions.py b/chia/wallet/conditions.py index 4788850717..aa62886fd6 100644 --- a/chia/wallet/conditions.py +++ b/chia/wallet/conditions.py @@ -9,6 +9,7 @@ from chia_rs import Coin, G1Element from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint8, uint32, uint64 from clvm.casts import int_from_bytes, int_to_bytes +from typing_extensions import Self from chia.types.blockchain_format.program import Program from chia.types.condition_opcodes import ConditionOpcode @@ -237,7 +238,7 @@ class CreateCoin(Condition): return condition @classmethod - def from_program(cls: type[_T_CreateCoin], program: Program) -> _T_CreateCoin: + def from_program(cls, program: Program) -> Self: potential_memos: Program = program.at("rrr") return cls( bytes32(program.at("rf").as_atom()), @@ -253,9 +254,6 @@ class CreateCoin(Condition): return [self.puzzle_hash, self.amount, self.memos] -_T_CreateCoin = TypeVar("_T_CreateCoin", bound=CreateCoin) - - @final @streamable @dataclass(frozen=True) @@ -541,9 +539,6 @@ class MessageParticipant(Streamable): ) -_T_MessageCondition = TypeVar("_T_MessageCondition", bound="SendMessage") - - @streamable @dataclass(frozen=True) class SendMessage(Condition): @@ -607,7 +602,7 @@ class SendMessage(Condition): return condition @classmethod - def from_program(cls: type[_T_MessageCondition], program: Program) -> _T_MessageCondition: + def from_program(cls, program: Program) -> Self: full_mode = uint8(program.at("rf").as_int()) var_args = list(program.at("rrr").as_iter()) return cls( diff --git a/chia/wallet/nft_wallet/uncurry_nft.py b/chia/wallet/nft_wallet/uncurry_nft.py index 8863dba6bf..b0f691cdaa 100644 --- a/chia/wallet/nft_wallet/uncurry_nft.py +++ b/chia/wallet/nft_wallet/uncurry_nft.py @@ -2,11 +2,12 @@ from __future__ import annotations import logging from dataclasses import dataclass -from typing import Optional, TypeVar +from typing import Optional from chia_rs import CoinSpend, CoinState from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint16 +from typing_extensions import Self from chia.types.blockchain_format.program import Program from chia.util.streamable import Streamable, streamable @@ -16,8 +17,6 @@ from chia.wallet.singleton import SINGLETON_TOP_LAYER_MOD log = logging.getLogger(__name__) -_T_UncurriedNFT = TypeVar("_T_UncurriedNFT", bound="UncurriedNFT") - @streamable @dataclass(frozen=True) @@ -88,7 +87,7 @@ class UncurriedNFT(Streamable): trade_price_percentage: Optional[uint16] @classmethod - def uncurry(cls: type[_T_UncurriedNFT], mod: Program, curried_args: Program) -> Optional[_T_UncurriedNFT]: + def uncurry(cls, mod: Program, curried_args: Program) -> Optional[Self]: """ Try to uncurry a NFT puzzle :param cls UncurriedNFT class diff --git a/chia/wallet/trade_record.py b/chia/wallet/trade_record.py index 04343e9837..19534e23ef 100644 --- a/chia/wallet/trade_record.py +++ b/chia/wallet/trade_record.py @@ -1,10 +1,11 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Any, Optional, TypeVar +from typing import Any, Optional from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint8, uint32, uint64 +from typing_extensions import Self from chia.types.blockchain_format.coin import Coin from chia.util.streamable import Streamable, streamable @@ -12,8 +13,6 @@ from chia.wallet.conditions import ConditionValidTimes from chia.wallet.trading.offer import Offer from chia.wallet.trading.trade_status import TradeStatus -_T_TradeRecord = TypeVar("_T_TradeRecord", bound="TradeRecordOld") - @streamable @dataclass(frozen=True) @@ -51,9 +50,7 @@ class TradeRecordOld(Streamable): return formatted @classmethod - def from_json_dict_convenience( - cls: type[_T_TradeRecord], record: dict[str, Any], offer: str = "" - ) -> _T_TradeRecord: + def from_json_dict_convenience(cls, record: dict[str, Any], offer: str = "") -> Self: new_record = record.copy() new_record["status"] = TradeStatus[record["status"]].value del new_record["summary"] diff --git a/chia/wallet/util/tx_config.py b/chia/wallet/util/tx_config.py index 7220606c42..ddca5c8928 100644 --- a/chia/wallet/util/tx_config.py +++ b/chia/wallet/util/tx_config.py @@ -1,12 +1,12 @@ from __future__ import annotations import dataclasses -from typing import Any, Optional, TypeVar +from typing import Any, Optional from chia_rs import ConsensusConstants from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint64 -from typing_extensions import NotRequired, TypedDict, Unpack +from typing_extensions import NotRequired, Self, TypedDict, Unpack from chia.consensus.default_constants import DEFAULT_CONSTANTS from chia.types.blockchain_format.coin import Coin @@ -66,9 +66,6 @@ class AutofillArgs(TypedDict): logged_in_fingerprint: NotRequired[int] -_T_CoinSelectionConfigLoader = TypeVar("_T_CoinSelectionConfigLoader", bound="CoinSelectionConfigLoader") - - @streamable @dataclasses.dataclass(frozen=True) class CoinSelectionConfigLoader(Streamable): @@ -90,9 +87,7 @@ class CoinSelectionConfigLoader(Streamable): ) @classmethod - def from_json_dict( - cls: type[_T_CoinSelectionConfigLoader], json_dict: dict[str, Any] - ) -> _T_CoinSelectionConfigLoader: + def from_json_dict(cls, json_dict: dict[str, Any]) -> Self: if "excluded_coins" in json_dict: excluded_coins: list[Coin] = [Coin.from_json_dict(c) for c in json_dict["excluded_coins"]] excluded_coin_ids: list[str] = [c.name().hex() for c in excluded_coins] diff --git a/chia/wallet/vc_wallet/cr_cat_drivers.py b/chia/wallet/vc_wallet/cr_cat_drivers.py index 39e4a2cb44..47d481c9ec 100644 --- a/chia/wallet/vc_wallet/cr_cat_drivers.py +++ b/chia/wallet/vc_wallet/cr_cat_drivers.py @@ -4,7 +4,7 @@ import functools from collections.abc import Iterable from dataclasses import dataclass, replace from enum import IntEnum -from typing import Optional, TypeVar +from typing import Optional from chia_puzzles_py.programs import ( CONDITIONS_W_FEE_ANNOUNCE, @@ -20,6 +20,7 @@ from chia_rs import CoinSpend from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint16, uint64 from clvm.casts import int_to_bytes +from typing_extensions import Self from chia.types.blockchain_format.coin import Coin, coin_as_list from chia.types.blockchain_format.program import Program @@ -166,9 +167,6 @@ def construct_pending_approval_state(puzzle_hash: bytes32, amount: uint64) -> Pr return PENDING_VC_ANNOUNCEMENT.curry(Program.to([[51, puzzle_hash, amount, [puzzle_hash]]])) -_T_CRCAT = TypeVar("_T_CRCAT", bound="CRCAT") - - @dataclass(frozen=True) class CRCAT: coin: Coin @@ -180,7 +178,7 @@ class CRCAT: @classmethod def launch( - cls: type[_T_CRCAT], + cls, # General CAT launching info origin_coin: Coin, payment: CreateCoin, @@ -308,7 +306,7 @@ class CRCAT: return solution.at("f").at("rrrrrrf") @classmethod - def get_current_from_coin_spend(cls: type[_T_CRCAT], spend: CoinSpend) -> CRCAT: # pragma: no cover + def get_current_from_coin_spend(cls, spend: CoinSpend) -> CRCAT: # pragma: no cover uncurried_puzzle: UncurriedPuzzle = uncurry_puzzle(spend.puzzle_reveal) first_uncurried_cr_layer: UncurriedPuzzle = uncurry_puzzle(uncurried_puzzle.args.at("rrf")) second_uncurried_cr_layer: UncurriedPuzzle = uncurry_puzzle(first_uncurried_cr_layer.mod) @@ -327,7 +325,7 @@ class CRCAT: @classmethod def get_next_from_coin_spend( - cls: type[_T_CRCAT], + cls, parent_spend: CoinSpend, conditions: Optional[Program] = None, # For optimization purposes, the conditions may already have been run ) -> list[CRCAT]: @@ -516,8 +514,8 @@ class CRCAT: @classmethod def spend_many( - cls: type[_T_CRCAT], - inner_spends: list[tuple[_T_CRCAT, int, Program, Program]], # CRCAT, extra_delta, inner puzzle, inner solution + cls, + inner_spends: list[tuple[Self, int, Program, Program]], # CRCAT, extra_delta, inner puzzle, inner solution # CR layer solving info proof_of_inclusions: Program, proof_checker_solution: Program, @@ -539,7 +537,7 @@ class CRCAT: def prev_index(index: int) -> int: return index - 1 - sorted_inner_spends: list[tuple[_T_CRCAT, int, Program, Program]] = sorted( + sorted_inner_spends: list[tuple[Self, int, Program, Program]] = sorted( inner_spends, key=lambda spend: spend[0].coin.name(), ) diff --git a/chia/wallet/vc_wallet/vc_drivers.py b/chia/wallet/vc_wallet/vc_drivers.py index d281f110fb..940484c672 100644 --- a/chia/wallet/vc_wallet/vc_drivers.py +++ b/chia/wallet/vc_wallet/vc_drivers.py @@ -1,7 +1,7 @@ from __future__ import annotations from dataclasses import dataclass, replace -from typing import Optional, TypeVar +from typing import Optional from chia_puzzles_py.programs import ACS_TRANSFER_PROGRAM as ACS_TRANSFER_PROGRAM_BYTES from chia_puzzles_py.programs import COVENANT_LAYER as COVENANT_LAYER_BYTES @@ -23,6 +23,7 @@ from chia_puzzles_py.programs import STD_PARENT_MORPHER_HASH as STD_PARENT_MORPH from chia_rs import CoinSpend from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint64 +from typing_extensions import Self from chia.types.blockchain_format.coin import Coin from chia.types.blockchain_format.program import Program @@ -290,7 +291,6 @@ OWNERSHIP_LAYER_LAUNCHER_HASH = OWNERSHIP_LAYER_LAUNCHER.get_tree_hash() ######################## # Verified Credentials # ######################## -_T_VerifiedCredential = TypeVar("_T_VerifiedCredential", bound="VerifiedCredential") @streamable @@ -312,14 +312,14 @@ class VerifiedCredential(Streamable): @classmethod def launch( - cls: type[_T_VerifiedCredential], + cls, origin_coins: list[Coin], provider_id: bytes32, new_inner_puzzle_hash: bytes32, memos: list[bytes32], fee: uint64 = uint64(0), extra_conditions: tuple[Condition, ...] = tuple(), - ) -> tuple[list[Program], list[CoinSpend], _T_VerifiedCredential]: + ) -> tuple[list[Program], list[CoinSpend], Self]: """ Launch a VC. @@ -539,7 +539,7 @@ class VerifiedCredential(Streamable): return True, "" @classmethod - def get_next_from_coin_spend(cls: type[_T_VerifiedCredential], parent_spend: CoinSpend) -> _T_VerifiedCredential: + def get_next_from_coin_spend(cls, parent_spend: CoinSpend) -> Self: """ Given a coin spend, this will return the next VC that was create as an output of that spend. This is the main method to use when syncing. If a spend has been identified as having a VC puzzle reveal, running this method @@ -608,7 +608,7 @@ class VerifiedCredential(Streamable): parent_proof_hash=None if parent_proof_hash == Program.to(None) else parent_proof_hash, ) - new_vc: _T_VerifiedCredential = cls( + new_vc: Self = cls( coin, singleton_lineage_proof, eml_lineage_proof, diff --git a/chia/wallet/vc_wallet/vc_store.py b/chia/wallet/vc_wallet/vc_store.py index 135f769935..5d52213872 100644 --- a/chia/wallet/vc_wallet/vc_store.py +++ b/chia/wallet/vc_wallet/vc_store.py @@ -2,11 +2,12 @@ from __future__ import annotations import dataclasses from functools import cmp_to_key -from typing import Optional, TypeVar +from typing import Optional from aiosqlite import Row from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint32, uint64 +from typing_extensions import Self from chia.types.blockchain_format.coin import Coin from chia.types.blockchain_format.program import Program @@ -81,9 +82,6 @@ class VCProofs: return new_tree -_T_VCStore = TypeVar("_T_VCStore", bound="VCStore") - - @streamable @dataclasses.dataclass(frozen=True) class VCRecord(Streamable): @@ -114,7 +112,7 @@ class VCStore: db_wrapper: DBWrapper2 @classmethod - async def create(cls: type[_T_VCStore], db_wrapper: DBWrapper2) -> _T_VCStore: + async def create(cls, db_wrapper: DBWrapper2) -> Self: self = cls() self.db_wrapper = db_wrapper diff --git a/chia/wallet/wallet_nft_store.py b/chia/wallet/wallet_nft_store.py index 4eab728cd2..4b2d1ab413 100644 --- a/chia/wallet/wallet_nft_store.py +++ b/chia/wallet/wallet_nft_store.py @@ -3,10 +3,11 @@ from __future__ import annotations import json import logging from sqlite3 import Row -from typing import Optional, TypeVar, Union +from typing import Optional, Union from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint32 +from typing_extensions import Self from chia.types.blockchain_format.coin import Coin from chia.types.blockchain_format.program import Program @@ -15,7 +16,6 @@ from chia.wallet.lineage_proof import LineageProof from chia.wallet.nft_wallet.nft_info import DEFAULT_STATUS, IN_TRANSACTION_STATUS, NFTCoinInfo log = logging.getLogger(__name__) -_T_WalletNftStore = TypeVar("_T_WalletNftStore", bound="WalletNftStore") REMOVE_BUFF_BLOCKS = 1000 NFT_COIN_INFO_COLUMNS = "nft_id, coin, lineage_proof, mint_height, status, full_puzzle, latest_height, minter_did" @@ -42,7 +42,7 @@ class WalletNftStore: db_wrapper: DBWrapper2 @classmethod - async def create(cls: type[_T_WalletNftStore], db_wrapper: DBWrapper2) -> _T_WalletNftStore: + async def create(cls, db_wrapper: DBWrapper2) -> Self: self = cls() self.db_wrapper = db_wrapper async with self.db_wrapper.writer_maybe_transaction() as conn: diff --git a/chia/wallet/wallet_node.py b/chia/wallet/wallet_node.py index b0e49fdf8a..88dee1ef39 100644 --- a/chia/wallet/wallet_node.py +++ b/chia/wallet/wallet_node.py @@ -200,7 +200,7 @@ class WalletNode: else: self._keychain_proxy = await connect_to_keychain_and_validate(self.root_path, self.log) if not self._keychain_proxy: - raise KeychainProxyConnectionFailure() + raise KeychainProxyConnectionFailure return self._keychain_proxy def get_cache_for_peer(self, peer: WSChiaConnection) -> PeerRequestCache: diff --git a/chia/wallet/wallet_node_api.py b/chia/wallet/wallet_node_api.py index 931e036ec3..5bfbbe7c3e 100644 --- a/chia/wallet/wallet_node_api.py +++ b/chia/wallet/wallet_node_api.py @@ -39,14 +39,12 @@ class WalletNodeAPI: """ The full node has rejected our request for removals. """ - pass @metadata.request() async def reject_additions_request(self, response: wallet_protocol.RejectAdditionsRequest): """ The full node has rejected our request for additions. """ - pass @metadata.request(peer_required=True, execute_task=True) async def new_peak_wallet(self, peak: wallet_protocol.NewPeakWallet, peer: WSChiaConnection): @@ -83,7 +81,6 @@ class WalletNodeAPI: """ The full node has rejected our request for a header. """ - pass @metadata.request() async def respond_block_header(self, response: wallet_protocol.RespondBlockHeader): diff --git a/chia/wallet/wallet_singleton_store.py b/chia/wallet/wallet_singleton_store.py index d02525ef74..2ad860e884 100644 --- a/chia/wallet/wallet_singleton_store.py +++ b/chia/wallet/wallet_singleton_store.py @@ -3,12 +3,13 @@ from __future__ import annotations import json import logging from sqlite3 import Row -from typing import Optional, TypeVar, Union +from typing import Optional, Union from chia_rs import CoinSpend from chia_rs.sized_bytes import bytes32 from chia_rs.sized_ints import uint32, uint64 from clvm.casts import int_from_bytes +from typing_extensions import Self from chia.consensus.condition_tools import conditions_dict_for_solution from chia.consensus.default_constants import DEFAULT_CONSTANTS @@ -22,14 +23,13 @@ from chia.wallet.singleton import get_inner_puzzle_from_singleton, get_singleton from chia.wallet.singleton_record import SingletonRecord log = logging.getLogger(__name__) -_T_WalletSingletonStore = TypeVar("_T_WalletSingletonStore", bound="WalletSingletonStore") class WalletSingletonStore: db_wrapper: DBWrapper2 @classmethod - async def create(cls: type[_T_WalletSingletonStore], wrapper: DBWrapper2) -> _T_WalletSingletonStore: + async def create(cls, wrapper: DBWrapper2) -> Self: self = cls() self.db_wrapper = wrapper diff --git a/chia/wallet/wallet_state_manager.py b/chia/wallet/wallet_state_manager.py index 7156479d2e..21e5c95d7b 100644 --- a/chia/wallet/wallet_state_manager.py +++ b/chia/wallet/wallet_state_manager.py @@ -2055,7 +2055,7 @@ class WalletStateManager: ): # Optimization to avoid the computation below. Any coin that has a different amount is not a pool reward return False - for i in range(0, 30): + for i in range(30): try_height = created_height - i if try_height < 0: break @@ -2068,7 +2068,7 @@ class WalletStateManager: if coin.amount < calculate_base_farmer_reward(created_height): # Optimization to avoid the computation below. Any coin less than this base amount cannot be farmer reward return False - for i in range(0, 30): + for i in range(30): try_height = created_height - i if try_height < 0: break diff --git a/ruff.toml b/ruff.toml index fbf82dab17..87c735ac69 100644 --- a/ruff.toml +++ b/ruff.toml @@ -3,17 +3,41 @@ line-length = 120 [lint] preview = true select = [ - "PL", # Pylint - "I", # Isort - "FA", # Flake8: future-annotations - "UP", # Pyupgrade - "RUF", # Ruff specific - "F", # Flake8 core - "ASYNC", # Flake8 async - "ISC", # flake8-implicit-str-concat + "PL", # Pylint + "I", # Isort + "FA", # Flake8: future-annotations + "UP", # Pyupgrade + "RUF", # Ruff specific + "F", # Flake8 core + "ASYNC", # Flake8 async + "ISC", # flake8-implicit-str-concat "TID", # flake8-tidy-imports - "E", - "W", + "T10", # Debug statements + "EXE", # shebang usage + "ICN", # Import name conventions (i.e. import pandas as pd) + "INP", # Missing __init__.py + "Q", # quotes + "SLOT", # __slots__ usage + "TID", # Tidy imports + "FLY", # .join -> f-string + "PIE", # flake8 plugin for extra lints + "PYI", # type stubs linting + "RSE", # Linting raises + "S", # Potential security issues + # pycodestyle + "E", + "W", + # Trailing commas + # "COM812" # missing-trailing-comma (5105 errors) + "COM818", + "COM819", + # Libraries we don't use so might as well enable + "INT", + "AIR", + "FAST", + "DJ", + "NPY", + "PD", ] explicit-preview-rules = false ignore = [ @@ -72,6 +96,25 @@ ignore = [ "RUF043", # pytest-raises-ambiguous-pattern "RUF046", # unnecessary-cast-to-int "RUF052", # used-dummy-variable + + # Security linter + # Need review on which of these we can/should fix + "S101", + "S110", + "S404", + "S311", + "S602", + "S607", + "S603", + "S608", + "S112", + "S105", + "S104", + "S323", + "S605", + "S301", + "S403", + "S106", ] diff --git a/tools/manage_clvm.py b/tools/manage_clvm.py index 4ac6023c31..7c36d84e03 100644 --- a/tools/manage_clvm.py +++ b/tools/manage_clvm.py @@ -88,7 +88,7 @@ def load_cache(file: typing.IO[str]) -> Cache: try: loaded_version = loaded_cache["version"] except KeyError as e: - raise NoCacheVersionError() from e + raise NoCacheVersionError from e if loaded_version != current_cache_version: raise WrongCacheVersionError(found_version=loaded_version, expected_version=current_cache_version) diff --git a/tools/run_block.py b/tools/run_block.py old mode 100644 new mode 100755