[CHIA-3633] August 2025 pass of Ruff linting rules (#19929)

* Enable Ruff `PLR1704` (`redefined-argument-from-local`)

* Enable Ruff `PLR5501` (`collapsible-else-if`)

* Enable Ruff `PLW2901` (`redefined-loop-name`)

* bad change

* Enable Ruff `RUF043` (`pytest-raises-ambiguous-pattern`)

* Enable Ruff `RUF046` (`unnecessary-cast-to-int`)

* Enable Ruff `RUF052` (`used-dummy-variable`)

* Remove unused ignore `UP006`

* One mis-signaled regex

* Comments by @altendky

* bad change, my bad
This commit is contained in:
Matt Hauff
2025-08-11 14:39:12 -07:00
committed by GitHub
parent b95e8d9349
commit a803dc0fa6
57 changed files with 390 additions and 433 deletions
@@ -116,11 +116,10 @@ async def _validate_and_add_block(
if err is not None:
# Got an error
raise AssertionError(err)
else:
# Here we will enforce checking of the exact error
if err != expected_error:
# Did not get the right error, or did not get an error
raise AssertionError(f"Expected {expected_error} but got {err}")
# Here we will enforce checking of the exact error
elif err != expected_error:
# Did not get the right error, or did not get an error
raise AssertionError(f"Expected {expected_error} but got {err}")
if expected_result is not None and expected_result != result:
raise AssertionError(f"Expected {expected_result} but got {result}")
@@ -1,5 +1,6 @@
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, ClassVar, Optional, cast
@@ -93,7 +94,7 @@ async def test_augmented_chain(default_10000_blocks: list[FullBlock]) -> None:
with pytest.raises(KeyError):
await abc.prev_block_hash([blocks[2].header_hash])
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await abc.lookup_block_generators(blocks[3].header_hash, {uint32(3)})
block_records = []
@@ -105,11 +106,11 @@ async def test_augmented_chain(default_10000_blocks: list[FullBlock]) -> None:
assert abc.height_to_block_record(uint32(1)) == block_records[1]
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await abc.lookup_block_generators(blocks[10].header_hash, {uint32(3), uint32(10)})
# block 1 exists in the chain, but it doesn't have a generator
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await abc.lookup_block_generators(blocks[1].header_hash, {uint32(1)})
expect_gen = blocks[2].transactions_generator
+5 -4
View File
@@ -4,6 +4,7 @@ import asyncio
import copy
import logging
import random
import re
import time
from collections.abc import AsyncIterator, Awaitable
from contextlib import asynccontextmanager
@@ -4158,24 +4159,24 @@ async def test_lookup_block_generators(
# make sure we don't cross the forks
if clear_cache:
b.clean_block_records()
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await b.lookup_block_generators(peak_1.prev_header_hash, {uint32(516)})
if clear_cache:
b.clean_block_records()
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await b.lookup_block_generators(peak_2.prev_header_hash, {uint32(503)})
# make sure we fail when looking up a non-transaction block from the main
# chain, regardless of which chain we start at
if clear_cache:
b.clean_block_records()
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await b.lookup_block_generators(peak_1.prev_header_hash, {uint32(8)})
if clear_cache:
b.clean_block_records()
with pytest.raises(ValueError, match="Err.GENERATOR_REF_HAS_NO_GENERATOR"):
with pytest.raises(ValueError, match=re.escape(Err.GENERATOR_REF_HAS_NO_GENERATOR.name)):
await b.lookup_block_generators(peak_2.prev_header_hash, {uint32(8)})
# if we try to look up generators starting from a disconnected block, we
+2 -2
View File
@@ -230,8 +230,8 @@ def blockchain_constants(consensus_mode: ConsensusMode) -> ConsensusConstants:
@pytest.fixture(scope="session", name="bt")
async def block_tools_fixture(get_keychain, blockchain_constants, anyio_backend) -> BlockTools:
# Note that this causes a lot of CPU and disk traffic - disk, DB, ports, process creation ...
_shared_block_tools = await create_block_tools_async(constants=blockchain_constants, keychain=get_keychain)
return _shared_block_tools
shared_block_tools = await create_block_tools_async(constants=blockchain_constants, keychain=get_keychain)
return shared_block_tools
# if you have a system that has an unusual hostname for localhost and you want
+1 -1
View File
@@ -2278,7 +2278,7 @@ async def test_unsubscribe_unknown(
bare_data_layer_api: DataLayerRpcApi,
seeded_random: random.Random,
) -> None:
with pytest.raises(RuntimeError, match="No subscription found for the given store_id."):
with pytest.raises(RuntimeError, match="No subscription found for the given store_id"):
await bare_data_layer_api.unsubscribe(request={"id": bytes32.random(seeded_random).hex(), "retain": False})
@@ -594,7 +594,7 @@ async def test_ancestor_table_unique_inserts(data_store: DataStore, store_id: by
hash_2 = bytes32.from_hexstr("924be8ff27e84cba17f5bc918097f8410fab9824713a4668a21c8e060a8cab40")
await data_store._insert_ancestor_table(hash_1, hash_2, store_id, 2)
await data_store._insert_ancestor_table(hash_1, hash_2, store_id, 2)
with pytest.raises(Exception, match="^Requested insertion of ancestor"):
with pytest.raises(Exception, match=r"^Requested insertion of ancestor"):
await data_store._insert_ancestor_table(hash_1, hash_1, store_id, 2)
await data_store._insert_ancestor_table(hash_1, hash_2, store_id, 2)
@@ -2385,11 +2385,10 @@ async def test_get_leaf_at_minimum_height(
if isinstance(node, InternalNode):
heights[node.left_hash] = heights[node.hash] + 1
heights[node.right_hash] = heights[node.hash] + 1
elif min_leaf_height is not None:
min_leaf_height = min(min_leaf_height, heights[node.hash])
else:
if min_leaf_height is not None:
min_leaf_height = min(min_leaf_height, heights[node.hash])
else:
min_leaf_height = heights[node.hash]
min_leaf_height = heights[node.hash]
assert min_leaf_height is not None
if pre > 0:
@@ -418,8 +418,8 @@ async def test_get_generator(bt: BlockTools, db_version: int, use_cache: bool) -
store = await BlockStore.create(db_wrapper, use_cache=use_cache)
new_blocks = []
for i, block in enumerate(blocks):
block = block.replace(transactions_generator=generator(i))
for i, original_block in enumerate(blocks):
block = original_block.replace(transactions_generator=generator(i))
block_record = header_block_to_sub_block_record(
DEFAULT_CONSTANTS, uint64(0), block, uint64(0), False, uint8(0), uint32(max(0, block.height - 1)), None
)
@@ -560,7 +560,7 @@ class TestPeerManager:
# use tmp_path pytest fixture to create a temporary directory
async def test_serialization(self, tmp_path: Path):
addrman = AddressManagerTest()
now = int(math.floor(time.time()))
now = math.floor(time.time())
t_peer1 = TimestampedPeerInfo("250.7.1.1", uint16(8333), uint64(now - 10000))
t_peer2 = TimestampedPeerInfo("1050:0000:0000:0000:0005:0600:300c:326b", uint16(9999), uint64(now - 20000))
t_peer3 = TimestampedPeerInfo("250.7.3.3", uint16(9999), uint64(now - 30000))
@@ -587,7 +587,7 @@ class TestPeerManager:
@pytest.mark.anyio
async def test_bad_ip_encoding(self, tmp_path: Path):
addrman = AddressManagerTest()
now = int(math.floor(time.time()))
now = math.floor(time.time())
t_peer1 = TimestampedPeerInfo("250.7.1.1", uint16(8333), uint64(now - 10000))
t_peer2 = TimestampedPeerInfo("1050:0000:0000:0000:0005:0600:300c:326b", uint16(9999), uint64(now - 20000))
t_peer3 = TimestampedPeerInfo("250.7.3.3", uint16(9999), uint64(now - 30000))
@@ -725,7 +725,7 @@ class TestPeerManager:
# create a file with the old serialization, then migrate to new serialization
addrman = AddressManagerTest()
now = int(math.floor(time.time()))
now = math.floor(time.time())
t_peer1 = TimestampedPeerInfo("250.7.1.1", uint16(8333), uint64(now - 10000))
t_peer2 = TimestampedPeerInfo("1050:0000:0000:0000:0005:0600:300c:326b", uint16(9999), uint64(now - 20000))
t_peer3 = TimestampedPeerInfo("250.7.3.3", uint16(9999), uint64(now - 30000))
+16 -18
View File
@@ -2678,16 +2678,15 @@ async def test_long_reorg_nodes(
blocks = default_10000_blocks[: 1600 - chain_length]
reorg_blocks = test_long_reorg_blocks_light[: 1600 - chain_length]
reorg_height = 2000
else:
if fork_point == 1500:
blocks = default_10000_blocks[: 1900 - chain_length]
reorg_blocks = test_long_reorg_1500_blocks[: 1900 - chain_length]
reorg_height = 2300
else: # pragma: no cover
pytest.skip("We rely on the light-blocks test for a 0 forkpoint")
blocks = default_10000_blocks[: 1100 - chain_length]
# reorg_blocks = test_long_reorg_blocks[: 1100 - chain_length]
reorg_height = 1600
elif fork_point == 1500:
blocks = default_10000_blocks[: 1900 - chain_length]
reorg_blocks = test_long_reorg_1500_blocks[: 1900 - chain_length]
reorg_height = 2300
else: # pragma: no cover
pytest.skip("We rely on the light-blocks test for a 0 forkpoint")
blocks = default_10000_blocks[: 1100 - chain_length]
# reorg_blocks = test_long_reorg_blocks[: 1100 - chain_length]
reorg_height = 1600
# this is a pre-requisite for a reorg to happen
assert default_10000_blocks[reorg_height].weight > reorg_blocks[-1].weight
@@ -3163,15 +3162,14 @@ async def declare_pos_unfinished_block(
challenge_chain_sp = block.reward_chain_block.challenge_chain_sp_vdf.output.get_hash()
if block.reward_chain_block.reward_chain_sp_vdf is not None:
reward_chain_sp = block.reward_chain_block.reward_chain_sp_vdf.output.get_hash()
elif len(block.finished_sub_slots) > 0:
reward_chain_sp = block.finished_sub_slots[-1].reward_chain.get_hash()
else:
if len(block.finished_sub_slots) > 0:
reward_chain_sp = block.finished_sub_slots[-1].reward_chain.get_hash()
else:
curr = blockchain.block_record(block.prev_header_hash)
while not curr.first_in_sub_slot:
curr = blockchain.block_record(curr.prev_hash)
assert curr.finished_reward_slot_hashes is not None
reward_chain_sp = curr.finished_reward_slot_hashes[-1]
curr = blockchain.block_record(block.prev_header_hash)
while not curr.first_in_sub_slot:
curr = blockchain.block_record(curr.prev_hash)
assert curr.finished_reward_slot_hashes is not None
reward_chain_sp = curr.finished_reward_slot_hashes[-1]
farmer_reward_address = block.foliage.foliage_block_data.farmer_reward_puzzle_hash
pool_target = block.foliage.foliage_block_data.pool_target
pool_target_signature = block.foliage.foliage_block_data.pool_signature
@@ -23,7 +23,6 @@ async def test_basics() -> None:
cost = uint64(5000000)
for i in range(300, 700):
i = uint32(i)
items = []
for _ in range(2, 100):
fee = uint64(10000000)
@@ -50,7 +49,7 @@ async def test_basics() -> None:
)
items.append(mempool_item2)
fee_tracker.process_block(i, items)
fee_tracker.process_block(uint32(i), items)
short, med, long = fee_tracker.estimate_fees()
@@ -72,7 +71,6 @@ async def test_fee_increase() -> None:
estimator = SmartFeeEstimator(fee_tracker, uint64(test_constants.MAX_BLOCK_COST_CLVM))
random = Random(x=1)
for i in range(300, 700):
i = uint32(i)
items = []
for _ in range(20):
fee = uint64(0)
@@ -85,7 +83,7 @@ async def test_fee_increase() -> None:
)
items.append(mempool_item)
fee_tracker.process_block(i, items)
fee_tracker.process_block(uint32(i), items)
short, med, long = fee_tracker.estimate_fees()
mempool_info = mempool_manager.mempool.fee_estimator.get_mempool_info()
@@ -79,7 +79,7 @@ def test_process_fast_forward_spends_unknown_ff() -> None:
singleton_ff = SingletonFastForward()
# We have no fast forward records yet, so we'll process this coin for the
# first time here, but the item's latest singleton lineage returns None
with pytest.raises(ValueError, match="Cannot proceed with singleton spend fast forward."):
with pytest.raises(ValueError, match="Cannot proceed with singleton spend fast forward"):
singleton_ff.process_fast_forward_spends(
mempool_item=internal_mempool_item, height=TEST_HEIGHT, constants=DEFAULT_CONSTANTS
)
+2 -2
View File
@@ -457,9 +457,9 @@ async def test_signage_points(
full_node_service_1.config,
) as client:
# Only provide one
with pytest.raises(ValueError, match="sp_hash or challenge_hash must be provided."):
with pytest.raises(ValueError, match="sp_hash or challenge_hash must be provided"):
await client.get_recent_signage_point_or_eos(None, None)
with pytest.raises(ValueError, match="Either sp_hash or challenge_hash must be provided, not both."):
with pytest.raises(ValueError, match="Either sp_hash or challenge_hash must be provided, not both"):
await client.get_recent_signage_point_or_eos(std_hash(b"0"), std_hash(b"1"))
# Not found
with pytest.raises(ValueError, match="in cache"):
+2 -2
View File
@@ -220,9 +220,9 @@ class TestKeychain:
test_vectors_path = importlib_resources.files(chia._tests.util.__name__).joinpath("bip39_test_vectors.json")
all_vectors = json.loads(test_vectors_path.read_text(encoding="utf-8"))
for idx, [entropy_hex, full_mnemonic, seed, short_mnemonic] in enumerate(all_vectors["english"]):
for idx, [entropy_hex, full_mnemonic, seed_hex, short_mnemonic] in enumerate(all_vectors["english"]):
entropy_bytes = bytes.fromhex(entropy_hex)
seed = bytes.fromhex(seed)
seed = bytes.fromhex(seed_hex)
assert mnemonic_from_short_words(short_mnemonic) == full_mnemonic
assert bytes_from_mnemonic(short_mnemonic) == entropy_bytes
@@ -68,8 +68,7 @@ def test_steady_fee_pressure() -> None:
estimates_during = []
start_from = 250
for height in range(start, end):
height = uint32(height)
items = make_block(height, 1, cost, fee, num_blocks_wait_in_mempool)
items = make_block(uint32(height), 1, cost, fee, num_blocks_wait_in_mempool)
estimator.new_block(FeeBlockInfo(uint32(height), items))
if height >= start_from:
estimation = estimator.estimate_fee_rate(time_offset_seconds=time_offset_seconds * (height - start_from))
+3 -4
View File
@@ -117,10 +117,9 @@ class PlotRefreshTester:
if plot_info.prover.get_filename() == value.prover.get_filename():
values_found += 1
continue
else:
if value in expected_list:
values_found += 1
continue
elif value in expected_list:
values_found += 1
continue
if values_found != len(expected_list):
log.error(f"{name} invalid: values_found {values_found} expected {len(expected_list)}")
return
+2 -1
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from io import StringIO
from typing import Optional, cast
@@ -484,7 +485,7 @@ async def test_plotnft_cli_join(
wallet_id = await create_new_plotnft(wallet_environments)
# Test joining the same pool again
with pytest.raises(click.ClickException, match="already farming to pool http://pool.example.com"):
with pytest.raises(click.ClickException, match=re.escape("already farming to pool http://pool.example.com")):
await JoinPlotNFTCMD(
rpc_info=NeedsWalletRPC(
client_info=client_info,
@@ -1,6 +1,7 @@
from __future__ import annotations
import copy
import re
from unittest import TestCase
import pytest
@@ -31,6 +32,7 @@ from chia.pools.pool_wallet_info import PoolState
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
from chia.types.coin_spend import make_spend
from chia.util.errors import Err
from chia.wallet.puzzles import singleton_top_layer
from chia.wallet.puzzles.p2_conditions import puzzle_for_conditions
from chia.wallet.puzzles.p2_delegated_puzzle_or_hidden_puzzle import (
@@ -242,7 +244,8 @@ class TestPoolPuzzles(TestCase):
)
# Spend it and hope it fails!
with pytest.raises(
BadSpendBundleError, match="condition validation failure Err.ASSERT_ANNOUNCE_CONSUMED_FAILED"
BadSpendBundleError,
match=re.escape(f"condition validation failure {Err.ASSERT_ANNOUNCE_CONSUMED_FAILED!s}"),
):
coin_db.update_coin_store_for_spend_bundle(
SpendBundle([singleton_coinsol], G2Element()), time, DEFAULT_CONSTANTS.MAX_BLOCK_COST_CLVM
@@ -269,7 +272,8 @@ class TestPoolPuzzles(TestCase):
)
# Spend it and hope it fails!
with pytest.raises(
BadSpendBundleError, match="condition validation failure Err.ASSERT_ANNOUNCE_CONSUMED_FAILED"
BadSpendBundleError,
match=re.escape(f"condition validation failure {Err.ASSERT_ANNOUNCE_CONSUMED_FAILED!s}"),
):
coin_db.update_coin_store_for_spend_bundle(
SpendBundle([singleton_coinsol, bad_coinsol], G2Element()), time, DEFAULT_CONSTANTS.MAX_BLOCK_COST_CLVM
@@ -320,7 +324,10 @@ class TestPoolPuzzles(TestCase):
(data + singleton.name() + DEFAULT_CONSTANTS.AGG_SIG_ME_ADDITIONAL_DATA),
)
# Spend it and hope it fails!
with pytest.raises(BadSpendBundleError, match="condition validation failure Err.ASSERT_HEIGHT_RELATIVE_FAILED"):
with pytest.raises(
BadSpendBundleError,
match=re.escape(f"condition validation failure {Err.ASSERT_HEIGHT_RELATIVE_FAILED!s}"),
):
coin_db.update_coin_store_for_spend_bundle(
SpendBundle([return_coinsol], sig), time, DEFAULT_CONSTANTS.MAX_BLOCK_COST_CLVM
)
+1 -1
View File
@@ -1260,7 +1260,7 @@ class TestPoolWalletRpc:
mock.return_value = False
# Test joining the same pool via the RPC client
with pytest.raises(ResponseFailureError, match="Wallet needs to be fully synced."):
with pytest.raises(ResponseFailureError, match="Wallet needs to be fully synced"):
await wallet_rpc.pw_join_pool(
PWJoinPool(
wallet_id=uint32(wallet_id),
+10 -10
View File
@@ -182,7 +182,7 @@ def test_split_manager_raises_on_second_entry() -> None:
split = SplitManager(manager=sync_manager(y=x), object=None)
split.enter()
with pytest.raises(Exception, match="^already entered$"):
with pytest.raises(Exception, match=r"^already entered$"):
split.enter()
@@ -193,7 +193,7 @@ def test_split_manager_raises_on_second_entry_after_exiting() -> None:
split.enter()
split.exit()
with pytest.raises(Exception, match="^already entered, already exited$"):
with pytest.raises(Exception, match=r"^already entered, already exited$"):
split.enter()
@@ -204,7 +204,7 @@ def test_split_manager_raises_on_second_exit() -> None:
split.enter()
split.exit()
with pytest.raises(Exception, match="^already exited$"):
with pytest.raises(Exception, match=r"^already exited$"):
split.exit()
@@ -213,7 +213,7 @@ def test_split_manager_raises_on_exit_without_entry() -> None:
split = SplitManager(manager=sync_manager(y=x), object=None)
with pytest.raises(Exception, match="^not yet entered$"):
with pytest.raises(Exception, match=r"^not yet entered$"):
split.exit()
@@ -274,7 +274,7 @@ async def test_split_async_manager_raises_on_second_entry() -> None:
split = SplitAsyncManager(manager=async_manager(y=x), object=None)
await split.enter()
with pytest.raises(Exception, match="^already entered$"):
with pytest.raises(Exception, match=r"^already entered$"):
await split.enter()
@@ -286,7 +286,7 @@ async def test_split_async_manager_raises_on_second_entry_after_exiting() -> Non
await split.enter()
await split.exit()
with pytest.raises(Exception, match="^already entered, already exited$"):
with pytest.raises(Exception, match=r"^already entered, already exited$"):
await split.enter()
@@ -298,7 +298,7 @@ async def test_split_async_manager_raises_on_second_exit() -> None:
await split.enter()
await split.exit()
with pytest.raises(Exception, match="^already exited$"):
with pytest.raises(Exception, match=r"^already exited$"):
await split.exit()
@@ -308,7 +308,7 @@ async def test_split_async_manager_raises_on_exit_without_entry() -> None:
split = SplitAsyncManager(manager=async_manager(y=x), object=None)
with pytest.raises(Exception, match="^not yet entered$"):
with pytest.raises(Exception, match=r"^not yet entered$"):
await split.exit()
@@ -390,7 +390,7 @@ async def test_valued_event_set_again_raises_and_does_not_change_value() -> None
value = 37
valued_event.set(value)
with pytest.raises(Exception, match="^Value already set$"):
with pytest.raises(Exception, match=r"^Value already set$"):
valued_event.set(value + 1)
with anyio.fail_after(adjusted_timeout(10)):
@@ -404,7 +404,7 @@ async def test_valued_event_wait_raises_if_not_set() -> None:
valued_event = ValuedEvent[int]()
valued_event._event.set()
with pytest.raises(Exception, match="^Value not set despite event being set$"):
with pytest.raises(Exception, match=r"^Value not set despite event being set$"):
with anyio.fail_after(adjusted_timeout(10)):
await valued_event.wait()
@@ -1153,7 +1153,7 @@ async def test_cat_max_amount_send(wallet_environments: WalletTestFramework, wal
assert action_scope.side_effects.transactions[0].amount == uint64(max_sent_amount)
# 3) Generate transaction that is greater than limit
with pytest.raises(ValueError, match="Can't select amount higher than our spendable balance."):
with pytest.raises(ValueError, match="Can't select amount higher than our spendable balance"):
async with cat_wallet.wallet_state_manager.new_action_scope(
wallet_environments.tx_config, push=False
) as action_scope:
+2 -2
View File
@@ -791,7 +791,7 @@ async def test_get_info(wallet_environments: WalletTestFramework):
coin = (await wallet_0.select_coins(uint64(1), action_scope)).pop()
assert coin.amount % 2 == 1
coin_id = coin.name()
with pytest.raises(ValueError, match="The coin is not a DID."):
with pytest.raises(ValueError, match="The coin is not a DID"):
await api_0.get_did_info(DIDGetInfo(coin_id.hex()))
# Test multiple odd coins
@@ -845,7 +845,7 @@ async def test_get_info(wallet_environments: WalletTestFramework):
]
)
with pytest.raises(ValueError, match="This is not a singleton, multiple children coins found."):
with pytest.raises(ValueError, match=r"This is not a singleton, multiple children coins found."):
await api_0.get_did_info(DIDGetInfo(coin_1.name().hex()))
@@ -528,7 +528,7 @@ async def test_nft_wallet_creation_and_transfer(wallet_environments: WalletTestF
await time_out_assert(30, get_nft_count, 1, nft_wallet_1)
# Test an error case
with pytest.raises(ResponseFailureError, match="The NFT doesn't support setting a DID."):
with pytest.raises(ResponseFailureError, match="The NFT doesn't support setting a DID"):
await env_1.rpc_client.set_nft_did(
NFTSetNFTDID(
wallet_id=uint32(env_1.wallet_aliases["nft"]),
@@ -659,7 +659,7 @@ async def test_nft_wallet_rpc_creation_and_list(wallet_environments: WalletTestF
# test counts
assert (await env.rpc_client.count_nfts(NFTCountNFTs(uint32(env.wallet_aliases["nft"])))).count == 2
assert (await env.rpc_client.count_nfts(NFTCountNFTs())).count == 2
with pytest.raises(ResponseFailureError, match="Wallet 50 not found."):
with pytest.raises(ResponseFailureError, match="Wallet 50 not found"):
await env.rpc_client.count_nfts(NFTCountNFTs(uint32(50)))
+2 -2
View File
@@ -848,8 +848,8 @@ def test_signer_protocol_in(monkeypatch: pytest.MonkeyPatch) -> None:
with open("some file", "wb") as file:
file.write(byte_serialize_clvm_streamable(coin, translation_layer=FOO_COIN_TRANSLATION))
with open("some file2", "wb") as file:
file.write(byte_serialize_clvm_streamable(coin, translation_layer=FOO_COIN_TRANSLATION))
with open("some file2", "wb") as file2:
file2.write(byte_serialize_clvm_streamable(coin, translation_layer=FOO_COIN_TRANSLATION))
result = runner.invoke(
cmd, ["temp_cmd", "--signer-protocol-input", "some file", "--signer-protocol-input", "some file2"]
@@ -65,10 +65,9 @@ def satisfies_hint(obj: T, type_hint: type[T]) -> bool:
object_hint_pairs.extend((v, args[1]) for v in obj.values())
else:
raise NotImplementedError(f"Type {origin} is not yet supported")
else:
# Handle concrete types
if type(obj) is not type_hint:
return False
# Handle concrete types
elif type(obj) is not type_hint:
return False
return True
+5 -5
View File
@@ -181,10 +181,10 @@ def _generate_command_parser(cls: type[ChiaCommand]) -> _CommandParsingStage:
needs_context: bool = False
hints = get_type_hints(cls)
_fields = fields(cls) # type: ignore[arg-type]
cls_fields = fields(cls) # type: ignore[arg-type]
for _field in _fields:
field_name = _field.name
for cls_field in cls_fields:
field_name = cls_field.name
if getattr(hints[field_name], COMMAND_HELPER_ATTRIBUTE_NAME, False):
members[field_name] = _generate_command_parser(hints[field_name])
elif field_name == "context":
@@ -193,9 +193,9 @@ def _generate_command_parser(cls: type[ChiaCommand]) -> _CommandParsingStage:
else:
needs_context = True
kwarg_names.append(field_name)
elif "option_args" in _field.metadata:
elif "option_args" in cls_field.metadata:
option_args: dict[str, Any] = {"multiple": False, "required": False}
option_args.update(_field.metadata["option_args"])
option_args.update(cls_field.metadata["option_args"])
if "type" not in option_args:
origin = get_origin(hints[field_name])
+8 -10
View File
@@ -743,11 +743,10 @@ def derive_child_key(
if non_observer_derivation:
assert current_sk is not None # semantics above guarantee this
current_sk = _derive_path(current_sk, path_indices)
elif current_sk is not None:
current_sk = _derive_path_unhardened(current_sk, path_indices)
else:
if current_sk is not None:
current_sk = _derive_path_unhardened(current_sk, path_indices)
else:
current_pk = _derive_pk_unhardened(current_pk, path_indices)
current_pk = _derive_pk_unhardened(current_pk, path_indices)
derivation_root_sk = current_sk
derivation_root_pk = current_pk
@@ -768,13 +767,12 @@ def derive_child_key(
assert derivation_root_sk is not None # semantics above guarantee this
sk = _derive_path(derivation_root_sk, [i])
pk = sk.get_g1()
elif derivation_root_sk is not None:
sk = _derive_path_unhardened(derivation_root_sk, [i])
pk = sk.get_g1()
else:
if derivation_root_sk is not None:
sk = _derive_path_unhardened(derivation_root_sk, [i])
pk = sk.get_g1()
else:
sk = None
pk = _derive_pk_unhardened(derivation_root_pk, [i])
sk = None
pk = _derive_pk_unhardened(derivation_root_pk, [i])
hd_path: str = (
" (" + hd_path_root + str(i) + ("n" if non_observer_derivation else "") + ")" if show_hd_path else ""
)
+4 -2
View File
@@ -446,8 +446,10 @@ async def change_payout_instructions(launcher_id: bytes32, address: CliAddress,
for pool_config in old_configs:
if pool_config.launcher_id == launcher_id:
id_found = True
pool_config = replace(pool_config, payout_instructions=puzzle_hash.hex())
new_pool_configs.append(pool_config)
new_pool_config = replace(pool_config, payout_instructions=puzzle_hash.hex())
else:
new_pool_config = pool_config
new_pool_configs.append(new_pool_config)
if id_found:
print(f"Launcher Id: {launcher_id.hex()} Found, Updating Config.")
await update_pool_config(root_path, new_pool_configs)
+8 -7
View File
@@ -181,7 +181,7 @@ async def get_unit_name_for_wallet_id(
async def get_transaction(
*, root_path: pathlib.Path, wallet_rpc_port: Optional[int], fingerprint: Optional[int], tx_id: str, verbose: int
) -> None:
async with get_wallet_client(root_path, wallet_rpc_port, fingerprint) as (wallet_client, fingerprint, config):
async with get_wallet_client(root_path, wallet_rpc_port, fingerprint) as (wallet_client, _, config):
transaction_id = bytes32.from_hexstr(tx_id)
address_prefix = selected_network_address_prefix(config)
tx: TransactionRecord = (
@@ -278,7 +278,9 @@ async def get_transactions(
if len(coin_records["coin_records"]) > 0:
coin_record = coin_records["coin_records"][0]
else:
j -= 1
# Ignoring this because it seems useful to the loop
# But we should probably consider a better loop
j -= 1 # noqa: PLW2901
skipped += 1
continue
print_transaction(
@@ -1257,9 +1259,8 @@ async def mint_nft(
raise ValueError("Disabling DID ownership is not supported for this NFT wallet, it does have a DID")
else:
did_id = None
else:
if not wallet_has_did:
did_id = ""
elif not wallet_has_did:
did_id = ""
mint_response = await wallet_client.mint_nft(
request=NFTMintNFTRequest(
@@ -1878,7 +1879,7 @@ async def approve_r_cats(
push: bool,
condition_valid_times: ConditionValidTimes,
) -> list[TransactionRecord]:
async with get_wallet_client(root_path, wallet_rpc_port, fingerprint) as (wallet_client, fingerprint, config):
async with get_wallet_client(root_path, wallet_rpc_port, fingerprint) as (wallet_client, fp, config):
if wallet_client is None:
return
txs = await wallet_client.crcat_approve_pending(
@@ -1889,7 +1890,7 @@ async def approve_r_cats(
min_coin_amount=min_coin_amount,
max_coin_amount=max_coin_amount,
reuse_puzhash=reuse,
).to_tx_config(units["cat"], config, fingerprint),
).to_tx_config(units["cat"], config, fp),
push=push,
timelock_info=condition_valid_times,
)
+2 -3
View File
@@ -334,9 +334,8 @@ async def validate_block_body(
if block.transactions_generator is not None:
if std_hash(bytes(block.transactions_generator)) != block.transactions_info.generator_root:
return Err.INVALID_TRANSACTIONS_GENERATOR_HASH
else:
if block.transactions_info.generator_root != bytes([0] * 32):
return Err.INVALID_TRANSACTIONS_GENERATOR_HASH
elif block.transactions_info.generator_root != bytes([0] * 32):
return Err.INVALID_TRANSACTIONS_GENERATOR_HASH
# 8a. The generator_ref_list must be the hash of the serialized bytes of
# the generator ref list for this block (or 'one' bytes [0x01] if no generator)
+9 -10
View File
@@ -354,17 +354,16 @@ def create_unfinished_block(
else:
if new_sub_slot:
rc_sp_hash = finished_sub_slots[-1].reward_chain.get_hash()
elif is_genesis:
rc_sp_hash = constants.GENESIS_CHALLENGE
else:
if is_genesis:
rc_sp_hash = constants.GENESIS_CHALLENGE
else:
assert prev_block is not None
assert blocks is not None
curr = prev_block
while not curr.first_in_sub_slot:
curr = blocks.block_record(curr.prev_hash)
assert curr.finished_reward_slot_hashes is not None
rc_sp_hash = curr.finished_reward_slot_hashes[-1]
assert prev_block is not None
assert blocks is not None
curr = prev_block
while not curr.first_in_sub_slot:
curr = blocks.block_record(curr.prev_hash)
assert curr.finished_reward_slot_hashes is not None
rc_sp_hash = curr.finished_reward_slot_hashes[-1]
signage_point = SignagePoint(None, None, None, None)
cc_sp_signature: Optional[G2Element] = get_plot_signature(cc_sp_hash, proof_of_space.plot_public_key)
+61 -69
View File
@@ -138,13 +138,12 @@ def validate_unfinished_header_block(
if not curr.finished_challenge_slot_hashes[-1] == challenge_hash:
print(curr.finished_challenge_slot_hashes[-1], challenge_hash)
return None, ValidationError(Err.INVALID_PREV_CHALLENGE_SLOT_HASH)
else:
# 2c. check sub-slot challenge hash for empty slot
if (
not header_block.finished_sub_slots[finished_sub_slot_n - 1].challenge_chain.get_hash()
== challenge_hash
):
return None, ValidationError(Err.INVALID_PREV_CHALLENGE_SLOT_HASH)
# 2c. check sub-slot challenge hash for empty slot
elif (
not header_block.finished_sub_slots[finished_sub_slot_n - 1].challenge_chain.get_hash()
== challenge_hash
):
return None, ValidationError(Err.INVALID_PREV_CHALLENGE_SLOT_HASH)
if genesis_block:
# 2d. Validate that genesis block has no ICC
@@ -176,20 +175,19 @@ def validate_unfinished_header_block(
icc_vdf_input = ClassgroupElement.get_default_element()
else:
icc_vdf_input = prev_b.infused_challenge_vdf_output
else:
# This is not the first sub slot after the last block, so we might not have an ICC
if (
header_block.finished_sub_slots[finished_sub_slot_n - 1].reward_chain.deficit
< constants.MIN_BLOCKS_PER_CHALLENGE_BLOCK
):
finished_ss = header_block.finished_sub_slots[finished_sub_slot_n - 1]
assert finished_ss.infused_challenge_chain is not None
# This is not the first sub slot after the last block, so we might not have an ICC
elif (
header_block.finished_sub_slots[finished_sub_slot_n - 1].reward_chain.deficit
< constants.MIN_BLOCKS_PER_CHALLENGE_BLOCK
):
finished_ss = header_block.finished_sub_slots[finished_sub_slot_n - 1]
assert finished_ss.infused_challenge_chain is not None
# Only sets the icc iff the previous sub slots deficit is 4 or less
icc_challenge_hash = finished_ss.infused_challenge_chain.get_hash()
icc_iters_committed = prev_b.sub_slot_iters
icc_iters_proof = icc_iters_committed
icc_vdf_input = ClassgroupElement.get_default_element()
# Only sets the icc iff the previous sub slots deficit is 4 or less
icc_challenge_hash = finished_ss.infused_challenge_chain.get_hash()
icc_iters_committed = prev_b.sub_slot_iters
icc_iters_proof = icc_iters_committed
icc_vdf_input = ClassgroupElement.get_default_element()
# 2e. Validate that there is not icc iff icc_challenge hash is None
assert (sub_slot.infused_challenge_chain is None) == (icc_challenge_hash is None)
@@ -241,10 +239,9 @@ def validate_unfinished_header_block(
!= sub_slot.challenge_chain.infused_challenge_chain_sub_slot_hash
):
return None, ValidationError(Err.INVALID_ICC_HASH_CC)
else:
# 2h. Check infused challenge sub-slot hash not included for other deficits
if sub_slot.challenge_chain.infused_challenge_chain_sub_slot_hash is not None:
return None, ValidationError(Err.INVALID_ICC_HASH_CC)
# 2h. Check infused challenge sub-slot hash not included for other deficits
elif sub_slot.challenge_chain.infused_challenge_chain_sub_slot_hash is not None:
return None, ValidationError(Err.INVALID_ICC_HASH_CC)
# 2i. Check infused challenge sub-slot hash in reward sub-slot
if (
@@ -396,10 +393,9 @@ def validate_unfinished_header_block(
f"{sub_slot.reward_chain.deficit}",
),
)
else:
# 2t. Otherwise, deficit stays the same at the slot ends, cannot reset until 0
if sub_slot.reward_chain.deficit != prev_b.deficit:
return None, ValidationError(Err.INVALID_DEFICIT, "deficit is wrong at slot end")
# 2t. Otherwise, deficit stays the same at the slot ends, cannot reset until 0
elif sub_slot.reward_chain.deficit != prev_b.deficit:
return None, ValidationError(Err.INVALID_DEFICIT, "deficit is wrong at slot end")
# 3. Check sub-epoch summary
# Note that the subepoch summary is the summary of the previous subepoch (not the one that just finished)
@@ -635,16 +631,15 @@ def validate_unfinished_header_block(
return None, ValidationError(Err.INVALID_RC_SP_VDF)
if new_sub_slot:
rc_sp_hash = header_block.finished_sub_slots[-1].reward_chain.get_hash()
elif genesis_block:
rc_sp_hash = constants.GENESIS_CHALLENGE
else:
if genesis_block:
rc_sp_hash = constants.GENESIS_CHALLENGE
else:
assert prev_b is not None
curr = prev_b
while not curr.first_in_sub_slot:
curr = blocks.block_record(curr.prev_hash)
assert curr.finished_reward_slot_hashes is not None
rc_sp_hash = curr.finished_reward_slot_hashes[-1]
assert prev_b is not None
curr = prev_b
while not curr.first_in_sub_slot:
curr = blocks.block_record(curr.prev_hash)
assert curr.finished_reward_slot_hashes is not None
rc_sp_hash = curr.finished_reward_slot_hashes[-1]
# 12. Check reward chain sp signature
if not AugSchemeMPL.verify(
@@ -761,25 +756,24 @@ def validate_unfinished_header_block(
!= constants.GENESIS_PRE_FARM_FARMER_PUZZLE_HASH
):
return None, ValidationError(Err.INVALID_PREFARM)
# 20b. If pospace has a pool pk, heck pool target signature. Should not check this for genesis block.
elif header_block.reward_chain_block.proof_of_space.pool_public_key is not None:
assert header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash is None
assert header_block.foliage.foliage_block_data.pool_signature is not None
if not AugSchemeMPL.verify(
header_block.reward_chain_block.proof_of_space.pool_public_key,
bytes(header_block.foliage.foliage_block_data.pool_target),
header_block.foliage.foliage_block_data.pool_signature,
):
return None, ValidationError(Err.INVALID_POOL_SIGNATURE)
else:
# 20b. If pospace has a pool pk, heck pool target signature. Should not check this for genesis block.
if header_block.reward_chain_block.proof_of_space.pool_public_key is not None:
assert header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash is None
assert header_block.foliage.foliage_block_data.pool_signature is not None
if not AugSchemeMPL.verify(
header_block.reward_chain_block.proof_of_space.pool_public_key,
bytes(header_block.foliage.foliage_block_data.pool_target),
header_block.foliage.foliage_block_data.pool_signature,
):
return None, ValidationError(Err.INVALID_POOL_SIGNATURE)
else:
# 20c. Otherwise, the plot is associated with a contract puzzle hash, not a public key
assert header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash is not None
if (
header_block.foliage.foliage_block_data.pool_target.puzzle_hash
!= header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash
):
return None, ValidationError(Err.INVALID_POOL_TARGET)
# 20c. Otherwise, the plot is associated with a contract puzzle hash, not a public key
assert header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash is not None
if (
header_block.foliage.foliage_block_data.pool_target.puzzle_hash
!= header_block.reward_chain_block.proof_of_space.pool_contract_puzzle_hash
):
return None, ValidationError(Err.INVALID_POOL_TARGET)
# 21. Check extension data if applicable. None for mainnet.
# 22. Check if foliage block is present
@@ -928,18 +922,17 @@ def validate_finished_header_block(
# 29. Check challenge chain infusion point VDF
if new_sub_slot:
cc_vdf_challenge = header_block.finished_sub_slots[-1].challenge_chain.get_hash()
# Not first block in slot
elif genesis_block:
# genesis block
cc_vdf_challenge = constants.GENESIS_CHALLENGE
else:
# Not first block in slot
if genesis_block:
# genesis block
cc_vdf_challenge = constants.GENESIS_CHALLENGE
else:
assert prev_b is not None
# Not genesis block, go back to first block in slot
curr = prev_b
while curr.finished_challenge_slot_hashes is None:
curr = blocks.block_record(curr.prev_hash)
cc_vdf_challenge = curr.finished_challenge_slot_hashes[-1]
assert prev_b is not None
# Not genesis block, go back to first block in slot
curr = prev_b
while curr.finished_challenge_slot_hashes is None:
curr = blocks.block_record(curr.prev_hash)
cc_vdf_challenge = curr.finished_challenge_slot_hashes[-1]
cc_target_vdf_info = VDFInfo(
cc_vdf_challenge,
@@ -1047,9 +1040,8 @@ def validate_finished_header_block(
icc_target_vdf_info,
):
return None, ValidationError(Err.INVALID_ICC_VDF, "invalid icc proof")
else:
if header_block.infused_challenge_chain_ip_proof is not None:
return None, ValidationError(Err.INVALID_ICC_VDF)
elif header_block.infused_challenge_chain_ip_proof is not None:
return None, ValidationError(Err.INVALID_ICC_VDF)
# 32. Check reward block hash
if header_block.foliage.reward_block_hash != header_block.reward_chain_block.get_hash():
+2 -3
View File
@@ -708,9 +708,8 @@ class Blockchain:
if block.transactions_generator is not None:
if std_hash(bytes(block.transactions_generator)) != block.transactions_info.generator_root:
return None, Err.INVALID_TRANSACTIONS_GENERATOR_HASH
else:
if block.transactions_info.generator_root != bytes([0] * 32):
return None, Err.INVALID_TRANSACTIONS_GENERATOR_HASH
elif block.transactions_info.generator_root != bytes([0] * 32):
return None, Err.INVALID_TRANSACTIONS_GENERATOR_HASH
if (
block.foliage_transaction_block is None
+24 -25
View File
@@ -72,34 +72,33 @@ def get_block_challenge(
else:
# No overflow, new slot with a new challenge
challenge = header_block.finished_sub_slots[-1].challenge_chain.get_hash()
elif genesis_block:
challenge = constants.GENESIS_CHALLENGE
else:
if genesis_block:
challenge = constants.GENESIS_CHALLENGE
else:
if overflow:
if skip_overflow_last_ss_validation:
# Overflow infusion without the new slot, so get the last challenge
challenges_to_look_for = 1
else:
# Overflow infusion, so get the second to last challenge. skip_overflow_last_ss_validation is False,
# Which means no sub slots are omitted
challenges_to_look_for = 2
else:
if overflow:
if skip_overflow_last_ss_validation:
# Overflow infusion without the new slot, so get the last challenge
challenges_to_look_for = 1
reversed_challenge_hashes: list[bytes32] = []
curr: BlockRecord = blocks.block_record(header_block.prev_header_hash)
while len(reversed_challenge_hashes) < challenges_to_look_for:
if curr.first_in_sub_slot:
assert curr.finished_challenge_slot_hashes is not None
reversed_challenge_hashes += reversed(curr.finished_challenge_slot_hashes)
if len(reversed_challenge_hashes) >= challenges_to_look_for:
break
if curr.height == 0:
assert curr.finished_challenge_slot_hashes is not None
assert len(curr.finished_challenge_slot_hashes) > 0
else:
# Overflow infusion, so get the second to last challenge. skip_overflow_last_ss_validation is False,
# Which means no sub slots are omitted
challenges_to_look_for = 2
else:
challenges_to_look_for = 1
reversed_challenge_hashes: list[bytes32] = []
curr: BlockRecord = blocks.block_record(header_block.prev_header_hash)
while len(reversed_challenge_hashes) < challenges_to_look_for:
if curr.first_in_sub_slot:
assert curr.finished_challenge_slot_hashes is not None
reversed_challenge_hashes += reversed(curr.finished_challenge_slot_hashes)
if len(reversed_challenge_hashes) >= challenges_to_look_for:
break
curr = blocks.block_record(curr.prev_hash)
challenge = reversed_challenge_hashes[challenges_to_look_for - 1]
if curr.height == 0:
assert curr.finished_challenge_slot_hashes is not None
assert len(curr.finished_challenge_slot_hashes) > 0
break
curr = blocks.block_record(curr.prev_hash)
challenge = reversed_challenge_hashes[challenges_to_look_for - 1]
return challenge
+2 -3
View File
@@ -1373,9 +1373,8 @@ class WebSocketServer:
"service": service,
"queue": self.extract_plot_queue(),
}
else:
if self.ping_job is None:
self.ping_job = create_referenced_task(self.ping_task())
elif self.ping_job is None:
self.ping_job = create_referenced_task(self.ping_task())
self.log.info(f"registered for service {service}")
log.info(f"{response}")
return response
+11 -11
View File
@@ -590,15 +590,14 @@ class DataLayerWallet:
if coins is None or len(coins) == 0:
if launcher_id is None:
raise ValueError("Not enough info to know which DL coin to send")
elif len(coins) != 1:
raise ValueError("The wallet can only send one DL coin at a time")
else:
if len(coins) != 1:
raise ValueError("The wallet can only send one DL coin at a time")
record = await self.wallet_state_manager.dl_store.get_singleton_record(next(iter(coins)).name())
if record is None:
raise ValueError("The specified coin is not a tracked DL")
else:
record = await self.wallet_state_manager.dl_store.get_singleton_record(next(iter(coins)).name())
if record is None:
raise ValueError("The specified coin is not a tracked DL")
else:
launcher_id = record.launcher_id
launcher_id = record.launcher_id
if len(amounts) != 1 or len(puzzle_hashes) != 1:
raise ValueError("The wallet can only send one DL coin to one place at a time")
@@ -1090,12 +1089,13 @@ class DataLayerWallet:
# Create all of the new solutions
new_spends: list[CoinSpend] = []
for spend in offer.coin_spends():
spend_to_add = spend
solution = Program.from_serialized(spend.solution)
if match_dl_singleton(spend.puzzle_reveal)[0]:
try:
graftroot: Program = solution.at("rrffrf")
except EvalError:
new_spends.append(spend)
new_spends.append(spend_to_add)
continue
mod, curried_args_prg = graftroot.uncurry()
if mod == GRAFTROOT_DL_OFFERS:
@@ -1138,9 +1138,9 @@ class DataLayerWallet:
]
)
)
new_spend: CoinSpend = spend.replace(solution=new_solution.to_serialized())
spend = new_spend
new_spends.append(spend)
spend_to_add = spend.replace(solution=new_solution.to_serialized())
new_spends.append(spend_to_add)
return Offer({}, WalletSpendBundle(new_spends, offer.aggregated_signature()), offer.driver_dict)
+29 -28
View File
@@ -1172,8 +1172,8 @@ class DataStore:
)
if status == Status.COMMITTED:
for left_hash, right_hash, store_id in insert_ancestors_cache:
await self._insert_ancestor_table(left_hash, right_hash, store_id, new_generation)
for left_hash, right_hash, cache_store_id in insert_ancestors_cache:
await self._insert_ancestor_table(left_hash, right_hash, cache_store_id, new_generation)
return new_root
@@ -1329,8 +1329,8 @@ class DataStore:
generation=new_generation,
)
if status == Status.COMMITTED:
for left_hash, right_hash, store_id in insert_ancestors_cache:
await self._insert_ancestor_table(left_hash, right_hash, store_id, new_generation)
for left_hash, right_hash, cache_store_id in insert_ancestors_cache:
await self._insert_ancestor_table(left_hash, right_hash, cache_store_id, new_generation)
return new_root
@@ -1428,8 +1428,8 @@ class DataStore:
"""
params = {"pending_status": Status.PENDING.value, "pending_batch_status": Status.PENDING_BATCH.value}
if writer is None:
async with self.db_wrapper.writer(foreign_key_enforcement_enabled=False) as writer:
await writer.execute(query, params)
async with self.db_wrapper.writer(foreign_key_enforcement_enabled=False) as sub_writer:
await sub_writer.execute(query, params)
else:
await writer.execute(query, params)
@@ -1497,16 +1497,15 @@ class DataStore:
pending_root = await self.get_pending_root(store_id=store_id)
if pending_root is None:
latest_local_root: Optional[Root] = old_root
else:
if pending_root.status == Status.PENDING_BATCH:
# We have an unfinished batch, continue the current batch on top of it.
if pending_root.generation != old_root.generation + 1:
raise Exception("Internal error")
await self.change_root_status(pending_root, Status.COMMITTED)
await self.build_ancestor_table_for_latest_root(store_id=store_id)
latest_local_root = pending_root
else:
elif pending_root.status == Status.PENDING_BATCH:
# We have an unfinished batch, continue the current batch on top of it.
if pending_root.generation != old_root.generation + 1:
raise Exception("Internal error")
await self.change_root_status(pending_root, Status.COMMITTED)
await self.build_ancestor_table_for_latest_root(store_id=store_id)
latest_local_root = pending_root
else:
raise Exception("Internal error")
assert latest_local_root is not None
@@ -1548,11 +1547,10 @@ class DataStore:
if old_node is None:
pending_autoinsert_hashes.append(terminal_node_hash)
elif key_hash_frequency[hash] == 1:
raise Exception(f"Key already present: {key.hex()}")
else:
if key_hash_frequency[hash] == 1:
raise Exception(f"Key already present: {key.hex()}")
else:
pending_upsert_new_hashes[old_node.hash] = terminal_node_hash
pending_upsert_new_hashes[old_node.hash] = terminal_node_hash
continue
insert_result = await self.autoinsert(
key, value, store_id, True, Status.COMMITTED, root=latest_local_root
@@ -1878,8 +1876,12 @@ class DataStore:
hash_to_node: dict[bytes32, Node] = {}
for node in reversed(nodes):
if isinstance(node, InternalNode):
node = replace(node, left=hash_to_node[node.left_hash], right=hash_to_node[node.right_hash])
hash_to_node[node.hash] = node
node_entry: Node = replace(
node, left=hash_to_node[node.left_hash], right=hash_to_node[node.right_hash]
)
else:
node_entry = node
hash_to_node[node_entry.hash] = node_entry
root_node = hash_to_node[root_node.hash]
@@ -2228,13 +2230,12 @@ class DataStore:
)
else:
subscriptions.append(Subscription(store_id, []))
else:
if url is not None and num_consecutive_failures is not None and ignore_till is not None:
new_servers_info = subscription.servers_info
new_servers_info.append(ServerInfo(url, num_consecutive_failures, ignore_till))
new_subscription = replace(subscription, servers_info=new_servers_info)
subscriptions.remove(subscription)
subscriptions.append(new_subscription)
elif url is not None and num_consecutive_failures is not None and ignore_till is not None:
new_servers_info = subscription.servers_info
new_servers_info.append(ServerInfo(url, num_consecutive_failures, ignore_till))
new_subscription = replace(subscription, servers_info=new_servers_info)
subscriptions.remove(subscription)
subscriptions.append(new_subscription)
return subscriptions
+4 -7
View File
@@ -1393,14 +1393,11 @@ class FullNodeAPI:
error_name = error.name if error is not None else None
if status == MempoolInclusionStatus.SUCCESS:
response = wallet_protocol.TransactionAck(spend_name, uint8(status.value), error_name)
# If it failed/pending, but it previously succeeded (in mempool), this is idempotence, return SUCCESS
elif self.full_node.mempool_manager.get_spendbundle(spend_name) is not None:
response = wallet_protocol.TransactionAck(spend_name, uint8(MempoolInclusionStatus.SUCCESS.value), None)
else:
# If it failed/pending, but it previously succeeded (in mempool), this is idempotence, return SUCCESS
if self.full_node.mempool_manager.get_spendbundle(spend_name) is not None:
response = wallet_protocol.TransactionAck(
spend_name, uint8(MempoolInclusionStatus.SUCCESS.value), None
)
else:
response = wallet_protocol.TransactionAck(spend_name, uint8(status.value), error_name)
response = wallet_protocol.TransactionAck(spend_name, uint8(status.value), error_name)
return make_msg(ProtocolMessageTypes.transaction_ack, response)
@metadata.request()
+13 -14
View File
@@ -411,17 +411,16 @@ class WeightProofHandler:
while not curr_sub_rec.sub_epoch_summary_included:
curr_sub_rec = blocks[curr_sub_rec.prev_hash]
first_rc_end_of_slot_vdf = self.first_rc_end_of_slot_vdf(header_block, blocks, header_blocks)
elif header_block_sub_rec.overflow and header_block_sub_rec.first_in_sub_slot:
sub_slots_num = 2
while sub_slots_num > 0 and curr_sub_rec.height > 0:
if curr_sub_rec.first_in_sub_slot:
assert curr_sub_rec.finished_challenge_slot_hashes is not None
sub_slots_num -= len(curr_sub_rec.finished_challenge_slot_hashes)
curr_sub_rec = blocks[curr_sub_rec.prev_hash]
else:
if header_block_sub_rec.overflow and header_block_sub_rec.first_in_sub_slot:
sub_slots_num = 2
while sub_slots_num > 0 and curr_sub_rec.height > 0:
if curr_sub_rec.first_in_sub_slot:
assert curr_sub_rec.finished_challenge_slot_hashes is not None
sub_slots_num -= len(curr_sub_rec.finished_challenge_slot_hashes)
curr_sub_rec = blocks[curr_sub_rec.prev_hash]
else:
while not curr_sub_rec.first_in_sub_slot and curr_sub_rec.height > 0:
curr_sub_rec = blocks[curr_sub_rec.prev_hash]
while not curr_sub_rec.first_in_sub_slot and curr_sub_rec.height > 0:
curr_sub_rec = blocks[curr_sub_rec.prev_hash]
curr = header_blocks[curr_sub_rec.header_hash]
sub_slots_data: list[SubSlotData] = []
@@ -1533,10 +1532,10 @@ def _get_last_ses_hash(
) -> tuple[Optional[bytes32], uint32]:
for idx, block in enumerate(reversed(recent_reward_chain)):
if (block.reward_chain_block.height % constants.SUB_EPOCH_BLOCKS) == 0:
idx = len(recent_reward_chain) - 1 - idx # reverse
original_idx = len(recent_reward_chain) - 1 - idx # reverse
# find first block after sub slot end
while idx < len(recent_reward_chain):
curr = recent_reward_chain[idx]
while original_idx < len(recent_reward_chain):
curr = recent_reward_chain[original_idx]
if len(curr.finished_sub_slots) > 0:
for slot in curr.finished_sub_slots:
if slot.challenge_chain.subepoch_summary_hash is not None:
@@ -1544,7 +1543,7 @@ def _get_last_ses_hash(
slot.challenge_chain.subepoch_summary_hash,
curr.reward_chain_block.height,
)
idx += 1
original_idx += 1
return None, uint32(0)
+5 -5
View File
@@ -170,9 +170,9 @@ def check_plots(
challenge = std_hash(i.to_bytes(32, "big"))
# Some plot errors cause get_qualities_for_challenge to throw a RuntimeError
try:
quality_start_time = int(round(time() * 1000))
quality_start_time = round(time() * 1000)
for index, quality_str in enumerate(pr.get_qualities_for_challenge(challenge)):
quality_spent_time = int(round(time() * 1000)) - quality_start_time
quality_spent_time = round(time() * 1000) - quality_start_time
if quality_spent_time > 8000:
log.warning(
f"\tLooking up qualities took: {quality_spent_time} ms. This should be below 8 seconds "
@@ -183,9 +183,9 @@ def check_plots(
# Other plot errors cause get_full_proof or validate_proof to throw an AssertionError
try:
proof_start_time = int(round(time() * 1000))
proof_start_time = round(time() * 1000)
proof = pr.get_full_proof(challenge, index, parallel_read)
proof_spent_time = int(round(time() * 1000)) - proof_start_time
proof_spent_time = round(time() * 1000) - proof_start_time
if proof_spent_time > 15000:
log.warning(
f"\tFinding proof took: {proof_spent_time} ms. This should be below 15 seconds "
@@ -207,7 +207,7 @@ def check_plots(
f"{type(e)}: {e} error in proving/verifying for plot {plot_path}. Filepath: {plot_path}"
)
caught_exception = True
quality_start_time = int(round(time() * 1000))
quality_start_time = round(time() * 1000)
except KeyboardInterrupt:
log.warning("Interrupted, closing")
return
+3 -4
View File
@@ -83,10 +83,9 @@ class PlotKeysResolver:
if self.pool_contract_address is not None:
raise RuntimeError("Choose one of pool_contract_address and pool_public_key")
pool_public_key = G1Element.from_bytes(bytes.fromhex(self.pool_public_key))
else:
if self.pool_contract_address is None:
# If nothing is set, farms to the provided key (or the first key)
pool_public_key = await self.get_pool_public_key(keychain_proxy)
elif self.pool_contract_address is None:
# If nothing is set, farms to the provided key (or the first key)
pool_public_key = await self.get_pool_public_key(keychain_proxy)
self.resolved_keys = PlotKeys(farmer_public_key, pool_public_key, self.pool_contract_address)
finally:
+4 -8
View File
@@ -195,11 +195,10 @@ class CrawlStore:
counter += 1
if reliability.ignore_till < now and reliability.ban_till < now:
add = True
else:
if reliability.ban_till >= now:
self.banned_peers += 1
elif reliability.ignore_till >= now:
self.ignored_peers += 1
elif reliability.ban_till >= now:
self.banned_peers += 1
elif reliability.ignore_till >= now:
self.ignored_peers += 1
record = self.host_to_records[peer_id]
if record.last_try_timestamp == 0 and record.connected_timestamp == 0:
add = True
@@ -342,9 +341,6 @@ class CrawlStore:
handshake = {}
for host, record in self.host_to_records.items():
if host not in self.host_to_records:
continue
record = self.host_to_records[host]
if record.version == "undefined":
continue
if record.handshake_time < time.time() - 5 * 24 * 3600:
+10 -13
View File
@@ -177,7 +177,7 @@ class ExtendedPeerInfo:
def is_terrible(self, now: Optional[int] = None) -> bool:
if now is None:
now = int(math.floor(time.time()))
now = math.floor(time.time())
# never remove things tried in the last minute
if self.last_try > 0 and self.last_try >= now - 60:
return False
@@ -202,7 +202,7 @@ class ExtendedPeerInfo:
def get_selection_chance(self, now: Optional[int] = None) -> float:
if now is None:
now = int(math.floor(time.time()))
now = math.floor(time.time())
chance = 1.0
since_last_try = max(now - self.last_try, 0)
# deprioritize very recent attempts away
@@ -371,9 +371,8 @@ class AddressManager:
if value == -1:
if (row, col) in self.used_new_matrix_positions:
self.used_new_matrix_positions.remove((row, col))
else:
if (row, col) not in self.used_new_matrix_positions:
self.used_new_matrix_positions.add((row, col))
elif (row, col) not in self.used_new_matrix_positions:
self.used_new_matrix_positions.add((row, col))
# Use only this method for modifying tried matrix.
def _set_tried_matrix(self, row: int, col: int, value: int) -> None:
@@ -381,9 +380,8 @@ class AddressManager:
if value == -1:
if (row, col) in self.used_tried_matrix_positions:
self.used_tried_matrix_positions.remove((row, col))
else:
if (row, col) not in self.used_tried_matrix_positions:
self.used_tried_matrix_positions.add((row, col))
elif (row, col) not in self.used_tried_matrix_positions:
self.used_tried_matrix_positions.add((row, col))
def load_used_table_positions(self) -> None:
self.used_new_matrix_positions = set()
@@ -587,10 +585,9 @@ class AddressManager:
info.ref_count += 1
if node_id is not None:
self._set_new_matrix(new_bucket, new_bucket_pos, node_id)
else:
if info.ref_count == 0:
if node_id is not None:
self.delete_new_entry_(node_id)
elif info.ref_count == 0:
if node_id is not None:
self.delete_new_entry_(node_id)
return is_unique
def attempt_(self, addr: PeerInfo, count_failures: bool, timestamp: int) -> None:
@@ -737,7 +734,7 @@ class AddressManager:
return addr
def cleanup(self, max_timestamp_difference: int, max_consecutive_failures: int) -> None:
now = int(math.floor(time.time()))
now = math.floor(time.time())
for bucket in range(NEW_BUCKET_COUNT):
for pos in range(BUCKET_SIZE):
if self.new_matrix[bucket][pos] != -1:
+4 -5
View File
@@ -228,12 +228,11 @@ class FullNodeDiscovery:
if self.server.is_duplicate_or_self_connection(addr):
# Mark it as a softer attempt, without counting the failures.
await self.address_manager.attempt(addr, False)
elif client_connected is True:
await self.address_manager.mark_good(addr)
await self.address_manager.connect(addr)
else:
if client_connected is True:
await self.address_manager.mark_good(addr)
await self.address_manager.connect(addr)
else:
await self.address_manager.attempt(addr, True)
await self.address_manager.attempt(addr, True)
self.pending_outbound_connections.remove(addr.host)
except Exception as e:
if addr.host in self.pending_outbound_connections:
+2 -3
View File
@@ -260,9 +260,8 @@ class ChiaServer:
if is_crawler is not None:
if time.time() - connection.creation_time > 5:
to_remove.append(connection)
else:
if time.time() - connection.last_message_time > 1800:
to_remove.append(connection)
elif time.time() - connection.last_message_time > 1800:
to_remove.append(connection)
for connection in to_remove:
self.log.debug(f"Garbage collecting connection {connection.peer_info.host} due to inactivity")
if connection.closed:
+6 -8
View File
@@ -898,11 +898,10 @@ class BlockTools:
# address, so continue until a proof of space tied to a pk is found
continue
pool_target = PoolTarget(proof_of_space.pool_contract_puzzle_hash, uint32(0))
elif pool_reward_puzzle_hash is not None:
pool_target = PoolTarget(pool_reward_puzzle_hash, uint32(0))
else:
if pool_reward_puzzle_hash is not None:
pool_target = PoolTarget(pool_reward_puzzle_hash, uint32(0))
else:
pool_target = PoolTarget(self.pool_ph, uint32(0))
pool_target = PoolTarget(self.pool_ph, uint32(0))
new_gen = self.setup_new_gen(
tx_block_heights,
@@ -1193,11 +1192,10 @@ class BlockTools:
# address, so continue until a proof of space tied to a pk is found
continue
pool_target = PoolTarget(proof_of_space.pool_contract_puzzle_hash, uint32(0))
elif pool_reward_puzzle_hash is not None:
pool_target = PoolTarget(pool_reward_puzzle_hash, uint32(0))
else:
if pool_reward_puzzle_hash is not None:
pool_target = PoolTarget(pool_reward_puzzle_hash, uint32(0))
else:
pool_target = PoolTarget(self.pool_ph, uint32(0))
pool_target = PoolTarget(self.pool_ph, uint32(0))
new_gen = self.setup_new_gen(
tx_block_heights,
+12 -13
View File
@@ -160,20 +160,19 @@ class Timelord:
slow_bluebox = self.config.get("slow_bluebox", False)
if not self.bluebox_mode:
self.main_loop = create_referenced_task(self._manage_chains())
elif os.name == "nt" or slow_bluebox:
# `vdf_client` doesn't build on windows, use `prove()` from chiavdf.
workers = self.config.get("slow_bluebox_process_count", 1)
self._executor_shutdown_tempfile = _create_shutdown_file()
self.bluebox_pool = ThreadPoolExecutor(
max_workers=workers,
thread_name_prefix="blue-box-",
)
self.main_loop = create_referenced_task(
self._start_manage_discriminant_queue_sanitizer_slow(self.bluebox_pool, workers)
)
else:
if os.name == "nt" or slow_bluebox:
# `vdf_client` doesn't build on windows, use `prove()` from chiavdf.
workers = self.config.get("slow_bluebox_process_count", 1)
self._executor_shutdown_tempfile = _create_shutdown_file()
self.bluebox_pool = ThreadPoolExecutor(
max_workers=workers,
thread_name_prefix="blue-box-",
)
self.main_loop = create_referenced_task(
self._start_manage_discriminant_queue_sanitizer_slow(self.bluebox_pool, workers)
)
else:
self.main_loop = create_referenced_task(self._manage_discriminant_queue_sanitizer())
self.main_loop = create_referenced_task(self._manage_discriminant_queue_sanitizer())
log.info(f"Started timelord, listening on port {self.get_vdf_server_port()}")
try:
yield
+7 -8
View File
@@ -124,15 +124,14 @@ def get_host_parameter_limit() -> int:
limit_number = sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER
host_parameter_limit = connection.getlimit(limit_number)
else:
# guessing based on defaults, seems you can't query
# guessing based on defaults, seems you can't query
# https://www.sqlite.org/changes.html#version_3_32_0
# Increase the default upper bound on the number of parameters from 999 to 32766.
if sqlite3.sqlite_version_info >= (3, 32, 0):
host_parameter_limit = 32766
else:
host_parameter_limit = 999
# https://www.sqlite.org/changes.html#version_3_32_0
# Increase the default upper bound on the number of parameters from 999 to 32766.
elif sqlite3.sqlite_version_info >= (3, 32, 0):
host_parameter_limit = 32766
else:
host_parameter_limit = 999
return host_parameter_limit
+7 -4
View File
@@ -105,8 +105,11 @@ class CATOuterPuzzle:
parent_coin: Coin = parent_spend.coin
also = constructor.also()
if also is not None:
solution = self._solve(also, solver, puzzle, solution)
puzzle = self._construct(also, puzzle)
constructed_solution = self._solve(also, solver, puzzle, solution)
constructed_puzzle = self._construct(also, puzzle)
else:
constructed_solution = solution
constructed_puzzle = puzzle
args = match_cat_puzzle(uncurry_puzzle(parent_spend.puzzle_reveal))
assert args is not None
_, _, parent_inner_puzzle = args
@@ -114,8 +117,8 @@ class CATOuterPuzzle:
SpendableCAT(
coin,
tail_hash,
puzzle,
solution,
constructed_puzzle,
constructed_solution,
lineage_proof=LineageProof(
parent_coin.parent_coin_info, parent_inner_puzzle.get_tree_hash(), uint64(parent_coin.amount)
),
+3 -3
View File
@@ -550,9 +550,9 @@ class NFTWallet:
name: Optional[str] = None,
) -> Any:
# Off the bat we don't support multiple profile but when we do this will have to change
for wallet in wallet_state_manager.wallets.values():
if wallet.type() == WalletType.NFT.value:
return wallet
for wsm_wallet in wallet_state_manager.wallets.values():
if wsm_wallet.type() == WalletType.NFT.value:
return wsm_wallet
# TODO: These are not the arguments to this function yet but they will be
return await cls.create_new_nft_wallet(
+7 -8
View File
@@ -65,15 +65,14 @@ class PuzzleInfo:
return True
else:
return False
else:
if self.type() == types[0]:
types.pop(0)
if self.also():
return self.also().check_type(types) # type: ignore
else:
return self.check_type(types)
elif self.type() == types[0]:
types.pop(0)
if self.also():
return self.also().check_type(types) # type: ignore
else:
return False
return self.check_type(types)
else:
return False
@dataclass(frozen=True)
+2 -2
View File
@@ -39,9 +39,9 @@ def build_merkle_tree_from_binary_tree(tuples: TupleTree) -> tuple[bytes32, dict
proof.append(right_root)
new_proofs[name] = (path, proof)
for name, (path, proof) in right_proofs.items():
path |= 1 << len(proof)
appended_path = path | (1 << len(proof))
proof.append(left_root)
new_proofs[name] = (path, proof)
new_proofs[name] = (appended_path, proof)
return new_root, new_proofs
+3 -5
View File
@@ -455,12 +455,10 @@ class VCWallet:
crcat_spends.append(crcat_spend)
if spend in offer._bundle.coin_spends:
spends_to_fix[spend.coin.name()] = spend
else:
if spend in offer._bundle.coin_spends: # pragma: no cover
other_spends.append(spend)
else:
if spend in offer._bundle.coin_spends:
elif spend in offer._bundle.coin_spends: # pragma: no cover
other_spends.append(spend)
elif spend in offer._bundle.coin_spends:
other_spends.append(spend)
# Figure out what VC announcements are needed
announcements_to_make: dict[bytes32, list[CreatePuzzleAnnouncement]] = {}
+25 -30
View File
@@ -911,14 +911,13 @@ class WalletNode:
):
# only one peer told us to rollback so only clear for that peer
await self.perform_atomic_rollback(fork_height, cache=cache)
else:
if fork_height is not None:
# only one peer told us to rollback so only clear for that peer
cache.clear_after_height(fork_height)
self.log.info(f"clear_after_height {fork_height} for peer {peer}")
if not trusted:
# Rollback race_cache not in clear_after_height to avoid applying rollbacks from new peak processing
cache.rollback_race_cache(fork_height=fork_height)
elif fork_height is not None:
# only one peer told us to rollback so only clear for that peer
cache.clear_after_height(fork_height)
self.log.info(f"clear_after_height {fork_height} for peer {peer}")
if not trusted:
# Rollback race_cache not in clear_after_height to avoid applying rollbacks from new peak processing
cache.rollback_race_cache(fork_height=fork_height)
all_tasks: list[asyncio.Task[None]] = []
target_concurrent_tasks: int = 30
@@ -989,18 +988,17 @@ class WalletNode:
)
if not await self.wallet_state_manager.add_coin_states(batch.entries, peer, fork_height):
return False
elif fork_height is not None:
cache.add_states_to_race_cache(batch.entries)
else:
if fork_height is not None:
cache.add_states_to_race_cache(batch.entries)
else:
while len(all_tasks) >= target_concurrent_tasks:
all_tasks = [task for task in all_tasks if not task.done()]
await asyncio.sleep(0.1)
if self._shut_down:
self.log.info("Terminating receipt and validation due to shut down request")
await asyncio.gather(*all_tasks)
return False
all_tasks.append(create_referenced_task(validate_and_add(batch.entries, idx)))
while len(all_tasks) >= target_concurrent_tasks:
all_tasks = [task for task in all_tasks if not task.done()]
await asyncio.sleep(0.1)
if self._shut_down:
self.log.info("Terminating receipt and validation due to shut down request")
await asyncio.gather(*all_tasks)
return False
all_tasks.append(create_referenced_task(validate_and_add(batch.entries, idx)))
idx += len(batch.entries)
still_connected = self._server is not None and peer.peer_node_id in self.server.all_connections
@@ -1158,9 +1156,8 @@ class WalletNode:
await self.new_peak_from_trusted(
new_peak_hb, latest_timestamp, peer, new_peak.fork_point_with_previous_peak
)
else:
if not await self.new_peak_from_untrusted(new_peak_hb, peer):
return
elif not await self.new_peak_from_untrusted(new_peak_hb, peer):
return
# todo why do we call this if there was an exception / the sync is not finished
async with self.wallet_state_manager.lock:
@@ -1272,10 +1269,9 @@ class WalletNode:
)
if success:
self.synced_peers.add(peer.peer_node_id)
else:
if peak_hb is not None and new_peak_hb.weight <= peak_hb.weight:
# Don't process blocks at the same weight
return False
elif peak_hb is not None and new_peak_hb.weight <= peak_hb.weight:
# Don't process blocks at the same weight
return False
# For every block, we need to apply the cache from race_cache
for potential_height in range(backtrack_fork_height + 1, new_peak_hb.height + 1):
@@ -1663,10 +1659,9 @@ class WalletNode:
if not prev_block_rc_hash == reversed_slots[-1].reward_chain.end_of_slot_vdf.challenge:
self.log.error("Failed validation 7")
return False
else:
if not prev_block_rc_hash == reward_chain_hash:
self.log.error("Failed validation 8")
return False
elif not prev_block_rc_hash == reward_chain_hash:
self.log.error("Failed validation 8")
return False
blocks_to_cache.append((reward_chain_hash, en_block.height))
agg_sig: G2Element = AugSchemeMPL.aggregate([sig for (_, _, sig) in pk_m_sig])
+20 -18
View File
@@ -1428,14 +1428,16 @@ class WalletStateManager:
nft_data.parent_coin_spend.solution,
)
if uncurried_nft.supports_did:
_new_did_id = get_new_owner_did(uncurried_nft, Program.from_serialized(nft_data.parent_coin_spend.solution))
parsed_did_id = get_new_owner_did(
uncurried_nft, Program.from_serialized(nft_data.parent_coin_spend.solution)
)
old_did_id = uncurried_nft.owner_did
if _new_did_id is None:
if parsed_did_id is None:
new_did_id = old_did_id
elif _new_did_id == b"":
elif parsed_did_id == b"":
new_did_id = None
else:
new_did_id = _new_did_id
new_did_id = parsed_did_id
self.log.debug(
"Handling NFT: %s, old DID:%s, new DID:%s, old P2:%s, new P2:%s",
nft_data.parent_coin_spend,
@@ -1945,8 +1947,8 @@ class WalletStateManager:
# No more singleton (maybe destroyed?)
break
coin_name = new_singleton_coin.name()
existing = await self.coin_store.get_coin_record(coin_name)
new_singleton_name = new_singleton_coin.name()
existing = await self.coin_store.get_coin_record(new_singleton_name)
if existing is None:
await self.coin_added(
new_singleton_coin,
@@ -1955,7 +1957,7 @@ class WalletStateManager:
uint32(record.wallet_id),
record.wallet_type,
peer,
coin_name,
new_singleton_name,
coin_data,
)
await self.coin_store.set_spent(
@@ -1963,7 +1965,7 @@ class WalletStateManager:
)
await self.add_interested_coin_ids([new_singleton_coin.name()])
new_coin_state: list[CoinState] = await self.wallet_node.get_coin_state(
[coin_name], peer=peer, fork_height=fork_height
[new_singleton_name], peer=peer, fork_height=fork_height
)
assert len(new_coin_state) == 1
curr_coin_state = new_coin_state[0]
@@ -2039,8 +2041,8 @@ class WalletStateManager:
launcher_spend_additions = compute_additions(launcher_spend)
assert len(launcher_spend_additions) == 1
coin_added = launcher_spend_additions[0]
coin_name = coin_added.name()
existing = await self.coin_store.get_coin_record(coin_name)
coin_added_name = coin_added.name()
existing = await self.coin_store.get_coin_record(coin_added_name)
if existing is None:
await self.coin_added(
coin_added,
@@ -2049,10 +2051,10 @@ class WalletStateManager:
pool_wallet.id(),
pool_wallet.type(),
peer,
coin_name,
coin_added_name,
coin_data,
)
await self.add_interested_coin_ids([coin_name])
await self.add_interested_coin_ids([coin_added_name])
else:
raise RuntimeError("All cases already handled") # Logic error, all cases handled
@@ -2611,20 +2613,20 @@ class WalletStateManager:
[path_hint for pk in pks for path_hint in (await self.path_hint_for_pubkey(pk),) if path_hint is not None],
)
async def gather_signing_info(self, coin_spends: list[Spend]) -> SigningInstructions:
async def gather_signing_info(self, spends: list[Spend]) -> SigningInstructions:
pks: list[bytes] = []
signing_targets: list[SigningTarget] = []
for coin_spend in coin_spends:
_coin_spend = coin_spend.as_coin_spend()
for spend in spends:
coin_spend = spend.as_coin_spend()
# Get AGG_SIG conditions
conditions_dict = conditions_dict_for_solution(
Program.from_serialized(_coin_spend.puzzle_reveal),
Program.from_serialized(_coin_spend.solution),
Program.from_serialized(coin_spend.puzzle_reveal),
Program.from_serialized(coin_spend.solution),
self.constants.MAX_BLOCK_COST_CLVM,
)
# Create signature
for pk, msg in pkm_pairs_for_conditions_dict(
conditions_dict, _coin_spend.coin, self.constants.AGG_SIG_ME_ADDITIONAL_DATA
conditions_dict, coin_spend.coin, self.constants.AGG_SIG_ME_ADDITIONAL_DATA
):
pk_bytes = bytes(pk)
pks.append(pk_bytes)
+3 -4
View File
@@ -262,10 +262,9 @@ class WalletTransactionStore:
if time_submitted < current_time - (60 * 10):
records.append(record)
self.tx_submitted[record.name] = current_time, 1
else:
if count < minimum_send_attempts:
records.append(record)
self.tx_submitted[record.name] = time_submitted, (count + 1)
elif count < minimum_send_attempts:
records.append(record)
self.tx_submitted[record.name] = time_submitted, (count + 1)
else:
records.append(record)
self.tx_submitted[record.name] = current_time, 1
-10
View File
@@ -61,13 +61,10 @@ ignore = [
# Should probably fix these
"PLR6301", # no-self-use
"PLR2004", # magic-value-comparison
"PLR1704", # redefined-argument-from-local
"PLR5501", # collapsible-else-if
# Pylint warning
"PLW1641", # eq-without-hash
# Should probably fix these
"PLW2901", # redefined-loop-name
"PLW1514", # unspecified-encoding
"PLW0603", # global-statement
@@ -80,10 +77,6 @@ ignore = [
# flake8-implicit-str-concat
"ISC003", # explicit-string-concatenation
# pyupgrade
# Should probably fix these
"UP006", # non-pep585-annotation
# Ruff Specific
# This code is problematic because using instantiated types as defaults is so common across the codebase.
@@ -93,9 +86,6 @@ ignore = [
"RUF056", # falsy-dict-get-fallback
# Should probably fix this
"RUF029", # unused-async
"RUF043", # pytest-raises-ambiguous-pattern
"RUF046", # unnecessary-cast-to-int
"RUF052", # used-dummy-variable
# Security linter
"S603", # subprocess-without-shell-equals-true
-1
View File
@@ -83,7 +83,6 @@ def main(pid: int, output: str, threads: bool) -> None:
out.write(f" {(c[row].system_time - c[row - 1].system_time) * 100 / time_delta:6.2f}% ")
else:
out.write(" 0.00% 0.00% ")
row += 1
out.write("\n")
with open("plot-cpu.gnuplot", "w+") as out: