[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
This commit is contained in:
Arvid Norberg
2026-07-29 09:37:24 -05:00
committed by GitHub
parent 40e76f1706
commit fe15e9ee6f
46 changed files with 108 additions and 139 deletions
+1 -5
View File
@@ -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,
+6 -2
View File
@@ -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]]:
+5 -13
View File
@@ -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,
)
@@ -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
+1 -1
View File
@@ -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}
+3 -4
View File
@@ -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
+2 -3
View File
@@ -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)
+6 -6
View File
@@ -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
+1 -1
View File
@@ -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"
+7 -7
View File
@@ -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(
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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:
+1 -1
View File
@@ -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")
+1 -1
View File
@@ -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!")
+2 -2
View File
@@ -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 (
+1 -7
View File
@@ -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)
+1 -1
View File
@@ -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,
)
+4 -4
View File
@@ -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),
+3 -3
View File
@@ -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)
+1 -1
View File
@@ -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
+3 -3
View File
@@ -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
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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
+8 -12
View File
@@ -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:
+1 -1
View File
@@ -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
+2 -1
View File
@@ -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
+2 -1
View File
@@ -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))
+1 -1
View File
@@ -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]
+1 -1
View File
@@ -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
):
+2 -2
View File
@@ -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(
[
+2 -2
View File
@@ -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:
+1 -1
View File
@@ -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]
+2 -2
View File
@@ -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):
+5 -5
View File
@@ -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")
+3 -10
View File
@@ -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(
+1 -1
View File
@@ -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()
+1 -1
View File
@@ -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,
+1 -5
View File
@@ -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:
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+3 -3
View File
@@ -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}")
+2 -1
View File
@@ -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:
+1 -1
View File
@@ -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)
+9 -13
View File
@@ -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)
+1
View File
@@ -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
+2 -2
View File
@@ -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