[LABS-245] Enable PEP604 Ruff rules (#20269)

* Enable PEP604 Ruff rules

* Fix harcoded signature in test

* Hack CLVMStreamable test with note to fast follow
This commit is contained in:
Matt Hauff
2025-11-18 12:34:00 -08:00
committed by GitHub
parent 6c8ccd246d
commit 40db4635a8
450 changed files with 4034 additions and 4321 deletions
+1 -2
View File
@@ -6,7 +6,6 @@ import random
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from time import monotonic from time import monotonic
from typing import Optional
import aiosqlite import aiosqlite
import click import click
@@ -38,7 +37,7 @@ with open(Path(file_path).parent / "transaction_height_delta", "rb") as f:
@dataclass(frozen=True) @dataclass(frozen=True)
class BlockInfo: class BlockInfo:
prev_header_hash: bytes32 prev_header_hash: bytes32
transactions_generator: Optional[SerializedProgram] transactions_generator: SerializedProgram | None
transactions_generator_ref_list: list[uint32] transactions_generator_ref_list: list[uint32]
+3 -4
View File
@@ -4,7 +4,6 @@ import asyncio
from collections.abc import Collection from collections.abc import Collection
from dataclasses import dataclass from dataclasses import dataclass
from time import monotonic from time import monotonic
from typing import Optional
from chia_rs import CoinSpend, G2Element, SpendBundle from chia_rs import CoinSpend, G2Element, SpendBundle
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -35,9 +34,9 @@ class BenchBlockRecord:
header_hash: bytes32 header_hash: bytes32
height: uint32 height: uint32
timestamp: Optional[uint64] timestamp: uint64 | None
prev_transaction_block_height: uint32 prev_transaction_block_height: uint32
prev_transaction_block_hash: Optional[bytes32] prev_transaction_block_hash: bytes32 | None
@property @property
def is_transaction_block(self) -> bool: def is_transaction_block(self) -> bool:
@@ -90,7 +89,7 @@ async def run_mempool_benchmark() -> None:
return ret return ret
# We currently don't need to keep track of these for our purpose # We currently don't need to keep track of these for our purpose
async def get_unspent_lineage_info_for_puzzle_hash(_: bytes32) -> Optional[UnspentLineageInfo]: async def get_unspent_lineage_info_for_puzzle_hash(_: bytes32) -> UnspentLineageInfo | None:
assert False assert False
timestamp = uint64(1631794488) timestamp = uint64(1631794488)
+3 -4
View File
@@ -7,7 +7,6 @@ from contextlib import contextmanager
from dataclasses import dataclass from dataclasses import dataclass
from subprocess import check_call from subprocess import check_call
from time import monotonic from time import monotonic
from typing import Optional
from chia_rs import SpendBundle from chia_rs import SpendBundle
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -58,9 +57,9 @@ class BenchBlockRecord:
header_hash: bytes32 header_hash: bytes32
height: uint32 height: uint32
timestamp: Optional[uint64] timestamp: uint64 | None
prev_transaction_block_height: uint32 prev_transaction_block_height: uint32
prev_transaction_block_hash: Optional[bytes32] prev_transaction_block_hash: bytes32 | None
@property @property
def is_transaction_block(self) -> bool: def is_transaction_block(self) -> bool:
@@ -91,7 +90,7 @@ async def run_mempool_benchmark() -> None:
return ret return ret
# We currently don't need to keep track of these for our purpose # We currently don't need to keep track of these for our purpose
async def get_unspent_lineage_info_for_puzzle_hash(_: bytes32) -> Optional[UnspentLineageInfo]: async def get_unspent_lineage_info_for_puzzle_hash(_: bytes32) -> UnspentLineageInfo | None:
assert False assert False
wt = WalletTool(DEFAULT_CONSTANTS) wt = WalletTool(DEFAULT_CONSTANTS)
+14 -13
View File
@@ -3,11 +3,12 @@ from __future__ import annotations
import json import json
import random import random
import sys import sys
from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum from enum import Enum
from statistics import stdev from statistics import stdev
from time import process_time as clock from time import process_time as clock
from typing import Any, Callable, Optional, TextIO, Union from typing import Any, TextIO
import click import click
from chia_rs import FullBlock from chia_rs import FullBlock
@@ -43,8 +44,8 @@ class BenchmarkMiddle(Streamable):
@streamable @streamable
@dataclass(frozen=True) @dataclass(frozen=True)
class BenchmarkClass(Streamable): class BenchmarkClass(Streamable):
a: Optional[BenchmarkMiddle] a: BenchmarkMiddle | None
b: Optional[BenchmarkMiddle] b: BenchmarkMiddle | None
c: BenchmarkMiddle c: BenchmarkMiddle
d: list[BenchmarkMiddle] d: list[BenchmarkMiddle]
e: tuple[BenchmarkMiddle, BenchmarkMiddle, BenchmarkMiddle] e: tuple[BenchmarkMiddle, BenchmarkMiddle, BenchmarkMiddle]
@@ -64,8 +65,8 @@ def get_random_middle() -> BenchmarkMiddle:
def get_random_benchmark_object() -> BenchmarkClass: def get_random_benchmark_object() -> BenchmarkClass:
a: Optional[BenchmarkMiddle] = None a: BenchmarkMiddle | None = None
b: Optional[BenchmarkMiddle] = get_random_middle() b: BenchmarkMiddle | None = get_random_middle()
c: BenchmarkMiddle = get_random_middle() c: BenchmarkMiddle = get_random_middle()
d: list[BenchmarkMiddle] = [get_random_middle() for _ in range(5)] d: list[BenchmarkMiddle] = [get_random_middle() for _ in range(5)]
e: tuple[BenchmarkMiddle, BenchmarkMiddle, BenchmarkMiddle] = ( e: tuple[BenchmarkMiddle, BenchmarkMiddle, BenchmarkMiddle] = (
@@ -79,10 +80,10 @@ def get_random_benchmark_object() -> BenchmarkClass:
def print_row( def print_row(
*, *,
mode: str, mode: str,
us_per_iteration: Union[str, float], us_per_iteration: str | float,
stdev_us_per_iteration: Union[str, float], stdev_us_per_iteration: str | float,
avg_iterations: Union[str, int], avg_iterations: str | int,
stdev_iterations: Union[str, float], stdev_iterations: str | float,
end: str = "\n", end: str = "\n",
) -> None: ) -> None:
print( print(
@@ -142,14 +143,14 @@ def to_bytes(obj: Any) -> bytes:
@dataclass @dataclass
class ModeParameter: class ModeParameter:
conversion_cb: Callable[[Any], Any] conversion_cb: Callable[[Any], Any]
preparation_cb: Optional[Callable[[Any], Any]] = None preparation_cb: Callable[[Any], Any] | None = None
@dataclass @dataclass
class BenchmarkParameter: class BenchmarkParameter:
data_class: type[Any] data_class: type[Any]
object_creation_cb: Callable[[], Any] object_creation_cb: Callable[[], Any]
mode_parameter: dict[Mode, Optional[ModeParameter]] mode_parameter: dict[Mode, ModeParameter | None]
benchmark_parameter: dict[Data, BenchmarkParameter] = { benchmark_parameter: dict[Data, BenchmarkParameter] = {
@@ -202,12 +203,12 @@ def pop_data(key: str, *, old: dict[str, Any], new: dict[str, Any]) -> tuple[Any
return old.pop(key), new.pop(key) return old.pop(key), new.pop(key)
def print_compare_row(c0: str, c1: Union[str, float], c2: Union[str, float], c3: Union[str, float]) -> None: def print_compare_row(c0: str, c1: str | float, c2: str | float, c3: str | float) -> None:
print(f"{c0:<12} | {c1:<16} | {c2:<16} | {c3:<12}") print(f"{c0:<12} | {c1:<16} | {c2:<16} | {c3:<12}")
def compare_results( def compare_results(
old: dict[str, dict[str, dict[str, Union[float, int]]]], new: dict[str, dict[str, dict[str, Union[float, int]]]] old: dict[str, dict[str, dict[str, float | int]]], new: dict[str, dict[str, dict[str, float | int]]]
) -> None: ) -> None:
old_version, new_version = pop_data("version", old=old, new=new) old_version, new_version = pop_data("version", old=old, new=new)
if old_version != new_version: if old_version != new_version:
+2 -3
View File
@@ -6,20 +6,19 @@ import subprocess
import sys import sys
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from pathlib import Path from pathlib import Path
from typing import Optional, Union
from chia.util.db_wrapper import DBWrapper2 from chia.util.db_wrapper import DBWrapper2
@contextlib.asynccontextmanager @contextlib.asynccontextmanager
async def setup_db(name: Union[str, os.PathLike[str]], db_version: int) -> AsyncIterator[DBWrapper2]: async def setup_db(name: str | os.PathLike[str], db_version: int) -> AsyncIterator[DBWrapper2]:
db_filename = Path(name) db_filename = Path(name)
try: try:
os.unlink(db_filename) os.unlink(db_filename)
except FileNotFoundError: except FileNotFoundError:
pass pass
log_path: Optional[Path] log_path: Path | None
if "--sql-logging" in sys.argv: if "--sql-logging" in sys.argv:
log_path = Path("sql.log") log_path = Path("sql.log")
else: else:
@@ -1,7 +1,5 @@
from __future__ import annotations from __future__ import annotations
from typing import Optional
from chia_rs import FullBlock, SpendBundleConditions from chia_rs import FullBlock, SpendBundleConditions
from chia_rs.sized_ints import uint32, uint64 from chia_rs.sized_ints import uint32, uint64
@@ -46,10 +44,10 @@ async def _validate_and_add_block(
blockchain: Blockchain, blockchain: Blockchain,
block: FullBlock, block: FullBlock,
*, *,
expected_result: Optional[AddBlockResult] = None, expected_result: AddBlockResult | None = None,
expected_error: Optional[Err] = None, expected_error: Err | None = None,
skip_prevalidation: bool = False, skip_prevalidation: bool = False,
fork_info: Optional[ForkInfo] = None, fork_info: ForkInfo | None = None,
) -> None: ) -> None:
# Tries to validate and add the block, and checks that there are no errors in the process and that the # Tries to validate and add the block, and checks that there are no errors in the process and that the
# block is added to the peak. # block is added to the peak.
@@ -137,7 +135,7 @@ async def _validate_and_add_block_multi_error(
block: FullBlock, block: FullBlock,
expected_errors: list[Err], expected_errors: list[Err],
skip_prevalidation: bool = False, skip_prevalidation: bool = False,
fork_info: Optional[ForkInfo] = None, fork_info: ForkInfo | None = None,
) -> None: ) -> None:
# Checks that the blockchain returns one of the expected errors # Checks that the blockchain returns one of the expected errors
try: try:
@@ -155,7 +153,7 @@ async def _validate_and_add_block_multi_result(
block: FullBlock, block: FullBlock,
expected_result: list[AddBlockResult], expected_result: list[AddBlockResult],
skip_prevalidation: bool = False, skip_prevalidation: bool = False,
fork_info: Optional[ForkInfo] = None, fork_info: ForkInfo | None = None,
) -> None: ) -> None:
try: try:
await _validate_and_add_block( await _validate_and_add_block(
@@ -176,7 +174,7 @@ async def _validate_and_add_block_no_error(
blockchain: Blockchain, blockchain: Blockchain,
block: FullBlock, block: FullBlock,
skip_prevalidation: bool = False, skip_prevalidation: bool = False,
fork_info: Optional[ForkInfo] = None, fork_info: ForkInfo | None = None,
) -> None: ) -> None:
# adds a block and ensures that there is no error. However, does not ensure that block extended the peak of # adds a block and ensures that there is no error. However, does not ensure that block extended the peak of
# the blockchain # the blockchain
@@ -2,7 +2,7 @@ from __future__ import annotations
import re import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import TYPE_CHECKING, ClassVar, Optional, cast from typing import TYPE_CHECKING, ClassVar, cast
import pytest import pytest
from chia_rs import BlockRecord, FullBlock from chia_rs import BlockRecord, FullBlock
@@ -30,14 +30,14 @@ class NullBlockchain:
async def lookup_block_generators(self, header_hash: bytes32, generator_refs: set[uint32]) -> dict[uint32, bytes]: async def lookup_block_generators(self, header_hash: bytes32, generator_refs: set[uint32]) -> dict[uint32, bytes]:
raise ValueError(Err.GENERATOR_REF_HAS_NO_GENERATOR) # pragma: no cover raise ValueError(Err.GENERATOR_REF_HAS_NO_GENERATOR) # pragma: no cover
async def get_block_record_from_db(self, header_hash: bytes32) -> Optional[BlockRecord]: async def get_block_record_from_db(self, header_hash: bytes32) -> BlockRecord | None:
return None # pragma: no cover return None # pragma: no cover
def add_block_record(self, block_record: BlockRecord) -> None: def add_block_record(self, block_record: BlockRecord) -> None:
self.added_blocks.add(block_record.header_hash) self.added_blocks.add(block_record.header_hash)
# BlockRecordsProtocol # BlockRecordsProtocol
def try_block_record(self, header_hash: bytes32) -> Optional[BlockRecord]: def try_block_record(self, header_hash: bytes32) -> BlockRecord | None:
return None # pragma: no cover return None # pragma: no cover
def block_record(self, header_hash: bytes32) -> BlockRecord: def block_record(self, header_hash: bytes32) -> BlockRecord:
@@ -46,7 +46,7 @@ class NullBlockchain:
def height_to_block_record(self, height: uint32) -> BlockRecord: def height_to_block_record(self, height: uint32) -> BlockRecord:
raise ValueError("Height is not in blockchain") raise ValueError("Height is not in blockchain")
def height_to_hash(self, height: uint32) -> Optional[bytes32]: def height_to_hash(self, height: uint32) -> bytes32 | None:
return self.heights.get(height) return self.heights.get(height)
def contains_block(self, header_hash: bytes32, height: uint32) -> bool: def contains_block(self, header_hash: bytes32, height: uint32) -> bool:
+5 -6
View File
@@ -9,7 +9,6 @@ import time
from collections.abc import AsyncIterator, Awaitable from collections.abc import AsyncIterator, Awaitable
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from dataclasses import dataclass, replace from dataclasses import dataclass, replace
from typing import Optional
import pytest import pytest
from chia_rs import ( from chia_rs import (
@@ -3266,7 +3265,7 @@ class TestBodyValidation:
assert preval_result.error == Err.BAD_AGGREGATE_SIGNATURE.value assert preval_result.error == Err.BAD_AGGREGATE_SIGNATURE.value
def maybe_header_hash(block: Optional[BlockRecord]) -> Optional[bytes32]: def maybe_header_hash(block: BlockRecord | None) -> bytes32 | None:
if block is None: if block is None:
return None return None
return block.header_hash return block.header_hash
@@ -3313,7 +3312,7 @@ class TestReorgs:
reorg_point = 12 reorg_point = 12
blocks = bt.get_consecutive_blocks(reorg_point) blocks = bt.get_consecutive_blocks(reorg_point)
last_tx_block: Optional[bytes32] = None last_tx_block: bytes32 | None = None
for block in blocks: for block in blocks:
assert maybe_header_hash(b.get_tx_peak()) == last_tx_block assert maybe_header_hash(b.get_tx_peak()) == last_tx_block
await _validate_and_add_block(b, block) await _validate_and_add_block(b, block)
@@ -3324,7 +3323,7 @@ class TestReorgs:
assert peak.height == reorg_point - 1 assert peak.height == reorg_point - 1
assert maybe_header_hash(b.get_tx_peak()) == last_tx_block assert maybe_header_hash(b.get_tx_peak()) == last_tx_block
reorg_last_tx_block: Optional[bytes32] = None reorg_last_tx_block: bytes32 | None = None
fork_block = blocks[9] fork_block = blocks[9]
fork_info = ForkInfo(fork_block.height, fork_block.height, fork_block.header_hash) fork_info = ForkInfo(fork_block.height, fork_block.height, fork_block.header_hash)
blocks_reorg_chain = bt.get_consecutive_blocks(7, blocks[:10], seed=b"2") blocks_reorg_chain = bt.get_consecutive_blocks(7, blocks[:10], seed=b"2")
@@ -4085,7 +4084,7 @@ async def test_get_tx_peak(default_400_blocks: list[FullBlock], empty_blockchain
assert bc.get_tx_peak() == last_tx_block_record assert bc.get_tx_peak() == last_tx_block_record
def to_bytes(gen: Optional[SerializedProgram]) -> bytes: def to_bytes(gen: SerializedProgram | None) -> bytes:
assert gen is not None assert gen is not None
return bytes(gen) return bytes(gen)
@@ -4218,7 +4217,7 @@ async def get_fork_info(blockchain: Blockchain, block: FullBlock, peak: BlockRec
counter = 0 counter = 0
start = time.monotonic() start = time.monotonic()
for height in range(fork_info.fork_height + 1, block.height): for height in range(fork_info.fork_height + 1, block.height):
fork_block: Optional[FullBlock] = await blockchain.block_store.get_full_block(fork_chain[uint32(height)]) fork_block: FullBlock | None = await blockchain.block_store.get_full_block(fork_chain[uint32(height)])
assert fork_block is not None assert fork_block is not None
assert fork_block.height - 1 == fork_info.peak_height assert fork_block.height - 1 == fork_info.peak_height
assert fork_block.height == 0 or fork_block.prev_header_hash == fork_info.peak_hash assert fork_block.height == 0 or fork_block.prev_header_hash == fork_info.peak_hash
+2 -4
View File
@@ -1,7 +1,5 @@
from __future__ import annotations from __future__ import annotations
from typing import Optional
import pytest import pytest
from chia_rs import Coin, ConsensusConstants, FullBlock, additions_and_removals, get_flags_for_height_and_constants from chia_rs import Coin, ConsensusConstants, FullBlock, additions_and_removals, get_flags_for_height_and_constants
from chia_rs.sized_ints import uint64 from chia_rs.sized_ints import uint64
@@ -102,8 +100,8 @@ def validate_chain(
normalized_to_identity_icc_eos: bool = False, normalized_to_identity_icc_eos: bool = False,
normalized_to_identity_cc_sp: bool = False, normalized_to_identity_cc_sp: bool = False,
normalized_to_identity_cc_ip: bool = False, normalized_to_identity_cc_ip: bool = False,
block_list_input: Optional[list[FullBlock]] = None, block_list_input: list[FullBlock] | None = None,
time_per_block: Optional[float] = None, time_per_block: float | None = None,
dummy_block_references: bool = False, dummy_block_references: bool = False,
include_transactions: bool = False, include_transactions: bool = False,
) -> None: ) -> None:
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional
import pytest import pytest
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -16,14 +15,14 @@ from chia.util.casts import int_to_bytes
@dataclass(frozen=True) @dataclass(frozen=True)
class BR: class BR:
prev_header_hash: bytes32 prev_header_hash: bytes32
transactions_generator: Optional[SerializedProgram] transactions_generator: SerializedProgram | None
transactions_generator_ref_list: list[uint32] transactions_generator_ref_list: list[uint32]
@dataclass(frozen=True) @dataclass(frozen=True)
class FB: class FB:
prev_header_hash: bytes32 prev_header_hash: bytes32
transactions_generator: Optional[SerializedProgram] transactions_generator: SerializedProgram | None
height: uint32 height: uint32
+1 -2
View File
@@ -3,7 +3,6 @@ from __future__ import annotations
from collections import defaultdict from collections import defaultdict
from collections.abc import Iterator from collections.abc import Iterator
from dataclasses import dataclass, replace from dataclasses import dataclass, replace
from typing import Optional
from chia_rs import ConsensusConstants, SpendBundle from chia_rs import ConsensusConstants, SpendBundle
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -145,5 +144,5 @@ class CoinStore:
) )
self._ph_index[coin.puzzle_hash].append(name) self._ph_index[coin.puzzle_hash].append(name)
def coin_record(self, coin_id: bytes32) -> Optional[CoinRecord]: def coin_record(self, coin_id: bytes32) -> CoinRecord | None:
return self._db.get(coin_id) return self._db.get(coin_id)
+3 -3
View File
@@ -1,6 +1,6 @@
from __future__ import annotations from __future__ import annotations
from typing import Any, Optional from typing import Any
from chialisp import start_clvm_program from chialisp import start_clvm_program
@@ -17,8 +17,8 @@ factorial_sym = {factorial_function_hash: "factorial"}
def test_simple_program_run() -> None: def test_simple_program_run() -> None:
p = start_clvm_program(factorial, "ff0580", factorial_sym) p = start_clvm_program(factorial, "ff0580", factorial_sym)
last: Optional[Any] = None last: Any | None = None
location: Optional[Any] = None location: Any | None = None
while not p.is_ended(): while not p.is_ended():
step_result = p.step() step_result = p.step()
+2 -1
View File
@@ -1,8 +1,9 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from typing import Callable, SupportsBytes from typing import SupportsBytes
import pytest import pytest
from chia_rs import CoinSpend, G1Element, G2Element, SpendBundle from chia_rs import CoinSpend, G1Element, G2Element, SpendBundle
+2 -2
View File
@@ -1,6 +1,6 @@
from __future__ import annotations from __future__ import annotations
from typing import Any, Union from typing import Any
import pytest import pytest
@@ -35,7 +35,7 @@ def test_puzzle_info() -> None:
assert solver == Solver(capitalize_bytes) assert solver == Solver(capitalize_bytes)
assert puzzle_info == PuzzleInfo(capitalize_bytes) assert puzzle_info == PuzzleInfo(capitalize_bytes)
obj: Union[PuzzleInfo, Solver] obj: PuzzleInfo | Solver
for obj in (puzzle_info, solver): for obj in (puzzle_info, solver):
assert obj["string"] == "hello" assert obj["string"] == "hello"
assert obj["bytes"] == bytes.fromhex("cafef00d") assert obj["bytes"] == bytes.fromhex("cafef00d")
+2 -4
View File
@@ -1,7 +1,5 @@
from __future__ import annotations from __future__ import annotations
from typing import Optional
import pytest import pytest
from chia_rs import AugSchemeMPL, CoinSpend, G1Element, G2Element, PrivateKey, SpendBundle from chia_rs import AugSchemeMPL, CoinSpend, G1Element, G2Element, PrivateKey, SpendBundle
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -54,9 +52,9 @@ async def make_and_spend_bundle(
coin: Coin, coin: Coin,
delegated_puzzle: Program, delegated_puzzle: Program,
coinsols: list[CoinSpend], coinsols: list[CoinSpend],
ex_error: Optional[Err] = None, ex_error: Err | None = None,
fail_msg: str = "", fail_msg: str = "",
cost_logger: Optional[CostLogger] = None, cost_logger: CostLogger | None = None,
cost_log_msg: str = "", cost_log_msg: str = "",
): ):
signature: G2Element = sign_delegated_puz(delegated_puzzle, coin) signature: G2Element = sign_delegated_puz(delegated_puzzle, coin)
+13 -13
View File
@@ -5,7 +5,7 @@ from collections.abc import AsyncIterator, Iterable
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from typing import Any, Optional, cast from typing import Any, cast
from chia_rs import BlockRecord, Coin, G1Element, G2Element from chia_rs import BlockRecord, Coin, G1Element, G2Element
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -59,15 +59,15 @@ from chia.wallet.wallet_spend_bundle import WalletSpendBundle
# Any functions that are the same for every command being tested should be below. # Any functions that are the same for every command being tested should be below.
# Functions that are specific to a command should be in the test file for that command. # Functions that are specific to a command should be in the test file for that command.
logType = dict[str, Optional[list[tuple[Any, ...]]]] logType = dict[str, list[tuple[Any, ...]] | None]
@dataclass @dataclass
class TestRpcClient: class TestRpcClient:
client_type: type[RpcClient] client_type: type[RpcClient]
rpc_port: Optional[uint16] = None rpc_port: uint16 | None = None
root_path: Optional[Path] = None root_path: Path | None = None
config: Optional[dict[str, Any]] = None config: dict[str, Any] | None = None
create_called: bool = field(init=False, default=False) create_called: bool = field(init=False, default=False)
rpc_log: dict[str, list[tuple[Any, ...]]] = field(init=False, default_factory=dict) rpc_log: dict[str, list[tuple[Any, ...]]] = field(init=False, default_factory=dict)
@@ -240,7 +240,7 @@ class TestWalletRpcClient(TestRpcClient):
wallet_id: int, wallet_id: int,
additions: list[dict[str, object]], additions: list[dict[str, object]],
tx_config: TXConfig, tx_config: TXConfig,
coins: Optional[list[Coin]] = None, coins: list[Coin] | None = None,
fee: uint64 = uint64(0), fee: uint64 = uint64(0),
push: bool = True, push: bool = True,
timelock_info: ConditionValidTimes = ConditionValidTimes(), timelock_info: ConditionValidTimes = ConditionValidTimes(),
@@ -280,8 +280,8 @@ class TestFullNodeRpcClient(TestRpcClient):
async def get_fee_estimate( async def get_fee_estimate(
self, self,
target_times: Optional[list[int]], target_times: list[int] | None,
cost: Optional[int], cost: int | None,
) -> dict[str, Any]: ) -> dict[str, Any]:
return {} return {}
@@ -313,11 +313,11 @@ class TestFullNodeRpcClient(TestRpcClient):
self.add_to_log("get_blockchain_state", ()) self.add_to_log("get_blockchain_state", ())
return response return response
async def get_block_record_by_height(self, height: int) -> Optional[BlockRecord]: async def get_block_record_by_height(self, height: int) -> BlockRecord | None:
self.add_to_log("get_block_record_by_height", (height,)) self.add_to_log("get_block_record_by_height", (height,))
return cast(BlockRecord, create_test_block_record(height=uint32(height))) return cast(BlockRecord, create_test_block_record(height=uint32(height)))
async def get_block_record(self, header_hash: bytes32) -> Optional[BlockRecord]: async def get_block_record(self, header_hash: bytes32) -> BlockRecord | None:
self.add_to_log("get_block_record", (header_hash,)) self.add_to_log("get_block_record", (header_hash,))
return cast(BlockRecord, create_test_block_record(header_hash=header_hash)) return cast(BlockRecord, create_test_block_record(header_hash=header_hash))
@@ -374,7 +374,7 @@ def create_service_and_wallet_client_generators(test_rpc_clients: TestRpcClients
async def test_get_any_service_client( async def test_get_any_service_client(
client_type: type[_T_RpcClient], client_type: type[_T_RpcClient],
root_path: Path, root_path: Path,
rpc_port: Optional[int] = None, rpc_port: int | None = None,
consume_errors: bool = True, consume_errors: bool = True,
use_ssl: bool = True, use_ssl: bool = True,
) -> AsyncIterator[tuple[_T_RpcClient, dict[str, Any]]]: ) -> AsyncIterator[tuple[_T_RpcClient, dict[str, Any]]]:
@@ -402,8 +402,8 @@ def create_service_and_wallet_client_generators(test_rpc_clients: TestRpcClients
@asynccontextmanager @asynccontextmanager
async def test_get_wallet_client( async def test_get_wallet_client(
root_path: Path = default_root, root_path: Path = default_root,
wallet_rpc_port: Optional[int] = None, wallet_rpc_port: int | None = None,
fingerprint: Optional[int] = None, fingerprint: int | None = None,
) -> AsyncIterator[tuple[WalletRpcClient, int, dict[str, Any]]]: ) -> AsyncIterator[tuple[WalletRpcClient, int, dict[str, Any]]]:
async with test_get_any_service_client(WalletRpcClient, root_path, wallet_rpc_port) as (wallet_client, config): async with test_get_any_service_client(WalletRpcClient, root_path, wallet_rpc_port) as (wallet_client, config):
wallet_client.fingerprint = fingerprint # type: ignore wallet_client.fingerprint = fingerprint # type: ignore
+6 -6
View File
@@ -5,7 +5,7 @@ import textwrap
from collections.abc import Sequence from collections.abc import Sequence
from dataclasses import asdict from dataclasses import asdict
from decimal import Decimal from decimal import Decimal
from typing import Any, Optional from typing import Any
import click import click
import pytest import pytest
@@ -32,7 +32,7 @@ from chia.wallet.transaction_record import TransactionRecord
from chia.wallet.util.tx_config import CoinSelectionConfig, TXConfig from chia.wallet.util.tx_config import CoinSelectionConfig, TXConfig
def check_click_parsing(cmd: ChiaCommand, *args: str, context: Optional[ChiaCliContext] = None) -> None: def check_click_parsing(cmd: ChiaCommand, *args: str, context: ChiaCliContext | None = None) -> None:
@click.group() @click.group()
def _cmd() -> None: def _cmd() -> None:
pass pass
@@ -232,7 +232,7 @@ def test_typing() -> None:
# Test optional # Test optional
@chia_command(group=cmd, name="temp_cmd_optional", short_help="blah", help="n/a") @chia_command(group=cmd, name="temp_cmd_optional", short_help="blah", help="n/a")
class TempCMDOptional: class TempCMDOptional:
optional: Optional[int] = option("--optional", required=False) optional: int | None = option("--optional", required=False)
def run(self) -> None: ... def run(self) -> None: ...
@@ -244,7 +244,7 @@ def test_typing() -> None:
@chia_command(group=cmd, name="temp_cmd_optional_bad", short_help="blah", help="n/a") @chia_command(group=cmd, name="temp_cmd_optional_bad", short_help="blah", help="n/a")
class TempCMDOptionalBad2: class TempCMDOptionalBad2:
optional: Optional[int] = option("--optional", required=True) optional: int | None = option("--optional", required=True)
def run(self) -> None: ... def run(self) -> None: ...
@@ -252,13 +252,13 @@ def test_typing() -> None:
@chia_command(group=cmd, name="temp_cmd_optional_bad", short_help="blah", help="n/a") @chia_command(group=cmd, name="temp_cmd_optional_bad", short_help="blah", help="n/a")
class TempCMDOptionalBad3: class TempCMDOptionalBad3:
optional: Optional[int] = option("--optional", default="string", required=False) optional: int | None = option("--optional", default="string", required=False)
def run(self) -> None: ... def run(self) -> None: ...
@chia_command(group=cmd, name="temp_cmd_optional_fine", short_help="blah", help="n/a") @chia_command(group=cmd, name="temp_cmd_optional_fine", short_help="blah", help="n/a")
class TempCMDOptionalBad4: class TempCMDOptionalBad4:
optional: Optional[int] = option("--optional", default=None, required=False) optional: int | None = option("--optional", default=None, required=False)
def run(self) -> None: ... def run(self) -> None: ...
+3 -3
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
import sys import sys
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any
import pytest import pytest
from _pytest.capture import CaptureFixture from _pytest.capture import CaptureFixture
@@ -33,10 +33,10 @@ async def test_daemon(
class DummyKeychain: class DummyKeychain:
@staticmethod @staticmethod
def get_cached_master_passphrase() -> Optional[str]: def get_cached_master_passphrase() -> str | None:
return None return None
def get_current_passphrase() -> Optional[str]: def get_current_passphrase() -> str | None:
return "a-passphrase" return "a-passphrase"
mocker.patch("chia.cmds.start_funcs.connect_to_daemon_and_validate", side_effect=connect_to_daemon_and_validate) mocker.patch("chia.cmds.start_funcs.connect_to_daemon_and_validate", side_effect=connect_to_daemon_and_validate)
+4 -4
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any
from chia_rs import FoliageTransactionBlock, FullBlock from chia_rs import FoliageTransactionBlock, FullBlock
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -16,7 +16,7 @@ from chia.types.blockchain_format.serialized_program import SerializedProgram
@dataclass @dataclass
class ShowFullNodeRpcClient(TestFullNodeRpcClient): class ShowFullNodeRpcClient(TestFullNodeRpcClient):
async def get_fee_estimate(self, target_times: Optional[list[int]], cost: Optional[int]) -> dict[str, Any]: async def get_fee_estimate(self, target_times: list[int] | None, cost: int | None) -> dict[str, Any]:
self.add_to_log("get_fee_estimate", (target_times, cost)) self.add_to_log("get_fee_estimate", (target_times, cost))
response: dict[str, Any] = { response: dict[str, Any] = {
"current_fee_rate": 0, "current_fee_rate": 0,
@@ -38,7 +38,7 @@ class ShowFullNodeRpcClient(TestFullNodeRpcClient):
} }
return response return response
async def get_block(self, header_hash: bytes32) -> Optional[FullBlock]: async def get_block(self, header_hash: bytes32) -> FullBlock | None:
# we return a block with the height matching the header hash # we return a block with the height matching the header hash
self.add_to_log("get_block", (header_hash,)) self.add_to_log("get_block", (header_hash,))
height = hash_to_height(header_hash) height = hash_to_height(header_hash)
@@ -106,7 +106,7 @@ def test_chia_show(capsys: object, get_test_cli_clients: tuple[TestRpcClients, P
"Is a Transaction Block?True", "Is a Transaction Block?True",
] ]
run_cli_command_and_assert(capsys, root_dir, command_args, assert_list) run_cli_command_and_assert(capsys, root_dir, command_args, assert_list)
expected_calls: dict[str, Optional[list[tuple[Any, ...]]]] = { # name of rpc: (args) expected_calls: dict[str, list[tuple[Any, ...]] | None] = { # name of rpc: (args)
"get_blockchain_state": None, "get_blockchain_state": None,
"get_block_record": [(height_hash(height),) for height in [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 11, 10]], "get_block_record": [(height_hash(height),) for height in [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 11, 10]],
"get_block_record_by_height": [(10,)], "get_block_record_by_height": [(10,)],
+1 -2
View File
@@ -2,7 +2,6 @@ from __future__ import annotations
from collections.abc import Sequence from collections.abc import Sequence
from pathlib import Path from pathlib import Path
from typing import Optional
import click import click
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -102,7 +101,7 @@ def test_tx_config_args() -> None:
max_coin_amount: CliAmount, max_coin_amount: CliAmount,
coins_to_exclude: Sequence[bytes32], coins_to_exclude: Sequence[bytes32],
amounts_to_exclude: Sequence[CliAmount], amounts_to_exclude: Sequence[CliAmount],
reuse: Optional[bool], reuse: bool | None,
) -> None: ) -> None:
print( print(
CMDTXConfigLoader( CMDTXConfigLoader(
+4 -5
View File
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint8, uint32, uint64 from chia_rs.sized_ints import uint8, uint32, uint64
@@ -17,10 +16,10 @@ class TestBlockRecord:
header_hash: bytes32 header_hash: bytes32
height: uint32 height: uint32
timestamp: Optional[uint64] timestamp: uint64 | None
prev_transaction_block_height: uint32 prev_transaction_block_height: uint32
prev_transaction_block_hash: Optional[bytes32] prev_transaction_block_hash: bytes32 | None
prev_hash: Optional[bytes32] prev_hash: bytes32 | None
weight: uint64 = uint64(10000) weight: uint64 = uint64(10000)
fees: uint64 = uint64(5000) fees: uint64 = uint64(5000)
farmer_puzzle_hash: bytes32 = bytes32([1] * 32) farmer_puzzle_hash: bytes32 = bytes32([1] * 32)
@@ -43,7 +42,7 @@ def hash_to_height(int_bytes: bytes32) -> int:
def create_test_block_record( def create_test_block_record(
*, height: uint32 = uint32(11), timestamp: uint64 = uint64(10040), header_hash: Optional[bytes32] = None *, height: uint32 = uint32(11), timestamp: uint64 = uint64(10040), header_hash: bytes32 | None = None
) -> TestBlockRecord: ) -> TestBlockRecord:
if header_hash is None: if header_hash is None:
header_hash = height_hash(height) header_hash = height_hash(height)
+3 -4
View File
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import Optional, Union
import pytest import pytest
from chia_rs import G2Element from chia_rs import G2Element
@@ -62,12 +61,12 @@ def test_did_create(capsys: object, get_test_cli_clients: tuple[TestRpcClients,
amount: int, amount: int,
tx_config: TXConfig, tx_config: TXConfig,
fee: int = 0, fee: int = 0,
name: Optional[str] = "DID Wallet", name: str | None = "DID Wallet",
backup_ids: Optional[list[str]] = None, backup_ids: list[str] | None = None,
required_num: int = 0, required_num: int = 0,
push: bool = True, push: bool = True,
timelock_info: ConditionValidTimes = ConditionValidTimes(), timelock_info: ConditionValidTimes = ConditionValidTimes(),
) -> dict[str, Union[str, int]]: ) -> dict[str, str | int]:
if backup_ids is None: if backup_ids is None:
backup_ids = [] backup_ids = []
self.add_to_log( self.add_to_log(
+2 -2
View File
@@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any
from chia_rs import G2Element from chia_rs import G2Element
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -40,7 +40,7 @@ def test_nft_create(capsys: object, get_test_cli_clients: tuple[TestRpcClients,
# set RPC Client # set RPC Client
class NFTCreateRpcClient(TestWalletRpcClient): class NFTCreateRpcClient(TestWalletRpcClient):
async def create_new_nft_wallet(self, did_id: str, name: Optional[str] = None) -> dict[str, Any]: async def create_new_nft_wallet(self, did_id: str, name: str | None = None) -> dict[str, Any]:
self.add_to_log("create_new_nft_wallet", (did_id, name)) self.add_to_log("create_new_nft_wallet", (did_id, name))
return {"wallet_id": 4} return {"wallet_id": 4}
+4 -4
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import datetime import datetime
import os import os
from pathlib import Path from pathlib import Path
from typing import Any, Optional, Union from typing import Any
import importlib_resources import importlib_resources
import pytest import pytest
@@ -302,8 +302,8 @@ def test_show(capsys: object, get_test_cli_clients: tuple[TestRpcClients, Path])
return NFTGetWalletDIDResponse("did:chia:1qgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpq4msw0c") return NFTGetWalletDIDResponse("did:chia:1qgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpq4msw0c")
async def get_connections( async def get_connections(
self, node_type: Optional[NodeType] = None self, node_type: NodeType | None = None
) -> list[dict[str, Union[str, int, float, bytes32]]]: ) -> list[dict[str, str | int | float | bytes32]]:
self.add_to_log("get_connections", (node_type,)) self.add_to_log("get_connections", (node_type,))
return [ return [
{ {
@@ -950,7 +950,7 @@ def test_get_offers(capsys: object, get_test_cli_clients: tuple[TestRpcClients,
self, self,
start: int = 0, start: int = 0,
end: int = 50, end: int = 50,
sort_key: Optional[str] = None, sort_key: str | None = None,
reverse: bool = False, reverse: bool = False,
file_contents: bool = False, file_contents: bool = False,
exclude_my_offers: bool = False, exclude_my_offers: bool = False,
+5 -5
View File
@@ -12,9 +12,9 @@ import os
import random import random
import sysconfig import sysconfig
import tempfile import tempfile
from collections.abc import AsyncIterator, Iterator from collections.abc import AsyncIterator, Callable, Iterator
from contextlib import AsyncExitStack from contextlib import AsyncExitStack
from typing import Any, Callable, Union from typing import Any
import aiohttp import aiohttp
import pytest import pytest
@@ -800,7 +800,7 @@ async def one_node(
@pytest.fixture(scope="function") @pytest.fixture(scope="function")
async def one_node_one_block( async def one_node_one_block(
blockchain_constants: ConsensusConstants, blockchain_constants: ConsensusConstants,
) -> AsyncIterator[tuple[Union[FullNodeAPI, FullNodeSimulator], ChiaServer, BlockTools]]: ) -> AsyncIterator[tuple[FullNodeAPI | FullNodeSimulator, ChiaServer, BlockTools]]:
async with setup_simulators_and_wallets(1, 0, blockchain_constants) as new: async with setup_simulators_and_wallets(1, 0, blockchain_constants) as new:
(nodes, _, bt) = make_old_setup_simulators_and_wallets(new=new) (nodes, _, bt) = make_old_setup_simulators_and_wallets(new=new)
full_node_1 = nodes[0] full_node_1 = nodes[0]
@@ -1272,8 +1272,8 @@ async def farmer_harvester_2_simulators_zero_bits_plot_filter(
tuple[ tuple[
FarmerService, FarmerService,
HarvesterService, HarvesterService,
Union[FullNodeService, SimulatorFullNodeService], FullNodeService | SimulatorFullNodeService,
Union[FullNodeService, SimulatorFullNodeService], FullNodeService | SimulatorFullNodeService,
BlockTools, BlockTools,
] ]
]: ]:
+4 -4
View File
@@ -1,8 +1,8 @@
from __future__ import annotations from __future__ import annotations
import zipfile import zipfile
from collections.abc import Callable
from pathlib import Path from pathlib import Path
from typing import Callable, Optional
import pytest import pytest
from click.testing import CliRunner, Result from click.testing import CliRunner, Result
@@ -26,7 +26,7 @@ def configure(root_path: Path, *args: str) -> Result:
) )
def configure_interactive(root_path: Path, user_input: Optional[str] = None) -> Result: def configure_interactive(root_path: Path, user_input: str | None = None) -> Result:
return CliRunner().invoke( return CliRunner().invoke(
cli, cli,
[ [
@@ -53,7 +53,7 @@ def enable(root_path: Path, *args: str) -> Result:
) )
def enable_interactive(root_path: Path, user_input: Optional[str] = None) -> Result: def enable_interactive(root_path: Path, user_input: str | None = None) -> Result:
return CliRunner().invoke( return CliRunner().invoke(
cli, cli,
[ [
@@ -66,7 +66,7 @@ def enable_interactive(root_path: Path, user_input: Optional[str] = None) -> Res
) )
def prepare_submission(root_path: Path, user_input: Optional[str] = None) -> Result: def prepare_submission(root_path: Path, user_input: str | None = None) -> Result:
return CliRunner().invoke( return CliRunner().invoke(
cli, cli,
[ [
+2 -3
View File
@@ -4,7 +4,6 @@ import json
import os import os
import re import re
from pathlib import Path from pathlib import Path
from typing import Optional
import pytest import pytest
from click.testing import CliRunner, Result from click.testing import CliRunner, Result
@@ -54,7 +53,7 @@ def setup_keyringwrapper(tmp_path):
KeyringWrapper.set_keys_root_path(DEFAULT_KEYS_ROOT_PATH) KeyringWrapper.set_keys_root_path(DEFAULT_KEYS_ROOT_PATH)
def assert_label(keychain: Keychain, label: Optional[str], index: int) -> None: def assert_label(keychain: Keychain, label: str | None, index: int) -> None:
all_keys = keychain.get_keys() all_keys = keychain.get_keys()
assert len(all_keys) > index assert len(all_keys) > index
assert all_keys[index].label == label assert all_keys[index].label == label
@@ -200,7 +199,7 @@ class TestKeysCommands:
], ],
) )
def test_generate_and_add_label_parameter( def test_generate_and_add_label_parameter(
self, cmd_params: list[str], label: Optional[str], input_str: Optional[str], tmp_path, empty_keyring self, cmd_params: list[str], label: str | None, input_str: str | None, tmp_path, empty_keyring
): ):
keychain = empty_keyring keychain = empty_keyring
keys_root_path = keychain.keyring_wrapper.keys_root_path keys_root_path = keychain.keyring_wrapper.keys_root_path
@@ -3,7 +3,6 @@ from __future__ import annotations
import logging import logging
import random import random
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional
import pytest import pytest
from chia_rs import G1Element, PlotParam from chia_rs import G1Element, PlotParam
@@ -28,10 +27,10 @@ class ProofOfSpaceCase:
pos_challenge: bytes32 pos_challenge: bytes32
plot_size: PlotParam plot_size: PlotParam
plot_public_key: G1Element plot_public_key: G1Element
pool_public_key: Optional[G1Element] = None pool_public_key: G1Element | None = None
pool_contract_puzzle_hash: Optional[bytes32] = None pool_contract_puzzle_hash: bytes32 | None = None
height: uint32 = DEFAULT_CONSTANTS.HARD_FORK2_HEIGHT height: uint32 = DEFAULT_CONSTANTS.HARD_FORK2_HEIGHT
expected_error: Optional[str] = None expected_error: str | None = None
marks: Marks = () marks: Marks = ()
+8 -8
View File
@@ -5,7 +5,7 @@ import json
import logging import logging
from dataclasses import dataclass, field, replace from dataclasses import dataclass, field, replace
from pathlib import Path from pathlib import Path
from typing import Any, Optional, Union, cast from typing import Any, cast
import aiohttp import aiohttp
import pytest import pytest
@@ -94,7 +94,7 @@ class ChiaPlottersBladebitArgsCase:
pool_contract: str = "txch1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" pool_contract: str = "txch1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
compress: int = 1 compress: int = 1
device: int = 0 device: int = 0
hybrid_disk_mode: Optional[int] = None hybrid_disk_mode: int | None = None
farmer_pk: str = "" farmer_pk: str = ""
final_dir: str = "" final_dir: str = ""
marks: Marks = () marks: Marks = ()
@@ -147,7 +147,7 @@ class ChiaPlottersBladebitArgsCase:
class Service: class Service:
running: bool running: bool
def poll(self) -> Optional[int]: def poll(self) -> int | None:
return None if self.running else 1 return None if self.running else 1
@@ -155,8 +155,8 @@ class Service:
@dataclass @dataclass
class Daemon: class Daemon:
# Instance variables used by WebSocketServer.is_running() # Instance variables used by WebSocketServer.is_running()
services: dict[str, Union[list[Service], Service]] services: dict[str, list[Service] | Service]
connections: dict[str, Optional[list[Any]]] connections: dict[str, list[Any] | None]
# Instance variables used by WebSocketServer.get_wallet_addresses() # Instance variables used by WebSocketServer.get_wallet_addresses()
net_config: dict[str, Any] = field(default_factory=dict) net_config: dict[str, Any] = field(default_factory=dict)
@@ -314,9 +314,9 @@ label_newline_or_tab_response_data = {
def assert_response( def assert_response(
response: aiohttp.http_websocket.WSMessage, response: aiohttp.http_websocket.WSMessage,
expected_response_data: dict[str, Any], expected_response_data: dict[str, Any],
request_id: Optional[str] = None, request_id: str | None = None,
ack: bool = True, ack: bool = True,
command: Optional[str] = None, command: str | None = None,
) -> None: ) -> None:
# Expect: JSON response # Expect: JSON response
assert response.type == aiohttp.WSMsgType.TEXT assert response.type == aiohttp.WSMsgType.TEXT
@@ -332,7 +332,7 @@ def assert_response(
def assert_response_success_only( def assert_response_success_only(
response: aiohttp.http_websocket.WSMessage, request_id: Optional[str] = None response: aiohttp.http_websocket.WSMessage, request_id: str | None = None
) -> dict[str, Any]: ) -> dict[str, Any]:
# Expect: JSON response # Expect: JSON response
assert response.type == aiohttp.WSMsgType.TEXT assert response.type == aiohttp.WSMsgType.TEXT
+2 -2
View File
@@ -4,8 +4,8 @@ import os
import pathlib import pathlib
import sys import sys
import time import time
from collections.abc import AsyncIterable, Awaitable, Iterator from collections.abc import AsyncIterable, Awaitable, Callable, Iterator
from typing import Any, Callable from typing import Any
import pytest import pytest
+8 -8
View File
@@ -16,7 +16,7 @@ from copy import deepcopy
from dataclasses import dataclass from dataclasses import dataclass
from enum import IntEnum from enum import IntEnum
from pathlib import Path from pathlib import Path
from typing import Any, Optional, cast from typing import Any, cast
import anyio import anyio
import chia_rs.datalayer import chia_rs.datalayer
@@ -96,10 +96,10 @@ class InterfaceLayer(enum.Enum):
async def init_data_layer_service( async def init_data_layer_service(
wallet_rpc_port: uint16, wallet_rpc_port: uint16,
bt: BlockTools, bt: BlockTools,
db_path: Optional[Path] = None, db_path: Path | None = None,
wallet_service: Optional[WalletService] = None, wallet_service: WalletService | None = None,
manage_data_interval: int = 5, manage_data_interval: int = 5,
maximum_full_file_count: Optional[int] = None, maximum_full_file_count: int | None = None,
enable_batch_autoinsert: bool = True, enable_batch_autoinsert: bool = True,
group_files_by_store: bool = False, group_files_by_store: bool = False,
) -> AsyncIterator[DataLayerService]: ) -> AsyncIterator[DataLayerService]:
@@ -130,9 +130,9 @@ async def init_data_layer(
wallet_rpc_port: uint16, wallet_rpc_port: uint16,
bt: BlockTools, bt: BlockTools,
db_path: Path, db_path: Path,
wallet_service: Optional[WalletService] = None, wallet_service: WalletService | None = None,
manage_data_interval: int = 5, manage_data_interval: int = 5,
maximum_full_file_count: Optional[int] = None, maximum_full_file_count: int | None = None,
group_files_by_store: bool = False, group_files_by_store: bool = False,
enable_batch_autoinsert: bool = True, enable_batch_autoinsert: bool = True,
) -> AsyncIterator[DataLayer]: ) -> AsyncIterator[DataLayer]:
@@ -1033,7 +1033,7 @@ async def process_for_data_layer_keys(
full_node_api: FullNodeSimulator, full_node_api: FullNodeSimulator,
data_layer: DataLayer, data_layer: DataLayer,
store_id: bytes32, store_id: bytes32,
expected_value: Optional[bytes] = None, expected_value: bytes | None = None,
) -> None: ) -> None:
for sleep_time in backoff_times(): for sleep_time in backoff_times():
try: try:
@@ -3067,7 +3067,7 @@ async def test_pagination_cmds(
one_wallet_and_one_simulator_services: SimulatorsAndWalletsServices, one_wallet_and_one_simulator_services: SimulatorsAndWalletsServices,
tmp_path: Path, tmp_path: Path,
layer: InterfaceLayer, layer: InterfaceLayer,
max_page_size: Optional[int], max_page_size: int | None,
bt: BlockTools, bt: BlockTools,
) -> None: ) -> None:
wallet_rpc_api, full_node_api, wallet_rpc_port, ph, bt = await init_wallet_and_node( wallet_rpc_api, full_node_api, wallet_rpc_port, ph, bt = await init_wallet_and_node(
+10 -10
View File
@@ -10,12 +10,12 @@ import re
import shutil import shutil
import statistics import statistics
import time import time
from collections.abc import Awaitable from collections.abc import Awaitable, Callable
from dataclasses import dataclass from dataclasses import dataclass
from hashlib import sha256 from hashlib import sha256
from pathlib import Path from pathlib import Path
from random import Random from random import Random
from typing import Any, BinaryIO, Callable, Optional from typing import Any, BinaryIO
import aiohttp import aiohttp
import chia_rs.datalayer import chia_rs.datalayer
@@ -290,7 +290,7 @@ async def test_get_ancestors_optimized(data_store: DataStore, store_id: bytes32)
node_count = 0 node_count = 0
node_hashes: list[bytes32] = [] node_hashes: list[bytes32] = []
hash_to_key: dict[bytes32, bytes] = {} hash_to_key: dict[bytes32, bytes] = {}
node_hash: Optional[bytes32] node_hash: bytes32 | None
for i in range(1000): for i in range(1000):
is_insert = False is_insert = False
@@ -1223,7 +1223,7 @@ async def test_server_http_ban(
async def mock_http_download( async def mock_http_download(
target_filename_path: Path, target_filename_path: Path,
filename: str, filename: str,
proxy_url: Optional[str], proxy_url: str | None,
server_info: ServerInfo, server_info: ServerInfo,
timeout: aiohttp.ClientTimeout, timeout: aiohttp.ClientTimeout,
log: logging.Logger, log: logging.Logger,
@@ -1278,7 +1278,7 @@ async def test_server_http_ban(
assert sinfo.ignore_till == start_timestamp # we don't increase on second failure assert sinfo.ignore_till == start_timestamp # we don't increase on second failure
async def get_first_generation(data_store: DataStore, node_hash: bytes32, store_id: bytes32) -> Optional[int]: async def get_first_generation(data_store: DataStore, node_hash: bytes32, store_id: bytes32) -> int | None:
async with data_store.db_wrapper.reader() as reader: async with data_store.db_wrapper.reader() as reader:
cursor = await reader.execute( cursor = await reader.execute(
"SELECT generation FROM nodes WHERE hash = ? AND store_id = ?", "SELECT generation FROM nodes WHERE hash = ? AND store_id = ?",
@@ -1301,8 +1301,8 @@ async def write_tree_to_file_old_format(
node_hash: bytes32, node_hash: bytes32,
store_id: bytes32, store_id: bytes32,
writer: BinaryIO, writer: BinaryIO,
merkle_blob: Optional[MerkleBlob] = None, merkle_blob: MerkleBlob | None = None,
hash_to_index: Optional[dict[bytes32, TreeIndex]] = None, hash_to_index: dict[bytes32, TreeIndex] | None = None,
) -> None: ) -> None:
if node_hash == bytes32.zeros: if node_hash == bytes32.zeros:
return return
@@ -1760,7 +1760,7 @@ async def test_insert_from_delta_file(
async def mock_http_download( async def mock_http_download(
target_filename_path: Path, target_filename_path: Path,
filename: str, filename: str,
proxy_url: Optional[str], proxy_url: str | None,
server_info: ServerInfo, server_info: ServerInfo,
timeout: int, timeout: int,
log: logging.Logger, log: logging.Logger,
@@ -1770,7 +1770,7 @@ async def test_insert_from_delta_file(
async def mock_http_download_2( async def mock_http_download_2(
target_filename_path: Path, target_filename_path: Path,
filename: str, filename: str,
proxy_url: Optional[str], proxy_url: str | None,
server_info: ServerInfo, server_info: ServerInfo,
timeout: int, timeout: int,
log: logging.Logger, log: logging.Logger,
@@ -2180,7 +2180,7 @@ async def test_basic_key_value_db_vs_disk_cutoff(
) as cursor: ) as cursor:
row = await cursor.fetchone() row = await cursor.fetchone()
assert row is not None assert row is not None
db_blob: Optional[bytes] = row["blob"] db_blob: bytes | None = row["blob"]
if size_offset <= 0: if size_offset <= 0:
assert not file_exists assert not file_exists
+10 -10
View File
@@ -8,7 +8,7 @@ import shutil
import subprocess import subprocess
from collections.abc import Iterator from collections.abc import Iterator
from dataclasses import dataclass from dataclasses import dataclass
from typing import IO, TYPE_CHECKING, Any, Literal, Optional, Union, overload from typing import IO, TYPE_CHECKING, Any, Literal, overload
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -34,8 +34,8 @@ async def general_insert(
store_id: bytes32, store_id: bytes32,
key: bytes, key: bytes,
value: bytes, value: bytes,
reference_node_hash: Optional[bytes32], reference_node_hash: bytes32 | None,
side: Optional[Side], side: Side | None,
) -> bytes32: ) -> bytes32:
insert_result = await data_store.insert( insert_result = await data_store.insert(
key=key, key=key,
@@ -123,12 +123,12 @@ class ChiaRoot:
def run( def run(
self, self,
args: list[Union[str, os_PathLike_str]], args: list[str | os_PathLike_str],
*other_args: Any, *other_args: Any,
check: bool = True, check: bool = True,
encoding: str = "utf-8", encoding: str = "utf-8",
stdout: Optional[_FILE] = subprocess.PIPE, stdout: _FILE | None = subprocess.PIPE,
stderr: Optional[_FILE] = subprocess.PIPE, stderr: _FILE | None = subprocess.PIPE,
**kwargs: Any, **kwargs: Any,
) -> subprocess_CompletedProcess_str: ) -> subprocess_CompletedProcess_str:
# TODO: --root-path doesn't seem to work here... # TODO: --root-path doesn't seem to work here...
@@ -143,7 +143,7 @@ class ChiaRoot:
chia_executable = shutil.which("chia") chia_executable = shutil.which("chia")
if chia_executable is None: if chia_executable is None:
chia_executable = "chia" chia_executable = "chia"
modified_args: list[Union[str, os_PathLike_str]] = [ modified_args: list[str | os_PathLike_str] = [
self.scripts_path.joinpath(chia_executable), self.scripts_path.joinpath(chia_executable),
"--root-path", "--root-path",
self.path, self.path,
@@ -166,7 +166,7 @@ class ChiaRoot:
return self.path.joinpath("log", "debug.log").read_text(encoding="utf-8") return self.path.joinpath("log", "debug.log").read_text(encoding="utf-8")
def print_log(self) -> None: def print_log(self) -> None:
log_text: Optional[str] log_text: str | None
try: try:
log_text = self.read_log() log_text = self.read_log()
@@ -204,8 +204,8 @@ def create_valid_node_values(
def create_valid_node_values( def create_valid_node_values(
node_type: NodeType, node_type: NodeType,
left_hash: Optional[bytes32] = None, left_hash: bytes32 | None = None,
right_hash: Optional[bytes32] = None, right_hash: bytes32 | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
if node_type == NodeType.INTERNAL: if node_type == NodeType.INTERNAL:
assert left_hash is not None assert left_hash is not None
+2 -4
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
from asyncio import Task, gather, sleep from asyncio import Task, gather, sleep
from collections.abc import Coroutine from collections.abc import Coroutine
from typing import Any, Optional, TypeVar from typing import Any, TypeVar
import pytest import pytest
from chia_rs.sized_ints import uint8, uint32, uint64 from chia_rs.sized_ints import uint8, uint32, uint64
@@ -80,9 +80,7 @@ async def test_farmer_responds_with_signed_values(farmer_one_harvester: FarmerOn
) )
setattr(farmer_api, "_process_respond_signatures", lambda res: signed_values) setattr(farmer_api, "_process_respond_signatures", lambda res: signed_values)
signed_values_task: Task[Optional[Message]] = await begin_task( signed_values_task: Task[Message | None] = await begin_task(farmer_api.request_signed_values(request_signed_values))
farmer_api.request_signed_values(request_signed_values)
)
# Wait a bit for the dummy harvester to receive the signature request and respond with a dummy signature # Wait a bit for the dummy harvester to receive the signature request and respond with a dummy signature
await sleep(1) await sleep(1)
@@ -5,7 +5,7 @@ import logging
import random import random
import sqlite3 import sqlite3
from pathlib import Path from pathlib import Path
from typing import Optional, cast from typing import cast
import pytest import pytest
@@ -41,7 +41,7 @@ def use_cache(request: SubRequest) -> bool:
return cast(bool, request.param) return cast(bool, request.param)
def maybe_serialize(gen: Optional[SerializedProgram]) -> Optional[bytes]: def maybe_serialize(gen: SerializedProgram | None) -> bytes | None:
if gen is None: if gen is None:
return None return None
else: else:
@@ -3,7 +3,6 @@ from __future__ import annotations
import logging import logging
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Optional
import aiosqlite import aiosqlite
import pytest import pytest
@@ -236,7 +235,7 @@ async def test_rollback(db_version: int, bt: BlockTools) -> None:
async with DBConnection(db_version) as db_wrapper: async with DBConnection(db_version) as db_wrapper:
coin_store = await CoinStore.create(db_wrapper) coin_store = await CoinStore.create(db_wrapper)
selected_coin: Optional[CoinRecord] = None selected_coin: CoinRecord | None = None
all_coins: list[Coin] = [] all_coins: list[Coin] = []
for block in blocks: for block in blocks:
@@ -320,7 +319,7 @@ async def test_basic_reorg(tmp_dir: Path, db_version: int, bt: BlockTools) -> No
height_map = await BlockHeightMap.create(tmp_dir, db_wrapper) height_map = await BlockHeightMap.create(tmp_dir, db_wrapper)
b: Blockchain = await Blockchain.create(coin_store, store, height_map, bt.constants, 2) b: Blockchain = await Blockchain.create(coin_store, store, height_map, bt.constants, 2)
try: try:
records: list[Optional[CoinRecord]] = [] records: list[CoinRecord | None] = []
for block in blocks: for block in blocks:
await _validate_and_add_block(b, block) await _validate_and_add_block(b, block)
@@ -570,7 +569,7 @@ async def test_coin_state_batches(
continue continue
expected_crs.append(cr) expected_crs.append(cr)
height: Optional[uint32] = uint32(0) height: uint32 | None = uint32(0)
all_coin_states: list[CoinState] = [] all_coin_states: list[CoinState] = []
remaining_phs = random_coin_records.puzzle_hashes.copy() remaining_phs = random_coin_records.puzzle_hashes.copy()
@@ -3,7 +3,6 @@ from __future__ import annotations
import logging import logging
import random import random
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from typing import Optional
import pytest import pytest
from chia_rs import ConsensusConstants, FullBlock, UnfinishedBlock from chia_rs import ConsensusConstants, FullBlock, UnfinishedBlock
@@ -128,15 +127,15 @@ async def test_unfinished_block_rank(
) )
async def test_find_best_block( async def test_find_best_block(
seeded_random: random.Random, seeded_random: random.Random,
blocks: list[tuple[Optional[int], bool]], blocks: list[tuple[int | None, bool]],
expected: Optional[int], expected: int | None,
default_400_blocks: list[FullBlock], default_400_blocks: list[FullBlock],
bt: BlockTools, bt: BlockTools,
) -> None: ) -> None:
result: dict[Optional[bytes32], UnfinishedBlockEntry] = {} result: dict[bytes32 | None, UnfinishedBlockEntry] = {}
i = 0 i = 0
for b, with_unf in blocks: for b, with_unf in blocks:
unf: Optional[UnfinishedBlock] unf: UnfinishedBlock | None
if with_unf: if with_unf:
unf = make_unfinished_block(default_400_blocks[i], bt.constants) unf = make_unfinished_block(default_400_blocks[i], bt.constants)
i += 1 i += 1
@@ -1022,10 +1021,10 @@ async def test_basic_store(
and i1 > (i2 + 3) and i1 > (i2 + 3)
): ):
# We hit all the conditions that we want # We hit all the conditions that we want
all_sps: list[Optional[SignagePoint]] = [None] * custom_block_tools.constants.NUM_SPS_SUB_SLOT all_sps: list[SignagePoint | None] = [None] * custom_block_tools.constants.NUM_SPS_SUB_SLOT
def assert_sp_none(sp_index: int, is_none: bool) -> None: def assert_sp_none(sp_index: int, is_none: bool) -> None:
sp_to_check: Optional[SignagePoint] = all_sps[sp_index] sp_to_check: SignagePoint | None = all_sps[sp_index]
assert sp_to_check is not None assert sp_to_check is not None
assert sp_to_check.cc_vdf is not None assert sp_to_check.cc_vdf is not None
fetched = store.get_signage_point(sp_to_check.cc_vdf.output.get_hash()) fetched = store.get_signage_point(sp_to_check.cc_vdf.output.get_hash())
@@ -3,7 +3,6 @@ from __future__ import annotations
import os import os
import struct import struct
from pathlib import Path from pathlib import Path
from typing import Optional
import pytest import pytest
from chia_rs import SubEpochSummary from chia_rs import SubEpochSummary
@@ -27,7 +26,7 @@ def gen_ses(height: int) -> SubEpochSummary:
async def new_block( async def new_block(
db: DBWrapper2, block_hash: bytes32, parent: bytes32, height: int, is_peak: bool, ses: Optional[SubEpochSummary] db: DBWrapper2, block_hash: bytes32, parent: bytes32, height: int, is_peak: bool, ses: SubEpochSummary | None
) -> None: ) -> None:
async with db.writer_maybe_transaction() as conn: async with db.writer_maybe_transaction() as conn:
cursor = await conn.execute( cursor = await conn.execute(
@@ -67,7 +66,7 @@ async def setup_db(db: DBWrapper2) -> None:
# and the chain_id will be mixed in to the hashes, to form a separate chain at # and the chain_id will be mixed in to the hashes, to form a separate chain at
# the same heights as the main chain # the same heights as the main chain
async def setup_chain( async def setup_chain(
db: DBWrapper2, length: int, *, chain_id: int = 0, ses_every: Optional[int] = None, start_height: int = 0 db: DBWrapper2, length: int, *, chain_id: int = 0, ses_every: int | None = None, start_height: int = 0
) -> None: ) -> None:
height = start_height height = start_height
peak_hash = gen_block_hash(height + chain_id * 65536) peak_hash = gen_block_hash(height + chain_id * 65536)
@@ -6,7 +6,6 @@ or that they're failing for the right reason when they're invalid.
from __future__ import annotations from __future__ import annotations
import logging import logging
from typing import Optional
import pytest import pytest
from chia_rs import AugSchemeMPL, FullBlock, G2Element, SpendBundle from chia_rs import AugSchemeMPL, FullBlock, G2Element, SpendBundle
@@ -59,7 +58,7 @@ async def check_spend_bundle_validity(
bt: BlockTools, bt: BlockTools,
blocks: list[FullBlock], blocks: list[FullBlock],
spend_bundle: SpendBundle, spend_bundle: SpendBundle,
expected_err: Optional[Err] = None, expected_err: Err | None = None,
) -> tuple[list[CoinRecord], list[CoinRecord], FullBlock]: ) -> tuple[list[CoinRecord], list[CoinRecord], FullBlock]:
""" """
This test helper create an extra block after the given blocks that contains the given This test helper create an extra block after the given blocks that contains the given
@@ -96,7 +95,7 @@ async def check_spend_bundle_validity(
async def check_conditions( async def check_conditions(
bt: BlockTools, bt: BlockTools,
condition_solution: Program, condition_solution: Program,
expected_err: Optional[Err] = None, expected_err: Err | None = None,
spend_reward_index: int = -2, spend_reward_index: int = -2,
*, *,
aggsig: G2Element = G2Element(), aggsig: G2Element = G2Element(),
@@ -366,7 +365,7 @@ class TestConditions:
condition1: str, condition1: str,
condition2: str, condition2: str,
num: int, num: int,
expect_err: Optional[Err], expect_err: Err | None,
bt: BlockTools, bt: BlockTools,
) -> None: ) -> None:
""" """
@@ -446,7 +445,7 @@ class TestConditions:
], ],
) )
async def test_message_conditions( async def test_message_conditions(
self, bt: BlockTools, consensus_mode: ConsensusMode, conds: str, expected: Optional[Err] self, bt: BlockTools, consensus_mode: ConsensusMode, conds: str, expected: Err | None
) -> None: ) -> None:
blocks = await initial_blocks(bt) blocks = await initial_blocks(bt)
coin = blocks[-2].get_included_reward_coins()[0] coin = blocks[-2].get_included_reward_coins()[0]
+7 -7
View File
@@ -7,7 +7,7 @@ import logging
import random import random
import time import time
from collections.abc import Awaitable, Coroutine from collections.abc import Awaitable, Coroutine
from typing import Any, Optional from typing import Any
import pytest import pytest
from chia_rs import ( from chia_rs import (
@@ -246,7 +246,7 @@ async def test_block_compression(
await time_out_assert(30, check_transaction_confirmed, True, tr) await time_out_assert(30, check_transaction_confirmed, True, tr)
# Confirm generator is not compressed # Confirm generator is not compressed
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator program: SerializedProgram | None = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None assert program is not None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) == 0 assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) == 0
@@ -993,7 +993,7 @@ async def test_new_transaction_and_mempool(
included_tx = 0 included_tx = 0
not_included_tx = 0 not_included_tx = 0
seen_bigger_transaction_has_high_fee = False seen_bigger_transaction_has_high_fee = False
successful_bundle: Optional[WalletSpendBundle] = None successful_bundle: WalletSpendBundle | None = None
# Fill mempool # Fill mempool
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash() receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
@@ -1473,7 +1473,7 @@ async def test_new_unfinished_block2_forward_limit(
unf_blocks: list[UnfinishedBlock] = [] unf_blocks: list[UnfinishedBlock] = []
last_reward_hash: Optional[bytes32] = None last_reward_hash: bytes32 | None = None
for idx in range(6): for idx in range(6):
# we include a different transaction in each block. This makes the # we include a different transaction in each block. This makes the
# foliage different in each of them, but the reward block (plot) the same # foliage different in each of them, but the reward block (plot) the same
@@ -1769,7 +1769,7 @@ async def test_request_unfinished_block2(
# the "best" unfinished block according to the metric we use to pick one # the "best" unfinished block according to the metric we use to pick one
# deterministically # deterministically
best_unf: Optional[UnfinishedBlock] = None best_unf: UnfinishedBlock | None = None
for idx in range(6): for idx in range(6):
# we include a different transaction in each block. This makes the # we include a different transaction in each block. This makes the
@@ -3226,7 +3226,7 @@ async def declare_pos_unfinished_block(
await full_node_api.declare_proof_of_space(pospace, dummy_peer) await full_node_api.declare_proof_of_space(pospace, dummy_peer)
tx_peak = blockchain.get_tx_peak() tx_peak = blockchain.get_tx_peak()
assert tx_peak is not None assert tx_peak is not None
q_str: Optional[bytes32] = verify_and_get_quality_string( q_str: bytes32 | None = verify_and_get_quality_string(
block.reward_chain_block.proof_of_space, block.reward_chain_block.proof_of_space,
blockchain.constants, blockchain.constants,
challenge, challenge,
@@ -3259,7 +3259,7 @@ async def add_tx_to_mempool(
coinbase_puzzlehash: bytes32, coinbase_puzzlehash: bytes32,
receiver_puzzlehash: bytes32, receiver_puzzlehash: bytes32,
amount: uint64, amount: uint64,
) -> Optional[SpendBundle]: ) -> SpendBundle | None:
spend_coin = None spend_coin = None
coins = spend_block.get_included_reward_coins() coins = spend_block.get_included_reward_coins()
for coin in coins: for coin in coins:
@@ -1,7 +1,5 @@
from __future__ import annotations from __future__ import annotations
from typing import Optional
import pytest import pytest
from chia_rs import BlockRecord from chia_rs import BlockRecord
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -38,7 +36,7 @@ async def test_hints_to_add(bt: BlockTools, empty_blockchain: Blockchain) -> Non
blocks = bt.get_consecutive_blocks(2) blocks = bt.get_consecutive_blocks(2)
await _validate_and_add_block(empty_blockchain, blocks[0]) await _validate_and_add_block(empty_blockchain, blocks[0])
await _validate_and_add_block(empty_blockchain, blocks[1]) await _validate_and_add_block(empty_blockchain, blocks[1])
br: Optional[BlockRecord] = empty_blockchain.get_peak() br: BlockRecord | None = empty_blockchain.get_peak()
assert br is not None assert br is not None
scs = StateChangeSummary(br, uint32(0), [], removals, additions, []) scs = StateChangeSummary(br, uint32(0), [], removals, additions, [])
@@ -56,7 +54,7 @@ async def test_lookup_coin_ids(bt: BlockTools, empty_blockchain: Blockchain) ->
blocks = bt.get_consecutive_blocks(2) blocks = bt.get_consecutive_blocks(2)
await _validate_and_add_block(empty_blockchain, blocks[0]) await _validate_and_add_block(empty_blockchain, blocks[0])
await _validate_and_add_block(empty_blockchain, blocks[1]) await _validate_and_add_block(empty_blockchain, blocks[1])
br: Optional[BlockRecord] = empty_blockchain.get_peak() br: BlockRecord | None = empty_blockchain.get_peak()
assert br is not None assert br is not None
rewards: list[Coin] = [ rewards: list[Coin] = [
@@ -1,7 +1,5 @@
from __future__ import annotations from __future__ import annotations
from typing import Optional
from chia_rs import FullBlock from chia_rs import FullBlock
from chia_rs.sized_ints import uint8, uint32 from chia_rs.sized_ints import uint8, uint32
@@ -102,7 +100,7 @@ def test_prev_tx_block_blockrecord_not_tx(bt: BlockTools) -> None:
# get the latest infused transaction block before the signage point of the last block in the list # get the latest infused transaction block before the signage point of the last block in the list
def find_tx_before_sp(block_list: list[FullBlock]) -> Optional[FullBlock]: def find_tx_before_sp(block_list: list[FullBlock]) -> FullBlock | None:
before_slot = False before_slot = False
before_sp = False before_sp = False
if len(block_list[-1].finished_sub_slots) > 0: if len(block_list[-1].finished_sub_slots) > 0:
@@ -2,7 +2,6 @@ from __future__ import annotations
import asyncio import asyncio
import random import random
from typing import Optional
import pytest import pytest
from chia_rs import BlockRecord from chia_rs import BlockRecord
@@ -77,7 +76,7 @@ async def test_tx_propagation(three_nodes_two_wallets, self_hostname, seeded_ran
await time_out_assert(20, wallet_0.wallet_state_manager.main_wallet.get_confirmed_balance, funds) await time_out_assert(20, wallet_0.wallet_state_manager.main_wallet.get_confirmed_balance, funds)
async def peak_height(fna: FullNodeAPI): async def peak_height(fna: FullNodeAPI):
peak: Optional[BlockRecord] = fna.full_node.blockchain.get_peak() peak: BlockRecord | None = fna.full_node.blockchain.get_peak()
if peak is None: if peak is None:
return -1 return -1
peak_height = peak.height peak_height = peak.height
@@ -4,7 +4,7 @@ import asyncio
import logging import logging
import random import random
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional, cast from typing import cast
import pytest import pytest
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -18,10 +18,10 @@ log = logging.getLogger(__name__)
@dataclass(frozen=True) @dataclass(frozen=True)
class FakeTransactionQueueEntry: class FakeTransactionQueueEntry:
index: int index: int
peer_id: Optional[bytes32] peer_id: bytes32 | None
def get_transaction_queue_entry(peer_id: Optional[bytes32], tx_index: int) -> TransactionQueueEntry: # easy shortcut def get_transaction_queue_entry(peer_id: bytes32 | None, tx_index: int) -> TransactionQueueEntry: # easy shortcut
return cast(TransactionQueueEntry, FakeTransactionQueueEntry(index=tx_index, peer_id=peer_id)) return cast(TransactionQueueEntry, FakeTransactionQueueEntry(index=tx_index, peer_id=peer_id))
+15 -15
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import dataclasses import dataclasses
import logging import logging
import random import random
from typing import Callable, Optional from collections.abc import Callable
import pytest import pytest
from chia_rs import ( from chia_rs import (
@@ -100,7 +100,7 @@ def wallet_a(bt: BlockTools) -> WalletTool:
def generate_test_spend_bundle( def generate_test_spend_bundle(
wallet: WalletTool, wallet: WalletTool,
coin: Coin, coin: Coin,
condition_dic: Optional[dict[ConditionOpcode, list[ConditionWithArgs]]] = None, condition_dic: dict[ConditionOpcode, list[ConditionWithArgs]] | None = None,
fee: uint64 = uint64(0), fee: uint64 = uint64(0),
amount: uint64 = uint64(1000), amount: uint64 = uint64(1000),
new_puzzle_hash: bytes32 = BURN_PUZZLE_HASH, new_puzzle_hash: bytes32 = BURN_PUZZLE_HASH,
@@ -350,7 +350,7 @@ async def respond_transaction(
peer: WSChiaConnection, peer: WSChiaConnection,
tx_bytes: bytes = b"", tx_bytes: bytes = b"",
test: bool = False, test: bool = False,
) -> tuple[MempoolInclusionStatus, Optional[Err]]: ) -> tuple[MempoolInclusionStatus, Err | None]:
""" """
Receives a full transaction from peer. Receives a full transaction from peer.
If tx is added to mempool, send tx_id to others. (new_transaction) If tx is added to mempool, send tx_id to others. (new_transaction)
@@ -395,7 +395,7 @@ co = ConditionOpcode
mis = MempoolInclusionStatus mis = MempoolInclusionStatus
async def send_sb(node: FullNodeAPI, sb: SpendBundle) -> Optional[Message]: async def send_sb(node: FullNodeAPI, sb: SpendBundle) -> Message | None:
tx = wallet_protocol.SendTransaction(sb) tx = wallet_protocol.SendTransaction(sb)
return await node.send_transaction(tx, test=True) return await node.send_transaction(tx, test=True)
@@ -716,7 +716,7 @@ class TestMempoolManager:
sb: SpendBundle = generate_test_spend_bundle(wallet_a, coin1) sb: SpendBundle = generate_test_spend_bundle(wallet_a, coin1)
assert sb.aggregated_signature != G2Element.generator() assert sb.aggregated_signature != G2Element.generator()
sb = sb.replace(aggregated_signature=G2Element.generator()) sb = sb.replace(aggregated_signature=G2Element.generator())
res: Optional[Message] = await send_sb(full_node_1, sb) res: Message | None = await send_sb(full_node_1, sb)
assert res is not None assert res is not None
ack: TransactionAck = TransactionAck.from_bytes(res.data) ack: TransactionAck = TransactionAck.from_bytes(res.data)
assert ack.status == MempoolInclusionStatus.FAILED.value assert ack.status == MempoolInclusionStatus.FAILED.value
@@ -730,8 +730,8 @@ class TestMempoolManager:
dic: dict[ConditionOpcode, list[ConditionWithArgs]], dic: dict[ConditionOpcode, list[ConditionWithArgs]],
fee: int = 0, fee: int = 0,
num_blocks: int = 3, num_blocks: int = 3,
coin: Optional[Coin] = None, coin: Coin | None = None,
) -> tuple[list[FullBlock], SpendBundle, WSChiaConnection, MempoolInclusionStatus, Optional[Err]]: ) -> tuple[list[FullBlock], SpendBundle, WSChiaConnection, MempoolInclusionStatus, Err | None]:
reward_ph = wallet_a.get_new_puzzlehash() reward_ph = wallet_a.get_new_puzzlehash()
full_node_1, server_1, bt = one_node_one_block full_node_1, server_1, bt = one_node_one_block
blocks = await full_node_1.get_all_full_blocks() blocks = await full_node_1.get_all_full_blocks()
@@ -772,7 +772,7 @@ class TestMempoolManager:
node_server_bt: tuple[FullNodeSimulator, ChiaServer, BlockTools], node_server_bt: tuple[FullNodeSimulator, ChiaServer, BlockTools],
wallet_a: WalletTool, wallet_a: WalletTool,
test_fun: Callable[[Coin, Coin], SpendBundle], test_fun: Callable[[Coin, Coin], SpendBundle],
) -> tuple[list[FullBlock], SpendBundle, MempoolInclusionStatus, Optional[Err]]: ) -> tuple[list[FullBlock], SpendBundle, MempoolInclusionStatus, Err | None]:
reward_ph = wallet_a.get_new_puzzlehash() reward_ph = wallet_a.get_new_puzzlehash()
full_node_1, server_1, bt = node_server_bt full_node_1, server_1, bt = node_server_bt
blocks = await full_node_1.get_all_full_blocks() blocks = await full_node_1.get_all_full_blocks()
@@ -1256,7 +1256,7 @@ class TestMempoolManager:
self, self,
assert_garbage: bool, assert_garbage: bool,
announce_garbage: bool, announce_garbage: bool,
expected: Optional[Err], expected: Err | None,
expected_included: MempoolInclusionStatus, expected_included: MempoolInclusionStatus,
one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools],
wallet_a: WalletTool, wallet_a: WalletTool,
@@ -1469,7 +1469,7 @@ class TestMempoolManager:
self, self,
assert_garbage: bool, assert_garbage: bool,
announce_garbage: bool, announce_garbage: bool,
expected: Optional[Err], expected: Err | None,
expected_included: MempoolInclusionStatus, expected_included: MempoolInclusionStatus,
one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools],
wallet_a: WalletTool, wallet_a: WalletTool,
@@ -2530,7 +2530,7 @@ class TestGeneratorConditions:
], ],
) )
def test_softfork_condition( def test_softfork_condition(
self, mempool: bool, condition: str, expect_error: Optional[int], softfork_height: uint32 self, mempool: bool, condition: str, expect_error: int | None, softfork_height: uint32
) -> None: ) -> None:
npc_result = generator_condition_tester(condition, mempool_mode=mempool, height=softfork_height) npc_result = generator_condition_tester(condition, mempool_mode=mempool, height=softfork_height)
print(npc_result) print(npc_result)
@@ -2550,7 +2550,7 @@ class TestGeneratorConditions:
], ],
) )
def test_message_condition( def test_message_condition(
self, mempool: bool, condition: str, expect_error: Optional[int], softfork_height: uint32 self, mempool: bool, condition: str, expect_error: int | None, softfork_height: uint32
) -> None: ) -> None:
npc_result = generator_condition_tester(condition, mempool_mode=mempool, height=softfork_height) npc_result = generator_condition_tester(condition, mempool_mode=mempool, height=softfork_height)
print(npc_result) print(npc_result)
@@ -2920,7 +2920,7 @@ def test_items_by_feerate(items: list[MempoolItem], expected: list[Coin]) -> Non
assert len(ordered_items) == len(expected) assert len(ordered_items) == len(expected)
last_fpc: Optional[float] = None last_fpc: float | None = None
for mi, expected_coin in zip(ordered_items, expected): for mi, expected_coin in zip(ordered_items, expected):
assert len(mi.bundle_coin_spends) == 1 assert len(mi.bundle_coin_spends) == 1
assert next(iter(mi.bundle_coin_spends.values())).coin_spend.coin == expected_coin assert next(iter(mi.bundle_coin_spends.values())).coin_spend.coin == expected_coin
@@ -3413,7 +3413,7 @@ async def test_lineage_cache(seeded_random: random.Random) -> None:
bytes32.random(seeded_random), bytes32.random(seeded_random), bytes32.random(seeded_random) bytes32.random(seeded_random), bytes32.random(seeded_random), bytes32.random(seeded_random)
) )
async def callback1(ph: bytes32) -> Optional[UnspentLineageInfo]: async def callback1(ph: bytes32) -> UnspentLineageInfo | None:
nonlocal called nonlocal called
called += 1 called += 1
return info1 return info1
@@ -3432,7 +3432,7 @@ async def test_lineage_cache(seeded_random: random.Random) -> None:
called = 0 called = 0
async def callback_none(ph: bytes32) -> Optional[UnspentLineageInfo]: async def callback_none(ph: bytes32) -> UnspentLineageInfo | None:
nonlocal called nonlocal called
called += 1 called += 1
return None return None
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
import datetime import datetime
from typing import Union
import pytest import pytest
from chia_rs.sized_ints import uint64 from chia_rs.sized_ints import uint64
@@ -20,9 +19,7 @@ from chia.wallet.wallet import Wallet
@pytest.mark.anyio @pytest.mark.anyio
async def test_protocol_messages( async def test_protocol_messages(
simulator_and_wallet: tuple[ simulator_and_wallet: tuple[list[FullNodeAPI | FullNodeSimulator], list[tuple[Wallet, ChiaServer]], BlockTools],
list[Union[FullNodeAPI, FullNodeSimulator]], list[tuple[Wallet, ChiaServer]], BlockTools
],
) -> None: ) -> None:
full_nodes, _wallets, bt = simulator_and_wallet full_nodes, _wallets, bt = simulator_and_wallet
a_wallet = bt.get_pool_wallet_tool() a_wallet = bt.get_pool_wallet_tool()
@@ -34,7 +31,7 @@ async def test_protocol_messages(
pool_reward_puzzle_hash=reward_ph, pool_reward_puzzle_hash=reward_ph,
) )
full_node_sim: Union[FullNodeAPI, FullNodeSimulator] = full_nodes[0] full_node_sim: FullNodeAPI | FullNodeSimulator = full_nodes[0]
for block in blocks: for block in blocks:
await full_node_sim.full_node.add_block(block) await full_node_sim.full_node.add_block(block)
@@ -3,8 +3,8 @@ from __future__ import annotations
import dataclasses import dataclasses
import logging import logging
import random import random
from collections.abc import Awaitable, Collection, Sequence from collections.abc import Awaitable, Callable, Collection, Sequence
from typing import Any, Callable, ClassVar, Optional, Union from typing import Any, ClassVar
import pytest import pytest
from chia_rs import ( from chia_rs import (
@@ -205,9 +205,9 @@ class TestBlockRecord:
header_hash: bytes32 header_hash: bytes32
height: uint32 height: uint32
timestamp: Optional[uint64] timestamp: uint64 | None
prev_transaction_block_height: uint32 prev_transaction_block_height: uint32
prev_transaction_block_hash: Optional[bytes32] prev_transaction_block_hash: bytes32 | None
@property @property
def is_transaction_block(self) -> bool: def is_transaction_block(self) -> bool:
@@ -219,7 +219,7 @@ async def zero_calls_get_coin_records(coin_ids: Collection[bytes32]) -> list[Coi
return [] return []
async def zero_calls_get_unspent_lineage_info_for_puzzle_hash(_puzzle_hash: bytes32) -> Optional[UnspentLineageInfo]: async def zero_calls_get_unspent_lineage_info_for_puzzle_hash(_puzzle_hash: bytes32) -> UnspentLineageInfo | None:
assert False # pragma no cover assert False # pragma no cover
@@ -258,7 +258,7 @@ async def instantiate_mempool_manager(
block_height: uint32 = TEST_HEIGHT, block_height: uint32 = TEST_HEIGHT,
block_timestamp: uint64 = TEST_TIMESTAMP, block_timestamp: uint64 = TEST_TIMESTAMP,
constants: ConsensusConstants = DEFAULT_CONSTANTS, constants: ConsensusConstants = DEFAULT_CONSTANTS,
max_tx_clvm_cost: Optional[uint64] = None, max_tx_clvm_cost: uint64 | None = None,
) -> MempoolManager: ) -> MempoolManager:
mempool_manager = MempoolManager( mempool_manager = MempoolManager(
get_coin_records, get_coin_records,
@@ -275,9 +275,9 @@ async def instantiate_mempool_manager(
async def setup_mempool_with_coins( async def setup_mempool_with_coins(
*, *,
coin_amounts: list[int], coin_amounts: list[int],
max_block_clvm_cost: Optional[int] = None, max_block_clvm_cost: int | None = None,
max_tx_clvm_cost: Optional[uint64] = None, max_tx_clvm_cost: uint64 | None = None,
mempool_block_buffer: Optional[int] = None, mempool_block_buffer: int | None = None,
) -> tuple[MempoolManager, list[Coin]]: ) -> tuple[MempoolManager, list[Coin]]:
coins = [] coins = []
test_coin_records = {} test_coin_records = {}
@@ -305,24 +305,24 @@ async def setup_mempool_with_coins(
return (mempool_manager, coins) return (mempool_manager, coins)
CreateCoin = tuple[bytes32, int, Optional[bytes]] CreateCoin = tuple[bytes32, int, bytes | None]
def make_test_conds( def make_test_conds(
*, *,
birth_height: Optional[int] = None, birth_height: int | None = None,
birth_seconds: Optional[int] = None, birth_seconds: int | None = None,
height_relative: Optional[int] = None, height_relative: int | None = None,
height_absolute: int = 0, height_absolute: int = 0,
seconds_relative: Optional[int] = None, seconds_relative: int | None = None,
seconds_absolute: int = 0, seconds_absolute: int = 0,
before_height_relative: Optional[int] = None, before_height_relative: int | None = None,
before_height_absolute: Optional[int] = None, before_height_absolute: int | None = None,
before_seconds_relative: Optional[int] = None, before_seconds_relative: int | None = None,
before_seconds_absolute: Optional[int] = None, before_seconds_absolute: int | None = None,
cost: int = 0, cost: int = 0,
spend_ids: Sequence[tuple[Union[bytes32, Coin], int]] = [(TEST_COIN_ID, 0)], spend_ids: Sequence[tuple[bytes32 | Coin, int]] = [(TEST_COIN_ID, 0)],
created_coins: Optional[list[list[CreateCoin]]] = None, created_coins: list[list[CreateCoin]] | None = None,
) -> SpendBundleConditions: ) -> SpendBundleConditions:
if created_coins is None: if created_coins is None:
created_coins = [] created_coins = []
@@ -432,7 +432,7 @@ class TestCheckTimeLocks:
def test_conditions( def test_conditions(
self, self,
conds: SpendBundleConditions, conds: SpendBundleConditions,
expected: Optional[Err], expected: Err | None,
) -> None: ) -> None:
assert ( assert (
check_time_locks( check_time_locks(
@@ -446,7 +446,7 @@ class TestCheckTimeLocks:
def expect( def expect(
*, height: int = 0, seconds: int = 0, before_height: Optional[int] = None, before_seconds: Optional[int] = None *, height: int = 0, seconds: int = 0, before_height: int | None = None, before_seconds: int | None = None
) -> TimelockConditions: ) -> TimelockConditions:
ret = TimelockConditions(uint32(height), uint64(seconds)) ret = TimelockConditions(uint32(height), uint64(seconds))
if before_height is not None: if before_height is not None:
@@ -538,7 +538,7 @@ def spend_bundle_from_conditions(
async def add_spendbundle( async def add_spendbundle(
mempool_manager: MempoolManager, sb: SpendBundle, sb_name: bytes32 mempool_manager: MempoolManager, sb: SpendBundle, sb_name: bytes32
) -> tuple[Optional[uint64], MempoolInclusionStatus, Optional[Err]]: ) -> tuple[uint64 | None, MempoolInclusionStatus, Err | None]:
sbc = await mempool_manager.pre_validate_spendbundle(sb, sb_name) sbc = await mempool_manager.pre_validate_spendbundle(sb, sb_name)
ret = await mempool_manager.add_spend_bundle(sb, sbc, sb_name, TEST_HEIGHT) ret = await mempool_manager.add_spend_bundle(sb, sbc, sb_name, TEST_HEIGHT)
invariant_check_mempool(mempool_manager.mempool) invariant_check_mempool(mempool_manager.mempool)
@@ -550,7 +550,7 @@ async def generate_and_add_spendbundle(
conditions: list[list[Any]], conditions: list[list[Any]],
coin: Coin = TEST_COIN, coin: Coin = TEST_COIN,
aggsig: G2Element = G2Element(), aggsig: G2Element = G2Element(),
) -> tuple[SpendBundle, bytes32, tuple[Optional[uint64], MempoolInclusionStatus, Optional[Err]]]: ) -> tuple[SpendBundle, bytes32, tuple[uint64 | None, MempoolInclusionStatus, Err | None]]:
sb = spend_bundle_from_conditions(conditions, coin, aggsig) sb = spend_bundle_from_conditions(conditions, coin, aggsig)
sb_name = sb.name() sb_name = sb.name()
result = await add_spendbundle(mempool_manager, sb, sb_name) result = await add_spendbundle(mempool_manager, sb, sb_name)
@@ -838,7 +838,7 @@ async def test_ephemeral_timelock(
opcode: ConditionOpcode, opcode: ConditionOpcode,
lock_value: int, lock_value: int,
expected_status: MempoolInclusionStatus, expected_status: MempoolInclusionStatus,
expected_error: Optional[Err], expected_error: Err | None,
) -> None: ) -> None:
mempool_manager = await instantiate_mempool_manager( mempool_manager = await instantiate_mempool_manager(
get_coin_records=get_coin_records_for_test_coins, get_coin_records=get_coin_records_for_test_coins,
@@ -877,7 +877,7 @@ def test_optional_max() -> None:
assert optional_max(uint32(123), uint32(234)) == uint32(234) assert optional_max(uint32(123), uint32(234)) == uint32(234)
def mk_coin_spend(coin: Coin, solution: Optional[str] = None) -> CoinSpend: def mk_coin_spend(coin: Coin, solution: str | None = None) -> CoinSpend:
return make_spend( return make_spend(
coin, coin,
SerializedProgram.to(None), SerializedProgram.to(None),
@@ -904,10 +904,10 @@ def mk_item(
*, *,
cost: int = 1, cost: int = 1,
fee: int = 0, fee: int = 0,
assert_height: Optional[int] = None, assert_height: int | None = None,
assert_before_height: Optional[int] = None, assert_before_height: int | None = None,
assert_before_seconds: Optional[int] = None, assert_before_seconds: int | None = None,
solution: Optional[str] = None, solution: str | None = None,
flags: list[int] = [], flags: list[int] = [],
) -> MempoolItem: ) -> MempoolItem:
# we don't actually care about the puzzle and solutions for the purpose of # we don't actually care about the puzzle and solutions for the purpose of
@@ -1377,7 +1377,7 @@ async def test_create_bundle_from_mempool_on_max_cost(num_skipped_items: int, ca
) )
@pytest.mark.anyio @pytest.mark.anyio
async def test_assert_before_expiration( async def test_assert_before_expiration(
opcode: ConditionOpcode, arg: int, expect_eviction: bool, expect_limit: Optional[int] opcode: ConditionOpcode, arg: int, expect_eviction: bool, expect_limit: int | None
) -> None: ) -> None:
async def get_coin_records(coin_ids: Collection[bytes32]) -> list[CoinRecord]: async def get_coin_records(coin_ids: Collection[bytes32]) -> list[CoinRecord]:
all_coins = {TEST_COIN.name(): CoinRecord(TEST_COIN, uint32(5), uint32(0), False, uint64(9900))} all_coins = {TEST_COIN.name(): CoinRecord(TEST_COIN, uint32(5), uint32(0), False, uint64(9900))}
@@ -1439,7 +1439,7 @@ def make_test_spendbundle(coin: Coin, *, fee: int = 0, eligible_spend: bool = Fa
async def send_spendbundle( async def send_spendbundle(
mempool_manager: MempoolManager, mempool_manager: MempoolManager,
sb: SpendBundle, sb: SpendBundle,
expected_result: tuple[MempoolInclusionStatus, Optional[Err]] = (MempoolInclusionStatus.SUCCESS, None), expected_result: tuple[MempoolInclusionStatus, Err | None] = (MempoolInclusionStatus.SUCCESS, None),
) -> None: ) -> None:
result = await add_spendbundle(mempool_manager, sb, sb.name()) result = await add_spendbundle(mempool_manager, sb, sb.name())
assert (result[1], result[2]) == expected_result assert (result[1], result[2]) == expected_result
@@ -1450,7 +1450,7 @@ async def make_and_send_spendbundle(
coin: Coin, coin: Coin,
*, *,
fee: int = 0, fee: int = 0,
expected_result: tuple[MempoolInclusionStatus, Optional[Err]] = (MempoolInclusionStatus.SUCCESS, None), expected_result: tuple[MempoolInclusionStatus, Err | None] = (MempoolInclusionStatus.SUCCESS, None),
) -> SpendBundle: ) -> SpendBundle:
sb = make_test_spendbundle(coin, fee=fee) sb = make_test_spendbundle(coin, fee=fee)
await send_spendbundle(mempool_manager, sb, expected_result) await send_spendbundle(mempool_manager, sb, expected_result)
@@ -2131,7 +2131,7 @@ async def test_identical_spend_aggregation_e2e(
), ),
], ],
) )
async def test_mempool_timelocks(cond1: list[object], cond2: list[object], expected: Optional[Err]) -> None: async def test_mempool_timelocks(cond1: list[object], cond2: list[object], expected: Err | None) -> None:
coins = [] coins = []
test_coin_records = {} test_coin_records = {}
@@ -2348,7 +2348,7 @@ class TestCoins:
def spend_coin(self, coin_id: bytes32, height: uint32 = uint32(10)) -> None: def spend_coin(self, coin_id: bytes32, height: uint32 = uint32(10)) -> None:
self.coin_records[coin_id] = dataclasses.replace(self.coin_records[coin_id], spent_block_index=height) self.coin_records[coin_id] = dataclasses.replace(self.coin_records[coin_id], spent_block_index=height)
def update_lineage(self, puzzle_hash: bytes32, coin: Optional[Coin]) -> None: def update_lineage(self, puzzle_hash: bytes32, coin: Coin | None) -> None:
if coin is None: if coin is None:
self.lineage_info.pop(puzzle_hash) self.lineage_info.pop(puzzle_hash)
else: else:
@@ -2365,7 +2365,7 @@ class TestCoins:
return ret return ret
async def get_unspent_lineage_info(self, ph: bytes32) -> Optional[UnspentLineageInfo]: async def get_unspent_lineage_info(self, ph: bytes32) -> UnspentLineageInfo | None:
return self.lineage_info.get(ph) return self.lineage_info.get(ph)
@@ -3012,7 +3012,7 @@ class CheckRemovalsCase:
removals: dict[bytes32, CoinRecord] removals: dict[bytes32, CoinRecord]
bundle_coin_spends: dict[bytes32, BundleCoinSpend] = dataclasses.field(default_factory=dict) bundle_coin_spends: dict[bytes32, BundleCoinSpend] = dataclasses.field(default_factory=dict)
conflicting_mempool_items: dict[bytes32, list[MempoolItem]] = dataclasses.field(default_factory=dict) conflicting_mempool_items: dict[bytes32, list[MempoolItem]] = dataclasses.field(default_factory=dict)
expected_result: tuple[Optional[Err], list[MempoolItem]] = dataclasses.field(default_factory=lambda: (None, [])) expected_result: tuple[Err | None, list[MempoolItem]] = dataclasses.field(default_factory=lambda: (None, []))
marks: Marks = () marks: Marks = ()
@@ -3295,7 +3295,7 @@ async def test_new_peak_txs_added(condition_and_error: tuple[ConditionOpcode, Er
assert error == expected_error assert error == expected_error
# Advance the mempool beyond the asserted height to retry the test item # Advance the mempool beyond the asserted height to retry the test item
if optimized_path: if optimized_path:
spent_coins: Optional[list[bytes32]] = [] spent_coins: list[bytes32] | None = []
new_peak_info = await mempool_manager.new_peak( new_peak_info = await mempool_manager.new_peak(
create_test_block_record(height=uint32(condition_height)), spent_coins create_test_block_record(height=uint32(condition_height)), spent_coins
) )
@@ -2,7 +2,7 @@ from __future__ import annotations
import copy import copy
import dataclasses import dataclasses
from typing import Any, Optional from typing import Any
import pytest import pytest
from chia_rs import AugSchemeMPL, CoinSpend, G1Element, G2Element, PrivateKey, SpendBundle from chia_rs import AugSchemeMPL, CoinSpend, G1Element, G2Element, PrivateKey, SpendBundle
@@ -199,10 +199,10 @@ async def make_and_send_spend_bundle(
is_eligible_for_ff: bool = True, is_eligible_for_ff: bool = True,
*, *,
is_launcher_coin: bool = False, is_launcher_coin: bool = False,
signing_puzzle: Optional[Program] = None, signing_puzzle: Program | None = None,
signing_coin: Optional[Coin] = None, signing_coin: Coin | None = None,
aggsig: G2Element = G2Element(), aggsig: G2Element = G2Element(),
) -> tuple[MempoolInclusionStatus, Optional[Err]]: ) -> tuple[MempoolInclusionStatus, Err | None]:
if is_launcher_coin or not is_eligible_for_ff: if is_launcher_coin or not is_eligible_for_ff:
assert signing_puzzle is not None assert signing_puzzle is not None
assert signing_coin is not None assert signing_coin is not None
+7 -7
View File
@@ -7,7 +7,7 @@ import logging.config
import pathlib import pathlib
import sys import sys
import threading import threading
from typing import Optional, final, overload from typing import final, overload
from chia._tests.util.misc import create_logger from chia._tests.util.misc import create_logger
from chia.server.chia_policy import ChiaPolicy from chia.server.chia_policy import ChiaPolicy
@@ -47,7 +47,7 @@ async def async_main(
shutdown_path: pathlib.Path, shutdown_path: pathlib.Path,
ip: str = "127.0.0.1", ip: str = "127.0.0.1",
port: int = 8444, port: int = 8444,
port_holder: Optional[list[int]] = None, port_holder: list[int] | None = None,
) -> None: ... ) -> None: ...
@@ -58,22 +58,22 @@ async def async_main(
thread_end_event: threading.Event, thread_end_event: threading.Event,
ip: str = "127.0.0.1", ip: str = "127.0.0.1",
port: int = 8444, port: int = 8444,
port_holder: Optional[list[int]] = None, port_holder: list[int] | None = None,
) -> None: ... ) -> None: ...
async def async_main( async def async_main(
*, *,
out_path: pathlib.Path, out_path: pathlib.Path,
shutdown_path: Optional[pathlib.Path] = None, shutdown_path: pathlib.Path | None = None,
thread_end_event: Optional[threading.Event] = None, thread_end_event: threading.Event | None = None,
ip: str = "127.0.0.1", ip: str = "127.0.0.1",
port: int = 8444, port: int = 8444,
port_holder: Optional[list[int]] = None, port_holder: list[int] | None = None,
) -> None: ) -> None:
with out_path.open(mode="w") as file: with out_path.open(mode="w") as file:
logger = create_logger(file=file) logger = create_logger(file=file)
file_task: Optional[asyncio.Task[None]] = None file_task: asyncio.Task[None] | None = None
if thread_end_event is None: if thread_end_event is None:
assert shutdown_path is not None assert shutdown_path is not None
thread_end_event = threading.Event() thread_end_event = threading.Event()
+1 -2
View File
@@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio import asyncio
import logging import logging
import time import time
from typing import Optional
import pytest import pytest
from aiohttp import ClientSession, ClientTimeout, WSCloseCode, WSMessage, WSMsgType, WSServerHandshakeError from aiohttp import ClientSession, ClientTimeout, WSCloseCode, WSMessage, WSMsgType, WSServerHandshakeError
@@ -36,7 +35,7 @@ def not_localhost(host: str) -> bool:
class FakeRateLimiter: class FakeRateLimiter:
def process_msg_and_check( def process_msg_and_check(
self, message: Message, our_capabilities: list[Capability], peer_capabilities: list[Capability] self, message: Message, our_capabilities: list[Capability], peer_capabilities: list[Capability]
) -> Optional[str]: ) -> str | None:
return None return None
+1 -1
View File
@@ -64,7 +64,7 @@ def test_base_event_loop_has_methods() -> None:
) )
assert inspect.isfunction(_chia_create_server) assert inspect.isfunction(_chia_create_server)
expected_signature = "(cls: 'Any', protocol_factory: '_ProtocolFactory', host: 'Any', port: 'Any', *, family: 'socket.AddressFamily' = <AddressFamily.AF_UNSPEC: 0>, flags: 'socket.AddressInfo' = <AddressInfo.AI_PASSIVE: 1>, sock: 'Any' = None, backlog: 'int' = 100, ssl: '_SSLContext' = None, reuse_address: 'Optional[bool]' = None, reuse_port: 'Optional[bool]' = None, ssl_handshake_timeout: 'Optional[float]' = 30, start_serving: 'bool' = True) -> 'PausableServer'" # noqa: E501 expected_signature = "(cls: 'Any', protocol_factory: '_ProtocolFactory', host: 'Any', port: 'Any', *, family: 'socket.AddressFamily' = <AddressFamily.AF_UNSPEC: 0>, flags: 'socket.AddressInfo' = <AddressInfo.AI_PASSIVE: 1>, sock: 'Any' = None, backlog: 'int' = 100, ssl: '_SSLContext' = None, reuse_address: 'bool | None' = None, reuse_port: 'bool | None' = None, ssl_handshake_timeout: 'float | None' = 30, start_serving: 'bool' = True) -> 'PausableServer'" # noqa: E501
assert str(inspect.signature(_chia_create_server)) == expected_signature assert str(inspect.signature(_chia_create_server)) == expected_signature
class EchoProtocol(asyncio.Protocol): class EchoProtocol(asyncio.Protocol):
+7 -8
View File
@@ -10,7 +10,6 @@ import sys
import threading import threading
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Optional
import anyio import anyio
import pytest import pytest
@@ -45,8 +44,8 @@ async def serve_in_thread(
@dataclass @dataclass
class Client: class Client:
reader: Optional[asyncio.StreamReader] reader: asyncio.StreamReader | None
writer: Optional[asyncio.StreamWriter] writer: asyncio.StreamWriter | None
@classmethod @classmethod
async def open(cls, ip: str, port: int) -> Client: async def open(cls, ip: str, port: int) -> Client:
@@ -95,10 +94,10 @@ class ServeInThread:
requested_port: int requested_port: int
out_path: pathlib.Path out_path: pathlib.Path
connection_limit: int = 25 connection_limit: int = 25
original_connection_limit: Optional[int] = None original_connection_limit: int | None = None
loop: Optional[asyncio.AbstractEventLoop] = None loop: asyncio.AbstractEventLoop | None = None
server_task: Optional[asyncio.Task[None]] = None server_task: asyncio.Task[None] | None = None
thread: Optional[threading.Thread] = None thread: threading.Thread | None = None
thread_end_event: threading.Event = field(default_factory=threading.Event) thread_end_event: threading.Event = field(default_factory=threading.Event)
port_holder: list[int] = field(default_factory=list) port_holder: list[int] = field(default_factory=list)
@@ -189,7 +188,7 @@ async def test_loop(tmp_path: pathlib.Path) -> None:
await asyncio.sleep(adjusted_timeout(5)) await asyncio.sleep(adjusted_timeout(5))
writer = None writer = None
post_connection_error: Optional[str] = None post_connection_error: str | None = None
try: try:
logger.info(" ==== attempting a single new connection") logger.info(" ==== attempting a single new connection")
with anyio.fail_after(delay=adjusted_timeout(1)): with anyio.fail_after(delay=adjusted_timeout(1)):
+2 -3
View File
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import Union
import pytest import pytest
from chia_rs.sized_ints import uint32 from chia_rs.sized_ints import uint32
@@ -65,7 +64,7 @@ async def test_limits_v2(incoming: bool, tx_msg: bool, limit_size: bool, monkeyp
message_data = b"\0" * 1024 message_data = b"\0" * 1024
msg_type = ProtocolMessageTypes.new_transaction msg_type = ProtocolMessageTypes.new_transaction
limits: dict[ProtocolMessageTypes, Union[RLSettings, Unlimited]] limits: dict[ProtocolMessageTypes, RLSettings | Unlimited]
if limit_size: if limit_size:
agg_limit = RLSettings(False, count * 2, len(message_data), count * len(message_data)) agg_limit = RLSettings(False, count * 2, len(message_data), count * len(message_data))
@@ -79,7 +78,7 @@ async def test_limits_v2(incoming: bool, tx_msg: bool, limit_size: bool, monkeyp
def mock_get_limits( def mock_get_limits(
our_capabilities: list[Capability], peer_capabilities: list[Capability] our_capabilities: list[Capability], peer_capabilities: list[Capability]
) -> tuple[dict[ProtocolMessageTypes, Union[RLSettings, Unlimited]], RLSettings]: ) -> tuple[dict[ProtocolMessageTypes, RLSettings | Unlimited], RLSettings]:
return limits, agg_limit return limits, agg_limit
import chia.server.rate_limits import chia.server.rate_limits
+2 -1
View File
@@ -1,8 +1,9 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from typing import Callable, ClassVar, cast from typing import ClassVar, cast
import pytest import pytest
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
+2 -2
View File
@@ -7,7 +7,7 @@ import sys
import time import time
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from pathlib import Path from pathlib import Path
from typing import Any, Optional, cast from typing import Any, cast
import aiohttp.client_exceptions import aiohttp.client_exceptions
import pytest import pytest
@@ -114,7 +114,7 @@ async def test_daemon_terminates(signal_number: signal.Signals, chia_root: ChiaR
async def test_services_terminate( async def test_services_terminate(
signal_number: signal.Signals, signal_number: signal.Signals,
chia_root: ChiaRoot, chia_root: ChiaRoot,
create_service: Optional[CreateServiceProtocol], create_service: CreateServiceProtocol | None,
module_path: str, module_path: str,
service_config_name: str, service_config_name: str,
) -> None: ) -> None:
@@ -4,12 +4,12 @@ import dataclasses
import logging import logging
import operator import operator
import time import time
from collections.abc import Awaitable from collections.abc import Awaitable, Callable
from math import ceil from math import ceil
from os import mkdir from os import mkdir
from pathlib import Path from pathlib import Path
from shutil import copy from shutil import copy
from typing import Any, Callable, Union, cast from typing import Any, cast
import pytest import pytest
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -362,7 +362,7 @@ def test_plot_matches_filter(filter_item: FilterItem, match: bool) -> None:
async def test_farmer_get_harvester_plots_endpoints( async def test_farmer_get_harvester_plots_endpoints(
harvester_farmer_environment: HarvesterFarmerEnvironment, harvester_farmer_environment: HarvesterFarmerEnvironment,
endpoint: Callable[[FarmerRpcClient, PaginatedRequestData], Awaitable[dict[str, Any]]], endpoint: Callable[[FarmerRpcClient, PaginatedRequestData], Awaitable[dict[str, Any]]],
filtering: Union[list[FilterItem], list[str]], filtering: list[FilterItem] | list[str],
sort_key: str, sort_key: str,
reverse: bool, reverse: bool,
expected_plot_count: int, expected_plot_count: int,
+1 -2
View File
@@ -5,7 +5,6 @@ import random
from hashlib import sha256 from hashlib import sha256
from itertools import permutations from itertools import permutations
from random import Random from random import Random
from typing import Optional
import pytest import pytest
from chia_rs import Coin, MerkleSet, compute_merkle_set_root, confirm_included_already_hashed from chia_rs import Coin, MerkleSet, compute_merkle_set_root, confirm_included_already_hashed
@@ -311,7 +310,7 @@ def test_validate_removals_full_list(num_coins: int, seeded_random: Random) -> N
# the root can be computed by all the removals # the root can be computed by all the removals
coins = make_test_coins(num_coins, seeded_random) coins = make_test_coins(num_coins, seeded_random)
coin_map: list[tuple[bytes32, Optional[Coin]]] = [] coin_map: list[tuple[bytes32, Coin | None]] = []
removals_merkle_set = MerkleSet([coin.name() for coin in coins]) removals_merkle_set = MerkleSet([coin.name() for coin in coins])
for coin in coins: for coin in coins:
coin_map.append((coin.name(), coin)) coin_map.append((coin.name(), coin))
+4 -4
View File
@@ -4,7 +4,7 @@ import time
from dataclasses import dataclass from dataclasses import dataclass
from ipaddress import IPv4Address, IPv6Address from ipaddress import IPv4Address, IPv6Address
from socket import AF_INET, AF_INET6, SOCK_STREAM from socket import AF_INET, AF_INET6, SOCK_STREAM
from typing import Optional, Union, cast from typing import cast
from unittest.mock import AsyncMock from unittest.mock import AsyncMock
import dns import dns
@@ -367,9 +367,9 @@ def get_mock_resolver() -> AsyncMock:
# Adjust mock_resolve to accept all arguments # Adjust mock_resolve to accept all arguments
async def mock_resolve( async def mock_resolve(
qname: Union[dns.name.Name, str], qname: dns.name.Name | str,
rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A, rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A,
lifetime: Optional[float] = None, lifetime: float | None = None,
) -> RRset: ) -> RRset:
if rdtype == "A": if rdtype == "A":
return mock_rrset_a return mock_rrset_a
+3 -3
View File
@@ -10,7 +10,7 @@ from multiprocessing import Pool, Queue, TimeoutError
from pathlib import Path from pathlib import Path
from threading import Thread from threading import Thread
from time import sleep from time import sleep
from typing import Any, Optional from typing import Any
import pytest import pytest
import yaml import yaml
@@ -41,7 +41,7 @@ def write_config(
atomic_write: bool, atomic_write: bool,
do_sleep: bool, do_sleep: bool,
iterations: int, iterations: int,
error_queue: Optional[Queue] = None, error_queue: Queue | None = None,
): ):
""" """
Wait for a random amount of time and write out the config data. With a large Wait for a random amount of time and write out the config data. With a large
@@ -74,7 +74,7 @@ def write_config(
def read_and_compare_config( def read_and_compare_config(
root_path: Path, default_config: dict, do_sleep: bool, iterations: int, error_queue: Optional[Queue] = None root_path: Path, default_config: dict, do_sleep: bool, iterations: int, error_queue: Queue | None = None
): ):
""" """
Wait for a random amount of time, read the config and compare with the Wait for a random amount of time, read the config and compare with the
+2 -2
View File
@@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Optional from typing import Any
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32 from chia_rs.sized_ints import uint32
@@ -18,7 +18,7 @@ def test_primitives() -> None:
@dataclass(frozen=True) @dataclass(frozen=True)
class PrimitivesTest(Streamable): class PrimitivesTest(Streamable):
a: uint32 a: uint32
b: Optional[str] b: str | None
c: str c: str
d: bytes d: bytes
e: bytes32 e: bytes32
+3 -3
View File
@@ -2,8 +2,8 @@ from __future__ import annotations
import json import json
import random import random
from collections.abc import Callable
from dataclasses import dataclass, replace from dataclasses import dataclass, replace
from typing import Callable, Optional
import importlib_resources import importlib_resources
import pytest import pytest
@@ -271,7 +271,7 @@ def test_key_data_secrets_creation(
@pytest.mark.parametrize("label", [None, "key"]) @pytest.mark.parametrize("label", [None, "key"])
def test_key_data_generate(label: Optional[str]) -> None: def test_key_data_generate(label: str | None) -> None:
key_data = KeyData.generate(label) key_data = KeyData.generate(label)
assert key_data.private_key == AugSchemeMPL.key_gen(mnemonic_to_seed(key_data.mnemonic_str())) assert key_data.private_key == AugSchemeMPL.key_gen(mnemonic_to_seed(key_data.mnemonic_str()))
assert key_data.entropy == bytes_from_mnemonic(key_data.mnemonic_str()) assert key_data.entropy == bytes_from_mnemonic(key_data.mnemonic_str())
@@ -343,7 +343,7 @@ def test_key_data_secrets_post_init(input_data: tuple[list[str], bytes, PrivateK
], ],
) )
def test_key_data_post_init( def test_key_data_post_init(
input_data: tuple[uint32, G1Element, Optional[str], Optional[KeyDataSecrets]], data_type: str input_data: tuple[uint32, G1Element, str | None, KeyDataSecrets | None], data_type: str
) -> None: ) -> None:
with pytest.raises(KeychainKeyDataMismatch, match=data_type): with pytest.raises(KeychainKeyDataMismatch, match=data_type):
KeyData(*input_data) KeyData(*input_data)
+2 -1
View File
@@ -3,11 +3,12 @@ from __future__ import annotations
import logging import logging
import os import os
import time import time
from collections.abc import Callable
from multiprocessing import Pool, TimeoutError from multiprocessing import Pool, TimeoutError
from pathlib import Path from pathlib import Path
from sys import platform from sys import platform
from time import sleep from time import sleep
from typing import Any, Callable from typing import Any
import pytest import pytest
+1 -2
View File
@@ -4,7 +4,6 @@ import contextlib
import dataclasses import dataclasses
import logging import logging
import re import re
from typing import Union
import pytest import pytest
@@ -22,7 +21,7 @@ def logger_fixture() -> logging.Logger:
@dataclasses.dataclass @dataclasses.dataclass
class ErrorCase: class ErrorCase:
type_to_raise: type[BaseException] type_to_raise: type[BaseException]
type_to_catch: Union[type[BaseException], tuple[type[BaseException], ...]] type_to_catch: type[BaseException] | tuple[type[BaseException], ...]
should_match: bool should_match: bool
+15 -15
View File
@@ -2,16 +2,16 @@ from __future__ import annotations
import io import io
import re import re
from collections.abc import Callable
from dataclasses import dataclass, field, fields from dataclasses import dataclass, field, fields
from enum import Enum from enum import Enum
from typing import Any, Callable, ClassVar, Optional, get_type_hints from typing import Any, ClassVar, Literal, get_args, get_type_hints
import pytest import pytest
from chia_rs import FullBlock, G1Element, SubEpochChallengeSegment from chia_rs import FullBlock, G1Element, SubEpochChallengeSegment
from chia_rs.sized_bytes import bytes4, bytes32 from chia_rs.sized_bytes import bytes4, bytes32
from chia_rs.sized_ints import uint8, uint32, uint64 from chia_rs.sized_ints import uint8, uint32, uint64
from clvm_tools import binutils from clvm_tools import binutils
from typing_extensions import Literal, get_args
from chia.protocols.wallet_protocol import RespondRemovals from chia.protocols.wallet_protocol import RespondRemovals
from chia.simulator.block_tools import BlockTools, test_constants from chia.simulator.block_tools import BlockTools, test_constants
@@ -418,10 +418,10 @@ class PostInitTestClassBad(Streamable):
@streamable @streamable
@dataclass(frozen=True) @dataclass(frozen=True)
class PostInitTestClassOptional(Streamable): class PostInitTestClassOptional(Streamable):
a: Optional[uint8] a: uint8 | None
b: Optional[uint8] b: uint8 | None
c: Optional[uint8] c: uint8 | None
d: Optional[uint8] d: uint8 | None
@streamable @streamable
@@ -537,8 +537,8 @@ def test_basic() -> None:
b: uint32 b: uint32
c: list[uint32] c: list[uint32]
d: list[list[uint32]] d: list[list[uint32]]
e: Optional[uint32] e: uint32 | None
f: Optional[uint32] f: uint32 | None
g: tuple[uint32, str, bytes] g: tuple[uint32, str, bytes]
h: dict[uint32, str] h: dict[uint32, str]
i: IntegerEnum i: IntegerEnum
@@ -590,9 +590,9 @@ def test_json(bt: BlockTools) -> None:
@streamable @streamable
@dataclass(frozen=True) @dataclass(frozen=True)
class OptionalTestClass(Streamable): class OptionalTestClass(Streamable):
a: Optional[str] a: str | None
b: Optional[bool] b: bool | None
c: Optional[list[Optional[str]]] c: list[str | None] | None
@pytest.mark.parametrize( @pytest.mark.parametrize(
@@ -606,7 +606,7 @@ class OptionalTestClass(Streamable):
(None, None, None), (None, None, None),
], ],
) )
def test_optional_json(a: Optional[str], b: Optional[bool], c: Optional[list[Optional[str]]]) -> None: def test_optional_json(a: str | None, b: bool | None, c: list[str | None] | None) -> None:
obj: OptionalTestClass = OptionalTestClass.from_json_dict({"a": a, "b": b, "c": c}) obj: OptionalTestClass = OptionalTestClass.from_json_dict({"a": a, "b": b, "c": c})
assert obj.a == a assert obj.a == a
assert obj.b == b assert obj.b == b
@@ -623,7 +623,7 @@ class TestClassRecursive1(Streamable):
@dataclass(frozen=True) @dataclass(frozen=True)
class TestClassRecursive2(Streamable): class TestClassRecursive2(Streamable):
a: uint32 a: uint32
b: list[Optional[list[TestClassRecursive1]]] b: list[list[TestClassRecursive1] | None]
c: bytes32 c: bytes32
@@ -637,7 +637,7 @@ def test_recursive_json() -> None:
def test_recursive_types() -> None: def test_recursive_types() -> None:
coin: Optional[Coin] = None coin: Coin | None = None
l1 = [(bytes32([2] * 32), coin)] l1 = [(bytes32([2] * 32), coin)]
rr = RespondRemovals(uint32(1), bytes32([1] * 32), l1, None) rr = RespondRemovals(uint32(1), bytes32([1] * 32), l1, None)
RespondRemovals(rr.height, rr.header_hash, rr.coins, rr.proofs) RespondRemovals(rr.height, rr.header_hash, rr.coins, rr.proofs)
@@ -650,7 +650,7 @@ def test_ambiguous_deserialization_optionals() -> None:
@streamable @streamable
@dataclass(frozen=True) @dataclass(frozen=True)
class TestClassOptional(Streamable): class TestClassOptional(Streamable):
a: Optional[uint8] a: uint8 | None
# Does not have the required elements # Does not have the required elements
with pytest.raises(AssertionError): with pytest.raises(AssertionError):
+3 -2
View File
@@ -2,8 +2,9 @@ from __future__ import annotations
import asyncio import asyncio
import contextlib import contextlib
from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, Optional from typing import TYPE_CHECKING
import aiosqlite import aiosqlite
import pytest import pytest
@@ -494,7 +495,7 @@ async def test_foreign_key_pragma_rolls_back_on_foreign_key_error() -> None:
@dataclass @dataclass
class RowFactoryCase: class RowFactoryCase:
id: str id: str
factory: Optional[type[aiosqlite.Row]] factory: type[aiosqlite.Row] | None
marks: Marks = () marks: Marks = ()
+12 -12
View File
@@ -6,7 +6,7 @@ import operator
import unittest import unittest
from collections.abc import Iterator from collections.abc import Iterator
from dataclasses import asdict, dataclass, field from dataclasses import asdict, dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar, Union, cast from typing import TYPE_CHECKING, Any, ClassVar, cast
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32, uint64 from chia_rs.sized_ints import uint32, uint64
@@ -50,9 +50,9 @@ OPP_DICT = {"<": operator.lt, ">": operator.gt, "<=": operator.le, ">=": operato
class BalanceCheckingError(Exception): class BalanceCheckingError(Exception):
errors: dict[Union[int, str], list[str]] errors: dict[int | str, list[str]]
def __init__(self, errors: dict[Union[int, str], list[str]]) -> None: def __init__(self, errors: dict[int | str, list[str]]) -> None:
self.errors = errors self.errors = errors
def __repr__(self) -> str: def __repr__(self) -> str:
@@ -69,10 +69,10 @@ class WalletState:
@dataclass @dataclass
class WalletStateTransition: class WalletStateTransition:
pre_block_balance_updates: dict[Union[int, str], dict[str, int]] = field(default_factory=dict) pre_block_balance_updates: dict[int | str, dict[str, int]] = field(default_factory=dict)
post_block_balance_updates: dict[Union[int, str], dict[str, int]] = field(default_factory=dict) post_block_balance_updates: dict[int | str, dict[str, int]] = field(default_factory=dict)
pre_block_additional_balance_info: dict[Union[int, str], dict[str, int]] = field(default_factory=dict) pre_block_additional_balance_info: dict[int | str, dict[str, int]] = field(default_factory=dict)
post_block_additional_balance_info: dict[Union[int, str], dict[str, int]] = field(default_factory=dict) post_block_additional_balance_info: dict[int | str, dict[str, int]] = field(default_factory=dict)
@dataclass @dataclass
@@ -121,7 +121,7 @@ class WalletEnvironment:
def xch_wallet(self) -> Wallet: def xch_wallet(self) -> Wallet:
return self.service._node.wallet_state_manager.main_wallet return self.service._node.wallet_state_manager.main_wallet
def dealias_wallet_id(self, wallet_id_or_alias: Union[int, str]) -> uint32: def dealias_wallet_id(self, wallet_id_or_alias: int | str) -> uint32:
""" """
This function turns something that is either a wallet id or a wallet alias into a wallet id. This function turns something that is either a wallet id or a wallet alias into a wallet id.
""" """
@@ -131,7 +131,7 @@ class WalletEnvironment:
else uint32(self.wallet_aliases[wallet_id_or_alias]) else uint32(self.wallet_aliases[wallet_id_or_alias])
) )
def alias_wallet_id(self, wallet_id: uint32) -> Union[uint32, str]: def alias_wallet_id(self, wallet_id: uint32) -> uint32 | str:
""" """
This function turns a wallet id into an alias if one is available or the same wallet id if one is not. This function turns a wallet id into an alias if one is available or the same wallet id if one is not.
""" """
@@ -141,7 +141,7 @@ class WalletEnvironment:
else: else:
return wallet_id return wallet_id
async def check_balances(self, additional_balance_info: dict[Union[int, str], dict[str, int]] = {}) -> None: async def check_balances(self, additional_balance_info: dict[int | str, dict[str, int]] = {}) -> None:
""" """
This function checks the internal representation of what the balances should be against the balances that the This function checks the internal representation of what the balances should be against the balances that the
wallet actually returns via the RPC. wallet actually returns via the RPC.
@@ -151,7 +151,7 @@ class WalletEnvironment:
dealiased_additional_balance_info: dict[uint32, dict[str, int]] = { dealiased_additional_balance_info: dict[uint32, dict[str, int]] = {
self.dealias_wallet_id(k): v for k, v in additional_balance_info.items() self.dealias_wallet_id(k): v for k, v in additional_balance_info.items()
} }
errors: dict[Union[int, str], list[str]] = {} errors: dict[int | str, list[str]] = {}
for wallet_id in self.wallet_state_manager.wallets: for wallet_id in self.wallet_state_manager.wallets:
if wallet_id not in self.wallet_states: if wallet_id not in self.wallet_states:
raise KeyError(f"No wallet state for wallet id {wallet_id} (alias: {self.alias_wallet_id(wallet_id)})") raise KeyError(f"No wallet state for wallet id {wallet_id} (alias: {self.alias_wallet_id(wallet_id)})")
@@ -189,7 +189,7 @@ class WalletEnvironment:
if errors != {}: if errors != {}:
raise BalanceCheckingError(errors) raise BalanceCheckingError(errors)
async def change_balances(self, update_dictionary: dict[Union[int, str], dict[str, int]]) -> None: async def change_balances(self, update_dictionary: dict[int | str, dict[str, int]]) -> None:
""" """
This method changes the internal representation of what the wallet balances should be. This is probably This method changes the internal representation of what the wallet balances should be. This is probably
necessary to call before check_balances as most wallet operations will result in a balance change that causes necessary to call before check_balances as most wallet operations will result in a balance change that causes
+4 -3
View File
@@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, Callable, Optional from collections.abc import Callable
from typing import TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from chia._tests.util.misc import TestId from chia._tests.util.misc import TestId
@@ -15,5 +16,5 @@ if TYPE_CHECKING:
# result in you likely getting the default `None` values since they are not # result in you likely getting the default `None` values since they are not
# populated until tests are running. # populated until tests are running.
record_property: Optional[Callable[[str, object], None]] = None record_property: Callable[[str, object], None] | None = None
test_id: Optional[TestId] = None test_id: TestId | None = None
+18 -18
View File
@@ -5,7 +5,7 @@ import logging
from dataclasses import dataclass from dataclasses import dataclass
from time import time from time import time
from types import TracebackType from types import TracebackType
from typing import Any, Optional, Union, cast from typing import Any, cast
from unittest.mock import ANY from unittest.mock import ANY
import pytest import pytest
@@ -57,7 +57,7 @@ class IncrementPoolStatsCase:
name: str name: str
current_time: float current_time: float
count: int count: int
value: Optional[Union[int, dict[str, Any]]] value: int | dict[str, Any] | None
expected_result: Any expected_result: Any
def __init__( def __init__(
@@ -66,7 +66,7 @@ class IncrementPoolStatsCase:
name: str, name: str,
current_time: float, current_time: float,
count: int, count: int,
value: Optional[Union[int, dict[str, Any]]], value: int | dict[str, Any] | None,
expected_result: Any, expected_result: Any,
): ):
prepared_p2_singleton_puzzle_hash = std_hash(b"11223344") prepared_p2_singleton_puzzle_hash = std_hash(b"11223344")
@@ -137,13 +137,13 @@ class NewProofOfSpaceCase:
plot_size: PlotParam plot_size: PlotParam
plot_challenge: bytes32 plot_challenge: bytes32
plot_public_key: G1Element plot_public_key: G1Element
pool_public_key: Optional[G1Element] pool_public_key: G1Element | None
pool_contract_puzzle_hash: bytes32 pool_contract_puzzle_hash: bytes32
height: uint32 height: uint32
proof: bytes proof: bytes
pool_config: PoolWalletConfig pool_config: PoolWalletConfig
pool_difficulty: Optional[uint64] pool_difficulty: uint64 | None
authentication_token_timeout: Optional[uint8] authentication_token_timeout: uint8 | None
farmer_private_keys: list[PrivateKey] farmer_private_keys: list[PrivateKey]
authentication_keys: dict[bytes32, PrivateKey] authentication_keys: dict[bytes32, PrivateKey]
use_invalid_peer_response: bool use_invalid_peer_response: bool
@@ -157,8 +157,8 @@ class NewProofOfSpaceCase:
difficulty: uint64, difficulty: uint64,
sub_slot_iters: uint64, sub_slot_iters: uint64,
pool_url: str, pool_url: str,
pool_difficulty: Optional[uint64], pool_difficulty: uint64 | None,
authentication_token_timeout: Optional[uint8], authentication_token_timeout: uint8 | None,
use_invalid_peer_response: bool, use_invalid_peer_response: bool,
has_valid_authentication_keys: bool, has_valid_authentication_keys: bool,
expected_pool_stats: dict[str, Any], expected_pool_stats: dict[str, Any],
@@ -676,9 +676,9 @@ async def test_farmer_new_proof_of_space_for_pool_stats(
class DummyPoolResponse: class DummyPoolResponse:
ok: bool ok: bool
status: int status: int
error_code: Optional[int] = None error_code: int | None = None
error_message: Optional[str] = None error_message: str | None = None
new_difficulty: Optional[int] = None new_difficulty: int | None = None
async def text(self) -> str: async def text(self) -> str:
json_dict: dict[str, Any] = dict() json_dict: dict[str, Any] = dict()
@@ -695,9 +695,9 @@ class DummyPoolResponse:
async def __aexit__( async def __aexit__(
self, self,
exc_type: Optional[type[BaseException]], exc_type: type[BaseException] | None,
exc_val: Optional[BaseException], exc_val: BaseException | None,
exc_tb: Optional[TracebackType], exc_tb: TracebackType | None,
) -> None: ) -> None:
pass pass
@@ -1010,7 +1010,7 @@ class DummyPoolInfoResponse:
ok: bool ok: bool
status: int status: int
url: URL url: URL
pool_info: Optional[dict[str, Any]] = None pool_info: dict[str, Any] | None = None
history: tuple[DummyClientResponse, ...] = () history: tuple[DummyClientResponse, ...] = ()
async def text(self) -> str: async def text(self) -> str:
@@ -1024,9 +1024,9 @@ class DummyPoolInfoResponse:
async def __aexit__( async def __aexit__(
self, self,
exc_type: Optional[type[BaseException]], exc_type: type[BaseException] | None,
exc_val: Optional[BaseException], exc_val: BaseException | None,
exc_tb: Optional[TracebackType], exc_tb: TracebackType | None,
) -> None: ) -> None:
pass pass
@@ -4,7 +4,7 @@ import asyncio
import unittest.mock import unittest.mock
from math import floor from math import floor
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any
from unittest.mock import AsyncMock, Mock from unittest.mock import AsyncMock, Mock
import pytest import pytest
@@ -56,12 +56,12 @@ def farmer_is_started(farmer: Farmer) -> bool:
return farmer.started return farmer.started
async def get_harvester_config(harvester_rpc_port: Optional[int], root_path: Path) -> dict[str, Any]: async def get_harvester_config(harvester_rpc_port: int | None, root_path: Path) -> dict[str, Any]:
async with get_any_service_client(HarvesterRpcClient, root_path, harvester_rpc_port) as (harvester_client, _): async with get_any_service_client(HarvesterRpcClient, root_path, harvester_rpc_port) as (harvester_client, _):
return await harvester_client.get_harvester_config() return await harvester_client.get_harvester_config()
async def update_harvester_config(harvester_rpc_port: Optional[int], root_path: Path, config: dict[str, Any]) -> bool: async def update_harvester_config(harvester_rpc_port: int | None, root_path: Path, config: dict[str, Any]) -> bool:
async with get_any_service_client(HarvesterRpcClient, root_path, harvester_rpc_port) as (harvester_client, _): async with get_any_service_client(HarvesterRpcClient, root_path, harvester_rpc_port) as (harvester_client, _):
return await harvester_client.update_harvester_config(config) return await harvester_client.update_harvester_config(config)
@@ -2,7 +2,7 @@ from __future__ import annotations
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any
import pytest import pytest
from chia_rs import FullBlock from chia_rs import FullBlock
@@ -94,7 +94,7 @@ async def test_filter_prefix_bits_with_farmer_harvester(
state_change = None state_change = None
state_change_data = None state_change_data = None
def state_changed_callback(change: str, change_data: Optional[dict[str, Any]]) -> None: def state_changed_callback(change: str, change_data: dict[str, Any] | None) -> None:
nonlocal state_change, state_change_data nonlocal state_change, state_change_data
state_change = change state_change = change
state_change_data = change_data state_change_data = change_data
@@ -7,7 +7,7 @@ import dataclasses
import json import json
import logging import logging
from os.path import dirname from os.path import dirname
from typing import Optional, Union, cast from typing import cast
import pytest import pytest
from chia_rs import ( from chia_rs import (
@@ -61,8 +61,8 @@ async def test_harvester_receive_source_signing_data(
farmer_harvester_2_simulators_zero_bits_plot_filter: tuple[ farmer_harvester_2_simulators_zero_bits_plot_filter: tuple[
FarmerService, FarmerService,
HarvesterService, HarvesterService,
Union[FullNodeService, SimulatorFullNodeService], FullNodeService | SimulatorFullNodeService,
Union[FullNodeService, SimulatorFullNodeService], FullNodeService | SimulatorFullNodeService,
BlockTools, BlockTools,
], ],
) -> None: ) -> None:
@@ -121,12 +121,12 @@ async def test_harvester_receive_source_signing_data(
async def intercept_harvester_request_signatures( async def intercept_harvester_request_signatures(
self: HarvesterAPI, request: harvester_protocol.RequestSignatures self: HarvesterAPI, request: harvester_protocol.RequestSignatures
) -> Optional[Message]: ) -> Message | None:
nonlocal harvester nonlocal harvester
nonlocal farmer_reward_address nonlocal farmer_reward_address
validate_harvester_request_signatures(request) validate_harvester_request_signatures(request)
result_msg: Optional[Message] = await HarvesterAPI.request_signatures( result_msg: Message | None = await HarvesterAPI.request_signatures(
cast(HarvesterAPI, harvester.server.api), request cast(HarvesterAPI, harvester.server.api), request
) )
assert result_msg is not None assert result_msg is not None
@@ -158,15 +158,14 @@ async def test_harvester_receive_source_signing_data(
assert hash assert hash
assert src assert src
data: Optional[ data: (
Union[ FoliageBlockData
FoliageBlockData, | FoliageTransactionBlock
FoliageTransactionBlock, | ClassgroupElement
ClassgroupElement, | ChallengeChainSubSlot
ChallengeChainSubSlot, | RewardChainSubSlot
RewardChainSubSlot, | None
] ) = None
] = None
if src.kind == uint8(SigningDataKind.FOLIAGE_BLOCK_DATA): if src.kind == uint8(SigningDataKind.FOLIAGE_BLOCK_DATA):
data = FoliageBlockData.from_bytes(src.data) data = FoliageBlockData.from_bytes(src.data)
assert ( assert (
@@ -227,7 +226,7 @@ async def test_harvester_receive_source_signing_data(
async def intercept_farmer_request_signed_values( async def intercept_farmer_request_signed_values(
self: FarmerAPI, request: farmer_protocol.RequestSignedValues self: FarmerAPI, request: farmer_protocol.RequestSignedValues
) -> Optional[Message]: ) -> Message | None:
nonlocal farmer nonlocal farmer
nonlocal farmer_reward_address nonlocal farmer_reward_address
nonlocal full_node_2 nonlocal full_node_2
@@ -284,8 +283,8 @@ async def test_harvester_fee_convention(
farmer_harvester_2_simulators_zero_bits_plot_filter: tuple[ farmer_harvester_2_simulators_zero_bits_plot_filter: tuple[
FarmerService, FarmerService,
HarvesterService, HarvesterService,
Union[FullNodeService, SimulatorFullNodeService], FullNodeService | SimulatorFullNodeService,
Union[FullNodeService, SimulatorFullNodeService], FullNodeService | SimulatorFullNodeService,
BlockTools, BlockTools,
], ],
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
@@ -314,8 +313,8 @@ async def test_harvester_fee_invalid_convention(
farmer_harvester_2_simulators_zero_bits_plot_filter: tuple[ farmer_harvester_2_simulators_zero_bits_plot_filter: tuple[
FarmerService, FarmerService,
HarvesterService, HarvesterService,
Union[FullNodeService, SimulatorFullNodeService], FullNodeService | SimulatorFullNodeService,
Union[FullNodeService, SimulatorFullNodeService], FullNodeService | SimulatorFullNodeService,
BlockTools, BlockTools,
], ],
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
@@ -437,7 +436,7 @@ def node_type_connected(server: ChiaServer, node_type: NodeType) -> bool:
def decode_sp( def decode_sp(
is_sub_slot: bool, sp64: str is_sub_slot: bool, sp64: str
) -> Union[timelord_protocol.NewEndOfSubSlotVDF, timelord_protocol.NewSignagePointVDF]: ) -> timelord_protocol.NewEndOfSubSlotVDF | timelord_protocol.NewSignagePointVDF:
sp_bytes = base64.b64decode(sp64) sp_bytes = base64.b64decode(sp64)
if is_sub_slot: if is_sub_slot:
return timelord_protocol.NewEndOfSubSlotVDF.from_bytes(sp_bytes) return timelord_protocol.NewEndOfSubSlotVDF.from_bytes(sp_bytes)
@@ -496,7 +495,7 @@ async def inject_signage_points(signage_points: SPList, full_node_1: FullNode, f
api2 = cast(FullNodeAPI, full_node_2.server.api) api2 = cast(FullNodeAPI, full_node_2.server.api)
for i, sp in enumerate(signage_points): for i, sp in enumerate(signage_points):
req: Union[full_node_protocol.RespondEndOfSubSlot, full_node_protocol.RespondSignagePoint] req: full_node_protocol.RespondEndOfSubSlot | full_node_protocol.RespondSignagePoint
if isinstance(sp, timelord_protocol.NewEndOfSubSlotVDF): if isinstance(sp, timelord_protocol.NewEndOfSubSlotVDF):
full_node_1.log.info(f"Injecting SP for end of sub-slot @ {i}") full_node_1.log.info(f"Injecting SP for end of sub-slot @ {i}")
+5 -5
View File
@@ -3,11 +3,11 @@ from __future__ import annotations
import asyncio import asyncio
import contextlib import contextlib
import functools import functools
from collections.abc import AsyncIterator from collections.abc import AsyncIterator, Callable
from dataclasses import dataclass, field, replace from dataclasses import dataclass, field, replace
from pathlib import Path from pathlib import Path
from shutil import copy from shutil import copy
from typing import Any, Callable, Optional from typing import Any
import pytest import pytest
from chia_rs import G1Element, PlotParam from chia_rs import G1Element, PlotParam
@@ -131,7 +131,7 @@ class Environment:
split_farmer_service_manager: SplitAsyncManager[FarmerService] split_farmer_service_manager: SplitAsyncManager[FarmerService]
split_harvester_managers: list[SplitAsyncManager[Harvester]] split_harvester_managers: list[SplitAsyncManager[Harvester]]
def get_harvester(self, peer_id: bytes32) -> Optional[Harvester]: def get_harvester(self, peer_id: bytes32) -> Harvester | None:
for harvester in self.harvesters: for harvester in self.harvesters:
assert harvester.server is not None assert harvester.server is not None
if harvester.server.node_id == peer_id: if harvester.server.node_id == peer_id:
@@ -187,10 +187,10 @@ class Environment:
self.remove_directory(harvester_index, self.dir_invalid, State.invalid) self.remove_directory(harvester_index, self.dir_invalid, State.invalid)
self.remove_directory(harvester_index, self.dir_duplicates, State.duplicates) self.remove_directory(harvester_index, self.dir_duplicates, State.duplicates)
async def plot_sync_callback(self, peer_id: bytes32, delta: Optional[Delta]) -> None: async def plot_sync_callback(self, peer_id: bytes32, delta: Delta | None) -> None:
if delta is None: if delta is None:
return return
harvester: Optional[Harvester] = self.get_harvester(peer_id) harvester: Harvester | None = self.get_harvester(peer_id)
assert harvester is not None assert harvester is not None
expected = self.expected[self.harvesters.index(harvester)] expected = self.expected[self.harvesters.index(harvester)]
assert len(expected.valid_delta.additions) == len(delta.valid.additions) assert len(expected.valid_delta.additions) == len(delta.valid.additions)
+4 -3
View File
@@ -4,7 +4,8 @@ import dataclasses
import logging import logging
import random import random
import time import time
from typing import Any, Callable, Union from collections.abc import Callable
from typing import Any
import pytest import pytest
from chia_rs import G1Element from chia_rs import G1Element
@@ -90,7 +91,7 @@ def assert_error_response(plot_sync: Receiver, error_code: ErrorCodes) -> None:
assert response.error.code == error_code.value assert response.error.code == error_code.value
def pre_function_validate(receiver: Receiver, data: Union[list[Plot], list[str]], expected_state: State) -> None: def pre_function_validate(receiver: Receiver, data: list[Plot] | list[str], expected_state: State) -> None:
if expected_state == State.loaded: if expected_state == State.loaded:
for plot_info in data: for plot_info in data:
assert type(plot_info) is Plot assert type(plot_info) is Plot
@@ -109,7 +110,7 @@ def pre_function_validate(receiver: Receiver, data: Union[list[Plot], list[str]]
assert path not in receiver.duplicates() assert path not in receiver.duplicates()
def post_function_validate(receiver: Receiver, data: Union[list[Plot], list[str]], expected_state: State) -> None: def post_function_validate(receiver: Receiver, data: list[Plot] | list[str], expected_state: State) -> None:
if expected_state == State.loaded: if expected_state == State.loaded:
for plot_info in data: for plot_info in data:
assert type(plot_info) is Plot assert type(plot_info) is Plot
+2 -2
View File
@@ -10,7 +10,7 @@ from collections.abc import AsyncIterator
from dataclasses import dataclass, field from dataclasses import dataclass, field
from enum import Enum from enum import Enum
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any
import pytest import pytest
from chia_rs import G1Element from chia_rs import G1Element
@@ -102,7 +102,7 @@ class TestData:
batch_size = self.harvester.plot_manager.refresh_parameter.batch_size batch_size = self.harvester.plot_manager.refresh_parameter.batch_size
# Used to capture the sync id in `run_internal` # Used to capture the sync id in `run_internal`
sync_id: Optional[uint64] = None sync_id: uint64 | None = None
def run_internal() -> None: def run_internal() -> None:
nonlocal sync_id nonlocal sync_id
+1 -2
View File
@@ -4,7 +4,6 @@ import contextlib
import time import time
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint16, uint64 from chia_rs.sized_ints import uint16, uint64
@@ -25,7 +24,7 @@ class WSChiaConnectionDummy:
connection_type: NodeType connection_type: NodeType
peer_node_id: bytes32 peer_node_id: bytes32
peer_info: PeerInfo = PeerInfo("127.0.0.1", uint16(0)) peer_info: PeerInfo = PeerInfo("127.0.0.1", uint16(0))
last_sent_message: Optional[Message] = None last_sent_message: Message | None = None
async def send_message(self, message: Message) -> None: async def send_message(self, message: Message) -> None:
self.last_sent_message = message self.last_sent_message = message
+3 -3
View File
@@ -3,12 +3,12 @@ from __future__ import annotations
import logging import logging
import sys import sys
import time import time
from collections.abc import Iterator from collections.abc import Callable, Iterator
from dataclasses import dataclass, replace from dataclasses import dataclass, replace
from os import unlink from os import unlink
from pathlib import Path from pathlib import Path
from shutil import copy, move from shutil import copy, move
from typing import Callable, Optional, cast from typing import cast
import pytest import pytest
from chia_rs import G1Element from chia_rs import G1Element
@@ -664,7 +664,7 @@ async def test_cache_lifetime(environment: Environment) -> None:
) )
@pytest.mark.anyio @pytest.mark.anyio
async def test_callback_event_raises(environment, event_to_raise: PlotRefreshEvents): async def test_callback_event_raises(environment, event_to_raise: PlotRefreshEvents):
last_event_fired: Optional[PlotRefreshEvents] = None last_event_fired: PlotRefreshEvents | None = None
def raising_callback(event: PlotRefreshEvents, _: PlotRefreshResult): def raising_callback(event: PlotRefreshEvents, _: PlotRefreshResult):
nonlocal last_event_fired nonlocal last_event_fired
+3 -3
View File
@@ -4,7 +4,7 @@ import json
import re import re
from dataclasses import dataclass from dataclasses import dataclass
from io import StringIO from io import StringIO
from typing import Optional, cast from typing import cast
import click import click
import pytest import pytest
@@ -59,8 +59,8 @@ pytestmark = [pytest.mark.limit_consensus_modes(reason="irrelevant")]
class StateUrlCase: class StateUrlCase:
id: str id: str
state: str state: str
pool_url: Optional[str] pool_url: str | None
expected_error: Optional[str] = None expected_error: str | None = None
marks: Marks = () marks: Marks = ()
+3 -3
View File
@@ -8,7 +8,7 @@ from collections.abc import AsyncIterator
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from shutil import rmtree from shutil import rmtree
from typing import Any, Union from typing import Any
import pytest import pytest
@@ -211,7 +211,7 @@ async def process_plotnft_create(
) -> int: ) -> int:
wallet_rpc: WalletRpcClient = wallet_test_framework.environments[0].rpc_client wallet_rpc: WalletRpcClient = wallet_test_framework.environments[0].rpc_client
pre_block_balance_updates: dict[Union[int, str], dict[str, int]] = { pre_block_balance_updates: dict[int | str, dict[str, int]] = {
1: { 1: {
"confirmed_wallet_balance": 0, "confirmed_wallet_balance": 0,
"unconfirmed_wallet_balance": -1, "unconfirmed_wallet_balance": -1,
@@ -222,7 +222,7 @@ async def process_plotnft_create(
} }
} }
post_block_balance_updates: dict[Union[int, str], dict[str, int]] = { post_block_balance_updates: dict[int | str, dict[str, int]] = {
1: { 1: {
"confirmed_wallet_balance": -1, "confirmed_wallet_balance": -1,
"unconfirmed_wallet_balance": 0, "unconfirmed_wallet_balance": 0,
+3 -3
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from typing import Any, Optional, cast from typing import Any, cast
from unittest.mock import MagicMock from unittest.mock import MagicMock
import pytest import pytest
@@ -27,7 +27,7 @@ class MockStandardWallet:
@dataclass @dataclass
class MockWalletStateManager: class MockWalletStateManager:
root_path: Optional[Path] = None root_path: Path | None = None
config: dict[str, Any] = field(default_factory=dict) config: dict[str, Any] = field(default_factory=dict)
@@ -43,7 +43,7 @@ class MockPoolWalletConfig:
@dataclass @dataclass
class MockPoolState: class MockPoolState:
pool_url: Optional[str] pool_url: str | None
target_puzzle_hash: bytes32 target_puzzle_hash: bytes32
owner_pubkey: G1Element owner_pubkey: G1Element
+1 -4
View File
@@ -2,7 +2,6 @@ from __future__ import annotations
import random import random
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Optional
import pytest import pytest
from chia_rs import CoinSpend from chia_rs import CoinSpend
@@ -18,9 +17,7 @@ from chia.wallet.util.compute_additions import compute_additions
from chia.wallet.wallet_pool_store import WalletPoolStore from chia.wallet.wallet_pool_store import WalletPoolStore
def make_child_solution( def make_child_solution(coin_spend: CoinSpend | None, new_coin: Coin | None, seeded_random: random.Random) -> CoinSpend:
coin_spend: Optional[CoinSpend], new_coin: Optional[Coin], seeded_random: random.Random
) -> CoinSpend:
new_puzzle_hash: bytes32 = bytes32.random(seeded_random) new_puzzle_hash: bytes32 = bytes32.random(seeded_random)
solution = "()" solution = "()"
puzzle = f"(q . ((51 0x{new_puzzle_hash.hex()} 1)))" puzzle = f"(q . ((51 0x{new_puzzle_hash.hex()} 1)))"
+2 -2
View File
@@ -7,7 +7,7 @@ from collections import defaultdict
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from statistics import StatisticsError, mean, stdev from statistics import StatisticsError, mean, stdev
from typing import Any, Optional, TextIO, final from typing import Any, TextIO, final
import click import click
import lxml.etree import lxml.etree
@@ -126,7 +126,7 @@ def main(
percent_margin: int, percent_margin: int,
randomoji: bool, randomoji: bool,
tag: str, tag: str,
result_count_limit: Optional[int], result_count_limit: int | None,
) -> None: ) -> None:
data_type = supported_data_types_by_tag[tag] data_type = supported_data_types_by_tag[tag]
+4 -4
View File
@@ -1,9 +1,9 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import AsyncIterator, Awaitable from collections.abc import AsyncIterator, Awaitable, Callable
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Any, Callable, Optional from typing import Any
import pytest import pytest
from chia_rs.sized_ints import uint16 from chia_rs.sized_ints import uint16
@@ -31,8 +31,8 @@ client_fetch_methods = [
@dataclass @dataclass
class InvalidCreateCase: class InvalidCreateCase:
id: str id: str
root_path: Optional[Path] = None root_path: Path | None = None
net_config: Optional[dict[str, Any]] = None net_config: dict[str, Any] | None = None
marks: Marks = () marks: Marks = ()
+3 -3
View File
@@ -7,7 +7,7 @@ import ssl
import sys import sys
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, Optional, cast from typing import TYPE_CHECKING, Any, ClassVar, cast
import aiohttp import aiohttp
import pytest import pytest
@@ -42,7 +42,7 @@ class TestRpcApi:
service: RpcServiceProtocol service: RpcServiceProtocol
service_name: str = service_name service_name: str = service_name
async def _state_changed(self, change: str, change_data: Optional[dict[str, Any]] = None) -> list[WsRpcMessage]: async def _state_changed(self, change: str, change_data: dict[str, Any] | None = None) -> list[WsRpcMessage]:
# just here to satisfy the complete protocol # just here to satisfy the complete protocol
return [] # pragma: no cover return [] # pragma: no cover
@@ -73,7 +73,7 @@ class Client:
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
yield cls(session=session, ssl_context=ssl_context, url=url) yield cls(session=session, ssl_context=ssl_context, url=url)
async def request(self, endpoint: str, json: Optional[dict[str, Any]] = None) -> dict[str, Any]: async def request(self, endpoint: str, json: dict[str, Any] | None = None) -> dict[str, Any]:
if json is None: if json is None:
json = {} json = {}
+2 -2
View File
@@ -1,9 +1,9 @@
from __future__ import annotations from __future__ import annotations
from typing import Literal, Union from typing import Literal
# Defaults are conservative. # Defaults are conservative.
parallel: Union[bool, int, Literal["auto"]] = True parallel: bool | int | Literal["auto"] = True
checkout_blocks_and_plots = False checkout_blocks_and_plots = False
install_timelord = False install_timelord = False
# NOTE: do not use until the hangs are fixed # NOTE: do not use until the hangs are fixed
+2 -4
View File
@@ -1,7 +1,5 @@
from __future__ import annotations from __future__ import annotations
from typing import Optional
import pytest import pytest
from chia_rs import BlockRecord, FullBlock, SubEpochSummary, UnfinishedBlock from chia_rs import BlockRecord, FullBlock, SubEpochSummary, UnfinishedBlock
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -579,7 +577,7 @@ def get_recent_reward_challenges(blockchain: Blockchain) -> list[tuple[bytes32,
if peak is None: if peak is None:
return [] return []
recent_rc: list[tuple[bytes32, uint128]] = [] recent_rc: list[tuple[bytes32, uint128]] = []
curr: Optional[BlockRecord] = peak curr: BlockRecord | None = peak
while curr is not None and len(recent_rc) < 2 * blockchain.constants.MAX_SUB_SLOT_BLOCKS: while curr is not None and len(recent_rc) < 2 * blockchain.constants.MAX_SUB_SLOT_BLOCKS:
if curr != peak: if curr != peak:
recent_rc.append((curr.reward_infusion_new_challenge, curr.total_iters)) recent_rc.append((curr.reward_infusion_new_challenge, curr.total_iters))
@@ -602,7 +600,7 @@ def timelord_peak_from_block(
) -> timelord_protocol.NewPeakTimelord: ) -> timelord_protocol.NewPeakTimelord:
peak = blockchain.block_record(block.header_hash) peak = blockchain.block_record(block.header_hash)
_, difficulty = get_next_sub_slot_iters_and_difficulty(blockchain.constants, False, peak, blockchain) _, difficulty = get_next_sub_slot_iters_and_difficulty(blockchain.constants, False, peak, blockchain)
ses: Optional[SubEpochSummary] = next_sub_epoch_summary( ses: SubEpochSummary | None = next_sub_epoch_summary(
blockchain.constants, blockchain, peak.required_iters, block, True blockchain.constants, blockchain, peak.required_iters, block, True
) )
+2 -1
View File
@@ -1,8 +1,9 @@
from __future__ import annotations from __future__ import annotations
import textwrap import textwrap
from collections.abc import Callable
from pathlib import Path from pathlib import Path
from typing import Any, Callable from typing import Any
import click import click
import pytest import pytest
+3 -4
View File
@@ -5,7 +5,6 @@ import os
import pickle # noqa: S403 # TODO: use explicit serialization instead of pickle import pickle # noqa: S403 # TODO: use explicit serialization instead of pickle
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from pathlib import Path from pathlib import Path
from typing import Optional
from chia_rs import ConsensusConstants, FullBlock from chia_rs import ConsensusConstants, FullBlock
from chia_rs.sized_ints import uint64 from chia_rs.sized_ints import uint64
@@ -49,8 +48,8 @@ def persistent_blocks(
normalized_to_identity_icc_eos: bool = False, normalized_to_identity_icc_eos: bool = False,
normalized_to_identity_cc_sp: bool = False, normalized_to_identity_cc_sp: bool = False,
normalized_to_identity_cc_ip: bool = False, normalized_to_identity_cc_ip: bool = False,
block_list_input: Optional[list[FullBlock]] = None, block_list_input: list[FullBlock] | None = None,
time_per_block: Optional[float] = None, time_per_block: float | None = None,
dummy_block_references: bool = False, dummy_block_references: bool = False,
include_transactions: bool = False, include_transactions: bool = False,
) -> list[FullBlock]: ) -> list[FullBlock]:
@@ -112,7 +111,7 @@ def new_test_db(
empty_sub_slots: int, empty_sub_slots: int,
bt: BlockTools, bt: BlockTools,
block_list_input: list[FullBlock], block_list_input: list[FullBlock],
time_per_block: Optional[float], time_per_block: float | None,
*, *,
normalized_to_identity_cc_eos: bool = False, # CC_EOS, normalized_to_identity_cc_eos: bool = False, # CC_EOS,
normalized_to_identity_icc_eos: bool = False, # ICC_EOS normalized_to_identity_icc_eos: bool = False, # ICC_EOS
+11 -11
View File
@@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
from typing import TYPE_CHECKING, ClassVar, Optional, cast from typing import TYPE_CHECKING, ClassVar, cast
from chia_rs import BlockRecord, HeaderBlock, SubEpochChallengeSegment, SubEpochSegments, SubEpochSummary from chia_rs import BlockRecord, HeaderBlock, SubEpochChallengeSegment, SubEpochSegments, SubEpochSummary
from chia_rs.sized_bytes import bytes32 from chia_rs.sized_bytes import bytes32
@@ -20,9 +20,9 @@ class BlockchainMock:
def __init__( def __init__(
self, self,
blocks: dict[bytes32, BlockRecord], blocks: dict[bytes32, BlockRecord],
headers: Optional[dict[bytes32, HeaderBlock]] = None, headers: dict[bytes32, HeaderBlock] | None = None,
height_to_hash: Optional[dict[uint32, bytes32]] = None, height_to_hash: dict[uint32, bytes32] | None = None,
sub_epoch_summaries: Optional[dict[uint32, SubEpochSummary]] = None, sub_epoch_summaries: dict[uint32, SubEpochSummary] | None = None,
): ):
if sub_epoch_summaries is None: if sub_epoch_summaries is None:
sub_epoch_summaries = {} sub_epoch_summaries = {}
@@ -37,10 +37,10 @@ class BlockchainMock:
self._sub_epoch_segments: dict[bytes32, SubEpochSegments] = {} self._sub_epoch_segments: dict[bytes32, SubEpochSegments] = {}
self.log = logging.getLogger(__name__) self.log = logging.getLogger(__name__)
def get_peak(self) -> Optional[BlockRecord]: def get_peak(self) -> BlockRecord | None:
return None return None
def get_peak_height(self) -> Optional[uint32]: def get_peak_height(self) -> uint32 | None:
return None return None
def block_record(self, header_hash: bytes32) -> BlockRecord: def block_record(self, header_hash: bytes32) -> BlockRecord:
@@ -49,7 +49,7 @@ class BlockchainMock:
def height_to_block_record(self, height: uint32, check_db: bool = False) -> BlockRecord: def height_to_block_record(self, height: uint32, check_db: bool = False) -> BlockRecord:
# Precondition: height is < peak height # Precondition: height is < peak height
header_hash: Optional[bytes32] = self.height_to_hash(height) header_hash: bytes32 | None = self.height_to_hash(height)
assert header_hash is not None assert header_hash is not None
return self.block_record(header_hash) return self.block_record(header_hash)
@@ -60,7 +60,7 @@ class BlockchainMock:
def get_ses(self, height: uint32) -> SubEpochSummary: def get_ses(self, height: uint32) -> SubEpochSummary:
return self._sub_epoch_summaries[height] return self._sub_epoch_summaries[height]
def height_to_hash(self, height: uint32) -> Optional[bytes32]: def height_to_hash(self, height: uint32) -> bytes32 | None:
assert height in self._height_to_hash assert height in self._height_to_hash
return self._height_to_hash[height] return self._height_to_hash[height]
@@ -88,10 +88,10 @@ class BlockchainMock:
block_records.append(self.height_to_block_record(height)) block_records.append(self.height_to_block_record(height))
return block_records return block_records
def try_block_record(self, header_hash: bytes32) -> Optional[BlockRecord]: def try_block_record(self, header_hash: bytes32) -> BlockRecord | None:
return self._block_records.get(header_hash) return self._block_records.get(header_hash)
async def get_block_record_from_db(self, header_hash: bytes32) -> Optional[BlockRecord]: async def get_block_record_from_db(self, header_hash: bytes32) -> BlockRecord | None:
return self._block_records[header_hash] return self._block_records[header_hash]
async def prev_block_hash(self, header_hashes: list[bytes32]) -> list[bytes32]: async def prev_block_hash(self, header_hashes: list[bytes32]) -> list[bytes32]:
@@ -119,7 +119,7 @@ class BlockchainMock:
async def get_sub_epoch_challenge_segments( async def get_sub_epoch_challenge_segments(
self, self,
sub_epoch_summary_hash: bytes32, sub_epoch_summary_hash: bytes32,
) -> Optional[list[SubEpochChallengeSegment]]: ) -> list[SubEpochChallengeSegment] | None:
segments = self._sub_epoch_segments.get(sub_epoch_summary_hash) segments = self._sub_epoch_segments.get(sub_epoch_summary_hash)
if segments is None: if segments is None:
return None return None
@@ -4,8 +4,9 @@ from __future__ import annotations
import os import os
import subprocess import subprocess
import sys import sys
from collections.abc import Callable
from pathlib import Path from pathlib import Path
from typing import Any, Callable from typing import Any
from chia_rs.sized_ints import uint32 from chia_rs.sized_ints import uint32
+2 -3
View File
@@ -4,7 +4,6 @@ import tempfile
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from pathlib import Path from pathlib import Path
from typing import Optional
import aiosqlite import aiosqlite
@@ -14,8 +13,8 @@ from chia.util.db_wrapper import DBWrapper2, generate_in_memory_db_uri
@asynccontextmanager @asynccontextmanager
async def DBConnection( async def DBConnection(
db_version: int, db_version: int,
foreign_keys: Optional[bool] = None, foreign_keys: bool | None = None,
row_factory: Optional[type[aiosqlite.Row]] = None, row_factory: type[aiosqlite.Row] | None = None,
) -> AsyncIterator[DBWrapper2]: ) -> AsyncIterator[DBWrapper2]:
db_uri = generate_in_memory_db_uri() db_uri = generate_in_memory_db_uri()
async with DBWrapper2.managed( async with DBWrapper2.managed(
+9 -11
View File
@@ -5,10 +5,10 @@ import logging
import shutil import shutil
import tempfile import tempfile
import time import time
from collections.abc import Iterator from collections.abc import Callable, Iterator
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from typing import Callable, Optional, cast from typing import cast
import aiosqlite import aiosqlite
import zstd import zstd
@@ -60,9 +60,7 @@ def enable_profiler(profile: bool, counter: int) -> Iterator[None]:
class FakeServer: class FakeServer:
async def send_to_all( async def send_to_all(self, messages: list[Message], node_type: NodeType, exclude: bytes32 | None = None) -> None:
self, messages: list[Message], node_type: NodeType, exclude: Optional[bytes32] = None
) -> None:
pass pass
async def send_to_all_if( async def send_to_all_if(
@@ -70,18 +68,18 @@ class FakeServer:
messages: list[Message], messages: list[Message],
node_type: NodeType, node_type: NodeType,
predicate: Callable[[WSChiaConnection], bool], predicate: Callable[[WSChiaConnection], bool],
exclude: Optional[bytes32] = None, exclude: bytes32 | None = None,
) -> None: ) -> None:
pass pass
def set_received_message_callback(self, callback: ConnectionCallback) -> None: def set_received_message_callback(self, callback: ConnectionCallback) -> None:
pass pass
async def get_peer_info(self) -> Optional[PeerInfo]: async def get_peer_info(self) -> PeerInfo | None:
return None return None
def get_connections( def get_connections(
self, node_type: Optional[NodeType] = None, *, outbound: Optional[bool] = False self, node_type: NodeType | None = None, *, outbound: bool | None = False
) -> list[WSChiaConnection]: ) -> list[WSChiaConnection]:
return [] return []
@@ -91,7 +89,7 @@ class FakeServer:
async def start_client( async def start_client(
self, self,
target_node: PeerInfo, target_node: PeerInfo,
on_connect: Optional[ConnectionCallback] = None, on_connect: ConnectionCallback | None = None,
auth: bool = False, auth: bool = False,
is_feeler: bool = False, is_feeler: bool = False,
) -> bool: ) -> bool:
@@ -105,7 +103,7 @@ class FakePeer:
def __init__(self) -> None: def __init__(self) -> None:
self.peer_node_id = bytes([0] * 32) self.peer_node_id = bytes([0] * 32)
async def get_peer_info(self) -> Optional[PeerInfo]: async def get_peer_info(self) -> PeerInfo | None:
return None return None
@@ -118,7 +116,7 @@ async def run_sync_test(
keep_up: bool, keep_up: bool,
db_sync: str, db_sync: str,
node_profiler: bool, node_profiler: bool,
start_at_checkpoint: Optional[str], start_at_checkpoint: str | None,
) -> None: ) -> None:
logger = logging.getLogger() logger = logging.getLogger()
logger.setLevel(logging.WARNING) logger.setLevel(logging.WARNING)
+4 -5
View File
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import Optional
import click import click
from pytest import MonkeyPatch from pytest import MonkeyPatch
@@ -20,8 +19,8 @@ from chia.ssl.create_ssl import generate_ca_signed_cert, get_chia_ca_crt_key, ma
required=True, required=True,
) )
def gen_ssl(suffix: str = "") -> None: def gen_ssl(suffix: str = "") -> None:
captured_crt: Optional[bytes] = None captured_crt: bytes | None = None
captured_key: Optional[bytes] = None captured_key: bytes | None = None
capture_cert_and_key = False capture_cert_and_key = False
def patched_write_ssl_cert_and_key(cert_path: Path, cert_data: bytes, key_path: Path, key_data: bytes) -> None: def patched_write_ssl_cert_and_key(cert_path: Path, cert_data: bytes, key_path: Path, key_data: bytes) -> None:
@@ -39,8 +38,8 @@ def gen_ssl(suffix: str = "") -> None:
patch = MonkeyPatch() patch = MonkeyPatch()
patch.setattr("chia.ssl.create_ssl.write_ssl_cert_and_key", patched_write_ssl_cert_and_key) patch.setattr("chia.ssl.create_ssl.write_ssl_cert_and_key", patched_write_ssl_cert_and_key)
private_ca_crt: Optional[bytes] = None private_ca_crt: bytes | None = None
private_ca_key: Optional[bytes] = None private_ca_key: bytes | None = None
capture_cert_and_key = True capture_cert_and_key = True
make_ca_cert(Path("SSL_TEST_PRIVATE_CA_CRT"), Path("SSL_TEST_PRIVATE_CA_KEY")) make_ca_cert(Path("SSL_TEST_PRIVATE_CA_CRT"), Path("SSL_TEST_PRIVATE_CA_KEY"))
+23 -23
View File
@@ -12,7 +12,7 @@ import pathlib
import ssl import ssl
import subprocess import subprocess
import sys import sys
from collections.abc import Awaitable, Collection, Iterator from collections.abc import Awaitable, Callable, Collection, Iterator
from concurrent.futures import Future from concurrent.futures import Future
from dataclasses import dataclass, field from dataclasses import dataclass, field
from enum import Enum from enum import Enum
@@ -20,7 +20,7 @@ from statistics import mean
from textwrap import dedent from textwrap import dedent
from time import thread_time from time import thread_time
from types import TracebackType from types import TracebackType
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional, Protocol, TextIO, TypeVar, Union, cast, final from typing import TYPE_CHECKING, Any, ClassVar, Protocol, TextIO, TypeVar, cast, final
import aiohttp import aiohttp
import pytest import pytest
@@ -88,7 +88,7 @@ class RuntimeResults:
duration: float duration: float
entry_file: str entry_file: str
entry_line: int entry_line: int
overhead: Optional[float] overhead: float | None
def block(self, label: str = "") -> str: def block(self, label: str = "") -> str:
# The entry line is reported starting at the beginning of the line to trigger # The entry line is reported starting at the beginning of the line to trigger
@@ -112,13 +112,13 @@ class AssertRuntimeResults:
duration: float duration: float
entry_file: str entry_file: str
entry_line: int entry_line: int
overhead: Optional[float] overhead: float | None
limit: float limit: float
ratio: float ratio: float
@classmethod @classmethod
def from_runtime_results( def from_runtime_results(
cls, results: RuntimeResults, limit: float, entry_file: str, entry_line: int, overhead: Optional[float] cls, results: RuntimeResults, limit: float, entry_file: str, entry_line: int, overhead: float | None
) -> AssertRuntimeResults: ) -> AssertRuntimeResults:
return cls( return cls(
start=results.start, start=results.start,
@@ -161,7 +161,7 @@ class AssertRuntimeResults:
def measure_overhead( def measure_overhead(
manager_maker: Callable[ manager_maker: Callable[
[], contextlib.AbstractContextManager[Union[Future[RuntimeResults], Future[AssertRuntimeResults]]] [], contextlib.AbstractContextManager[Future[RuntimeResults] | Future[AssertRuntimeResults]]
], ],
cycles: int = 10, cycles: int = 10,
) -> float: ) -> float:
@@ -183,7 +183,7 @@ def measure_runtime(
label: str = "", label: str = "",
clock: Callable[[], float] = thread_time, clock: Callable[[], float] = thread_time,
gc_mode: GcMode = GcMode.disable, gc_mode: GcMode = GcMode.disable,
overhead: Optional[float] = None, overhead: float | None = None,
print_results: bool = True, print_results: bool = True,
) -> Iterator[Future[RuntimeResults]]: ) -> Iterator[Future[RuntimeResults]]:
entry_file, entry_line = caller_file_and_line( entry_file, entry_line = caller_file_and_line(
@@ -289,12 +289,12 @@ class _AssertRuntime:
clock: Callable[[], float] = thread_time clock: Callable[[], float] = thread_time
gc_mode: GcMode = GcMode.disable gc_mode: GcMode = GcMode.disable
print: bool = True print: bool = True
overhead: Optional[float] = None overhead: float | None = None
entry_file: Optional[str] = None entry_file: str | None = None
entry_line: Optional[int] = None entry_line: int | None = None
_results: Optional[AssertRuntimeResults] = None _results: AssertRuntimeResults | None = None
runtime_manager: Optional[contextlib.AbstractContextManager[Future[RuntimeResults]]] = None runtime_manager: contextlib.AbstractContextManager[Future[RuntimeResults]] | None = None
runtime_results_callable: Optional[Future[RuntimeResults]] = None runtime_results_callable: Future[RuntimeResults] | None = None
enable_assertion: bool = True enable_assertion: bool = True
def __enter__(self) -> Future[AssertRuntimeResults]: def __enter__(self) -> Future[AssertRuntimeResults]:
@@ -315,9 +315,9 @@ class _AssertRuntime:
def __exit__( def __exit__(
self, self,
exc_type: Optional[type[BaseException]], exc_type: type[BaseException] | None,
exc: Optional[BaseException], exc: BaseException | None,
traceback: Optional[TracebackType], traceback: TracebackType | None,
) -> None: ) -> None:
if ( if (
self.entry_file is None self.entry_file is None
@@ -366,8 +366,8 @@ class _AssertRuntime:
@dataclasses.dataclass @dataclasses.dataclass
class BenchmarkRunner: class BenchmarkRunner:
enable_assertion: bool = True enable_assertion: bool = True
test_id: Optional[TestId] = None test_id: TestId | None = None
overhead: Optional[float] = None overhead: float | None = None
def assert_runtime(self, *args: Any, **kwargs: Any) -> _AssertRuntime: def assert_runtime(self, *args: Any, **kwargs: Any) -> _AssertRuntime:
kwargs.setdefault("enable_assertion", self.enable_assertion) kwargs.setdefault("enable_assertion", self.enable_assertion)
@@ -445,7 +445,7 @@ class CoinGenerator:
self._seed += 1 self._seed += 1
return uint64(self._seed) return uint64(self._seed)
def get(self, parent_coin_id: Optional[bytes32] = None, include_hint: bool = True) -> HintedCoin: def get(self, parent_coin_id: bytes32 | None = None, include_hint: bool = True) -> HintedCoin:
if parent_coin_id is None: if parent_coin_id is None:
parent_coin_id = self._get_hash() parent_coin_id = self._get_hash()
hint = None hint = None
@@ -516,7 +516,7 @@ class RecordingWebServer:
hostname: str, hostname: str,
port: uint16, port: uint16,
max_request_body_size: int = 1024**2, # Default `client_max_size` from web.Application max_request_body_size: int = 1024**2, # Default `client_max_size` from web.Application
ssl_context: Optional[ssl.SSLContext] = None, ssl_context: ssl.SSLContext | None = None,
prefer_ipv6: bool = False, prefer_ipv6: bool = False,
) -> RecordingWebServer: ) -> RecordingWebServer:
web_server = await WebServer.create( web_server = await WebServer.create(
@@ -657,9 +657,9 @@ def is_attribute_local(o: object, name: str) -> bool:
@contextlib.contextmanager @contextlib.contextmanager
def patch_request_handler( def patch_request_handler(
api: Union[ApiProtocol, type[ApiProtocol]], api: ApiProtocol | type[ApiProtocol],
handler: Callable[..., Awaitable[Optional[Message]]], handler: Callable[..., Awaitable[Message | None]],
request_type: Optional[ProtocolMessageTypes] = None, request_type: ProtocolMessageTypes | None = None,
) -> Iterator[None]: ) -> Iterator[None]:
if request_type is None: if request_type is None:
request_type = ProtocolMessageTypes[handler.__name__] request_type = ProtocolMessageTypes[handler.__name__]
+16 -17
View File
@@ -7,7 +7,6 @@ from collections.abc import AsyncIterator
from contextlib import AsyncExitStack, ExitStack, asynccontextmanager from contextlib import AsyncExitStack, ExitStack, asynccontextmanager
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Optional, Union
import anyio import anyio
from chia_rs import ConsensusConstants from chia_rs import ConsensusConstants
@@ -59,8 +58,8 @@ SimulatorsAndWalletsServices = tuple[list[SimulatorFullNodeService], list[Wallet
@dataclass(frozen=True) @dataclass(frozen=True)
class FullSystem: class FullSystem:
node_1: Union[FullNodeService, SimulatorFullNodeService] node_1: FullNodeService | SimulatorFullNodeService
node_2: Union[FullNodeService, SimulatorFullNodeService] node_2: FullNodeService | SimulatorFullNodeService
harvester: Harvester harvester: Harvester
farmer: Farmer farmer: Farmer
introducer: IntroducerAPI introducer: IntroducerAPI
@@ -159,11 +158,11 @@ async def setup_simulators_and_wallets(
spam_filter_after_n_txs: int = 200, spam_filter_after_n_txs: int = 200,
xch_spam_amount: int = 1000000, xch_spam_amount: int = 1000000,
*, *,
key_seed: Optional[bytes32] = None, key_seed: bytes32 | None = None,
initial_num_public_keys: int = 5, initial_num_public_keys: int = 5,
db_version: int = 2, db_version: int = 2,
config_overrides: Optional[dict[str, int]] = None, config_overrides: dict[str, int] | None = None,
disable_capabilities: Optional[list[Capability]] = None, disable_capabilities: list[Capability] | None = None,
) -> AsyncIterator[SimulatorsAndWallets]: ) -> AsyncIterator[SimulatorsAndWallets]:
with TempKeyring(populate=True) as keychain1, TempKeyring(populate=True) as keychain2: with TempKeyring(populate=True) as keychain1, TempKeyring(populate=True) as keychain2:
if config_overrides is None: if config_overrides is None:
@@ -212,11 +211,11 @@ async def setup_simulators_and_wallets_service(
spam_filter_after_n_txs: int = 200, spam_filter_after_n_txs: int = 200,
xch_spam_amount: int = 1000000, xch_spam_amount: int = 1000000,
*, *,
key_seed: Optional[bytes32] = None, key_seed: bytes32 | None = None,
initial_num_public_keys: int = 5, initial_num_public_keys: int = 5,
db_version: int = 2, db_version: int = 2,
config_overrides: Optional[dict[str, int]] = None, config_overrides: dict[str, int] | None = None,
disable_capabilities: Optional[list[Capability]] = None, disable_capabilities: list[Capability] | None = None,
) -> AsyncIterator[tuple[list[SimulatorFullNodeService], list[WalletService], BlockTools]]: ) -> AsyncIterator[tuple[list[SimulatorFullNodeService], list[WalletService], BlockTools]]:
with TempKeyring(populate=True) as keychain1, TempKeyring(populate=True) as keychain2: with TempKeyring(populate=True) as keychain1, TempKeyring(populate=True) as keychain2:
async with setup_simulators_and_wallets_inner( async with setup_simulators_and_wallets_inner(
@@ -241,15 +240,15 @@ async def setup_simulators_and_wallets_inner(
db_version: int, db_version: int,
consensus_constants: ConsensusConstants, consensus_constants: ConsensusConstants,
initial_num_public_keys: int, initial_num_public_keys: int,
key_seed: Optional[bytes32], key_seed: bytes32 | None,
keychain1: Keychain, keychain1: Keychain,
keychain2: Keychain, keychain2: Keychain,
simulator_count: int, simulator_count: int,
spam_filter_after_n_txs: int, spam_filter_after_n_txs: int,
wallet_count: int, wallet_count: int,
xch_spam_amount: int, xch_spam_amount: int,
config_overrides: Optional[dict[str, int]], config_overrides: dict[str, int] | None,
disable_capabilities: Optional[list[Capability]], disable_capabilities: list[Capability] | None,
) -> AsyncIterator[tuple[list[BlockTools], list[SimulatorFullNodeService], list[WalletService]]]: ) -> AsyncIterator[tuple[list[BlockTools], list[SimulatorFullNodeService], list[WalletService]]]:
if config_overrides is not None and "full_node.max_sync_wait" not in config_overrides: if config_overrides is not None and "full_node.max_sync_wait" not in config_overrides:
config_overrides["full_node.max_sync_wait"] = 0 config_overrides["full_node.max_sync_wait"] = 0
@@ -310,7 +309,7 @@ async def setup_farmer_solver_multi_harvester(
consensus_constants: ConsensusConstants, consensus_constants: ConsensusConstants,
*, *,
start_services: bool, start_services: bool,
solver_peer: Optional[UnresolvedPeerInfo] = None, solver_peer: UnresolvedPeerInfo | None = None,
) -> AsyncIterator[tuple[list[HarvesterService], FarmerService, BlockTools]]: ) -> AsyncIterator[tuple[list[HarvesterService], FarmerService, BlockTools]]:
async with AsyncExitStack() as async_exit_stack: async with AsyncExitStack() as async_exit_stack:
farmer_service = await async_exit_stack.enter_async_context( farmer_service = await async_exit_stack.enter_async_context(
@@ -348,8 +347,8 @@ async def setup_farmer_solver_multi_harvester(
async def setup_full_system( async def setup_full_system(
consensus_constants: ConsensusConstants, consensus_constants: ConsensusConstants,
shared_b_tools: BlockTools, shared_b_tools: BlockTools,
b_tools: Optional[BlockTools] = None, b_tools: BlockTools | None = None,
b_tools_1: Optional[BlockTools] = None, b_tools_1: BlockTools | None = None,
db_version: int = 2, db_version: int = 2,
) -> AsyncIterator[FullSystem]: ) -> AsyncIterator[FullSystem]:
with TempKeyring(populate=True) as keychain1, TempKeyring(populate=True) as keychain2: with TempKeyring(populate=True) as keychain1, TempKeyring(populate=True) as keychain2:
@@ -361,8 +360,8 @@ async def setup_full_system(
@asynccontextmanager @asynccontextmanager
async def setup_full_system_inner( async def setup_full_system_inner(
b_tools: Optional[BlockTools], b_tools: BlockTools | None,
b_tools_1: Optional[BlockTools], b_tools_1: BlockTools | None,
connect_to_daemon: bool, connect_to_daemon: bool,
consensus_constants: ConsensusConstants, consensus_constants: ConsensusConstants,
db_version: int, db_version: int,
+21 -21
View File
@@ -7,7 +7,7 @@ from collections.abc import AsyncIterator
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any
import anyio import anyio
from chia_rs import ( from chia_rs import (
@@ -58,7 +58,7 @@ and is designed so that you could test with it and then swap in a real rpc clien
@asynccontextmanager @asynccontextmanager
async def sim_and_client( async def sim_and_client(
db_path: Optional[Path] = None, defaults: ConsensusConstants = DEFAULT_CONSTANTS, pass_prefarm: bool = True db_path: Path | None = None, defaults: ConsensusConstants = DEFAULT_CONSTANTS, pass_prefarm: bool = True
) -> AsyncIterator[tuple[SpendSim, SimClient]]: ) -> AsyncIterator[tuple[SpendSim, SimClient]]:
async with SpendSim.managed(db_path, defaults) as sim: async with SpendSim.managed(db_path, defaults) as sim:
client: SimClient = SimClient(sim) client: SimClient = SimClient(sim)
@@ -103,7 +103,7 @@ class CostLogger:
@streamable @streamable
@dataclass(frozen=True) @dataclass(frozen=True)
class SimFullBlock(Streamable): class SimFullBlock(Streamable):
transactions_generator: Optional[BlockGenerator] transactions_generator: BlockGenerator | None
height: uint32 # Note that height is not on a regular FullBlock height: uint32 # Note that height is not on a regular FullBlock
@@ -155,7 +155,7 @@ class SpendSim:
@classmethod @classmethod
@contextlib.asynccontextmanager @contextlib.asynccontextmanager
async def managed( async def managed(
cls, db_path: Optional[Path] = None, defaults: ConsensusConstants = DEFAULT_CONSTANTS cls, db_path: Path | None = None, defaults: ConsensusConstants = DEFAULT_CONSTANTS
) -> AsyncIterator[Self]: ) -> AsyncIterator[Self]:
self = cls() self = cls()
if db_path is None: if db_path is None:
@@ -203,7 +203,7 @@ class SpendSim:
) )
await c.close() await c.close()
async def new_peak(self, spent_coins_ids: Optional[list[bytes32]]) -> None: async def new_peak(self, spent_coins_ids: list[bytes32] | None) -> None:
await self.mempool_manager.new_peak(self.block_records[-1], spent_coins_ids) await self.mempool_manager.new_peak(self.block_records[-1], spent_coins_ids)
def new_coin_record(self, coin: Coin, coinbase: bool = False) -> CoinRecord: def new_coin_record(self, coin: Coin, coinbase: bool = False) -> CoinRecord:
@@ -229,7 +229,7 @@ class SpendSim:
coins.add(coin) coins.add(coin)
return list(coins) return list(coins)
async def generate_transaction_generator(self, bundle: Optional[SpendBundle]) -> Optional[BlockGenerator]: async def generate_transaction_generator(self, bundle: SpendBundle | None) -> BlockGenerator | None:
if bundle is None: if bundle is None:
return None return None
return simple_solution_generator(bundle) return simple_solution_generator(bundle)
@@ -257,7 +257,7 @@ class SpendSim:
), ),
] ]
# Coin store gets updated # Coin store gets updated
generator_bundle: Optional[SpendBundle] = None generator_bundle: SpendBundle | None = None
tx_additions = [] tx_additions = []
tx_removals = [] tx_removals = []
spent_coins_ids = None spent_coins_ids = None
@@ -295,7 +295,7 @@ class SpendSim:
tx_removals=spent_coins_ids if spent_coins_ids is not None else [], tx_removals=spent_coins_ids if spent_coins_ids is not None else [],
) )
# SimBlockRecord is created # SimBlockRecord is created
generator: Optional[BlockGenerator] = await self.generate_transaction_generator(generator_bundle) generator: BlockGenerator | None = await self.generate_transaction_generator(generator_bundle)
self.block_records.append(SimBlockRecord.create(included_reward_coins, next_block_height, self.timestamp)) self.block_records.append(SimBlockRecord.create(included_reward_coins, next_block_height, self.timestamp))
self.blocks.append(SimFullBlock(generator, next_block_height)) self.blocks.append(SimFullBlock(generator, next_block_height))
@@ -336,7 +336,7 @@ class SimClient:
def __init__(self, service: SpendSim) -> None: def __init__(self, service: SpendSim) -> None:
self.service = service self.service = service
async def push_tx(self, spend_bundle: SpendBundle) -> tuple[MempoolInclusionStatus, Optional[Err]]: async def push_tx(self, spend_bundle: SpendBundle) -> tuple[MempoolInclusionStatus, Err | None]:
try: try:
spend_bundle_id = spend_bundle.name() spend_bundle_id = spend_bundle.name()
sbc = await self.service.mempool_manager.pre_validate_spendbundle(spend_bundle, spend_bundle_id) sbc = await self.service.mempool_manager.pre_validate_spendbundle(spend_bundle, spend_bundle_id)
@@ -348,14 +348,14 @@ class SimClient:
) )
return info.status, info.error return info.status, info.error
async def get_coin_record_by_name(self, name: bytes32) -> Optional[CoinRecord]: async def get_coin_record_by_name(self, name: bytes32) -> CoinRecord | None:
return await self.service.coin_store.get_coin_record(name) return await self.service.coin_store.get_coin_record(name)
async def get_coin_records_by_names( async def get_coin_records_by_names(
self, self,
names: list[bytes32], names: list[bytes32],
start_height: Optional[int] = None, start_height: int | None = None,
end_height: Optional[int] = None, end_height: int | None = None,
include_spent_coins: bool = False, include_spent_coins: bool = False,
) -> list[CoinRecord]: ) -> list[CoinRecord]:
kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "names": names} kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "names": names}
@@ -368,8 +368,8 @@ class SimClient:
async def get_coin_records_by_parent_ids( async def get_coin_records_by_parent_ids(
self, self,
parent_ids: list[bytes32], parent_ids: list[bytes32],
start_height: Optional[int] = None, start_height: int | None = None,
end_height: Optional[int] = None, end_height: int | None = None,
include_spent_coins: bool = False, include_spent_coins: bool = False,
) -> list[CoinRecord]: ) -> list[CoinRecord]:
kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "parent_ids": parent_ids} kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "parent_ids": parent_ids}
@@ -383,8 +383,8 @@ class SimClient:
self, self,
puzzle_hash: bytes32, puzzle_hash: bytes32,
include_spent_coins: bool = True, include_spent_coins: bool = True,
start_height: Optional[int] = None, start_height: int | None = None,
end_height: Optional[int] = None, end_height: int | None = None,
) -> list[CoinRecord]: ) -> list[CoinRecord]:
kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "puzzle_hash": puzzle_hash} kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "puzzle_hash": puzzle_hash}
if start_height is not None: if start_height is not None:
@@ -397,8 +397,8 @@ class SimClient:
self, self,
puzzle_hashes: list[bytes32], puzzle_hashes: list[bytes32],
include_spent_coins: bool = True, include_spent_coins: bool = True,
start_height: Optional[int] = None, start_height: int | None = None,
end_height: Optional[int] = None, end_height: int | None = None,
) -> list[CoinRecord]: ) -> list[CoinRecord]:
kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "puzzle_hashes": puzzle_hashes} kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "puzzle_hashes": puzzle_hashes}
if start_height is not None: if start_height is not None:
@@ -460,7 +460,7 @@ class SimClient:
spends[item.name] = item spends[item.name] = item
return spends return spends
async def get_mempool_item_by_tx_id(self, tx_id: bytes32) -> Optional[dict[str, Any]]: async def get_mempool_item_by_tx_id(self, tx_id: bytes32) -> dict[str, Any] | None:
item = self.service.mempool_manager.get_mempool_item(tx_id) item = self.service.mempool_manager.get_mempool_item(tx_id)
if item is None: if item is None:
return None return None
@@ -471,8 +471,8 @@ class SimClient:
self, self,
hint: bytes32, hint: bytes32,
include_spent_coins: bool = True, include_spent_coins: bool = True,
start_height: Optional[int] = None, start_height: int | None = None,
end_height: Optional[int] = None, end_height: int | None = None,
) -> list[CoinRecord]: ) -> list[CoinRecord]:
""" """
Retrieves coins by hint, by default returns unspent coins. Retrieves coins by hint, by default returns unspent coins.
+2 -3
View File
@@ -4,7 +4,6 @@ import asyncio
import random import random
import re import re
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional
import anyio import anyio
import pytest import pytest
@@ -128,12 +127,12 @@ async def test_worker_exception_logged(caplog: pytest.LogCaptureFixture) -> None
def __init__(self) -> None: def __init__(self) -> None:
super().__init__(expected_message) super().__init__(expected_message)
work_queue: asyncio.Queue[Optional[Exception]] = asyncio.Queue() work_queue: asyncio.Queue[Exception | None] = asyncio.Queue()
result_queue: asyncio.Queue[None] = asyncio.Queue() result_queue: asyncio.Queue[None] = asyncio.Queue()
async def worker( async def worker(
worker_id: int, worker_id: int,
work_queue: asyncio.Queue[Optional[Exception]] = work_queue, work_queue: asyncio.Queue[Exception | None] = work_queue,
result_queue: asyncio.Queue[None] = result_queue, result_queue: asyncio.Queue[None] = result_queue,
) -> None: ) -> None:
work = await work_queue.get() work = await work_queue.get()
+1 -3
View File
@@ -1,7 +1,5 @@
from __future__ import annotations from __future__ import annotations
from typing import Optional
import pytest import pytest
from packaging.version import Version from packaging.version import Version
@@ -46,5 +44,5 @@ def test_chia_short_version() -> None:
("something", "something"), ("something", "something"),
], ],
) )
def test_chia_short_version_from_str(version: str, result: Optional[str]) -> None: def test_chia_short_version_from_str(version: str, result: str | None) -> None:
assert chia_short_version(version) == result assert chia_short_version(version) == result
+3 -3
View File
@@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Optional from typing import Any
from chia_rs.sized_ints import uint16 from chia_rs.sized_ints import uint16
@@ -158,8 +158,8 @@ class SetPeerInfoCase(DataCase):
service_config: dict[str, Any] service_config: dict[str, Any]
requested_node_type: NodeType requested_node_type: NodeType
expected_service_config: dict[str, Any] expected_service_config: dict[str, Any]
peer_host: Optional[str] = None peer_host: str | None = None
peer_port: Optional[int] = None peer_port: int | None = None
marks: Marks = () marks: Marks = ()
@property @property
+2 -3
View File
@@ -2,7 +2,6 @@ from __future__ import annotations
import random import random
from collections.abc import Generator, Iterator from collections.abc import Generator, Iterator
from typing import Optional
import pytest import pytest
from chia_rs import ( from chia_rs import (
@@ -135,7 +134,7 @@ def get_foliage() -> Generator[Foliage, None, None]:
) )
def get_foliage_transaction_block() -> Generator[Optional[FoliageTransactionBlock], None, None]: def get_foliage_transaction_block() -> Generator[FoliageTransactionBlock | None, None, None]:
yield None yield None
timestamp = uint64(1631794488) timestamp = uint64(1631794488)
yield FoliageTransactionBlock( yield FoliageTransactionBlock(
@@ -148,7 +147,7 @@ def get_foliage_transaction_block() -> Generator[Optional[FoliageTransactionBloc
) )
def get_transactions_info(height: uint32, foliage_transaction_block: Optional[FoliageTransactionBlock]): def get_transactions_info(height: uint32, foliage_transaction_block: FoliageTransactionBlock | None):
if not foliage_transaction_block: if not foliage_transaction_block:
yield None yield None
else: else:
+1 -2
View File
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
from typing import Optional
import pytest import pytest
@@ -18,7 +17,7 @@ async def test_stuff() -> None:
semaphore = LimitedSemaphore.create(active_limit=active_limit, waiting_limit=waiting_limit) semaphore = LimitedSemaphore.create(active_limit=active_limit, waiting_limit=waiting_limit)
finish_event = asyncio.Event() finish_event = asyncio.Event()
async def acquire(entered_event: Optional[asyncio.Event] = None) -> None: async def acquire(entered_event: asyncio.Event | None = None) -> None:
async with semaphore.acquire(): async with semaphore.acquire():
assert entered_event is not None assert entered_event is not None
entered_event.set() entered_event.set()

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