From fe15e9ee6f01e4c176640e40ab82d5aa9c0b9bd9 Mon Sep 17 00:00:00 2001 From: Arvid Norberg Date: Wed, 29 Jul 2026 07:37:24 -0700 Subject: [PATCH] [CHIA-4326] enable redundant expressions check in mypy (#21143) * fix type annotation in configure.py and init.py * enable mypy redundant-expr and remove redundant expressions --- chia/_tests/blockchain/test_blockchain.py | 6 +---- chia/_tests/core/daemon/test_daemon.py | 8 +++++-- chia/_tests/core/full_node/test_full_node.py | 18 +++++---------- .../test_third_party_harvesters.py | 2 +- chia/_tests/plot_sync/test_sync_simulated.py | 2 +- chia/_tests/timelord/test_new_peak.py | 7 +++--- chia/_tests/util/spend_sim.py | 5 ++--- chia/_tests/wallet/rpc/test_wallet_rpc.py | 12 +++++----- chia/cmds/cmds_util.py | 2 +- chia/cmds/configure.py | 14 ++++++------ chia/cmds/init.py | 2 +- chia/cmds/show_funcs.py | 2 +- chia/cmds/start_funcs.py | 2 +- chia/cmds/wallet_funcs.py | 2 +- chia/consensus/block_header_validation.py | 4 ++-- chia/consensus/condition_tools.py | 8 +------ chia/consensus/make_sub_epoch_summary.py | 2 +- chia/data_layer/data_layer.py | 8 +++---- chia/data_layer/data_store.py | 6 ++--- chia/farmer/farmer_api.py | 2 +- chia/full_node/full_node.py | 6 ++--- chia/full_node/full_node_api.py | 4 ++-- chia/full_node/full_node_rpc_api.py | 2 +- chia/full_node/weight_proof.py | 20 +++++++---------- chia/introducer/introducer_api.py | 2 +- chia/plot_sync/sender.py | 3 ++- chia/rpc/rpc_server.py | 3 ++- chia/server/address_manager.py | 2 +- chia/server/chia_policy.py | 2 +- chia/server/ws_connection.py | 4 ++-- chia/types/mempool_item.py | 4 ++-- chia/util/config.py | 2 +- chia/util/keychain.py | 4 ++-- chia/util/streamable.py | 10 ++++----- chia/util/virtual_project_analysis.py | 13 +++-------- chia/wallet/derive_keys.py | 2 +- chia/wallet/did_wallet/did_wallet.py | 2 +- chia/wallet/nft_wallet/nft_wallet.py | 6 +---- chia/wallet/trade_manager.py | 2 +- chia/wallet/util/clvm_streamable.py | 2 +- chia/wallet/vc_wallet/cr_cat_wallet.py | 6 ++--- chia/wallet/wallet_node.py | 3 ++- chia/wallet/wallet_node_api.py | 2 +- chia/wallet/wallet_state_manager.py | 22 ++++++++----------- mypy.ini.template | 1 + tools/validate_rpcs.py | 4 ++-- 46 files changed, 108 insertions(+), 139 deletions(-) diff --git a/chia/_tests/blockchain/test_blockchain.py b/chia/_tests/blockchain/test_blockchain.py index e139ced36c..b9168d3804 100644 --- a/chia/_tests/blockchain/test_blockchain.py +++ b/chia/_tests/blockchain/test_blockchain.py @@ -2869,11 +2869,7 @@ class TestBodyValidation: assert block_2.transactions_generator is not None block_generator = BlockGenerator(block_2.transactions_generator, []) - max_cost = ( - min(b.constants.MAX_BLOCK_COST_CLVM * 1000, block.transactions_info.cost) - if block.transactions_info is not None - else b.constants.MAX_BLOCK_COST_CLVM * 1000 - ) + max_cost = min(b.constants.MAX_BLOCK_COST_CLVM * 1000, block.transactions_info.cost) npc_result = get_name_puzzle_conditions( block_generator, max_cost, diff --git a/chia/_tests/core/daemon/test_daemon.py b/chia/_tests/core/daemon/test_daemon.py index d5f0961033..8bfd38a8b5 100644 --- a/chia/_tests/core/daemon/test_daemon.py +++ b/chia/_tests/core/daemon/test_daemon.py @@ -5,7 +5,7 @@ import json import logging from dataclasses import dataclass, field, replace from pathlib import Path -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast import aiohttp import pytest @@ -39,6 +39,9 @@ from chia.util.keyring_wrapper import DEFAULT_PASSPHRASE_IF_NO_MASTER_PASSPHRASE from chia.util.ws_message import create_payload, create_payload_dict from chia.wallet.derive_keys import master_sk_to_farmer_sk, master_sk_to_pool_sk +if TYPE_CHECKING: + from _typeshed import FileDescriptorOrPath + chiapos_version = importlib.metadata.version("chiapos") @@ -2114,7 +2117,8 @@ def test_run_plotter_bladebit( case.farmer_pk = bytes(bt.farmer_pk).hex() case.final_dir = str(bt.plot_dir) - def bladebit_exists(x: Path) -> bool: + def bladebit_exists(x: FileDescriptorOrPath) -> bool: + # os.path.exists is patched globally, so this also sees stdlib callers (e.g. gettext) with str paths. return True if isinstance(x, Path) and x.parent == root_path / "plotters" else mocker.DEFAULT def get_bladebit_version(_: Path) -> tuple[bool, list[str]]: diff --git a/chia/_tests/core/full_node/test_full_node.py b/chia/_tests/core/full_node/test_full_node.py index 82c1dd9bbc..4333c5dd55 100644 --- a/chia/_tests/core/full_node/test_full_node.py +++ b/chia/_tests/core/full_node/test_full_node.py @@ -150,11 +150,7 @@ async def new_transaction_not_requested(incoming: asyncio.Queue[Message], new_sp await asyncio.sleep(3) while not incoming.empty(): response = await incoming.get() - if ( - response is not None - and isinstance(response, Message) - and response.type == ProtocolMessageTypes.request_transaction.value - ): + if response.type == ProtocolMessageTypes.request_transaction.value: request = full_node_protocol.RequestTransaction.from_bytes(response.data) if request.transaction_id == new_spend.transaction_id: return False @@ -165,11 +161,7 @@ async def new_transaction_requested(incoming: asyncio.Queue[Message], new_spend: await asyncio.sleep(1) while not incoming.empty(): response = await incoming.get() - if ( - response is not None - and isinstance(response, Message) - and response.type == ProtocolMessageTypes.request_transaction.value - ): + if response.type == ProtocolMessageTypes.request_transaction.value: request = full_node_protocol.RequestTransaction.from_bytes(response.data) if request.transaction_id == new_spend.transaction_id: return True @@ -634,7 +626,7 @@ async def test_request_peers( msg_bytes = await full_node_peers.request_peers(PeerInfo("::1", server_2._port)) assert msg_bytes is not None msg = fnp.RespondPeers.from_bytes(msg_bytes.data) - if msg is not None and not (len(msg.peer_list) == 1): + if 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 @@ -1782,7 +1774,7 @@ async def test_new_unfinished_block( else: res = await full_node_1.new_unfinished_block(fnp.NewUnfinishedBlock(unf.partial_hash)) assert res is not None - assert res is not None and res.data == bytes(fnp.RequestUnfinishedBlock(unf.partial_hash)) + assert res.data == bytes(fnp.RequestUnfinishedBlock(unf.partial_hash)) # when we receive a new unfinished block, we advertise it to our peers. # We send new_unfinished_blocks to old peers (0.0.35 and earlier) and we @@ -4131,7 +4123,7 @@ async def declare_pos_unfinished_block_pos_request( eos, blockchain, peak, - ssi if ssi is not None else None, + ssi, diff, full_peak, ) diff --git a/chia/_tests/farmer_harvester/test_third_party_harvesters.py b/chia/_tests/farmer_harvester/test_third_party_harvesters.py index 5a3c431f2e..e53e0abf5b 100644 --- a/chia/_tests/farmer_harvester/test_third_party_harvesters.py +++ b/chia/_tests/farmer_harvester/test_third_party_harvesters.py @@ -478,7 +478,7 @@ async def add_test_blocks_into_full_node(blocks: list[FullBlock], full_node: Ful ) ) pre_validation_results: list[PreValidationResult] = list(await asyncio.gather(*futures)) - assert pre_validation_results is not None and len(pre_validation_results) == len(blocks) + assert len(pre_validation_results) == len(blocks) for i in range(len(blocks)): block = blocks[i] if block.height != 0 and len(block.finished_sub_slots) > 0: # pragma: no cover diff --git a/chia/_tests/plot_sync/test_sync_simulated.py b/chia/_tests/plot_sync/test_sync_simulated.py index ed1355cb82..108d21172a 100644 --- a/chia/_tests/plot_sync/test_sync_simulated.py +++ b/chia/_tests/plot_sync/test_sync_simulated.py @@ -78,7 +78,7 @@ class TestData: self.keys_missing = keys_missing self.duplicates = duplicates - removed_paths: list[Path] = [Path(p.prover.get_filename()) for p in removed] if removed is not None else [] + removed_paths: list[Path] = [Path(p.prover.get_filename()) for p in removed] invalid_dict: dict[Path, int] = {Path(p.prover.get_filename()): 0 for p in self.invalid} keys_missing_set: set[Path] = {Path(p.prover.get_filename()) for p in self.keys_missing} duplicates_set: set[str] = {p.prover.get_filename() for p in self.duplicates} diff --git a/chia/_tests/timelord/test_new_peak.py b/chia/_tests/timelord/test_new_peak.py index 89dcb94cef..2abe1a3888 100644 --- a/chia/_tests/timelord/test_new_peak.py +++ b/chia/_tests/timelord/test_new_peak.py @@ -456,8 +456,7 @@ class TestNewPeak: await time_out_assert(60, tl_new_peak_is_none, True, timelord_api) assert ( - timelord_api.timelord.last_state.peak is not None - and timelord_api.timelord.last_state.peak.reward_chain_block.get_hash() + timelord_api.timelord.last_state.peak.reward_chain_block.get_hash() == next_peak.reward_chain_block.get_hash() ) @@ -619,7 +618,7 @@ class TestNewPeak: await _validate_and_add_block(b1, block) peak = timelord_peak_from_block(b1, blocks[-1]) - assert peak is not None and timelord_api.timelord.new_peak is None + assert timelord_api.timelord.new_peak is None await timelord_api.new_peak_timelord(peak) assert timelord_api.timelord.new_peak is not None await time_out_assert(60, tl_new_peak_is_none, True, timelord_api) @@ -712,7 +711,7 @@ async def get_rc_prev(blockchain: Blockchain, block: FullBlock) -> bytes32: assert full_blk is not None sub_slot = None for s in full_blk.finished_sub_slots: - if s is not None and s.challenge_chain.get_hash() == block.reward_chain_block.pos_ss_cc_challenge_hash: + if s.challenge_chain.get_hash() == block.reward_chain_block.pos_ss_cc_challenge_hash: sub_slot = s if sub_slot is None: assert block.reward_chain_block.pos_ss_cc_challenge_hash == blockchain.constants.GENESIS_CHALLENGE diff --git a/chia/_tests/util/spend_sim.py b/chia/_tests/util/spend_sim.py index ac8ab43a1c..a65952bfec 100644 --- a/chia/_tests/util/spend_sim.py +++ b/chia/_tests/util/spend_sim.py @@ -265,7 +265,7 @@ class SpendSim: generator_bundle: SpendBundle | None = None tx_additions = [] tx_removals = [] - spent_coins_ids = None + spent_coins_ids: list[bytes32] = [] if (len(self.block_records) > 0) and (self.mempool_manager.mempool.size() > 0): peak = self.mempool_manager.peak if peak is not None: @@ -274,7 +274,6 @@ class SpendSim: bundle, additions = result generator_bundle = bundle spent_coins: dict[bytes32, Coin] = {} - spent_coins_ids = [] for spend in generator_bundle.coin_spends: hint_dict, _ = compute_spend_hints_and_additions(spend) hints: list[tuple[bytes32, bytes]] = [] @@ -297,7 +296,7 @@ class SpendSim: timestamp=self.timestamp, included_reward_coins=included_reward_coins, tx_additions=tx_additions, - tx_removals=spent_coins_ids if spent_coins_ids is not None else [], + tx_removals=spent_coins_ids, ) # SimBlockRecord is created generator: BlockGenerator | None = await self.generate_transaction_generator(generator_bundle) diff --git a/chia/_tests/wallet/rpc/test_wallet_rpc.py b/chia/_tests/wallet/rpc/test_wallet_rpc.py index cc3381221d..c8fe351474 100644 --- a/chia/_tests/wallet/rpc/test_wallet_rpc.py +++ b/chia/_tests/wallet/rpc/test_wallet_rpc.py @@ -761,8 +761,8 @@ async def test_create_signed_transaction( "unconfirmed_wallet_balance": -cat_delta, "<=#spendable_balance": -cat_delta, "<=#max_send_amount": -cat_delta, - ">=#pending_change": 1 if is_cat else 0, - "pending_coin_removal_count": 1 if is_cat else 0, + ">=#pending_change": 1, + "pending_coin_removal_count": 1, } } if is_cat @@ -782,10 +782,10 @@ async def test_create_signed_transaction( { "cat": { "confirmed_wallet_balance": -cat_delta, - ">=#spendable_balance": 1 if is_cat else 0, - ">=#max_send_amount": 1 if is_cat else 0, - "<=#pending_change": -1 if is_cat else 0, - "pending_coin_removal_count": -1 if is_cat else 0, + ">=#spendable_balance": 1, + ">=#max_send_amount": 1, + "<=#pending_change": -1, + "pending_coin_removal_count": -1, } } if is_cat diff --git a/chia/cmds/cmds_util.py b/chia/cmds/cmds_util.py index f0d67cfd27..a5c0cc16c6 100644 --- a/chia/cmds/cmds_util.py +++ b/chia/cmds/cmds_util.py @@ -453,7 +453,7 @@ class CMDTXConfigLoader(CMDCoinSelectionConfigLoader): ).autofill(constants=DEFAULT_CONSTANTS, config=config, logged_in_fingerprint=fingerprint) -def format_bytes(bytes: int) -> str: +def format_bytes(bytes: object) -> str: if not isinstance(bytes, int) or bytes < 0: return "Invalid" diff --git a/chia/cmds/configure.py b/chia/cmds/configure.py index d1769531ac..e9cf69429b 100644 --- a/chia/cmds/configure.py +++ b/chia/cmds/configure.py @@ -31,10 +31,10 @@ def configure( set_peer_count: str, testnet: str, peer_connect_timeout: str, - crawler_db_path: str, + crawler_db_path: str | None, crawler_minimum_version_count: int | None, - seeder_domain_name: str, - seeder_nameserver: str, + seeder_domain_name: str | None, + seeder_nameserver: str | None, set_solver_trusted_peers_only: str, set_log_systemd: str, ) -> None: @@ -349,10 +349,10 @@ def configure_cmd( set_peer_count: str, testnet: str, set_peer_connect_timeout: str, - crawler_db_path: str, - crawler_minimum_version_count: int, - seeder_domain_name: str, - seeder_nameserver: str, + crawler_db_path: str | None, + crawler_minimum_version_count: int | None, + seeder_domain_name: str | None, + seeder_nameserver: str | None, set_solver_trusted_peers_only: str, ) -> None: configure( diff --git a/chia/cmds/init.py b/chia/cmds/init.py index 41a61b99a8..9b7f9254be 100644 --- a/chia/cmds/init.py +++ b/chia/cmds/init.py @@ -28,7 +28,7 @@ from chia.cmds.cmd_classes import ChiaCliContext @click.pass_context def init_cmd( ctx: click.Context, - create_certs: str, + create_certs: str | None, fix_ssl_permissions: bool, testnet: bool, set_passphrase: bool, diff --git a/chia/cmds/show_funcs.py b/chia/cmds/show_funcs.py index ec896fca7c..149a3a5d38 100644 --- a/chia/cmds/show_funcs.py +++ b/chia/cmds/show_funcs.py @@ -48,7 +48,7 @@ async def print_blockchain_state(node_client: FullNodeRpcClient, config: dict[st f"({sync_max_block - sync_current_block} behind). " f"({sync_current_block * 100.0 / sync_max_block:2.2f}% synced)" ) - print("Peak: Hash:", peak.header_hash if peak is not None else "") + print("Peak: Hash:", peak.header_hash) elif peak is not None: print(f"Current Blockchain Status: Not Synced. Peak height: {peak.height}") else: diff --git a/chia/cmds/start_funcs.py b/chia/cmds/start_funcs.py index f655ccd92c..a2efa1fb53 100644 --- a/chia/cmds/start_funcs.py +++ b/chia/cmds/start_funcs.py @@ -97,7 +97,7 @@ async def async_start( continue print(f"{service}: ", end="", flush=True) msg = await daemon.start_service(service_name=service) - success = msg and msg["data"]["success"] + success = msg["data"]["success"] if success is True: print("started") diff --git a/chia/cmds/wallet_funcs.py b/chia/cmds/wallet_funcs.py index febbdcf364..05208f9938 100644 --- a/chia/cmds/wallet_funcs.py +++ b/chia/cmds/wallet_funcs.py @@ -1686,7 +1686,7 @@ async def delete_notifications(wallet_info: WalletClientInfo, ids: Sequence[byte if delete_all: await wallet_info.client.delete_notifications(DeleteNotifications()) else: - await wallet_info.client.delete_notifications(DeleteNotifications(ids=list(ids) if ids is not None else None)) + await wallet_info.client.delete_notifications(DeleteNotifications(ids=list(ids))) print("Success!") diff --git a/chia/consensus/block_header_validation.py b/chia/consensus/block_header_validation.py index 92fb936342..71e5de417a 100644 --- a/chia/consensus/block_header_validation.py +++ b/chia/consensus/block_header_validation.py @@ -425,7 +425,7 @@ def validate_unfinished_header_block( assert prev_b is not None # 3b. Check that we finished a slot and we finished a sub-epoch - if not new_sub_slot or not can_finish_se: + if not can_finish_se: return ( None, ValidationError( @@ -457,7 +457,7 @@ def validate_unfinished_header_block( ), ) - elif new_sub_slot and not genesis_block: + elif not genesis_block: # 3d. Check that we don't have to include a sub-epoch summary if can_finish_se or can_finish_epoch: return ( diff --git a/chia/consensus/condition_tools.py b/chia/consensus/condition_tools.py index e4bd97923c..306f8d3ce1 100644 --- a/chia/consensus/condition_tools.py +++ b/chia/consensus/condition_tools.py @@ -125,13 +125,7 @@ def pkm_pairs(conditions: SpendBundleConditions, additional_data: bytes) -> tupl def validate_cwa(cwa: ConditionWithArgs) -> None: - if ( - len(cwa.vars) != 2 - or len(cwa.vars[0]) != 48 - or len(cwa.vars[1]) > 1024 - or cwa.vars[0] is None - or cwa.vars[1] is None - ): + if len(cwa.vars) != 2 or len(cwa.vars[0]) != 48 or len(cwa.vars[1]) > 1024 or cwa.vars[1] is None: raise ConsensusError(Err.INVALID_CONDITION) diff --git a/chia/consensus/make_sub_epoch_summary.py b/chia/consensus/make_sub_epoch_summary.py index 48464367d8..3f49cbd0cc 100644 --- a/chia/consensus/make_sub_epoch_summary.py +++ b/chia/consensus/make_sub_epoch_summary.py @@ -174,7 +174,7 @@ def next_sub_epoch_summary( constants, blocks, uint32(prev_b.height + 1), - prev_b.header_hash if prev_b is not None else None, + prev_b.header_hash, deficit, False, ) diff --git a/chia/data_layer/data_layer.py b/chia/data_layer/data_layer.py index e2acb4830a..0dee7d13b0 100644 --- a/chia/data_layer/data_layer.py +++ b/chia/data_layer/data_layer.py @@ -766,7 +766,7 @@ class DataLayer: latest_generation = root.generation # Don't store full tree files before this generation. full_tree_first_publish_generation = max(0, latest_generation - self.maximum_full_file_count + 1) - publish_generation = min(singleton_record.generation, 0 if root is None else root.generation) + publish_generation = min(singleton_record.generation, root.generation) # If we make some batch updates, which get confirmed to the chain, we need to create the files. # We iterate back and write the missing files, until we find the files already written. root = await self.data_store.get_tree_root(store_id=store_id, generation=publish_generation) @@ -783,7 +783,7 @@ class DataLayer: # this particular return only happens if the files already exist, no need to log anything break try: - if uploaders is not None and len(uploaders) > 0: + if len(uploaders) > 0: request_json = { "store_id": store_id.hex(), "diff_filename": write_file_result.diff_tree.name, @@ -830,7 +830,7 @@ class DataLayer: if singleton_record is None: self.log.error(f"No singleton record found for: {store_id}") return - max_generation = min(singleton_record.generation, 0 if root is None else root.generation) + max_generation = min(singleton_record.generation, root.generation) server_files_location = foldername if foldername is not None else self.server_files_location files = [] for generation in range(1, max_generation + 1): @@ -849,7 +849,7 @@ class DataLayer: files.append(res.full_tree.name) uploaders = await self.get_uploaders(store_id) - if uploaders is not None and len(uploaders) > 0: + if len(uploaders) > 0: request_json = { "store_id": store_id.hex(), "files": json.dumps(files), diff --git a/chia/data_layer/data_store.py b/chia/data_layer/data_store.py index 9b72c5ee39..ad67093476 100644 --- a/chia/data_layer/data_store.py +++ b/chia/data_layer/data_store.py @@ -372,7 +372,7 @@ class DataStore: while len(chunk) < 4: size_to_read = 4 - len(chunk) cur_chunk = reader.read(size_to_read) - if cur_chunk is None or cur_chunk == b"": + if cur_chunk == b"": if size_to_read < 4: raise Exception("Incomplete read of length.") break @@ -385,7 +385,7 @@ class DataStore: while len(serialize_nodes_bytes) < size: size_to_read = size - len(serialize_nodes_bytes) cur_chunk = reader.read(size_to_read) - if cur_chunk is None or cur_chunk == b"": + if cur_chunk == b"": raise Exception("Incomplete read of blob.") serialize_nodes_bytes += cur_chunk serialized_node = SerializedNode.from_bytes(serialize_nodes_bytes) @@ -1280,7 +1280,7 @@ class DataStore: async def get_terminal_node_for_seed(self, seed: bytes32, store_id: bytes32) -> TerminalNode | None: root = await self.get_tree_root(store_id=store_id) - if root is None or root.node_hash is None: + if root.node_hash is None: return None merkle_blob = await self.get_merkle_blob(store_id=store_id, root_hash=root.node_hash) diff --git a/chia/farmer/farmer_api.py b/chia/farmer/farmer_api.py index bd27750d22..27f7a96538 100644 --- a/chia/farmer/farmer_api.py +++ b/chia/farmer/farmer_api.py @@ -569,7 +569,7 @@ class FarmerAPI: # create the proof of space with the solver's proof proof_bytes = response.proof - if proof_bytes is None or len(proof_bytes) == 0: + if len(proof_bytes) == 0: self.farmer.log.warning(f"Received empty proof from solver for proof {partial_proof.fragments[:5]}...") return diff --git a/chia/full_node/full_node.py b/chia/full_node/full_node.py index 577a3ae531..a6ac8dc356 100644 --- a/chia/full_node/full_node.py +++ b/chia/full_node/full_node.py @@ -502,7 +502,7 @@ class FullNode: else: peak_store = None for con in connections: - if peak_store is not None and con.peer_node_id in peak_store: + if con.peer_node_id in peak_store: peak = peak_store[con.peer_node_id] peak_height = peak.height peak_hash = peak.header_hash @@ -829,7 +829,7 @@ class FullNode: peak_peers: set[bytes32] = self.sync_store.get_peers_that_have_peak([target_peak.header_hash]) # Don't ask if we already know this peer has the peak if peer.peer_node_id not in peak_peers: - target_peak_response: RespondBlock | None = await peer.call_api( + target_peak_response = await peer.call_api( FullNodeAPI.request_block, full_node_protocol.RequestBlock(target_peak.height, False), timeout=10, @@ -2012,7 +2012,7 @@ class FullNode: ) signage_points: list[tuple[RespondSignagePoint, WSChiaConnection, EndOfSubSlotBundle | None]] = [] - if fns_peak_result.new_signage_points is not None and peer is not None: + if peer is not None: for index, sp in fns_peak_result.new_signage_points: assert ( sp.cc_vdf is not None diff --git a/chia/full_node/full_node_api.py b/chia/full_node/full_node_api.py index 3ea26a7eeb..a2521f13ad 100644 --- a/chia/full_node/full_node_api.py +++ b/chia/full_node/full_node_api.py @@ -859,7 +859,7 @@ class FullNodeAPI: peer_host = peer.peer_info.host if is_localhost(peer_host): self.log.debug(f"Not banning localhost peer for invalid signage point VDF proof: {peer_host}") - elif server is not None and is_in_network(peer_host, server.exempt_peer_networks): + elif is_in_network(peer_host, server.exempt_peer_networks): self.log.debug(f"Not banning exempt network peer for invalid signage point VDF proof: {peer_host}") else: self.log.warning( @@ -1508,7 +1508,7 @@ class FullNodeAPI: msg = make_msg(ProtocolMessageTypes.reject_removals_request, reject) return msg - assert block is not None and block.foliage_transaction_block is not None + assert block.foliage_transaction_block is not None all_removals: list[CoinRecord] = await self.full_node.coin_store.get_coins_removed_at_height( block.height diff --git a/chia/full_node/full_node_rpc_api.py b/chia/full_node/full_node_rpc_api.py index 9be2225378..950da43bec 100644 --- a/chia/full_node/full_node_rpc_api.py +++ b/chia/full_node/full_node_rpc_api.py @@ -1131,7 +1131,7 @@ class FullNodeRpcApi: last_peak_timestamp = peak.timestamp peak_with_timestamp = peak_height # Last transaction block height last_tx_block = self.service.blockchain.height_to_block_record(peak_with_timestamp) - while last_tx_block is None or last_peak_timestamp is None: + while last_peak_timestamp is None: peak_with_timestamp -= 1 last_tx_block = self.service.blockchain.height_to_block_record(peak_with_timestamp) last_peak_timestamp = last_tx_block.timestamp diff --git a/chia/full_node/weight_proof.py b/chia/full_node/weight_proof.py index 87966458e4..7c2a874131 100644 --- a/chia/full_node/weight_proof.py +++ b/chia/full_node/weight_proof.py @@ -157,7 +157,7 @@ class WeightProofHandler: # sample sub epoch # next sub block ses_block = ses_blocks[sub_epoch_n] - if ses_block is None or ses_block.sub_epoch_summary_included is None: + if ses_block.sub_epoch_summary_included is None: log.error("error while building proof") return None @@ -279,7 +279,7 @@ class WeightProofHandler: if ses_height > peak_height: break ses_block = ses_blocks[sub_epoch_n] - if ses_block is None or ses_block.sub_epoch_summary_included is None: + if ses_block.sub_epoch_summary_included is None: log.error("error while building proof") return None await self.__create_persist_segment(prev_ses_block, ses_block, ses_height, sub_epoch_n) @@ -655,7 +655,7 @@ class WeightProofHandler: if idx == len(received_summaries) - 1: # end of wp summaries, local chain is longer or equal to wp chain break - if local_ses is None or local_ses.get_hash() != received_summaries[idx].get_hash(): + if local_ses.get_hash() != received_summaries[idx].get_hash(): break fork_point_index = idx @@ -786,11 +786,7 @@ def handle_finished_slots(end_of_slot: EndOfSubSlotBundle, icc_end_of_slot_info: None, None, None, - ( - None - if end_of_slot.proofs.challenge_chain_slot_proof is None - else end_of_slot.proofs.challenge_chain_slot_proof - ), + end_of_slot.proofs.challenge_chain_slot_proof, ( None if end_of_slot.proofs.infused_challenge_chain_slot_proof is None @@ -1285,7 +1281,7 @@ def validate_recent_blocks( # we need at least two challenges and more than 2 transaction blocks in the cache to validate pospace # otherwise we might fail to validate due to lack of information - if (challenge is not None) and (prev_challenge is not None) and transaction_blocks > 2: + if (prev_challenge is not None) and transaction_blocks > 2: overflow = is_overflow_block(constants, block.reward_chain_block.signage_point_index) if not adjusted: assert prev_block_record is not None @@ -1473,9 +1469,9 @@ def __get_rc_sub_slot( if idx >= 2 and slots[idx - 2].cc_slot_end is None: slots_n = 2 - new_diff = None if ses is None else ses.new_difficulty - new_ssi = None if ses is None else ses.new_sub_slot_iters - ses_hash: bytes32 | None = None if ses is None else ses.get_hash() + new_diff = ses.new_difficulty + new_ssi = ses.new_sub_slot_iters + ses_hash: bytes32 | None = ses.get_hash() overflow = is_overflow_block(constants, first.signage_point_index) if overflow: if idx >= 2 and slots[idx - 2].cc_slot_end is not None and slots[idx - 1].cc_slot_end is not None: diff --git a/chia/introducer/introducer_api.py b/chia/introducer/introducer_api.py index 44d0b9e508..89a9fa87fd 100644 --- a/chia/introducer/introducer_api.py +++ b/chia/introducer/introducer_api.py @@ -44,7 +44,7 @@ class IntroducerAPI: peer: WSChiaConnection, ) -> Message | None: max_peers = self.introducer.max_peers_to_send - if self.introducer.server is None or self.introducer.server.introducer_peers is None: + if self.introducer.server.introducer_peers is None: return None rawpeers = self.introducer.server.introducer_peers.get_peers( max_peers * 5, True, self.introducer.recent_peer_threshold diff --git a/chia/plot_sync/sender.py b/chia/plot_sync/sender.py index 520147c9a5..c0d2037aba 100644 --- a/chia/plot_sync/sender.py +++ b/chia/plot_sync/sender.py @@ -337,7 +337,8 @@ class Sender: if self._stop_requested: return await asyncio.sleep(0.1) - while not self._stop_requested and self.sync_active(): + # _stop_requested may be set concurrently by stop() during the awaits below + while not self._stop_requested and self.sync_active(): # type: ignore[redundant-expr] if self._next_message_id >= len(self._messages): await asyncio.sleep(0.1) continue diff --git a/chia/rpc/rpc_server.py b/chia/rpc/rpc_server.py index bec1be1386..49e36f18c8 100644 --- a/chia/rpc/rpc_server.py +++ b/chia/rpc/rpc_server.py @@ -239,7 +239,8 @@ class RpcServer(Generic[_T_RpcApiProtocol]): for payload in payloads: if "success" not in payload["data"]: payload["data"]["success"] = True - if self.websocket is None or self.websocket.closed: + # websocket may be closed/cleared concurrently across the awaits in this loop + if self.websocket is None or self.websocket.closed: # type: ignore[redundant-expr] return None try: await self.websocket.send_str(dict_to_json_str(payload)) diff --git a/chia/server/address_manager.py b/chia/server/address_manager.py index be36315af5..4e34b1f631 100644 --- a/chia/server/address_manager.py +++ b/chia/server/address_manager.py @@ -520,7 +520,7 @@ class AddressManager: def delete_new_entry_(self, node_id: int) -> None: info = self.map_info[node_id] - if info is None or info.random_pos is None: + if info.random_pos is None: return None self.swap_random_(info.random_pos, len(self.random_pos) - 1) self.random_pos = self.random_pos[:-1] diff --git a/chia/server/chia_policy.py b/chia/server/chia_policy.py index 806d4317b8..98ba57a42b 100644 --- a/chia/server/chia_policy.py +++ b/chia/server/chia_policy.py @@ -157,7 +157,7 @@ class PausableServer(BaseEventsServer): logging.getLogger(__name__).debug(f"Connection lost. Total connections: {active_connections}") if ( active_connections > 0 - and self._sockets is not None + and self._sockets is not None # type: ignore[redundant-expr] # asyncio sets Server._sockets to None on close and self._paused and active_connections < self.max_concurrent_connections ): diff --git a/chia/server/ws_connection.py b/chia/server/ws_connection.py index 4fcf4f1073..667a1c2013 100644 --- a/chia/server/ws_connection.py +++ b/chia/server/ws_connection.py @@ -414,7 +414,7 @@ class WSChiaConnection: self.incoming_message_task.cancel() if self.outbound_task is not None: self.outbound_task.cancel() - if self.ws is not None and self.ws.closed is False: + if self.ws.closed is False: await self.ws.close(code=ws_close_code, message=message) if self.session is not None: await self.session.close() @@ -843,7 +843,7 @@ class WSChiaConnection: assert message.id is not None rl_window = self.rate_limit_windows[message_type] # Drop and retry this message if sending it exceeds the window - if peer_subject_to_rl and window_size is not None and rl_window.in_flight >= window_size: + if peer_subject_to_rl and rl_window.in_flight >= window_size: create_referenced_task(self._wait_and_retry(message, priority=priority), known_unreferenced=True) details = ", ".join( [ diff --git a/chia/types/mempool_item.py b/chia/types/mempool_item.py index 10cd606db3..ca10ce1414 100644 --- a/chia/types/mempool_item.py +++ b/chia/types/mempool_item.py @@ -82,11 +82,11 @@ class MempoolItem: @property def cost(self) -> uint64: - return uint64(0 if self.conds is None else self.conds.cost) + return uint64(self.conds.cost) @property def num_spends(self) -> int: - return 0 if self.conds is None else len(self.conds.spends) + return len(self.conds.spends) @property def virtual_cost(self) -> uint64: diff --git a/chia/util/config.py b/chia/util/config.py index 6f132a3eed..3d96137be2 100644 --- a/chia/util/config.py +++ b/chia/util/config.py @@ -236,7 +236,7 @@ def traverse_dict(d: dict[str, Any], key_path: str) -> Any: # Extract one path component at a time components = key_path.split(":", maxsplit=1) - if components is None or len(components) == 0: + if len(components) == 0: raise KeyError(f"invalid config key path: {key_path}") key = components[0] diff --git a/chia/util/keychain.py b/chia/util/keychain.py index 469f2507d1..3aca0de23d 100644 --- a/chia/util/keychain.py +++ b/chia/util/keychain.py @@ -427,7 +427,7 @@ class Keychain: for index in range(MAX_KEYS): try: key_data = self._get_key_data(index, include_secrets=include_secrets) - if key_data is None or (skip_public_only and key_data.secrets is None): + if skip_public_only and key_data.secrets is None: continue yield key_data except KeychainUserNotFound: @@ -506,7 +506,7 @@ class Keychain: for index in range(MAX_KEYS): try: key_data = self._get_key_data(index, include_secrets=False) - if key_data is not None and key_data.fingerprint == fingerprint: + if key_data.fingerprint == fingerprint: try: self.keyring_wrapper.keyring.delete_label(key_data.fingerprint) except (KeychainException, NotImplementedError): diff --git a/chia/util/streamable.py b/chia/util/streamable.py index e81e7adccd..33ae62e094 100644 --- a/chia/util/streamable.py +++ b/chia/util/streamable.py @@ -371,7 +371,7 @@ def recurse_jsonify( def parse_bool(f: BinaryIO) -> bool: bool_byte = f.read(1) - assert bool_byte is not None and len(bool_byte) == 1 # Checks for EOF + assert len(bool_byte) == 1 # Checks for EOF if bool_byte == bytes([0]): return False elif bool_byte == bytes([1]): @@ -382,7 +382,7 @@ def parse_bool(f: BinaryIO) -> bool: def parse_uint32(f: BinaryIO, byteorder: Literal["little", "big"] = "big") -> uint32: size_bytes = f.read(4) - assert size_bytes is not None and len(size_bytes) == 4 # Checks for EOF + assert len(size_bytes) == 4 # Checks for EOF return uint32(int.from_bytes(size_bytes, byteorder)) @@ -392,7 +392,7 @@ def write_uint32(f: BinaryIO, value: uint32, byteorder: Literal["little", "big"] def parse_optional(f: BinaryIO, parse_inner_type_f: ParseFunctionType) -> object | None: is_present_bytes = f.read(1) - assert is_present_bytes is not None and len(is_present_bytes) == 1 # Checks for EOF + assert len(is_present_bytes) == 1 # Checks for EOF if is_present_bytes == bytes([0]): return None elif is_present_bytes == bytes([1]): @@ -412,7 +412,7 @@ def parse_rust(f: BinaryIO, f_type: type[Any]) -> Any: def parse_bytes(f: BinaryIO) -> bytes: list_size = parse_uint32(f) bytes_read = f.read(list_size) - assert bytes_read is not None and len(bytes_read) == list_size + assert len(bytes_read) == list_size return bytes_read @@ -470,7 +470,7 @@ def parse_dict( def parse_str(f: BinaryIO) -> str: str_size = parse_uint32(f) str_read_bytes = f.read(str_size) - assert str_read_bytes is not None and len(str_read_bytes) == str_size # Checks for EOF + assert len(str_read_bytes) == str_size # Checks for EOF return bytes.decode(str_read_bytes, "utf-8") diff --git a/chia/util/virtual_project_analysis.py b/chia/util/virtual_project_analysis.py index f5732d2c5a..389b9487ab 100644 --- a/chia/util/virtual_project_analysis.py +++ b/chia/util/virtual_project_analysis.py @@ -108,7 +108,7 @@ def build_virtual_dependency_graph( virtual_graph.setdefault(root, []) dependency_files = [ChiaFile.parse(Path(imp)) for imp in imports] - dependencies = [f.annotations.package for f in dependency_files if f.annotations is not None] + dependencies = [f.annotations.package for f in dependency_files] virtual_graph[root].extend(dependencies) @@ -189,21 +189,14 @@ def find_cycles( # Parse the parent package file. dependent_file = ChiaFile.parse(dependent) # Skip this package if it has no annotations or should be ignored in cycle detection. - if ( - dependent_file.annotations is None - or dependent_file.annotations.package in ignore_cycles_in - or dependent in ignore_specific_files - ): + if dependent_file.annotations.package in ignore_cycles_in or dependent in ignore_specific_files: continue for provider in sorted(graph[dependent]): if provider in excluded_paths: continue provider_file = ChiaFile.parse(provider) - if ( - provider_file.annotations is None - or provider_file.annotations.package == dependent_file.annotations.package - ): + if provider_file.annotations.package == dependent_file.annotations.package: continue dependency_paths = find_all_dependency_paths( diff --git a/chia/wallet/derive_keys.py b/chia/wallet/derive_keys.py index 3aa8071c20..2989bc9a21 100644 --- a/chia/wallet/derive_keys.py +++ b/chia/wallet/derive_keys.py @@ -121,7 +121,7 @@ def match_address_to_sk( Checks the list of given address is a derivation of the given sk within the given number of derivations Returns a Set of the addresses that are derivations of the given sk """ - if sk is None or not addresses_to_search: + if not addresses_to_search: return set() found_addresses: set[bytes32] = set() diff --git a/chia/wallet/did_wallet/did_wallet.py b/chia/wallet/did_wallet/did_wallet.py index 3253a1b16b..67a3fab945 100644 --- a/chia/wallet/did_wallet/did_wallet.py +++ b/chia/wallet/did_wallet/did_wallet.py @@ -1052,7 +1052,7 @@ class DIDWallet: async def update_metadata(self, metadata: dict[str, str]) -> bool: # validate metadata - if not all(isinstance(k, str) and isinstance(v, str) for k, v in metadata.items()): + if not all(isinstance(v, str) for v in metadata.values()): raise ValueError("Metadata key value pairs must be strings.") did_info = DIDInfo( origin_coin=self.did_info.origin_coin, diff --git a/chia/wallet/nft_wallet/nft_wallet.py b/chia/wallet/nft_wallet/nft_wallet.py index 77221218dc..663ef9ecab 100644 --- a/chia/wallet/nft_wallet/nft_wallet.py +++ b/chia/wallet/nft_wallet/nft_wallet.py @@ -205,11 +205,7 @@ class NFTWallet: launcher_coin_states: list[CoinState] = await self.wallet_state_manager.wallet_node.get_coin_state( [singleton_id], peer=peer ) - assert ( - launcher_coin_states is not None - and len(launcher_coin_states) == 1 - and launcher_coin_states[0].spent_height is not None - ) + assert len(launcher_coin_states) == 1 and launcher_coin_states[0].spent_height is not None mint_height: uint32 = uint32(launcher_coin_states[0].spent_height) minter_did = None if uncurried_nft.supports_did: diff --git a/chia/wallet/trade_manager.py b/chia/wallet/trade_manager.py index 895401191f..bd93a57da2 100644 --- a/chia/wallet/trade_manager.py +++ b/chia/wallet/trade_manager.py @@ -463,7 +463,7 @@ class TradeManager: valid_times=parse_timelock_info(extra_conditions), ) - if success is True and trade_offer is not None and not validate_only: + if not validate_only: await self.save_trade(trade_offer, created_offer) return success, trade_offer, error diff --git a/chia/wallet/util/clvm_streamable.py b/chia/wallet/util/clvm_streamable.py index df80246426..0c7afb0543 100644 --- a/chia/wallet/util/clvm_streamable.py +++ b/chia/wallet/util/clvm_streamable.py @@ -95,7 +95,7 @@ def byte_deserialize_clvm_streamable( # TODO: this is more than _just_ a Streamable, but it is also a Streamable and that's # useful for now def is_clvm_streamable_type(v: type[object]) -> bool: - return isinstance(v, type) and issubclass(v, Streamable) and hasattr(v, "_clvm_streamable") + return issubclass(v, Streamable) and hasattr(v, "_clvm_streamable") # TODO: this is more than _just_ a Streamable, but it is also a Streamable and that's diff --git a/chia/wallet/vc_wallet/cr_cat_wallet.py b/chia/wallet/vc_wallet/cr_cat_wallet.py index 55033aad60..b0af1aef54 100644 --- a/chia/wallet/vc_wallet/cr_cat_wallet.py +++ b/chia/wallet/vc_wallet/cr_cat_wallet.py @@ -320,7 +320,7 @@ class CRCATWallet(CATWallet): async def is_coin_spendable(self, record: WalletCoinRecord) -> bool: crcat: CRCAT = self.coin_record_to_crcat(record) - if crcat.lineage_proof is not None and not crcat.lineage_proof.is_none(): + if not crcat.lineage_proof.is_none(): return True return False @@ -332,7 +332,7 @@ class CRCATWallet(CATWallet): amount: uint128 = uint128(0) for record in record_list: crcat: CRCAT = self.coin_record_to_crcat(record) - if crcat.lineage_proof is not None and not crcat.lineage_proof.is_none(): + if not crcat.lineage_proof.is_none(): amount = uint128(amount + record.coin.amount) self.log.info(f"Confirmed balance for cat wallet {self.id()} is {amount}") @@ -346,7 +346,7 @@ class CRCATWallet(CATWallet): amount: uint128 = uint128(0) for record in record_list: crcat: CRCAT = self.coin_record_to_crcat(record) - if crcat.lineage_proof is not None and not crcat.lineage_proof.is_none(): + if not crcat.lineage_proof.is_none(): amount = uint128(amount + record.coin.amount) self.log.info(f"Pending approval balance for cat wallet {self.id()} is {amount}") diff --git a/chia/wallet/wallet_node.py b/chia/wallet/wallet_node.py index ae86c943c2..e2cd00603e 100644 --- a/chia/wallet/wallet_node.py +++ b/chia/wallet/wallet_node.py @@ -564,7 +564,8 @@ class WalletNode: return None for msg, sent_peers in await self._messages_to_resend(): - if self._shut_down or self._server is None or self._wallet_state_manager is None: + # these may change concurrently during the await above (e.g. on shutdown) + if self._shut_down or self._server is None or self._wallet_state_manager is None: # type: ignore[redundant-expr] return None full_nodes = self.server.get_connections(NodeType.FULL_NODE) for peer in full_nodes: diff --git a/chia/wallet/wallet_node_api.py b/chia/wallet/wallet_node_api.py index db4716ab26..fd62edc126 100644 --- a/chia/wallet/wallet_node_api.py +++ b/chia/wallet/wallet_node_api.py @@ -154,7 +154,7 @@ class WalletNodeAPI: if self.wallet_node.wallet_peers is not None: await self.wallet_node.wallet_peers.add_peers(request.peer_list, peer.get_peer_info(), False) - if peer is not None and peer.connection_type is NodeType.INTRODUCER: + if peer.connection_type is NodeType.INTRODUCER: await peer.close() @metadata.request(peer_required=True) diff --git a/chia/wallet/wallet_state_manager.py b/chia/wallet/wallet_state_manager.py index af9fe88f68..46d0ffa785 100644 --- a/chia/wallet/wallet_state_manager.py +++ b/chia/wallet/wallet_state_manager.py @@ -1505,11 +1505,7 @@ class WalletStateManager: launcher_parent: list[CoinState] = await self.wallet_node.get_coin_state( [launcher_coin.parent_coin_info], peer=peer ) - assert ( - launcher_parent is not None - and len(launcher_parent) == 1 - and launcher_parent[0].spent_height is not None - ) + assert len(launcher_parent) == 1 and launcher_parent[0].spent_height is not None # NFTs minted out of coinbase coins would not have minter DIDs if self.constants.GENESIS_CHALLENGE[:16] in bytes( launcher_parent[0].coin.parent_coin_info @@ -1518,7 +1514,7 @@ class WalletStateManager: did_coin: list[CoinState] = await self.wallet_node.get_coin_state( [launcher_parent[0].coin.parent_coin_info], peer=peer ) - assert did_coin is not None and len(did_coin) == 1 and did_coin[0].spent_height is not None + assert len(did_coin) == 1 and did_coin[0].spent_height is not None did_spend = await fetch_coin_spend_for_coin_state(did_coin[0], peer) uncurried = uncurry_puzzle(did_spend.puzzle_reveal) did_curried_args = match_did_puzzle(uncurried.mod, uncurried.args) @@ -1908,7 +1904,7 @@ class WalletStateManager: # TODO: we need to potentially roll back the pool wallet here pass # if the new coin has not been spent (i.e not ephemeral) - elif coin_state.created_height is not None and coin_state.spent_height is None: + elif coin_state.spent_height is None: if local_record is None: await self.coin_added( coin_state.coin, @@ -1923,7 +1919,7 @@ class WalletStateManager: await self.add_interested_coin_ids([coin_name]) # if the coin has been spent - elif coin_state.created_height is not None and coin_state.spent_height is not None: + elif coin_state.spent_height is not None: self.log.debug("Coin spent: %s", coin_state) children = await self.wallet_node.fetch_children(coin_name, peer=peer, fork_height=fork_height) record = local_record @@ -2097,7 +2093,7 @@ class WalletStateManager: ) if record.wallet_type is WalletType.POOLING_WALLET: - if coin_state.spent_height is not None and coin_state.coin.amount == uint64(1): + if coin_state.coin.amount == uint64(1): singleton_wallet: PoolWallet = self.get_wallet( id=uint32(record.wallet_id), required_type=PoolWallet ) @@ -2531,7 +2527,7 @@ class WalletStateManager: for removed_coin in coins_removed: trades_by_coin = await self.trade_manager.get_trades_by_coin(removed_coin) for trade in trades_by_coin: - if trade is not None and trade.status in { + if trade.status in { TradeStatus.PENDING_CONFIRM.value, TradeStatus.PENDING_ACCEPT.value, TradeStatus.PENDING_CANCEL.value, @@ -3204,7 +3200,7 @@ class WalletStateManager: self, peer: WSChiaConnection, coin_id: bytes32, latest: bool = True ) -> tuple[CoinSpend, CoinState]: coin_state_list: list[CoinState] = await self.wallet_node.get_coin_state([coin_id], peer=peer) - if coin_state_list is None or len(coin_state_list) < 1: + if len(coin_state_list) < 1: raise ValueError(f"Coin record 0x{coin_id.hex()} not found") coin_state: CoinState = coin_state_list[0] if latest: @@ -3224,7 +3220,7 @@ class WalletStateManager: parent_coin_state_list: list[CoinState] = await self.wallet_node.get_coin_state( [coin_state.coin.parent_coin_info], peer=peer ) - if parent_coin_state_list is None or len(parent_coin_state_list) < 1: + if len(parent_coin_state_list) < 1: raise ValueError(f"Parent coin record 0x{coin_state.coin.parent_coin_info.hex()} not found") parent_coin_state: CoinState = parent_coin_state_list[0] coin_spend = await fetch_coin_spend_for_coin_state(parent_coin_state, peer) @@ -3295,7 +3291,7 @@ class WalletStateManager: launcher_coin: list[CoinState] = await self.wallet_node.get_coin_state( [uncurried_nft.singleton_launcher_id], peer=peer ) - if launcher_coin is None or len(launcher_coin) < 1 or launcher_coin[0].spent_height is None: + if len(launcher_coin) < 1 or launcher_coin[0].spent_height is None: raise ValueError(f"Launcher coin record 0x{uncurried_nft.singleton_launcher_id.hex()} not found") minter_did = await self.get_minter_did(launcher_coin[0].coin, peer) diff --git a/mypy.ini.template b/mypy.ini.template index 1ef05ec4d8..534693edc0 100644 --- a/mypy.ini.template +++ b/mypy.ini.template @@ -2,6 +2,7 @@ files = benchmarks,build_scripts,chia,tools,*.py show_error_codes = True warn_unused_ignores = True +enable_error_code = redundant-expr disallow_any_generics = True disallow_subclassing_any = True diff --git a/tools/validate_rpcs.py b/tools/validate_rpcs.py index ba1460a09b..8cfaf07550 100755 --- a/tools/validate_rpcs.py +++ b/tools/validate_rpcs.py @@ -31,7 +31,7 @@ def get_height_to_hash_filename(root_path: Path, config: dict[str, Any]) -> Path db_path_replaced: Path = root_path / config["full_node"]["database_path"] db_directory: Path = path_from_root(root_path, db_path_replaced).parent selected_network: str = config["full_node"]["selected_network"] - suffix = "" if (selected_network is None or selected_network == "mainnet") else f"-{selected_network}" + suffix = "" if selected_network == "mainnet" else f"-{selected_network}" return db_directory / f"height-to-hash{suffix}" @@ -210,7 +210,7 @@ async def cli_async( config, ): blockchain_state: dict[str, Any] = await node_client.get_blockchain_state() - if blockchain_state is None or blockchain_state["peak"] is None: + if blockchain_state["peak"] is None: # Peak height is required for the cache. print("No blockchain found. Exiting.") return