From 17c461ee9d481ad0a2d59c9142422ae73edc10bf Mon Sep 17 00:00:00 2001 From: Matt Date: Thu, 7 Nov 2024 10:24:03 -0800 Subject: [PATCH 01/12] Tighten up ruff ignore list --- activated.py | 2 +- benchmarks/streamable.py | 4 +- chia/_tests/core/data_layer/test_data_rpc.py | 2 +- .../_tests/core/data_layer/test_data_store.py | 2 +- chia/_tests/core/data_layer/util.py | 2 +- chia/_tests/core/full_node/test_full_node.py | 2 +- chia/_tests/core/test_farmer_harvester_rpc.py | 2 +- chia/_tests/core/test_full_node_rpc.py | 2 +- chia/_tests/core/test_seeder.py | 2 +- chia/_tests/core/util/test_block_cache.py | 8 +-- chia/_tests/plot_sync/test_receiver.py | 4 +- chia/_tests/wallet/test_conditions.py | 2 +- chia/cmds/configure.py | 4 +- chia/cmds/init_funcs.py | 6 +- chia/cmds/installers.py | 2 + chia/consensus/constants.py | 5 +- chia/daemon/server.py | 2 +- chia/data_layer/s3_plugin_service.py | 2 +- chia/full_node/full_node.py | 2 +- chia/full_node/weight_proof.py | 2 +- chia/plotters/bladebit.py | 2 +- chia/pools/pool_wallet.py | 5 +- chia/rpc/full_node_rpc_api.py | 2 +- chia/rpc/rpc_server.py | 2 +- chia/rpc/util.py | 4 +- chia/rpc/wallet_rpc_api.py | 8 +-- chia/seeder/dns_server.py | 2 +- chia/server/server.py | 7 +- chia/timelord/timelord_state.py | 6 +- chia/util/streamable.py | 2 +- chia/wallet/trade_manager.py | 3 +- chia/wallet/trading/offer.py | 6 +- chia/wallet/transaction_record.py | 2 +- chia/wallet/wallet_state_manager.py | 7 +- installhelper.py | 2 +- ruff.toml | 64 ++++++++----------- tools/chialispp.py | 2 +- 37 files changed, 86 insertions(+), 99 deletions(-) diff --git a/activated.py b/activated.py index f065cc6d46df..1a033c8495a7 100755 --- a/activated.py +++ b/activated.py @@ -33,7 +33,7 @@ def main(*args: str) -> int: script = "activated.sh" command = ["sh", os.fspath(here.joinpath(script)), env.value, *args] - completed_process = subprocess.run(command) + completed_process = subprocess.run(command, check=False) return completed_process.returncode diff --git a/benchmarks/streamable.py b/benchmarks/streamable.py index 366310c2d4d9..8ff2b22291ad 100644 --- a/benchmarks/streamable.py +++ b/benchmarks/streamable.py @@ -236,7 +236,7 @@ def run(data: Data, mode: Mode, runs: int, ms: int, live: bool, output: TextIO, results: dict[Data, dict[Mode, list[list[int]]]] = {} bench_results: dict[str, Any] = {"version": _version, "commit_hash": get_commit_hash()} for current_data, parameter in benchmark_parameter.items(): - if data == Data.all or current_data == data: + if data in (Data.all, current_data): results[current_data] = {} bench_results[current_data] = {} print( @@ -252,7 +252,7 @@ def run(data: Data, mode: Mode, runs: int, ms: int, live: bool, output: TextIO, ) for current_mode, current_mode_parameter in parameter.mode_parameter.items(): results[current_data][current_mode] = [] - if mode == Mode.all or current_mode == mode: + if mode in (Mode.all, current_mode): us_iteration_results: list[int] all_results: list[list[int]] = results[current_data][current_mode] obj = parameter.object_creation_cb() diff --git a/chia/_tests/core/data_layer/test_data_rpc.py b/chia/_tests/core/data_layer/test_data_rpc.py index 2b08621692b9..251e8d3fde88 100644 --- a/chia/_tests/core/data_layer/test_data_rpc.py +++ b/chia/_tests/core/data_layer/test_data_rpc.py @@ -3087,7 +3087,7 @@ async def test_pagination_cmds( ) elif layer == InterfaceLayer.cli: for command in ("get_keys", "get_keys_values", "get_kv_diff"): - if command == "get_keys" or command == "get_keys_values": + if command in ("get_keys", "get_keys_values"): args: list[str] = [ sys.executable, "-m", diff --git a/chia/_tests/core/data_layer/test_data_store.py b/chia/_tests/core/data_layer/test_data_store.py index 79565c5684c1..faa7cd041258 100644 --- a/chia/_tests/core/data_layer/test_data_store.py +++ b/chia/_tests/core/data_layer/test_data_store.py @@ -402,7 +402,7 @@ async def test_batch_update( [0.4, 0.2, 0.2, 0.2], k=1, ) - if op_type == "insert" or op_type == "upsert-insert" or len(keys_values) == 0: + if op_type in ("insert", "upsert-insert") or len(keys_values) == 0: if len(keys_values) == 0: op_type = "insert" key = operation.to_bytes(4, byteorder="big") diff --git a/chia/_tests/core/data_layer/util.py b/chia/_tests/core/data_layer/util.py index 406309f65a24..b97426dd3633 100644 --- a/chia/_tests/core/data_layer/util.py +++ b/chia/_tests/core/data_layer/util.py @@ -157,7 +157,7 @@ def run( kwargs["stderr"] = stderr try: - return subprocess.run(*final_args, **kwargs) + return subprocess.run(*final_args, **kwargs, check=False) except OSError as e: raise Exception(f"failed to run:\n {final_args}\n {kwargs}") from e diff --git a/chia/_tests/core/full_node/test_full_node.py b/chia/_tests/core/full_node/test_full_node.py index abec2bd49baf..1b7b07810cde 100644 --- a/chia/_tests/core/full_node/test_full_node.py +++ b/chia/_tests/core/full_node/test_full_node.py @@ -507,7 +507,7 @@ async def have_msgs(): if msg is not None and not (len(msg.peer_list) == 1): return False peer = msg.peer_list[0] - return (peer.host == self_hostname or peer.host == "127.0.0.1") and peer.port == 1000 + return (peer.host in (self_hostname, "127.0.0.1")) and peer.port == 1000 await time_out_assert_custom_interval(10, 1, have_msgs, True) full_node_1.full_node.full_node_peers.address_manager = AddressManager() diff --git a/chia/_tests/core/test_farmer_harvester_rpc.py b/chia/_tests/core/test_farmer_harvester_rpc.py index 44481966bc58..40fc2e6c6bb5 100644 --- a/chia/_tests/core/test_farmer_harvester_rpc.py +++ b/chia/_tests/core/test_farmer_harvester_rpc.py @@ -47,7 +47,7 @@ async def wait_for_plot_sync(receiver: Receiver, previous_last_sync_id: uint64) -> None: def wait() -> bool: current_last_sync_id = receiver.last_sync().sync_id - return current_last_sync_id != 0 and current_last_sync_id != previous_last_sync_id + return current_last_sync_id not in (0, previous_last_sync_id) await time_out_assert(30, wait) diff --git a/chia/_tests/core/test_full_node_rpc.py b/chia/_tests/core/test_full_node_rpc.py index b20463a76450..179d515ce13d 100644 --- a/chia/_tests/core/test_full_node_rpc.py +++ b/chia/_tests/core/test_full_node_rpc.py @@ -228,7 +228,7 @@ async def test1(two_nodes_sim_and_wallets_services, self_hostname, consensus_mod block_spends = await client.get_block_spends(block.header_hash) assert len(block_spends) == 3 - assert sorted(block_spends, key=lambda x: str(x)) == sorted(coin_spends, key=lambda x: str(x)) + assert sorted(block_spends, key=str) == sorted(coin_spends, key=str) block_spends_with_conditions = await client.get_block_spends_with_conditions(block.header_hash) diff --git a/chia/_tests/core/test_seeder.py b/chia/_tests/core/test_seeder.py index 26cc5c692a07..fd3ed5ffb2ee 100644 --- a/chia/_tests/core/test_seeder.py +++ b/chia/_tests/core/test_seeder.py @@ -164,7 +164,7 @@ async def test_error_conditions( no_peers_response = await make_dns_query(use_tcp, target_address, port, no_peers) assert no_peers_response.rcode() == dns.rcode.NOERROR - if request_type == dns.rdatatype.A or request_type == dns.rdatatype.AAAA: + if request_type in (dns.rdatatype.A, dns.rdatatype.AAAA): assert len(no_peers_response.answer) == 0 # no response, as expected elif request_type == dns.rdatatype.ANY: # ns + soa assert len(no_peers_response.answer) == 2 diff --git a/chia/_tests/core/util/test_block_cache.py b/chia/_tests/core/util/test_block_cache.py index e7ed476aacc5..69c83e1221dc 100644 --- a/chia/_tests/core/util/test_block_cache.py +++ b/chia/_tests/core/util/test_block_cache.py @@ -36,9 +36,9 @@ async def test_block_cache(seeded_random: random.Random) -> None: if i == 0: continue assert await a.prev_block_hash([hh]) == [hashes[i - 1]] - assert a.try_block_record(hh) == BR(i + 1, hashes[i], hashes[i - 1]) - assert a.block_record(hh) == BR(i + 1, hashes[i], hashes[i - 1]) - assert a.height_to_hash(uint32(i + 1)) == hashes[i] - assert a.height_to_block_record(uint32(i + 1)) == BR(i + 1, hashes[i], hashes[i - 1]) + assert a.try_block_record(hh) == BR(i + 1, hh, hashes[i - 1]) + assert a.block_record(hh) == BR(i + 1, hh, hashes[i - 1]) + assert a.height_to_hash(uint32(i + 1)) == hh + assert a.height_to_block_record(uint32(i + 1)) == BR(i + 1, hh, hashes[i - 1]) assert a.contains_block(hh) assert a.contains_height(uint32(i + 1)) diff --git a/chia/_tests/plot_sync/test_receiver.py b/chia/_tests/plot_sync/test_receiver.py index b45b95aa5a9e..fc4e8d062a49 100644 --- a/chia/_tests/plot_sync/test_receiver.py +++ b/chia/_tests/plot_sync/test_receiver.py @@ -132,7 +132,7 @@ async def run_sync_step(receiver: Receiver, sync_step: SyncStepData) -> None: assert receiver.current_sync().state == sync_step.state last_sync_time_before = receiver._last_sync.time_done # For the list types invoke the trigger function in batches - if sync_step.payload_type == PlotSyncPlotList or sync_step.payload_type == PlotSyncPathList: + if sync_step.payload_type in (PlotSyncPlotList, PlotSyncPathList): step_data, _ = sync_step.args assert len(step_data) == 10 # Invoke batches of: 1, 2, 3, 4 items and validate the data against plot store before and after @@ -289,7 +289,7 @@ async def test_to_dict(counts_only: bool, seeded_random: random.Random) -> None: for state in State: await run_sync_step(receiver, sync_steps[state]) - if state != State.idle and state != State.removed and state != State.done: + if state not in (State.idle, State.removed, State.done): expected_plot_files_processed += len(sync_steps[state].args[0]) sync_data = receiver.to_dict()["syncing"] diff --git a/chia/_tests/wallet/test_conditions.py b/chia/_tests/wallet/test_conditions.py index fbdca992d972..cc4155c8dfab 100644 --- a/chia/_tests/wallet/test_conditions.py +++ b/chia/_tests/wallet/test_conditions.py @@ -381,7 +381,7 @@ def test_invalid_condition( ], prg: bytes, ) -> None: - if (cond == Remark or cond == UnknownCondition) and prg != b"\x80": + if (cond in (Remark, UnknownCondition)) and prg != b"\x80": pytest.skip("condition takes arbitrary arguments") with pytest.raises((ValueError, EvalError, KeyError)): diff --git a/chia/cmds/configure.py b/chia/cmds/configure.py index 8ebac359a06c..a8d662edf1f7 100644 --- a/chia/cmds/configure.py +++ b/chia/cmds/configure.py @@ -103,7 +103,7 @@ def configure( print("Target peer count updated") change_made = True if testnet: - if testnet == "true" or testnet == "t": + if testnet in ("true", "t"): print("Setting Testnet") # check if network_overrides.constants.testnet11 exists if ( @@ -167,7 +167,7 @@ def configure( print("Default full node port, introducer and network setting updated") change_made = True - elif testnet == "false" or testnet == "f": + elif testnet in ("false", "f"): print("Setting Mainnet") mainnet_port = "8444" mainnet_introducer = "introducer.chia.net" diff --git a/chia/cmds/init_funcs.py b/chia/cmds/init_funcs.py index e6a4794e4fca..1b5e3db78aa2 100644 --- a/chia/cmds/init_funcs.py +++ b/chia/cmds/init_funcs.py @@ -41,8 +41,8 @@ def dict_add_new_default(updated: dict[str, Any], default: dict[str, Any], do_not_migrate_keys: dict[str, Any]) -> None: - for k in do_not_migrate_keys: - if k in updated and do_not_migrate_keys[k] == "": + for k, v in do_not_migrate_keys.items(): + if k in updated and v == "": updated.pop(k) for k, v in default.items(): ignore = False @@ -56,7 +56,7 @@ def dict_add_new_default(updated: dict[str, Any], default: dict[str, Any], do_no # If there is an intermediate key with empty string value, do not migrate all descendants if do_not_migrate_keys.get(k, None) == "": do_not_migrate_keys[k] = v - dict_add_new_default(updated[k], default[k], do_not_migrate_keys.get(k, {})) + dict_add_new_default(updated[k], v, do_not_migrate_keys.get(k, {})) elif k not in updated or ignore is True: updated[k] = v diff --git a/chia/cmds/installers.py b/chia/cmds/installers.py index fd0cae1f553f..653dab07183e 100644 --- a/chia/cmds/installers.py +++ b/chia/cmds/installers.py @@ -61,6 +61,7 @@ def test_command(expected_chia_version_str: str, require_madmax: bool) -> None: capture_output=True, encoding="utf-8", timeout=adjusted_timeout(30), + check=False, ) assert chia_version_process.returncode == 0 assert chia_version_process.stderr == "" @@ -76,6 +77,7 @@ def test_command(expected_chia_version_str: str, require_madmax: bool) -> None: capture_output=True, encoding="utf-8", timeout=adjusted_timeout(30), + check=False, ) print() diff --git a/chia/consensus/constants.py b/chia/consensus/constants.py index 3e77f0880a21..c07f1818672b 100644 --- a/chia/consensus/constants.py +++ b/chia/consensus/constants.py @@ -3,7 +3,7 @@ import logging from typing import Any -from chia_rs import ConsensusConstants as ConsensusConstants +from chia_rs import ConsensusConstants from chia.util.byte_types import hexstr_to_bytes from chia.util.hash import std_hash @@ -47,3 +47,6 @@ def replace_str_to_bytes(constants: ConsensusConstants, **changes: Any) -> Conse # TODO: this is too magical here and is really only used for configuration unmarshalling return constants.replace(**filtered_changes) # type: ignore[arg-type] + + +__all__ = ["ConsensusConstants", "replace_str_to_bytes"] diff --git a/chia/daemon/server.py b/chia/daemon/server.py index c59fd47480ec..8d71d9e72ec9 100644 --- a/chia/daemon/server.py +++ b/chia/daemon/server.py @@ -1020,7 +1020,7 @@ def _build_plotting_command_args(self, request: Any, ignoreCount: bool, index: i # plotter command must be either # 'chia plotters bladebit ramplot' or 'chia plotters bladebit diskplot' plot_type = request["plot_type"] - assert plot_type == "diskplot" or plot_type == "ramplot" or plot_type == "cudaplot" + assert plot_type in ("diskplot", "ramplot", "cudaplot") command_args.append(plot_type) command_args.extend(self._common_plotting_command_args(request, ignoreCount)) diff --git a/chia/data_layer/s3_plugin_service.py b/chia/data_layer/s3_plugin_service.py index a9489e8f1fa2..3422d87fc8b0 100644 --- a/chia/data_layer/s3_plugin_service.py +++ b/chia/data_layer/s3_plugin_service.py @@ -14,7 +14,7 @@ from typing import Any, Optional, overload from urllib.parse import urlparse -import boto3 as boto3 +import boto3 import yaml from aiohttp import web from botocore.exceptions import ClientError diff --git a/chia/full_node/full_node.py b/chia/full_node/full_node.py index 7f3a83001228..f7e1ee20ce5c 100644 --- a/chia/full_node/full_node.py +++ b/chia/full_node/full_node.py @@ -1609,7 +1609,7 @@ async def add_prevalidated_blocks( agg_state_change_summary.additions + state_change_summary.additions, agg_state_change_summary.new_rewards + state_change_summary.new_rewards, ) - elif result == AddBlockResult.INVALID_BLOCK or result == AddBlockResult.DISCONNECTED_BLOCK: + elif result in (AddBlockResult.INVALID_BLOCK, AddBlockResult.DISCONNECTED_BLOCK): if error is not None: self.log.error(f"Error: {error}, Invalid block from peer: {peer_info} ") return agg_state_change_summary, error diff --git a/chia/full_node/weight_proof.py b/chia/full_node/weight_proof.py index 4c8f195f310f..ff0a1d7fad83 100644 --- a/chia/full_node/weight_proof.py +++ b/chia/full_node/weight_proof.py @@ -880,7 +880,7 @@ def _map_sub_epoch_summaries( if idx < len(sub_epoch_data) - 1: delta = 0 if idx > 0: - delta = sub_epoch_data[idx].num_blocks_overflow + delta = data.num_blocks_overflow log.debug(f"sub epoch {idx} start weight is {total_weight + curr_difficulty} ") sub_epoch_weight_list.append(uint128(total_weight + curr_difficulty)) total_weight = uint128( diff --git a/chia/plotters/bladebit.py b/chia/plotters/bladebit.py index dfce9a3b9b32..47ec6487318e 100644 --- a/chia/plotters/bladebit.py +++ b/chia/plotters/bladebit.py @@ -286,7 +286,7 @@ def plot_bladebit(args, chia_root_path, root_path): args.connect_to_daemon, ) ) - if args.plot_type == "ramplot" or args.plot_type == "diskplot" or args.plot_type == "cudaplot": + if args.plot_type in ("ramplot", "diskplot", "cudaplot"): plot_type = args.plot_type else: plot_type = "diskplot" diff --git a/chia/pools/pool_wallet.py b/chia/pools/pool_wallet.py index 7b1c1025f50c..9013a51ca924 100644 --- a/chia/pools/pool_wallet.py +++ b/chia/pools/pool_wallet.py @@ -177,10 +177,7 @@ def _verify_pool_state(cls, state: PoolState) -> Optional[str]: if state.state == PoolSingletonState.SELF_POOLING.value: return cls._verify_self_pooled(state) - elif ( - state.state == PoolSingletonState.FARMING_TO_POOL.value - or state.state == PoolSingletonState.LEAVING_POOL.value - ): + elif state.state in (PoolSingletonState.FARMING_TO_POOL.value, PoolSingletonState.LEAVING_POOL.value): return cls._verify_pooling_state(state) else: return "Internal Error" diff --git a/chia/rpc/full_node_rpc_api.py b/chia/rpc/full_node_rpc_api.py index 10087338357e..73cbc802739a 100644 --- a/chia/rpc/full_node_rpc_api.py +++ b/chia/rpc/full_node_rpc_api.py @@ -132,7 +132,7 @@ async def _state_changed(self, change: str, change_data: Optional[dict[str, Any] change_data = {} payloads = [] - if change == "new_peak" or change == "sync_mode": + if change in ("new_peak", "sync_mode"): data = await self.get_blockchain_state({}) assert data is not None payloads.append( diff --git a/chia/rpc/rpc_server.py b/chia/rpc/rpc_server.py index 38b9c7c18236..fb316a4783ea 100644 --- a/chia/rpc/rpc_server.py +++ b/chia/rpc/rpc_server.py @@ -202,7 +202,7 @@ async def _state_changed(self, change: str, change_data: Optional[dict[str, Any] return None payloads: list[WsRpcMessage] = await self.rpc_api._state_changed(change, change_data) - if change == "add_connection" or change == "close_connection" or change == "peer_changed_peak": + if change in ("add_connection", "close_connection", "peer_changed_peak"): data = await self.get_connections({}) if data is not None: payload = create_payload_dict( diff --git a/chia/rpc/util.py b/chia/rpc/util.py index af31786fe09a..9c57ae4c153d 100644 --- a/chia/rpc/util.py +++ b/chia/rpc/util.py @@ -209,9 +209,7 @@ async def rpc_endpoint( if ( func.__name__ == "create_new_wallet" and request["wallet_type"] == "pool_wallet" - or func.__name__ == "pw_join_pool" - or func.__name__ == "pw_self_pool" - or func.__name__ == "pw_absorb_rewards" + or func.__name__ in ("pw_join_pool", "pw_self_pool", "pw_absorb_rewards") ): # Theses RPCs return not "convenience" for some reason response["transaction"] = new_txs[-1].to_json_dict() diff --git a/chia/rpc/wallet_rpc_api.py b/chia/rpc/wallet_rpc_api.py index 9da56239cec0..9348adab20e5 100644 --- a/chia/rpc/wallet_rpc_api.py +++ b/chia/rpc/wallet_rpc_api.py @@ -1785,7 +1785,7 @@ async def verify_signature(self, request: dict[str, Any]) -> EndpointResult: except ValueError: raise ValueError(f"Invalid signing mode: {signing_mode_str!r}") - if signing_mode == SigningMode.CHIP_0002 or signing_mode == SigningMode.CHIP_0002_P2_DELEGATED_CONDITIONS: + if signing_mode in (SigningMode.CHIP_0002, SigningMode.CHIP_0002_P2_DELEGATED_CONDITIONS): # CHIP-0002 message signatures are made over the tree hash of: # ("Chia Signed Message", message) message_to_verify: bytes = Program.to((CHIP_0002_SIGN_MESSAGE_PREFIX, input_message)).get_tree_hash() @@ -2086,11 +2086,11 @@ async def create_offer_for_ids( driver_dict[bytes32.from_hexstr(key)] = PuzzleInfo(value) modified_offer: dict[Union[int, bytes32], int] = {} - for key in offer: + for key, val in offer.items(): try: - modified_offer[bytes32.from_hexstr(key)] = offer[key] + modified_offer[bytes32.from_hexstr(key)] = val except ValueError: - modified_offer[int(key)] = offer[key] + modified_offer[int(key)] = val async with self.service.wallet_state_manager.lock: result = await self.service.wallet_state_manager.trade_manager.create_offer_for_ids( diff --git a/chia/seeder/dns_server.py b/chia/seeder/dns_server.py index d0efe7de6ad7..9c9ac3708b5f 100644 --- a/chia/seeder/dns_server.py +++ b/chia/seeder/dns_server.py @@ -504,7 +504,7 @@ async def dns_response(self, request: DNSRecord) -> DNSRecord: valid_domain = True for response in domain_responses: rqt: int = getattr(QTYPE, response.__class__.__name__) - if question_type == rqt or question_type == QTYPE.ANY: + if question_type in (rqt, QTYPE.ANY): reply.add_answer(RR(rname=qname, rtype=rqt, rclass=1, ttl=ttl, rdata=response)) if not valid_domain and len(reply.rr) == 0: # if we didn't find any records to return reply.header.rcode = RCODE.NXDOMAIN diff --git a/chia/server/server.py b/chia/server/server.py index 71f75279998b..6c98cafcf584 100644 --- a/chia/server/server.py +++ b/chia/server/server.py @@ -254,7 +254,7 @@ async def garbage_collect_connections_task(self) -> None: if connection.closed: to_remove.append(connection) elif ( - self._local_type == NodeType.FULL_NODE or self._local_type == NodeType.WALLET + self._local_type in (NodeType.FULL_NODE, NodeType.WALLET) ) and connection.connection_type == NodeType.FULL_NODE: if is_crawler is not None: if time.time() - connection.creation_time > 5: @@ -541,8 +541,9 @@ async def connection_closed( ban_until: float = time.time() + ban_time self.log.warning(f"Banning {connection.peer_info.host} for {ban_time} seconds") if connection.peer_info.host in self.banned_peers: - if ban_until > self.banned_peers[connection.peer_info.host]: - self.banned_peers[connection.peer_info.host] = ban_until + self.banned_peers[connection.peer_info.host] = max( + ban_until, self.banned_peers[connection.peer_info.host] + ) else: self.banned_peers[connection.peer_info.host] = ban_until diff --git a/chia/timelord/timelord_state.py b/chia/timelord/timelord_state.py index e6e35c11cc07..a162f4977b46 100644 --- a/chia/timelord/timelord_state.py +++ b/chia/timelord/timelord_state.py @@ -121,7 +121,7 @@ def can_infuse_block(self, overflow: bool) -> bool: if overflow and self.new_epoch: # No overflows in new epoch return False - if self.state_type == StateType.FIRST_SUB_SLOT or self.state_type == StateType.END_OF_SUB_SLOT: + if self.state_type in (StateType.FIRST_SUB_SLOT, StateType.END_OF_SUB_SLOT): return True ss_start_iters = self.get_total_iters() - self.get_last_ip() already_infused_count: int = 0 @@ -160,7 +160,7 @@ def just_infused_sub_epoch_summary(self) -> bool: return self.state_type == StateType.END_OF_SUB_SLOT and self.infused_ses def get_next_sub_epoch_summary(self) -> Optional[SubEpochSummary]: - if self.state_type == StateType.FIRST_SUB_SLOT or self.state_type == StateType.END_OF_SUB_SLOT: + if self.state_type in (StateType.FIRST_SUB_SLOT, StateType.END_OF_SUB_SLOT): # Can only infuse SES after a peak (in an end of sub slot) return None assert self.peak is not None @@ -233,7 +233,7 @@ def get_initial_form(self, chain: Chain) -> Optional[ClassgroupElement]: else: return None elif self.state_type == StateType.END_OF_SUB_SLOT: - if chain == Chain.CHALLENGE_CHAIN or chain == Chain.REWARD_CHAIN: + if chain in (Chain.CHALLENGE_CHAIN, Chain.REWARD_CHAIN): return ClassgroupElement.get_default_element() if chain == Chain.INFUSED_CHALLENGE_CHAIN: assert self.subslot_end is not None diff --git a/chia/util/streamable.py b/chia/util/streamable.py index 787be2a0fa0e..b6e47b154b48 100644 --- a/chia/util/streamable.py +++ b/chia/util/streamable.py @@ -216,7 +216,7 @@ def function_to_convert_one_item( elif hasattr(f_type, "from_json_dict"): if json_parser is None: json_parser = f_type.from_json_dict - return lambda item: json_parser(item) + return json_parser elif issubclass(f_type, bytes): # Type is bytes, data is a hex string or bytes return lambda item: convert_byte_type(f_type, item) diff --git a/chia/wallet/trade_manager.py b/chia/wallet/trade_manager.py index 1f64f406f422..5cb2cc02836f 100644 --- a/chia/wallet/trade_manager.py +++ b/chia/wallet/trade_manager.py @@ -1033,8 +1033,7 @@ async def check_for_final_modifications( if WalletType(wallet.type()) == WalletType.VC: assert isinstance(wallet, VCWallet) return await wallet.add_vc_authorization(offer, solver, action_scope) - else: - raise ValueError("No VCs to approve CR-CATs with") # pragma: no cover + raise ValueError("No VCs to approve CR-CATs with") # pragma: no cover return offer, Solver({}) diff --git a/chia/wallet/trading/offer.py b/chia/wallet/trading/offer.py index 3aa58fdc94d7..5a8e6ec066dc 100644 --- a/chia/wallet/trading/offer.py +++ b/chia/wallet/trading/offer.py @@ -326,11 +326,11 @@ def summary(self) -> tuple[dict[str, int], dict[str, int], dict[str, dict[str, A def keys_to_strings(dic: dict[Optional[bytes32], Any]) -> dict[str, Any]: new_dic: dict[str, Any] = {} - for key in dic: + for key, val in dic.items(): if key is None: - new_dic["xch"] = dic[key] + new_dic["xch"] = val else: - new_dic[key.hex()] = dic[key] + new_dic[key.hex()] = val return new_dic driver_dict: dict[str, Any] = {} diff --git a/chia/wallet/transaction_record.py b/chia/wallet/transaction_record.py index 8fb0d71cc0a3..5ccbdb551fec 100644 --- a/chia/wallet/transaction_record.py +++ b/chia/wallet/transaction_record.py @@ -67,7 +67,7 @@ def is_in_mempool(self) -> bool: def height_farmed(self, genesis_challenge: bytes32) -> Optional[uint32]: if not self.confirmed: return None - if self.type == TransactionType.FEE_REWARD or self.type == TransactionType.COINBASE_REWARD: + if self.type in (TransactionType.FEE_REWARD, TransactionType.COINBASE_REWARD): for block_index in range(self.confirmed_at_height, self.confirmed_at_height - 100, -1): if block_index < 0: return None diff --git a/chia/wallet/wallet_state_manager.py b/chia/wallet/wallet_state_manager.py index 1cef6dee295e..d26ba2c20567 100644 --- a/chia/wallet/wallet_state_manager.py +++ b/chia/wallet/wallet_state_manager.py @@ -1692,10 +1692,9 @@ async def handle_vc(self, vc: VerifiedCredential) -> Optional[WalletIdentifier]: self.log.info(f"Found verified credential {vc.launcher_id.hex()}.") for wallet_info in await self.get_all_wallet_info_entries(wallet_type=WalletType.VC): return WalletIdentifier(wallet_info.id, WalletType.VC) - else: - # Create a new VC wallet - vc_wallet = await VCWallet.create_new_vc_wallet(self, self.main_wallet) # pragma: no cover - return WalletIdentifier(vc_wallet.id(), WalletType.VC) # pragma: no cover + # Create a new VC wallet + vc_wallet = await VCWallet.create_new_vc_wallet(self, self.main_wallet) # pragma: no cover + return WalletIdentifier(vc_wallet.id(), WalletType.VC) # pragma: no cover async def _add_coin_states( self, diff --git a/installhelper.py b/installhelper.py index 51de3f90bcbf..f6e2f9606d0d 100644 --- a/installhelper.py +++ b/installhelper.py @@ -55,7 +55,7 @@ def get_chia_version() -> str: chia_executable = shutil.which("chia") if chia_executable is None: chia_executable = "chia" - output = subprocess.run([chia_executable, "version"], capture_output=True) + output = subprocess.run([chia_executable, "version"], capture_output=True, check=False) if output.returncode == 0: version = str(output.stdout.strip(), "utf-8").splitlines()[-1] return make_semver(version) diff --git a/ruff.toml b/ruff.toml index d44603e9b421..1e37af422019 100644 --- a/ruff.toml +++ b/ruff.toml @@ -15,48 +15,36 @@ select = [ explicit-preview-rules = false ignore = [ # Pylint convention - "PLC0105", # type-name-incorrect-variance - "PLC0415", # import-outside-top-level - "PLC2801", # unnecessary-dunder-call - "PLC0206", # dict-index-missing-items - "PLC1901", # compare-to-empty-string - "PLC2701", # import-private-name - "PLC0414", # useless-import-alias + "PLC0105", # type-name-incorrect-variance (2) (?) + "PLC0415", # import-outside-top-level (286) (x) + "PLC2801", # unnecessary-dunder-call (11) (x) + "PLC1901", # compare-to-empty-string (51) (x) + "PLC2701", # import-private-name (24) (x) # Pylint refactor - "PLR0915", # too-many-statements - "PLR0914", # too-many-locals - "PLR0913", # too-many-arguments - "PLR0912", # too-many-branches - "PLR1702", # too-many-nested-blocks - "PLR0904", # too-many-public-methods - "PLR6301", # no-self-use - "PLR0917", # too-many-positional-arguments - "PLR6201", # literal-membership - "PLR0911", # too-many-return-statements - "PLR2004", # magic-value-comparison - "PLR1714", # repeated-equality-comparison - "PLR6104", # non-augmented-assignment - "PLR1704", # redefined-argument-from-local - "PLR0916", # too-many-boolean-expressions - "PLR5501", # collapsible-else-if - "PLR1711", # useless-return - "PLR1730", # if-stmt-min-max - "PLR1736", # unnecessary-list-index-lookup - "PLR1733", # unnecessary-dict-index-lookup + "PLR0915", # too-many-statements (222) (x) + "PLR0914", # too-many-locals (328) (x) + "PLR0913", # too-many-arguments (397) (x) + "PLR0912", # too-many-branches (193) (x) + "PLR1702", # too-many-nested-blocks (124) (x) + "PLR0904", # too-many-public-methods (47) (x) + "PLR0917", # too-many-positional-arguments (345) (x) + "PLR0916", # too-many-boolean-expressions (3) (x) + "PLR0911", # too-many-return-statements (52) (x) + "PLR6301", # no-self-use (699) (-) + "PLR6201", # literal-membership (86) (?) + "PLR2004", # magic-value-comparison (901) (-) + "PLR6104", # non-augmented-assignment (27) (?) + "PLR1704", # redefined-argument-from-local (13) (-) + "PLR5501", # collapsible-else-if (49) (?) + "PLR1711", # useless-return (14) (?) # Pylint warning - "PLW2901", # redefined-loop-name - "PLW1641", # eq-without-hash - "PLW1514", # unspecified-encoding - "PLW0602", # global-variable-not-assigned - "PLW0603", # global-statement - "PLW0108", # unnecessary-lambda - "PLW1510", # subprocess-run-without-check - "PLW0120", # useless-else-on-loop - - # Flake8 core - # "F841", # unused-variable (540) + "PLW2901", # redefined-loop-name (19) (-) + "PLW1641", # eq-without-hash (5) (?) + "PLW1514", # unspecified-encoding (69) (?) + "PLW0602", # global-variable-not-assigned (5) (?) + "PLW0603", # global-statement (9) (?) ] diff --git a/tools/chialispp.py b/tools/chialispp.py index 334b5e866f93..09f88f598883 100644 --- a/tools/chialispp.py +++ b/tools/chialispp.py @@ -151,7 +151,7 @@ def output_line(self) -> None: if semis == 0: # We've entered a string, stop processing - if ch == b"'" or ch == b'"': + if ch in (b"'", b'"'): in_string = ch continue elif ch == b"(": From 9f5ffd9e0e41f9ed9a16f07b971981bd2e478b9c Mon Sep 17 00:00:00 2001 From: Matt Date: Thu, 7 Nov 2024 10:44:57 -0800 Subject: [PATCH 02/12] Okay that fix was indeed unsafe --- chia/_tests/core/data_layer/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chia/_tests/core/data_layer/util.py b/chia/_tests/core/data_layer/util.py index b97426dd3633..61cf1d09b0b1 100644 --- a/chia/_tests/core/data_layer/util.py +++ b/chia/_tests/core/data_layer/util.py @@ -157,7 +157,7 @@ def run( kwargs["stderr"] = stderr try: - return subprocess.run(*final_args, **kwargs, check=False) + return subprocess.run(*final_args, **kwargs) # noqa: PLW1510 except OSError as e: raise Exception(f"failed to run:\n {final_args}\n {kwargs}") from e From 02b1eaa79c4628639431abc1638678a2e7fec92a Mon Sep 17 00:00:00 2001 From: Kyle Altendorf Date: Thu, 7 Nov 2024 14:45:06 -0500 Subject: [PATCH 03/12] enable type-name-incorrect-variance --- chia/wallet/util/wallet_types.py | 4 ++-- chia/wallet/wallet_protocol.py | 8 +++++--- ruff.toml | 1 - 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/chia/wallet/util/wallet_types.py b/chia/wallet/util/wallet_types.py index 93be99573d32..7237ee966e2b 100644 --- a/chia/wallet/util/wallet_types.py +++ b/chia/wallet/util/wallet_types.py @@ -51,7 +51,7 @@ class RemarkDataType(IntEnum): CLAWBACK = 2 -T = TypeVar("T", contravariant=True) +T_contra = TypeVar("T_contra", contravariant=True) @dataclass(frozen=True) @@ -60,7 +60,7 @@ class WalletIdentifier: type: WalletType @classmethod - def create(cls, wallet: WalletProtocol[T]) -> WalletIdentifier: + def create(cls, wallet: WalletProtocol[T_contra]) -> WalletIdentifier: return cls(wallet.id(), wallet.type()) diff --git a/chia/wallet/wallet_protocol.py b/chia/wallet/wallet_protocol.py index e80427d3573a..00c92b27a806 100644 --- a/chia/wallet/wallet_protocol.py +++ b/chia/wallet/wallet_protocol.py @@ -20,16 +20,18 @@ if TYPE_CHECKING: from chia.wallet.wallet_state_manager import WalletStateManager -T = TypeVar("T", contravariant=True) +T_contra = TypeVar("T_contra", contravariant=True) -class WalletProtocol(Protocol[T]): +class WalletProtocol(Protocol[T_contra]): @classmethod def type(cls) -> WalletType: ... def id(self) -> uint32: ... - async def coin_added(self, coin: Coin, height: uint32, peer: WSChiaConnection, coin_data: Optional[T]) -> None: ... + async def coin_added( + self, coin: Coin, height: uint32, peer: WSChiaConnection, coin_data: Optional[T_contra] + ) -> None: ... async def select_coins( self, diff --git a/ruff.toml b/ruff.toml index 1e37af422019..6f620fafa683 100644 --- a/ruff.toml +++ b/ruff.toml @@ -15,7 +15,6 @@ select = [ explicit-preview-rules = false ignore = [ # Pylint convention - "PLC0105", # type-name-incorrect-variance (2) (?) "PLC0415", # import-outside-top-level (286) (x) "PLC2801", # unnecessary-dunder-call (11) (x) "PLC1901", # compare-to-empty-string (51) (x) From 1a5e15e391273bb8c6c75ce2d8c7f2b69cc2c4b2 Mon Sep 17 00:00:00 2001 From: Kyle Altendorf Date: Thu, 7 Nov 2024 14:58:36 -0500 Subject: [PATCH 04/12] enable literal-membership --- benchmarks/streamable.py | 4 ++-- chia/_tests/blockchain/test_blockchain.py | 2 +- .../core/data_layer/test_data_layer_util.py | 4 ++-- chia/_tests/core/data_layer/test_data_rpc.py | 2 +- chia/_tests/core/data_layer/test_data_store.py | 2 +- chia/_tests/core/full_node/test_full_node.py | 2 +- chia/_tests/core/mempool/test_mempool.py | 8 ++++---- chia/_tests/core/mempool/test_mempool_manager.py | 4 ++-- chia/_tests/core/services/test_services.py | 2 +- chia/_tests/core/test_farmer_harvester_rpc.py | 2 +- chia/_tests/core/test_seeder.py | 2 +- chia/_tests/core/util/test_files.py | 4 ++-- chia/_tests/core/util/test_keychain.py | 4 ++-- chia/_tests/environments/wallet.py | 2 +- chia/_tests/plot_sync/test_receiver.py | 4 ++-- chia/_tests/wallet/test_conditions.py | 2 +- chia/_tests/wallet/test_notifications.py | 2 +- chia/_tests/wallet/test_wallet_node.py | 4 ++-- .../_tests/wallet/vc_wallet/test_vc_lifecycle.py | 6 +++--- chia/cmds/cmd_classes.py | 2 +- chia/cmds/cmds_util.py | 4 ++-- chia/cmds/configure.py | 4 ++-- chia/cmds/param_types.py | 2 +- chia/cmds/plotnft.py | 2 +- chia/cmds/wallet_funcs.py | 2 +- chia/consensus/constants.py | 2 +- chia/daemon/server.py | 6 +++--- chia/data_layer/data_store.py | 2 +- chia/full_node/full_node.py | 2 +- chia/plotters/bladebit.py | 12 ++++++------ chia/plotters/madmax.py | 8 ++++---- chia/plotters/plotters_util.py | 2 +- chia/pools/pool_puzzles.py | 10 +++++----- chia/pools/pool_wallet.py | 10 +++++----- chia/rpc/crawler_rpc_api.py | 2 +- chia/rpc/full_node_rpc_api.py | 4 ++-- chia/rpc/rpc_server.py | 2 +- chia/rpc/timelord_rpc_api.py | 2 +- chia/rpc/util.py | 2 +- chia/rpc/wallet_rpc_api.py | 10 +++++----- chia/seeder/dns_server.py | 2 +- chia/server/chia_policy.py | 8 ++++---- chia/server/server.py | 2 +- chia/server/ws_connection.py | 4 ++-- chia/simulator/block_tools.py | 4 ++-- chia/timelord/timelord_state.py | 6 +++--- chia/types/coin_spend.py | 4 ++-- chia/util/config.py | 4 ++-- chia/util/full_block_utils.py | 2 +- chia/util/keychain.py | 8 ++++---- chia/util/network.py | 2 +- chia/util/profiler.py | 2 +- chia/util/task_timing.py | 2 +- chia/wallet/conditions.py | 2 +- chia/wallet/trade_manager.py | 6 +++--- chia/wallet/transaction_record.py | 6 +++--- chia/wallet/util/compute_hints.py | 4 ++-- chia/wallet/wallet.py | 2 +- chia/wallet/wallet_state_manager.py | 16 ++++++++-------- ruff.toml | 5 ++--- tools/chialispp.py | 4 ++-- tools/generate_chain.py | 2 +- 62 files changed, 125 insertions(+), 126 deletions(-) diff --git a/benchmarks/streamable.py b/benchmarks/streamable.py index 8ff2b22291ad..e8c3a9ecf750 100644 --- a/benchmarks/streamable.py +++ b/benchmarks/streamable.py @@ -236,7 +236,7 @@ def run(data: Data, mode: Mode, runs: int, ms: int, live: bool, output: TextIO, results: dict[Data, dict[Mode, list[list[int]]]] = {} bench_results: dict[str, Any] = {"version": _version, "commit_hash": get_commit_hash()} for current_data, parameter in benchmark_parameter.items(): - if data in (Data.all, current_data): + if data in {Data.all, current_data}: results[current_data] = {} bench_results[current_data] = {} print( @@ -252,7 +252,7 @@ def run(data: Data, mode: Mode, runs: int, ms: int, live: bool, output: TextIO, ) for current_mode, current_mode_parameter in parameter.mode_parameter.items(): results[current_data][current_mode] = [] - if mode in (Mode.all, current_mode): + if mode in {Mode.all, current_mode}: us_iteration_results: list[int] all_results: list[list[int]] = results[current_data][current_mode] obj = parameter.object_creation_cb() diff --git a/chia/_tests/blockchain/test_blockchain.py b/chia/_tests/blockchain/test_blockchain.py index d0ec491ab5c4..0cd2d1577cd0 100644 --- a/chia/_tests/blockchain/test_blockchain.py +++ b/chia/_tests/blockchain/test_blockchain.py @@ -2627,7 +2627,7 @@ async def test_cost_exceeds_max( fork_info=fork_info, ) )[1] - assert err in [Err.BLOCK_COST_EXCEEDS_MAX] + assert err in {Err.BLOCK_COST_EXCEEDS_MAX} futures = await pre_validate_blocks_multiprocessing( b.constants, AugmentedBlockchain(b), diff --git a/chia/_tests/core/data_layer/test_data_layer_util.py b/chia/_tests/core/data_layer/test_data_layer_util.py index 3fd93a3f0f94..0821f996fb8c 100644 --- a/chia/_tests/core/data_layer/test_data_layer_util.py +++ b/chia/_tests/core/data_layer/test_data_layer_util.py @@ -171,14 +171,14 @@ def definition(key: bytes, value: bytes) -> bytes32: data: list[tuple[bytes, bytes, bytes32]] = [] for cycle in range(20000): - if cycle in (0, 1): + if cycle in {0, 1}: length = 0 else: length = seeded_random.randrange(100) key = get_random_bytes(length=length, r=seeded_random) - if cycle in (1, 2): + if cycle in {1, 2}: length = 0 else: length = seeded_random.randrange(100) diff --git a/chia/_tests/core/data_layer/test_data_rpc.py b/chia/_tests/core/data_layer/test_data_rpc.py index 251e8d3fde88..356d20b6dff1 100644 --- a/chia/_tests/core/data_layer/test_data_rpc.py +++ b/chia/_tests/core/data_layer/test_data_rpc.py @@ -3087,7 +3087,7 @@ async def test_pagination_cmds( ) elif layer == InterfaceLayer.cli: for command in ("get_keys", "get_keys_values", "get_kv_diff"): - if command in ("get_keys", "get_keys_values"): + if command in {"get_keys", "get_keys_values"}: args: list[str] = [ sys.executable, "-m", diff --git a/chia/_tests/core/data_layer/test_data_store.py b/chia/_tests/core/data_layer/test_data_store.py index faa7cd041258..470c44f653f8 100644 --- a/chia/_tests/core/data_layer/test_data_store.py +++ b/chia/_tests/core/data_layer/test_data_store.py @@ -402,7 +402,7 @@ async def test_batch_update( [0.4, 0.2, 0.2, 0.2], k=1, ) - if op_type in ("insert", "upsert-insert") or len(keys_values) == 0: + if op_type in {"insert", "upsert-insert"} or len(keys_values) == 0: if len(keys_values) == 0: op_type = "insert" key = operation.to_bytes(4, byteorder="big") diff --git a/chia/_tests/core/full_node/test_full_node.py b/chia/_tests/core/full_node/test_full_node.py index 1b7b07810cde..7967526401c8 100644 --- a/chia/_tests/core/full_node/test_full_node.py +++ b/chia/_tests/core/full_node/test_full_node.py @@ -507,7 +507,7 @@ async def have_msgs(): if msg is not None and not (len(msg.peer_list) == 1): return False peer = msg.peer_list[0] - return (peer.host in (self_hostname, "127.0.0.1")) and peer.port == 1000 + return (peer.host in {self_hostname, "127.0.0.1"}) and peer.port == 1000 await time_out_assert_custom_interval(10, 1, have_msgs, True) full_node_1.full_node.full_node_peers.address_manager = AddressManager() diff --git a/chia/_tests/core/mempool/test_mempool.py b/chia/_tests/core/mempool/test_mempool.py index 72d334f9e072..2649963ec82c 100644 --- a/chia/_tests/core/mempool/test_mempool.py +++ b/chia/_tests/core/mempool/test_mempool.py @@ -2227,7 +2227,7 @@ def test_invalid_condition_list_terminator(self, softfork_height: uint32) -> Non # note how the list of conditions isn't correctly terminated with a # NIL atom. This is a failure npc_result = generator_condition_tester("(80 50) . 3", height=softfork_height) - assert npc_result.error in [Err.INVALID_CONDITION.value, Err.GENERATOR_RUNTIME_ERROR.value] + assert npc_result.error in {Err.INVALID_CONDITION.value, Err.GENERATOR_RUNTIME_ERROR.value} @pytest.mark.parametrize( "opcode", @@ -2341,7 +2341,7 @@ def test_create_coin_cost(self, softfork_height: uint32) -> None: max_cost=generator_base_cost + 95 * COST_PER_BYTE + ConditionCost.CREATE_COIN.value - 1, height=softfork_height, ) - assert npc_result.error in [Err.BLOCK_COST_EXCEEDS_MAX.value, Err.INVALID_BLOCK_COST.value] + assert npc_result.error in {Err.BLOCK_COST_EXCEEDS_MAX.value, Err.INVALID_BLOCK_COST.value} @pytest.mark.parametrize( "condition", @@ -2383,11 +2383,11 @@ def test_agg_sig_cost(self, condition: ConditionOpcode, softfork_height: uint32) max_cost=generator_base_cost + 117 * COST_PER_BYTE + expected_cost - 1, height=softfork_height, ) - assert npc_result.error in [ + assert npc_result.error in { Err.GENERATOR_RUNTIME_ERROR.value, Err.BLOCK_COST_EXCEEDS_MAX.value, Err.INVALID_BLOCK_COST.value, - ] + } @pytest.mark.parametrize( "condition", diff --git a/chia/_tests/core/mempool/test_mempool_manager.py b/chia/_tests/core/mempool/test_mempool_manager.py index 0db312df78b1..200274e8fb57 100644 --- a/chia/_tests/core/mempool/test_mempool_manager.py +++ b/chia/_tests/core/mempool/test_mempool_manager.py @@ -1188,9 +1188,9 @@ async def get_coin_records(coin_ids: Collection[bytes32]) -> list[CoinRecord]: assert expect_limit is not None item = mempool_manager.get_mempool_item(bundle_name) assert item is not None - if opcode in [co.ASSERT_BEFORE_SECONDS_ABSOLUTE, co.ASSERT_BEFORE_SECONDS_RELATIVE]: + if opcode in {co.ASSERT_BEFORE_SECONDS_ABSOLUTE, co.ASSERT_BEFORE_SECONDS_RELATIVE}: assert item.assert_before_seconds == expect_limit - elif opcode in [co.ASSERT_BEFORE_HEIGHT_ABSOLUTE, co.ASSERT_BEFORE_HEIGHT_RELATIVE]: + elif opcode in {co.ASSERT_BEFORE_HEIGHT_ABSOLUTE, co.ASSERT_BEFORE_HEIGHT_RELATIVE}: assert item.assert_before_height == expect_limit else: assert False diff --git a/chia/_tests/core/services/test_services.py b/chia/_tests/core/services/test_services.py index f80648ad8d60..ed28baf06733 100644 --- a/chia/_tests/core/services/test_services.py +++ b/chia/_tests/core/services/test_services.py @@ -100,7 +100,7 @@ async def test_daemon_terminates(signal_number: signal.Signals, chia_root: ChiaR "chia.timelord.timelord_launcher", "timelord_launcher", marks=pytest.mark.skipif( - sys.platform in ("win32", "cygwin"), + sys.platform in {"win32", "cygwin"}, reason="windows is not supported by the timelord launcher", ), ), diff --git a/chia/_tests/core/test_farmer_harvester_rpc.py b/chia/_tests/core/test_farmer_harvester_rpc.py index 40fc2e6c6bb5..3f9e3c030104 100644 --- a/chia/_tests/core/test_farmer_harvester_rpc.py +++ b/chia/_tests/core/test_farmer_harvester_rpc.py @@ -47,7 +47,7 @@ async def wait_for_plot_sync(receiver: Receiver, previous_last_sync_id: uint64) -> None: def wait() -> bool: current_last_sync_id = receiver.last_sync().sync_id - return current_last_sync_id not in (0, previous_last_sync_id) + return current_last_sync_id not in {0, previous_last_sync_id} await time_out_assert(30, wait) diff --git a/chia/_tests/core/test_seeder.py b/chia/_tests/core/test_seeder.py index fd3ed5ffb2ee..b5ee99f178e1 100644 --- a/chia/_tests/core/test_seeder.py +++ b/chia/_tests/core/test_seeder.py @@ -164,7 +164,7 @@ async def test_error_conditions( no_peers_response = await make_dns_query(use_tcp, target_address, port, no_peers) assert no_peers_response.rcode() == dns.rcode.NOERROR - if request_type in (dns.rdatatype.A, dns.rdatatype.AAAA): + if request_type in {dns.rdatatype.A, dns.rdatatype.AAAA}: assert len(no_peers_response.answer) == 0 # no response, as expected elif request_type == dns.rdatatype.ANY: # ns + soa assert len(no_peers_response.answer) == 2 diff --git a/chia/_tests/core/util/test_files.py b/chia/_tests/core/util/test_files.py index 5ae5636edb4b..11b341dacf20 100644 --- a/chia/_tests/core/util/test_files.py +++ b/chia/_tests/core/util/test_files.py @@ -336,7 +336,7 @@ async def test_write_file_default_permissions(self, tmp_path: Path): Write a file to a location and use the default permissions. """ - if sys.platform in ["win32", "cygwin"]: + if sys.platform in {"win32", "cygwin"}: pytest.skip("Setting UNIX file permissions doesn't apply to Windows") dest_path: Path = tmp_path / "test_write_file/test_write_file.txt" @@ -355,7 +355,7 @@ async def test_write_file_custom_permissions(self, tmp_path: Path): Write a file to a location and use custom permissions. """ - if sys.platform in ["win32", "cygwin"]: + if sys.platform in {"win32", "cygwin"}: pytest.skip("Setting UNIX file permissions doesn't apply to Windows") dest_path: Path = tmp_path / "test_write_file/test_write_file.txt" diff --git a/chia/_tests/core/util/test_keychain.py b/chia/_tests/core/util/test_keychain.py index ba21e90eedcc..337bdf6c475c 100644 --- a/chia/_tests/core/util/test_keychain.py +++ b/chia/_tests/core/util/test_keychain.py @@ -180,7 +180,7 @@ def test_add_private_key_label(self, empty_temp_file_keyring: TempKeyring): # All added keys should still be valid with their label assert all( - key_data in [key_data_0, key_data_1, key_data_2] for key_data in keychain.get_keys(include_secrets=True) + key_data in {key_data_0, key_data_1, key_data_2} for key_data in keychain.get_keys(include_secrets=True) ) def test_bip39_eip2333_test_vector(self, empty_temp_file_keyring: TempKeyring): @@ -427,7 +427,7 @@ async def test_set_label(get_temp_keyring: Keychain) -> None: keychain.set_label(fingerprint=key_data_1.fingerprint, label=key_data_1.label) assert key_data_0 == keychain.get_key(fingerprint=key_data_0.fingerprint, include_secrets=True) # All added keys should still be valid with their label - assert all(key_data in [key_data_0, key_data_1] for key_data in keychain.get_keys(include_secrets=True)) + assert all(key_data in {key_data_0, key_data_1} for key_data in keychain.get_keys(include_secrets=True)) @pytest.mark.parametrize( diff --git a/chia/_tests/environments/wallet.py b/chia/_tests/environments/wallet.py index d1ca5d166cf6..8fb912efb4d7 100644 --- a/chia/_tests/environments/wallet.py +++ b/chia/_tests/environments/wallet.py @@ -196,7 +196,7 @@ async def change_balances(self, update_dictionary: dict[Union[int, str], dict[st new_values: dict[str, int] = {} existing_values: Balance = await self.node.get_balance(wallet_id) if "init" in kwargs and kwargs["init"]: - new_values = {k: v for k, v in kwargs.items() if k not in ("set_remainder", "init")} + new_values = {k: v for k, v in kwargs.items() if k not in {"set_remainder", "init"}} elif wallet_id not in self.wallet_states: raise ValueError( f"Wallet id {wallet_id} (alias: {self.alias_wallet_id(wallet_id)}) does not have a current state. " diff --git a/chia/_tests/plot_sync/test_receiver.py b/chia/_tests/plot_sync/test_receiver.py index fc4e8d062a49..a291664de98c 100644 --- a/chia/_tests/plot_sync/test_receiver.py +++ b/chia/_tests/plot_sync/test_receiver.py @@ -132,7 +132,7 @@ async def run_sync_step(receiver: Receiver, sync_step: SyncStepData) -> None: assert receiver.current_sync().state == sync_step.state last_sync_time_before = receiver._last_sync.time_done # For the list types invoke the trigger function in batches - if sync_step.payload_type in (PlotSyncPlotList, PlotSyncPathList): + if sync_step.payload_type in {PlotSyncPlotList, PlotSyncPathList}: step_data, _ = sync_step.args assert len(step_data) == 10 # Invoke batches of: 1, 2, 3, 4 items and validate the data against plot store before and after @@ -289,7 +289,7 @@ async def test_to_dict(counts_only: bool, seeded_random: random.Random) -> None: for state in State: await run_sync_step(receiver, sync_steps[state]) - if state not in (State.idle, State.removed, State.done): + if state not in {State.idle, State.removed, State.done}: expected_plot_files_processed += len(sync_steps[state].args[0]) sync_data = receiver.to_dict()["syncing"] diff --git a/chia/_tests/wallet/test_conditions.py b/chia/_tests/wallet/test_conditions.py index cc4155c8dfab..7f44a8d6bf15 100644 --- a/chia/_tests/wallet/test_conditions.py +++ b/chia/_tests/wallet/test_conditions.py @@ -381,7 +381,7 @@ def test_invalid_condition( ], prg: bytes, ) -> None: - if (cond in (Remark, UnknownCondition)) and prg != b"\x80": + if (cond in {Remark, UnknownCondition}) and prg != b"\x80": pytest.skip("condition takes arbitrary arguments") with pytest.raises((ValueError, EvalError, KeyError)): diff --git a/chia/_tests/wallet/test_notifications.py b/chia/_tests/wallet/test_notifications.py index d0647cb86fd0..5b967612ffdd 100644 --- a/chia/_tests/wallet/test_notifications.py +++ b/chia/_tests/wallet/test_notifications.py @@ -121,7 +121,7 @@ async def track_coin_state(*args: Any) -> bool: wallet_node_2.config["enable_notifications"] = True AMOUNT = uint64(1) FEE = uint64(0) - elif case in ("allow", "allow_larger"): + elif case in {"allow", "allow_larger"}: wallet_node_2.config["required_notification_amount"] = 750000000000 if case == "allow_larger": AMOUNT = uint64(1000000000000) diff --git a/chia/_tests/wallet/test_wallet_node.py b/chia/_tests/wallet/test_wallet_node.py index 26b8b9aeb739..712a28dfabd9 100644 --- a/chia/_tests/wallet/test_wallet_node.py +++ b/chia/_tests/wallet/test_wallet_node.py @@ -300,7 +300,7 @@ def test_get_last_used_fingerprint_file_doesnt_exist(root_path_populated_with_co def test_get_last_used_fingerprint_file_cant_read_unix(root_path_populated_with_config: Path) -> None: - if sys.platform in ["win32", "cygwin"]: + if sys.platform in {"win32", "cygwin"}: pytest.skip("Setting UNIX file permissions doesn't apply to Windows") root_path = root_path_populated_with_config @@ -332,7 +332,7 @@ def test_get_last_used_fingerprint_file_cant_read_unix(root_path_populated_with_ def test_get_last_used_fingerprint_file_cant_read_win32( root_path_populated_with_config: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - if sys.platform not in ["win32", "cygwin"]: + if sys.platform not in {"win32", "cygwin"}: pytest.skip("Windows-specific test") called_read_text = False diff --git a/chia/_tests/wallet/vc_wallet/test_vc_lifecycle.py b/chia/_tests/wallet/vc_wallet/test_vc_lifecycle.py index 5ddeeeb7a7e3..68c94cd4ec37 100644 --- a/chia/_tests/wallet/vc_wallet/test_vc_lifecycle.py +++ b/chia/_tests/wallet/vc_wallet/test_vc_lifecycle.py @@ -716,7 +716,7 @@ async def test_vc_lifecycle(test_syncing: bool, cost_logger: CostLogger) -> None 62, ( cr_1.expected_announcement() - if error not in ["use_malicious_cats", "attempt_honest_cat_piggyback"] + if error not in {"use_malicious_cats", "attempt_honest_cat_piggyback"} else malicious_cr_1.expected_announcement() ), ], @@ -724,7 +724,7 @@ async def test_vc_lifecycle(test_syncing: bool, cost_logger: CostLogger) -> None 62, ( cr_2.expected_announcement() - if error not in ["use_malicious_cats", "attempt_honest_cat_piggyback"] + if error not in {"use_malicious_cats", "attempt_honest_cat_piggyback"} else malicious_cr_2.expected_announcement() ), ], @@ -755,7 +755,7 @@ async def test_vc_lifecycle(test_syncing: bool, cost_logger: CostLogger) -> None else: vc = new_vc await sim.farm_block() - elif error in ["forget_vc", "use_malicious_cats", "attempt_honest_cat_piggyback"]: + elif error in {"forget_vc", "use_malicious_cats", "attempt_honest_cat_piggyback"}: assert result == (MempoolInclusionStatus.FAILED, Err.ASSERT_ANNOUNCE_CONSUMED_FAILED) elif error == "make_banned_announcement": assert result == (MempoolInclusionStatus.FAILED, Err.GENERATOR_RUNTIME_ERROR) diff --git a/chia/cmds/cmd_classes.py b/chia/cmds/cmd_classes.py index 0771c10247c7..04462a5a6f36 100644 --- a/chia/cmds/cmd_classes.py +++ b/chia/cmds/cmd_classes.py @@ -205,7 +205,7 @@ def _generate_command_parser(cls: type[ChiaCommand]) -> _CommandParsingStage: click.option( *option_args["param_decls"], type=type_arg, - **{k: v for k, v in option_args.items() if k not in ("param_decls", "type")}, + **{k: v for k, v in option_args.items() if k not in {"param_decls", "type"}}, ) ) diff --git a/chia/cmds/cmds_util.py b/chia/cmds/cmds_util.py index 57f4a6b0f989..96f50dbcd9fa 100644 --- a/chia/cmds/cmds_util.py +++ b/chia/cmds/cmds_util.py @@ -263,7 +263,7 @@ def cli_confirm(input_message: str, abort_message: str = "Did not confirm. Abort Raise a click.Abort if the user does not respond with 'y' or 'yes' """ response = input(input_message).lower() - if response not in ["y", "yes"]: + if response not in {"y", "yes"}: print(abort_message) raise click.Abort() @@ -325,7 +325,7 @@ def _convert_timelock_args_to_cvt(*args: Any, **kwargs: Any) -> None: min_time=uint64.construct_optional(kwargs["valid_at"]), max_time=uint64.construct_optional(kwargs["expires_at"]), ), - **{k: v for k, v in kwargs.items() if k not in ("valid_at", "expires_at")}, + **{k: v for k, v in kwargs.items() if k not in {"valid_at", "expires_at"}}, ) return click.option( diff --git a/chia/cmds/configure.py b/chia/cmds/configure.py index a8d662edf1f7..fd91e6e93a28 100644 --- a/chia/cmds/configure.py +++ b/chia/cmds/configure.py @@ -103,7 +103,7 @@ def configure( print("Target peer count updated") change_made = True if testnet: - if testnet in ("true", "t"): + if testnet in {"true", "t"}: print("Setting Testnet") # check if network_overrides.constants.testnet11 exists if ( @@ -167,7 +167,7 @@ def configure( print("Default full node port, introducer and network setting updated") change_made = True - elif testnet in ("false", "f"): + elif testnet in {"false", "f"}: print("Setting Mainnet") mainnet_port = "8444" mainnet_introducer = "introducer.chia.net" diff --git a/chia/cmds/param_types.py b/chia/cmds/param_types.py index 894129ef817f..0fac199735c7 100644 --- a/chia/cmds/param_types.py +++ b/chia/cmds/param_types.py @@ -171,7 +171,7 @@ def convert(self, value: Any, param: Optional[click.Parameter], ctx: Optional[cl self.fail("Invalid Type, address must be string.", param, ctx) try: hrp, _b32data = bech32_decode(value) - if hrp in ["xch", "txch"]: # I hate having to load the config here + if hrp in {"xch", "txch"}: # I hate having to load the config here addr_type: AddressType = AddressType.XCH expected_prefix = ctx.obj.get("expected_prefix") if ctx else None # attempt to get cached prefix if expected_prefix is None: diff --git a/chia/cmds/plotnft.py b/chia/cmds/plotnft.py index 88366522d689..5fed633d4fb6 100644 --- a/chia/cmds/plotnft.py +++ b/chia/cmds/plotnft.py @@ -76,7 +76,7 @@ def create_cmd( if pool_url is not None and state.lower() == "local": print(f" pool_url argument [{pool_url}] is not allowed when creating in 'local' state") return - if pool_url in [None, ""] and state.lower() == "pool": + if pool_url in {None, ""} and state.lower() == "pool": print(" pool_url argument (-u) is required for pool starting state") return valid_initial_states = {"pool": "FARMING_TO_POOL", "local": "SELF_POOLING"} diff --git a/chia/cmds/wallet_funcs.py b/chia/cmds/wallet_funcs.py index 6e788b25c486..9c43e677f960 100644 --- a/chia/cmds/wallet_funcs.py +++ b/chia/cmds/wallet_funcs.py @@ -836,7 +836,7 @@ async def cancel_offer( def wallet_coin_unit(typ: WalletType, address_prefix: str) -> tuple[str, int]: if typ in {WalletType.CAT, WalletType.CRCAT}: return "", units["cat"] - if typ in [WalletType.STANDARD_WALLET, WalletType.POOLING_WALLET, WalletType.MULTI_SIG]: + if typ in {WalletType.STANDARD_WALLET, WalletType.POOLING_WALLET, WalletType.MULTI_SIG}: return address_prefix, units["chia"] return "", units["mojo"] diff --git a/chia/consensus/constants.py b/chia/consensus/constants.py index c07f1818672b..b7189e79a637 100644 --- a/chia/consensus/constants.py +++ b/chia/consensus/constants.py @@ -20,7 +20,7 @@ def replace_str_to_bytes(constants: ConsensusConstants, **changes: Any) -> Conse for k, v in changes.items(): if not hasattr(constants, k): # NETWORK_TYPE used to be present in default config, but has been removed - if k not in ["NETWORK_TYPE"]: + if k not in {"NETWORK_TYPE"}: log.warning(f'invalid key in network configuration (config.yaml) "{k}". Ignoring') continue if isinstance(v, str): diff --git a/chia/daemon/server.py b/chia/daemon/server.py index 8d71d9e72ec9..36ca9e442986 100644 --- a/chia/daemon/server.py +++ b/chia/daemon/server.py @@ -819,7 +819,7 @@ async def _watch_file_changes(self, config, fp: TextIO, loop: asyncio.AbstractEv if config["state"] is not PlotState.RUNNING: return None - if new_data not in (None, ""): + if new_data not in {None, ""}: config["log"] = new_data if config["log"] is None else config["log"] + new_data config["log_new"] = new_data self.state_changed(service_plotter, self.prepare_plot_state_message(PlotEvent.LOG_CHANGED, id)) @@ -888,7 +888,7 @@ def _chiapos_plotting_command_args(self, request: Any, ignoreCount: bool) -> lis def _bladebit_plotting_command_args(self, request: Any, ignoreCount: bool) -> list[str]: plot_type = request["plot_type"] - if plot_type not in ["ramplot", "diskplot", "cudaplot"]: + if plot_type not in {"ramplot", "diskplot", "cudaplot"}: raise ValueError(f"Unknown plot_type: {plot_type}") command_args: list[str] = [] @@ -1020,7 +1020,7 @@ def _build_plotting_command_args(self, request: Any, ignoreCount: bool, index: i # plotter command must be either # 'chia plotters bladebit ramplot' or 'chia plotters bladebit diskplot' plot_type = request["plot_type"] - assert plot_type in ("diskplot", "ramplot", "cudaplot") + assert plot_type in {"diskplot", "ramplot", "cudaplot"} command_args.append(plot_type) command_args.extend(self._common_plotting_command_args(request, ignoreCount)) diff --git a/chia/data_layer/data_store.py b/chia/data_layer/data_store.py index 2e7688097893..6c5bfa9a43e8 100644 --- a/chia/data_layer/data_store.py +++ b/chia/data_layer/data_store.py @@ -1665,7 +1665,7 @@ async def insert_batch( # We delete all "temporary" records stored in root and ancestor tables and store only the final result. await self.rollback_to_generation(store_id, old_root.generation) await self.insert_root_with_ancestor_table(store_id=store_id, node_hash=root.node_hash, status=status) - if status in (Status.PENDING, Status.PENDING_BATCH): + if status in {Status.PENDING, Status.PENDING_BATCH}: new_root = await self.get_pending_root(store_id=store_id) assert new_root is not None elif status == Status.COMMITTED: diff --git a/chia/full_node/full_node.py b/chia/full_node/full_node.py index f7e1ee20ce5c..6da900d0d976 100644 --- a/chia/full_node/full_node.py +++ b/chia/full_node/full_node.py @@ -1609,7 +1609,7 @@ async def add_prevalidated_blocks( agg_state_change_summary.additions + state_change_summary.additions, agg_state_change_summary.new_rewards + state_change_summary.new_rewards, ) - elif result in (AddBlockResult.INVALID_BLOCK, AddBlockResult.DISCONNECTED_BLOCK): + elif result in {AddBlockResult.INVALID_BLOCK, AddBlockResult.DISCONNECTED_BLOCK}: if error is not None: self.log.error(f"Error: {error}, Invalid block from peer: {peer_info} ") return agg_state_change_summary, error diff --git a/chia/plotters/bladebit.py b/chia/plotters/bladebit.py index 47ec6487318e..79b42bcbe7ad 100644 --- a/chia/plotters/bladebit.py +++ b/chia/plotters/bladebit.py @@ -20,7 +20,7 @@ def is_bladebit_supported() -> bool: # bladebit >= 2.0.0 now supports macOS - return sys.platform.startswith("linux") or sys.platform in ["win32", "cygwin", "darwin"] + return sys.platform.startswith("linux") or sys.platform in {"win32", "cygwin", "darwin"} def meets_memory_requirement(plotters_root_path: Path) -> tuple[bool, Optional[str]]: @@ -83,8 +83,8 @@ def get_bladebit_package_path() -> Path: def get_bladebit_exec_path(with_cuda: bool = False) -> str: if with_cuda: - return "bladebit_cuda.exe" if sys.platform in ["win32", "cygwin"] else "bladebit_cuda" - return "bladebit.exe" if sys.platform in ["win32", "cygwin"] else "bladebit" + return "bladebit_cuda.exe" if sys.platform in {"win32", "cygwin"} else "bladebit_cuda" + return "bladebit.exe" if sys.platform in {"win32", "cygwin"} else "bladebit" def get_bladebit_exec_venv_path(with_cuda: bool = False) -> Optional[Path]: @@ -97,7 +97,7 @@ def get_bladebit_exec_venv_path(with_cuda: bool = False) -> Optional[Path]: def get_bladebit_exec_src_path(plotters_root_path: Path, with_cuda: bool = False) -> Path: bladebit_src_dir = get_bladebit_src_path(plotters_root_path) - build_dir = "build/Release" if sys.platform in ["win32", "cygwin"] else "build" + build_dir = "build/Release" if sys.platform in {"win32", "cygwin"} else "build" bladebit_exec = get_bladebit_exec_path(with_cuda) return bladebit_src_dir / build_dir / bladebit_exec @@ -272,7 +272,7 @@ def plot_bladebit(args, chia_root_path, root_path): print("Bladebit was not found.") return - if sys.platform in ["win32", "cygwin"]: + if sys.platform in {"win32", "cygwin"}: reset_loop_policy_for_windows() plot_keys = asyncio.run( @@ -286,7 +286,7 @@ def plot_bladebit(args, chia_root_path, root_path): args.connect_to_daemon, ) ) - if args.plot_type in ("ramplot", "diskplot", "cudaplot"): + if args.plot_type in {"ramplot", "diskplot", "cudaplot"}: plot_type = args.plot_type else: plot_type = "diskplot" diff --git a/chia/plotters/madmax.py b/chia/plotters/madmax.py index 8ad8de27543f..561a3f26ef94 100644 --- a/chia/plotters/madmax.py +++ b/chia/plotters/madmax.py @@ -18,7 +18,7 @@ def is_madmax_supported() -> bool: - return sys.platform.startswith("linux") or sys.platform in ["darwin", "win32", "cygwin"] + return sys.platform.startswith("linux") or sys.platform in {"darwin", "win32", "cygwin"} def get_madmax_src_path(plotters_root_path: Path) -> Path: @@ -39,7 +39,7 @@ def get_madmax_exec_venv_path(ksize: int = 32) -> Optional[Path]: madmax_exec = "chia_plot" if ksize > 32: madmax_exec += "_k34" # Use the chia_plot_k34 executable for k-sizes > 32 - if sys.platform in ["win32", "cygwin"]: + if sys.platform in {"win32", "cygwin"}: madmax_exec += ".exe" return venv_bin_path / madmax_exec @@ -49,7 +49,7 @@ def get_madmax_exec_src_path(plotters_root_path: Path, ksize: int = 32) -> Path: madmax_exec = "chia_plot" if ksize > 32: madmax_exec += "_k34" # Use the chia_plot_k34 executable for k-sizes > 32 - if sys.platform in ["win32", "cygwin"]: + if sys.platform in {"win32", "cygwin"}: madmax_exec += ".exe" return madmax_src_dir / madmax_exec @@ -59,7 +59,7 @@ def get_madmax_exec_package_path(ksize: int = 32) -> Path: madmax_exec: str = "chia_plot" if ksize > 32: madmax_exec += "_k34" # Use the chia_plot_k34 executable for k-sizes > 32 - if sys.platform in ["win32", "cygwin"]: + if sys.platform in {"win32", "cygwin"}: madmax_exec += ".exe" return madmax_dir / madmax_exec diff --git a/chia/plotters/plotters_util.py b/chia/plotters/plotters_util.py index f58828ce468a..21e87f0088bb 100644 --- a/chia/plotters/plotters_util.py +++ b/chia/plotters/plotters_util.py @@ -60,7 +60,7 @@ def sigint_handler(signum, frame): process.terminate() # For Windows, we'll install a SIGINT handler to catch Ctrl-C (KeyboardInterrupt isn't raised) - if sys.platform in ["win32", "cygwin"]: + if sys.platform in {"win32", "cygwin"}: signal.signal(signal.SIGINT, sigint_handler) installed_sigint_handler = True diff --git a/chia/pools/pool_puzzles.py b/chia/pools/pool_puzzles.py index 8c9844d6f113..43f1679a0bb9 100644 --- a/chia/pools/pool_puzzles.py +++ b/chia/pools/pool_puzzles.py @@ -161,17 +161,17 @@ def get_seconds_and_delayed_puzhash_from_p2_singleton_puzzle(puzzle: Program) -> # Verify that a puzzle is a Pool Wallet Singleton def is_pool_singleton_inner_puzzle(inner_puzzle: Program) -> bool: inner_f = get_template_singleton_inner_puzzle(inner_puzzle) - return inner_f in [POOL_WAITING_ROOM_MOD, POOL_MEMBER_MOD] + return inner_f in {POOL_WAITING_ROOM_MOD, POOL_MEMBER_MOD} def is_pool_waitingroom_inner_puzzle(inner_puzzle: Program) -> bool: inner_f = get_template_singleton_inner_puzzle(inner_puzzle) - return inner_f in [POOL_WAITING_ROOM_MOD] + return inner_f in {POOL_WAITING_ROOM_MOD} def is_pool_member_inner_puzzle(inner_puzzle: Program) -> bool: inner_f = get_template_singleton_inner_puzzle(inner_puzzle) - return inner_f in [POOL_MEMBER_MOD] + return inner_f in {POOL_MEMBER_MOD} # This spend will use the escape-type spend path for whichever state you are currently in @@ -410,7 +410,7 @@ def solution_to_pool_state(full_spend: CoinSpend) -> Optional[PoolState]: # Spend which is not absorb, and is not the launcher num_args = len(inner_solution.as_python()) - assert num_args in (2, 3) + assert num_args in {2, 3} if num_args == 2: # pool member @@ -445,7 +445,7 @@ def pool_state_to_inner_puzzle( delay_time, delay_ph, ) - if pool_state.state in [LEAVING_POOL.value, SELF_POOLING.value]: + if pool_state.state in {LEAVING_POOL.value, SELF_POOLING.value}: return escaping_inner_puzzle else: return create_pooling_inner_puzzle( diff --git a/chia/pools/pool_wallet.py b/chia/pools/pool_wallet.py index 9013a51ca924..395268786aec 100644 --- a/chia/pools/pool_wallet.py +++ b/chia/pools/pool_wallet.py @@ -137,7 +137,7 @@ def id(self) -> uint32: @classmethod def _verify_self_pooled(cls, state: PoolState) -> Optional[str]: err = "" - if state.pool_url not in [None, ""]: + if state.pool_url not in {None, ""}: err += " Unneeded pool_url for self-pooling" if state.relative_lock_height != 0: @@ -159,7 +159,7 @@ def _verify_pooling_state(cls, state: PoolState) -> Optional[str]: f"is greater than recommended maximum ({cls.MAXIMUM_RELATIVE_LOCK_HEIGHT})" ) - if state.pool_url in [None, ""]: + if state.pool_url in {None, ""}: err += " Empty pool url in pooling state" return err @@ -177,7 +177,7 @@ def _verify_pool_state(cls, state: PoolState) -> Optional[str]: if state.state == PoolSingletonState.SELF_POOLING.value: return cls._verify_self_pooled(state) - elif state.state in (PoolSingletonState.FARMING_TO_POOL.value, PoolSingletonState.LEAVING_POOL.value): + elif state.state in {PoolSingletonState.FARMING_TO_POOL.value, PoolSingletonState.LEAVING_POOL.value}: return cls._verify_pooling_state(state) else: return "Internal Error" @@ -660,7 +660,7 @@ async def join_pool(self, target_state: PoolState, fee: uint64, action_scope: Wa msg = f"Asked to change to current state. Target = {target_state}" self.log.info(msg) raise ValueError(msg) - elif current_state.current.state in [SELF_POOLING.value, LEAVING_POOL.value]: + elif current_state.current.state in {SELF_POOLING.value, LEAVING_POOL.value}: total_fee = fee elif current_state.current.state == FARMING_TO_POOL.value: total_fee = uint64(fee * 2) @@ -843,7 +843,7 @@ async def new_peak(self, peak_height: uint32) -> None: raise ValueError(f"Internal error. Pool wallet {self.wallet_id} state: {pool_wallet_info.current}") if ( - self.target_state.state in [FARMING_TO_POOL.value, SELF_POOLING.value] + self.target_state.state in {FARMING_TO_POOL.value, SELF_POOLING.value} and pool_wallet_info.current.state == LEAVING_POOL.value ): leave_height = tip_height + pool_wallet_info.current.relative_lock_height diff --git a/chia/rpc/crawler_rpc_api.py b/chia/rpc/crawler_rpc_api.py index eb55c23841af..0fcd3fbc6833 100644 --- a/chia/rpc/crawler_rpc_api.py +++ b/chia/rpc/crawler_rpc_api.py @@ -30,7 +30,7 @@ async def _state_changed(self, change: str, change_data: Optional[dict[str, Any] if change_data is None: change_data = await self.get_peer_counts({}) - if change in ("crawl_batch_completed", "loaded_initial_peers"): + if change in {"crawl_batch_completed", "loaded_initial_peers"}: payloads.append(create_payload_dict(change, change_data, self.service_name, "metrics")) return payloads diff --git a/chia/rpc/full_node_rpc_api.py b/chia/rpc/full_node_rpc_api.py index 73cbc802739a..ecebe009328b 100644 --- a/chia/rpc/full_node_rpc_api.py +++ b/chia/rpc/full_node_rpc_api.py @@ -132,7 +132,7 @@ async def _state_changed(self, change: str, change_data: Optional[dict[str, Any] change_data = {} payloads = [] - if change in ("new_peak", "sync_mode"): + if change in {"new_peak", "sync_mode"}: data = await self.get_blockchain_state({}) assert data is not None payloads.append( @@ -152,7 +152,7 @@ async def _state_changed(self, change: str, change_data: Optional[dict[str, Any] ) ) - if change in ("block", "signage_point"): + if change in {"block", "signage_point"}: payloads.append(create_payload_dict(change, change_data, self.service_name, "metrics")) if change == "unfinished_block": diff --git a/chia/rpc/rpc_server.py b/chia/rpc/rpc_server.py index fb316a4783ea..f8a4d73548dc 100644 --- a/chia/rpc/rpc_server.py +++ b/chia/rpc/rpc_server.py @@ -202,7 +202,7 @@ async def _state_changed(self, change: str, change_data: Optional[dict[str, Any] return None payloads: list[WsRpcMessage] = await self.rpc_api._state_changed(change, change_data) - if change in ("add_connection", "close_connection", "peer_changed_peak"): + if change in {"add_connection", "close_connection", "peer_changed_peak"}: data = await self.get_connections({}) if data is not None: payload = create_payload_dict( diff --git a/chia/rpc/timelord_rpc_api.py b/chia/rpc/timelord_rpc_api.py index 4141fe962679..9633909d4bbd 100644 --- a/chia/rpc/timelord_rpc_api.py +++ b/chia/rpc/timelord_rpc_api.py @@ -26,7 +26,7 @@ async def _state_changed(self, change: str, change_data: Optional[dict[str, Any] if change_data is None: change_data = {} - if change in ("finished_pot", "new_compact_proof", "skipping_peak", "new_peak"): + if change in {"finished_pot", "new_compact_proof", "skipping_peak", "new_peak"}: payloads.append(create_payload_dict(change, change_data, self.service_name, "metrics")) return payloads diff --git a/chia/rpc/util.py b/chia/rpc/util.py index 9c57ae4c153d..35182756dea1 100644 --- a/chia/rpc/util.py +++ b/chia/rpc/util.py @@ -209,7 +209,7 @@ async def rpc_endpoint( if ( func.__name__ == "create_new_wallet" and request["wallet_type"] == "pool_wallet" - or func.__name__ in ("pw_join_pool", "pw_self_pool", "pw_absorb_rewards") + or func.__name__ in {"pw_join_pool", "pw_self_pool", "pw_absorb_rewards"} ): # Theses RPCs return not "convenience" for some reason response["transaction"] = new_txs[-1].to_json_dict() diff --git a/chia/rpc/wallet_rpc_api.py b/chia/rpc/wallet_rpc_api.py index 9348adab20e5..9babbee8f379 100644 --- a/chia/rpc/wallet_rpc_api.py +++ b/chia/rpc/wallet_rpc_api.py @@ -1785,7 +1785,7 @@ async def verify_signature(self, request: dict[str, Any]) -> EndpointResult: except ValueError: raise ValueError(f"Invalid signing mode: {signing_mode_str!r}") - if signing_mode in (SigningMode.CHIP_0002, SigningMode.CHIP_0002_P2_DELEGATED_CONDITIONS): + if signing_mode in {SigningMode.CHIP_0002, SigningMode.CHIP_0002_P2_DELEGATED_CONDITIONS}: # CHIP-0002 message signatures are made over the tree hash of: # ("Chia Signed Message", message) message_to_verify: bytes = Program.to((CHIP_0002_SIGN_MESSAGE_PREFIX, input_message)).get_tree_hash() @@ -2149,12 +2149,12 @@ async def get_offer_summary(self, request: dict[str, Any]) -> EndpointResult: k: v for k, v in valid_times.to_json_dict().items() if k - not in ( + not in { "max_secs_after_created", "min_secs_since_created", "max_blocks_after_created", "min_blocks_since_created", - ) + } }, }, "id": offer.name(), @@ -2963,7 +2963,7 @@ async def dao_add_funds_to_treasury( wallet_type = self.service.wallet_state_manager.wallets[funding_wallet_id].type() amount = request.get("amount") assert amount - if wallet_type not in [WalletType.STANDARD_WALLET, WalletType.CAT]: # pragma: no cover + if wallet_type not in {WalletType.STANDARD_WALLET, WalletType.CAT}: # pragma: no cover raise ValueError(f"Cannot fund a treasury with assets from a {wallet_type.name} wallet") await dao_wallet.create_add_funds_to_treasury_spend( uint64(amount), @@ -3815,7 +3815,7 @@ async def nft_mint_bulk( royalty_address = request.get("royalty_address", None) if isinstance(royalty_address, str) and royalty_address != "": royalty_puzhash = decode_puzzle_hash(royalty_address) - elif royalty_address in [None, ""]: + elif royalty_address in {None, ""}: royalty_puzhash = await nft_wallet.standard_wallet.get_new_puzzlehash() else: royalty_puzhash = bytes32.from_hexstr(royalty_address) diff --git a/chia/seeder/dns_server.py b/chia/seeder/dns_server.py index 9c9ac3708b5f..2f37e6966ba6 100644 --- a/chia/seeder/dns_server.py +++ b/chia/seeder/dns_server.py @@ -504,7 +504,7 @@ async def dns_response(self, request: DNSRecord) -> DNSRecord: valid_domain = True for response in domain_responses: rqt: int = getattr(QTYPE, response.__class__.__name__) - if question_type in (rqt, QTYPE.ANY): + if question_type in {rqt, QTYPE.ANY}: reply.add_answer(RR(rname=qname, rtype=rqt, rclass=1, ttl=ttl, rdata=response)) if not valid_domain and len(reply.rr) == 0: # if we didn't find any records to return reply.header.rcode = RCODE.NXDOMAIN diff --git a/chia/server/chia_policy.py b/chia/server/chia_policy.py index 6073f69c173e..3d0648b2f02f 100644 --- a/chia/server/chia_policy.py +++ b/chia/server/chia_policy.py @@ -261,10 +261,10 @@ async def _chia_accept_loop(self, listener: socket.socket) -> tuple[socket.socke try: return await self._chia_accept(listener) except OSError as exc: - if exc.winerror not in ( + if exc.winerror not in { _winapi.ERROR_NETNAME_DELETED, _winapi.ERROR_OPERATION_ABORTED, - ): + }: raise def _chia_accept(self, listener: socket.socket) -> asyncio.Future[tuple[socket.socket, tuple[object, ...]]]: @@ -292,10 +292,10 @@ async def accept_coro(self: ChiaProactor, future: asyncio.Future[object], conn: raise except OSError as exc: # https://github.com/python/cpython/issues/93821#issuecomment-1157945855 - if exc.winerror not in ( + if exc.winerror not in { _winapi.ERROR_NETNAME_DELETED, _winapi.ERROR_OPERATION_ABORTED, - ): + }: raise future = self._register(ov, listener, finish_accept) diff --git a/chia/server/server.py b/chia/server/server.py index 6c98cafcf584..8e3dec10fa56 100644 --- a/chia/server/server.py +++ b/chia/server/server.py @@ -254,7 +254,7 @@ async def garbage_collect_connections_task(self) -> None: if connection.closed: to_remove.append(connection) elif ( - self._local_type in (NodeType.FULL_NODE, NodeType.WALLET) + self._local_type in {NodeType.FULL_NODE, NodeType.WALLET} ) and connection.connection_type == NodeType.FULL_NODE: if is_crawler is not None: if time.time() - connection.creation_time > 5: diff --git a/chia/server/ws_connection.py b/chia/server/ws_connection.py index ddfff06972aa..7c51e8b39e27 100644 --- a/chia/server/ws_connection.py +++ b/chia/server/ws_connection.py @@ -226,7 +226,7 @@ async def perform_handshake( raise ProtocolError(Err.INCOMPATIBLE_NETWORK_ID) if ( - local_type in [NodeType.FARMER, NodeType.HARVESTER] + local_type in {NodeType.FARMER, NodeType.HARVESTER} and inbound_handshake.protocol_version != protocol_version[local_type] ): self.log.warning( @@ -267,7 +267,7 @@ async def perform_handshake( remote_node_type = NodeType(inbound_handshake.node_type) if ( - remote_node_type in [NodeType.FARMER, NodeType.HARVESTER] + remote_node_type in {NodeType.FARMER, NodeType.HARVESTER} and inbound_handshake.protocol_version != protocol_version[remote_node_type] ): self.log.warning( diff --git a/chia/simulator/block_tools.py b/chia/simulator/block_tools.py index 23726b989d16..c1927d6a1bd9 100644 --- a/chia/simulator/block_tools.py +++ b/chia/simulator/block_tools.py @@ -1908,7 +1908,7 @@ def conditions_cost(conds: Program) -> uint64: elif condition == ConditionOpcode.SOFTFORK.value: arg = cond.rest().first().as_int() condition_cost += arg * 10000 - elif condition in [ + elif condition in { ConditionOpcode.AGG_SIG_UNSAFE, ConditionOpcode.AGG_SIG_ME, ConditionOpcode.AGG_SIG_PARENT, @@ -1917,7 +1917,7 @@ def conditions_cost(conds: Program) -> uint64: ConditionOpcode.AGG_SIG_PUZZLE_AMOUNT, ConditionOpcode.AGG_SIG_PARENT_AMOUNT, ConditionOpcode.AGG_SIG_PARENT_PUZZLE, - ]: + }: condition_cost += ConditionCost.AGG_SIG.value return uint64(condition_cost) diff --git a/chia/timelord/timelord_state.py b/chia/timelord/timelord_state.py index a162f4977b46..a431565a5cbc 100644 --- a/chia/timelord/timelord_state.py +++ b/chia/timelord/timelord_state.py @@ -121,7 +121,7 @@ def can_infuse_block(self, overflow: bool) -> bool: if overflow and self.new_epoch: # No overflows in new epoch return False - if self.state_type in (StateType.FIRST_SUB_SLOT, StateType.END_OF_SUB_SLOT): + if self.state_type in {StateType.FIRST_SUB_SLOT, StateType.END_OF_SUB_SLOT}: return True ss_start_iters = self.get_total_iters() - self.get_last_ip() already_infused_count: int = 0 @@ -160,7 +160,7 @@ def just_infused_sub_epoch_summary(self) -> bool: return self.state_type == StateType.END_OF_SUB_SLOT and self.infused_ses def get_next_sub_epoch_summary(self) -> Optional[SubEpochSummary]: - if self.state_type in (StateType.FIRST_SUB_SLOT, StateType.END_OF_SUB_SLOT): + if self.state_type in {StateType.FIRST_SUB_SLOT, StateType.END_OF_SUB_SLOT}: # Can only infuse SES after a peak (in an end of sub slot) return None assert self.peak is not None @@ -233,7 +233,7 @@ def get_initial_form(self, chain: Chain) -> Optional[ClassgroupElement]: else: return None elif self.state_type == StateType.END_OF_SUB_SLOT: - if chain in (Chain.CHALLENGE_CHAIN, Chain.REWARD_CHAIN): + if chain in {Chain.CHALLENGE_CHAIN, Chain.REWARD_CHAIN}: return ClassgroupElement.get_default_element() if chain == Chain.INFUSED_CHALLENGE_CHAIN: assert self.subslot_end is not None diff --git a/chia/types/coin_spend.py b/chia/types/coin_spend.py index 97c0fd28b842..e9da832b6910 100644 --- a/chia/types/coin_spend.py +++ b/chia/types/coin_spend.py @@ -63,7 +63,7 @@ def compute_additions_with_cost( raise ValidationError(Err.BLOCK_COST_EXCEEDS_MAX, "compute_additions() for CoinSpend") atoms = cond.as_iter() op = next(atoms).atom - if op in [ + if op in { ConditionOpcode.AGG_SIG_PARENT, ConditionOpcode.AGG_SIG_PUZZLE, ConditionOpcode.AGG_SIG_AMOUNT, @@ -72,7 +72,7 @@ def compute_additions_with_cost( ConditionOpcode.AGG_SIG_PARENT_PUZZLE, ConditionOpcode.AGG_SIG_UNSAFE, ConditionOpcode.AGG_SIG_ME, - ]: + }: cost += ConditionCost.AGG_SIG.value continue if op != ConditionOpcode.CREATE_COIN.value: diff --git a/chia/util/config.py b/chia/util/config.py index 60bae857ef26..2859d4b6655e 100644 --- a/chia/util/config.py +++ b/chia/util/config.py @@ -221,9 +221,9 @@ def str2bool(v: Union[str, bool]) -> bool: # Source from https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse if isinstance(v, bool): return v - if v.lower() in ("yes", "true", "True", "t", "y", "1"): + if v.lower() in {"yes", "true", "True", "t", "y", "1"}: return True - elif v.lower() in ("no", "false", "False", "f", "n", "0"): + elif v.lower() in {"no", "false", "False", "f", "n", "0"}: return False else: raise argparse.ArgumentTypeError("Boolean value expected.") diff --git a/chia/util/full_block_utils.py b/chia/util/full_block_utils.py index daacaf852433..812b10614ae2 100644 --- a/chia/util/full_block_utils.py +++ b/chia/util/full_block_utils.py @@ -56,7 +56,7 @@ def skip_uint8(buf: memoryview) -> memoryview: def skip_bool(buf: memoryview) -> memoryview: - assert buf[0] in [0, 1] + assert buf[0] in {0, 1} return buf[1:] diff --git a/chia/util/keychain.py b/chia/util/keychain.py index 0b835731dd10..7545e56398bd 100644 --- a/chia/util/keychain.py +++ b/chia/util/keychain.py @@ -41,7 +41,7 @@ def supports_os_passphrase_storage() -> bool: - return sys.platform in ["darwin", "win32", "cygwin"] + return sys.platform in {"darwin", "win32", "cygwin"} def passphrase_requirements() -> dict[str, Any]: @@ -71,7 +71,7 @@ def generate_mnemonic() -> str: def bytes_to_mnemonic(mnemonic_bytes: bytes) -> str: - if len(mnemonic_bytes) not in [16, 20, 24, 28, 32]: + if len(mnemonic_bytes) not in {16, 20, 24, 28, 32}: raise ValueError( f"Data length should be one of the following: [16, 20, 24, 28, 32], but it is {len(mnemonic_bytes)}." ) @@ -97,7 +97,7 @@ def bytes_to_mnemonic(mnemonic_bytes: bytes) -> str: def check_mnemonic_validity(mnemonic_str: str) -> bool: mnemonic: list[str] = mnemonic_str.split(" ") - return len(mnemonic) in [12, 15, 18, 21, 24] + return len(mnemonic) in {12, 15, 18, 21, 24} def mnemonic_from_short_words(mnemonic_str: str) -> str: @@ -107,7 +107,7 @@ def mnemonic_from_short_words(mnemonic_str: str) -> str: up words by the first 4 characters """ mnemonic: list[str] = mnemonic_str.split(" ") - if len(mnemonic) not in [12, 15, 18, 21, 24]: + if len(mnemonic) not in {12, 15, 18, 21, 24}: raise ValueError("Invalid mnemonic length") four_char_dict = {word[:4]: word for word in bip39_word_list().splitlines()} diff --git a/chia/util/network.py b/chia/util/network.py index 614d2db1f262..6bc1ae94673b 100644 --- a/chia/util/network.py +++ b/chia/util/network.py @@ -128,7 +128,7 @@ def is_trusted_cidr(peer_host: str, trusted_cidrs: list[str]) -> bool: def is_localhost(peer_host: str) -> bool: - return peer_host in ["127.0.0.1", "localhost", "::1", "0:0:0:0:0:0:0:1"] + return peer_host in {"127.0.0.1", "localhost", "::1", "0:0:0:0:0:0:0:1"} def is_trusted_peer( diff --git a/chia/util/profiler.py b/chia/util/profiler.py index 80973293aedd..dc480fd70e4a 100644 --- a/chia/util/profiler.py +++ b/chia/util/profiler.py @@ -143,7 +143,7 @@ def analyze_slot_range(profile_dir: pathlib.Path, first: int, last: int) -> None if len(sys.argv) == 2: # this analyzes the CPU usage at all slots saved to the profiler directory analyze_cpu_usage(profile_dir) - elif len(sys.argv) in [3, 4]: + elif len(sys.argv) in {3, 4}: # the additional arguments are interpreted as either one slot, or a # slot range (first and last) to analyze first = int(sys.argv[2]) diff --git a/chia/util/task_timing.py b/chia/util/task_timing.py index 0abf63bbf586..02a7670f9fed 100644 --- a/chia/util/task_timing.py +++ b/chia/util/task_timing.py @@ -163,7 +163,7 @@ def get_file(frame: FrameType) -> str: def trace_fun(frame: FrameType, event: str, arg: Any) -> None: - if event in ["c_call", "c_return", "c_exception"]: + if event in {"c_call", "c_return", "c_exception"}: return # we only care about instrumenting co-routines diff --git a/chia/wallet/conditions.py b/chia/wallet/conditions.py index 57a7539ea46e..a2c2bd9679b4 100644 --- a/chia/wallet/conditions.py +++ b/chia/wallet/conditions.py @@ -812,7 +812,7 @@ def from_program(cls, program: Program, **kwargs: Optional[Union[uint64, bytes32 condition_driver.pubkey, # type: ignore[attr-defined] condition_driver.msg, # type: ignore[attr-defined] opcode, - **{key: value for key, value in condition_driver.__dict__.items() if key not in ["pubkey", "msg"]}, + **{key: value for key, value in condition_driver.__dict__.items() if key not in {"pubkey", "msg"}}, ) diff --git a/chia/wallet/trade_manager.py b/chia/wallet/trade_manager.py index 5cb2cc02836f..704492408eaa 100644 --- a/chia/wallet/trade_manager.py +++ b/chia/wallet/trade_manager.py @@ -852,7 +852,7 @@ async def respond_to_offer( wallet = await self.wallet_state_manager.get_wallet_for_asset_id(asset_id.hex()) if wallet is None and amount < 0: raise ValueError(f"Do not have a wallet for asset ID: {asset_id} to fulfill offer") - elif wallet is None or wallet.type() in [WalletType.NFT, WalletType.DATA_LAYER]: + elif wallet is None or wallet.type() in {WalletType.NFT, WalletType.DATA_LAYER}: key = asset_id else: key = int(wallet.id()) @@ -999,12 +999,12 @@ async def get_offer_summary(self, offer: Offer) -> dict[str, Any]: k: v for k, v in valid_times.to_json_dict().items() if k - not in ( + not in { "max_secs_after_created", "min_secs_since_created", "max_blocks_after_created", "min_blocks_since_created", - ) + } }, } diff --git a/chia/wallet/transaction_record.py b/chia/wallet/transaction_record.py index 5ccbdb551fec..ca26718078d8 100644 --- a/chia/wallet/transaction_record.py +++ b/chia/wallet/transaction_record.py @@ -60,14 +60,14 @@ class TransactionRecordOld(Streamable): def is_in_mempool(self) -> bool: # If one of the nodes we sent it to responded with success or pending, we return True for _, mis, _ in self.sent_to: - if MempoolInclusionStatus(mis) in (MempoolInclusionStatus.SUCCESS, MempoolInclusionStatus.PENDING): + if MempoolInclusionStatus(mis) in {MempoolInclusionStatus.SUCCESS, MempoolInclusionStatus.PENDING}: return True return False def height_farmed(self, genesis_challenge: bytes32) -> Optional[uint32]: if not self.confirmed: return None - if self.type in (TransactionType.FEE_REWARD, TransactionType.COINBASE_REWARD): + if self.type in {TransactionType.FEE_REWARD, TransactionType.COINBASE_REWARD}: for block_index in range(self.confirmed_at_height, self.confirmed_at_height - 100, -1): if block_index < 0: return None @@ -131,7 +131,7 @@ def is_valid(self) -> bool: if any(x[1] == MempoolInclusionStatus.SUCCESS for x in self.sent_to): # we managed to push it to mempool at least once return True - if any(x[2] in (Err.INVALID_FEE_LOW_FEE.name, Err.INVALID_FEE_TOO_CLOSE_TO_ZERO.name) for x in self.sent_to): + if any(x[2] in {Err.INVALID_FEE_LOW_FEE.name, Err.INVALID_FEE_TOO_CLOSE_TO_ZERO.name} for x in self.sent_to): # we tried to push it to mempool and got a fee error so it's a temporary error return True return False diff --git a/chia/wallet/util/compute_hints.py b/chia/wallet/util/compute_hints.py index 18981d5594ce..b6fca6656822 100644 --- a/chia/wallet/util/compute_hints.py +++ b/chia/wallet/util/compute_hints.py @@ -33,7 +33,7 @@ def compute_spend_hints_and_additions( raise ValidationError(Err.BLOCK_COST_EXCEEDS_MAX, "compute_spend_hints_and_additions() for CoinSpend") atoms = condition.as_iter() op = next(atoms).atom - if op in [ + if op in { ConditionOpcode.AGG_SIG_PARENT, ConditionOpcode.AGG_SIG_PUZZLE, ConditionOpcode.AGG_SIG_AMOUNT, @@ -42,7 +42,7 @@ def compute_spend_hints_and_additions( ConditionOpcode.AGG_SIG_PARENT_PUZZLE, ConditionOpcode.AGG_SIG_UNSAFE, ConditionOpcode.AGG_SIG_ME, - ]: + }: cost += ConditionCost.AGG_SIG.value continue if op != ConditionOpcode.CREATE_COIN.value: diff --git a/chia/wallet/wallet.py b/chia/wallet/wallet.py index ac61c0cad843..96dfbdab3566 100644 --- a/chia/wallet/wallet.py +++ b/chia/wallet/wallet.py @@ -312,7 +312,7 @@ async def _generate_unsigned_transaction( raise ValueError("Cannot create two identical coins") for coin in coins: # Only one coin creates outputs - if origin_id in (None, coin.name()): + if origin_id in {None, coin.name()}: origin_id = coin.name() inner_puzzle = await self.puzzle_for_puzzle_hash(coin.puzzle_hash) decorated_target_puzzle_hash = decorator_manager.decorate_target_puzzle_hash( diff --git a/chia/wallet/wallet_state_manager.py b/chia/wallet/wallet_state_manager.py index d26ba2c20567..52ca376a0320 100644 --- a/chia/wallet/wallet_state_manager.py +++ b/chia/wallet/wallet_state_manager.py @@ -1981,7 +1981,7 @@ async def _add_coin_states( unconfirmed_record.name, uint32(coin_state.spent_height) ) - if record.wallet_type in [WalletType.POOLING_WALLET, WalletType.DAO]: + if record.wallet_type in {WalletType.POOLING_WALLET, WalletType.DAO}: wallet_type_to_class = {WalletType.POOLING_WALLET: PoolWallet, WalletType.DAO: DAOWallet} if coin_state.spent_height is not None and coin_state.coin.amount == uint64(1): singleton_wallet: Union[PoolWallet, DAOWallet] = self.get_wallet( @@ -2384,18 +2384,18 @@ async def remove_from_queue( if ( send_status != MempoolInclusionStatus.SUCCESS and error - and error not in (Err.INVALID_FEE_LOW_FEE, Err.INVALID_FEE_TOO_CLOSE_TO_ZERO) + and error not in {Err.INVALID_FEE_LOW_FEE, Err.INVALID_FEE_TOO_CLOSE_TO_ZERO} ): coins_removed = tx.spend_bundle.removals() trade_coins_removed = set() trades = [] for removed_coin in coins_removed: trade = await self.trade_manager.get_trade_by_coin(removed_coin) - if trade is not None and trade.status in ( + if trade is not None and trade.status in { TradeStatus.PENDING_CONFIRM.value, TradeStatus.PENDING_ACCEPT.value, TradeStatus.PENDING_CANCEL.value, - ): + }: if trade not in trades: trades.append(trade) # offer was tied to these coins, lets subscribe to them to get a confirmation to @@ -2464,14 +2464,14 @@ async def reorg_rollback(self, height: int) -> list[uint32]: reorged: list[TransactionRecord] = await self.tx_store.get_transaction_above(height) await self.tx_store.rollback_to_block(height) for record in reorged: - if TransactionType(record.type) in [ + if TransactionType(record.type) in { TransactionType.OUTGOING_TX, TransactionType.OUTGOING_TRADE, TransactionType.INCOMING_TRADE, TransactionType.OUTGOING_CLAWBACK, TransactionType.INCOMING_CLAWBACK_SEND, TransactionType.INCOMING_CLAWBACK_RECEIVE, - ]: + }: await self.tx_store.tx_reorged(record) # Removes wallets that were created from a blockchain transaction which got reorged. @@ -2499,7 +2499,7 @@ async def get_all_wallet_info_entries(self, wallet_type: Optional[WalletType] = async def get_wallet_for_asset_id(self, asset_id: str) -> Optional[WalletProtocol[Any]]: for wallet_id, wallet in self.wallets.items(): - if wallet.type() in (WalletType.CAT, WalletType.CRCAT): + if wallet.type() in {WalletType.CAT, WalletType.CRCAT}: assert isinstance(wallet, CATWallet) if wallet.get_asset_id() == asset_id: return wallet @@ -2618,7 +2618,7 @@ async def delete_trade_transactions(self, trade_id: bytes32) -> None: async def convert_puzzle_hash(self, wallet_id: uint32, puzzle_hash: bytes32) -> bytes32: wallet = self.wallets[wallet_id] # This should be general to wallets but for right now this is just for CATs so we'll add this if - if wallet.type() in (WalletType.CAT.value, WalletType.CRCAT.value): + if wallet.type() in {WalletType.CAT.value, WalletType.CRCAT.value}: assert isinstance(wallet, CATWallet) return await wallet.convert_puzzle_hash(puzzle_hash) diff --git a/ruff.toml b/ruff.toml index 6f620fafa683..099b5825db0b 100644 --- a/ruff.toml +++ b/ruff.toml @@ -16,9 +16,9 @@ explicit-preview-rules = false ignore = [ # Pylint convention "PLC0415", # import-outside-top-level (286) (x) - "PLC2801", # unnecessary-dunder-call (11) (x) + "PLC2801", # unnecessary-dunder-call (11) (*) "PLC1901", # compare-to-empty-string (51) (x) - "PLC2701", # import-private-name (24) (x) + "PLC2701", # import-private-name (24) (*) # Pylint refactor "PLR0915", # too-many-statements (222) (x) @@ -31,7 +31,6 @@ ignore = [ "PLR0916", # too-many-boolean-expressions (3) (x) "PLR0911", # too-many-return-statements (52) (x) "PLR6301", # no-self-use (699) (-) - "PLR6201", # literal-membership (86) (?) "PLR2004", # magic-value-comparison (901) (-) "PLR6104", # non-augmented-assignment (27) (?) "PLR1704", # redefined-argument-from-local (13) (-) diff --git a/tools/chialispp.py b/tools/chialispp.py index 09f88f598883..d8398e4a0e9d 100644 --- a/tools/chialispp.py +++ b/tools/chialispp.py @@ -120,7 +120,7 @@ def output_line(self) -> None: if self.getting_form_name == 1 and not (ch == b" "): self.getting_form_name = 2 self.form_name.append(ch) - elif self.getting_form_name == 2 and ch in (b" ", b"(", b")"): + elif self.getting_form_name == 2 and ch in {b" ", b"(", b")"}: self.getting_form_name = 0 self.got_form_on_line = self.cur_line else: @@ -151,7 +151,7 @@ def output_line(self) -> None: if semis == 0: # We've entered a string, stop processing - if ch in (b"'", b'"'): + if ch in {b"'", b'"'}: in_string = ch continue elif ch == b"(": diff --git a/tools/generate_chain.py b/tools/generate_chain.py index 5c4c4a9acae9..95c1ecf02f19 100644 --- a/tools/generate_chain.py +++ b/tools/generate_chain.py @@ -112,7 +112,7 @@ def main(length: int, fill_rate: int, profile: bool, block_refs: bool, output: O for b in blocks: for coin in b.get_included_reward_coins(): - if coin.puzzle_hash in [farmer_puzzlehash, pool_puzzlehash]: + if coin.puzzle_hash in {farmer_puzzlehash, pool_puzzlehash}: unspent_coins.append(coin) db.execute( "INSERT INTO full_blocks VALUES(?, ?, ?, ?, ?)", From 1f4348f93e536cfaaeeb2c3c02abcc3e741119f5 Mon Sep 17 00:00:00 2001 From: Kyle Altendorf Date: Thu, 7 Nov 2024 15:04:55 -0500 Subject: [PATCH 05/12] enable non-augmented-assignment --- chia/_tests/core/make_block_generator.py | 2 +- chia/_tests/core/server/test_capabilities.py | 2 +- chia/_tests/core/test_full_node_rpc.py | 2 +- chia/_tests/farmer_harvester/test_farmer_harvester.py | 2 +- chia/_tests/plotting/util.py | 2 +- chia/consensus/blockchain.py | 2 +- chia/data_layer/data_layer.py | 2 +- chia/full_node/fee_tracker.py | 4 ++-- chia/full_node/mempool_check_conditions.py | 2 +- chia/full_node/mempool_manager.py | 4 ++-- chia/full_node/weight_proof.py | 10 ++++------ chia/plot_sync/sender.py | 2 +- chia/server/address_manager.py | 4 ++-- chia/simulator/full_node_simulator.py | 4 +--- chia/wallet/cat_wallet/dao_cat_wallet.py | 4 ++-- chia/wallet/dao_wallet/dao_wallet.py | 6 +++--- chia/wallet/derive_keys.py | 2 +- chia/wallet/wallet_node.py | 2 +- ruff.toml | 1 - 19 files changed, 27 insertions(+), 32 deletions(-) diff --git a/chia/_tests/core/make_block_generator.py b/chia/_tests/core/make_block_generator.py index bad98496b2d9..67fafaaa7e9b 100644 --- a/chia/_tests/core/make_block_generator.py +++ b/chia/_tests/core/make_block_generator.py @@ -18,7 +18,7 @@ def int_to_public_key(index: int) -> G1Element: - index = index % GROUP_ORDER + index %= GROUP_ORDER private_key_from_int = PrivateKey.from_bytes(index.to_bytes(32, "big")) return private_key_from_int.get_g1() diff --git a/chia/_tests/core/server/test_capabilities.py b/chia/_tests/core/server/test_capabilities.py index 564cf9867faf..5fd9c0264fb8 100644 --- a/chia/_tests/core/server/test_capabilities.py +++ b/chia/_tests/core/server/test_capabilities.py @@ -57,7 +57,7 @@ def test_known_active_capabilities_filter( disabled: bool, ) -> None: if duplicated: - values = values * 2 + values *= 2 if disabled: values = [(value, "0") for value, state in values] diff --git a/chia/_tests/core/test_full_node_rpc.py b/chia/_tests/core/test_full_node_rpc.py index 179d515ce13d..b8fdb3a4e4b5 100644 --- a/chia/_tests/core/test_full_node_rpc.py +++ b/chia/_tests/core/test_full_node_rpc.py @@ -213,7 +213,7 @@ async def test1(two_nodes_sim_and_wallets_services, self_hostname, consensus_mod coin_records[i].coin.amount, ph_receiver, coin_records[i].coin ) await client.push_tx(spend_bundle) - coin_spends = coin_spends + spend_bundle.coin_spends + coin_spends += spend_bundle.coin_spends await time_out_assert( 5, full_node_api_1.full_node.mempool_manager.get_spendbundle, spend_bundle, spend_bundle.name() ) diff --git a/chia/_tests/farmer_harvester/test_farmer_harvester.py b/chia/_tests/farmer_harvester/test_farmer_harvester.py index 6c6d004a3281..b75af8e7e872 100644 --- a/chia/_tests/farmer_harvester/test_farmer_harvester.py +++ b/chia/_tests/farmer_harvester/test_farmer_harvester.py @@ -202,7 +202,7 @@ def check_config_match(config1: dict[str, Any], config2: dict[str, Any]) -> None harvester_config["parallel_decompressor_count"] += 1 harvester_config["decompressor_thread_count"] += 1 harvester_config["recursive_plot_scan"] = not harvester_config["recursive_plot_scan"] - harvester_config["refresh_parameter_interval_seconds"] = harvester_config["refresh_parameter_interval_seconds"] + 1 + harvester_config["refresh_parameter_interval_seconds"] += 1 res = await update_harvester_config(harvester_rpc_port, bt.root_path, harvester_config) assert res is True diff --git a/chia/_tests/plotting/util.py b/chia/_tests/plotting/util.py index 608491b40d2d..1a768b555330 100644 --- a/chia/_tests/plotting/util.py +++ b/chia/_tests/plotting/util.py @@ -8,5 +8,5 @@ def get_test_plots(sub_dir: str = "") -> list[Path]: path = get_plot_dir() if sub_dir != "": - path = path / sub_dir + path /= sub_dir return list(sorted(path.glob("*.plot"))) diff --git a/chia/consensus/blockchain.py b/chia/consensus/blockchain.py index a48c01ab7b07..d57d6a25870d 100644 --- a/chia/consensus/blockchain.py +++ b/chia/consensus/blockchain.py @@ -790,7 +790,7 @@ def clean_block_record(self, height: int) -> None: if height == 0: break - height = height - 1 + height -= 1 blocks_to_remove = self.__heights_in_cache.get(uint32(height), None) def clean_block_records(self) -> None: diff --git a/chia/data_layer/data_layer.py b/chia/data_layer/data_layer.py index ddb29adb2c77..2e37e6a7b621 100644 --- a/chia/data_layer/data_layer.py +++ b/chia/data_layer/data_layer.py @@ -866,7 +866,7 @@ async def update_subscriptions_from_wallet(self, store_id: bytes32) -> None: mirrors: list[Mirror] = await self.wallet_rpc.dl_get_mirrors(store_id) urls: list[str] = [] for mirror in mirrors: - urls = urls + [url.decode("utf8") for url in mirror.urls] + urls += [url.decode("utf8") for url in mirror.urls] urls = [url.rstrip("/") for url in urls] await self.data_store.update_subscriptions_from_wallet(store_id, urls) diff --git a/chia/full_node/fee_tracker.py b/chia/full_node/fee_tracker.py index ba517189bda7..0bd87cbbafdb 100644 --- a/chia/full_node/fee_tracker.py +++ b/chia/full_node/fee_tracker.py @@ -344,7 +344,7 @@ def estimate_median_val( tx_sum += self.tx_ct_avg[i] if found_answer and tx_sum != 0: - tx_sum = tx_sum / 2 + tx_sum /= 2 for i in range(min_bucket, max_bucket): if self.tx_ct_avg[i] < tx_sum: tx_sum -= self.tx_ct_avg[i] @@ -406,7 +406,7 @@ def init_buckets() -> list[float]: buckets: list[float] = [] while fee_rate < MAX_FEE_RATE: buckets.append(fee_rate) - fee_rate = fee_rate * STEP_SIZE + fee_rate *= STEP_SIZE buckets.append(INFINITE_FEE_RATE) return buckets diff --git a/chia/full_node/mempool_check_conditions.py b/chia/full_node/mempool_check_conditions.py index e12bb407ae83..c3da13502761 100644 --- a/chia/full_node/mempool_check_conditions.py +++ b/chia/full_node/mempool_check_conditions.py @@ -46,7 +46,7 @@ def get_name_puzzle_conditions( flags = get_flags_for_height_and_constants(height, constants) | DONT_VALIDATE_SIGNATURE if mempool_mode: - flags = flags | MEMPOOL_MODE + flags |= MEMPOOL_MODE if height >= constants.HARD_FORK_HEIGHT: run_block = run_block_generator2 diff --git a/chia/full_node/mempool_manager.py b/chia/full_node/mempool_manager.py index 6a627c08cb94..a336d346976f 100644 --- a/chia/full_node/mempool_manager.py +++ b/chia/full_node/mempool_manager.py @@ -423,7 +423,7 @@ async def validate_spend_bundle( child_coin = Coin(coin_id, puzzle_hash, uint64(amount)) spend_additions.append(child_coin) additions_dict[child_coin.name()] = child_coin - addition_amount = addition_amount + child_coin.amount + addition_amount += child_coin.amount is_eligible_for_dedup = bool(spend.flags & ELIGIBLE_FOR_DEDUP) is_eligible_for_ff = bool(spend.flags & ELIGIBLE_FOR_FF) eligibility_and_additions[coin_id] = EligibilityAndAdditions( @@ -486,7 +486,7 @@ async def validate_spend_bundle( removal_record_dict[name] = removal_record else: removal_record = removal_record_dict[name] - removal_amount = removal_amount + removal_record.coin.amount + removal_amount += removal_record.coin.amount fees = uint64(removal_amount - addition_amount) diff --git a/chia/full_node/weight_proof.py b/chia/full_node/weight_proof.py index ff0a1d7fad83..64a50c7b1657 100644 --- a/chia/full_node/weight_proof.py +++ b/chia/full_node/weight_proof.py @@ -1001,9 +1001,7 @@ def _validate_segment( if required_iters is None: return False, uint64(0), uint64(0), uint64(0), [] assert sub_slot_data.signage_point_index is not None - ip_iters = ip_iters + calculate_ip_iters( - constants, curr_ssi, sub_slot_data.signage_point_index, required_iters - ) + ip_iters += calculate_ip_iters(constants, curr_ssi, sub_slot_data.signage_point_index, required_iters) vdf_list = _get_challenge_block_vdfs(constants, idx, segment.sub_slots, curr_ssi) to_validate.extend(vdf_list) elif sampled and after_challenge: @@ -1012,8 +1010,8 @@ def _validate_segment( log.error(f"failed to validate sub slot data {idx} vdfs") return False, uint64(0), uint64(0), uint64(0), [] to_validate.extend(vdf_list) - slot_iters = slot_iters + curr_ssi - slots = slots + uint64(1) + slot_iters += curr_ssi + slots += uint64(1) return True, ip_iters, slot_iters, slots, to_validate @@ -1268,7 +1266,7 @@ def validate_recent_blocks( if ret is None: return False, [] required_iters = ret - validated_block_count = validated_block_count + 1 + validated_block_count += 1 curr_block_ses = None if not ses else summaries[ses_idx - 1] block_record = header_block_to_sub_block_record( diff --git a/chia/plot_sync/sender.py b/chia/plot_sync/sender.py index e2a2fbccf99f..4fcd98073b29 100644 --- a/chia/plot_sync/sender.py +++ b/chia/plot_sync/sender.py @@ -267,7 +267,7 @@ def sync_start(self, count: float, initial: bool) -> None: sync_id = int(time.time()) # Make sure we have unique sync-id's even if we restart refreshing within a second (i.e. in tests) if sync_id == self._last_sync_id: - sync_id = sync_id + 1 + sync_id += 1 log.debug(f"sync_start {sync_id}") self._sync_id = uint64(sync_id) self._add_message( diff --git a/chia/server/address_manager.py b/chia/server/address_manager.py index 4cb1c0c8a516..d685053e3152 100644 --- a/chia/server/address_manager.py +++ b/chia/server/address_manager.py @@ -81,7 +81,7 @@ def get_tried_bucket(self, key: int) -> int: bytes(std_hash(key.to_bytes(32, byteorder="big") + self.peer_info.get_key())[:8]), byteorder="big", ) - hash1 = hash1 % TRIED_BUCKETS_PER_GROUP + hash1 %= TRIED_BUCKETS_PER_GROUP hash2 = int.from_bytes( bytes(std_hash(key.to_bytes(32, byteorder="big") + self.peer_info.get_group() + bytes([hash1]))[:8]), byteorder="big", @@ -96,7 +96,7 @@ def get_new_bucket(self, key: int, src_peer: Optional[PeerInfo] = None) -> int: bytes(std_hash(key.to_bytes(32, byteorder="big") + self.peer_info.get_group() + src_peer.get_group())[:8]), byteorder="big", ) - hash1 = hash1 % NEW_BUCKETS_PER_SOURCE_GROUP + hash1 %= NEW_BUCKETS_PER_SOURCE_GROUP hash2 = int.from_bytes( bytes(std_hash(key.to_bytes(32, byteorder="big") + src_peer.get_group() + bytes([hash1]))[:8]), byteorder="big", diff --git a/chia/simulator/full_node_simulator.py b/chia/simulator/full_node_simulator.py index 72e9c9b0da32..191ff79dda1d 100644 --- a/chia/simulator/full_node_simulator.py +++ b/chia/simulator/full_node_simulator.py @@ -651,9 +651,7 @@ async def check_transactions_confirmed( transactions_left: set[bytes32] = {tx.name for tx in transactions} with anyio.fail_after(delay=adjusted_timeout(timeout)): for backoff in backoff_times(): - transactions_left = transactions_left & { - tx.name for tx in await wallet_state_manager.tx_store.get_all_unconfirmed() - } + transactions_left &= {tx.name for tx in await wallet_state_manager.tx_store.get_all_unconfirmed()} if len(transactions_left) == 0: break diff --git a/chia/wallet/cat_wallet/dao_cat_wallet.py b/chia/wallet/cat_wallet/dao_cat_wallet.py index c931cc2c38fc..d6d33cac2360 100644 --- a/chia/wallet/cat_wallet/dao_cat_wallet.py +++ b/chia/wallet/cat_wallet/dao_cat_wallet.py @@ -288,7 +288,7 @@ async def create_vote_spend( lockup_innerpuz_list = [] if running_sum + coin.amount <= amount: vote_amount = coin.amount - running_sum = running_sum + coin.amount + running_sum += coin.amount primaries = [ Payment( new_innerpuzzle.get_tree_hash(), @@ -303,7 +303,7 @@ async def create_vote_spend( ) else: vote_amount = uint64(amount - running_sum) - running_sum = running_sum + coin.amount + running_sum += coin.amount primaries = [ Payment( new_innerpuzzle.get_tree_hash(), diff --git a/chia/wallet/dao_wallet/dao_wallet.py b/chia/wallet/dao_wallet/dao_wallet.py index a73d8085cc2d..6eb25de62394 100644 --- a/chia/wallet/dao_wallet/dao_wallet.py +++ b/chia/wallet/dao_wallet/dao_wallet.py @@ -1826,7 +1826,7 @@ async def add_or_update_proposal_info( ) await self.add_parent(new_state.coin.name(), future_parent) return - index = index + 1 + index += 1 # check if we are the finished state if current_innerpuz == get_finished_state_inner_puzzle(singleton_id): @@ -1910,7 +1910,7 @@ async def add_or_update_proposal_info( ) await self.add_parent(new_state.coin.name(), future_parent) return - index = index + 1 + index += 1 # Search for the timer coin if not ended: @@ -2005,7 +2005,7 @@ async def update_closed_proposal_coin(self, new_state: CoinSpend, block_height: ) await self.add_parent(new_state.coin.name(), future_parent) return - index = index + 1 + index += 1 async def get_proposal_state(self, proposal_id: bytes32) -> dict[str, Union[int, bool]]: """ diff --git a/chia/wallet/derive_keys.py b/chia/wallet/derive_keys.py index fac41b6b6874..63ba07bf6461 100644 --- a/chia/wallet/derive_keys.py +++ b/chia/wallet/derive_keys.py @@ -139,7 +139,7 @@ def match_address_to_sk( if address in phs: found_addresses.add(address) - search_list = search_list - found_addresses + search_list -= found_addresses if not len(search_list): return found_addresses diff --git a/chia/wallet/wallet_node.py b/chia/wallet/wallet_node.py index 6a220e009e06..2c0a5b54ede6 100644 --- a/chia/wallet/wallet_node.py +++ b/chia/wallet/wallet_node.py @@ -343,7 +343,7 @@ async def reset_sync_db(self, db_path: Union[Path, str], fingerprint: int) -> bo self.log.info("Resetting wallet sync data...") rows = list(await conn.execute_fetchall("SELECT name FROM sqlite_master WHERE type='table'")) names = {x[0] for x in rows} - names = names - set(known_tables) + names -= set(known_tables) tables_to_drop = [] for name in names: for ignore_name in ignore_tables: diff --git a/ruff.toml b/ruff.toml index 099b5825db0b..1286326799e2 100644 --- a/ruff.toml +++ b/ruff.toml @@ -32,7 +32,6 @@ ignore = [ "PLR0911", # too-many-return-statements (52) (x) "PLR6301", # no-self-use (699) (-) "PLR2004", # magic-value-comparison (901) (-) - "PLR6104", # non-augmented-assignment (27) (?) "PLR1704", # redefined-argument-from-local (13) (-) "PLR5501", # collapsible-else-if (49) (?) "PLR1711", # useless-return (14) (?) From 29601e75168e1ec4b192183303a301c451f34eb4 Mon Sep 17 00:00:00 2001 From: Kyle Altendorf Date: Thu, 7 Nov 2024 15:12:01 -0500 Subject: [PATCH 06/12] enable useless-return --- chia/_tests/cmds/wallet/test_vcs.py | 1 - chia/_tests/cmds/wallet/test_wallet.py | 2 -- chia/_tests/wallet/dao_wallet/test_dao_clvm.py | 4 ---- chia/full_node/full_node_api.py | 1 - chia/util/keyring_wrapper.py | 2 -- chia/wallet/dao_wallet/dao_wallet.py | 5 ----- chia/wallet/wallet_node_api.py | 1 - chia/wallet/wallet_singleton_store.py | 1 - ruff.toml | 3 +-- 9 files changed, 1 insertion(+), 19 deletions(-) diff --git a/chia/_tests/cmds/wallet/test_vcs.py b/chia/_tests/cmds/wallet/test_vcs.py index cef9ac5dcde4..63cf4d268a12 100644 --- a/chia/_tests/cmds/wallet/test_vcs.py +++ b/chia/_tests/cmds/wallet/test_vcs.py @@ -194,7 +194,6 @@ def test_vcs_add_proof_reveal(capsys: object, get_test_cli_clients: tuple[TestRp class VcsAddProofRevealRpcClient(TestWalletRpcClient): async def vc_add_proofs(self, proofs: dict[str, Any]) -> None: self.add_to_log("vc_add_proofs", (proofs,)) - return None inst_rpc_client = VcsAddProofRevealRpcClient() test_rpc_clients.wallet_rpc_client = inst_rpc_client diff --git a/chia/_tests/cmds/wallet/test_wallet.py b/chia/_tests/cmds/wallet/test_wallet.py index ebd1a51d6bd8..7ca2e91a5307 100644 --- a/chia/_tests/cmds/wallet/test_wallet.py +++ b/chia/_tests/cmds/wallet/test_wallet.py @@ -558,7 +558,6 @@ def test_del_unconfirmed_tx(capsys: object, get_test_cli_clients: tuple[TestRpcC class UnconfirmedTxRpcClient(TestWalletRpcClient): async def delete_unconfirmed_transactions(self, wallet_id: int) -> None: self.add_to_log("delete_unconfirmed_transactions", (wallet_id,)) - return None inst_rpc_client = UnconfirmedTxRpcClient() test_rpc_clients.wallet_rpc_client = inst_rpc_client @@ -655,7 +654,6 @@ async def create_wallet_for_existing_cat(self, asset_id: bytes) -> dict[str, int async def set_cat_name(self, wallet_id: int, name: str) -> None: self.add_to_log("set_cat_name", (wallet_id, name)) - return None # we don't need to do anything here inst_rpc_client = AddTokenRpcClient() test_rpc_clients.wallet_rpc_client = inst_rpc_client diff --git a/chia/_tests/wallet/dao_wallet/test_dao_clvm.py b/chia/_tests/wallet/dao_wallet/test_dao_clvm.py index 0072467edbc9..728b889f3890 100644 --- a/chia/_tests/wallet/dao_wallet/test_dao_clvm.py +++ b/chia/_tests/wallet/dao_wallet/test_dao_clvm.py @@ -596,8 +596,6 @@ def test_validator() -> None: conds = proposal_validator.run(solution) assert len(conds.as_python()) == 3 - return - def test_spend_p2_singleton() -> None: # Curried values @@ -751,8 +749,6 @@ def test_merge_p2_singleton() -> None: assert cca in agg_acas assert merge_conds[ConditionOpcode.ASSERT_MY_COIN_ID][0].vars[0] == coin_id - return - def test_treasury() -> None: """ diff --git a/chia/full_node/full_node_api.py b/chia/full_node/full_node_api.py index d4e651cd60d3..74609b39c8d7 100644 --- a/chia/full_node/full_node_api.py +++ b/chia/full_node/full_node_api.py @@ -412,7 +412,6 @@ async def reject_blocks(self, request: full_node_protocol.RejectBlocks) -> None: @api_request() async def respond_blocks(self, request: full_node_protocol.RespondBlocks) -> None: self.log.warning("Received unsolicited/late blocks") - return None @api_request(peer_required=True) async def respond_block( diff --git a/chia/util/keyring_wrapper.py b/chia/util/keyring_wrapper.py index c25d92fbb56c..efcbd50eb28f 100644 --- a/chia/util/keyring_wrapper.py +++ b/chia/util/keyring_wrapper.py @@ -291,7 +291,6 @@ def save_master_passphrase_to_credential_store(self, passphrase: str) -> None: except KeyringError as e: if not warn_if_macos_errSecInteractionNotAllowed(e): raise - return None def remove_master_passphrase_from_credential_store(self) -> None: passphrase_store: Optional[OSPassphraseStore] = get_os_passphrase_store() @@ -310,7 +309,6 @@ def remove_master_passphrase_from_credential_store(self) -> None: except KeyringError as e: if not warn_if_macos_errSecInteractionNotAllowed(e): raise - return None def get_master_passphrase_from_credential_store(self) -> Optional[str]: passphrase_store: Optional[OSPassphraseStore] = get_os_passphrase_store() diff --git a/chia/wallet/dao_wallet/dao_wallet.py b/chia/wallet/dao_wallet/dao_wallet.py index 6eb25de62394..24c881f00532 100644 --- a/chia/wallet/dao_wallet/dao_wallet.py +++ b/chia/wallet/dao_wallet/dao_wallet.py @@ -450,7 +450,6 @@ async def coin_added(self, coin: Coin, height: uint32, peer: WSChiaConnection, c self.log.info(f"DAO funding coin added: {coin.name().hex()}:{coin}. Asset ID: {asset_id}") except Exception as e: # pragma: no cover self.log.exception(f"Error occurred during dao wallet coin addition: {e}") - return def get_cat_tail_hash(self) -> bytes32: cat_wallet: CATWallet = self.wallet_state_manager.wallets[self.dao_info.cat_wallet_id] @@ -471,7 +470,6 @@ async def clear_finished_proposals_from_memory(self) -> None: ] dao_info = dataclasses.replace(self.dao_info, proposals_list=new_list) await self.save_info(dao_info) - return async def resync_treasury_state(self) -> None: """ @@ -608,8 +606,6 @@ async def resync_treasury_state(self) -> None: response: Optional[RespondBlockHeader] = await peer.call_api(FullNodeAPI.request_block_header, request) await wallet_node.sync_from_untrusted_close_to_peak(response.header_block, peer) - return - async def generate_new_dao( self, amount_of_cats_to_create: Optional[uint64], @@ -2087,7 +2083,6 @@ async def update_treasury_info( uint64(new_state.coin.amount), ) await self.add_parent(new_state.coin.name(), future_parent) - return async def apply_state_transition(self, new_state: CoinSpend, block_height: uint32) -> bool: """ diff --git a/chia/wallet/wallet_node_api.py b/chia/wallet/wallet_node_api.py index 0cba2db8652a..316362d7440e 100644 --- a/chia/wallet/wallet_node_api.py +++ b/chia/wallet/wallet_node_api.py @@ -157,7 +157,6 @@ async def respond_peers(self, request: full_node_protocol.RespondPeers, peer: WS @api_request() async def respond_puzzle_solution(self, request: wallet_protocol.RespondPuzzleSolution): self.log.error("Unexpected message `respond_puzzle_solution`. Peer might be slow to respond") - return None @api_request() async def reject_puzzle_solution(self, request: wallet_protocol.RejectPuzzleSolution): diff --git a/chia/wallet/wallet_singleton_store.py b/chia/wallet/wallet_singleton_store.py index 325aaec0be83..f16fcf5e44ad 100644 --- a/chia/wallet/wallet_singleton_store.py +++ b/chia/wallet/wallet_singleton_store.py @@ -125,7 +125,6 @@ async def add_spend( current_records = await self.get_records_by_coin_id(coin_state.coin.name()) if len(current_records) > 0: await self.delete_singleton_by_coin_id(coin_state.coin.name(), block_height) - return def _to_singleton_record(self, row: Row) -> SingletonRecord: return SingletonRecord( diff --git a/ruff.toml b/ruff.toml index 1286326799e2..25b4f6bfec8b 100644 --- a/ruff.toml +++ b/ruff.toml @@ -33,8 +33,7 @@ ignore = [ "PLR6301", # no-self-use (699) (-) "PLR2004", # magic-value-comparison (901) (-) "PLR1704", # redefined-argument-from-local (13) (-) - "PLR5501", # collapsible-else-if (49) (?) - "PLR1711", # useless-return (14) (?) + "PLR5501", # collapsible-else-if (49) (-) # Pylint warning "PLW2901", # redefined-loop-name (19) (-) From 6865056e6e829f8904d7392bbbb27aa968130967 Mon Sep 17 00:00:00 2001 From: Kyle Altendorf Date: Thu, 7 Nov 2024 15:20:18 -0500 Subject: [PATCH 07/12] enable global-variable-not-assigned --- chia/server/start_service.py | 1 - chia/simulator/socket.py | 2 -- chia/util/task_timing.py | 4 ---- ruff.toml | 5 ++--- 4 files changed, 2 insertions(+), 10 deletions(-) diff --git a/chia/server/start_service.py b/chia/server/start_service.py index a39384532dac..469e426aab75 100644 --- a/chia/server/start_service.py +++ b/chia/server/start_service.py @@ -292,7 +292,6 @@ def _accept_signal( # we only handle signals in the main process. In the ProcessPoolExecutor # processes, we have to ignore them. We'll shut them down gracefully # from the main process - global main_pid ignore = os.getpid() != main_pid # TODO: if we remove this conditional behavior, consider moving logging to common signal handling diff --git a/chia/simulator/socket.py b/chia/simulator/socket.py index 175cc2d280fc..33cc4d88df06 100644 --- a/chia/simulator/socket.py +++ b/chia/simulator/socket.py @@ -7,8 +7,6 @@ def find_available_listen_port(name: str = "free") -> int: - global recent_ports - while True: with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: try: diff --git a/chia/util/task_timing.py b/chia/util/task_timing.py index 02a7670f9fed..36dd95d3e2cb 100644 --- a/chia/util/task_timing.py +++ b/chia/util/task_timing.py @@ -176,9 +176,6 @@ def trace_fun(frame: FrameType, event: str, arg: Any) -> None: if task is None: return - global g_tasks - global g_function_infos - ti = g_tasks.get(task) if ti is None: ti = TaskInfo() @@ -265,7 +262,6 @@ def fontcolor(pct: float) -> str: def stop_task_instrumentation(target_dir: str = f"task-profile-{os.getpid()}") -> None: sys.setprofile(None) - global g_function_infos try: os.mkdir(target_dir) diff --git a/ruff.toml b/ruff.toml index 25b4f6bfec8b..2a6fd315b163 100644 --- a/ruff.toml +++ b/ruff.toml @@ -37,9 +37,8 @@ ignore = [ # Pylint warning "PLW2901", # redefined-loop-name (19) (-) - "PLW1641", # eq-without-hash (5) (?) - "PLW1514", # unspecified-encoding (69) (?) - "PLW0602", # global-variable-not-assigned (5) (?) + "PLW1641", # eq-without-hash (5) (x) + "PLW1514", # unspecified-encoding (69) (-) "PLW0603", # global-statement (9) (?) ] From efde7f063fcd0f16955d21a9bd9d733c58278560 Mon Sep 17 00:00:00 2001 From: Kyle Altendorf Date: Thu, 7 Nov 2024 15:22:16 -0500 Subject: [PATCH 08/12] - --- ruff.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruff.toml b/ruff.toml index 2a6fd315b163..52075282338b 100644 --- a/ruff.toml +++ b/ruff.toml @@ -16,7 +16,7 @@ explicit-preview-rules = false ignore = [ # Pylint convention "PLC0415", # import-outside-top-level (286) (x) - "PLC2801", # unnecessary-dunder-call (11) (*) + "PLC2801", # unnecessary-dunder-call (11) (-) "PLC1901", # compare-to-empty-string (51) (x) "PLC2701", # import-private-name (24) (*) @@ -39,7 +39,7 @@ ignore = [ "PLW2901", # redefined-loop-name (19) (-) "PLW1641", # eq-without-hash (5) (x) "PLW1514", # unspecified-encoding (69) (-) - "PLW0603", # global-statement (9) (?) + "PLW0603", # global-statement (9) (-) ] From b8d844d7d534782af8de4a21d47e8a3369923b99 Mon Sep 17 00:00:00 2001 From: Kyle Altendorf Date: Thu, 7 Nov 2024 16:45:10 -0500 Subject: [PATCH 09/12] fixup --- chia/_tests/blockchain/test_blockchain.py | 2 +- chia/_tests/core/util/test_keychain.py | 5 +++-- chia/pools/pool_puzzles.py | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/chia/_tests/blockchain/test_blockchain.py b/chia/_tests/blockchain/test_blockchain.py index 0cd2d1577cd0..35e914aa5380 100644 --- a/chia/_tests/blockchain/test_blockchain.py +++ b/chia/_tests/blockchain/test_blockchain.py @@ -2627,7 +2627,7 @@ async def test_cost_exceeds_max( fork_info=fork_info, ) )[1] - assert err in {Err.BLOCK_COST_EXCEEDS_MAX} + assert err == Err.BLOCK_COST_EXCEEDS_MAX futures = await pre_validate_blocks_multiprocessing( b.constants, AugmentedBlockchain(b), diff --git a/chia/_tests/core/util/test_keychain.py b/chia/_tests/core/util/test_keychain.py index 337bdf6c475c..c35ace2fa436 100644 --- a/chia/_tests/core/util/test_keychain.py +++ b/chia/_tests/core/util/test_keychain.py @@ -180,7 +180,8 @@ def test_add_private_key_label(self, empty_temp_file_keyring: TempKeyring): # All added keys should still be valid with their label assert all( - key_data in {key_data_0, key_data_1, key_data_2} for key_data in keychain.get_keys(include_secrets=True) + key_data in (key_data_0, key_data_1, key_data_2) # noqa: PLR6201 + for key_data in keychain.get_keys(include_secrets=True) ) def test_bip39_eip2333_test_vector(self, empty_temp_file_keyring: TempKeyring): @@ -427,7 +428,7 @@ async def test_set_label(get_temp_keyring: Keychain) -> None: keychain.set_label(fingerprint=key_data_1.fingerprint, label=key_data_1.label) assert key_data_0 == keychain.get_key(fingerprint=key_data_0.fingerprint, include_secrets=True) # All added keys should still be valid with their label - assert all(key_data in {key_data_0, key_data_1} for key_data in keychain.get_keys(include_secrets=True)) + assert all(key_data in (key_data_0, key_data_1) for key_data in keychain.get_keys(include_secrets=True)) # noqa: PLR6201 @pytest.mark.parametrize( diff --git a/chia/pools/pool_puzzles.py b/chia/pools/pool_puzzles.py index 43f1679a0bb9..0005b0d6053f 100644 --- a/chia/pools/pool_puzzles.py +++ b/chia/pools/pool_puzzles.py @@ -161,17 +161,17 @@ def get_seconds_and_delayed_puzhash_from_p2_singleton_puzzle(puzzle: Program) -> # Verify that a puzzle is a Pool Wallet Singleton def is_pool_singleton_inner_puzzle(inner_puzzle: Program) -> bool: inner_f = get_template_singleton_inner_puzzle(inner_puzzle) - return inner_f in {POOL_WAITING_ROOM_MOD, POOL_MEMBER_MOD} + return inner_f in (POOL_WAITING_ROOM_MOD, POOL_MEMBER_MOD) # noqa: PLR6201 def is_pool_waitingroom_inner_puzzle(inner_puzzle: Program) -> bool: inner_f = get_template_singleton_inner_puzzle(inner_puzzle) - return inner_f in {POOL_WAITING_ROOM_MOD} + return inner_f == POOL_WAITING_ROOM_MOD def is_pool_member_inner_puzzle(inner_puzzle: Program) -> bool: inner_f = get_template_singleton_inner_puzzle(inner_puzzle) - return inner_f in {POOL_MEMBER_MOD} + return inner_f == POOL_MEMBER_MOD # This spend will use the escape-type spend path for whichever state you are currently in From f154b4f24cf554c0e69e6c0f93bde521dc02b10f Mon Sep 17 00:00:00 2001 From: Matt Date: Thu, 7 Nov 2024 14:15:08 -0800 Subject: [PATCH 10/12] Clean up roff.toml from annotations --- ruff.toml | 45 ++++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/ruff.toml b/ruff.toml index 52075282338b..bc77d4049ddd 100644 --- a/ruff.toml +++ b/ruff.toml @@ -15,31 +15,34 @@ select = [ explicit-preview-rules = false ignore = [ # Pylint convention - "PLC0415", # import-outside-top-level (286) (x) - "PLC2801", # unnecessary-dunder-call (11) (-) - "PLC1901", # compare-to-empty-string (51) (x) - "PLC2701", # import-private-name (24) (*) + "PLC0415", # import-outside-top-level + "PLC1901", # compare-to-empty-string + # Should probably fix these + "PLC2801", # unnecessary-dunder-call + "PLC2701", # import-private-name # Pylint refactor - "PLR0915", # too-many-statements (222) (x) - "PLR0914", # too-many-locals (328) (x) - "PLR0913", # too-many-arguments (397) (x) - "PLR0912", # too-many-branches (193) (x) - "PLR1702", # too-many-nested-blocks (124) (x) - "PLR0904", # too-many-public-methods (47) (x) - "PLR0917", # too-many-positional-arguments (345) (x) - "PLR0916", # too-many-boolean-expressions (3) (x) - "PLR0911", # too-many-return-statements (52) (x) - "PLR6301", # no-self-use (699) (-) - "PLR2004", # magic-value-comparison (901) (-) - "PLR1704", # redefined-argument-from-local (13) (-) - "PLR5501", # collapsible-else-if (49) (-) + "PLR0915", # too-many-statements + "PLR0914", # too-many-locals + "PLR0913", # too-many-arguments + "PLR0912", # too-many-branches + "PLR1702", # too-many-nested-blocks + "PLR0904", # too-many-public-methods + "PLR0917", # too-many-positional-arguments + "PLR0916", # too-many-boolean-expressions + "PLR0911", # too-many-return-statements + # Should probably fix these + "PLR6301", # no-self-use + "PLR2004", # magic-value-comparison + "PLR1704", # redefined-argument-from-local + "PLR5501", # collapsible-else-if # Pylint warning - "PLW2901", # redefined-loop-name (19) (-) - "PLW1641", # eq-without-hash (5) (x) - "PLW1514", # unspecified-encoding (69) (-) - "PLW0603", # global-statement (9) (-) + "PLW1641", # eq-without-hash + # Should probably fix these + "PLW2901", # redefined-loop-name + "PLW1514", # unspecified-encoding + "PLW0603", # global-statement ] From a01f3e8db84b52da3accdbd40c4b4b0e410f26e7 Mon Sep 17 00:00:00 2001 From: Matt Date: Thu, 7 Nov 2024 14:21:55 -0800 Subject: [PATCH 11/12] use ignore instead of explicit re-export --- chia/consensus/constants.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/chia/consensus/constants.py b/chia/consensus/constants.py index b7189e79a637..0a2b8c17ad28 100644 --- a/chia/consensus/constants.py +++ b/chia/consensus/constants.py @@ -3,7 +3,7 @@ import logging from typing import Any -from chia_rs import ConsensusConstants +from chia_rs import ConsensusConstants as ConsensusConstants # noqa: PLC0414 from chia.util.byte_types import hexstr_to_bytes from chia.util.hash import std_hash @@ -47,6 +47,3 @@ def replace_str_to_bytes(constants: ConsensusConstants, **changes: Any) -> Conse # TODO: this is too magical here and is really only used for configuration unmarshalling return constants.replace(**filtered_changes) # type: ignore[arg-type] - - -__all__ = ["ConsensusConstants", "replace_str_to_bytes"] From 1ae43185ae26505d61ce4649b66191313fa39f90 Mon Sep 17 00:00:00 2001 From: Matt Date: Thu, 7 Nov 2024 14:24:43 -0800 Subject: [PATCH 12/12] use more descriptive names --- chia/rpc/wallet_rpc_api.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chia/rpc/wallet_rpc_api.py b/chia/rpc/wallet_rpc_api.py index 9babbee8f379..74aaf8d851f8 100644 --- a/chia/rpc/wallet_rpc_api.py +++ b/chia/rpc/wallet_rpc_api.py @@ -2086,11 +2086,11 @@ async def create_offer_for_ids( driver_dict[bytes32.from_hexstr(key)] = PuzzleInfo(value) modified_offer: dict[Union[int, bytes32], int] = {} - for key, val in offer.items(): + for wallet_identifier, change in offer.items(): try: - modified_offer[bytes32.from_hexstr(key)] = val + modified_offer[bytes32.from_hexstr(wallet_identifier)] = change except ValueError: - modified_offer[int(key)] = val + modified_offer[int(wallet_identifier)] = change async with self.service.wallet_state_manager.lock: result = await self.service.wallet_state_manager.trade_manager.create_offer_for_ids(