[CHIA-3043] Add (hopefully) non-controversial ruff rules (#19684)

* Add (hopefully) non-controversial ruff rules

* mypy-exclusions.txt

* PIE

* Fix pre-commit?

* PYI

* RSE

* S + ignores

* Whitespace fix

* Re-add build-init-files.py

* Add comment about security ignores

* Update mypy-exclusions.txt

Co-authored-by: Kyle Altendorf <sda@fstab.net>

* Fix the executable status of build-init-files.py

* Set executable bit for tools/run_block.py and readd shebang

* Fix new errors

---------

Co-authored-by: Kyle Altendorf <sda@fstab.net>
This commit is contained in:
Matt Hauff
2025-06-11 08:36:08 -07:00
committed by GitHub
co-authored by Kyle Altendorf
parent 9289a05f12
commit 6050235bdb
107 changed files with 318 additions and 328 deletions
-1
View File
@@ -56,7 +56,6 @@ repos:
- id: trailing-whitespace
- id: check-merge-conflict
- id: check-ast
- id: debug-statements
- repo: local
hooks:
- id: chialispp
+1 -1
View File
@@ -64,7 +64,7 @@ def get_commit_hash() -> str:
sys.exit("Failed to get the commit hash")
try:
if len(subprocess.run(["git", "status", "-s"], check=True, stdout=subprocess.PIPE).stdout) > 0:
raise Exception()
raise Exception
except Exception:
commit_hash += "-dirty"
return commit_hash
+4 -4
View File
@@ -14,7 +14,7 @@ from chia.wallet.util.compute_additions import compute_additions
@pytest.mark.anyio
async def test_farming():
async with sim_and_client(pass_prefarm=False) as (sim, _):
for i in range(0, 5):
for i in range(5):
await sim.farm_block()
assert len(sim.blocks) == 5
@@ -25,7 +25,7 @@ async def test_farming():
@pytest.mark.anyio
async def test_rewind():
async with sim_and_client() as (sim, _):
for i in range(0, 5):
for i in range(5):
await sim.farm_block()
save_height = sim.get_height()
@@ -39,11 +39,11 @@ async def test_rewind():
@pytest.mark.anyio
async def test_all_endpoints():
async with sim_and_client() as (sim, sim_client):
for i in range(0, 5):
for i in range(5):
await sim.farm_block()
await sim.farm_block(bytes32.zeros)
await sim.farm_block(bytes32([1] * 32))
for i in range(0, 5):
for i in range(5):
await sim.farm_block()
# get_coin_records_by_hint
+2 -2
View File
@@ -734,7 +734,7 @@ async def test_get_owned_stores(
await wallet_node.server.start_client(PeerInfo(self_hostname, full_node_api.server.get_port()), None)
async with wallet_node.wallet_state_manager.new_action_scope(DEFAULT_TX_CONFIG, push=True) as action_scope:
ph = await action_scope.get_puzzle_hash(wallet_node.wallet_state_manager)
for i in range(0, num_blocks):
for i in range(num_blocks):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
funds = sum(
calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks)
@@ -752,7 +752,7 @@ async def test_get_owned_stores(
expected_store_ids.append(launcher_id)
await time_out_assert(4, check_mempool_spend_count, True, full_node_api, 3)
for i in range(0, num_blocks):
for i in range(num_blocks):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await asyncio.sleep(0.5)
@@ -107,7 +107,7 @@ async def test_create_tree_accepts_bytes32(raw_data_store: DataStore) -> None:
await raw_data_store.create_tree(store_id=store_id)
@pytest.mark.parametrize(argnames=["length"], argvalues=[[length] for length in [*range(0, 32), *range(33, 48)]])
@pytest.mark.parametrize(argnames=["length"], argvalues=[[length] for length in [*range(32), *range(33, 48)]])
@pytest.mark.anyio
async def test_create_store_fails_for_not_bytes32(raw_data_store: DataStore, length: int) -> None:
bad_store_id = b"\0" * length
@@ -1361,7 +1361,7 @@ async def test_server_http_ban(
log: logging.Logger,
) -> None:
if error:
raise aiohttp.ClientConnectionError()
raise aiohttp.ClientConnectionError
start_timestamp = int(time.time())
with monkeypatch.context() as m:
@@ -91,7 +91,7 @@ async def test_duplicates(db_version: int) -> None:
hint_0 = 32 * b"\0"
coin_id_0 = bytes32(32 * b"\4")
for i in range(0, 2):
for i in range(2):
hints = [(coin_id_0, hint_0), (coin_id_0, hint_0)]
await hint_store.add_hints(hints)
coins_for_hint_0 = await hint_store.get_coin_ids(hint_0)
@@ -511,7 +511,7 @@ class TestBlockHeightMap:
assert len(new_heights) == 4000 * 32
# pytest doesn't behave very well comparing large buffers
# (when the test fails). Compare small portions at a time instead
for idx in range(0, 2000):
for idx in range(2000):
assert new_heights[idx * 32 : idx * 32 + 32] == gen_block_hash(idx)
+3 -3
View File
@@ -683,7 +683,7 @@ async def test_respond_end_of_sub_slot_no_reorg(
# First get two blocks in the same sub slot
blocks = await full_node_1.get_all_full_blocks()
for i in range(0, 9999999):
for i in range(9999999):
blocks = bt.get_consecutive_blocks(5, block_list_input=blocks, skip_slots=1, seed=i.to_bytes(4, "big"))
if len(blocks[-1].finished_sub_slots) == 0:
break
@@ -1468,7 +1468,7 @@ async def test_new_unfinished_block2_forward_limit(
unf_blocks: list[UnfinishedBlock] = []
last_reward_hash: Optional[bytes32] = None
for idx in range(0, 6):
for idx in range(6):
# we include a different transaction in each block. This makes the
# foliage different in each of them, but the reward block (plot) the same
tx = wallet_a.generate_signed_transaction(uint64(100 * (idx + 1)), puzzle_hash, coin)
@@ -1765,7 +1765,7 @@ async def test_request_unfinished_block2(
# deterministically
best_unf: Optional[UnfinishedBlock] = None
for idx in range(0, 6):
for idx in range(6):
# we include a different transaction in each block. This makes the
# foliage different in each of them, but the reward block (plot) the same
tx = wallet_a.generate_signed_transaction(uint64(100 * (idx + 1)), puzzle_hash, coin)
+1 -1
View File
@@ -1152,7 +1152,7 @@ class TestMempoolManager:
assert sb1 is None
assert status == MempoolInclusionStatus.FAILED
for i in range(0, 4):
for i in range(4):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(bytes32(32 * b"0")))
tx2: full_node_protocol.RespondTransaction = full_node_protocol.RespondTransaction(spend_bundle1)
@@ -74,7 +74,7 @@ async def test_fee_increase() -> None:
for i in range(300, 700):
i = uint32(i)
items = []
for _ in range(0, 20):
for _ in range(20):
fee = uint64(0)
included_height = uint32(random.randint(i - 60, i - 1))
cost = uint64(5000000)
@@ -1205,7 +1205,7 @@ async def test_total_mempool_fees() -> None:
async def test_create_bundle_from_mempool(reverse_tx_order: bool) -> None:
async def make_coin_spends(coins: list[Coin], *, high_fees: bool = True) -> list[CoinSpend]:
spends_list = []
for i in range(0, len(coins)):
for i in range(len(coins)):
coin_spend = make_spend(
coins[i],
IDENTITY_PUZZLE,
+1 -1
View File
@@ -69,7 +69,7 @@ async def main() -> None:
logger = create_logger(file=file)
async def f() -> None:
await asyncio.gather(*[tcp_echo_client(task_counter=f"{i}", logger=logger) for i in range(0, NUM_CLIENTS)])
await asyncio.gather(*[tcp_echo_client(task_counter=f"{i}", logger=logger) for i in range(NUM_CLIENTS)])
task = create_referenced_task(f())
try:
+1 -1
View File
@@ -275,7 +275,7 @@ async def test_standard_tx(benchmark_runner: BenchmarkRunner) -> None:
with benchmark_runner.assert_runtime(seconds=0.1):
total_cost = 0
for i in range(0, 1000):
for i in range(1000):
cost, _result = run_with_cost(puzzle_program, test_constants.MAX_BLOCK_COST_CLVM, solution_program)
total_cost += cost
+1 -1
View File
@@ -116,7 +116,7 @@ def test_db_validate_in_main_chain(invalid_in_chain: bool, default_config: dict[
make_block_table(conn)
prev = bytes32(DEFAULT_CONSTANTS.AGG_SIG_ME_ADDITIONAL_DATA)
for height in range(0, 100):
for height in range(100):
header_hash = rand_hash()
add_block(conn, header_hash, prev, height, True)
if height % 4 == 0:
@@ -397,7 +397,7 @@ async def test_farmer_get_harvester_plots_endpoints(
plots = harvester_plots
elif endpoint == FarmerRpcClient.get_harvester_plots_invalid:
invalid_paths = add_plot_directories("invalid", 3)
for dir_index, r in [(0, range(0, 6)), (1, range(6, 8)), (2, range(8, 13))]:
for dir_index, r in [(0, range(6)), (1, range(6, 8)), (2, range(8, 13))]:
plots += [str(invalid_paths[dir_index] / f"{i}.plot") for i in r]
for plot in plots:
with open(plot, "w"):
@@ -412,7 +412,7 @@ async def test_farmer_get_harvester_plots_endpoints(
elif endpoint == FarmerRpcClient.get_harvester_plots_duplicates:
duplicate_paths = add_plot_directories("duplicates", 2)
for dir_index, r in [(0, range(0, 3)), (1, range(3, 7))]:
for dir_index, r in [(0, range(3)), (1, range(3, 7))]:
for i in r:
plot_path = Path(harvester_plots[i]["filename"])
plots.append(str(duplicate_paths[dir_index] / plot_path.name))
+2 -2
View File
@@ -355,7 +355,7 @@ async def test_get_key(include_secrets: bool, get_temp_keyring: Keychain):
keychain: Keychain = get_temp_keyring
expected_keys = []
# Add 10 keys and validate the result `get_key` for each of them after each addition
for _ in range(0, 10):
for _ in range(10):
key_data = KeyData.generate()
mnemonic_str = key_data.mnemonic_str()
if not include_secrets:
@@ -385,7 +385,7 @@ async def test_get_keys(include_secrets: bool, get_temp_keyring: Keychain):
assert keychain.get_keys(include_secrets) == []
expected_keys = []
# Add 10 keys and validate the result of `get_keys` after each addition
for _ in range(0, 10):
for _ in range(10):
key_data = KeyData.generate()
mnemonic_str = key_data.mnemonic_str()
if not include_secrets:
+1 -1
View File
@@ -75,7 +75,7 @@ def child_writer_dispatch_with_readiness_check(
except LockfileError:
attempts -= 1
if attempts == 0:
raise LockfileError()
raise LockfileError
except Exception as e:
log.warning(
f"[pid:{os.getpid()}] caught exception in child_writer_dispatch_with_readiness_check: "
+5 -5
View File
@@ -41,7 +41,7 @@ def test_consumes_exception(
caplog: pytest.LogCaptureFixture,
) -> None:
with log_exceptions(log=logger, consume=True):
raise Exception()
raise Exception
def test_propagates_exception(
@@ -67,7 +67,7 @@ def test_passed_message_is_used(
caplog: pytest.LogCaptureFixture,
) -> None:
with log_exceptions(log=logger, consume=True, message=log_message):
raise Exception()
raise Exception
assert len(caplog.records) == 1, caplog.records
@@ -87,7 +87,7 @@ def test_specified_level_is_used(
) -> None:
caplog.set_level(min(all_levels.values()))
with log_exceptions(level=level, log=logger, consume=True):
raise Exception()
raise Exception
assert len(caplog.records) == 1, caplog.records
@@ -100,7 +100,7 @@ def test_traceback_is_logged(
caplog: pytest.LogCaptureFixture,
) -> None:
with log_exceptions(log=logger, consume=True, show_traceback=True):
raise Exception()
raise Exception
assert len(caplog.records) == 1, caplog.records
@@ -113,7 +113,7 @@ def test_traceback_is_not_logged(
caplog: pytest.LogCaptureFixture,
) -> None:
with log_exceptions(log=logger, consume=True, show_traceback=False):
raise Exception()
raise Exception
assert len(caplog.records) == 1, caplog.records
+1 -1
View File
@@ -800,7 +800,7 @@ class TestFromBytes:
class FailFromBytes:
@classmethod
def from_bytes(cls, b: bytes) -> FailFromBytes:
raise ValueError()
raise ValueError
def test_parse_str() -> None:
+1 -3
View File
@@ -24,8 +24,6 @@ if TYPE_CHECKING:
class UniqueError(Exception):
"""Used to uniquely trigger the exception path out of the context managers."""
pass
async def increment_counter(db_wrapper: DBWrapper2) -> None:
async with db_wrapper.writer_maybe_transaction() as connection:
@@ -427,7 +425,7 @@ async def test_cancelled_reader_does_not_cancel_writer() -> None:
with pytest.raises(UniqueError):
async with db_wrapper.reader() as _:
raise UniqueError()
raise UniqueError
assert await query_value(connection=writer) == 1
+3 -2
View File
@@ -13,6 +13,7 @@ from chia_rs import AugSchemeMPL, G1Element, G2Element, PrivateKey, ProofOfSpace
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint8, uint16, uint32, uint64
from pytest_mock import MockerFixture
from typing_extensions import Self
from yarl import URL
from chia import __version__
@@ -680,7 +681,7 @@ class DummyPoolResponse:
return json.dumps(json_dict)
async def __aenter__(self) -> DummyPoolResponse:
async def __aenter__(self) -> Self:
return self
async def __aexit__(
@@ -1004,7 +1005,7 @@ class DummyPoolInfoResponse:
return json.dumps(self.pool_info)
async def __aenter__(self) -> DummyPoolInfoResponse:
async def __aenter__(self) -> Self:
return self
async def __aexit__(
@@ -80,7 +80,7 @@ def test_steady_fee_pressure() -> None:
estimation = estimator.estimate_fee_rate(time_offset_seconds=time_offset_seconds * (height - start_from))
estimates_after.append(estimation)
block_estimates = [estimator.estimate_fee_rate_for_block(uint32(h + 1)) for h in range(0, 50)]
block_estimates = [estimator.estimate_fee_rate_for_block(uint32(h + 1)) for h in range(50)]
for idx, es_after in enumerate(estimates_after):
assert abs(es_after.mojos_per_clvm_cost - estimates_during[idx].mojos_per_clvm_cost) < 0.001
assert es_after.mojos_per_clvm_cost == block_estimates[idx].mojos_per_clvm_cost
+2 -2
View File
@@ -537,7 +537,7 @@ async def test_farmer_restart(environment: Environment) -> None:
# Load all directories for both harvesters
await add_and_validate_all_directories(env)
last_sync_ids: list[uint64] = []
for i in range(0, len(env.harvesters)):
for i in range(len(env.harvesters)):
last_sync_ids.append(env.harvesters[i].plot_sync_sender._last_sync_id)
# Stop the farmer and make sure both receivers get dropped and refreshing gets stopped on the harvesters
await env.split_farmer_service_manager.exit()
@@ -551,7 +551,7 @@ async def test_farmer_restart(environment: Environment) -> None:
assert len(env.farmer.plot_sync_receivers) == 2
# Do not use run_sync_test here, to have a more realistic test scenario just
# wait for the harvesters to be synced. The handshake should trigger re-sync.
for i in range(0, len(env.harvesters)):
for i in range(len(env.harvesters)):
harvester: Harvester = env.harvesters[i]
assert harvester.server is not None
receiver = env.farmer.plot_sync_receivers[harvester.server.node_id]
+2 -2
View File
@@ -137,7 +137,7 @@ async def run_sync_step(receiver: Receiver, sync_step: SyncStepData) -> None:
assert len(step_data) == 10
# Invoke batches of: 1, 2, 3, 4 items and validate the data against plot store before and after
indexes = [0, 1, 3, 6, 10]
for i in range(0, len(indexes) - 1):
for i in range(len(indexes) - 1):
plots_processed_before = receiver.current_sync().plots_processed
invoke_data = step_data[indexes[i] : indexes[i + 1]]
pre_function_validate(receiver, invoke_data, sync_step.state)
@@ -166,7 +166,7 @@ def plot_sync_setup(seeded_random: random.Random) -> tuple[Receiver, list[SyncSt
receiver = Receiver(harvester_connection, dummy_callback) # type:ignore[arg-type]
# Create example plot data
path_list = [str(x) for x in range(0, 40)]
path_list = [str(x) for x in range(40)]
plot_info_list = [
Plot(
filename=str(x),
+1 -1
View File
@@ -291,7 +291,7 @@ def create_example_plots(count: int, seeded_random: random.Random) -> list[PlotI
file_size=uint64(0),
time_modified=time.time(),
)
for x in range(0, count)
for x in range(count)
]
-2
View File
@@ -1,5 +1,3 @@
#!/usr/bin/env python3
from __future__ import annotations
import asyncio
+3 -3
View File
@@ -115,7 +115,7 @@ if __name__ == "__main__":
seeded_random = random.Random()
seeded_random.seed(a=0, version=2)
for i in range(0, 1000):
for i in range(1000):
private_key: PrivateKey = master_sk_to_wallet_sk(secret_key, uint32(i))
public_key = private_key.get_g1()
solution = wallet_tool.make_solution(
@@ -134,7 +134,7 @@ if __name__ == "__main__":
# Run Puzzle 1000 times
puzzle_start = time.time()
clvm_cost = 0
for i in range(0, 1000):
for i in range(1000):
cost_run, _ = puzzles[i].run_with_cost(INFINITE_COST, solutions[i])
clvm_cost += cost_run
@@ -152,7 +152,7 @@ if __name__ == "__main__":
# Run AggSig 1000 times
agg_sig_start = time.time()
agg_sig_cost = 0
for i in range(0, 1000):
for i in range(1000):
valid = AugSchemeMPL.verify(public_key, message, signature)
assert valid
agg_sig_cost += 20
+13 -12
View File
@@ -31,6 +31,7 @@ from aiohttp import web
from chia_rs import Coin
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint16, uint32, uint64
from typing_extensions import Self
import chia
import chia._tests
@@ -49,10 +50,10 @@ from chia.wallet.wallet_node import WalletNode
class GcMode(enum.Enum):
nothing = enum.auto
precollect = enum.auto
disable = enum.auto
enable = enum.auto
nothing = enum.auto()
precollect = enum.auto()
disable = enum.auto()
enable = enum.auto()
@contextlib.contextmanager
@@ -613,37 +614,37 @@ T_ComparableEnum = TypeVar("T_ComparableEnum", bound="ComparableEnum")
class ComparableEnum(Enum):
def __lt__(self: T_ComparableEnum, other: T_ComparableEnum) -> object:
def __lt__(self, other: Self) -> object:
if self.__class__ is not other.__class__:
return NotImplemented
return self.value.__lt__(other.value)
def __le__(self: T_ComparableEnum, other: T_ComparableEnum) -> object:
def __le__(self, other: Self) -> object:
if self.__class__ is not other.__class__:
return NotImplemented
return self.value.__le__(other.value)
def __eq__(self: T_ComparableEnum, other: object) -> bool:
def __eq__(self, other: object) -> bool:
if self.__class__ is not other.__class__:
return False
return cast(bool, self.value.__eq__(cast(T_ComparableEnum, other).value))
return cast(bool, self.value.__eq__(cast(Self, other).value))
def __ne__(self: T_ComparableEnum, other: object) -> bool:
def __ne__(self, other: object) -> bool:
if self.__class__ is not other.__class__:
return True
return cast(bool, self.value.__ne__(cast(T_ComparableEnum, other).value))
return cast(bool, self.value.__ne__(cast(Self, other).value))
def __gt__(self: T_ComparableEnum, other: T_ComparableEnum) -> object:
def __gt__(self, other: Self) -> object:
if self.__class__ is not other.__class__:
return NotImplemented
return self.value.__gt__(other.value)
def __ge__(self: T_ComparableEnum, other: T_ComparableEnum) -> object:
def __ge__(self, other: Self) -> object:
if self.__class__ is not other.__class__:
return NotImplemented
+5 -5
View File
@@ -250,10 +250,10 @@ async def setup_simulators_and_wallets_inner(
async with AsyncExitStack() as async_exit_stack:
bt_tools: list[BlockTools] = [
await create_block_tools_async(consensus_constants, keychain=keychain1, config_overrides=config_overrides)
for _ in range(0, simulator_count)
for _ in range(simulator_count)
]
if wallet_count > simulator_count:
for _ in range(0, wallet_count - simulator_count):
for _ in range(wallet_count - simulator_count):
bt_tools.append(
await create_block_tools_async(
consensus_constants, keychain=keychain2, config_overrides=config_overrides
@@ -273,7 +273,7 @@ async def setup_simulators_and_wallets_inner(
disable_capabilities=disable_capabilities,
)
)
for index in range(0, simulator_count)
for index in range(simulator_count)
]
wallets: list[WalletService] = [
@@ -289,7 +289,7 @@ async def setup_simulators_and_wallets_inner(
initial_num_public_keys=initial_num_public_keys,
)
)
for index in range(0, wallet_count)
for index in range(wallet_count)
]
yield bt_tools, simulators, wallets
@@ -329,7 +329,7 @@ async def setup_farmer_multi_harvester(
start_service=start_services,
)
)
for i in range(0, harvester_count)
for i in range(harvester_count)
]
yield harvester_services, farmer_service, block_tools
+5 -10
View File
@@ -7,7 +7,7 @@ from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional, TypeVar
from typing import Any, Optional
import anyio
from chia_rs import (
@@ -21,6 +21,7 @@ from chia_rs import (
)
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from typing_extensions import Self
from chia.consensus.block_rewards import calculate_base_farmer_reward, calculate_pool_reward
from chia.consensus.coinbase import create_farmer_coin, create_pool_coin
@@ -106,9 +107,6 @@ class SimFullBlock(Streamable):
height: uint32 # Note that height is not on a regular FullBlock
_T_SimBlockRecord = TypeVar("_T_SimBlockRecord", bound="SimBlockRecord")
@streamable
@dataclass(frozen=True)
class SimBlockRecord(Streamable):
@@ -121,7 +119,7 @@ class SimBlockRecord(Streamable):
prev_transaction_block_hash: bytes32
@classmethod
def create(cls: type[_T_SimBlockRecord], rci: list[Coin], height: uint32, timestamp: uint64) -> _T_SimBlockRecord:
def create(cls, rci: list[Coin], height: uint32, timestamp: uint64) -> Self:
prev_transaction_block_height = uint32(height - 1 if height > 0 else 0)
return cls(
rci,
@@ -143,9 +141,6 @@ class SimStore(Streamable):
blocks: list[SimFullBlock]
_T_SpendSim = TypeVar("_T_SpendSim", bound="SpendSim")
class SpendSim:
db_wrapper: DBWrapper2
coin_store: CoinStore
@@ -160,8 +155,8 @@ class SpendSim:
@classmethod
@contextlib.asynccontextmanager
async def managed(
cls: type[_T_SpendSim], db_path: Optional[Path] = None, defaults: ConsensusConstants = DEFAULT_CONSTANTS
) -> AsyncIterator[_T_SpendSim]:
cls, db_path: Optional[Path] = None, defaults: ConsensusConstants = DEFAULT_CONSTANTS
) -> AsyncIterator[Self]:
self = cls()
if db_path is None:
uri = f"file:db_{random.randint(0, 99999999)}?mode=memory&cache=shared"
+1 -1
View File
@@ -98,7 +98,7 @@ def test_empty_lists() -> None:
@pytest.mark.parametrize("collection_type", [list, set])
def test_valid(collection_type: type) -> None:
for k in range(1, 10):
test_collection = collection_type([x for x in range(0, k)])
test_collection = collection_type([x for x in range(k)])
for i in range(1, len(test_collection) + 1): # Test batch_size 1 to 11 (length + 1)
checked = 0
for batch in to_batches(test_collection, i):
+4 -4
View File
@@ -35,8 +35,8 @@ def test_constructor_invalid_inputs(page_size: int, page_size_limit: int, except
def test_page_count() -> None:
for page_size in range(1, 10):
for i in range(0, 10):
assert Paginator.create(range(0, i), page_size).page_count() == max(1, ceil(i / page_size))
for i in range(10):
assert Paginator.create(range(i), page_size).page_count() == max(1, ceil(i / page_size))
@pytest.mark.parametrize(
@@ -62,10 +62,10 @@ def test_page_count() -> None:
],
)
def test_get_page_valid(length: int, page: int, page_size: int, expected_data: list[int]) -> None:
assert Paginator.create(list(range(0, length)), page_size).get_page(page) == expected_data
assert Paginator.create(list(range(length)), page_size).get_page(page) == expected_data
@pytest.mark.parametrize("page", [-1000, -10, -1, 5, 10, 1000])
def test_get_page_invalid(page: int) -> None:
with pytest.raises(PageOutOfBoundsError):
Paginator.create(range(0, 17), 5).get_page(page)
Paginator.create(range(17), 5).get_page(page)
+2 -2
View File
@@ -128,7 +128,7 @@ class Request:
def __lt__(self, other: Request) -> bool:
if self.acquisition_order is None or other.acquisition_order is None:
raise RequestNotCompleteError()
raise RequestNotCompleteError
return self.acquisition_order < other.acquisition_order
@@ -152,7 +152,7 @@ class Request:
def before(self, other: Request) -> bool:
if self.release_order is None or other.acquisition_order is None:
raise RequestNotCompleteError()
raise RequestNotCompleteError
return self.release_order < other.acquisition_order
+3 -1
View File
@@ -11,6 +11,8 @@ from inspect import getframeinfo, stack
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Protocol, TypeVar, cast, final
from typing_extensions import Self
import chia
import chia._tests
from chia._tests import ether
@@ -37,7 +39,7 @@ class DataTypeProtocol(Protocol):
__match_args__: ClassVar[tuple[str, ...]] = ()
@classmethod
def unmarshal(cls: type[T], marshalled: dict[str, Any]) -> T: ...
def unmarshal(cls, marshalled: dict[str, Any]) -> Self: ...
def marshal(self) -> dict[str, Any]: ...
@@ -1715,7 +1715,7 @@ async def test_cat_melt_balance(wallet_environments: WalletTestFramework) -> Non
assert isinstance(cat_wallet, CATWallet)
# Let's test that continuing to melt this CAT results in the correct balance changes
for _ in range(0, 5):
for _ in range(5):
tx_amount -= 1
new_coin = (await cat_wallet.get_cat_spendable_coins())[0].coin
new_spend = unsigned_spend_bundle_for_spendable_cats(
+2 -2
View File
@@ -5,7 +5,7 @@ import unittest
from collections.abc import AsyncIterator, Awaitable
from contextlib import AsyncExitStack
from dataclasses import replace
from typing import Any, Callable, Literal, Optional
from typing import Any, Callable, Optional
import pytest
from chia_rs import (
@@ -64,7 +64,7 @@ async def ignore_block_validation(
if "standard_block_tools" in request.keywords:
return None
async def validate_block_body(*args: Any, **kwargs: Any) -> Literal[None]:
async def validate_block_body(*args: Any, **kwargs: Any) -> None:
return None
def create_wrapper(original_create: Any) -> Any:
@@ -38,7 +38,7 @@ NIL_PH = Program.to(None).get_tree_hash()
async def test_graftroot(cost_logger: CostLogger) -> None:
async with sim_and_client() as (sim, sim_client):
# Create the coin we're testing
all_values: list[bytes32] = [bytes32([x] * 32) for x in range(0, 100)]
all_values: list[bytes32] = [bytes32([x] * 32) for x in range(100)]
root, proofs = build_merkle_tree(all_values)
p2_conditions = Program.to((1, [[51, ACS_PH, 0]])) # An coin to create to make sure this hits the blockchain
desired_key_values = ((bytes32.zeros, bytes32([1] * 32)), (bytes32([7] * 32), bytes32([8] * 32)))
@@ -61,8 +61,8 @@ async def test_dl_offers(wallet_environments: WalletTestFramework) -> None:
await env_maker.change_balances({"dl": {"init": True}})
await env_taker.change_balances({"dl": {"init": True}})
MAKER_ROWS = [bytes32([i] * 32) for i in range(0, 10)]
TAKER_ROWS = [bytes32([i] * 32) for i in range(0, 10)]
MAKER_ROWS = [bytes32([i] * 32) for i in range(10)]
TAKER_ROWS = [bytes32([i] * 32) for i in range(10)]
maker_root, _ = build_merkle_tree(MAKER_ROWS)
taker_root, _ = build_merkle_tree(TAKER_ROWS)
@@ -364,7 +364,7 @@ async def test_dl_offer_cancellation(wallet_environments: WalletTestFramework) -
dl_wallet = await DataLayerWallet.create_new_dl_wallet(env_maker.wallet_state_manager)
await env_maker.change_balances({"dl": {"init": True}})
ROWS = [bytes32([i] * 32) for i in range(0, 10)]
ROWS = [bytes32([i] * 32) for i in range(10)]
root, _ = build_merkle_tree(ROWS)
async with dl_wallet.wallet_state_manager.new_action_scope(
@@ -535,7 +535,7 @@ async def test_multiple_dl_offers(wallet_environments: WalletTestFramework) -> N
await env_maker.change_balances({"dl": {"init": True}})
await env_taker.change_balances({"dl": {"init": True}})
MAKER_ROWS = [bytes32([i] * 32) for i in range(0, 10)]
MAKER_ROWS = [bytes32([i] * 32) for i in range(10)]
TAKER_ROWS = [bytes32([i] * 32) for i in range(10, 20)]
maker_root, _ = build_merkle_tree(MAKER_ROWS)
taker_root, _ = build_merkle_tree(TAKER_ROWS)
+2 -2
View File
@@ -1495,7 +1495,7 @@ async def test_did_auto_transfer_limit(
await full_node_api.farm_blocks_to_wallet(1, wallet)
# Check that we cap out at 10 DID Wallets automatically created upon transfer received
for i in range(0, 14):
for i in range(14):
async with wallet.wallet_state_manager.new_action_scope(DEFAULT_TX_CONFIG, push=True) as action_scope:
did_wallet_1: DIDWallet = await DIDWallet.create_new_did_wallet(
wallet_node.wallet_state_manager,
@@ -2389,7 +2389,7 @@ async def test_did_coin_records(wallet_environments: WalletTestFramework, use_al
]
)
for _ in range(0, 2):
for _ in range(2):
async with did_wallet.wallet_state_manager.new_action_scope(
wallet_environments.tx_config, push=True
) as action_scope:
+7 -7
View File
@@ -51,7 +51,7 @@ class TestWalletRpc:
await server_2.start_client(PeerInfo(self_hostname, full_node_server.get_port()), None)
await server_3.start_client(PeerInfo(self_hostname, full_node_server.get_port()), None)
for i in range(0, num_blocks):
for i in range(num_blocks):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph))
initial_funds = sum(
@@ -87,7 +87,7 @@ class TestWalletRpc:
merkle_root: bytes32 = bytes32.zeros
txs, launcher_id = await client.create_new_dl(merkle_root, uint64(50))
for i in range(0, 5):
for i in range(5):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros))
await asyncio.sleep(0.5)
@@ -105,7 +105,7 @@ class TestWalletRpc:
new_root: bytes32 = bytes32([1] * 32)
await client.dl_update_root(launcher_id, new_root, uint64(100))
for i in range(0, 5):
for i in range(5):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros))
await asyncio.sleep(0.5)
@@ -169,7 +169,7 @@ class TestWalletRpc:
txs, launcher_id_2 = await client.create_new_dl(merkle_root, uint64(50))
txs, launcher_id_3 = await client.create_new_dl(merkle_root, uint64(50))
for i in range(0, 5):
for i in range(5):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros))
await asyncio.sleep(0.5)
@@ -186,7 +186,7 @@ class TestWalletRpc:
uint64(0),
)
for i in range(0, 5):
for i in range(5):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros))
await asyncio.sleep(0.5)
@@ -210,7 +210,7 @@ class TestWalletRpc:
await full_node_api.wait_transaction_records_entered_mempool(txs)
height = full_node_api.full_node.blockchain.get_peak_height()
assert height is not None
for i in range(0, 5):
for i in range(5):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros))
await asyncio.sleep(0.5)
additions = []
@@ -228,7 +228,7 @@ class TestWalletRpc:
)
await time_out_assert(15, client.dl_get_mirrors, [mirror], launcher_id)
await client.dl_delete_mirror(mirror_coin.name(), fee=uint64(2000000000000))
for i in range(0, 5):
for i in range(5):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(bytes32.zeros))
await asyncio.sleep(0.5)
await time_out_assert(15, client.dl_get_mirrors, [], launcher_id)
+4 -4
View File
@@ -1437,7 +1437,7 @@ async def test_retry_store(
) -> list[CoinState]:
if flakiness_info.coin_state_flaky:
flakiness_info.coin_state_flaky = False
raise PeerRequestException()
raise PeerRequestException
else:
return await func(coin_names, peer, fork_height)
@@ -1470,7 +1470,7 @@ async def test_retry_store(
) -> list[CoinState]:
if flakiness_info.fetch_children_flaky:
flakiness_info.fetch_children_flaky = False
raise PeerRequestException()
raise PeerRequestException
else:
return await func(coin_name, peer, fork_height)
@@ -1482,7 +1482,7 @@ async def test_retry_store(
async def new_func(height: uint32) -> uint64:
if flakiness_info.get_timestamp_flaky:
flakiness_info.get_timestamp_flaky = False
raise PeerRequestException()
raise PeerRequestException
else:
return await func(height)
@@ -1494,7 +1494,7 @@ async def test_retry_store(
async def new_func(puzzle_hash: bytes32) -> Optional[WalletIdentifier]:
if flakiness_info.db_flaky:
flakiness_info.db_flaky = False
raise AIOSqliteError()
raise AIOSqliteError
else:
return await func(puzzle_hash)
+1 -1
View File
@@ -101,7 +101,7 @@ class TestCoinSelection:
async def test_coin_selection_zero_coins(self, a_hash: bytes32) -> None:
coin_list: list[WalletCoinRecord] = [
WalletCoinRecord(Coin(a_hash, a_hash, uint64(0)), uint32(1), uint32(1), False, True, WalletType(0), 1)
for _ in range(0, 100)
for _ in range(100)
]
result: set[Coin] = await select_coins(
+1 -1
View File
@@ -85,7 +85,7 @@ async def test_notifications(
await server_0.start_client(PeerInfo(self_hostname, full_node_server.get_port()), None)
await server_1.start_client(PeerInfo(self_hostname, full_node_server.get_port()), None)
for i in range(0, 2):
for i in range(2):
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph_1))
await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph_token))
await full_node_api.wait_for_wallets_synced(wallet_nodes=[wallet_node_1, wallet_node_2], timeout=30)
+2 -2
View File
@@ -44,11 +44,11 @@ def test_compute_spend_hints_and_additions() -> None:
with pytest.raises(ValidationError):
compute_spend_hints_and_additions(
make_spend(parent_coin.coin, Program.to(1), Program.to([[51, bytes32.zeros, 0] for _ in range(0, 10000)]))
make_spend(parent_coin.coin, Program.to(1), Program.to([[51, bytes32.zeros, 0] for _ in range(10000)]))
)
with pytest.raises(ValidationError):
compute_spend_hints_and_additions(
make_spend(parent_coin.coin, Program.to(1), Program.to([[50, bytes48.zeros, b""] for _ in range(0, 10000)]))
make_spend(parent_coin.coin, Program.to(1), Program.to([[50, bytes48.zeros, b""] for _ in range(10000)]))
)
+1 -1
View File
@@ -191,7 +191,7 @@ class TestWalletSimulator:
normal_puzhash = await action_scope.get_puzzle_hash(wallet_1.wallet_state_manager)
# Transfer to normal wallet
for _ in range(0, number_of_coins):
for _ in range(number_of_coins):
async with wallet.wallet_state_manager.new_action_scope(DEFAULT_TX_CONFIG, push=True) as action_scope:
await wallet.generate_signed_transaction(
[uint64(tx_amount)],
@@ -398,7 +398,7 @@ async def test_puzzle_hash_requests(wallet_environments: WalletTestFramework) ->
# Test transactionality
previous_result = None
for _ in range(0, wsm.initial_num_public_keys): # all currently unused
for _ in range(wsm.initial_num_public_keys): # all currently unused
previous_result = await wsm._get_unused_derivation_record(wsm.main_wallet.id(), previous_result=previous_result)
assert previous_result is not None
await previous_result.commit(wsm)
@@ -399,7 +399,7 @@ async def test_revocation_layer(cost_logger: CostLogger) -> None:
@pytest.mark.parametrize("num_proofs", range(1, 6))
async def test_proofs_checker(cost_logger: CostLogger, num_proofs: int) -> None:
async with sim_and_client() as (sim, client):
flags: list[str] = [str(i) for i in range(0, num_proofs)]
flags: list[str] = [str(i) for i in range(num_proofs)]
proofs_checker: ProofsChecker = ProofsChecker(flags)
# (mod (PROOFS_CHECKER proofs) (if (a PROOFS_CHECKER (list proofs)) () (x)))
+1 -1
View File
@@ -94,7 +94,7 @@ class WalletBlockTools(BlockTools):
latest_block = None
last_timestamp = uint64((int(time.time()) if genesis_timestamp is None else genesis_timestamp) - 20)
for _ in range(0, num_blocks):
for _ in range(num_blocks):
additions = []
removals = []
block_generator: Optional[BlockGenerator] = None
+1 -1
View File
@@ -138,7 +138,7 @@ def prepare_submission_cmd(ctx: click.Context) -> None:
user_input = input("Select the version you want to prepare for submission: ")
try:
if int(user_input) <= 0:
raise IndexError()
raise IndexError
prepare_result = available_results[int(user_input) - 1]
except IndexError:
raise click.ClickException(f"Invalid choice: {user_input}")
+1 -1
View File
@@ -81,7 +81,7 @@ def cli(
if Keychain.master_passphrase_is_valid(passphrase):
cache_passphrase(passphrase)
else:
raise KeychainCurrentPassphraseIsInvalid()
raise KeychainCurrentPassphraseIsInvalid
except KeychainCurrentPassphraseIsInvalid:
if Path(passphrase_file.name).is_file():
print(f'Invalid passphrase found in "{passphrase_file.name}"')
+12 -12
View File
@@ -45,11 +45,11 @@ ChiaCommand = Union[SyncChiaCommand, AsyncChiaCommand]
def option(*param_decls: str, **kwargs: Any) -> Any:
if sys.version_info < (3, 10): # versions < 3.10 don't know about kw_only and they complain about lacks of defaults
if sys.version_info >= (3, 10):
default_default = MISSING
else: # versions < 3.10 don't know about kw_only and they complain about lacks of defaults
# Can't get coverage on this because we only test on one version
default_default = None # pragma: no cover
else:
default_default = MISSING
return field(
metadata=dict(
@@ -270,16 +270,16 @@ def chia_command(
def _chia_command(cls: type[ChiaCommand]) -> type[ChiaCommand]:
# The type ignores here are largely due to the fact that the class information is not preserved after being
# passed through the dataclass wrapper. Not sure what to do about this right now.
if sys.version_info < (3, 10): # pragma: no cover
# stuff below 3.10 doesn't know about kw_only
wrapped_cls: type[ChiaCommand] = dataclass(
frozen=True,
)(cls)
else:
if sys.version_info >= (3, 10):
wrapped_cls: type[ChiaCommand] = dataclass(
frozen=True,
kw_only=True,
)(cls)
else: # pragma: no cover
# stuff below 3.10 doesn't know about kw_only
wrapped_cls: type[ChiaCommand] = dataclass(
frozen=True,
)(cls)
metadata = Metadata(
command=click.command(
@@ -316,9 +316,9 @@ def get_chia_command_metadata(cls: type[ChiaCommand]) -> Metadata:
@dataclass_transform(frozen_default=True)
def command_helper(cls: type[Any]) -> type[Any]:
if sys.version_info < (3, 10): # stuff below 3.10 doesn't support kw_only
new_cls = dataclass(frozen=True)(cls) # pragma: no cover
else:
if sys.version_info >= (3, 10):
new_cls = dataclass(frozen=True, kw_only=True)(cls)
else: # stuff below 3.10 doesn't support kw_only
new_cls = dataclass(frozen=True)(cls) # pragma: no cover
setattr(new_cls, COMMAND_HELPER_ATTRIBUTE_NAME, True)
return new_cls
+1 -1
View File
@@ -267,7 +267,7 @@ def cli_confirm(input_message: str, abort_message: str = "Did not confirm. Abort
response = input(input_message).lower()
if response not in {"y", "yes"}:
print(abort_message)
raise click.Abort()
raise click.Abort
def coin_selection_args(func: Callable[..., None]) -> Callable[..., None]:
+1 -1
View File
@@ -92,7 +92,7 @@ def print_coins(
return
num_per_screen = 5 if paginate else len(coins)
for i in range(0, len(coins), num_per_screen):
for j in range(0, num_per_screen):
for j in range(num_per_screen):
if i + j >= len(coins):
break
coin, conf_height = coins[i + j]
-2
View File
@@ -13,8 +13,6 @@ from chia_rs.sized_ints import uint64
from chia.cmds import options
from chia.cmds.param_types import Bytes32ParamType
_T = TypeVar("_T")
FC = TypeVar("FC", bound=Union[Callable[..., Any], click.Command])
logger = logging.getLogger(__name__)
+4 -4
View File
@@ -8,7 +8,7 @@ import uuid
import webbrowser
from collections.abc import Sequence
from pathlib import Path
from typing import Callable, ClassVar, Literal, Optional, Union, overload
from typing import Callable, ClassVar, Literal, Optional, overload
import anyio
import click
@@ -21,9 +21,9 @@ class UnexpectedFormError(Exception):
pass
Oses = Union[Literal["linux"], Literal["macos-arm"], Literal["macos-intel"], Literal["windows"]]
Method = Union[Literal["GET"], Literal["POST"]]
Per = Union[Literal["directory"], Literal["file"]]
Oses = Literal["linux", "macos-arm", "macos-intel", "windows"]
Method = Literal["GET", "POST"]
Per = Literal["directory", "file"]
all_oses: Sequence[Oses] = ("linux", "macos-arm", "macos-intel", "windows")
+2 -2
View File
@@ -379,11 +379,11 @@ def _resolve_fingerprint_and_sk(
if non_observer_derivation and resolved_sk is None:
print("Could not resolve private key for non-observer derivation")
raise ResolutionError()
raise ResolutionError
if reolved_fp is None:
print("A fingerprint of a root key to derive from is required")
raise ResolutionError()
raise ResolutionError
return reolved_fp, resolved_sk
+1 -1
View File
@@ -131,7 +131,7 @@ def status_cmd(ctx: click.Context, json_output: bool) -> None:
status = "ACTIVE"
try:
if not get_routes(service, config, root_path=root_path, quiet=True)["success"]:
raise Exception()
raise Exception
except Exception:
status = "INACTIVE"
status_data[service] = status
+1 -1
View File
@@ -363,7 +363,7 @@ async def print_coin_records(
num_per_screen = 5 if paginate else len(coin_records)
# ripped from cmds/wallet_funcs.
for i in range(0, len(coin_records), num_per_screen):
for j in range(0, num_per_screen):
for j in range(num_per_screen):
if i + j >= len(coin_records):
break
print_coin_record(
+1 -1
View File
@@ -234,7 +234,7 @@ async def get_transactions(
skipped = 0
num_per_screen = 5 if paginate else len(txs)
for i in range(0, len(txs), num_per_screen):
for j in range(0, num_per_screen):
for j in range(num_per_screen):
if i + j + skipped >= len(txs):
break
coin_record: Optional[dict[str, Any]] = None
+1 -1
View File
@@ -125,4 +125,4 @@ def calculate_iterations_quality(
)
return max(iters, uint64(1))
else:
raise NotImplementedError()
raise NotImplementedError
+5 -5
View File
@@ -97,7 +97,7 @@ class KeychainProxy(DaemonProxy):
self.log.debug(f"Sending request to keychain command: {request['command']} from {request['origin']}.")
return await super()._get(request)
except asyncio.TimeoutError:
raise KeychainProxyConnectionTimeout()
raise KeychainProxyConnectionTimeout
async def start(self, wait_for_start: bool = False) -> None:
self.keychain_connection_task = create_referenced_task(self.connect_to_keychain())
@@ -156,11 +156,11 @@ class KeychainProxy(DaemonProxy):
if error:
error_details = response["data"].get("error_details", {})
if error == KEYCHAIN_ERR_LOCKED:
raise KeychainIsLocked()
raise KeychainIsLocked
elif error == KEYCHAIN_ERR_NO_KEYS:
raise KeychainIsEmpty()
raise KeychainIsEmpty
elif error == KEYCHAIN_ERR_KEY_NOT_FOUND:
raise KeychainKeyNotFound()
raise KeychainKeyNotFound
elif error == KEYCHAIN_ERR_MALFORMED_REQUEST:
message = error_details.get("message", "")
raise KeychainMalformedRequest(message)
@@ -356,7 +356,7 @@ class KeychainProxy(DaemonProxy):
if self.use_local_keychain():
keys = self.keychain.get_keys(include_secrets=private)
if len(keys) == 0:
raise KeychainIsEmpty()
raise KeychainIsEmpty
else:
selected_key = keys[0]
if fingerprint is not None:
+1 -1
View File
@@ -392,7 +392,7 @@ class Root:
}
node_type_to_class: dict[NodeType, Union[type[InternalNode], type[TerminalNode]]] = {
node_type_to_class: dict[NodeType, type[Union[InternalNode, TerminalNode]]] = {
NodeType.INTERNAL: InternalNode,
NodeType.TERMINAL: TerminalNode,
}
+3 -4
View File
@@ -1,11 +1,12 @@
from __future__ import annotations
import dataclasses
from typing import Optional, TypeVar, Union
from typing import Optional, Union
from aiosqlite import Row
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint16, uint32, uint64
from typing_extensions import Self
from chia.data_layer.data_layer_wallet import Mirror
from chia.data_layer.singleton_record import SingletonRecord
@@ -13,8 +14,6 @@ from chia.types.blockchain_format.coin import Coin
from chia.util.db_wrapper import DBWrapper2, execute_fetchone
from chia.wallet.lineage_proof import LineageProof
_T_DataLayerStore = TypeVar("_T_DataLayerStore", bound="DataLayerStore")
def _row_to_singleton_record(row: Row) -> SingletonRecord:
return SingletonRecord(
@@ -49,7 +48,7 @@ class DataLayerStore:
db_wrapper: DBWrapper2
@classmethod
async def create(cls: type[_T_DataLayerStore], db_wrapper: DBWrapper2) -> _T_DataLayerStore:
async def create(cls, db_wrapper: DBWrapper2) -> Self:
self = cls()
self.db_wrapper = db_wrapper
-1
View File
@@ -384,7 +384,6 @@ def read_store_ids_from_config(config: dict[str, Any]) -> list[StoreConfig]:
else:
bad_store_id = "<missing>"
log.info(f"Ignoring invalid store id: {bad_store_id}: {type(e).__name__} {e}")
pass
return stores
+1 -1
View File
@@ -226,7 +226,7 @@ class Farmer:
else:
self.keychain_proxy = await connect_to_keychain_and_validate(self._root_path, self.log)
if not self.keychain_proxy:
raise KeychainProxyConnectionFailure()
raise KeychainProxyConnectionFailure
return self.keychain_proxy
async def get_all_private_keys(self) -> list[tuple[PrivateKey, bytes]]:
-2
View File
@@ -94,7 +94,6 @@ class BlockHeightMap:
except Exception as e:
# it's OK if this file doesn't exist, we can rebuild it
log.info(f"Failed to load height-to-hash: {e}")
pass
try:
async with aiofiles.open(self.__ses_filename, "rb") as f:
@@ -102,7 +101,6 @@ class BlockHeightMap:
except Exception as e:
# it's OK if this file doesn't exist, we can rebuild it
log.info(f"Failed to load sub-epoch-summaries: {e}")
pass
peak: bytes32 = row[0]
prev_hash: bytes32 = row[1]
@@ -11,32 +11,24 @@ from chia.types.fee_rate import FeeRateV2
class FeeEstimatorInterface(Protocol):
def new_block_height(self, block_height: uint32) -> None:
"""Called immediately when block height changes. Can be called multiple times before `new_block`"""
pass
def new_block(self, block_info: FeeBlockInfo) -> None:
"""A new transaction block has been added to the blockchain"""
pass
def add_mempool_item(self, mempool_item_info: FeeMempoolInfo, mempool_item: MempoolItemInfo) -> None:
"""A MempoolItem (transaction and associated info) has been added to the mempool"""
pass
def remove_mempool_item(self, mempool_info: FeeMempoolInfo, mempool_item: MempoolItemInfo) -> None:
"""A MempoolItem (transaction and associated info) has been removed from the mempool"""
pass
def estimate_fee_rate(self, *, time_offset_seconds: int) -> FeeRateV2:
"""time_offset_seconds: number of seconds into the future for which to estimate fee"""
pass
def mempool_size(self) -> CLVMCost:
"""Report last seen mempool size"""
pass
def mempool_max_size(self) -> CLVMCost:
"""Report current mempool max "size" (i.e. CLVM cost)"""
pass
def get_mempool_info(self) -> FeeMempoolInfo:
"""Report Mempool current configuration and state"""
pass
+25 -25
View File
@@ -107,8 +107,8 @@ class FeeStat: # TxConfirmStats
my_type: str,
):
self.buckets = buckets
self.confirmed_average = [[] for _ in range(0, max_periods)]
self.failed_average = [[] for _ in range(0, max_periods)]
self.confirmed_average = [[] for _ in range(max_periods)]
self.failed_average = [[] for _ in range(max_periods)]
self.decay = decay
self.scale = scale
self.max_confirms = self.scale * len(self.confirmed_average)
@@ -117,18 +117,18 @@ class FeeStat: # TxConfirmStats
self.type = my_type
self.max_periods = max_periods
for i in range(0, max_periods):
self.confirmed_average[i] = [0 for _ in range(0, len(buckets))]
self.failed_average[i] = [0 for _ in range(0, len(buckets))]
for i in range(max_periods):
self.confirmed_average[i] = [0 for _ in range(len(buckets))]
self.failed_average[i] = [0 for _ in range(len(buckets))]
self.tx_ct_avg = [0 for _ in range(0, len(buckets))]
self.m_fee_rate_avg = [0 for _ in range(0, len(buckets))]
self.tx_ct_avg = [0 for _ in range(len(buckets))]
self.m_fee_rate_avg = [0 for _ in range(len(buckets))]
self.unconfirmed_txs = [[] for _ in range(0, self.max_confirms)]
for i in range(0, self.max_confirms):
self.unconfirmed_txs[i] = [0 for _ in range(0, len(buckets))]
self.unconfirmed_txs = [[] for _ in range(self.max_confirms)]
for i in range(self.max_confirms):
self.unconfirmed_txs[i] = [0 for _ in range(len(buckets))]
self.old_unconfirmed_txs = [0 for _ in range(0, len(buckets))]
self.old_unconfirmed_txs = [0 for _ in range(len(buckets))]
def tx_confirmed(self, blocks_to_confirm: int, item: MempoolItemInfo) -> None:
if blocks_to_confirm < 1:
@@ -147,8 +147,8 @@ class FeeStat: # TxConfirmStats
self.m_fee_rate_avg[bucket_index] += fee_rate
def update_moving_averages(self) -> None:
for j in range(0, len(self.buckets)):
for i in range(0, len(self.confirmed_average)):
for j in range(len(self.buckets)):
for i in range(len(self.confirmed_average)):
self.confirmed_average[i][j] *= self.decay
self.failed_average[i][j] *= self.decay
@@ -156,7 +156,7 @@ class FeeStat: # TxConfirmStats
self.m_fee_rate_avg[j] *= self.decay
def clear_current(self, block_height: uint32) -> None:
for i in range(0, len(self.buckets)):
for i in range(len(self.buckets)):
self.old_unconfirmed_txs[i] += self.unconfirmed_txs[block_height % len(self.unconfirmed_txs)][i]
self.unconfirmed_txs[block_height % len(self.unconfirmed_txs)][i] = 0
@@ -186,7 +186,7 @@ class FeeStat: # TxConfirmStats
if block_ago >= self.scale:
periods_ago = block_ago / self.scale
for i in range(0, len(self.failed_average)):
for i in range(len(self.failed_average)):
if i >= periods_ago:
break
self.failed_average[i][bucket_index] += 1
@@ -196,38 +196,38 @@ class FeeStat: # TxConfirmStats
str_confirmed_average: list[list[str]] = []
str_failed_average: list[list[str]] = []
str_m_fee_rate_avg: list[str] = []
for i in range(0, self.max_periods):
for i in range(self.max_periods):
str_i_list_conf = []
for j in range(0, len(self.confirmed_average[i])):
for j in range(len(self.confirmed_average[i])):
str_i_list_conf.append(float.hex(float(self.confirmed_average[i][j])))
str_confirmed_average.append(str_i_list_conf)
str_i_list_fail = []
for j in range(0, len(self.failed_average[i])):
for j in range(len(self.failed_average[i])):
str_i_list_fail.append(float.hex(float(self.failed_average[i][j])))
str_failed_average.append(str_i_list_fail)
for i in range(0, len(self.tx_ct_avg)):
for i in range(len(self.tx_ct_avg)):
str_tx_ct_abg.append(float.hex(float(self.tx_ct_avg[i])))
for i in range(0, len(self.m_fee_rate_avg)):
for i in range(len(self.m_fee_rate_avg)):
str_m_fee_rate_avg.append(float.hex(float(self.m_fee_rate_avg[i])))
return FeeStatBackup(self.type, str_tx_ct_abg, str_confirmed_average, str_failed_average, str_m_fee_rate_avg)
def import_backup(self, backup: FeeStatBackup) -> None:
for i in range(0, self.max_periods):
for j in range(0, len(self.confirmed_average[i])):
for i in range(self.max_periods):
for j in range(len(self.confirmed_average[i])):
self.confirmed_average[i][j] = float.fromhex(backup.confirmed_average[i][j])
for j in range(0, len(self.failed_average[i])):
for j in range(len(self.failed_average[i])):
self.failed_average[i][j] = float.fromhex(backup.failed_average[i][j])
for i in range(0, len(self.tx_ct_avg)):
for i in range(len(self.tx_ct_avg)):
self.tx_ct_avg[i] = float.fromhex(backup.tx_ct_avg[i])
for i in range(0, len(self.m_fee_rate_avg)):
for i in range(len(self.m_fee_rate_avg)):
self.m_fee_rate_avg[i] = float.fromhex(backup.m_fee_rate_avg[i])
# See TxConfirmStats::EstimateMedianVal in https://github.com/bitcoin/bitcoin/blob/master/src/policy/fees.cpp
+2 -2
View File
@@ -2154,7 +2154,7 @@ class FullNode:
added = AddBlockResult.DISCONNECTED_BLOCK
error_code: Optional[Err] = Err.INVALID_PREV_BLOCK_HASH
elif Err(pre_validation_result.error) == Err.TIMESTAMP_TOO_FAR_IN_FUTURE:
raise TimestampError()
raise TimestampError
else:
raise ValueError(
f"Failed to validate block {header_hash} height "
@@ -2369,7 +2369,7 @@ class FullNode:
_, header_error = await self.blockchain.validate_unfinished_block_header(block)
if header_error is not None:
if header_error == Err.TIMESTAMP_TOO_FAR_IN_FUTURE:
raise TimestampError()
raise TimestampError
else:
raise ConsensusError(header_error)
validate_time = time.monotonic() - start_header_time
+1 -1
View File
@@ -301,7 +301,7 @@ class FullNodeAPI:
if len(tips) > 4:
# Remove old from cache
for i in range(0, 4):
for i in range(4):
self.full_node.pow_creation.pop(tips[i])
if wp is None:
+1 -1
View File
@@ -882,7 +882,7 @@ class FullNodeStore:
if cc_hash == challenge_hash:
found_rc_hash = False
for i in range(0, index):
for i in range(index):
sp: Optional[SignagePoint] = sps[i]
if sp is not None and sp.rc_vdf is not None and sp.rc_vdf.challenge == last_rc_infusion:
found_rc_hash = True
+4 -4
View File
@@ -1149,7 +1149,7 @@ def sub_slot_data_vdf_input(
if is_overflow and new_sub_slot:
if sub_slot_idx >= 2:
if sub_slots[sub_slot_idx - 2].cc_slot_end_info is None:
for ssd_idx in reversed(range(0, sub_slot_idx - 1)):
for ssd_idx in reversed(range(sub_slot_idx - 1)):
ssd = sub_slots[ssd_idx]
if ssd.cc_slot_end_info is not None:
ssd = sub_slots[ssd_idx + 1]
@@ -1164,7 +1164,7 @@ def sub_slot_data_vdf_input(
return cc_input
elif not is_overflow and not new_sub_slot:
for ssd_idx in reversed(range(0, sub_slot_idx)):
for ssd_idx in reversed(range(sub_slot_idx)):
ssd = sub_slots[ssd_idx]
if ssd.cc_slot_end_info is not None:
ssd = sub_slots[ssd_idx + 1]
@@ -1181,7 +1181,7 @@ def sub_slot_data_vdf_input(
elif not new_sub_slot and is_overflow:
slots_seen = 0
for ssd_idx in reversed(range(0, sub_slot_idx)):
for ssd_idx in reversed(range(sub_slot_idx)):
ssd = sub_slots[ssd_idx]
if ssd.cc_slot_end_info is not None:
slots_seen += 1
@@ -1474,7 +1474,7 @@ def __get_rc_sub_slot(
def __get_cc_sub_slot(sub_slots: list[SubSlotData], idx: int, ses: Optional[SubEpochSummary]) -> ChallengeChainSubSlot:
sub_slot: Optional[SubSlotData] = None
for i in reversed(range(0, idx)):
for i in reversed(range(idx)):
sub_slot = sub_slots[i]
if sub_slot.cc_slot_end_info is not None:
break
+1 -1
View File
@@ -125,7 +125,7 @@ class Sender:
if not self._plot_manager.initial_refresh() or self._sync_id != 0:
self._reset()
else:
raise AlreadyStartedError()
raise AlreadyStartedError
def stop(self) -> None:
self._stop_requested = True
+3 -6
View File
@@ -1,11 +1,8 @@
from __future__ import annotations
from typing import Any, TypeVar
from typing_extensions import Protocol
_T = TypeVar("_T")
from typing import Any
from typing_extensions import Protocol, Self
# If accepted for general use then this should be moved to a common location
# and probably implemented by the framework instead of manual decoration.
@@ -13,7 +10,7 @@ _T = TypeVar("_T")
class MarshallableProtocol(Protocol):
@classmethod
def unmarshal(cls: type[_T], marshalled: dict[str, Any]) -> _T: ...
def unmarshal(cls, marshalled: dict[str, Any]) -> Self: ...
def marshal(self) -> dict[str, Any]: ...
+6 -7
View File
@@ -7,11 +7,12 @@ from contextlib import asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from ssl import SSLContext
from typing import Any, Optional, TypeVar
from typing import Any, Optional
import aiohttp
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint16
from typing_extensions import Self
from chia.protocols.outbound_message import NodeType
from chia.server.server import ssl_context_for_client
@@ -19,8 +20,6 @@ from chia.server.ssl_context import private_ssl_ca_paths
from chia.util.byte_types import hexstr_to_bytes
from chia.util.task_referencer import create_referenced_task
_T_RpcClient = TypeVar("_T_RpcClient", bound="RpcClient")
# It would be better to not inherit from ValueError. This is being done to separate
# the possibility to identify these errors in new code from having to review and
@@ -50,12 +49,12 @@ class RpcClient:
@classmethod
async def create(
cls: type[_T_RpcClient],
cls,
self_hostname: str,
port: uint16,
root_path: Optional[Path],
net_config: Optional[dict[str, Any]],
) -> _T_RpcClient:
) -> Self:
if (root_path is not None) != (net_config is not None):
raise ValueError("Either both or neither of root_path and net_config must be provided")
@@ -89,12 +88,12 @@ class RpcClient:
@classmethod
@asynccontextmanager
async def create_as_context(
cls: type[_T_RpcClient],
cls,
self_hostname: str,
port: uint16,
root_path: Optional[Path] = None,
net_config: Optional[dict[str, Any]] = None,
) -> AsyncIterator[_T_RpcClient]:
) -> AsyncIterator[Self]:
self = await cls.create(
self_hostname=self_hostname,
port=port,
+1 -1
View File
@@ -303,7 +303,7 @@ class RpcServer(Generic[_T_RpcApiProtocol]):
async def close_connection(self, request: dict[str, Any]) -> EndpointResult:
node_id = hexstr_to_bytes(request["node_id"])
if self.rpc_api.service.server is None:
raise web.HTTPInternalServerError()
raise web.HTTPInternalServerError
connections_to_close = [c for c in self.rpc_api.service.server.get_connections() if c.peer_node_id == node_id]
if len(connections_to_close) == 0:
raise ValueError(f"Connection with node_id {node_id.hex()} does not exist")
+8 -16
View File
@@ -2,12 +2,12 @@ from __future__ import annotations
import sys
from dataclasses import dataclass, field
from typing import Any, Optional, TypeVar, final
from typing import Any, Optional, final
from chia_rs import G1Element, G2Element, PrivateKey
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint16, uint32, uint64
from typing_extensions import dataclass_transform
from typing_extensions import Self, dataclass_transform
from chia.util.byte_types import hexstr_to_bytes
from chia.util.streamable import Streamable, streamable
@@ -28,15 +28,13 @@ from chia.wallet.util.tx_config import TXConfig
from chia.wallet.vc_wallet.vc_store import VCProofs, VCRecord
from chia.wallet.wallet_spend_bundle import WalletSpendBundle
_T_OfferEndpointResponse = TypeVar("_T_OfferEndpointResponse", bound="_OfferEndpointResponse")
@dataclass_transform(frozen_default=True, kw_only_default=True)
def kw_only_dataclass(cls: type[Any]) -> type[Any]:
if sys.version_info < (3, 10):
return dataclass(frozen=True)(cls) # pragma: no cover
else:
if sys.version_info >= (3, 10):
return dataclass(frozen=True, kw_only=True)(cls)
else:
return dataclass(frozen=True)(cls) # pragma: no cover
def default_raise() -> Any: # pragma: no cover
@@ -404,13 +402,10 @@ class VCProofsRPC(Streamable):
return VCProofs({key: value for key, value in self.key_value_pairs})
@classmethod
def from_vc_proofs(cls: type[_T_VCProofsRPC], vc_proofs: VCProofs) -> _T_VCProofsRPC:
def from_vc_proofs(cls, vc_proofs: VCProofs) -> Self:
return cls([(key, value) for key, value in vc_proofs.key_value_pairs.items()])
_T_VCProofsRPC = TypeVar("_T_VCProofsRPC", bound=VCProofsRPC)
# utility for VCGetListResponse
@streamable
@dataclass(frozen=True)
@@ -471,13 +466,10 @@ class VCAddProofs(VCProofsRPC):
return {"proofs": self.to_vc_proofs().key_value_pairs}
@classmethod
def from_json_dict(cls: type[_T_VCAddProofs], json_dict: dict[str, Any]) -> _T_VCAddProofs:
def from_json_dict(cls, json_dict: dict[str, Any]) -> Self:
return cls([(key, value) for key, value in json_dict["proofs"].items()])
_T_VCAddProofs = TypeVar("_T_VCAddProofs", bound=VCAddProofs)
@streamable
@dataclass(frozen=True)
class VCGetProofsForRoot(Streamable):
@@ -771,7 +763,7 @@ class _OfferEndpointResponse(TransactionEndpointResponse):
trade_record: TradeRecord
@classmethod
def from_json_dict(cls: type[_T_OfferEndpointResponse], json_dict: dict[str, Any]) -> _T_OfferEndpointResponse:
def from_json_dict(cls, json_dict: dict[str, Any]) -> Self:
tx_endpoint: TransactionEndpointResponse = json_deserialize_with_clvm_streamable(
json_dict, TransactionEndpointResponse
)
+2
View File
@@ -35,6 +35,8 @@ DnsCallback = Callable[[DNSRecord], Awaitable[DNSRecord]]
class DomainName(str):
__slots__ = ()
def __getattr__(self, item: str) -> DomainName:
return DomainName(f"{item}.{self}") # DomainName.NS becomes DomainName("NS.DomainName")
+1 -1
View File
@@ -313,7 +313,7 @@ class AddressManager:
# deserialize new_table
new_table_count = uint32.parse(data)
new_table_nodes: list[tuple[uint64, uint64]] = []
for i in range(0, new_table_count):
for i in range(new_table_count):
node_id = uint64.parse(data)
bucket = uint64.parse(data)
new_table_nodes.append((node_id, bucket))
+2 -2
View File
@@ -824,7 +824,7 @@ class BlockTools:
num_empty_slots_added += 1
else:
# Loop over every signage point (Except for the last ones, which are used for overflows)
for signage_point_index in range(0, constants.NUM_SPS_SUB_SLOT - constants.NUM_SP_INTERVALS_EXTRA):
for signage_point_index in range(constants.NUM_SPS_SUB_SLOT - constants.NUM_SP_INTERVALS_EXTRA):
curr = latest_block
while curr.total_iters > sub_slot_start_total_iters + calculate_sp_iters(
constants, sub_slot_iters, uint8(signage_point_index)
@@ -1310,7 +1310,7 @@ class BlockTools:
# Keep trying until we get a good proof of space that also passes sp filter
while True:
cc_challenge, rc_challenge = get_challenges(constants, {}, finished_sub_slots, None)
for signage_point_index in range(0, constants.NUM_SPS_SUB_SLOT):
for signage_point_index in range(constants.NUM_SPS_SUB_SLOT):
signage_point: SignagePoint = get_signage_point(
constants,
BlockCache({}),
-1
View File
@@ -317,7 +317,6 @@ async def setup_wallet_node(
# filesystem operations are async on windows
# [WinError 32] The process cannot access the file because it is
# being used by another process
pass
keychain.delete_all_keys()
+6 -5
View File
@@ -10,6 +10,7 @@ from clvm.CLVMObject import CLVMStorage
from clvm.EvalError import EvalError
from clvm.serialize import sexp_from_stream, sexp_to_stream
from clvm.SExp import SExp
from typing_extensions import Self
from chia.types.blockchain_format.serialized_program import SerializedProgram
from chia.types.blockchain_format.tree_hash import sha256_treehash
@@ -30,14 +31,14 @@ class Program(SExp):
"""
@classmethod
def parse(cls: type[T_Program], f) -> T_Program:
def parse(cls, f) -> Self:
return sexp_from_stream(f, cls.to)
def stream(self, f) -> None:
sexp_to_stream(self, f)
@classmethod
def from_serialized(cls: type[T_Program], prg: SerializedProgram) -> T_Program:
def from_serialized(cls, prg: SerializedProgram) -> Self:
"""
Convert the SerializedProgram to a Program object.
"""
@@ -50,7 +51,7 @@ class Program(SExp):
return SerializedProgram.from_bytes(bytes(self))
@classmethod
def from_bytes(cls: type[T_Program], blob: bytes) -> T_Program:
def from_bytes(cls, blob: bytes) -> Self:
# this runs the program "1", which just returns the first argument.
# the first argument is the buffer we want to parse. This effectively
# leverages the rust parser and LazyNode, making it a lot faster to
@@ -64,7 +65,7 @@ class Program(SExp):
return cls.to(ret)
@classmethod
def fromhex(cls: type[T_Program], hexstr: str) -> T_Program:
def fromhex(cls, hexstr: str) -> Self:
return cls.from_bytes(hexstr_to_bytes(hexstr))
@classmethod
@@ -104,7 +105,7 @@ class Program(SExp):
raise ValueError(f"`at` got illegal character `{c}`. Only `f` & `r` allowed")
return v
def replace(self: T_Program, **kwargs: Any) -> T_Program:
def replace(self, **kwargs: Any) -> Self:
"""
Create a new program replacing the given paths (using `at` syntax).
Example:
@@ -23,7 +23,7 @@ def get_plot_id(pos: ProofOfSpace) -> bytes32:
def validate_proof_v2(plot_id: bytes32, size: uint8, challenge: bytes32, proof: bytes) -> Optional[bytes]:
raise NotImplementedError()
raise NotImplementedError
def verify_and_get_quality_string(
@@ -94,7 +94,7 @@ def verify_and_get_quality_string_v2(
*,
height: uint32,
) -> Optional[bytes32]:
raise NotImplementedError()
raise NotImplementedError
def passes_plot_filter(
+2 -1
View File
@@ -6,6 +6,7 @@ from dataclasses import dataclass, field
from typing import Callable, Generic, Optional, Protocol, TypeVar
import aiosqlite
from typing_extensions import Self
from chia.util.db_wrapper import DBWrapper2, execute_fetchone
@@ -80,7 +81,7 @@ class SideEffects(Protocol):
def __bytes__(self) -> bytes: ...
@classmethod
def from_bytes(cls: type[_T_SideEffects], blob: bytes) -> _T_SideEffects: ...
def from_bytes(cls, blob: bytes) -> Self: ...
_T_SideEffects = TypeVar("_T_SideEffects", bound=SideEffects)
+1 -1
View File
@@ -7,6 +7,6 @@ def hexstr_to_bytes(input_str: str) -> bytes:
"""
Converts a hex string into bytes, removing the 0x if it's present.
"""
if input_str.startswith("0x") or input_str.startswith("0X"):
if input_str.startswith(("0x", "0X")):
return bytes.fromhex(input_str[2:])
return bytes.fromhex(input_str)
+1 -1
View File
@@ -314,7 +314,7 @@ class DBWrapper2:
# probably skip the nested foreign key check when exiting since
# we don't have many foreign key errors and so it is likely ok
# to save the extra time checking twice.
raise NestedForeignKeyDelayedRequestError()
raise NestedForeignKeyDelayedRequestError
async with self._savepoint_ctx():
yield self._write_connection
return
-2
View File
@@ -349,5 +349,3 @@ class CliRpcConnectionError(ClickException):
"""
This error is raised when a rpc server cant be reached by the cli async generator
"""
pass
+6 -7
View File
@@ -79,12 +79,11 @@ def bytes_to_mnemonic(mnemonic_bytes: bytes) -> str:
CS = len(mnemonic_bytes) // 4
checksum = BitArray(bytes(std_hash(mnemonic_bytes)))[:CS]
bitarray = BitArray(mnemonic_bytes) + checksum
mnemonics = []
assert len(bitarray) % 11 == 0
for i in range(0, len(bitarray) // 11):
for i in range(len(bitarray) // 11):
start = i * 11
end = start + 11
bits = bitarray[start:end]
@@ -127,7 +126,7 @@ def bytes_from_mnemonic(mnemonic_str: str) -> bytes:
word_list = {word: i for i, word in enumerate(bip39_word_list().splitlines())}
bit_array = BitArray()
for i in range(0, len(mnemonic)):
for i in range(len(mnemonic)):
word = mnemonic[i]
if word not in word_list:
raise ValueError(f"'{word}' is not in the mnemonic dictionary; may be misspelled")
@@ -264,24 +263,24 @@ class KeyData(Streamable):
@property
def mnemonic(self) -> list[str]:
if self.secrets is None:
raise KeychainSecretsMissing()
raise KeychainSecretsMissing
return self.secrets.mnemonic
def mnemonic_str(self) -> str:
if self.secrets is None:
raise KeychainSecretsMissing()
raise KeychainSecretsMissing
return self.secrets.mnemonic_str()
@property
def entropy(self) -> bytes:
if self.secrets is None:
raise KeychainSecretsMissing()
raise KeychainSecretsMissing
return self.secrets.entropy
@property
def private_key(self) -> PrivateKey:
if self.secrets is None:
raise KeychainSecretsMissing()
raise KeychainSecretsMissing
return self.secrets.private_key
+2 -2
View File
@@ -112,7 +112,7 @@ def obtain_current_passphrase(prompt: str = DEFAULT_PASSPHRASE_PROMPT, use_passp
time.sleep(FAILED_ATTEMPT_DELAY)
print("Incorrect passphrase\n")
raise KeychainMaxUnlockAttempts()
raise KeychainMaxUnlockAttempts
class KeyringWrapper:
@@ -254,7 +254,7 @@ class KeyringWrapper:
and current_passphrase is not None
and not self.master_passphrase_is_valid(current_passphrase)
):
raise KeychainCurrentPassphraseIsInvalid()
raise KeychainCurrentPassphraseIsInvalid
self.set_cached_master_passphrase(new_passphrase, validated=True)
+1 -1
View File
@@ -31,7 +31,7 @@ class LimitedSemaphore:
@contextlib.asynccontextmanager
async def acquire(self) -> AsyncIterator[int]:
if self._available_count < 1:
raise LimitedSemaphoreFullError()
raise LimitedSemaphoreFullError
self._available_count -= 1
try:
+1 -1
View File
@@ -66,7 +66,7 @@ class PriorityMutex(Generic[_T_Priority]):
if task is None:
raise Exception(f"unable to check current task, got: {task!r}")
if self._active is not None and self._active.task is task:
raise NestedLockUnsupportedError()
raise NestedLockUnsupportedError
element = _Element(task=task)
+5 -5
View File
@@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Any, BinaryIO, Callable, ClassVar, Optional, T
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint16, uint32, uint64
from typing_extensions import Literal, get_args, get_origin
from typing_extensions import Literal, Self, get_args, get_origin
from chia.util.byte_types import hexstr_to_bytes
from chia.util.hash import std_hash
@@ -575,9 +575,9 @@ class Streamable:
raise
@classmethod
def parse(cls: type[_T_Streamable], f: BinaryIO) -> _T_Streamable:
def parse(cls, f: BinaryIO) -> Self:
# Create the object without calling __init__() to avoid unnecessary post-init checks in strictdataclass
obj: _T_Streamable = object.__new__(cls)
obj: Self = object.__new__(cls)
for field in cls._streamable_fields:
object.__setattr__(obj, field.name, field.parse_function(f))
return obj
@@ -590,7 +590,7 @@ class Streamable:
return std_hash(bytes(self), skip_bytes_conversion=True)
@classmethod
def from_bytes(cls: type[_T_Streamable], blob: bytes) -> _T_Streamable:
def from_bytes(cls, blob: bytes) -> Self:
f = io.BytesIO(blob)
parsed = cls.parse(f)
assert f.read() == b""
@@ -617,7 +617,7 @@ class Streamable:
return ret
@classmethod
def from_json_dict(cls: type[_T_Streamable], json_dict: dict[str, Any]) -> _T_Streamable:
def from_json_dict(cls, json_dict: dict[str, Any]) -> Self:
return streamable_from_dict(cls, json_dict)
+3 -8
View File
@@ -9,6 +9,7 @@ from chia_rs import Coin, G1Element
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint8, uint32, uint64
from clvm.casts import int_from_bytes, int_to_bytes
from typing_extensions import Self
from chia.types.blockchain_format.program import Program
from chia.types.condition_opcodes import ConditionOpcode
@@ -237,7 +238,7 @@ class CreateCoin(Condition):
return condition
@classmethod
def from_program(cls: type[_T_CreateCoin], program: Program) -> _T_CreateCoin:
def from_program(cls, program: Program) -> Self:
potential_memos: Program = program.at("rrr")
return cls(
bytes32(program.at("rf").as_atom()),
@@ -253,9 +254,6 @@ class CreateCoin(Condition):
return [self.puzzle_hash, self.amount, self.memos]
_T_CreateCoin = TypeVar("_T_CreateCoin", bound=CreateCoin)
@final
@streamable
@dataclass(frozen=True)
@@ -541,9 +539,6 @@ class MessageParticipant(Streamable):
)
_T_MessageCondition = TypeVar("_T_MessageCondition", bound="SendMessage")
@streamable
@dataclass(frozen=True)
class SendMessage(Condition):
@@ -607,7 +602,7 @@ class SendMessage(Condition):
return condition
@classmethod
def from_program(cls: type[_T_MessageCondition], program: Program) -> _T_MessageCondition:
def from_program(cls, program: Program) -> Self:
full_mode = uint8(program.at("rf").as_int())
var_args = list(program.at("rrr").as_iter())
return cls(
+3 -4
View File
@@ -2,11 +2,12 @@ from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Optional, TypeVar
from typing import Optional
from chia_rs import CoinSpend, CoinState
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint16
from typing_extensions import Self
from chia.types.blockchain_format.program import Program
from chia.util.streamable import Streamable, streamable
@@ -16,8 +17,6 @@ from chia.wallet.singleton import SINGLETON_TOP_LAYER_MOD
log = logging.getLogger(__name__)
_T_UncurriedNFT = TypeVar("_T_UncurriedNFT", bound="UncurriedNFT")
@streamable
@dataclass(frozen=True)
@@ -88,7 +87,7 @@ class UncurriedNFT(Streamable):
trade_price_percentage: Optional[uint16]
@classmethod
def uncurry(cls: type[_T_UncurriedNFT], mod: Program, curried_args: Program) -> Optional[_T_UncurriedNFT]:
def uncurry(cls, mod: Program, curried_args: Program) -> Optional[Self]:
"""
Try to uncurry a NFT puzzle
:param cls UncurriedNFT class
+3 -6
View File
@@ -1,10 +1,11 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Optional, TypeVar
from typing import Any, Optional
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint8, uint32, uint64
from typing_extensions import Self
from chia.types.blockchain_format.coin import Coin
from chia.util.streamable import Streamable, streamable
@@ -12,8 +13,6 @@ from chia.wallet.conditions import ConditionValidTimes
from chia.wallet.trading.offer import Offer
from chia.wallet.trading.trade_status import TradeStatus
_T_TradeRecord = TypeVar("_T_TradeRecord", bound="TradeRecordOld")
@streamable
@dataclass(frozen=True)
@@ -51,9 +50,7 @@ class TradeRecordOld(Streamable):
return formatted
@classmethod
def from_json_dict_convenience(
cls: type[_T_TradeRecord], record: dict[str, Any], offer: str = ""
) -> _T_TradeRecord:
def from_json_dict_convenience(cls, record: dict[str, Any], offer: str = "") -> Self:
new_record = record.copy()
new_record["status"] = TradeStatus[record["status"]].value
del new_record["summary"]
+3 -8
View File
@@ -1,12 +1,12 @@
from __future__ import annotations
import dataclasses
from typing import Any, Optional, TypeVar
from typing import Any, Optional
from chia_rs import ConsensusConstants
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint64
from typing_extensions import NotRequired, TypedDict, Unpack
from typing_extensions import NotRequired, Self, TypedDict, Unpack
from chia.consensus.default_constants import DEFAULT_CONSTANTS
from chia.types.blockchain_format.coin import Coin
@@ -66,9 +66,6 @@ class AutofillArgs(TypedDict):
logged_in_fingerprint: NotRequired[int]
_T_CoinSelectionConfigLoader = TypeVar("_T_CoinSelectionConfigLoader", bound="CoinSelectionConfigLoader")
@streamable
@dataclasses.dataclass(frozen=True)
class CoinSelectionConfigLoader(Streamable):
@@ -90,9 +87,7 @@ class CoinSelectionConfigLoader(Streamable):
)
@classmethod
def from_json_dict(
cls: type[_T_CoinSelectionConfigLoader], json_dict: dict[str, Any]
) -> _T_CoinSelectionConfigLoader:
def from_json_dict(cls, json_dict: dict[str, Any]) -> Self:
if "excluded_coins" in json_dict:
excluded_coins: list[Coin] = [Coin.from_json_dict(c) for c in json_dict["excluded_coins"]]
excluded_coin_ids: list[str] = [c.name().hex() for c in excluded_coins]
+8 -10
View File
@@ -4,7 +4,7 @@ import functools
from collections.abc import Iterable
from dataclasses import dataclass, replace
from enum import IntEnum
from typing import Optional, TypeVar
from typing import Optional
from chia_puzzles_py.programs import (
CONDITIONS_W_FEE_ANNOUNCE,
@@ -20,6 +20,7 @@ from chia_rs import CoinSpend
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint16, uint64
from clvm.casts import int_to_bytes
from typing_extensions import Self
from chia.types.blockchain_format.coin import Coin, coin_as_list
from chia.types.blockchain_format.program import Program
@@ -166,9 +167,6 @@ def construct_pending_approval_state(puzzle_hash: bytes32, amount: uint64) -> Pr
return PENDING_VC_ANNOUNCEMENT.curry(Program.to([[51, puzzle_hash, amount, [puzzle_hash]]]))
_T_CRCAT = TypeVar("_T_CRCAT", bound="CRCAT")
@dataclass(frozen=True)
class CRCAT:
coin: Coin
@@ -180,7 +178,7 @@ class CRCAT:
@classmethod
def launch(
cls: type[_T_CRCAT],
cls,
# General CAT launching info
origin_coin: Coin,
payment: CreateCoin,
@@ -308,7 +306,7 @@ class CRCAT:
return solution.at("f").at("rrrrrrf")
@classmethod
def get_current_from_coin_spend(cls: type[_T_CRCAT], spend: CoinSpend) -> CRCAT: # pragma: no cover
def get_current_from_coin_spend(cls, spend: CoinSpend) -> CRCAT: # pragma: no cover
uncurried_puzzle: UncurriedPuzzle = uncurry_puzzle(spend.puzzle_reveal)
first_uncurried_cr_layer: UncurriedPuzzle = uncurry_puzzle(uncurried_puzzle.args.at("rrf"))
second_uncurried_cr_layer: UncurriedPuzzle = uncurry_puzzle(first_uncurried_cr_layer.mod)
@@ -327,7 +325,7 @@ class CRCAT:
@classmethod
def get_next_from_coin_spend(
cls: type[_T_CRCAT],
cls,
parent_spend: CoinSpend,
conditions: Optional[Program] = None, # For optimization purposes, the conditions may already have been run
) -> list[CRCAT]:
@@ -516,8 +514,8 @@ class CRCAT:
@classmethod
def spend_many(
cls: type[_T_CRCAT],
inner_spends: list[tuple[_T_CRCAT, int, Program, Program]], # CRCAT, extra_delta, inner puzzle, inner solution
cls,
inner_spends: list[tuple[Self, int, Program, Program]], # CRCAT, extra_delta, inner puzzle, inner solution
# CR layer solving info
proof_of_inclusions: Program,
proof_checker_solution: Program,
@@ -539,7 +537,7 @@ class CRCAT:
def prev_index(index: int) -> int:
return index - 1
sorted_inner_spends: list[tuple[_T_CRCAT, int, Program, Program]] = sorted(
sorted_inner_spends: list[tuple[Self, int, Program, Program]] = sorted(
inner_spends,
key=lambda spend: spend[0].coin.name(),
)
+6 -6
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass, replace
from typing import Optional, TypeVar
from typing import Optional
from chia_puzzles_py.programs import ACS_TRANSFER_PROGRAM as ACS_TRANSFER_PROGRAM_BYTES
from chia_puzzles_py.programs import COVENANT_LAYER as COVENANT_LAYER_BYTES
@@ -23,6 +23,7 @@ from chia_puzzles_py.programs import STD_PARENT_MORPHER_HASH as STD_PARENT_MORPH
from chia_rs import CoinSpend
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint64
from typing_extensions import Self
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
@@ -290,7 +291,6 @@ OWNERSHIP_LAYER_LAUNCHER_HASH = OWNERSHIP_LAYER_LAUNCHER.get_tree_hash()
########################
# Verified Credentials #
########################
_T_VerifiedCredential = TypeVar("_T_VerifiedCredential", bound="VerifiedCredential")
@streamable
@@ -312,14 +312,14 @@ class VerifiedCredential(Streamable):
@classmethod
def launch(
cls: type[_T_VerifiedCredential],
cls,
origin_coins: list[Coin],
provider_id: bytes32,
new_inner_puzzle_hash: bytes32,
memos: list[bytes32],
fee: uint64 = uint64(0),
extra_conditions: tuple[Condition, ...] = tuple(),
) -> tuple[list[Program], list[CoinSpend], _T_VerifiedCredential]:
) -> tuple[list[Program], list[CoinSpend], Self]:
"""
Launch a VC.
@@ -539,7 +539,7 @@ class VerifiedCredential(Streamable):
return True, ""
@classmethod
def get_next_from_coin_spend(cls: type[_T_VerifiedCredential], parent_spend: CoinSpend) -> _T_VerifiedCredential:
def get_next_from_coin_spend(cls, parent_spend: CoinSpend) -> Self:
"""
Given a coin spend, this will return the next VC that was create as an output of that spend. This is the main
method to use when syncing. If a spend has been identified as having a VC puzzle reveal, running this method
@@ -608,7 +608,7 @@ class VerifiedCredential(Streamable):
parent_proof_hash=None if parent_proof_hash == Program.to(None) else parent_proof_hash,
)
new_vc: _T_VerifiedCredential = cls(
new_vc: Self = cls(
coin,
singleton_lineage_proof,
eml_lineage_proof,
+3 -5
View File
@@ -2,11 +2,12 @@ from __future__ import annotations
import dataclasses
from functools import cmp_to_key
from typing import Optional, TypeVar
from typing import Optional
from aiosqlite import Row
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64
from typing_extensions import Self
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
@@ -81,9 +82,6 @@ class VCProofs:
return new_tree
_T_VCStore = TypeVar("_T_VCStore", bound="VCStore")
@streamable
@dataclasses.dataclass(frozen=True)
class VCRecord(Streamable):
@@ -114,7 +112,7 @@ class VCStore:
db_wrapper: DBWrapper2
@classmethod
async def create(cls: type[_T_VCStore], db_wrapper: DBWrapper2) -> _T_VCStore:
async def create(cls, db_wrapper: DBWrapper2) -> Self:
self = cls()
self.db_wrapper = db_wrapper
+3 -3
View File
@@ -3,10 +3,11 @@ from __future__ import annotations
import json
import logging
from sqlite3 import Row
from typing import Optional, TypeVar, Union
from typing import Optional, Union
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32
from typing_extensions import Self
from chia.types.blockchain_format.coin import Coin
from chia.types.blockchain_format.program import Program
@@ -15,7 +16,6 @@ from chia.wallet.lineage_proof import LineageProof
from chia.wallet.nft_wallet.nft_info import DEFAULT_STATUS, IN_TRANSACTION_STATUS, NFTCoinInfo
log = logging.getLogger(__name__)
_T_WalletNftStore = TypeVar("_T_WalletNftStore", bound="WalletNftStore")
REMOVE_BUFF_BLOCKS = 1000
NFT_COIN_INFO_COLUMNS = "nft_id, coin, lineage_proof, mint_height, status, full_puzzle, latest_height, minter_did"
@@ -42,7 +42,7 @@ class WalletNftStore:
db_wrapper: DBWrapper2
@classmethod
async def create(cls: type[_T_WalletNftStore], db_wrapper: DBWrapper2) -> _T_WalletNftStore:
async def create(cls, db_wrapper: DBWrapper2) -> Self:
self = cls()
self.db_wrapper = db_wrapper
async with self.db_wrapper.writer_maybe_transaction() as conn:

Some files were not shown because too many files have changed in this diff Show More