Tighten up ruff ignore list (#18837)

* Tighten up ruff ignore list

* Okay that fix was indeed unsafe

* enable type-name-incorrect-variance

* enable literal-membership

* enable non-augmented-assignment

* enable useless-return

* enable global-variable-not-assigned

* -

* fixup

* Clean up roff.toml from annotations

* use ignore instead of explicit re-export

* use more descriptive names

---------

Co-authored-by: Kyle Altendorf <sda@fstab.net>
This commit is contained in:
Matt Hauff
2024-11-12 12:19:31 -07:00
committed by GitHub
co-authored by Kyle Altendorf
parent 06b2447f6c
commit 6c90a76b56
100 changed files with 197 additions and 240 deletions
+1 -1
View File
@@ -33,7 +33,7 @@ def main(*args: str) -> int:
script = "activated.sh" script = "activated.sh"
command = ["sh", os.fspath(here.joinpath(script)), env.value, *args] 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 return completed_process.returncode
+2 -2
View File
@@ -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]]]] = {} results: dict[Data, dict[Mode, list[list[int]]]] = {}
bench_results: dict[str, Any] = {"version": _version, "commit_hash": get_commit_hash()} bench_results: dict[str, Any] = {"version": _version, "commit_hash": get_commit_hash()}
for current_data, parameter in benchmark_parameter.items(): 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] = {} results[current_data] = {}
bench_results[current_data] = {} bench_results[current_data] = {}
print( 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(): for current_mode, current_mode_parameter in parameter.mode_parameter.items():
results[current_data][current_mode] = [] 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] us_iteration_results: list[int]
all_results: list[list[int]] = results[current_data][current_mode] all_results: list[list[int]] = results[current_data][current_mode]
obj = parameter.object_creation_cb() obj = parameter.object_creation_cb()
+1 -1
View File
@@ -2623,7 +2623,7 @@ class TestBodyValidation:
fork_info=fork_info, fork_info=fork_info,
) )
)[1] )[1]
assert err in [Err.BLOCK_COST_EXCEEDS_MAX] assert err == Err.BLOCK_COST_EXCEEDS_MAX
future = await pre_validate_block( future = await pre_validate_block(
b.constants, b.constants,
AugmentedBlockchain(b), AugmentedBlockchain(b),
-1
View File
@@ -194,7 +194,6 @@ def test_vcs_add_proof_reveal(capsys: object, get_test_cli_clients: tuple[TestRp
class VcsAddProofRevealRpcClient(TestWalletRpcClient): class VcsAddProofRevealRpcClient(TestWalletRpcClient):
async def vc_add_proofs(self, proofs: dict[str, Any]) -> None: async def vc_add_proofs(self, proofs: dict[str, Any]) -> None:
self.add_to_log("vc_add_proofs", (proofs,)) self.add_to_log("vc_add_proofs", (proofs,))
return None
inst_rpc_client = VcsAddProofRevealRpcClient() inst_rpc_client = VcsAddProofRevealRpcClient()
test_rpc_clients.wallet_rpc_client = inst_rpc_client test_rpc_clients.wallet_rpc_client = inst_rpc_client
-2
View File
@@ -558,7 +558,6 @@ def test_del_unconfirmed_tx(capsys: object, get_test_cli_clients: tuple[TestRpcC
class UnconfirmedTxRpcClient(TestWalletRpcClient): class UnconfirmedTxRpcClient(TestWalletRpcClient):
async def delete_unconfirmed_transactions(self, wallet_id: int) -> None: async def delete_unconfirmed_transactions(self, wallet_id: int) -> None:
self.add_to_log("delete_unconfirmed_transactions", (wallet_id,)) self.add_to_log("delete_unconfirmed_transactions", (wallet_id,))
return None
inst_rpc_client = UnconfirmedTxRpcClient() inst_rpc_client = UnconfirmedTxRpcClient()
test_rpc_clients.wallet_rpc_client = inst_rpc_client test_rpc_clients.wallet_rpc_client = inst_rpc_client
@@ -655,7 +654,6 @@ def test_add_token(capsys: object, get_test_cli_clients: tuple[TestRpcClients, P
async def set_cat_name(self, wallet_id: int, name: str) -> None: async def set_cat_name(self, wallet_id: int, name: str) -> None:
self.add_to_log("set_cat_name", (wallet_id, name)) self.add_to_log("set_cat_name", (wallet_id, name))
return None # we don't need to do anything here
inst_rpc_client = AddTokenRpcClient() inst_rpc_client = AddTokenRpcClient()
test_rpc_clients.wallet_rpc_client = inst_rpc_client test_rpc_clients.wallet_rpc_client = inst_rpc_client
@@ -171,14 +171,14 @@ def test_leaf_hash(seeded_random: Random) -> None:
data: list[tuple[bytes, bytes, bytes32]] = [] data: list[tuple[bytes, bytes, bytes32]] = []
for cycle in range(20000): for cycle in range(20000):
if cycle in (0, 1): if cycle in {0, 1}:
length = 0 length = 0
else: else:
length = seeded_random.randrange(100) length = seeded_random.randrange(100)
key = get_random_bytes(length=length, r=seeded_random) key = get_random_bytes(length=length, r=seeded_random)
if cycle in (1, 2): if cycle in {1, 2}:
length = 0 length = 0
else: else:
length = seeded_random.randrange(100) length = seeded_random.randrange(100)
+1 -1
View File
@@ -3087,7 +3087,7 @@ async def test_pagination_cmds(
) )
elif layer == InterfaceLayer.cli: elif layer == InterfaceLayer.cli:
for command in ("get_keys", "get_keys_values", "get_kv_diff"): 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] = [ args: list[str] = [
sys.executable, sys.executable,
"-m", "-m",
@@ -402,7 +402,7 @@ async def test_batch_update(
[0.4, 0.2, 0.2, 0.2], [0.4, 0.2, 0.2, 0.2],
k=1, 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: if len(keys_values) == 0:
op_type = "insert" op_type = "insert"
key = operation.to_bytes(4, byteorder="big") key = operation.to_bytes(4, byteorder="big")
+1 -1
View File
@@ -157,7 +157,7 @@ class ChiaRoot:
kwargs["stderr"] = stderr kwargs["stderr"] = stderr
try: try:
return subprocess.run(*final_args, **kwargs) return subprocess.run(*final_args, **kwargs) # noqa: PLW1510
except OSError as e: except OSError as e:
raise Exception(f"failed to run:\n {final_args}\n {kwargs}") from e raise Exception(f"failed to run:\n {final_args}\n {kwargs}") from e
+1 -1
View File
@@ -510,7 +510,7 @@ class TestFullNodeProtocol:
if msg is not None and not (len(msg.peer_list) == 1): if msg is not None and not (len(msg.peer_list) == 1):
return False return False
peer = msg.peer_list[0] 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) await time_out_assert_custom_interval(10, 1, have_msgs, True)
full_node_1.full_node.full_node_peers.address_manager = AddressManager() full_node_1.full_node.full_node_peers.address_manager = AddressManager()
+1 -1
View File
@@ -18,7 +18,7 @@ GROUP_ORDER = 0x73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000001
def int_to_public_key(index: int) -> G1Element: 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")) private_key_from_int = PrivateKey.from_bytes(index.to_bytes(32, "big"))
return private_key_from_int.get_g1() return private_key_from_int.get_g1()
+4 -4
View File
@@ -2232,7 +2232,7 @@ class TestGeneratorConditions:
# note how the list of conditions isn't correctly terminated with a # note how the list of conditions isn't correctly terminated with a
# NIL atom. This is a failure # NIL atom. This is a failure
npc_result = generator_condition_tester("(80 50) . 3", height=softfork_height) 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( @pytest.mark.parametrize(
"opcode", "opcode",
@@ -2346,7 +2346,7 @@ class TestGeneratorConditions:
max_cost=generator_base_cost + 95 * COST_PER_BYTE + ConditionCost.CREATE_COIN.value - 1, max_cost=generator_base_cost + 95 * COST_PER_BYTE + ConditionCost.CREATE_COIN.value - 1,
height=softfork_height, 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( @pytest.mark.parametrize(
"condition", "condition",
@@ -2388,11 +2388,11 @@ class TestGeneratorConditions:
max_cost=generator_base_cost + 117 * COST_PER_BYTE + expected_cost - 1, max_cost=generator_base_cost + 117 * COST_PER_BYTE + expected_cost - 1,
height=softfork_height, height=softfork_height,
) )
assert npc_result.error in [ assert npc_result.error in {
Err.GENERATOR_RUNTIME_ERROR.value, Err.GENERATOR_RUNTIME_ERROR.value,
Err.BLOCK_COST_EXCEEDS_MAX.value, Err.BLOCK_COST_EXCEEDS_MAX.value,
Err.INVALID_BLOCK_COST.value, Err.INVALID_BLOCK_COST.value,
] }
@pytest.mark.parametrize( @pytest.mark.parametrize(
"condition", "condition",
@@ -1217,9 +1217,9 @@ async def test_assert_before_expiration(
assert expect_limit is not None assert expect_limit is not None
item = mempool_manager.get_mempool_item(bundle_name) item = mempool_manager.get_mempool_item(bundle_name)
assert item is not None 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 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 assert item.assert_before_height == expect_limit
else: else:
assert False assert False
+1 -1
View File
@@ -57,7 +57,7 @@ def test_known_active_capabilities_filter(
disabled: bool, disabled: bool,
) -> None: ) -> None:
if duplicated: if duplicated:
values = values * 2 values *= 2
if disabled: if disabled:
values = [(value, "0") for value, state in values] values = [(value, "0") for value, state in values]
+1 -1
View File
@@ -100,7 +100,7 @@ async def test_daemon_terminates(signal_number: signal.Signals, chia_root: ChiaR
"chia.timelord.timelord_launcher", "chia.timelord.timelord_launcher",
"timelord_launcher", "timelord_launcher",
marks=pytest.mark.skipif( marks=pytest.mark.skipif(
sys.platform in ("win32", "cygwin"), sys.platform in {"win32", "cygwin"},
reason="windows is not supported by the timelord launcher", reason="windows is not supported by the timelord launcher",
), ),
), ),
@@ -47,7 +47,7 @@ log = logging.getLogger(__name__)
async def wait_for_plot_sync(receiver: Receiver, previous_last_sync_id: uint64) -> None: async def wait_for_plot_sync(receiver: Receiver, previous_last_sync_id: uint64) -> None:
def wait() -> bool: def wait() -> bool:
current_last_sync_id = receiver.last_sync().sync_id 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) await time_out_assert(30, wait)
+2 -2
View File
@@ -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 coin_records[i].coin.amount, ph_receiver, coin_records[i].coin
) )
await client.push_tx(spend_bundle) await client.push_tx(spend_bundle)
coin_spends = coin_spends + spend_bundle.coin_spends coin_spends += spend_bundle.coin_spends
await time_out_assert( await time_out_assert(
5, full_node_api_1.full_node.mempool_manager.get_spendbundle, spend_bundle, spend_bundle.name() 5, full_node_api_1.full_node.mempool_manager.get_spendbundle, spend_bundle, spend_bundle.name()
) )
@@ -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) block_spends = await client.get_block_spends(block.header_hash)
assert len(block_spends) == 3 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) block_spends_with_conditions = await client.get_block_spends_with_conditions(block.header_hash)
+1 -1
View File
@@ -164,7 +164,7 @@ async def test_error_conditions(
no_peers_response = await make_dns_query(use_tcp, target_address, port, no_peers) no_peers_response = await make_dns_query(use_tcp, target_address, port, no_peers)
assert no_peers_response.rcode() == dns.rcode.NOERROR 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 assert len(no_peers_response.answer) == 0 # no response, as expected
elif request_type == dns.rdatatype.ANY: # ns + soa elif request_type == dns.rdatatype.ANY: # ns + soa
assert len(no_peers_response.answer) == 2 assert len(no_peers_response.answer) == 2
+4 -4
View File
@@ -36,9 +36,9 @@ async def test_block_cache(seeded_random: random.Random) -> None:
if i == 0: if i == 0:
continue continue
assert await a.prev_block_hash([hh]) == [hashes[i - 1]] 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.try_block_record(hh) == BR(i + 1, hh, hashes[i - 1])
assert a.block_record(hh) == BR(i + 1, hashes[i], hashes[i - 1]) assert a.block_record(hh) == BR(i + 1, hh, hashes[i - 1])
assert a.height_to_hash(uint32(i + 1)) == hashes[i] assert a.height_to_hash(uint32(i + 1)) == hh
assert a.height_to_block_record(uint32(i + 1)) == BR(i + 1, hashes[i], hashes[i - 1]) assert a.height_to_block_record(uint32(i + 1)) == BR(i + 1, hh, hashes[i - 1])
assert a.contains_block(hh) assert a.contains_block(hh)
assert a.contains_height(uint32(i + 1)) assert a.contains_height(uint32(i + 1))
+2 -2
View File
@@ -336,7 +336,7 @@ class TestWriteFile:
Write a file to a location and use the default permissions. 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") pytest.skip("Setting UNIX file permissions doesn't apply to Windows")
dest_path: Path = tmp_path / "test_write_file/test_write_file.txt" dest_path: Path = tmp_path / "test_write_file/test_write_file.txt"
@@ -355,7 +355,7 @@ class TestWriteFile:
Write a file to a location and use custom permissions. 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") pytest.skip("Setting UNIX file permissions doesn't apply to Windows")
dest_path: Path = tmp_path / "test_write_file/test_write_file.txt" dest_path: Path = tmp_path / "test_write_file/test_write_file.txt"
+3 -2
View File
@@ -180,7 +180,8 @@ class TestKeychain:
# All added keys should still be valid with their label # All added keys should still be valid with their label
assert all( 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): 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) 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) 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 # 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( @pytest.mark.parametrize(
+1 -1
View File
@@ -196,7 +196,7 @@ class WalletEnvironment:
new_values: dict[str, int] = {} new_values: dict[str, int] = {}
existing_values: Balance = await self.node.get_balance(wallet_id) existing_values: Balance = await self.node.get_balance(wallet_id)
if "init" in kwargs and kwargs["init"]: 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: elif wallet_id not in self.wallet_states:
raise ValueError( raise ValueError(
f"Wallet id {wallet_id} (alias: {self.alias_wallet_id(wallet_id)}) does not have a current state. " f"Wallet id {wallet_id} (alias: {self.alias_wallet_id(wallet_id)}) does not have a current state. "
@@ -202,7 +202,7 @@ async def test_harvester_config(farmer_one_harvester: tuple[list[HarvesterServic
harvester_config["parallel_decompressor_count"] += 1 harvester_config["parallel_decompressor_count"] += 1
harvester_config["decompressor_thread_count"] += 1 harvester_config["decompressor_thread_count"] += 1
harvester_config["recursive_plot_scan"] = not harvester_config["recursive_plot_scan"] 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) res = await update_harvester_config(harvester_rpc_port, bt.root_path, harvester_config)
assert res is True assert res is True
+2 -2
View File
@@ -132,7 +132,7 @@ async def run_sync_step(receiver: Receiver, sync_step: SyncStepData) -> None:
assert receiver.current_sync().state == sync_step.state assert receiver.current_sync().state == sync_step.state
last_sync_time_before = receiver._last_sync.time_done last_sync_time_before = receiver._last_sync.time_done
# For the list types invoke the trigger function in batches # 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 step_data, _ = sync_step.args
assert len(step_data) == 10 assert len(step_data) == 10
# Invoke batches of: 1, 2, 3, 4 items and validate the data against plot store before and after # 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: for state in State:
await run_sync_step(receiver, sync_steps[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]) expected_plot_files_processed += len(sync_steps[state].args[0])
sync_data = receiver.to_dict()["syncing"] sync_data = receiver.to_dict()["syncing"]
+1 -1
View File
@@ -8,5 +8,5 @@ from chia.simulator.block_tools import get_plot_dir
def get_test_plots(sub_dir: str = "") -> list[Path]: def get_test_plots(sub_dir: str = "") -> list[Path]:
path = get_plot_dir() path = get_plot_dir()
if sub_dir != "": if sub_dir != "":
path = path / sub_dir path /= sub_dir
return list(sorted(path.glob("*.plot"))) return list(sorted(path.glob("*.plot")))
@@ -596,8 +596,6 @@ def test_validator() -> None:
conds = proposal_validator.run(solution) conds = proposal_validator.run(solution)
assert len(conds.as_python()) == 3 assert len(conds.as_python()) == 3
return
def test_spend_p2_singleton() -> None: def test_spend_p2_singleton() -> None:
# Curried values # Curried values
@@ -751,8 +749,6 @@ def test_merge_p2_singleton() -> None:
assert cca in agg_acas assert cca in agg_acas
assert merge_conds[ConditionOpcode.ASSERT_MY_COIN_ID][0].vars[0] == coin_id assert merge_conds[ConditionOpcode.ASSERT_MY_COIN_ID][0].vars[0] == coin_id
return
def test_treasury() -> None: def test_treasury() -> None:
""" """
+1 -1
View File
@@ -381,7 +381,7 @@ def test_invalid_condition(
], ],
prg: bytes, prg: bytes,
) -> None: ) -> 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") pytest.skip("condition takes arbitrary arguments")
with pytest.raises((ValueError, EvalError, KeyError)): with pytest.raises((ValueError, EvalError, KeyError)):
+1 -1
View File
@@ -121,7 +121,7 @@ async def test_notifications(
wallet_node_2.config["enable_notifications"] = True wallet_node_2.config["enable_notifications"] = True
AMOUNT = uint64(1) AMOUNT = uint64(1)
FEE = uint64(0) FEE = uint64(0)
elif case in ("allow", "allow_larger"): elif case in {"allow", "allow_larger"}:
wallet_node_2.config["required_notification_amount"] = 750000000000 wallet_node_2.config["required_notification_amount"] = 750000000000
if case == "allow_larger": if case == "allow_larger":
AMOUNT = uint64(1000000000000) AMOUNT = uint64(1000000000000)
+2 -2
View File
@@ -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: 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") pytest.skip("Setting UNIX file permissions doesn't apply to Windows")
root_path = root_path_populated_with_config 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( def test_get_last_used_fingerprint_file_cant_read_win32(
root_path_populated_with_config: Path, monkeypatch: pytest.MonkeyPatch root_path_populated_with_config: Path, monkeypatch: pytest.MonkeyPatch
) -> None: ) -> None:
if sys.platform not in ["win32", "cygwin"]: if sys.platform not in {"win32", "cygwin"}:
pytest.skip("Windows-specific test") pytest.skip("Windows-specific test")
called_read_text = False called_read_text = False
@@ -716,7 +716,7 @@ async def test_vc_lifecycle(test_syncing: bool, cost_logger: CostLogger) -> None
62, 62,
( (
cr_1.expected_announcement() 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() else malicious_cr_1.expected_announcement()
), ),
], ],
@@ -724,7 +724,7 @@ async def test_vc_lifecycle(test_syncing: bool, cost_logger: CostLogger) -> None
62, 62,
( (
cr_2.expected_announcement() 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() else malicious_cr_2.expected_announcement()
), ),
], ],
@@ -755,7 +755,7 @@ async def test_vc_lifecycle(test_syncing: bool, cost_logger: CostLogger) -> None
else: else:
vc = new_vc vc = new_vc
await sim.farm_block() 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) assert result == (MempoolInclusionStatus.FAILED, Err.ASSERT_ANNOUNCE_CONSUMED_FAILED)
elif error == "make_banned_announcement": elif error == "make_banned_announcement":
assert result == (MempoolInclusionStatus.FAILED, Err.GENERATOR_RUNTIME_ERROR) assert result == (MempoolInclusionStatus.FAILED, Err.GENERATOR_RUNTIME_ERROR)
+1 -1
View File
@@ -205,7 +205,7 @@ def _generate_command_parser(cls: type[ChiaCommand]) -> _CommandParsingStage:
click.option( click.option(
*option_args["param_decls"], *option_args["param_decls"],
type=type_arg, 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"}},
) )
) )
+2 -2
View File
@@ -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' Raise a click.Abort if the user does not respond with 'y' or 'yes'
""" """
response = input(input_message).lower() response = input(input_message).lower()
if response not in ["y", "yes"]: if response not in {"y", "yes"}:
print(abort_message) print(abort_message)
raise click.Abort() raise click.Abort()
@@ -325,7 +325,7 @@ def timelock_args(enable: Optional[bool] = None) -> Callable[[Callable[..., None
min_time=uint64.construct_optional(kwargs["valid_at"]), min_time=uint64.construct_optional(kwargs["valid_at"]),
max_time=uint64.construct_optional(kwargs["expires_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( return click.option(
+2 -2
View File
@@ -103,7 +103,7 @@ def configure(
print("Target peer count updated") print("Target peer count updated")
change_made = True change_made = True
if testnet: if testnet:
if testnet == "true" or testnet == "t": if testnet in {"true", "t"}:
print("Setting Testnet") print("Setting Testnet")
# check if network_overrides.constants.testnet11 exists # check if network_overrides.constants.testnet11 exists
if ( if (
@@ -167,7 +167,7 @@ def configure(
print("Default full node port, introducer and network setting updated") print("Default full node port, introducer and network setting updated")
change_made = True change_made = True
elif testnet == "false" or testnet == "f": elif testnet in {"false", "f"}:
print("Setting Mainnet") print("Setting Mainnet")
mainnet_port = "8444" mainnet_port = "8444"
mainnet_introducer = "introducer.chia.net" mainnet_introducer = "introducer.chia.net"
+3 -3
View File
@@ -41,8 +41,8 @@ from chia.wallet.derive_keys import (
def dict_add_new_default(updated: dict[str, Any], default: dict[str, Any], do_not_migrate_keys: dict[str, Any]) -> None: 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: for k, v in do_not_migrate_keys.items():
if k in updated and do_not_migrate_keys[k] == "": if k in updated and v == "":
updated.pop(k) updated.pop(k)
for k, v in default.items(): for k, v in default.items():
ignore = False 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 there is an intermediate key with empty string value, do not migrate all descendants
if do_not_migrate_keys.get(k, None) == "": if do_not_migrate_keys.get(k, None) == "":
do_not_migrate_keys[k] = v 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: elif k not in updated or ignore is True:
updated[k] = v updated[k] = v
+2
View File
@@ -61,6 +61,7 @@ def test_command(expected_chia_version_str: str, require_madmax: bool) -> None:
capture_output=True, capture_output=True,
encoding="utf-8", encoding="utf-8",
timeout=adjusted_timeout(30), timeout=adjusted_timeout(30),
check=False,
) )
assert chia_version_process.returncode == 0 assert chia_version_process.returncode == 0
assert chia_version_process.stderr == "" assert chia_version_process.stderr == ""
@@ -76,6 +77,7 @@ def test_command(expected_chia_version_str: str, require_madmax: bool) -> None:
capture_output=True, capture_output=True,
encoding="utf-8", encoding="utf-8",
timeout=adjusted_timeout(30), timeout=adjusted_timeout(30),
check=False,
) )
print() print()
+1 -1
View File
@@ -171,7 +171,7 @@ class AddressParamType(click.ParamType):
self.fail("Invalid Type, address must be string.", param, ctx) self.fail("Invalid Type, address must be string.", param, ctx)
try: try:
hrp, _b32data = bech32_decode(value) 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 addr_type: AddressType = AddressType.XCH
expected_prefix = ctx.obj.get("expected_prefix") if ctx else None # attempt to get cached prefix expected_prefix = ctx.obj.get("expected_prefix") if ctx else None # attempt to get cached prefix
if expected_prefix is None: if expected_prefix is None:
+1 -1
View File
@@ -76,7 +76,7 @@ def create_cmd(
if pool_url is not None and state.lower() == "local": 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") print(f" pool_url argument [{pool_url}] is not allowed when creating in 'local' state")
return 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") print(" pool_url argument (-u) is required for pool starting state")
return return
valid_initial_states = {"pool": "FARMING_TO_POOL", "local": "SELF_POOLING"} valid_initial_states = {"pool": "FARMING_TO_POOL", "local": "SELF_POOLING"}
+1 -1
View File
@@ -836,7 +836,7 @@ async def cancel_offer(
def wallet_coin_unit(typ: WalletType, address_prefix: str) -> tuple[str, int]: def wallet_coin_unit(typ: WalletType, address_prefix: str) -> tuple[str, int]:
if typ in {WalletType.CAT, WalletType.CRCAT}: if typ in {WalletType.CAT, WalletType.CRCAT}:
return "", units["cat"] 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 address_prefix, units["chia"]
return "", units["mojo"] return "", units["mojo"]
+1 -1
View File
@@ -790,7 +790,7 @@ class Blockchain:
if height == 0: if height == 0:
break break
height = height - 1 height -= 1
blocks_to_remove = self.__heights_in_cache.get(uint32(height), None) blocks_to_remove = self.__heights_in_cache.get(uint32(height), None)
def clean_block_records(self) -> None: def clean_block_records(self) -> None:
+2 -2
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import logging import logging
from typing import Any from typing import Any
from chia_rs import ConsensusConstants as ConsensusConstants from chia_rs import ConsensusConstants as ConsensusConstants # noqa: PLC0414
from chia.util.byte_types import hexstr_to_bytes from chia.util.byte_types import hexstr_to_bytes
from chia.util.hash import std_hash from chia.util.hash import std_hash
@@ -20,7 +20,7 @@ def replace_str_to_bytes(constants: ConsensusConstants, **changes: Any) -> Conse
for k, v in changes.items(): for k, v in changes.items():
if not hasattr(constants, k): if not hasattr(constants, k):
# NETWORK_TYPE used to be present in default config, but has been removed # 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') log.warning(f'invalid key in network configuration (config.yaml) "{k}". Ignoring')
continue continue
if isinstance(v, str): if isinstance(v, str):
+3 -3
View File
@@ -819,7 +819,7 @@ class WebSocketServer:
if config["state"] is not PlotState.RUNNING: if config["state"] is not PlotState.RUNNING:
return None 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_data if config["log"] is None else config["log"] + new_data
config["log_new"] = new_data config["log_new"] = new_data
self.state_changed(service_plotter, self.prepare_plot_state_message(PlotEvent.LOG_CHANGED, id)) self.state_changed(service_plotter, self.prepare_plot_state_message(PlotEvent.LOG_CHANGED, id))
@@ -888,7 +888,7 @@ class WebSocketServer:
def _bladebit_plotting_command_args(self, request: Any, ignoreCount: bool) -> list[str]: def _bladebit_plotting_command_args(self, request: Any, ignoreCount: bool) -> list[str]:
plot_type = request["plot_type"] 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}") raise ValueError(f"Unknown plot_type: {plot_type}")
command_args: list[str] = [] command_args: list[str] = []
@@ -1020,7 +1020,7 @@ class WebSocketServer:
# plotter command must be either # plotter command must be either
# 'chia plotters bladebit ramplot' or 'chia plotters bladebit diskplot' # 'chia plotters bladebit ramplot' or 'chia plotters bladebit diskplot'
plot_type = request["plot_type"] 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.append(plot_type)
command_args.extend(self._common_plotting_command_args(request, ignoreCount)) command_args.extend(self._common_plotting_command_args(request, ignoreCount))
+1 -1
View File
@@ -866,7 +866,7 @@ class DataLayer:
mirrors: list[Mirror] = await self.wallet_rpc.dl_get_mirrors(store_id) mirrors: list[Mirror] = await self.wallet_rpc.dl_get_mirrors(store_id)
urls: list[str] = [] urls: list[str] = []
for mirror in mirrors: 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] urls = [url.rstrip("/") for url in urls]
await self.data_store.update_subscriptions_from_wallet(store_id, urls) await self.data_store.update_subscriptions_from_wallet(store_id, urls)
+1 -1
View File
@@ -1665,7 +1665,7 @@ class DataStore:
# We delete all "temporary" records stored in root and ancestor tables and store only the final result. # 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.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) 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) new_root = await self.get_pending_root(store_id=store_id)
assert new_root is not None assert new_root is not None
elif status == Status.COMMITTED: elif status == Status.COMMITTED:
+1 -1
View File
@@ -14,7 +14,7 @@ from pathlib import Path
from typing import Any, Optional, overload from typing import Any, Optional, overload
from urllib.parse import urlparse from urllib.parse import urlparse
import boto3 as boto3 import boto3
import yaml import yaml
from aiohttp import web from aiohttp import web
from botocore.exceptions import ClientError from botocore.exceptions import ClientError
+2 -2
View File
@@ -344,7 +344,7 @@ class FeeStat: # TxConfirmStats
tx_sum += self.tx_ct_avg[i] tx_sum += self.tx_ct_avg[i]
if found_answer and tx_sum != 0: if found_answer and tx_sum != 0:
tx_sum = tx_sum / 2 tx_sum /= 2
for i in range(min_bucket, max_bucket): for i in range(min_bucket, max_bucket):
if self.tx_ct_avg[i] < tx_sum: if self.tx_ct_avg[i] < tx_sum:
tx_sum -= self.tx_ct_avg[i] tx_sum -= self.tx_ct_avg[i]
@@ -406,7 +406,7 @@ def init_buckets() -> list[float]:
buckets: list[float] = [] buckets: list[float] = []
while fee_rate < MAX_FEE_RATE: while fee_rate < MAX_FEE_RATE:
buckets.append(fee_rate) buckets.append(fee_rate)
fee_rate = fee_rate * STEP_SIZE fee_rate *= STEP_SIZE
buckets.append(INFINITE_FEE_RATE) buckets.append(INFINITE_FEE_RATE)
return buckets return buckets
+1 -1
View File
@@ -1618,7 +1618,7 @@ class FullNode:
agg_state_change_summary.additions + state_change_summary.additions, agg_state_change_summary.additions + state_change_summary.additions,
agg_state_change_summary.new_rewards + state_change_summary.new_rewards, 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: if error is not None:
self.log.error(f"Error: {error}, Invalid block from peer: {peer_info} ") self.log.error(f"Error: {error}, Invalid block from peer: {peer_info} ")
return agg_state_change_summary, error return agg_state_change_summary, error
-1
View File
@@ -413,7 +413,6 @@ class FullNodeAPI:
@metadata.request() @metadata.request()
async def respond_blocks(self, request: full_node_protocol.RespondBlocks) -> None: async def respond_blocks(self, request: full_node_protocol.RespondBlocks) -> None:
self.log.warning("Received unsolicited/late blocks") self.log.warning("Received unsolicited/late blocks")
return None
@metadata.request(peer_required=True) @metadata.request(peer_required=True)
async def respond_block( async def respond_block(
+1 -1
View File
@@ -46,7 +46,7 @@ def get_name_puzzle_conditions(
flags = get_flags_for_height_and_constants(height, constants) | DONT_VALIDATE_SIGNATURE flags = get_flags_for_height_and_constants(height, constants) | DONT_VALIDATE_SIGNATURE
if mempool_mode: if mempool_mode:
flags = flags | MEMPOOL_MODE flags |= MEMPOOL_MODE
if height >= constants.HARD_FORK_HEIGHT: if height >= constants.HARD_FORK_HEIGHT:
run_block = run_block_generator2 run_block = run_block_generator2
+2 -2
View File
@@ -418,7 +418,7 @@ class MempoolManager:
child_coin = Coin(coin_id, puzzle_hash, uint64(amount)) child_coin = Coin(coin_id, puzzle_hash, uint64(amount))
spend_additions.append(child_coin) spend_additions.append(child_coin)
additions_dict[child_coin.name()] = 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_dedup = bool(spend.flags & ELIGIBLE_FOR_DEDUP)
is_eligible_for_ff = bool(spend.flags & ELIGIBLE_FOR_FF) is_eligible_for_ff = bool(spend.flags & ELIGIBLE_FOR_FF)
eligibility_and_additions[coin_id] = EligibilityAndAdditions( eligibility_and_additions[coin_id] = EligibilityAndAdditions(
@@ -481,7 +481,7 @@ class MempoolManager:
removal_record_dict[name] = removal_record removal_record_dict[name] = removal_record
else: else:
removal_record = removal_record_dict[name] 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) fees = uint64(removal_amount - addition_amount)
+5 -7
View File
@@ -880,7 +880,7 @@ def _map_sub_epoch_summaries(
if idx < len(sub_epoch_data) - 1: if idx < len(sub_epoch_data) - 1:
delta = 0 delta = 0
if idx > 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} ") log.debug(f"sub epoch {idx} start weight is {total_weight + curr_difficulty} ")
sub_epoch_weight_list.append(uint128(total_weight + curr_difficulty)) sub_epoch_weight_list.append(uint128(total_weight + curr_difficulty))
total_weight = uint128( total_weight = uint128(
@@ -1001,9 +1001,7 @@ def _validate_segment(
if required_iters is None: if required_iters is None:
return False, uint64(0), uint64(0), uint64(0), [] return False, uint64(0), uint64(0), uint64(0), []
assert sub_slot_data.signage_point_index is not None assert sub_slot_data.signage_point_index is not None
ip_iters = ip_iters + calculate_ip_iters( ip_iters += calculate_ip_iters(constants, curr_ssi, sub_slot_data.signage_point_index, required_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) vdf_list = _get_challenge_block_vdfs(constants, idx, segment.sub_slots, curr_ssi)
to_validate.extend(vdf_list) to_validate.extend(vdf_list)
elif sampled and after_challenge: elif sampled and after_challenge:
@@ -1012,8 +1010,8 @@ def _validate_segment(
log.error(f"failed to validate sub slot data {idx} vdfs") log.error(f"failed to validate sub slot data {idx} vdfs")
return False, uint64(0), uint64(0), uint64(0), [] return False, uint64(0), uint64(0), uint64(0), []
to_validate.extend(vdf_list) to_validate.extend(vdf_list)
slot_iters = slot_iters + curr_ssi slot_iters += curr_ssi
slots = slots + uint64(1) slots += uint64(1)
return True, ip_iters, slot_iters, slots, to_validate return True, ip_iters, slot_iters, slots, to_validate
@@ -1268,7 +1266,7 @@ def validate_recent_blocks(
if ret is None: if ret is None:
return False, [] return False, []
required_iters = ret 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] curr_block_ses = None if not ses else summaries[ses_idx - 1]
block_record = header_block_to_sub_block_record( block_record = header_block_to_sub_block_record(
+1 -1
View File
@@ -267,7 +267,7 @@ class Sender:
sync_id = int(time.time()) 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) # 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: if sync_id == self._last_sync_id:
sync_id = sync_id + 1 sync_id += 1
log.debug(f"sync_start {sync_id}") log.debug(f"sync_start {sync_id}")
self._sync_id = uint64(sync_id) self._sync_id = uint64(sync_id)
self._add_message( self._add_message(
+6 -6
View File
@@ -20,7 +20,7 @@ BLADEBIT_PLOTTER_DIR = "bladebit"
def is_bladebit_supported() -> bool: def is_bladebit_supported() -> bool:
# bladebit >= 2.0.0 now supports macOS # 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]]: 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: def get_bladebit_exec_path(with_cuda: bool = False) -> str:
if with_cuda: if with_cuda:
return "bladebit_cuda.exe" if sys.platform in ["win32", "cygwin"] else "bladebit_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.exe" if sys.platform in {"win32", "cygwin"} else "bladebit"
def get_bladebit_exec_venv_path(with_cuda: bool = False) -> Optional[Path]: 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: 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) 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) bladebit_exec = get_bladebit_exec_path(with_cuda)
return bladebit_src_dir / build_dir / bladebit_exec 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.") print("Bladebit was not found.")
return return
if sys.platform in ["win32", "cygwin"]: if sys.platform in {"win32", "cygwin"}:
reset_loop_policy_for_windows() reset_loop_policy_for_windows()
plot_keys = asyncio.run( plot_keys = asyncio.run(
@@ -286,7 +286,7 @@ def plot_bladebit(args, chia_root_path, root_path):
args.connect_to_daemon, 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 plot_type = args.plot_type
else: else:
plot_type = "diskplot" plot_type = "diskplot"
+4 -4
View File
@@ -18,7 +18,7 @@ MADMAX_PLOTTER_DIR = "madmax-plotter"
def is_madmax_supported() -> bool: 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: 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" madmax_exec = "chia_plot"
if ksize > 32: if ksize > 32:
madmax_exec += "_k34" # Use the chia_plot_k34 executable for k-sizes > 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" madmax_exec += ".exe"
return venv_bin_path / madmax_exec 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" madmax_exec = "chia_plot"
if ksize > 32: if ksize > 32:
madmax_exec += "_k34" # Use the chia_plot_k34 executable for k-sizes > 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" madmax_exec += ".exe"
return madmax_src_dir / madmax_exec 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" madmax_exec: str = "chia_plot"
if ksize > 32: if ksize > 32:
madmax_exec += "_k34" # Use the chia_plot_k34 executable for k-sizes > 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" madmax_exec += ".exe"
return madmax_dir / madmax_exec return madmax_dir / madmax_exec
+1 -1
View File
@@ -60,7 +60,7 @@ async def run_plotter(root_path, plotter, args, progress_dict):
process.terminate() process.terminate()
# For Windows, we'll install a SIGINT handler to catch Ctrl-C (KeyboardInterrupt isn't raised) # 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) signal.signal(signal.SIGINT, sigint_handler)
installed_sigint_handler = True installed_sigint_handler = True
+5 -5
View File
@@ -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 # Verify that a puzzle is a Pool Wallet Singleton
def is_pool_singleton_inner_puzzle(inner_puzzle: Program) -> bool: def is_pool_singleton_inner_puzzle(inner_puzzle: Program) -> bool:
inner_f = get_template_singleton_inner_puzzle(inner_puzzle) 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: def is_pool_waitingroom_inner_puzzle(inner_puzzle: Program) -> bool:
inner_f = get_template_singleton_inner_puzzle(inner_puzzle) 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: def is_pool_member_inner_puzzle(inner_puzzle: Program) -> bool:
inner_f = get_template_singleton_inner_puzzle(inner_puzzle) 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 # 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 # Spend which is not absorb, and is not the launcher
num_args = len(inner_solution.as_python()) num_args = len(inner_solution.as_python())
assert num_args in (2, 3) assert num_args in {2, 3}
if num_args == 2: if num_args == 2:
# pool member # pool member
@@ -445,7 +445,7 @@ def pool_state_to_inner_puzzle(
delay_time, delay_time,
delay_ph, 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 return escaping_inner_puzzle
else: else:
return create_pooling_inner_puzzle( return create_pooling_inner_puzzle(
+5 -8
View File
@@ -137,7 +137,7 @@ class PoolWallet:
@classmethod @classmethod
def _verify_self_pooled(cls, state: PoolState) -> Optional[str]: def _verify_self_pooled(cls, state: PoolState) -> Optional[str]:
err = "" err = ""
if state.pool_url not in [None, ""]: if state.pool_url not in {None, ""}:
err += " Unneeded pool_url for self-pooling" err += " Unneeded pool_url for self-pooling"
if state.relative_lock_height != 0: if state.relative_lock_height != 0:
@@ -159,7 +159,7 @@ class PoolWallet:
f"is greater than recommended maximum ({cls.MAXIMUM_RELATIVE_LOCK_HEIGHT})" 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" err += " Empty pool url in pooling state"
return err return err
@@ -177,10 +177,7 @@ class PoolWallet:
if state.state == PoolSingletonState.SELF_POOLING.value: if state.state == PoolSingletonState.SELF_POOLING.value:
return cls._verify_self_pooled(state) return cls._verify_self_pooled(state)
elif ( elif state.state in {PoolSingletonState.FARMING_TO_POOL.value, PoolSingletonState.LEAVING_POOL.value}:
state.state == PoolSingletonState.FARMING_TO_POOL.value
or state.state == PoolSingletonState.LEAVING_POOL.value
):
return cls._verify_pooling_state(state) return cls._verify_pooling_state(state)
else: else:
return "Internal Error" return "Internal Error"
@@ -663,7 +660,7 @@ class PoolWallet:
msg = f"Asked to change to current state. Target = {target_state}" msg = f"Asked to change to current state. Target = {target_state}"
self.log.info(msg) self.log.info(msg)
raise ValueError(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 total_fee = fee
elif current_state.current.state == FARMING_TO_POOL.value: elif current_state.current.state == FARMING_TO_POOL.value:
total_fee = uint64(fee * 2) total_fee = uint64(fee * 2)
@@ -846,7 +843,7 @@ class PoolWallet:
raise ValueError(f"Internal error. Pool wallet {self.wallet_id} state: {pool_wallet_info.current}") raise ValueError(f"Internal error. Pool wallet {self.wallet_id} state: {pool_wallet_info.current}")
if ( 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 and pool_wallet_info.current.state == LEAVING_POOL.value
): ):
leave_height = tip_height + pool_wallet_info.current.relative_lock_height leave_height = tip_height + pool_wallet_info.current.relative_lock_height
+1 -1
View File
@@ -30,7 +30,7 @@ class CrawlerRpcApi:
if change_data is None: if change_data is None:
change_data = await self.get_peer_counts({}) 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")) payloads.append(create_payload_dict(change, change_data, self.service_name, "metrics"))
return payloads return payloads
+2 -2
View File
@@ -132,7 +132,7 @@ class FullNodeRpcApi:
change_data = {} change_data = {}
payloads = [] payloads = []
if change == "new_peak" or change == "sync_mode": if change in {"new_peak", "sync_mode"}:
data = await self.get_blockchain_state({}) data = await self.get_blockchain_state({})
assert data is not None assert data is not None
payloads.append( payloads.append(
@@ -152,7 +152,7 @@ class FullNodeRpcApi:
) )
) )
if change in ("block", "signage_point"): if change in {"block", "signage_point"}:
payloads.append(create_payload_dict(change, change_data, self.service_name, "metrics")) payloads.append(create_payload_dict(change, change_data, self.service_name, "metrics"))
if change == "unfinished_block": if change == "unfinished_block":
+1 -1
View File
@@ -202,7 +202,7 @@ class RpcServer(Generic[_T_RpcApiProtocol]):
return None return None
payloads: list[WsRpcMessage] = await self.rpc_api._state_changed(change, change_data) 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({}) data = await self.get_connections({})
if data is not None: if data is not None:
payload = create_payload_dict( payload = create_payload_dict(
+1 -1
View File
@@ -26,7 +26,7 @@ class TimelordRpcApi:
if change_data is None: if change_data is None:
change_data = {} 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")) payloads.append(create_payload_dict(change, change_data, self.service_name, "metrics"))
return payloads return payloads
+1 -3
View File
@@ -209,9 +209,7 @@ def tx_endpoint(
if ( if (
func.__name__ == "create_new_wallet" func.__name__ == "create_new_wallet"
and request["wallet_type"] == "pool_wallet" and request["wallet_type"] == "pool_wallet"
or func.__name__ == "pw_join_pool" or func.__name__ in {"pw_join_pool", "pw_self_pool", "pw_absorb_rewards"}
or func.__name__ == "pw_self_pool"
or func.__name__ == "pw_absorb_rewards"
): ):
# Theses RPCs return not "convenience" for some reason # Theses RPCs return not "convenience" for some reason
response["transaction"] = new_txs[-1].to_json_dict() response["transaction"] = new_txs[-1].to_json_dict()
+8 -8
View File
@@ -1785,7 +1785,7 @@ class WalletRpcApi:
except ValueError: except ValueError:
raise ValueError(f"Invalid signing mode: {signing_mode_str!r}") 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: # CHIP-0002 message signatures are made over the tree hash of:
# ("Chia Signed Message", message) # ("Chia Signed Message", message)
message_to_verify: bytes = Program.to((CHIP_0002_SIGN_MESSAGE_PREFIX, input_message)).get_tree_hash() message_to_verify: bytes = Program.to((CHIP_0002_SIGN_MESSAGE_PREFIX, input_message)).get_tree_hash()
@@ -2086,11 +2086,11 @@ class WalletRpcApi:
driver_dict[bytes32.from_hexstr(key)] = PuzzleInfo(value) driver_dict[bytes32.from_hexstr(key)] = PuzzleInfo(value)
modified_offer: dict[Union[int, bytes32], int] = {} modified_offer: dict[Union[int, bytes32], int] = {}
for key in offer: for wallet_identifier, change in offer.items():
try: try:
modified_offer[bytes32.from_hexstr(key)] = offer[key] modified_offer[bytes32.from_hexstr(wallet_identifier)] = change
except ValueError: except ValueError:
modified_offer[int(key)] = offer[key] modified_offer[int(wallet_identifier)] = change
async with self.service.wallet_state_manager.lock: async with self.service.wallet_state_manager.lock:
result = await self.service.wallet_state_manager.trade_manager.create_offer_for_ids( result = await self.service.wallet_state_manager.trade_manager.create_offer_for_ids(
@@ -2149,12 +2149,12 @@ class WalletRpcApi:
k: v k: v
for k, v in valid_times.to_json_dict().items() for k, v in valid_times.to_json_dict().items()
if k if k
not in ( not in {
"max_secs_after_created", "max_secs_after_created",
"min_secs_since_created", "min_secs_since_created",
"max_blocks_after_created", "max_blocks_after_created",
"min_blocks_since_created", "min_blocks_since_created",
) }
}, },
}, },
"id": offer.name(), "id": offer.name(),
@@ -2963,7 +2963,7 @@ class WalletRpcApi:
wallet_type = self.service.wallet_state_manager.wallets[funding_wallet_id].type() wallet_type = self.service.wallet_state_manager.wallets[funding_wallet_id].type()
amount = request.get("amount") amount = request.get("amount")
assert 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") raise ValueError(f"Cannot fund a treasury with assets from a {wallet_type.name} wallet")
await dao_wallet.create_add_funds_to_treasury_spend( await dao_wallet.create_add_funds_to_treasury_spend(
uint64(amount), uint64(amount),
@@ -3815,7 +3815,7 @@ class WalletRpcApi:
royalty_address = request.get("royalty_address", None) royalty_address = request.get("royalty_address", None)
if isinstance(royalty_address, str) and royalty_address != "": if isinstance(royalty_address, str) and royalty_address != "":
royalty_puzhash = decode_puzzle_hash(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() royalty_puzhash = await nft_wallet.standard_wallet.get_new_puzzlehash()
else: else:
royalty_puzhash = bytes32.from_hexstr(royalty_address) royalty_puzhash = bytes32.from_hexstr(royalty_address)
+1 -1
View File
@@ -504,7 +504,7 @@ class DNSServer:
valid_domain = True valid_domain = True
for response in domain_responses: for response in domain_responses:
rqt: int = getattr(QTYPE, response.__class__.__name__) 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)) 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 if not valid_domain and len(reply.rr) == 0: # if we didn't find any records to return
reply.header.rcode = RCODE.NXDOMAIN reply.header.rcode = RCODE.NXDOMAIN
+2 -2
View File
@@ -81,7 +81,7 @@ class ExtendedPeerInfo:
bytes(std_hash(key.to_bytes(32, byteorder="big") + self.peer_info.get_key())[:8]), bytes(std_hash(key.to_bytes(32, byteorder="big") + self.peer_info.get_key())[:8]),
byteorder="big", byteorder="big",
) )
hash1 = hash1 % TRIED_BUCKETS_PER_GROUP hash1 %= TRIED_BUCKETS_PER_GROUP
hash2 = int.from_bytes( hash2 = int.from_bytes(
bytes(std_hash(key.to_bytes(32, byteorder="big") + self.peer_info.get_group() + bytes([hash1]))[:8]), bytes(std_hash(key.to_bytes(32, byteorder="big") + self.peer_info.get_group() + bytes([hash1]))[:8]),
byteorder="big", byteorder="big",
@@ -96,7 +96,7 @@ class ExtendedPeerInfo:
bytes(std_hash(key.to_bytes(32, byteorder="big") + self.peer_info.get_group() + src_peer.get_group())[:8]), bytes(std_hash(key.to_bytes(32, byteorder="big") + self.peer_info.get_group() + src_peer.get_group())[:8]),
byteorder="big", byteorder="big",
) )
hash1 = hash1 % NEW_BUCKETS_PER_SOURCE_GROUP hash1 %= NEW_BUCKETS_PER_SOURCE_GROUP
hash2 = int.from_bytes( hash2 = int.from_bytes(
bytes(std_hash(key.to_bytes(32, byteorder="big") + src_peer.get_group() + bytes([hash1]))[:8]), bytes(std_hash(key.to_bytes(32, byteorder="big") + src_peer.get_group() + bytes([hash1]))[:8]),
byteorder="big", byteorder="big",
+4 -4
View File
@@ -261,10 +261,10 @@ if sys.platform == "win32":
try: try:
return await self._chia_accept(listener) return await self._chia_accept(listener)
except OSError as exc: except OSError as exc:
if exc.winerror not in ( if exc.winerror not in {
_winapi.ERROR_NETNAME_DELETED, _winapi.ERROR_NETNAME_DELETED,
_winapi.ERROR_OPERATION_ABORTED, _winapi.ERROR_OPERATION_ABORTED,
): }:
raise raise
def _chia_accept(self, listener: socket.socket) -> asyncio.Future[tuple[socket.socket, tuple[object, ...]]]: def _chia_accept(self, listener: socket.socket) -> asyncio.Future[tuple[socket.socket, tuple[object, ...]]]:
@@ -292,10 +292,10 @@ if sys.platform == "win32":
raise raise
except OSError as exc: except OSError as exc:
# https://github.com/python/cpython/issues/93821#issuecomment-1157945855 # 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_NETNAME_DELETED,
_winapi.ERROR_OPERATION_ABORTED, _winapi.ERROR_OPERATION_ABORTED,
): }:
raise raise
future = self._register(ov, listener, finish_accept) future = self._register(ov, listener, finish_accept)
+4 -3
View File
@@ -254,7 +254,7 @@ class ChiaServer:
if connection.closed: if connection.closed:
to_remove.append(connection) to_remove.append(connection)
elif ( 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: ) and connection.connection_type == NodeType.FULL_NODE:
if is_crawler is not None: if is_crawler is not None:
if time.time() - connection.creation_time > 5: if time.time() - connection.creation_time > 5:
@@ -541,8 +541,9 @@ class ChiaServer:
ban_until: float = time.time() + ban_time ban_until: float = time.time() + ban_time
self.log.warning(f"Banning {connection.peer_info.host} for {ban_time} seconds") self.log.warning(f"Banning {connection.peer_info.host} for {ban_time} seconds")
if connection.peer_info.host in self.banned_peers: 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] = max(
self.banned_peers[connection.peer_info.host] = ban_until ban_until, self.banned_peers[connection.peer_info.host]
)
else: else:
self.banned_peers[connection.peer_info.host] = ban_until self.banned_peers[connection.peer_info.host] = ban_until
-1
View File
@@ -292,7 +292,6 @@ class Service(Generic[_T_RpcServiceProtocol, _T_ApiProtocol, _T_RpcApiProtocol])
# we only handle signals in the main process. In the ProcessPoolExecutor # we only handle signals in the main process. In the ProcessPoolExecutor
# processes, we have to ignore them. We'll shut them down gracefully # processes, we have to ignore them. We'll shut them down gracefully
# from the main process # from the main process
global main_pid
ignore = os.getpid() != main_pid ignore = os.getpid() != main_pid
# TODO: if we remove this conditional behavior, consider moving logging to common signal handling # TODO: if we remove this conditional behavior, consider moving logging to common signal handling
+2 -2
View File
@@ -225,7 +225,7 @@ class WSChiaConnection:
raise ProtocolError(Err.INCOMPATIBLE_NETWORK_ID) raise ProtocolError(Err.INCOMPATIBLE_NETWORK_ID)
if ( if (
local_type in [NodeType.FARMER, NodeType.HARVESTER] local_type in {NodeType.FARMER, NodeType.HARVESTER}
and inbound_handshake.protocol_version != protocol_version[local_type] and inbound_handshake.protocol_version != protocol_version[local_type]
): ):
self.log.warning( self.log.warning(
@@ -266,7 +266,7 @@ class WSChiaConnection:
remote_node_type = NodeType(inbound_handshake.node_type) remote_node_type = NodeType(inbound_handshake.node_type)
if ( 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] and inbound_handshake.protocol_version != protocol_version[remote_node_type]
): ):
self.log.warning( self.log.warning(
+2 -2
View File
@@ -1908,7 +1908,7 @@ def conditions_cost(conds: Program) -> uint64:
elif condition == ConditionOpcode.SOFTFORK.value: elif condition == ConditionOpcode.SOFTFORK.value:
arg = cond.rest().first().as_int() arg = cond.rest().first().as_int()
condition_cost += arg * 10000 condition_cost += arg * 10000
elif condition in [ elif condition in {
ConditionOpcode.AGG_SIG_UNSAFE, ConditionOpcode.AGG_SIG_UNSAFE,
ConditionOpcode.AGG_SIG_ME, ConditionOpcode.AGG_SIG_ME,
ConditionOpcode.AGG_SIG_PARENT, ConditionOpcode.AGG_SIG_PARENT,
@@ -1917,7 +1917,7 @@ def conditions_cost(conds: Program) -> uint64:
ConditionOpcode.AGG_SIG_PUZZLE_AMOUNT, ConditionOpcode.AGG_SIG_PUZZLE_AMOUNT,
ConditionOpcode.AGG_SIG_PARENT_AMOUNT, ConditionOpcode.AGG_SIG_PARENT_AMOUNT,
ConditionOpcode.AGG_SIG_PARENT_PUZZLE, ConditionOpcode.AGG_SIG_PARENT_PUZZLE,
]: }:
condition_cost += ConditionCost.AGG_SIG.value condition_cost += ConditionCost.AGG_SIG.value
return uint64(condition_cost) return uint64(condition_cost)
+1 -3
View File
@@ -649,9 +649,7 @@ class FullNodeSimulator(FullNodeAPI):
transactions_left: set[bytes32] = {tx.name for tx in transactions} transactions_left: set[bytes32] = {tx.name for tx in transactions}
with anyio.fail_after(delay=adjusted_timeout(timeout)): with anyio.fail_after(delay=adjusted_timeout(timeout)):
for backoff in backoff_times(): for backoff in backoff_times():
transactions_left = transactions_left & { transactions_left &= {tx.name for tx in await wallet_state_manager.tx_store.get_all_unconfirmed()}
tx.name for tx in await wallet_state_manager.tx_store.get_all_unconfirmed()
}
if len(transactions_left) == 0: if len(transactions_left) == 0:
break break
-2
View File
@@ -7,8 +7,6 @@ recent_ports: set[int] = set()
def find_available_listen_port(name: str = "free") -> int: def find_available_listen_port(name: str = "free") -> int:
global recent_ports
while True: while True:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
try: try:
+3 -3
View File
@@ -121,7 +121,7 @@ class LastState:
if overflow and self.new_epoch: if overflow and self.new_epoch:
# No overflows in new epoch # No overflows in new epoch
return False 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 return True
ss_start_iters = self.get_total_iters() - self.get_last_ip() ss_start_iters = self.get_total_iters() - self.get_last_ip()
already_infused_count: int = 0 already_infused_count: int = 0
@@ -160,7 +160,7 @@ class LastState:
return self.state_type == StateType.END_OF_SUB_SLOT and self.infused_ses return self.state_type == StateType.END_OF_SUB_SLOT and self.infused_ses
def get_next_sub_epoch_summary(self) -> Optional[SubEpochSummary]: 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) # Can only infuse SES after a peak (in an end of sub slot)
return None return None
assert self.peak is not None assert self.peak is not None
@@ -233,7 +233,7 @@ class LastState:
else: else:
return None return None
elif self.state_type == StateType.END_OF_SUB_SLOT: 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() return ClassgroupElement.get_default_element()
if chain == Chain.INFUSED_CHALLENGE_CHAIN: if chain == Chain.INFUSED_CHALLENGE_CHAIN:
assert self.subslot_end is not None assert self.subslot_end is not None
+2 -2
View File
@@ -63,7 +63,7 @@ def compute_additions_with_cost(
raise ValidationError(Err.BLOCK_COST_EXCEEDS_MAX, "compute_additions() for CoinSpend") raise ValidationError(Err.BLOCK_COST_EXCEEDS_MAX, "compute_additions() for CoinSpend")
atoms = cond.as_iter() atoms = cond.as_iter()
op = next(atoms).atom op = next(atoms).atom
if op in [ if op in {
ConditionOpcode.AGG_SIG_PARENT, ConditionOpcode.AGG_SIG_PARENT,
ConditionOpcode.AGG_SIG_PUZZLE, ConditionOpcode.AGG_SIG_PUZZLE,
ConditionOpcode.AGG_SIG_AMOUNT, ConditionOpcode.AGG_SIG_AMOUNT,
@@ -72,7 +72,7 @@ def compute_additions_with_cost(
ConditionOpcode.AGG_SIG_PARENT_PUZZLE, ConditionOpcode.AGG_SIG_PARENT_PUZZLE,
ConditionOpcode.AGG_SIG_UNSAFE, ConditionOpcode.AGG_SIG_UNSAFE,
ConditionOpcode.AGG_SIG_ME, ConditionOpcode.AGG_SIG_ME,
]: }:
cost += ConditionCost.AGG_SIG.value cost += ConditionCost.AGG_SIG.value
continue continue
if op != ConditionOpcode.CREATE_COIN.value: if op != ConditionOpcode.CREATE_COIN.value:
+2 -2
View File
@@ -221,9 +221,9 @@ def str2bool(v: Union[str, bool]) -> bool:
# Source from https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse # Source from https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
if isinstance(v, bool): if isinstance(v, bool):
return v return v
if v.lower() in ("yes", "true", "True", "t", "y", "1"): if v.lower() in {"yes", "true", "True", "t", "y", "1"}:
return True return True
elif v.lower() in ("no", "false", "False", "f", "n", "0"): elif v.lower() in {"no", "false", "False", "f", "n", "0"}:
return False return False
else: else:
raise argparse.ArgumentTypeError("Boolean value expected.") raise argparse.ArgumentTypeError("Boolean value expected.")
+1 -1
View File
@@ -56,7 +56,7 @@ def skip_uint8(buf: memoryview) -> memoryview:
def skip_bool(buf: memoryview) -> memoryview: def skip_bool(buf: memoryview) -> memoryview:
assert buf[0] in [0, 1] assert buf[0] in {0, 1}
return buf[1:] return buf[1:]
+4 -4
View File
@@ -41,7 +41,7 @@ MIN_PASSPHRASE_LEN = 8
def supports_os_passphrase_storage() -> bool: 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]: def passphrase_requirements() -> dict[str, Any]:
@@ -71,7 +71,7 @@ def generate_mnemonic() -> str:
def bytes_to_mnemonic(mnemonic_bytes: bytes) -> 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( raise ValueError(
f"Data length should be one of the following: [16, 20, 24, 28, 32], but it is {len(mnemonic_bytes)}." 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: def check_mnemonic_validity(mnemonic_str: str) -> bool:
mnemonic: list[str] = mnemonic_str.split(" ") 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: 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 up words by the first 4 characters
""" """
mnemonic: list[str] = mnemonic_str.split(" ") 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") raise ValueError("Invalid mnemonic length")
four_char_dict = {word[:4]: word for word in bip39_word_list().splitlines()} four_char_dict = {word[:4]: word for word in bip39_word_list().splitlines()}
-2
View File
@@ -291,7 +291,6 @@ class KeyringWrapper:
except KeyringError as e: except KeyringError as e:
if not warn_if_macos_errSecInteractionNotAllowed(e): if not warn_if_macos_errSecInteractionNotAllowed(e):
raise raise
return None
def remove_master_passphrase_from_credential_store(self) -> None: def remove_master_passphrase_from_credential_store(self) -> None:
passphrase_store: Optional[OSPassphraseStore] = get_os_passphrase_store() passphrase_store: Optional[OSPassphraseStore] = get_os_passphrase_store()
@@ -310,7 +309,6 @@ class KeyringWrapper:
except KeyringError as e: except KeyringError as e:
if not warn_if_macos_errSecInteractionNotAllowed(e): if not warn_if_macos_errSecInteractionNotAllowed(e):
raise raise
return None
def get_master_passphrase_from_credential_store(self) -> Optional[str]: def get_master_passphrase_from_credential_store(self) -> Optional[str]:
passphrase_store: Optional[OSPassphraseStore] = get_os_passphrase_store() passphrase_store: Optional[OSPassphraseStore] = get_os_passphrase_store()
+1 -1
View File
@@ -128,7 +128,7 @@ def is_trusted_cidr(peer_host: str, trusted_cidrs: list[str]) -> bool:
def is_localhost(peer_host: 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( def is_trusted_peer(
+1 -1
View File
@@ -143,7 +143,7 @@ if __name__ == "__main__":
if len(sys.argv) == 2: if len(sys.argv) == 2:
# this analyzes the CPU usage at all slots saved to the profiler directory # this analyzes the CPU usage at all slots saved to the profiler directory
analyze_cpu_usage(profile_dir) 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 # the additional arguments are interpreted as either one slot, or a
# slot range (first and last) to analyze # slot range (first and last) to analyze
first = int(sys.argv[2]) first = int(sys.argv[2])
+1 -1
View File
@@ -216,7 +216,7 @@ def function_to_convert_one_item(
elif hasattr(f_type, "from_json_dict"): elif hasattr(f_type, "from_json_dict"):
if json_parser is None: if json_parser is None:
json_parser = f_type.from_json_dict json_parser = f_type.from_json_dict
return lambda item: json_parser(item) return json_parser
elif issubclass(f_type, bytes): elif issubclass(f_type, bytes):
# Type is bytes, data is a hex string or bytes # Type is bytes, data is a hex string or bytes
return lambda item: convert_byte_type(f_type, item) return lambda item: convert_byte_type(f_type, item)
+1 -5
View File
@@ -163,7 +163,7 @@ def get_file(frame: FrameType) -> str:
def trace_fun(frame: FrameType, event: str, arg: Any) -> None: 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 return
# we only care about instrumenting co-routines # we only care about instrumenting co-routines
@@ -176,9 +176,6 @@ def trace_fun(frame: FrameType, event: str, arg: Any) -> None:
if task is None: if task is None:
return return
global g_tasks
global g_function_infos
ti = g_tasks.get(task) ti = g_tasks.get(task)
if ti is None: if ti is None:
ti = TaskInfo() ti = TaskInfo()
@@ -265,7 +262,6 @@ def fontcolor(pct: float) -> str:
def stop_task_instrumentation(target_dir: str = f"task-profile-{os.getpid()}") -> None: def stop_task_instrumentation(target_dir: str = f"task-profile-{os.getpid()}") -> None:
sys.setprofile(None) sys.setprofile(None)
global g_function_infos
try: try:
os.mkdir(target_dir) os.mkdir(target_dir)
+2 -2
View File
@@ -288,7 +288,7 @@ class DAOCATWallet:
lockup_innerpuz_list = [] lockup_innerpuz_list = []
if running_sum + coin.amount <= amount: if running_sum + coin.amount <= amount:
vote_amount = coin.amount vote_amount = coin.amount
running_sum = running_sum + coin.amount running_sum += coin.amount
primaries = [ primaries = [
Payment( Payment(
new_innerpuzzle.get_tree_hash(), new_innerpuzzle.get_tree_hash(),
@@ -303,7 +303,7 @@ class DAOCATWallet:
) )
else: else:
vote_amount = uint64(amount - running_sum) vote_amount = uint64(amount - running_sum)
running_sum = running_sum + coin.amount running_sum += coin.amount
primaries = [ primaries = [
Payment( Payment(
new_innerpuzzle.get_tree_hash(), new_innerpuzzle.get_tree_hash(),
+1 -1
View File
@@ -812,7 +812,7 @@ class AggSig(Condition):
condition_driver.pubkey, # type: ignore[attr-defined] condition_driver.pubkey, # type: ignore[attr-defined]
condition_driver.msg, # type: ignore[attr-defined] condition_driver.msg, # type: ignore[attr-defined]
opcode, 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"}},
) )
+3 -8
View File
@@ -450,7 +450,6 @@ class DAOWallet:
self.log.info(f"DAO funding coin added: {coin.name().hex()}:{coin}. Asset ID: {asset_id}") self.log.info(f"DAO funding coin added: {coin.name().hex()}:{coin}. Asset ID: {asset_id}")
except Exception as e: # pragma: no cover except Exception as e: # pragma: no cover
self.log.exception(f"Error occurred during dao wallet coin addition: {e}") self.log.exception(f"Error occurred during dao wallet coin addition: {e}")
return
def get_cat_tail_hash(self) -> bytes32: def get_cat_tail_hash(self) -> bytes32:
cat_wallet: CATWallet = self.wallet_state_manager.wallets[self.dao_info.cat_wallet_id] cat_wallet: CATWallet = self.wallet_state_manager.wallets[self.dao_info.cat_wallet_id]
@@ -471,7 +470,6 @@ class DAOWallet:
] ]
dao_info = dataclasses.replace(self.dao_info, proposals_list=new_list) dao_info = dataclasses.replace(self.dao_info, proposals_list=new_list)
await self.save_info(dao_info) await self.save_info(dao_info)
return
async def resync_treasury_state(self) -> None: async def resync_treasury_state(self) -> None:
""" """
@@ -608,8 +606,6 @@ class DAOWallet:
response: Optional[RespondBlockHeader] = await peer.call_api(FullNodeAPI.request_block_header, request) 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) await wallet_node.sync_from_untrusted_close_to_peak(response.header_block, peer)
return
async def generate_new_dao( async def generate_new_dao(
self, self,
amount_of_cats_to_create: Optional[uint64], amount_of_cats_to_create: Optional[uint64],
@@ -1826,7 +1822,7 @@ class DAOWallet:
) )
await self.add_parent(new_state.coin.name(), future_parent) await self.add_parent(new_state.coin.name(), future_parent)
return return
index = index + 1 index += 1
# check if we are the finished state # check if we are the finished state
if current_innerpuz == get_finished_state_inner_puzzle(singleton_id): if current_innerpuz == get_finished_state_inner_puzzle(singleton_id):
@@ -1910,7 +1906,7 @@ class DAOWallet:
) )
await self.add_parent(new_state.coin.name(), future_parent) await self.add_parent(new_state.coin.name(), future_parent)
return return
index = index + 1 index += 1
# Search for the timer coin # Search for the timer coin
if not ended: if not ended:
@@ -2005,7 +2001,7 @@ class DAOWallet:
) )
await self.add_parent(new_state.coin.name(), future_parent) await self.add_parent(new_state.coin.name(), future_parent)
return return
index = index + 1 index += 1
async def get_proposal_state(self, proposal_id: bytes32) -> dict[str, Union[int, bool]]: async def get_proposal_state(self, proposal_id: bytes32) -> dict[str, Union[int, bool]]:
""" """
@@ -2087,7 +2083,6 @@ class DAOWallet:
uint64(new_state.coin.amount), uint64(new_state.coin.amount),
) )
await self.add_parent(new_state.coin.name(), future_parent) await self.add_parent(new_state.coin.name(), future_parent)
return
async def apply_state_transition(self, new_state: CoinSpend, block_height: uint32) -> bool: async def apply_state_transition(self, new_state: CoinSpend, block_height: uint32) -> bool:
""" """
+1 -1
View File
@@ -139,7 +139,7 @@ def match_address_to_sk(
if address in phs: if address in phs:
found_addresses.add(address) found_addresses.add(address)
search_list = search_list - found_addresses search_list -= found_addresses
if not len(search_list): if not len(search_list):
return found_addresses return found_addresses
+4 -5
View File
@@ -852,7 +852,7 @@ class TradeManager:
wallet = await self.wallet_state_manager.get_wallet_for_asset_id(asset_id.hex()) wallet = await self.wallet_state_manager.get_wallet_for_asset_id(asset_id.hex())
if wallet is None and amount < 0: if wallet is None and amount < 0:
raise ValueError(f"Do not have a wallet for asset ID: {asset_id} to fulfill offer") 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 key = asset_id
else: else:
key = int(wallet.id()) key = int(wallet.id())
@@ -999,12 +999,12 @@ class TradeManager:
k: v k: v
for k, v in valid_times.to_json_dict().items() for k, v in valid_times.to_json_dict().items()
if k if k
not in ( not in {
"max_secs_after_created", "max_secs_after_created",
"min_secs_since_created", "min_secs_since_created",
"max_blocks_after_created", "max_blocks_after_created",
"min_blocks_since_created", "min_blocks_since_created",
) }
}, },
} }
@@ -1033,8 +1033,7 @@ class TradeManager:
if WalletType(wallet.type()) == WalletType.VC: if WalletType(wallet.type()) == WalletType.VC:
assert isinstance(wallet, VCWallet) assert isinstance(wallet, VCWallet)
return await wallet.add_vc_authorization(offer, solver, action_scope) 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({}) return offer, Solver({})
+3 -3
View File
@@ -326,11 +326,11 @@ class Offer:
def keys_to_strings(dic: dict[Optional[bytes32], Any]) -> dict[str, Any]: def keys_to_strings(dic: dict[Optional[bytes32], Any]) -> dict[str, Any]:
new_dic: dict[str, Any] = {} new_dic: dict[str, Any] = {}
for key in dic: for key, val in dic.items():
if key is None: if key is None:
new_dic["xch"] = dic[key] new_dic["xch"] = val
else: else:
new_dic[key.hex()] = dic[key] new_dic[key.hex()] = val
return new_dic return new_dic
driver_dict: dict[str, Any] = {} driver_dict: dict[str, Any] = {}
+3 -3
View File
@@ -60,14 +60,14 @@ class TransactionRecordOld(Streamable):
def is_in_mempool(self) -> bool: def is_in_mempool(self) -> bool:
# If one of the nodes we sent it to responded with success or pending, we return True # If one of the nodes we sent it to responded with success or pending, we return True
for _, mis, _ in self.sent_to: 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 True
return False return False
def height_farmed(self, genesis_challenge: bytes32) -> Optional[uint32]: def height_farmed(self, genesis_challenge: bytes32) -> Optional[uint32]:
if not self.confirmed: if not self.confirmed:
return None 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): for block_index in range(self.confirmed_at_height, self.confirmed_at_height - 100, -1):
if block_index < 0: if block_index < 0:
return None return None
@@ -131,7 +131,7 @@ class TransactionRecordOld(Streamable):
if any(x[1] == MempoolInclusionStatus.SUCCESS for x in self.sent_to): if any(x[1] == MempoolInclusionStatus.SUCCESS for x in self.sent_to):
# we managed to push it to mempool at least once # we managed to push it to mempool at least once
return True 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 # we tried to push it to mempool and got a fee error so it's a temporary error
return True return True
return False return False
+2 -2
View File
@@ -33,7 +33,7 @@ def compute_spend_hints_and_additions(
raise ValidationError(Err.BLOCK_COST_EXCEEDS_MAX, "compute_spend_hints_and_additions() for CoinSpend") raise ValidationError(Err.BLOCK_COST_EXCEEDS_MAX, "compute_spend_hints_and_additions() for CoinSpend")
atoms = condition.as_iter() atoms = condition.as_iter()
op = next(atoms).atom op = next(atoms).atom
if op in [ if op in {
ConditionOpcode.AGG_SIG_PARENT, ConditionOpcode.AGG_SIG_PARENT,
ConditionOpcode.AGG_SIG_PUZZLE, ConditionOpcode.AGG_SIG_PUZZLE,
ConditionOpcode.AGG_SIG_AMOUNT, ConditionOpcode.AGG_SIG_AMOUNT,
@@ -42,7 +42,7 @@ def compute_spend_hints_and_additions(
ConditionOpcode.AGG_SIG_PARENT_PUZZLE, ConditionOpcode.AGG_SIG_PARENT_PUZZLE,
ConditionOpcode.AGG_SIG_UNSAFE, ConditionOpcode.AGG_SIG_UNSAFE,
ConditionOpcode.AGG_SIG_ME, ConditionOpcode.AGG_SIG_ME,
]: }:
cost += ConditionCost.AGG_SIG.value cost += ConditionCost.AGG_SIG.value
continue continue
if op != ConditionOpcode.CREATE_COIN.value: if op != ConditionOpcode.CREATE_COIN.value:
+2 -2
View File
@@ -51,7 +51,7 @@ class RemarkDataType(IntEnum):
CLAWBACK = 2 CLAWBACK = 2
T = TypeVar("T", contravariant=True) T_contra = TypeVar("T_contra", contravariant=True)
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -60,7 +60,7 @@ class WalletIdentifier:
type: WalletType type: WalletType
@classmethod @classmethod
def create(cls, wallet: WalletProtocol[T]) -> WalletIdentifier: def create(cls, wallet: WalletProtocol[T_contra]) -> WalletIdentifier:
return cls(wallet.id(), wallet.type()) return cls(wallet.id(), wallet.type())
+1 -1
View File
@@ -312,7 +312,7 @@ class Wallet:
raise ValueError("Cannot create two identical coins") raise ValueError("Cannot create two identical coins")
for coin in coins: for coin in coins:
# Only one coin creates outputs # Only one coin creates outputs
if origin_id in (None, coin.name()): if origin_id in {None, coin.name()}:
origin_id = coin.name() origin_id = coin.name()
inner_puzzle = await self.puzzle_for_puzzle_hash(coin.puzzle_hash) inner_puzzle = await self.puzzle_for_puzzle_hash(coin.puzzle_hash)
decorated_target_puzzle_hash = decorator_manager.decorate_target_puzzle_hash( decorated_target_puzzle_hash = decorator_manager.decorate_target_puzzle_hash(
+1 -1
View File
@@ -343,7 +343,7 @@ class WalletNode:
self.log.info("Resetting wallet sync data...") self.log.info("Resetting wallet sync data...")
rows = list(await conn.execute_fetchall("SELECT name FROM sqlite_master WHERE type='table'")) rows = list(await conn.execute_fetchall("SELECT name FROM sqlite_master WHERE type='table'"))
names = {x[0] for x in rows} names = {x[0] for x in rows}
names = names - set(known_tables) names -= set(known_tables)
tables_to_drop = [] tables_to_drop = []
for name in names: for name in names:
for ignore_name in ignore_tables: for ignore_name in ignore_tables:
-1
View File
@@ -158,7 +158,6 @@ class WalletNodeAPI:
@metadata.request() @metadata.request()
async def respond_puzzle_solution(self, request: wallet_protocol.RespondPuzzleSolution): async def respond_puzzle_solution(self, request: wallet_protocol.RespondPuzzleSolution):
self.log.error("Unexpected message `respond_puzzle_solution`. Peer might be slow to respond") self.log.error("Unexpected message `respond_puzzle_solution`. Peer might be slow to respond")
return None
@metadata.request() @metadata.request()
async def reject_puzzle_solution(self, request: wallet_protocol.RejectPuzzleSolution): async def reject_puzzle_solution(self, request: wallet_protocol.RejectPuzzleSolution):
+5 -3
View File
@@ -20,16 +20,18 @@ from chia.wallet.wallet_spend_bundle import WalletSpendBundle
if TYPE_CHECKING: if TYPE_CHECKING:
from chia.wallet.wallet_state_manager import WalletStateManager 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 @classmethod
def type(cls) -> WalletType: ... def type(cls) -> WalletType: ...
def id(self) -> uint32: ... 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( async def select_coins(
self, self,
-1
View File
@@ -125,7 +125,6 @@ class WalletSingletonStore:
current_records = await self.get_records_by_coin_id(coin_state.coin.name()) current_records = await self.get_records_by_coin_id(coin_state.coin.name())
if len(current_records) > 0: if len(current_records) > 0:
await self.delete_singleton_by_coin_id(coin_state.coin.name(), block_height) await self.delete_singleton_by_coin_id(coin_state.coin.name(), block_height)
return
def _to_singleton_record(self, row: Row) -> SingletonRecord: def _to_singleton_record(self, row: Row) -> SingletonRecord:
return SingletonRecord( return SingletonRecord(
+11 -12
View File
@@ -1692,10 +1692,9 @@ class WalletStateManager:
self.log.info(f"Found verified credential {vc.launcher_id.hex()}.") 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): for wallet_info in await self.get_all_wallet_info_entries(wallet_type=WalletType.VC):
return WalletIdentifier(wallet_info.id, WalletType.VC) return WalletIdentifier(wallet_info.id, WalletType.VC)
else: # Create a new VC wallet
# Create a new VC wallet vc_wallet = await VCWallet.create_new_vc_wallet(self, self.main_wallet) # pragma: no cover
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
return WalletIdentifier(vc_wallet.id(), WalletType.VC) # pragma: no cover
async def _add_coin_states( async def _add_coin_states(
self, self,
@@ -1982,7 +1981,7 @@ class WalletStateManager:
unconfirmed_record.name, uint32(coin_state.spent_height) 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} 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): if coin_state.spent_height is not None and coin_state.coin.amount == uint64(1):
singleton_wallet: Union[PoolWallet, DAOWallet] = self.get_wallet( singleton_wallet: Union[PoolWallet, DAOWallet] = self.get_wallet(
@@ -2385,18 +2384,18 @@ class WalletStateManager:
if ( if (
send_status != MempoolInclusionStatus.SUCCESS send_status != MempoolInclusionStatus.SUCCESS
and error 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() coins_removed = tx.spend_bundle.removals()
trade_coins_removed = set() trade_coins_removed = set()
trades = [] trades = []
for removed_coin in coins_removed: for removed_coin in coins_removed:
trade = await self.trade_manager.get_trade_by_coin(removed_coin) 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_CONFIRM.value,
TradeStatus.PENDING_ACCEPT.value, TradeStatus.PENDING_ACCEPT.value,
TradeStatus.PENDING_CANCEL.value, TradeStatus.PENDING_CANCEL.value,
): }:
if trade not in trades: if trade not in trades:
trades.append(trade) trades.append(trade)
# offer was tied to these coins, lets subscribe to them to get a confirmation to # offer was tied to these coins, lets subscribe to them to get a confirmation to
@@ -2465,14 +2464,14 @@ class WalletStateManager:
reorged: list[TransactionRecord] = await self.tx_store.get_transaction_above(height) reorged: list[TransactionRecord] = await self.tx_store.get_transaction_above(height)
await self.tx_store.rollback_to_block(height) await self.tx_store.rollback_to_block(height)
for record in reorged: for record in reorged:
if TransactionType(record.type) in [ if TransactionType(record.type) in {
TransactionType.OUTGOING_TX, TransactionType.OUTGOING_TX,
TransactionType.OUTGOING_TRADE, TransactionType.OUTGOING_TRADE,
TransactionType.INCOMING_TRADE, TransactionType.INCOMING_TRADE,
TransactionType.OUTGOING_CLAWBACK, TransactionType.OUTGOING_CLAWBACK,
TransactionType.INCOMING_CLAWBACK_SEND, TransactionType.INCOMING_CLAWBACK_SEND,
TransactionType.INCOMING_CLAWBACK_RECEIVE, TransactionType.INCOMING_CLAWBACK_RECEIVE,
]: }:
await self.tx_store.tx_reorged(record) await self.tx_store.tx_reorged(record)
# Removes wallets that were created from a blockchain transaction which got reorged. # Removes wallets that were created from a blockchain transaction which got reorged.
@@ -2500,7 +2499,7 @@ class WalletStateManager:
async def get_wallet_for_asset_id(self, asset_id: str) -> Optional[WalletProtocol[Any]]: async def get_wallet_for_asset_id(self, asset_id: str) -> Optional[WalletProtocol[Any]]:
for wallet_id, wallet in self.wallets.items(): 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) assert isinstance(wallet, CATWallet)
if wallet.get_asset_id() == asset_id: if wallet.get_asset_id() == asset_id:
return wallet return wallet
@@ -2619,7 +2618,7 @@ class WalletStateManager:
async def convert_puzzle_hash(self, wallet_id: uint32, puzzle_hash: bytes32) -> bytes32: async def convert_puzzle_hash(self, wallet_id: uint32, puzzle_hash: bytes32) -> bytes32:
wallet = self.wallets[wallet_id] 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 # 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) assert isinstance(wallet, CATWallet)
return await wallet.convert_puzzle_hash(puzzle_hash) return await wallet.convert_puzzle_hash(puzzle_hash)
+1 -1
View File
@@ -55,7 +55,7 @@ def get_chia_version() -> str:
chia_executable = shutil.which("chia") chia_executable = shutil.which("chia")
if chia_executable is None: if chia_executable is None:
chia_executable = "chia" 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: if output.returncode == 0:
version = str(output.stdout.strip(), "utf-8").splitlines()[-1] version = str(output.stdout.strip(), "utf-8").splitlines()[-1]
return make_semver(version) return make_semver(version)
+9 -23
View File
@@ -15,13 +15,11 @@ select = [
explicit-preview-rules = false explicit-preview-rules = false
ignore = [ ignore = [
# Pylint convention # Pylint convention
"PLC0105", # type-name-incorrect-variance
"PLC0415", # import-outside-top-level "PLC0415", # import-outside-top-level
"PLC2801", # unnecessary-dunder-call
"PLC0206", # dict-index-missing-items
"PLC1901", # compare-to-empty-string "PLC1901", # compare-to-empty-string
# Should probably fix these
"PLC2801", # unnecessary-dunder-call
"PLC2701", # import-private-name "PLC2701", # import-private-name
"PLC0414", # useless-import-alias
# Pylint refactor # Pylint refactor
"PLR0915", # too-many-statements "PLR0915", # too-many-statements
@@ -30,33 +28,21 @@ ignore = [
"PLR0912", # too-many-branches "PLR0912", # too-many-branches
"PLR1702", # too-many-nested-blocks "PLR1702", # too-many-nested-blocks
"PLR0904", # too-many-public-methods "PLR0904", # too-many-public-methods
"PLR6301", # no-self-use
"PLR0917", # too-many-positional-arguments "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 "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 "PLR5501", # collapsible-else-if
"PLR1711", # useless-return
"PLR1730", # if-stmt-min-max
"PLR1736", # unnecessary-list-index-lookup
"PLR1733", # unnecessary-dict-index-lookup
# Pylint warning # Pylint warning
"PLW2901", # redefined-loop-name
"PLW1641", # eq-without-hash "PLW1641", # eq-without-hash
# Should probably fix these
"PLW2901", # redefined-loop-name
"PLW1514", # unspecified-encoding "PLW1514", # unspecified-encoding
"PLW0602", # global-variable-not-assigned
"PLW0603", # global-statement "PLW0603", # global-statement
"PLW0108", # unnecessary-lambda
"PLW1510", # subprocess-run-without-check
"PLW0120", # useless-else-on-loop
# Flake8 core
# "F841", # unused-variable (540)
] ]
+2 -2
View File
@@ -120,7 +120,7 @@ class Formatter:
if self.getting_form_name == 1 and not (ch == b" "): if self.getting_form_name == 1 and not (ch == b" "):
self.getting_form_name = 2 self.getting_form_name = 2
self.form_name.append(ch) 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.getting_form_name = 0
self.got_form_on_line = self.cur_line self.got_form_on_line = self.cur_line
else: else:
@@ -151,7 +151,7 @@ class Formatter:
if semis == 0: if semis == 0:
# We've entered a string, stop processing # We've entered a string, stop processing
if ch == b"'" or ch == b'"': if ch in {b"'", b'"'}:
in_string = ch in_string = ch
continue continue
elif ch == b"(": elif ch == b"(":
+1 -1
View File
@@ -112,7 +112,7 @@ def main(length: int, fill_rate: int, profile: bool, block_refs: bool, output: O
for b in blocks: for b in blocks:
for coin in b.get_included_reward_coins(): 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) unspent_coins.append(coin)
db.execute( db.execute(
"INSERT INTO full_blocks VALUES(?, ?, ?, ?, ?)", "INSERT INTO full_blocks VALUES(?, ?, ?, ?, ?)",