[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 pathlib import Path
from time import monotonic
from typing import Optional
import aiosqlite
import click
@@ -38,7 +37,7 @@ with open(Path(file_path).parent / "transaction_height_delta", "rb") as f:
@dataclass(frozen=True)
class BlockInfo:
prev_header_hash: bytes32
transactions_generator: Optional[SerializedProgram]
transactions_generator: SerializedProgram | None
transactions_generator_ref_list: list[uint32]
+3 -4
View File
@@ -4,7 +4,6 @@ import asyncio
from collections.abc import Collection
from dataclasses import dataclass
from time import monotonic
from typing import Optional
from chia_rs import CoinSpend, G2Element, SpendBundle
from chia_rs.sized_bytes import bytes32
@@ -35,9 +34,9 @@ class BenchBlockRecord:
header_hash: bytes32
height: uint32
timestamp: Optional[uint64]
timestamp: uint64 | None
prev_transaction_block_height: uint32
prev_transaction_block_hash: Optional[bytes32]
prev_transaction_block_hash: bytes32 | None
@property
def is_transaction_block(self) -> bool:
@@ -90,7 +89,7 @@ async def run_mempool_benchmark() -> None:
return ret
# 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
timestamp = uint64(1631794488)
+3 -4
View File
@@ -7,7 +7,6 @@ from contextlib import contextmanager
from dataclasses import dataclass
from subprocess import check_call
from time import monotonic
from typing import Optional
from chia_rs import SpendBundle
from chia_rs.sized_bytes import bytes32
@@ -58,9 +57,9 @@ class BenchBlockRecord:
header_hash: bytes32
height: uint32
timestamp: Optional[uint64]
timestamp: uint64 | None
prev_transaction_block_height: uint32
prev_transaction_block_hash: Optional[bytes32]
prev_transaction_block_hash: bytes32 | None
@property
def is_transaction_block(self) -> bool:
@@ -91,7 +90,7 @@ async def run_mempool_benchmark() -> None:
return ret
# 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
wt = WalletTool(DEFAULT_CONSTANTS)
+14 -13
View File
@@ -3,11 +3,12 @@ from __future__ import annotations
import json
import random
import sys
from collections.abc import Callable
from dataclasses import dataclass
from enum import Enum
from statistics import stdev
from time import process_time as clock
from typing import Any, Callable, Optional, TextIO, Union
from typing import Any, TextIO
import click
from chia_rs import FullBlock
@@ -43,8 +44,8 @@ class BenchmarkMiddle(Streamable):
@streamable
@dataclass(frozen=True)
class BenchmarkClass(Streamable):
a: Optional[BenchmarkMiddle]
b: Optional[BenchmarkMiddle]
a: BenchmarkMiddle | None
b: BenchmarkMiddle | None
c: BenchmarkMiddle
d: list[BenchmarkMiddle]
e: tuple[BenchmarkMiddle, BenchmarkMiddle, BenchmarkMiddle]
@@ -64,8 +65,8 @@ def get_random_middle() -> BenchmarkMiddle:
def get_random_benchmark_object() -> BenchmarkClass:
a: Optional[BenchmarkMiddle] = None
b: Optional[BenchmarkMiddle] = get_random_middle()
a: BenchmarkMiddle | None = None
b: BenchmarkMiddle | None = get_random_middle()
c: BenchmarkMiddle = get_random_middle()
d: list[BenchmarkMiddle] = [get_random_middle() for _ in range(5)]
e: tuple[BenchmarkMiddle, BenchmarkMiddle, BenchmarkMiddle] = (
@@ -79,10 +80,10 @@ def get_random_benchmark_object() -> BenchmarkClass:
def print_row(
*,
mode: str,
us_per_iteration: Union[str, float],
stdev_us_per_iteration: Union[str, float],
avg_iterations: Union[str, int],
stdev_iterations: Union[str, float],
us_per_iteration: str | float,
stdev_us_per_iteration: str | float,
avg_iterations: str | int,
stdev_iterations: str | float,
end: str = "\n",
) -> None:
print(
@@ -142,14 +143,14 @@ def to_bytes(obj: Any) -> bytes:
@dataclass
class ModeParameter:
conversion_cb: Callable[[Any], Any]
preparation_cb: Optional[Callable[[Any], Any]] = None
preparation_cb: Callable[[Any], Any] | None = None
@dataclass
class BenchmarkParameter:
data_class: type[Any]
object_creation_cb: Callable[[], Any]
mode_parameter: dict[Mode, Optional[ModeParameter]]
mode_parameter: dict[Mode, ModeParameter | None]
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)
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}")
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:
old_version, new_version = pop_data("version", old=old, new=new)
if old_version != new_version:
+2 -3
View File
@@ -6,20 +6,19 @@ import subprocess
import sys
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Optional, Union
from chia.util.db_wrapper import DBWrapper2
@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)
try:
os.unlink(db_filename)
except FileNotFoundError:
pass
log_path: Optional[Path]
log_path: Path | None
if "--sql-logging" in sys.argv:
log_path = Path("sql.log")
else:
@@ -1,7 +1,5 @@
from __future__ import annotations
from typing import Optional
from chia_rs import FullBlock, SpendBundleConditions
from chia_rs.sized_ints import uint32, uint64
@@ -46,10 +44,10 @@ async def _validate_and_add_block(
blockchain: Blockchain,
block: FullBlock,
*,
expected_result: Optional[AddBlockResult] = None,
expected_error: Optional[Err] = None,
expected_result: AddBlockResult | None = None,
expected_error: Err | None = None,
skip_prevalidation: bool = False,
fork_info: Optional[ForkInfo] = None,
fork_info: ForkInfo | None = None,
) -> None:
# 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.
@@ -137,7 +135,7 @@ async def _validate_and_add_block_multi_error(
block: FullBlock,
expected_errors: list[Err],
skip_prevalidation: bool = False,
fork_info: Optional[ForkInfo] = None,
fork_info: ForkInfo | None = None,
) -> None:
# Checks that the blockchain returns one of the expected errors
try:
@@ -155,7 +153,7 @@ async def _validate_and_add_block_multi_result(
block: FullBlock,
expected_result: list[AddBlockResult],
skip_prevalidation: bool = False,
fork_info: Optional[ForkInfo] = None,
fork_info: ForkInfo | None = None,
) -> None:
try:
await _validate_and_add_block(
@@ -176,7 +174,7 @@ async def _validate_and_add_block_no_error(
blockchain: Blockchain,
block: FullBlock,
skip_prevalidation: bool = False,
fork_info: Optional[ForkInfo] = None,
fork_info: ForkInfo | None = None,
) -> None:
# adds a block and ensures that there is no error. However, does not ensure that block extended the peak of
# the blockchain
@@ -2,7 +2,7 @@ from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, ClassVar, Optional, cast
from typing import TYPE_CHECKING, ClassVar, cast
import pytest
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]:
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
def add_block_record(self, block_record: BlockRecord) -> None:
self.added_blocks.add(block_record.header_hash)
# 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
def block_record(self, header_hash: bytes32) -> BlockRecord:
@@ -46,7 +46,7 @@ class NullBlockchain:
def height_to_block_record(self, height: uint32) -> BlockRecord:
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)
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 contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from typing import Optional
import pytest
from chia_rs import (
@@ -3266,7 +3265,7 @@ class TestBodyValidation:
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:
return None
return block.header_hash
@@ -3313,7 +3312,7 @@ class TestReorgs:
reorg_point = 12
blocks = bt.get_consecutive_blocks(reorg_point)
last_tx_block: Optional[bytes32] = None
last_tx_block: bytes32 | None = None
for block in blocks:
assert maybe_header_hash(b.get_tx_peak()) == last_tx_block
await _validate_and_add_block(b, block)
@@ -3324,7 +3323,7 @@ class TestReorgs:
assert peak.height == reorg_point - 1
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_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")
@@ -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
def to_bytes(gen: Optional[SerializedProgram]) -> bytes:
def to_bytes(gen: SerializedProgram | None) -> bytes:
assert gen is not None
return bytes(gen)
@@ -4218,7 +4217,7 @@ async def get_fork_info(blockchain: Blockchain, block: FullBlock, peak: BlockRec
counter = 0
start = time.monotonic()
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.height - 1 == fork_info.peak_height
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 typing import Optional
import pytest
from chia_rs import Coin, ConsensusConstants, FullBlock, additions_and_removals, get_flags_for_height_and_constants
from chia_rs.sized_ints import uint64
@@ -102,8 +100,8 @@ def validate_chain(
normalized_to_identity_icc_eos: bool = False,
normalized_to_identity_cc_sp: bool = False,
normalized_to_identity_cc_ip: bool = False,
block_list_input: Optional[list[FullBlock]] = None,
time_per_block: Optional[float] = None,
block_list_input: list[FullBlock] | None = None,
time_per_block: float | None = None,
dummy_block_references: bool = False,
include_transactions: bool = False,
) -> None:
@@ -1,7 +1,6 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
import pytest
from chia_rs.sized_bytes import bytes32
@@ -16,14 +15,14 @@ from chia.util.casts import int_to_bytes
@dataclass(frozen=True)
class BR:
prev_header_hash: bytes32
transactions_generator: Optional[SerializedProgram]
transactions_generator: SerializedProgram | None
transactions_generator_ref_list: list[uint32]
@dataclass(frozen=True)
class FB:
prev_header_hash: bytes32
transactions_generator: Optional[SerializedProgram]
transactions_generator: SerializedProgram | None
height: uint32
+1 -2
View File
@@ -3,7 +3,6 @@ from __future__ import annotations
from collections import defaultdict
from collections.abc import Iterator
from dataclasses import dataclass, replace
from typing import Optional
from chia_rs import ConsensusConstants, SpendBundle
from chia_rs.sized_bytes import bytes32
@@ -145,5 +144,5 @@ class CoinStore:
)
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)
+3 -3
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
from typing import Any, Optional
from typing import Any
from chialisp import start_clvm_program
@@ -17,8 +17,8 @@ factorial_sym = {factorial_function_hash: "factorial"}
def test_simple_program_run() -> None:
p = start_clvm_program(factorial, "ff0580", factorial_sym)
last: Optional[Any] = None
location: Optional[Any] = None
last: Any | None = None
location: Any | None = None
while not p.is_ended():
step_result = p.step()
+2 -1
View File
@@ -1,8 +1,9 @@
from __future__ import annotations
import logging
from collections.abc import Callable
from dataclasses import dataclass
from typing import Callable, SupportsBytes
from typing import SupportsBytes
import pytest
from chia_rs import CoinSpend, G1Element, G2Element, SpendBundle
+2 -2
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
from typing import Any, Union
from typing import Any
import pytest
@@ -35,7 +35,7 @@ def test_puzzle_info() -> None:
assert solver == Solver(capitalize_bytes)
assert puzzle_info == PuzzleInfo(capitalize_bytes)
obj: Union[PuzzleInfo, Solver]
obj: PuzzleInfo | Solver
for obj in (puzzle_info, solver):
assert obj["string"] == "hello"
assert obj["bytes"] == bytes.fromhex("cafef00d")
+2 -4
View File
@@ -1,7 +1,5 @@
from __future__ import annotations
from typing import Optional
import pytest
from chia_rs import AugSchemeMPL, CoinSpend, G1Element, G2Element, PrivateKey, SpendBundle
from chia_rs.sized_bytes import bytes32
@@ -54,9 +52,9 @@ async def make_and_spend_bundle(
coin: Coin,
delegated_puzzle: Program,
coinsols: list[CoinSpend],
ex_error: Optional[Err] = None,
ex_error: Err | None = None,
fail_msg: str = "",
cost_logger: Optional[CostLogger] = None,
cost_logger: CostLogger | None = None,
cost_log_msg: str = "",
):
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 dataclasses import dataclass, field
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.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.
# 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
class TestRpcClient:
client_type: type[RpcClient]
rpc_port: Optional[uint16] = None
root_path: Optional[Path] = None
config: Optional[dict[str, Any]] = None
rpc_port: uint16 | None = None
root_path: Path | None = None
config: dict[str, Any] | None = None
create_called: bool = field(init=False, default=False)
rpc_log: dict[str, list[tuple[Any, ...]]] = field(init=False, default_factory=dict)
@@ -240,7 +240,7 @@ class TestWalletRpcClient(TestRpcClient):
wallet_id: int,
additions: list[dict[str, object]],
tx_config: TXConfig,
coins: Optional[list[Coin]] = None,
coins: list[Coin] | None = None,
fee: uint64 = uint64(0),
push: bool = True,
timelock_info: ConditionValidTimes = ConditionValidTimes(),
@@ -280,8 +280,8 @@ class TestFullNodeRpcClient(TestRpcClient):
async def get_fee_estimate(
self,
target_times: Optional[list[int]],
cost: Optional[int],
target_times: list[int] | None,
cost: int | None,
) -> dict[str, Any]:
return {}
@@ -313,11 +313,11 @@ class TestFullNodeRpcClient(TestRpcClient):
self.add_to_log("get_blockchain_state", ())
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,))
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,))
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(
client_type: type[_T_RpcClient],
root_path: Path,
rpc_port: Optional[int] = None,
rpc_port: int | None = None,
consume_errors: bool = True,
use_ssl: bool = True,
) -> AsyncIterator[tuple[_T_RpcClient, dict[str, Any]]]:
@@ -402,8 +402,8 @@ def create_service_and_wallet_client_generators(test_rpc_clients: TestRpcClients
@asynccontextmanager
async def test_get_wallet_client(
root_path: Path = default_root,
wallet_rpc_port: Optional[int] = None,
fingerprint: Optional[int] = None,
wallet_rpc_port: int | None = None,
fingerprint: int | None = None,
) -> AsyncIterator[tuple[WalletRpcClient, int, dict[str, Any]]]:
async with test_get_any_service_client(WalletRpcClient, root_path, wallet_rpc_port) as (wallet_client, config):
wallet_client.fingerprint = fingerprint # type: ignore
+6 -6
View File
@@ -5,7 +5,7 @@ import textwrap
from collections.abc import Sequence
from dataclasses import asdict
from decimal import Decimal
from typing import Any, Optional
from typing import Any
import click
import pytest
@@ -32,7 +32,7 @@ from chia.wallet.transaction_record import TransactionRecord
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()
def _cmd() -> None:
pass
@@ -232,7 +232,7 @@ def test_typing() -> None:
# Test optional
@chia_command(group=cmd, name="temp_cmd_optional", short_help="blah", help="n/a")
class TempCMDOptional:
optional: Optional[int] = option("--optional", required=False)
optional: int | None = option("--optional", required=False)
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")
class TempCMDOptionalBad2:
optional: Optional[int] = option("--optional", required=True)
optional: int | None = option("--optional", required=True)
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")
class TempCMDOptionalBad3:
optional: Optional[int] = option("--optional", default="string", required=False)
optional: int | None = option("--optional", default="string", required=False)
def run(self) -> None: ...
@chia_command(group=cmd, name="temp_cmd_optional_fine", short_help="blah", help="n/a")
class TempCMDOptionalBad4:
optional: Optional[int] = option("--optional", default=None, required=False)
optional: int | None = option("--optional", default=None, required=False)
def run(self) -> None: ...
+3 -3
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
import sys
from pathlib import Path
from typing import Any, Optional
from typing import Any
import pytest
from _pytest.capture import CaptureFixture
@@ -33,10 +33,10 @@ async def test_daemon(
class DummyKeychain:
@staticmethod
def get_cached_master_passphrase() -> Optional[str]:
def get_cached_master_passphrase() -> str | None:
return None
def get_current_passphrase() -> Optional[str]:
def get_current_passphrase() -> str | None:
return "a-passphrase"
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 pathlib import Path
from typing import Any, Optional
from typing import Any
from chia_rs import FoliageTransactionBlock, FullBlock
from chia_rs.sized_bytes import bytes32
@@ -16,7 +16,7 @@ from chia.types.blockchain_format.serialized_program import SerializedProgram
@dataclass
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))
response: dict[str, Any] = {
"current_fee_rate": 0,
@@ -38,7 +38,7 @@ class ShowFullNodeRpcClient(TestFullNodeRpcClient):
}
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
self.add_to_log("get_block", (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",
]
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_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,)],
+1 -2
View File
@@ -2,7 +2,6 @@ from __future__ import annotations
from collections.abc import Sequence
from pathlib import Path
from typing import Optional
import click
from chia_rs.sized_bytes import bytes32
@@ -102,7 +101,7 @@ def test_tx_config_args() -> None:
max_coin_amount: CliAmount,
coins_to_exclude: Sequence[bytes32],
amounts_to_exclude: Sequence[CliAmount],
reuse: Optional[bool],
reuse: bool | None,
) -> None:
print(
CMDTXConfigLoader(
+4 -5
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint8, uint32, uint64
@@ -17,10 +16,10 @@ class TestBlockRecord:
header_hash: bytes32
height: uint32
timestamp: Optional[uint64]
timestamp: uint64 | None
prev_transaction_block_height: uint32
prev_transaction_block_hash: Optional[bytes32]
prev_hash: Optional[bytes32]
prev_transaction_block_hash: bytes32 | None
prev_hash: bytes32 | None
weight: uint64 = uint64(10000)
fees: uint64 = uint64(5000)
farmer_puzzle_hash: bytes32 = bytes32([1] * 32)
@@ -43,7 +42,7 @@ def hash_to_height(int_bytes: bytes32) -> int:
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:
if header_hash is None:
header_hash = height_hash(height)
+3 -4
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
from pathlib import Path
from typing import Optional, Union
import pytest
from chia_rs import G2Element
@@ -62,12 +61,12 @@ def test_did_create(capsys: object, get_test_cli_clients: tuple[TestRpcClients,
amount: int,
tx_config: TXConfig,
fee: int = 0,
name: Optional[str] = "DID Wallet",
backup_ids: Optional[list[str]] = None,
name: str | None = "DID Wallet",
backup_ids: list[str] | None = None,
required_num: int = 0,
push: bool = True,
timelock_info: ConditionValidTimes = ConditionValidTimes(),
) -> dict[str, Union[str, int]]:
) -> dict[str, str | int]:
if backup_ids is None:
backup_ids = []
self.add_to_log(
+2 -2
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
from pathlib import Path
from typing import Any, Optional
from typing import Any
from chia_rs import G2Element
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
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))
return {"wallet_id": 4}
+4 -4
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import datetime
import os
from pathlib import Path
from typing import Any, Optional, Union
from typing import Any
import importlib_resources
import pytest
@@ -302,8 +302,8 @@ def test_show(capsys: object, get_test_cli_clients: tuple[TestRpcClients, Path])
return NFTGetWalletDIDResponse("did:chia:1qgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpq4msw0c")
async def get_connections(
self, node_type: Optional[NodeType] = None
) -> list[dict[str, Union[str, int, float, bytes32]]]:
self, node_type: NodeType | None = None
) -> list[dict[str, str | int | float | bytes32]]:
self.add_to_log("get_connections", (node_type,))
return [
{
@@ -950,7 +950,7 @@ def test_get_offers(capsys: object, get_test_cli_clients: tuple[TestRpcClients,
self,
start: int = 0,
end: int = 50,
sort_key: Optional[str] = None,
sort_key: str | None = None,
reverse: bool = False,
file_contents: bool = False,
exclude_my_offers: bool = False,
+5 -5
View File
@@ -12,9 +12,9 @@ import os
import random
import sysconfig
import tempfile
from collections.abc import AsyncIterator, Iterator
from collections.abc import AsyncIterator, Callable, Iterator
from contextlib import AsyncExitStack
from typing import Any, Callable, Union
from typing import Any
import aiohttp
import pytest
@@ -800,7 +800,7 @@ async def one_node(
@pytest.fixture(scope="function")
async def one_node_one_block(
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:
(nodes, _, bt) = make_old_setup_simulators_and_wallets(new=new)
full_node_1 = nodes[0]
@@ -1272,8 +1272,8 @@ async def farmer_harvester_2_simulators_zero_bits_plot_filter(
tuple[
FarmerService,
HarvesterService,
Union[FullNodeService, SimulatorFullNodeService],
Union[FullNodeService, SimulatorFullNodeService],
FullNodeService | SimulatorFullNodeService,
FullNodeService | SimulatorFullNodeService,
BlockTools,
]
]:
+4 -4
View File
@@ -1,8 +1,8 @@
from __future__ import annotations
import zipfile
from collections.abc import Callable
from pathlib import Path
from typing import Callable, Optional
import pytest
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(
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(
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(
cli,
[
+2 -3
View File
@@ -4,7 +4,6 @@ import json
import os
import re
from pathlib import Path
from typing import Optional
import pytest
from click.testing import CliRunner, Result
@@ -54,7 +53,7 @@ def setup_keyringwrapper(tmp_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()
assert len(all_keys) > index
assert all_keys[index].label == label
@@ -200,7 +199,7 @@ class TestKeysCommands:
],
)
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
keys_root_path = keychain.keyring_wrapper.keys_root_path
@@ -3,7 +3,6 @@ from __future__ import annotations
import logging
import random
from dataclasses import dataclass
from typing import Optional
import pytest
from chia_rs import G1Element, PlotParam
@@ -28,10 +27,10 @@ class ProofOfSpaceCase:
pos_challenge: bytes32
plot_size: PlotParam
plot_public_key: G1Element
pool_public_key: Optional[G1Element] = None
pool_contract_puzzle_hash: Optional[bytes32] = None
pool_public_key: G1Element | None = None
pool_contract_puzzle_hash: bytes32 | None = None
height: uint32 = DEFAULT_CONSTANTS.HARD_FORK2_HEIGHT
expected_error: Optional[str] = None
expected_error: str | None = None
marks: Marks = ()
+8 -8
View File
@@ -5,7 +5,7 @@ import json
import logging
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any, Optional, Union, cast
from typing import Any, cast
import aiohttp
import pytest
@@ -94,7 +94,7 @@ class ChiaPlottersBladebitArgsCase:
pool_contract: str = "txch1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
compress: int = 1
device: int = 0
hybrid_disk_mode: Optional[int] = None
hybrid_disk_mode: int | None = None
farmer_pk: str = ""
final_dir: str = ""
marks: Marks = ()
@@ -147,7 +147,7 @@ class ChiaPlottersBladebitArgsCase:
class Service:
running: bool
def poll(self) -> Optional[int]:
def poll(self) -> int | None:
return None if self.running else 1
@@ -155,8 +155,8 @@ class Service:
@dataclass
class Daemon:
# Instance variables used by WebSocketServer.is_running()
services: dict[str, Union[list[Service], Service]]
connections: dict[str, Optional[list[Any]]]
services: dict[str, list[Service] | Service]
connections: dict[str, list[Any] | None]
# Instance variables used by WebSocketServer.get_wallet_addresses()
net_config: dict[str, Any] = field(default_factory=dict)
@@ -314,9 +314,9 @@ label_newline_or_tab_response_data = {
def assert_response(
response: aiohttp.http_websocket.WSMessage,
expected_response_data: dict[str, Any],
request_id: Optional[str] = None,
request_id: str | None = None,
ack: bool = True,
command: Optional[str] = None,
command: str | None = None,
) -> None:
# Expect: JSON response
assert response.type == aiohttp.WSMsgType.TEXT
@@ -332,7 +332,7 @@ def assert_response(
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]:
# Expect: JSON response
assert response.type == aiohttp.WSMsgType.TEXT
+2 -2
View File
@@ -4,8 +4,8 @@ import os
import pathlib
import sys
import time
from collections.abc import AsyncIterable, Awaitable, Iterator
from typing import Any, Callable
from collections.abc import AsyncIterable, Awaitable, Callable, Iterator
from typing import Any
import pytest
+8 -8
View File
@@ -16,7 +16,7 @@ from copy import deepcopy
from dataclasses import dataclass
from enum import IntEnum
from pathlib import Path
from typing import Any, Optional, cast
from typing import Any, cast
import anyio
import chia_rs.datalayer
@@ -96,10 +96,10 @@ class InterfaceLayer(enum.Enum):
async def init_data_layer_service(
wallet_rpc_port: uint16,
bt: BlockTools,
db_path: Optional[Path] = None,
wallet_service: Optional[WalletService] = None,
db_path: Path | None = None,
wallet_service: WalletService | None = None,
manage_data_interval: int = 5,
maximum_full_file_count: Optional[int] = None,
maximum_full_file_count: int | None = None,
enable_batch_autoinsert: bool = True,
group_files_by_store: bool = False,
) -> AsyncIterator[DataLayerService]:
@@ -130,9 +130,9 @@ async def init_data_layer(
wallet_rpc_port: uint16,
bt: BlockTools,
db_path: Path,
wallet_service: Optional[WalletService] = None,
wallet_service: WalletService | None = None,
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,
enable_batch_autoinsert: bool = True,
) -> AsyncIterator[DataLayer]:
@@ -1033,7 +1033,7 @@ async def process_for_data_layer_keys(
full_node_api: FullNodeSimulator,
data_layer: DataLayer,
store_id: bytes32,
expected_value: Optional[bytes] = None,
expected_value: bytes | None = None,
) -> None:
for sleep_time in backoff_times():
try:
@@ -3067,7 +3067,7 @@ async def test_pagination_cmds(
one_wallet_and_one_simulator_services: SimulatorsAndWalletsServices,
tmp_path: Path,
layer: InterfaceLayer,
max_page_size: Optional[int],
max_page_size: int | None,
bt: BlockTools,
) -> None:
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 statistics
import time
from collections.abc import Awaitable
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from hashlib import sha256
from pathlib import Path
from random import Random
from typing import Any, BinaryIO, Callable, Optional
from typing import Any, BinaryIO
import aiohttp
import chia_rs.datalayer
@@ -290,7 +290,7 @@ async def test_get_ancestors_optimized(data_store: DataStore, store_id: bytes32)
node_count = 0
node_hashes: list[bytes32] = []
hash_to_key: dict[bytes32, bytes] = {}
node_hash: Optional[bytes32]
node_hash: bytes32 | None
for i in range(1000):
is_insert = False
@@ -1223,7 +1223,7 @@ async def test_server_http_ban(
async def mock_http_download(
target_filename_path: Path,
filename: str,
proxy_url: Optional[str],
proxy_url: str | None,
server_info: ServerInfo,
timeout: aiohttp.ClientTimeout,
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
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:
cursor = await reader.execute(
"SELECT generation FROM nodes WHERE hash = ? AND store_id = ?",
@@ -1301,8 +1301,8 @@ async def write_tree_to_file_old_format(
node_hash: bytes32,
store_id: bytes32,
writer: BinaryIO,
merkle_blob: Optional[MerkleBlob] = None,
hash_to_index: Optional[dict[bytes32, TreeIndex]] = None,
merkle_blob: MerkleBlob | None = None,
hash_to_index: dict[bytes32, TreeIndex] | None = None,
) -> None:
if node_hash == bytes32.zeros:
return
@@ -1760,7 +1760,7 @@ async def test_insert_from_delta_file(
async def mock_http_download(
target_filename_path: Path,
filename: str,
proxy_url: Optional[str],
proxy_url: str | None,
server_info: ServerInfo,
timeout: int,
log: logging.Logger,
@@ -1770,7 +1770,7 @@ async def test_insert_from_delta_file(
async def mock_http_download_2(
target_filename_path: Path,
filename: str,
proxy_url: Optional[str],
proxy_url: str | None,
server_info: ServerInfo,
timeout: int,
log: logging.Logger,
@@ -2180,7 +2180,7 @@ async def test_basic_key_value_db_vs_disk_cutoff(
) as cursor:
row = await cursor.fetchone()
assert row is not None
db_blob: Optional[bytes] = row["blob"]
db_blob: bytes | None = row["blob"]
if size_offset <= 0:
assert not file_exists
+10 -10
View File
@@ -8,7 +8,7 @@ import shutil
import subprocess
from collections.abc import Iterator
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
@@ -34,8 +34,8 @@ async def general_insert(
store_id: bytes32,
key: bytes,
value: bytes,
reference_node_hash: Optional[bytes32],
side: Optional[Side],
reference_node_hash: bytes32 | None,
side: Side | None,
) -> bytes32:
insert_result = await data_store.insert(
key=key,
@@ -123,12 +123,12 @@ class ChiaRoot:
def run(
self,
args: list[Union[str, os_PathLike_str]],
args: list[str | os_PathLike_str],
*other_args: Any,
check: bool = True,
encoding: str = "utf-8",
stdout: Optional[_FILE] = subprocess.PIPE,
stderr: Optional[_FILE] = subprocess.PIPE,
stdout: _FILE | None = subprocess.PIPE,
stderr: _FILE | None = subprocess.PIPE,
**kwargs: Any,
) -> subprocess_CompletedProcess_str:
# TODO: --root-path doesn't seem to work here...
@@ -143,7 +143,7 @@ class ChiaRoot:
chia_executable = shutil.which("chia")
if chia_executable is None:
chia_executable = "chia"
modified_args: list[Union[str, os_PathLike_str]] = [
modified_args: list[str | os_PathLike_str] = [
self.scripts_path.joinpath(chia_executable),
"--root-path",
self.path,
@@ -166,7 +166,7 @@ class ChiaRoot:
return self.path.joinpath("log", "debug.log").read_text(encoding="utf-8")
def print_log(self) -> None:
log_text: Optional[str]
log_text: str | None
try:
log_text = self.read_log()
@@ -204,8 +204,8 @@ def create_valid_node_values(
def create_valid_node_values(
node_type: NodeType,
left_hash: Optional[bytes32] = None,
right_hash: Optional[bytes32] = None,
left_hash: bytes32 | None = None,
right_hash: bytes32 | None = None,
) -> dict[str, Any]:
if node_type == NodeType.INTERNAL:
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 collections.abc import Coroutine
from typing import Any, Optional, TypeVar
from typing import Any, TypeVar
import pytest
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)
signed_values_task: Task[Optional[Message]] = await begin_task(
farmer_api.request_signed_values(request_signed_values)
)
signed_values_task: Task[Message | None] = await begin_task(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
await sleep(1)
@@ -5,7 +5,7 @@ import logging
import random
import sqlite3
from pathlib import Path
from typing import Optional, cast
from typing import cast
import pytest
@@ -41,7 +41,7 @@ def use_cache(request: SubRequest) -> bool:
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:
return None
else:
@@ -3,7 +3,6 @@ from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
import aiosqlite
import pytest
@@ -236,7 +235,7 @@ async def test_rollback(db_version: int, bt: BlockTools) -> None:
async with DBConnection(db_version) as db_wrapper:
coin_store = await CoinStore.create(db_wrapper)
selected_coin: Optional[CoinRecord] = None
selected_coin: CoinRecord | None = None
all_coins: list[Coin] = []
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)
b: Blockchain = await Blockchain.create(coin_store, store, height_map, bt.constants, 2)
try:
records: list[Optional[CoinRecord]] = []
records: list[CoinRecord | None] = []
for block in blocks:
await _validate_and_add_block(b, block)
@@ -570,7 +569,7 @@ async def test_coin_state_batches(
continue
expected_crs.append(cr)
height: Optional[uint32] = uint32(0)
height: uint32 | None = uint32(0)
all_coin_states: list[CoinState] = []
remaining_phs = random_coin_records.puzzle_hashes.copy()
@@ -3,7 +3,6 @@ from __future__ import annotations
import logging
import random
from collections.abc import AsyncIterator
from typing import Optional
import pytest
from chia_rs import ConsensusConstants, FullBlock, UnfinishedBlock
@@ -128,15 +127,15 @@ async def test_unfinished_block_rank(
)
async def test_find_best_block(
seeded_random: random.Random,
blocks: list[tuple[Optional[int], bool]],
expected: Optional[int],
blocks: list[tuple[int | None, bool]],
expected: int | None,
default_400_blocks: list[FullBlock],
bt: BlockTools,
) -> None:
result: dict[Optional[bytes32], UnfinishedBlockEntry] = {}
result: dict[bytes32 | None, UnfinishedBlockEntry] = {}
i = 0
for b, with_unf in blocks:
unf: Optional[UnfinishedBlock]
unf: UnfinishedBlock | None
if with_unf:
unf = make_unfinished_block(default_400_blocks[i], bt.constants)
i += 1
@@ -1022,10 +1021,10 @@ async def test_basic_store(
and i1 > (i2 + 3)
):
# 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:
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.cc_vdf is not None
fetched = store.get_signage_point(sp_to_check.cc_vdf.output.get_hash())
@@ -3,7 +3,6 @@ from __future__ import annotations
import os
import struct
from pathlib import Path
from typing import Optional
import pytest
from chia_rs import SubEpochSummary
@@ -27,7 +26,7 @@ def gen_ses(height: int) -> SubEpochSummary:
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:
async with db.writer_maybe_transaction() as conn:
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
# the same heights as the main 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:
height = start_height
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
import logging
from typing import Optional
import pytest
from chia_rs import AugSchemeMPL, FullBlock, G2Element, SpendBundle
@@ -59,7 +58,7 @@ async def check_spend_bundle_validity(
bt: BlockTools,
blocks: list[FullBlock],
spend_bundle: SpendBundle,
expected_err: Optional[Err] = None,
expected_err: Err | None = None,
) -> tuple[list[CoinRecord], list[CoinRecord], FullBlock]:
"""
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(
bt: BlockTools,
condition_solution: Program,
expected_err: Optional[Err] = None,
expected_err: Err | None = None,
spend_reward_index: int = -2,
*,
aggsig: G2Element = G2Element(),
@@ -366,7 +365,7 @@ class TestConditions:
condition1: str,
condition2: str,
num: int,
expect_err: Optional[Err],
expect_err: Err | None,
bt: BlockTools,
) -> None:
"""
@@ -446,7 +445,7 @@ class TestConditions:
],
)
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:
blocks = await initial_blocks(bt)
coin = blocks[-2].get_included_reward_coins()[0]
+7 -7
View File
@@ -7,7 +7,7 @@ import logging
import random
import time
from collections.abc import Awaitable, Coroutine
from typing import Any, Optional
from typing import Any
import pytest
from chia_rs import (
@@ -246,7 +246,7 @@ async def test_block_compression(
await time_out_assert(30, check_transaction_confirmed, True, tr)
# 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 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
not_included_tx = 0
seen_bigger_transaction_has_high_fee = False
successful_bundle: Optional[WalletSpendBundle] = None
successful_bundle: WalletSpendBundle | None = None
# Fill mempool
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
@@ -1473,7 +1473,7 @@ async def test_new_unfinished_block2_forward_limit(
unf_blocks: list[UnfinishedBlock] = []
last_reward_hash: Optional[bytes32] = None
last_reward_hash: bytes32 | None = None
for idx in range(6):
# we include a different transaction in each block. This makes the
# foliage different in each of them, but the reward block (plot) the same
@@ -1769,7 +1769,7 @@ async def test_request_unfinished_block2(
# the "best" unfinished block according to the metric we use to pick one
# deterministically
best_unf: Optional[UnfinishedBlock] = None
best_unf: UnfinishedBlock | None = None
for idx in range(6):
# 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)
tx_peak = blockchain.get_tx_peak()
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,
blockchain.constants,
challenge,
@@ -3259,7 +3259,7 @@ async def add_tx_to_mempool(
coinbase_puzzlehash: bytes32,
receiver_puzzlehash: bytes32,
amount: uint64,
) -> Optional[SpendBundle]:
) -> SpendBundle | None:
spend_coin = None
coins = spend_block.get_included_reward_coins()
for coin in coins:
@@ -1,7 +1,5 @@
from __future__ import annotations
from typing import Optional
import pytest
from chia_rs import BlockRecord
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)
await _validate_and_add_block(empty_blockchain, blocks[0])
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
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)
await _validate_and_add_block(empty_blockchain, blocks[0])
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
rewards: list[Coin] = [
@@ -1,7 +1,5 @@
from __future__ import annotations
from typing import Optional
from chia_rs import FullBlock
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
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_sp = False
if len(block_list[-1].finished_sub_slots) > 0:
@@ -2,7 +2,6 @@ from __future__ import annotations
import asyncio
import random
from typing import Optional
import pytest
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)
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:
return -1
peak_height = peak.height
@@ -4,7 +4,7 @@ import asyncio
import logging
import random
from dataclasses import dataclass
from typing import Optional, cast
from typing import cast
import pytest
from chia_rs.sized_bytes import bytes32
@@ -18,10 +18,10 @@ log = logging.getLogger(__name__)
@dataclass(frozen=True)
class FakeTransactionQueueEntry:
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))
+15 -15
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import dataclasses
import logging
import random
from typing import Callable, Optional
from collections.abc import Callable
import pytest
from chia_rs import (
@@ -100,7 +100,7 @@ def wallet_a(bt: BlockTools) -> WalletTool:
def generate_test_spend_bundle(
wallet: WalletTool,
coin: Coin,
condition_dic: Optional[dict[ConditionOpcode, list[ConditionWithArgs]]] = None,
condition_dic: dict[ConditionOpcode, list[ConditionWithArgs]] | None = None,
fee: uint64 = uint64(0),
amount: uint64 = uint64(1000),
new_puzzle_hash: bytes32 = BURN_PUZZLE_HASH,
@@ -350,7 +350,7 @@ async def respond_transaction(
peer: WSChiaConnection,
tx_bytes: bytes = b"",
test: bool = False,
) -> tuple[MempoolInclusionStatus, Optional[Err]]:
) -> tuple[MempoolInclusionStatus, Err | None]:
"""
Receives a full transaction from peer.
If tx is added to mempool, send tx_id to others. (new_transaction)
@@ -395,7 +395,7 @@ co = ConditionOpcode
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)
return await node.send_transaction(tx, test=True)
@@ -716,7 +716,7 @@ class TestMempoolManager:
sb: SpendBundle = generate_test_spend_bundle(wallet_a, coin1)
assert sb.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
ack: TransactionAck = TransactionAck.from_bytes(res.data)
assert ack.status == MempoolInclusionStatus.FAILED.value
@@ -730,8 +730,8 @@ class TestMempoolManager:
dic: dict[ConditionOpcode, list[ConditionWithArgs]],
fee: int = 0,
num_blocks: int = 3,
coin: Optional[Coin] = None,
) -> tuple[list[FullBlock], SpendBundle, WSChiaConnection, MempoolInclusionStatus, Optional[Err]]:
coin: Coin | None = None,
) -> tuple[list[FullBlock], SpendBundle, WSChiaConnection, MempoolInclusionStatus, Err | None]:
reward_ph = wallet_a.get_new_puzzlehash()
full_node_1, server_1, bt = one_node_one_block
blocks = await full_node_1.get_all_full_blocks()
@@ -772,7 +772,7 @@ class TestMempoolManager:
node_server_bt: tuple[FullNodeSimulator, ChiaServer, BlockTools],
wallet_a: WalletTool,
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()
full_node_1, server_1, bt = node_server_bt
blocks = await full_node_1.get_all_full_blocks()
@@ -1256,7 +1256,7 @@ class TestMempoolManager:
self,
assert_garbage: bool,
announce_garbage: bool,
expected: Optional[Err],
expected: Err | None,
expected_included: MempoolInclusionStatus,
one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools],
wallet_a: WalletTool,
@@ -1469,7 +1469,7 @@ class TestMempoolManager:
self,
assert_garbage: bool,
announce_garbage: bool,
expected: Optional[Err],
expected: Err | None,
expected_included: MempoolInclusionStatus,
one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools],
wallet_a: WalletTool,
@@ -2530,7 +2530,7 @@ class TestGeneratorConditions:
],
)
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:
npc_result = generator_condition_tester(condition, mempool_mode=mempool, height=softfork_height)
print(npc_result)
@@ -2550,7 +2550,7 @@ class TestGeneratorConditions:
],
)
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:
npc_result = generator_condition_tester(condition, mempool_mode=mempool, height=softfork_height)
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)
last_fpc: Optional[float] = None
last_fpc: float | None = None
for mi, expected_coin in zip(ordered_items, expected):
assert len(mi.bundle_coin_spends) == 1
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)
)
async def callback1(ph: bytes32) -> Optional[UnspentLineageInfo]:
async def callback1(ph: bytes32) -> UnspentLineageInfo | None:
nonlocal called
called += 1
return info1
@@ -3432,7 +3432,7 @@ async def test_lineage_cache(seeded_random: random.Random) -> None:
called = 0
async def callback_none(ph: bytes32) -> Optional[UnspentLineageInfo]:
async def callback_none(ph: bytes32) -> UnspentLineageInfo | None:
nonlocal called
called += 1
return None
@@ -1,7 +1,6 @@
from __future__ import annotations
import datetime
from typing import Union
import pytest
from chia_rs.sized_ints import uint64
@@ -20,9 +19,7 @@ from chia.wallet.wallet import Wallet
@pytest.mark.anyio
async def test_protocol_messages(
simulator_and_wallet: tuple[
list[Union[FullNodeAPI, FullNodeSimulator]], list[tuple[Wallet, ChiaServer]], BlockTools
],
simulator_and_wallet: tuple[list[FullNodeAPI | FullNodeSimulator], list[tuple[Wallet, ChiaServer]], BlockTools],
) -> None:
full_nodes, _wallets, bt = simulator_and_wallet
a_wallet = bt.get_pool_wallet_tool()
@@ -34,7 +31,7 @@ async def test_protocol_messages(
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:
await full_node_sim.full_node.add_block(block)
@@ -3,8 +3,8 @@ from __future__ import annotations
import dataclasses
import logging
import random
from collections.abc import Awaitable, Collection, Sequence
from typing import Any, Callable, ClassVar, Optional, Union
from collections.abc import Awaitable, Callable, Collection, Sequence
from typing import Any, ClassVar
import pytest
from chia_rs import (
@@ -205,9 +205,9 @@ class TestBlockRecord:
header_hash: bytes32
height: uint32
timestamp: Optional[uint64]
timestamp: uint64 | None
prev_transaction_block_height: uint32
prev_transaction_block_hash: Optional[bytes32]
prev_transaction_block_hash: bytes32 | None
@property
def is_transaction_block(self) -> bool:
@@ -219,7 +219,7 @@ async def zero_calls_get_coin_records(coin_ids: Collection[bytes32]) -> list[Coi
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
@@ -258,7 +258,7 @@ async def instantiate_mempool_manager(
block_height: uint32 = TEST_HEIGHT,
block_timestamp: uint64 = TEST_TIMESTAMP,
constants: ConsensusConstants = DEFAULT_CONSTANTS,
max_tx_clvm_cost: Optional[uint64] = None,
max_tx_clvm_cost: uint64 | None = None,
) -> MempoolManager:
mempool_manager = MempoolManager(
get_coin_records,
@@ -275,9 +275,9 @@ async def instantiate_mempool_manager(
async def setup_mempool_with_coins(
*,
coin_amounts: list[int],
max_block_clvm_cost: Optional[int] = None,
max_tx_clvm_cost: Optional[uint64] = None,
mempool_block_buffer: Optional[int] = None,
max_block_clvm_cost: int | None = None,
max_tx_clvm_cost: uint64 | None = None,
mempool_block_buffer: int | None = None,
) -> tuple[MempoolManager, list[Coin]]:
coins = []
test_coin_records = {}
@@ -305,24 +305,24 @@ async def setup_mempool_with_coins(
return (mempool_manager, coins)
CreateCoin = tuple[bytes32, int, Optional[bytes]]
CreateCoin = tuple[bytes32, int, bytes | None]
def make_test_conds(
*,
birth_height: Optional[int] = None,
birth_seconds: Optional[int] = None,
height_relative: Optional[int] = None,
birth_height: int | None = None,
birth_seconds: int | None = None,
height_relative: int | None = None,
height_absolute: int = 0,
seconds_relative: Optional[int] = None,
seconds_relative: int | None = None,
seconds_absolute: int = 0,
before_height_relative: Optional[int] = None,
before_height_absolute: Optional[int] = None,
before_seconds_relative: Optional[int] = None,
before_seconds_absolute: Optional[int] = None,
before_height_relative: int | None = None,
before_height_absolute: int | None = None,
before_seconds_relative: int | None = None,
before_seconds_absolute: int | None = None,
cost: int = 0,
spend_ids: Sequence[tuple[Union[bytes32, Coin], int]] = [(TEST_COIN_ID, 0)],
created_coins: Optional[list[list[CreateCoin]]] = None,
spend_ids: Sequence[tuple[bytes32 | Coin, int]] = [(TEST_COIN_ID, 0)],
created_coins: list[list[CreateCoin]] | None = None,
) -> SpendBundleConditions:
if created_coins is None:
created_coins = []
@@ -432,7 +432,7 @@ class TestCheckTimeLocks:
def test_conditions(
self,
conds: SpendBundleConditions,
expected: Optional[Err],
expected: Err | None,
) -> None:
assert (
check_time_locks(
@@ -446,7 +446,7 @@ class TestCheckTimeLocks:
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:
ret = TimelockConditions(uint32(height), uint64(seconds))
if before_height is not None:
@@ -538,7 +538,7 @@ def spend_bundle_from_conditions(
async def add_spendbundle(
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)
ret = await mempool_manager.add_spend_bundle(sb, sbc, sb_name, TEST_HEIGHT)
invariant_check_mempool(mempool_manager.mempool)
@@ -550,7 +550,7 @@ async def generate_and_add_spendbundle(
conditions: list[list[Any]],
coin: Coin = TEST_COIN,
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_name = sb.name()
result = await add_spendbundle(mempool_manager, sb, sb_name)
@@ -838,7 +838,7 @@ async def test_ephemeral_timelock(
opcode: ConditionOpcode,
lock_value: int,
expected_status: MempoolInclusionStatus,
expected_error: Optional[Err],
expected_error: Err | None,
) -> None:
mempool_manager = await instantiate_mempool_manager(
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)
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(
coin,
SerializedProgram.to(None),
@@ -904,10 +904,10 @@ def mk_item(
*,
cost: int = 1,
fee: int = 0,
assert_height: Optional[int] = None,
assert_before_height: Optional[int] = None,
assert_before_seconds: Optional[int] = None,
solution: Optional[str] = None,
assert_height: int | None = None,
assert_before_height: int | None = None,
assert_before_seconds: int | None = None,
solution: str | None = None,
flags: list[int] = [],
) -> MempoolItem:
# 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
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:
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))}
@@ -1439,7 +1439,7 @@ def make_test_spendbundle(coin: Coin, *, fee: int = 0, eligible_spend: bool = Fa
async def send_spendbundle(
mempool_manager: MempoolManager,
sb: SpendBundle,
expected_result: tuple[MempoolInclusionStatus, Optional[Err]] = (MempoolInclusionStatus.SUCCESS, None),
expected_result: tuple[MempoolInclusionStatus, Err | None] = (MempoolInclusionStatus.SUCCESS, None),
) -> None:
result = await add_spendbundle(mempool_manager, sb, sb.name())
assert (result[1], result[2]) == expected_result
@@ -1450,7 +1450,7 @@ async def make_and_send_spendbundle(
coin: Coin,
*,
fee: int = 0,
expected_result: tuple[MempoolInclusionStatus, Optional[Err]] = (MempoolInclusionStatus.SUCCESS, None),
expected_result: tuple[MempoolInclusionStatus, Err | None] = (MempoolInclusionStatus.SUCCESS, None),
) -> SpendBundle:
sb = make_test_spendbundle(coin, fee=fee)
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 = []
test_coin_records = {}
@@ -2348,7 +2348,7 @@ class TestCoins:
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)
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:
self.lineage_info.pop(puzzle_hash)
else:
@@ -2365,7 +2365,7 @@ class TestCoins:
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)
@@ -3012,7 +3012,7 @@ class CheckRemovalsCase:
removals: dict[bytes32, CoinRecord]
bundle_coin_spends: dict[bytes32, BundleCoinSpend] = 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 = ()
@@ -3295,7 +3295,7 @@ async def test_new_peak_txs_added(condition_and_error: tuple[ConditionOpcode, Er
assert error == expected_error
# Advance the mempool beyond the asserted height to retry the test item
if optimized_path:
spent_coins: Optional[list[bytes32]] = []
spent_coins: list[bytes32] | None = []
new_peak_info = await mempool_manager.new_peak(
create_test_block_record(height=uint32(condition_height)), spent_coins
)
@@ -2,7 +2,7 @@ from __future__ import annotations
import copy
import dataclasses
from typing import Any, Optional
from typing import Any
import pytest
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_launcher_coin: bool = False,
signing_puzzle: Optional[Program] = None,
signing_coin: Optional[Coin] = None,
signing_puzzle: Program | None = None,
signing_coin: Coin | None = None,
aggsig: G2Element = G2Element(),
) -> tuple[MempoolInclusionStatus, Optional[Err]]:
) -> tuple[MempoolInclusionStatus, Err | None]:
if is_launcher_coin or not is_eligible_for_ff:
assert signing_puzzle is not None
assert signing_coin is not None
+7 -7
View File
@@ -7,7 +7,7 @@ import logging.config
import pathlib
import sys
import threading
from typing import Optional, final, overload
from typing import final, overload
from chia._tests.util.misc import create_logger
from chia.server.chia_policy import ChiaPolicy
@@ -47,7 +47,7 @@ async def async_main(
shutdown_path: pathlib.Path,
ip: str = "127.0.0.1",
port: int = 8444,
port_holder: Optional[list[int]] = None,
port_holder: list[int] | None = None,
) -> None: ...
@@ -58,22 +58,22 @@ async def async_main(
thread_end_event: threading.Event,
ip: str = "127.0.0.1",
port: int = 8444,
port_holder: Optional[list[int]] = None,
port_holder: list[int] | None = None,
) -> None: ...
async def async_main(
*,
out_path: pathlib.Path,
shutdown_path: Optional[pathlib.Path] = None,
thread_end_event: Optional[threading.Event] = None,
shutdown_path: pathlib.Path | None = None,
thread_end_event: threading.Event | None = None,
ip: str = "127.0.0.1",
port: int = 8444,
port_holder: Optional[list[int]] = None,
port_holder: list[int] | None = None,
) -> None:
with out_path.open(mode="w") as 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:
assert shutdown_path is not None
thread_end_event = threading.Event()
+1 -2
View File
@@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio
import logging
import time
from typing import Optional
import pytest
from aiohttp import ClientSession, ClientTimeout, WSCloseCode, WSMessage, WSMsgType, WSServerHandshakeError
@@ -36,7 +35,7 @@ def not_localhost(host: str) -> bool:
class FakeRateLimiter:
def process_msg_and_check(
self, message: Message, our_capabilities: list[Capability], peer_capabilities: list[Capability]
) -> Optional[str]:
) -> str | 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)
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
class EchoProtocol(asyncio.Protocol):
+7 -8
View File
@@ -10,7 +10,6 @@ import sys
import threading
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
from typing import Optional
import anyio
import pytest
@@ -45,8 +44,8 @@ async def serve_in_thread(
@dataclass
class Client:
reader: Optional[asyncio.StreamReader]
writer: Optional[asyncio.StreamWriter]
reader: asyncio.StreamReader | None
writer: asyncio.StreamWriter | None
@classmethod
async def open(cls, ip: str, port: int) -> Client:
@@ -95,10 +94,10 @@ class ServeInThread:
requested_port: int
out_path: pathlib.Path
connection_limit: int = 25
original_connection_limit: Optional[int] = None
loop: Optional[asyncio.AbstractEventLoop] = None
server_task: Optional[asyncio.Task[None]] = None
thread: Optional[threading.Thread] = None
original_connection_limit: int | None = None
loop: asyncio.AbstractEventLoop | None = None
server_task: asyncio.Task[None] | None = None
thread: threading.Thread | None = None
thread_end_event: threading.Event = field(default_factory=threading.Event)
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))
writer = None
post_connection_error: Optional[str] = None
post_connection_error: str | None = None
try:
logger.info(" ==== attempting a single new connection")
with anyio.fail_after(delay=adjusted_timeout(1)):
+2 -3
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Union
import pytest
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
msg_type = ProtocolMessageTypes.new_transaction
limits: dict[ProtocolMessageTypes, Union[RLSettings, Unlimited]]
limits: dict[ProtocolMessageTypes, RLSettings | Unlimited]
if limit_size:
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(
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
import chia.server.rate_limits
+2 -1
View File
@@ -1,8 +1,9 @@
from __future__ import annotations
import logging
from collections.abc import Callable
from dataclasses import dataclass
from typing import Callable, ClassVar, cast
from typing import ClassVar, cast
import pytest
from chia_rs.sized_bytes import bytes32
+2 -2
View File
@@ -7,7 +7,7 @@ import sys
import time
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Any, Optional, cast
from typing import Any, cast
import aiohttp.client_exceptions
import pytest
@@ -114,7 +114,7 @@ async def test_daemon_terminates(signal_number: signal.Signals, chia_root: ChiaR
async def test_services_terminate(
signal_number: signal.Signals,
chia_root: ChiaRoot,
create_service: Optional[CreateServiceProtocol],
create_service: CreateServiceProtocol | None,
module_path: str,
service_config_name: str,
) -> None:
@@ -4,12 +4,12 @@ import dataclasses
import logging
import operator
import time
from collections.abc import Awaitable
from collections.abc import Awaitable, Callable
from math import ceil
from os import mkdir
from pathlib import Path
from shutil import copy
from typing import Any, Callable, Union, cast
from typing import Any, cast
import pytest
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(
harvester_farmer_environment: HarvesterFarmerEnvironment,
endpoint: Callable[[FarmerRpcClient, PaginatedRequestData], Awaitable[dict[str, Any]]],
filtering: Union[list[FilterItem], list[str]],
filtering: list[FilterItem] | list[str],
sort_key: str,
reverse: bool,
expected_plot_count: int,
+1 -2
View File
@@ -5,7 +5,6 @@ import random
from hashlib import sha256
from itertools import permutations
from random import Random
from typing import Optional
import pytest
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
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])
for coin in coins:
coin_map.append((coin.name(), coin))
+4 -4
View File
@@ -4,7 +4,7 @@ import time
from dataclasses import dataclass
from ipaddress import IPv4Address, IPv6Address
from socket import AF_INET, AF_INET6, SOCK_STREAM
from typing import Optional, Union, cast
from typing import cast
from unittest.mock import AsyncMock
import dns
@@ -367,9 +367,9 @@ def get_mock_resolver() -> AsyncMock:
# Adjust mock_resolve to accept all arguments
async def mock_resolve(
qname: Union[dns.name.Name, str],
rdtype: Union[dns.rdatatype.RdataType, str] = dns.rdatatype.A,
lifetime: Optional[float] = None,
qname: dns.name.Name | str,
rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A,
lifetime: float | None = None,
) -> RRset:
if rdtype == "A":
return mock_rrset_a
+3 -3
View File
@@ -10,7 +10,7 @@ from multiprocessing import Pool, Queue, TimeoutError
from pathlib import Path
from threading import Thread
from time import sleep
from typing import Any, Optional
from typing import Any
import pytest
import yaml
@@ -41,7 +41,7 @@ def write_config(
atomic_write: bool,
do_sleep: bool,
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
@@ -74,7 +74,7 @@ def write_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
+2 -2
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Optional
from typing import Any
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint32
@@ -18,7 +18,7 @@ def test_primitives() -> None:
@dataclass(frozen=True)
class PrimitivesTest(Streamable):
a: uint32
b: Optional[str]
b: str | None
c: str
d: bytes
e: bytes32
+3 -3
View File
@@ -2,8 +2,8 @@ from __future__ import annotations
import json
import random
from collections.abc import Callable
from dataclasses import dataclass, replace
from typing import Callable, Optional
import importlib_resources
import pytest
@@ -271,7 +271,7 @@ def test_key_data_secrets_creation(
@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)
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())
@@ -343,7 +343,7 @@ def test_key_data_secrets_post_init(input_data: tuple[list[str], bytes, PrivateK
],
)
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:
with pytest.raises(KeychainKeyDataMismatch, match=data_type):
KeyData(*input_data)
+2 -1
View File
@@ -3,11 +3,12 @@ from __future__ import annotations
import logging
import os
import time
from collections.abc import Callable
from multiprocessing import Pool, TimeoutError
from pathlib import Path
from sys import platform
from time import sleep
from typing import Any, Callable
from typing import Any
import pytest
+1 -2
View File
@@ -4,7 +4,6 @@ import contextlib
import dataclasses
import logging
import re
from typing import Union
import pytest
@@ -22,7 +21,7 @@ def logger_fixture() -> logging.Logger:
@dataclasses.dataclass
class ErrorCase:
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
+15 -15
View File
@@ -2,16 +2,16 @@ from __future__ import annotations
import io
import re
from collections.abc import Callable
from dataclasses import dataclass, field, fields
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
from chia_rs import FullBlock, G1Element, SubEpochChallengeSegment
from chia_rs.sized_bytes import bytes4, bytes32
from chia_rs.sized_ints import uint8, uint32, uint64
from clvm_tools import binutils
from typing_extensions import Literal, get_args
from chia.protocols.wallet_protocol import RespondRemovals
from chia.simulator.block_tools import BlockTools, test_constants
@@ -418,10 +418,10 @@ class PostInitTestClassBad(Streamable):
@streamable
@dataclass(frozen=True)
class PostInitTestClassOptional(Streamable):
a: Optional[uint8]
b: Optional[uint8]
c: Optional[uint8]
d: Optional[uint8]
a: uint8 | None
b: uint8 | None
c: uint8 | None
d: uint8 | None
@streamable
@@ -537,8 +537,8 @@ def test_basic() -> None:
b: uint32
c: list[uint32]
d: list[list[uint32]]
e: Optional[uint32]
f: Optional[uint32]
e: uint32 | None
f: uint32 | None
g: tuple[uint32, str, bytes]
h: dict[uint32, str]
i: IntegerEnum
@@ -590,9 +590,9 @@ def test_json(bt: BlockTools) -> None:
@streamable
@dataclass(frozen=True)
class OptionalTestClass(Streamable):
a: Optional[str]
b: Optional[bool]
c: Optional[list[Optional[str]]]
a: str | None
b: bool | None
c: list[str | None] | None
@pytest.mark.parametrize(
@@ -606,7 +606,7 @@ class OptionalTestClass(Streamable):
(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})
assert obj.a == a
assert obj.b == b
@@ -623,7 +623,7 @@ class TestClassRecursive1(Streamable):
@dataclass(frozen=True)
class TestClassRecursive2(Streamable):
a: uint32
b: list[Optional[list[TestClassRecursive1]]]
b: list[list[TestClassRecursive1] | None]
c: bytes32
@@ -637,7 +637,7 @@ def test_recursive_json() -> None:
def test_recursive_types() -> None:
coin: Optional[Coin] = None
coin: Coin | None = None
l1 = [(bytes32([2] * 32), coin)]
rr = RespondRemovals(uint32(1), bytes32([1] * 32), l1, None)
RespondRemovals(rr.height, rr.header_hash, rr.coins, rr.proofs)
@@ -650,7 +650,7 @@ def test_ambiguous_deserialization_optionals() -> None:
@streamable
@dataclass(frozen=True)
class TestClassOptional(Streamable):
a: Optional[uint8]
a: uint8 | None
# Does not have the required elements
with pytest.raises(AssertionError):
+3 -2
View File
@@ -2,8 +2,9 @@ from __future__ import annotations
import asyncio
import contextlib
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, Optional
from typing import TYPE_CHECKING
import aiosqlite
import pytest
@@ -494,7 +495,7 @@ async def test_foreign_key_pragma_rolls_back_on_foreign_key_error() -> None:
@dataclass
class RowFactoryCase:
id: str
factory: Optional[type[aiosqlite.Row]]
factory: type[aiosqlite.Row] | None
marks: Marks = ()
+12 -12
View File
@@ -6,7 +6,7 @@ import operator
import unittest
from collections.abc import Iterator
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_ints import uint32, uint64
@@ -50,9 +50,9 @@ OPP_DICT = {"<": operator.lt, ">": operator.gt, "<=": operator.le, ">=": operato
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
def __repr__(self) -> str:
@@ -69,10 +69,10 @@ class WalletState:
@dataclass
class WalletStateTransition:
pre_block_balance_updates: dict[Union[int, str], dict[str, int]] = field(default_factory=dict)
post_block_balance_updates: dict[Union[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)
post_block_additional_balance_info: 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[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[int | str, dict[str, int]] = field(default_factory=dict)
@dataclass
@@ -121,7 +121,7 @@ class WalletEnvironment:
def xch_wallet(self) -> 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.
"""
@@ -131,7 +131,7 @@ class WalletEnvironment:
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.
"""
@@ -141,7 +141,7 @@ class WalletEnvironment:
else:
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
wallet actually returns via the RPC.
@@ -151,7 +151,7 @@ class WalletEnvironment:
dealiased_additional_balance_info: dict[uint32, dict[str, int]] = {
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:
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)})")
@@ -189,7 +189,7 @@ class WalletEnvironment:
if 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
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 typing import TYPE_CHECKING, Callable, Optional
from collections.abc import Callable
from typing import TYPE_CHECKING
if TYPE_CHECKING:
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
# populated until tests are running.
record_property: Optional[Callable[[str, object], None]] = None
test_id: Optional[TestId] = None
record_property: Callable[[str, object], None] | None = None
test_id: TestId | None = None
+18 -18
View File
@@ -5,7 +5,7 @@ import logging
from dataclasses import dataclass
from time import time
from types import TracebackType
from typing import Any, Optional, Union, cast
from typing import Any, cast
from unittest.mock import ANY
import pytest
@@ -57,7 +57,7 @@ class IncrementPoolStatsCase:
name: str
current_time: float
count: int
value: Optional[Union[int, dict[str, Any]]]
value: int | dict[str, Any] | None
expected_result: Any
def __init__(
@@ -66,7 +66,7 @@ class IncrementPoolStatsCase:
name: str,
current_time: float,
count: int,
value: Optional[Union[int, dict[str, Any]]],
value: int | dict[str, Any] | None,
expected_result: Any,
):
prepared_p2_singleton_puzzle_hash = std_hash(b"11223344")
@@ -137,13 +137,13 @@ class NewProofOfSpaceCase:
plot_size: PlotParam
plot_challenge: bytes32
plot_public_key: G1Element
pool_public_key: Optional[G1Element]
pool_public_key: G1Element | None
pool_contract_puzzle_hash: bytes32
height: uint32
proof: bytes
pool_config: PoolWalletConfig
pool_difficulty: Optional[uint64]
authentication_token_timeout: Optional[uint8]
pool_difficulty: uint64 | None
authentication_token_timeout: uint8 | None
farmer_private_keys: list[PrivateKey]
authentication_keys: dict[bytes32, PrivateKey]
use_invalid_peer_response: bool
@@ -157,8 +157,8 @@ class NewProofOfSpaceCase:
difficulty: uint64,
sub_slot_iters: uint64,
pool_url: str,
pool_difficulty: Optional[uint64],
authentication_token_timeout: Optional[uint8],
pool_difficulty: uint64 | None,
authentication_token_timeout: uint8 | None,
use_invalid_peer_response: bool,
has_valid_authentication_keys: bool,
expected_pool_stats: dict[str, Any],
@@ -676,9 +676,9 @@ async def test_farmer_new_proof_of_space_for_pool_stats(
class DummyPoolResponse:
ok: bool
status: int
error_code: Optional[int] = None
error_message: Optional[str] = None
new_difficulty: Optional[int] = None
error_code: int | None = None
error_message: str | None = None
new_difficulty: int | None = None
async def text(self) -> str:
json_dict: dict[str, Any] = dict()
@@ -695,9 +695,9 @@ class DummyPoolResponse:
async def __aexit__(
self,
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
pass
@@ -1010,7 +1010,7 @@ class DummyPoolInfoResponse:
ok: bool
status: int
url: URL
pool_info: Optional[dict[str, Any]] = None
pool_info: dict[str, Any] | None = None
history: tuple[DummyClientResponse, ...] = ()
async def text(self) -> str:
@@ -1024,9 +1024,9 @@ class DummyPoolInfoResponse:
async def __aexit__(
self,
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
pass
@@ -4,7 +4,7 @@ import asyncio
import unittest.mock
from math import floor
from pathlib import Path
from typing import Any, Optional
from typing import Any
from unittest.mock import AsyncMock, Mock
import pytest
@@ -56,12 +56,12 @@ def farmer_is_started(farmer: Farmer) -> bool:
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, _):
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, _):
return await harvester_client.update_harvester_config(config)
@@ -2,7 +2,7 @@ from __future__ import annotations
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Any, Optional
from typing import Any
import pytest
from chia_rs import FullBlock
@@ -94,7 +94,7 @@ async def test_filter_prefix_bits_with_farmer_harvester(
state_change = 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
state_change = change
state_change_data = change_data
@@ -7,7 +7,7 @@ import dataclasses
import json
import logging
from os.path import dirname
from typing import Optional, Union, cast
from typing import cast
import pytest
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[
FarmerService,
HarvesterService,
Union[FullNodeService, SimulatorFullNodeService],
Union[FullNodeService, SimulatorFullNodeService],
FullNodeService | SimulatorFullNodeService,
FullNodeService | SimulatorFullNodeService,
BlockTools,
],
) -> None:
@@ -121,12 +121,12 @@ async def test_harvester_receive_source_signing_data(
async def intercept_harvester_request_signatures(
self: HarvesterAPI, request: harvester_protocol.RequestSignatures
) -> Optional[Message]:
) -> Message | None:
nonlocal harvester
nonlocal farmer_reward_address
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
)
assert result_msg is not None
@@ -158,15 +158,14 @@ async def test_harvester_receive_source_signing_data(
assert hash
assert src
data: Optional[
Union[
FoliageBlockData,
FoliageTransactionBlock,
ClassgroupElement,
ChallengeChainSubSlot,
RewardChainSubSlot,
]
] = None
data: (
FoliageBlockData
| FoliageTransactionBlock
| ClassgroupElement
| ChallengeChainSubSlot
| RewardChainSubSlot
| None
) = None
if src.kind == uint8(SigningDataKind.FOLIAGE_BLOCK_DATA):
data = FoliageBlockData.from_bytes(src.data)
assert (
@@ -227,7 +226,7 @@ async def test_harvester_receive_source_signing_data(
async def intercept_farmer_request_signed_values(
self: FarmerAPI, request: farmer_protocol.RequestSignedValues
) -> Optional[Message]:
) -> Message | None:
nonlocal farmer
nonlocal farmer_reward_address
nonlocal full_node_2
@@ -284,8 +283,8 @@ async def test_harvester_fee_convention(
farmer_harvester_2_simulators_zero_bits_plot_filter: tuple[
FarmerService,
HarvesterService,
Union[FullNodeService, SimulatorFullNodeService],
Union[FullNodeService, SimulatorFullNodeService],
FullNodeService | SimulatorFullNodeService,
FullNodeService | SimulatorFullNodeService,
BlockTools,
],
caplog: pytest.LogCaptureFixture,
@@ -314,8 +313,8 @@ async def test_harvester_fee_invalid_convention(
farmer_harvester_2_simulators_zero_bits_plot_filter: tuple[
FarmerService,
HarvesterService,
Union[FullNodeService, SimulatorFullNodeService],
Union[FullNodeService, SimulatorFullNodeService],
FullNodeService | SimulatorFullNodeService,
FullNodeService | SimulatorFullNodeService,
BlockTools,
],
caplog: pytest.LogCaptureFixture,
@@ -437,7 +436,7 @@ def node_type_connected(server: ChiaServer, node_type: NodeType) -> bool:
def decode_sp(
is_sub_slot: bool, sp64: str
) -> Union[timelord_protocol.NewEndOfSubSlotVDF, timelord_protocol.NewSignagePointVDF]:
) -> timelord_protocol.NewEndOfSubSlotVDF | timelord_protocol.NewSignagePointVDF:
sp_bytes = base64.b64decode(sp64)
if is_sub_slot:
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)
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):
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 contextlib
import functools
from collections.abc import AsyncIterator
from collections.abc import AsyncIterator, Callable
from dataclasses import dataclass, field, replace
from pathlib import Path
from shutil import copy
from typing import Any, Callable, Optional
from typing import Any
import pytest
from chia_rs import G1Element, PlotParam
@@ -131,7 +131,7 @@ class Environment:
split_farmer_service_manager: SplitAsyncManager[FarmerService]
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:
assert harvester.server is not None
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_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:
return
harvester: Optional[Harvester] = self.get_harvester(peer_id)
harvester: Harvester | None = self.get_harvester(peer_id)
assert harvester is not None
expected = self.expected[self.harvesters.index(harvester)]
assert len(expected.valid_delta.additions) == len(delta.valid.additions)
+4 -3
View File
@@ -4,7 +4,8 @@ import dataclasses
import logging
import random
import time
from typing import Any, Callable, Union
from collections.abc import Callable
from typing import Any
import pytest
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
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:
for plot_info in data:
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()
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:
for plot_info in data:
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 enum import Enum
from pathlib import Path
from typing import Any, Optional
from typing import Any
import pytest
from chia_rs import G1Element
@@ -102,7 +102,7 @@ class TestData:
batch_size = self.harvester.plot_manager.refresh_parameter.batch_size
# Used to capture the sync id in `run_internal`
sync_id: Optional[uint64] = None
sync_id: uint64 | None = None
def run_internal() -> None:
nonlocal sync_id
+1 -2
View File
@@ -4,7 +4,6 @@ import contextlib
import time
from collections.abc import AsyncIterator
from dataclasses import dataclass
from typing import Optional
from chia_rs.sized_bytes import bytes32
from chia_rs.sized_ints import uint16, uint64
@@ -25,7 +24,7 @@ class WSChiaConnectionDummy:
connection_type: NodeType
peer_node_id: bytes32
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:
self.last_sent_message = message
+3 -3
View File
@@ -3,12 +3,12 @@ from __future__ import annotations
import logging
import sys
import time
from collections.abc import Iterator
from collections.abc import Callable, Iterator
from dataclasses import dataclass, replace
from os import unlink
from pathlib import Path
from shutil import copy, move
from typing import Callable, Optional, cast
from typing import cast
import pytest
from chia_rs import G1Element
@@ -664,7 +664,7 @@ async def test_cache_lifetime(environment: Environment) -> None:
)
@pytest.mark.anyio
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):
nonlocal last_event_fired
+3 -3
View File
@@ -4,7 +4,7 @@ import json
import re
from dataclasses import dataclass
from io import StringIO
from typing import Optional, cast
from typing import cast
import click
import pytest
@@ -59,8 +59,8 @@ pytestmark = [pytest.mark.limit_consensus_modes(reason="irrelevant")]
class StateUrlCase:
id: str
state: str
pool_url: Optional[str]
expected_error: Optional[str] = None
pool_url: str | None
expected_error: str | None = None
marks: Marks = ()
+3 -3
View File
@@ -8,7 +8,7 @@ from collections.abc import AsyncIterator
from dataclasses import dataclass
from pathlib import Path
from shutil import rmtree
from typing import Any, Union
from typing import Any
import pytest
@@ -211,7 +211,7 @@ async def process_plotnft_create(
) -> int:
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: {
"confirmed_wallet_balance": 0,
"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: {
"confirmed_wallet_balance": -1,
"unconfirmed_wallet_balance": 0,
+3 -3
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Optional, cast
from typing import Any, cast
from unittest.mock import MagicMock
import pytest
@@ -27,7 +27,7 @@ class MockStandardWallet:
@dataclass
class MockWalletStateManager:
root_path: Optional[Path] = None
root_path: Path | None = None
config: dict[str, Any] = field(default_factory=dict)
@@ -43,7 +43,7 @@ class MockPoolWalletConfig:
@dataclass
class MockPoolState:
pool_url: Optional[str]
pool_url: str | None
target_puzzle_hash: bytes32
owner_pubkey: G1Element
+1 -4
View File
@@ -2,7 +2,6 @@ from __future__ import annotations
import random
from dataclasses import dataclass, field
from typing import Optional
import pytest
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
def make_child_solution(
coin_spend: Optional[CoinSpend], new_coin: Optional[Coin], seeded_random: random.Random
) -> CoinSpend:
def make_child_solution(coin_spend: CoinSpend | None, new_coin: Coin | None, seeded_random: random.Random) -> CoinSpend:
new_puzzle_hash: bytes32 = bytes32.random(seeded_random)
solution = "()"
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 pathlib import Path
from statistics import StatisticsError, mean, stdev
from typing import Any, Optional, TextIO, final
from typing import Any, TextIO, final
import click
import lxml.etree
@@ -126,7 +126,7 @@ def main(
percent_margin: int,
randomoji: bool,
tag: str,
result_count_limit: Optional[int],
result_count_limit: int | None,
) -> None:
data_type = supported_data_types_by_tag[tag]
+4 -4
View File
@@ -1,9 +1,9 @@
from __future__ import annotations
from collections.abc import AsyncIterator, Awaitable
from collections.abc import AsyncIterator, Awaitable, Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Optional
from typing import Any
import pytest
from chia_rs.sized_ints import uint16
@@ -31,8 +31,8 @@ client_fetch_methods = [
@dataclass
class InvalidCreateCase:
id: str
root_path: Optional[Path] = None
net_config: Optional[dict[str, Any]] = None
root_path: Path | None = None
net_config: dict[str, Any] | None = None
marks: Marks = ()
+3 -3
View File
@@ -7,7 +7,7 @@ import ssl
import sys
from collections.abc import AsyncIterator
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, Optional, cast
from typing import TYPE_CHECKING, Any, ClassVar, cast
import aiohttp
import pytest
@@ -42,7 +42,7 @@ class TestRpcApi:
service: RpcServiceProtocol
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
return [] # pragma: no cover
@@ -73,7 +73,7 @@ class Client:
async with aiohttp.ClientSession() as session:
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:
json = {}
+2 -2
View File
@@ -1,9 +1,9 @@
from __future__ import annotations
from typing import Literal, Union
from typing import Literal
# Defaults are conservative.
parallel: Union[bool, int, Literal["auto"]] = True
parallel: bool | int | Literal["auto"] = True
checkout_blocks_and_plots = False
install_timelord = False
# NOTE: do not use until the hangs are fixed
+2 -4
View File
@@ -1,7 +1,5 @@
from __future__ import annotations
from typing import Optional
import pytest
from chia_rs import BlockRecord, FullBlock, SubEpochSummary, UnfinishedBlock
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:
return []
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:
if curr != peak:
recent_rc.append((curr.reward_infusion_new_challenge, curr.total_iters))
@@ -602,7 +600,7 @@ def timelord_peak_from_block(
) -> timelord_protocol.NewPeakTimelord:
peak = blockchain.block_record(block.header_hash)
_, 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
)
+2 -1
View File
@@ -1,8 +1,9 @@
from __future__ import annotations
import textwrap
from collections.abc import Callable
from pathlib import Path
from typing import Any, Callable
from typing import Any
import click
import pytest
+3 -4
View File
@@ -5,7 +5,6 @@ import os
import pickle # noqa: S403 # TODO: use explicit serialization instead of pickle
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Optional
from chia_rs import ConsensusConstants, FullBlock
from chia_rs.sized_ints import uint64
@@ -49,8 +48,8 @@ def persistent_blocks(
normalized_to_identity_icc_eos: bool = False,
normalized_to_identity_cc_sp: bool = False,
normalized_to_identity_cc_ip: bool = False,
block_list_input: Optional[list[FullBlock]] = None,
time_per_block: Optional[float] = None,
block_list_input: list[FullBlock] | None = None,
time_per_block: float | None = None,
dummy_block_references: bool = False,
include_transactions: bool = False,
) -> list[FullBlock]:
@@ -112,7 +111,7 @@ def new_test_db(
empty_sub_slots: int,
bt: BlockTools,
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_icc_eos: bool = False, # ICC_EOS
+11 -11
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
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.sized_bytes import bytes32
@@ -20,9 +20,9 @@ class BlockchainMock:
def __init__(
self,
blocks: dict[bytes32, BlockRecord],
headers: Optional[dict[bytes32, HeaderBlock]] = None,
height_to_hash: Optional[dict[uint32, bytes32]] = None,
sub_epoch_summaries: Optional[dict[uint32, SubEpochSummary]] = None,
headers: dict[bytes32, HeaderBlock] | None = None,
height_to_hash: dict[uint32, bytes32] | None = None,
sub_epoch_summaries: dict[uint32, SubEpochSummary] | None = None,
):
if sub_epoch_summaries is None:
sub_epoch_summaries = {}
@@ -37,10 +37,10 @@ class BlockchainMock:
self._sub_epoch_segments: dict[bytes32, SubEpochSegments] = {}
self.log = logging.getLogger(__name__)
def get_peak(self) -> Optional[BlockRecord]:
def get_peak(self) -> BlockRecord | None:
return None
def get_peak_height(self) -> Optional[uint32]:
def get_peak_height(self) -> uint32 | None:
return None
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:
# 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
return self.block_record(header_hash)
@@ -60,7 +60,7 @@ class BlockchainMock:
def get_ses(self, height: uint32) -> SubEpochSummary:
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
return self._height_to_hash[height]
@@ -88,10 +88,10 @@ class BlockchainMock:
block_records.append(self.height_to_block_record(height))
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)
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]
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(
self,
sub_epoch_summary_hash: bytes32,
) -> Optional[list[SubEpochChallengeSegment]]:
) -> list[SubEpochChallengeSegment] | None:
segments = self._sub_epoch_segments.get(sub_epoch_summary_hash)
if segments is None:
return None
@@ -4,8 +4,9 @@ from __future__ import annotations
import os
import subprocess
import sys
from collections.abc import Callable
from pathlib import Path
from typing import Any, Callable
from typing import Any
from chia_rs.sized_ints import uint32
+2 -3
View File
@@ -4,7 +4,6 @@ import tempfile
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
import aiosqlite
@@ -14,8 +13,8 @@ from chia.util.db_wrapper import DBWrapper2, generate_in_memory_db_uri
@asynccontextmanager
async def DBConnection(
db_version: int,
foreign_keys: Optional[bool] = None,
row_factory: Optional[type[aiosqlite.Row]] = None,
foreign_keys: bool | None = None,
row_factory: type[aiosqlite.Row] | None = None,
) -> AsyncIterator[DBWrapper2]:
db_uri = generate_in_memory_db_uri()
async with DBWrapper2.managed(
+9 -11
View File
@@ -5,10 +5,10 @@ import logging
import shutil
import tempfile
import time
from collections.abc import Iterator
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Callable, Optional, cast
from typing import cast
import aiosqlite
import zstd
@@ -60,9 +60,7 @@ def enable_profiler(profile: bool, counter: int) -> Iterator[None]:
class FakeServer:
async def send_to_all(
self, messages: list[Message], node_type: NodeType, exclude: Optional[bytes32] = None
) -> None:
async def send_to_all(self, messages: list[Message], node_type: NodeType, exclude: bytes32 | None = None) -> None:
pass
async def send_to_all_if(
@@ -70,18 +68,18 @@ class FakeServer:
messages: list[Message],
node_type: NodeType,
predicate: Callable[[WSChiaConnection], bool],
exclude: Optional[bytes32] = None,
exclude: bytes32 | None = None,
) -> None:
pass
def set_received_message_callback(self, callback: ConnectionCallback) -> None:
pass
async def get_peer_info(self) -> Optional[PeerInfo]:
async def get_peer_info(self) -> PeerInfo | None:
return None
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]:
return []
@@ -91,7 +89,7 @@ class FakeServer:
async def start_client(
self,
target_node: PeerInfo,
on_connect: Optional[ConnectionCallback] = None,
on_connect: ConnectionCallback | None = None,
auth: bool = False,
is_feeler: bool = False,
) -> bool:
@@ -105,7 +103,7 @@ class FakePeer:
def __init__(self) -> None:
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
@@ -118,7 +116,7 @@ async def run_sync_test(
keep_up: bool,
db_sync: str,
node_profiler: bool,
start_at_checkpoint: Optional[str],
start_at_checkpoint: str | None,
) -> None:
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
+4 -5
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
from pathlib import Path
from typing import Optional
import click
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,
)
def gen_ssl(suffix: str = "") -> None:
captured_crt: Optional[bytes] = None
captured_key: Optional[bytes] = None
captured_crt: bytes | None = None
captured_key: bytes | None = None
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:
@@ -39,8 +38,8 @@ def gen_ssl(suffix: str = "") -> None:
patch = MonkeyPatch()
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_key: Optional[bytes] = None
private_ca_crt: bytes | None = None
private_ca_key: bytes | None = None
capture_cert_and_key = True
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 subprocess
import sys
from collections.abc import Awaitable, Collection, Iterator
from collections.abc import Awaitable, Callable, Collection, Iterator
from concurrent.futures import Future
from dataclasses import dataclass, field
from enum import Enum
@@ -20,7 +20,7 @@ from statistics import mean
from textwrap import dedent
from time import thread_time
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 pytest
@@ -88,7 +88,7 @@ class RuntimeResults:
duration: float
entry_file: str
entry_line: int
overhead: Optional[float]
overhead: float | None
def block(self, label: str = "") -> str:
# The entry line is reported starting at the beginning of the line to trigger
@@ -112,13 +112,13 @@ class AssertRuntimeResults:
duration: float
entry_file: str
entry_line: int
overhead: Optional[float]
overhead: float | None
limit: float
ratio: float
@classmethod
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:
return cls(
start=results.start,
@@ -161,7 +161,7 @@ class AssertRuntimeResults:
def measure_overhead(
manager_maker: Callable[
[], contextlib.AbstractContextManager[Union[Future[RuntimeResults], Future[AssertRuntimeResults]]]
[], contextlib.AbstractContextManager[Future[RuntimeResults] | Future[AssertRuntimeResults]]
],
cycles: int = 10,
) -> float:
@@ -183,7 +183,7 @@ def measure_runtime(
label: str = "",
clock: Callable[[], float] = thread_time,
gc_mode: GcMode = GcMode.disable,
overhead: Optional[float] = None,
overhead: float | None = None,
print_results: bool = True,
) -> Iterator[Future[RuntimeResults]]:
entry_file, entry_line = caller_file_and_line(
@@ -289,12 +289,12 @@ class _AssertRuntime:
clock: Callable[[], float] = thread_time
gc_mode: GcMode = GcMode.disable
print: bool = True
overhead: Optional[float] = None
entry_file: Optional[str] = None
entry_line: Optional[int] = None
_results: Optional[AssertRuntimeResults] = None
runtime_manager: Optional[contextlib.AbstractContextManager[Future[RuntimeResults]]] = None
runtime_results_callable: Optional[Future[RuntimeResults]] = None
overhead: float | None = None
entry_file: str | None = None
entry_line: int | None = None
_results: AssertRuntimeResults | None = None
runtime_manager: contextlib.AbstractContextManager[Future[RuntimeResults]] | None = None
runtime_results_callable: Future[RuntimeResults] | None = None
enable_assertion: bool = True
def __enter__(self) -> Future[AssertRuntimeResults]:
@@ -315,9 +315,9 @@ class _AssertRuntime:
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc: Optional[BaseException],
traceback: Optional[TracebackType],
exc_type: type[BaseException] | None,
exc: BaseException | None,
traceback: TracebackType | None,
) -> None:
if (
self.entry_file is None
@@ -366,8 +366,8 @@ class _AssertRuntime:
@dataclasses.dataclass
class BenchmarkRunner:
enable_assertion: bool = True
test_id: Optional[TestId] = None
overhead: Optional[float] = None
test_id: TestId | None = None
overhead: float | None = None
def assert_runtime(self, *args: Any, **kwargs: Any) -> _AssertRuntime:
kwargs.setdefault("enable_assertion", self.enable_assertion)
@@ -445,7 +445,7 @@ class CoinGenerator:
self._seed += 1
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:
parent_coin_id = self._get_hash()
hint = None
@@ -516,7 +516,7 @@ class RecordingWebServer:
hostname: str,
port: uint16,
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,
) -> RecordingWebServer:
web_server = await WebServer.create(
@@ -657,9 +657,9 @@ def is_attribute_local(o: object, name: str) -> bool:
@contextlib.contextmanager
def patch_request_handler(
api: Union[ApiProtocol, type[ApiProtocol]],
handler: Callable[..., Awaitable[Optional[Message]]],
request_type: Optional[ProtocolMessageTypes] = None,
api: ApiProtocol | type[ApiProtocol],
handler: Callable[..., Awaitable[Message | None]],
request_type: ProtocolMessageTypes | None = None,
) -> Iterator[None]:
if request_type is None:
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 dataclasses import dataclass
from pathlib import Path
from typing import Optional, Union
import anyio
from chia_rs import ConsensusConstants
@@ -59,8 +58,8 @@ SimulatorsAndWalletsServices = tuple[list[SimulatorFullNodeService], list[Wallet
@dataclass(frozen=True)
class FullSystem:
node_1: Union[FullNodeService, SimulatorFullNodeService]
node_2: Union[FullNodeService, SimulatorFullNodeService]
node_1: FullNodeService | SimulatorFullNodeService
node_2: FullNodeService | SimulatorFullNodeService
harvester: Harvester
farmer: Farmer
introducer: IntroducerAPI
@@ -159,11 +158,11 @@ async def setup_simulators_and_wallets(
spam_filter_after_n_txs: int = 200,
xch_spam_amount: int = 1000000,
*,
key_seed: Optional[bytes32] = None,
key_seed: bytes32 | None = None,
initial_num_public_keys: int = 5,
db_version: int = 2,
config_overrides: Optional[dict[str, int]] = None,
disable_capabilities: Optional[list[Capability]] = None,
config_overrides: dict[str, int] | None = None,
disable_capabilities: list[Capability] | None = None,
) -> AsyncIterator[SimulatorsAndWallets]:
with TempKeyring(populate=True) as keychain1, TempKeyring(populate=True) as keychain2:
if config_overrides is None:
@@ -212,11 +211,11 @@ async def setup_simulators_and_wallets_service(
spam_filter_after_n_txs: int = 200,
xch_spam_amount: int = 1000000,
*,
key_seed: Optional[bytes32] = None,
key_seed: bytes32 | None = None,
initial_num_public_keys: int = 5,
db_version: int = 2,
config_overrides: Optional[dict[str, int]] = None,
disable_capabilities: Optional[list[Capability]] = None,
config_overrides: dict[str, int] | None = None,
disable_capabilities: list[Capability] | None = None,
) -> AsyncIterator[tuple[list[SimulatorFullNodeService], list[WalletService], BlockTools]]:
with TempKeyring(populate=True) as keychain1, TempKeyring(populate=True) as keychain2:
async with setup_simulators_and_wallets_inner(
@@ -241,15 +240,15 @@ async def setup_simulators_and_wallets_inner(
db_version: int,
consensus_constants: ConsensusConstants,
initial_num_public_keys: int,
key_seed: Optional[bytes32],
key_seed: bytes32 | None,
keychain1: Keychain,
keychain2: Keychain,
simulator_count: int,
spam_filter_after_n_txs: int,
wallet_count: int,
xch_spam_amount: int,
config_overrides: Optional[dict[str, int]],
disable_capabilities: Optional[list[Capability]],
config_overrides: dict[str, int] | None,
disable_capabilities: list[Capability] | None,
) -> AsyncIterator[tuple[list[BlockTools], list[SimulatorFullNodeService], list[WalletService]]]:
if config_overrides is not None and "full_node.max_sync_wait" not in config_overrides:
config_overrides["full_node.max_sync_wait"] = 0
@@ -310,7 +309,7 @@ async def setup_farmer_solver_multi_harvester(
consensus_constants: ConsensusConstants,
*,
start_services: bool,
solver_peer: Optional[UnresolvedPeerInfo] = None,
solver_peer: UnresolvedPeerInfo | None = None,
) -> AsyncIterator[tuple[list[HarvesterService], FarmerService, BlockTools]]:
async with AsyncExitStack() as async_exit_stack:
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(
consensus_constants: ConsensusConstants,
shared_b_tools: BlockTools,
b_tools: Optional[BlockTools] = None,
b_tools_1: Optional[BlockTools] = None,
b_tools: BlockTools | None = None,
b_tools_1: BlockTools | None = None,
db_version: int = 2,
) -> AsyncIterator[FullSystem]:
with TempKeyring(populate=True) as keychain1, TempKeyring(populate=True) as keychain2:
@@ -361,8 +360,8 @@ async def setup_full_system(
@asynccontextmanager
async def setup_full_system_inner(
b_tools: Optional[BlockTools],
b_tools_1: Optional[BlockTools],
b_tools: BlockTools | None,
b_tools_1: BlockTools | None,
connect_to_daemon: bool,
consensus_constants: ConsensusConstants,
db_version: int,
+21 -21
View File
@@ -7,7 +7,7 @@ from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional
from typing import Any
import anyio
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
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]]:
async with SpendSim.managed(db_path, defaults) as sim:
client: SimClient = SimClient(sim)
@@ -103,7 +103,7 @@ class CostLogger:
@streamable
@dataclass(frozen=True)
class SimFullBlock(Streamable):
transactions_generator: Optional[BlockGenerator]
transactions_generator: BlockGenerator | None
height: uint32 # Note that height is not on a regular FullBlock
@@ -155,7 +155,7 @@ class SpendSim:
@classmethod
@contextlib.asynccontextmanager
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]:
self = cls()
if db_path is None:
@@ -203,7 +203,7 @@ class SpendSim:
)
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)
def new_coin_record(self, coin: Coin, coinbase: bool = False) -> CoinRecord:
@@ -229,7 +229,7 @@ class SpendSim:
coins.add(coin)
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:
return None
return simple_solution_generator(bundle)
@@ -257,7 +257,7 @@ class SpendSim:
),
]
# Coin store gets updated
generator_bundle: Optional[SpendBundle] = None
generator_bundle: SpendBundle | None = None
tx_additions = []
tx_removals = []
spent_coins_ids = None
@@ -295,7 +295,7 @@ class SpendSim:
tx_removals=spent_coins_ids if spent_coins_ids is not None else [],
)
# 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.blocks.append(SimFullBlock(generator, next_block_height))
@@ -336,7 +336,7 @@ class SimClient:
def __init__(self, service: SpendSim) -> None:
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:
spend_bundle_id = spend_bundle.name()
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
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)
async def get_coin_records_by_names(
self,
names: list[bytes32],
start_height: Optional[int] = None,
end_height: Optional[int] = None,
start_height: int | None = None,
end_height: int | None = None,
include_spent_coins: bool = False,
) -> list[CoinRecord]:
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(
self,
parent_ids: list[bytes32],
start_height: Optional[int] = None,
end_height: Optional[int] = None,
start_height: int | None = None,
end_height: int | None = None,
include_spent_coins: bool = False,
) -> list[CoinRecord]:
kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "parent_ids": parent_ids}
@@ -383,8 +383,8 @@ class SimClient:
self,
puzzle_hash: bytes32,
include_spent_coins: bool = True,
start_height: Optional[int] = None,
end_height: Optional[int] = None,
start_height: int | None = None,
end_height: int | None = None,
) -> list[CoinRecord]:
kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "puzzle_hash": puzzle_hash}
if start_height is not None:
@@ -397,8 +397,8 @@ class SimClient:
self,
puzzle_hashes: list[bytes32],
include_spent_coins: bool = True,
start_height: Optional[int] = None,
end_height: Optional[int] = None,
start_height: int | None = None,
end_height: int | None = None,
) -> list[CoinRecord]:
kwargs: dict[str, Any] = {"include_spent_coins": include_spent_coins, "puzzle_hashes": puzzle_hashes}
if start_height is not None:
@@ -460,7 +460,7 @@ class SimClient:
spends[item.name] = item
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)
if item is None:
return None
@@ -471,8 +471,8 @@ class SimClient:
self,
hint: bytes32,
include_spent_coins: bool = True,
start_height: Optional[int] = None,
end_height: Optional[int] = None,
start_height: int | None = None,
end_height: int | None = None,
) -> list[CoinRecord]:
"""
Retrieves coins by hint, by default returns unspent coins.
+2 -3
View File
@@ -4,7 +4,6 @@ import asyncio
import random
import re
from dataclasses import dataclass
from typing import Optional
import anyio
import pytest
@@ -128,12 +127,12 @@ async def test_worker_exception_logged(caplog: pytest.LogCaptureFixture) -> None
def __init__(self) -> None:
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()
async def worker(
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,
) -> None:
work = await work_queue.get()
+1 -3
View File
@@ -1,7 +1,5 @@
from __future__ import annotations
from typing import Optional
import pytest
from packaging.version import Version
@@ -46,5 +44,5 @@ def test_chia_short_version() -> None:
("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
+3 -3
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Optional
from typing import Any
from chia_rs.sized_ints import uint16
@@ -158,8 +158,8 @@ class SetPeerInfoCase(DataCase):
service_config: dict[str, Any]
requested_node_type: NodeType
expected_service_config: dict[str, Any]
peer_host: Optional[str] = None
peer_port: Optional[int] = None
peer_host: str | None = None
peer_port: int | None = None
marks: Marks = ()
@property
+2 -3
View File
@@ -2,7 +2,6 @@ from __future__ import annotations
import random
from collections.abc import Generator, Iterator
from typing import Optional
import pytest
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
timestamp = uint64(1631794488)
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:
yield None
else:
+1 -2
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio
from typing import Optional
import pytest
@@ -18,7 +17,7 @@ async def test_stuff() -> None:
semaphore = LimitedSemaphore.create(active_limit=active_limit, waiting_limit=waiting_limit)
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():
assert entered_event is not None
entered_event.set()

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