diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 2319d942fb52..000000000000 --- a/.flake8 +++ /dev/null @@ -1,10 +0,0 @@ -[flake8] -max-line-length = 120 -exclude = ./typings/**/* -ignore = E203,W503 -extend-ignore = E226,E704,E701 -per-file-ignores = - chia/_tests/util/build_network_protocol_files.py:F405 - chia/_tests/util/test_network_protocol_files.py:F405 - chia/_tests/util/test_network_protocol_json.py:F405 - chia/_tests/util/protocol_messages_json.py:E501 diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index 53b8c1209bef..53a3bbdd86e2 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -21,5 +21,5 @@ jobs: - name: "Dependency Review" uses: actions/dependency-review-action@v4 with: - allow-dependencies-licenses: pkg:pypi/pyinstaller + allow-dependencies-licenses: pkg:pypi/pylint, pkg:pypi/pyinstaller deny-licenses: AGPL-1.0-only, AGPL-1.0-or-later, AGPL-1.0-or-later, AGPL-3.0-or-later, GPL-1.0-only, GPL-1.0-or-later, GPL-2.0-only, GPL-2.0-or-later, GPL-3.0-only, GPL-3.0-or-later diff --git a/.github/workflows/test-install-scripts.yml b/.github/workflows/test-install-scripts.yml index bda58f04f054..3e7006b1878e 100644 --- a/.github/workflows/test-install-scripts.yml +++ b/.github/workflows/test-install-scripts.yml @@ -22,34 +22,53 @@ concurrency: jobs: test_scripts: - name: Test Install Scripts - ${{ matrix.development.name }} - ${{ matrix.editable.name }} - runs-on: ${{ matrix.os.runs-on }} + name: Native ${{ matrix.os.emoji }} ${{ matrix.arch.name }} ${{ matrix.development.name }} - ${{ matrix.editable.name }} + runs-on: ${{ matrix.os.runs-on[matrix.arch.matrix] }} strategy: fail-fast: false matrix: python: - major-dot-minor: "3.10" os: - - runs-on: macos-latest - matrix: macos-arm - - runs-on: macos-13 - matrix: macos-intel - - runs-on: ubuntu-latest + - name: Linux + emoji: 🐧 + runs-on: + arm: [Linux, ARM64] + intel: ubuntu-latest matrix: linux - - runs-on: windows-latest + - name: macOS + emoji: 🍎 + runs-on: + arm: macos-latest + intel: macos-13 + matrix: macos + - name: Windows + emoji: 🪟 + runs-on: + intel: windows-latest matrix: windows + arch: + - name: ARM + matrix: arm + - name: Intel + matrix: intel development: - - name: Non-development + - name: Non-dev value: false - - name: Development + - name: Dev value: true editable: - - name: Non-editable + - name: Non-edit value: false matrix: non-editable - - name: Editable + - name: Edit value: true matrix: editable + exclude: + - os: + matrix: windows + arch: + matrix: arm steps: - name: Checkout Code @@ -112,7 +131,7 @@ jobs: [ "$POST_VERSION" != "shooby-doowah" -a "$PRE_VERSION" = "$POST_VERSION" ] test_scripts_in_docker: - name: Test Install Scripts ${{ matrix.distribution.name }} ${{ matrix.arch.name }} + name: Docker ${{ matrix.distribution.name }} ${{ matrix.arch.name }} runs-on: ${{ matrix.os.runs-on[matrix.arch.matrix] }} container: ${{ matrix.distribution.url }} strategy: diff --git a/.github/workflows/upload-pypi-source.yml b/.github/workflows/upload-pypi-source.yml index 7baee8f1b3d1..f8944eada266 100644 --- a/.github/workflows/upload-pypi-source.yml +++ b/.github/workflows/upload-pypi-source.yml @@ -120,8 +120,6 @@ jobs: check: - name: black command: black --check --diff . - - name: flake8 - command: flake8 benchmarks build_scripts chia tools *.py - name: generated protocol tests command: | python3 -m chia._tests.util.build_network_protocol_files diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ebee9872709c..f3e8e27f9397 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,13 +13,6 @@ repos: entry: ./activated.py python chia/_tests/build-init-files.py -v --root . language: system pass_filenames: false - - repo: local - hooks: - - id: pyupgrade - name: pyupgrade - entry: ./activated.py pyupgrade --py39-plus --keep-runtime-typing - language: system - types: [python] - repo: local hooks: - id: black @@ -92,20 +85,6 @@ repos: entry: ./activated.py mypy language: system pass_filenames: false - - repo: local - hooks: - - id: isort - name: isort - entry: ./activated.py isort - language: system - types: [python] - - repo: local - hooks: - - id: flake8 - name: Flake8 - entry: ./activated.py flake8 - language: system - types: [python] - repo: local hooks: - id: ruff diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 40a501a3f153..d570b7319cf6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -57,15 +57,13 @@ to configure how the tests are run. For example, for more logging: change the lo ```bash sh install.sh -d . ./activate -black . && isort benchmarks build_scripts chia tests tools *.py && mypy && flake8 benchmarks build_scripts chia tests tools *.py && pylint benchmarks build_scripts chia tests tools *.py +black . && ruff check --fix && mypy && pylint benchmarks build_scripts chia tests tools *.py py.test tests -v --durations 0 ``` The [black library](https://black.readthedocs.io/en/stable/) is used as an automatic style formatter to make things easier. -The [flake8 library](https://readthedocs.org/projects/flake8/) helps ensure consistent style. The [Mypy library](https://mypy.readthedocs.io/en/stable/) is very useful for ensuring objects are of the correct type, so try to always add the type of the return value, and the type of local variables. -The [isort library](https://isort.readthedocs.io) is used to sort, group and validate imports in all python files. -The [Ruff library](https://docs.astral.sh) is used to further lint all of the python files +The [Ruff library](https://docs.astral.sh) is used to sort, group, validate imports, ensure consistent style, and further lint all of the python files If you want verbose logging for tests, edit the `tests/pytest.ini` file. @@ -84,10 +82,9 @@ provided configuration with `pre-commit install`. 1. Install python extension 2. Set the environment to `./venv/bin/python` 3. Install mypy plugin -4. Preferences > Settings > Python > Linting > flake8 enabled -5. Preferences > Settings > Python > Linting > mypy enabled -6. Preferences > Settings > Formatting > Python > Provider > black -7. Preferences > Settings > mypy > Targets: set to `./chia` +4. Preferences > Settings > Python > Linting > mypy enabled +5. Preferences > Settings > Formatting > Python > Provider > black +6. Preferences > Settings > mypy > Targets: set to `./chia` ## Configure Pycharm diff --git a/Install.ps1 b/Install.ps1 index 051f48cd3198..0d2e40c5653f 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -102,7 +102,11 @@ foreach ($extra in $extras) $extras_cli += $extra } -./Setup-poetry.ps1 -pythonVersion "$pythonVersion" +if (-not (Get-Item -ErrorAction SilentlyContinue ".penv/Scripts/poetry.exe").Exists) +{ + ./Setup-poetry.ps1 -pythonVersion "$pythonVersion" +} + .penv/Scripts/poetry env use $(py -"$pythonVersion" -c 'import sys; print(sys.executable)') .penv/Scripts/poetry install @extras_cli diff --git a/benchmarks/block_ref.py b/benchmarks/block_ref.py index 1b7b35520e69..3a3f29f1289b 100644 --- a/benchmarks/block_ref.py +++ b/benchmarks/block_ref.py @@ -86,7 +86,7 @@ async def main(db_path: Path) -> None: timing += one_call assert gen is not None - print(f"get_block_generator(): {timing/REPETITIONS:0.3f}s") + print(f"get_block_generator(): {timing / REPETITIONS:0.3f}s") blockchain.shut_down() diff --git a/benchmarks/block_store.py b/benchmarks/block_store.py index 8e60a1ba9944..19b4b5b66be4 100644 --- a/benchmarks/block_store.py +++ b/benchmarks/block_store.py @@ -447,7 +447,7 @@ async def run_add_block_benchmark(version: int) -> None: print("profiling get_block_records_close_to_peak") start = monotonic() - block_dict, peak_h = await block_store.get_block_records_close_to_peak(99) + block_dict, _peak_h = await block_store.get_block_records_close_to_peak(99) assert len(block_dict) == 100 stop = monotonic() @@ -490,7 +490,7 @@ async def run_add_block_benchmark(version: int) -> None: print(f"all tests completed in {all_test_time:0.4f}s") db_size = os.path.getsize(Path("block-store-benchmark.db")) - print(f"database size: {db_size/1000000:.3f} MB") + print(f"database size: {db_size / 1000000:.3f} MB") if __name__ == "__main__": diff --git a/benchmarks/coin_store.py b/benchmarks/coin_store.py index cec13c9f22a3..43946cb7f913 100644 --- a/benchmarks/coin_store.py +++ b/benchmarks/coin_store.py @@ -293,14 +293,14 @@ async def run_new_block_benchmark(version: int) -> None: if verbose: print("") print( - f"{total_time:0.4f}s, GET COINS REMOVED AT HEIGHT {block_height-1} blocks, " + f"{total_time:0.4f}s, GET COINS REMOVED AT HEIGHT {block_height - 1} blocks, " f"found {found_coins} coins in total" ) all_test_time += total_time print(f"all tests completed in {all_test_time:0.4f}s") db_size = os.path.getsize(Path("coin-store-benchmark.db")) - print(f"database size: {db_size/1000000:.3f} MB") + print(f"database size: {db_size / 1000000:.3f} MB") if __name__ == "__main__": diff --git a/build_scripts/check_dependency_artifacts.py b/build_scripts/check_dependency_artifacts.py index a751e09be9de..408970b64989 100644 --- a/build_scripts/check_dependency_artifacts.py +++ b/build_scripts/check_dependency_artifacts.py @@ -24,7 +24,7 @@ def excepted(path: pathlib.Path) -> bool: # TODO: This should be implemented with a real file name parser though i'm # uncertain at the moment what package that would be. - name, dash, rest = path.name.partition("-") + name, _dash, _rest = path.name.partition("-") return name in excepted_packages diff --git a/chia/_tests/blockchain/test_blockchain.py b/chia/_tests/blockchain/test_blockchain.py index 51aab5cd9924..b3ab921830b8 100644 --- a/chia/_tests/blockchain/test_blockchain.py +++ b/chia/_tests/blockchain/test_blockchain.py @@ -77,7 +77,7 @@ async def make_empty_blockchain(constants: ConsensusConstants) -> AsyncIterator[ Provides a list of 10 valid blocks, as well as a blockchain with 9 blocks added to it. """ - async with create_blockchain(constants, 2) as (bc, db_wrapper): + async with create_blockchain(constants, 2) as (bc, _): yield bc @@ -606,7 +606,7 @@ async def do_test_invalid_icc_sub_slot_vdf( ), keychain=keychain, ) - async with create_blockchain(bt_high_iters.constants, db_version) as (bc1, db_wrapper): + async with create_blockchain(bt_high_iters.constants, db_version) as (bc1, _): blocks = bt_high_iters.get_consecutive_blocks(10) for block in blocks: if ( @@ -1850,8 +1850,8 @@ async def test_pre_validation( ) end = time.time() log.info(f"Total time: {end - start} seconds") - log.info(f"Average pv: {sum(times_pv)/(len(blocks)/n_at_a_time)}") - log.info(f"Average rb: {sum(times_rb)/(len(blocks))}") + log.info(f"Average pv: {sum(times_pv) / (len(blocks) / n_at_a_time)}") + log.info(f"Average rb: {sum(times_rb) / (len(blocks))}") class TestBodyValidation: @@ -2775,7 +2775,7 @@ async def test_invalid_cost_in_block( block_generator, max_cost, mempool_mode=False, height=softfork_height, constants=bt.constants ) fork_info = ForkInfo(block_2.height - 1, block_2.height - 1, block_2.prev_header_hash) - result, err, _ = await b.add_block( + _result, err, _ = await b.add_block( block_2, PreValidationResult(None, uint64(1), npc_result.conds, False, uint32(0)), None, diff --git a/chia/_tests/clvm/test_chialisp_deserialization.py b/chia/_tests/clvm/test_chialisp_deserialization.py index d42b2a9498c9..f497bf00668a 100644 --- a/chia/_tests/clvm/test_chialisp_deserialization.py +++ b/chia/_tests/clvm/test_chialisp_deserialization.py @@ -86,16 +86,16 @@ def test_deserialization_large_numbers(): def test_overflow_atoms(): b = hexstr_to_bytes(serialized_atom_overflow(0xFFFFFFFF)) with pytest.raises(Exception): - cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b]) + _cost, _output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b]) b = hexstr_to_bytes(serialized_atom_overflow(0x3FFFFFFFF)) with pytest.raises(Exception): - cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b]) + _cost, _output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b]) b = hexstr_to_bytes(serialized_atom_overflow(0xFFFFFFFFFF)) with pytest.raises(Exception): - cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b]) + _cost, _output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b]) b = hexstr_to_bytes(serialized_atom_overflow(0x1FFFFFFFFFF)) with pytest.raises(Exception): - cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b]) + _cost, _output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b]) diff --git a/chia/_tests/clvm/test_puzzles.py b/chia/_tests/clvm/test_puzzles.py index 1d23a68f8db9..0fa47062aa4d 100644 --- a/chia/_tests/clvm/test_puzzles.py +++ b/chia/_tests/clvm/test_puzzles.py @@ -28,7 +28,7 @@ T1 = CoinTimestamp(1, uint32(10000000)) T2 = CoinTimestamp(5, uint32(10003000)) -MAX_BLOCK_COST_CLVM = int(1e18) +MAX_BLOCK_COST_CLVM = 10**18 def secret_exponent_for_index(index: int) -> int: @@ -206,7 +206,7 @@ def test_p2_delegated_puzzle_or_hidden_puzzle_with_hidden_puzzle(): def do_test_spend_p2_delegated_puzzle_or_hidden_puzzle_with_delegated_puzzle(hidden_pub_key_index): key_lookup = KeyTool() - payments, conditions = default_payments_and_conditions(1, key_lookup) + _payments, conditions = default_payments_and_conditions(1, key_lookup) hidden_puzzle = p2_conditions.puzzle_for_conditions(conditions) hidden_public_key = public_key_for_index(hidden_pub_key_index, key_lookup) diff --git a/chia/_tests/clvm/test_singletons.py b/chia/_tests/clvm/test_singletons.py index c2f418156341..5d6a876b60c7 100644 --- a/chia/_tests/clvm/test_singletons.py +++ b/chia/_tests/clvm/test_singletons.py @@ -69,7 +69,7 @@ async def make_and_spend_bundle( spend_bundle = cost_logger.add_cost(cost_log_msg, spend_bundle) try: - result, error = await sim_client.push_tx(spend_bundle) + _result, error = await sim_client.push_tx(spend_bundle) if error is None: await sim.farm_block() elif ex_error is not None: @@ -334,7 +334,7 @@ async def test_singleton_top_layer(version, cost_logger): DELAY_TIME, DELAY_PH, ) - result, error = await sim_client.push_tx(SpendBundle([to_delay_ph_coinsol], G2Element())) + _result, error = await sim_client.push_tx(SpendBundle([to_delay_ph_coinsol], G2Element())) assert error == Err.ASSERT_SECONDS_RELATIVE_FAILED # SPEND TO DELAYED PUZZLE HASH diff --git a/chia/_tests/clvm/test_spend_sim.py b/chia/_tests/clvm/test_spend_sim.py index ea7b9a08b367..1deb89fe8eca 100644 --- a/chia/_tests/clvm/test_spend_sim.py +++ b/chia/_tests/clvm/test_spend_sim.py @@ -150,7 +150,7 @@ async def test_all_endpoints(): ], G2Element(), ) - result, error = await sim_client.push_tx(bundle) + _result, error = await sim_client.push_tx(bundle) assert not error # get_all_mempool_tx_ids mempool_items = await sim_client.get_all_mempool_tx_ids() diff --git a/chia/_tests/cmds/test_click_types.py b/chia/_tests/cmds/test_click_types.py index 3b3222a974ba..7b46aca19c5d 100644 --- a/chia/_tests/cmds/test_click_types.py +++ b/chia/_tests/cmds/test_click_types.py @@ -67,7 +67,7 @@ def test_click_tx_fee_type() -> None: TransactionFeeParamType().convert(overflow_decimal_str, None, None) # Test Type Failures with pytest.raises(BadParameter): - TransactionFeeParamType().convert(float(0.01), None, None) + TransactionFeeParamType().convert(0.01, None, None) def test_click_amount_type() -> None: @@ -139,7 +139,7 @@ def test_click_address_type() -> None: AddressParamType().convert(burn_bad_prefix, None, None) # Test Type Failures with pytest.raises(BadParameter): - AddressParamType().convert(float(0.01), None, None) + AddressParamType().convert(0.01, None, None) # check class error handling with pytest.raises(ValueError): @@ -170,7 +170,7 @@ def test_click_bytes32_type() -> None: Bytes32ParamType().convert("test", None, None) # Test Type Failures with pytest.raises(BadParameter): - Bytes32ParamType().convert(float(0.01), None, None) + Bytes32ParamType().convert(0.01, None, None) def test_click_uint64_type() -> None: @@ -192,4 +192,4 @@ def test_click_uint64_type() -> None: Uint64ParamType().convert(str(overflow_ammt), None, None) # Test Type Failures with pytest.raises(BadParameter): - Uint64ParamType().convert(float(0.01), None, None) + Uint64ParamType().convert(0.01, None, None) diff --git a/chia/_tests/cmds/test_cmds_util.py b/chia/_tests/cmds/test_cmds_util.py index 114316e99ec9..ea16cb427faf 100644 --- a/chia/_tests/cmds/test_cmds_util.py +++ b/chia/_tests/cmds/test_cmds_util.py @@ -44,7 +44,7 @@ async def test_failure_output_no_traceback( ) as (client, _): await client.fetch(path="/table", request_json={"response": expected_response}) - out, err = capsys.readouterr() + out, _err = capsys.readouterr() assert "ResponseFailureError" not in out assert "Traceback:" not in out @@ -69,7 +69,7 @@ async def test_failure_output_with_traceback( ) as (client, _): await client.fetch(path="/table", request_json={"response": expected_response}) - out, err = capsys.readouterr() + out, _err = capsys.readouterr() assert sample_traceback_json not in out assert sample_traceback in out diff --git a/chia/_tests/conftest.py b/chia/_tests/conftest.py index 010d93ccdfc2..c643d4ac3900 100644 --- a/chia/_tests/conftest.py +++ b/chia/_tests/conftest.py @@ -1,8 +1,7 @@ -# flake8: noqa E402 # See imports after multiprocessing.set_start_method +# ruff: noqa: E402 # See imports after multiprocessing.set_start_method from __future__ import annotations import asyncio -import dataclasses import datetime import functools import json @@ -24,7 +23,6 @@ from _pytest.fixtures import SubRequest from pytest import MonkeyPatch -import chia._tests from chia._tests import ether from chia._tests.core.data_layer.util import ChiaRoot from chia._tests.core.node_height import node_height_at_least @@ -50,13 +48,10 @@ from chia._tests.util.spend_sim import CostLogger from chia._tests.util.time_out_assert import time_out_assert from chia.consensus.constants import ConsensusConstants -from chia.full_node.full_node import FullNode from chia.full_node.full_node_api import FullNodeAPI from chia.rpc.farmer_rpc_client import FarmerRpcClient from chia.rpc.harvester_rpc_client import HarvesterRpcClient from chia.rpc.wallet_rpc_client import WalletRpcClient -from chia.seeder.crawler import Crawler -from chia.seeder.crawler_api import CrawlerAPI from chia.seeder.dns_server import DNSServer from chia.server.server import ChiaServer from chia.server.start_service import Service @@ -71,13 +66,10 @@ ) from chia.simulator.start_simulator import SimulatorFullNodeService from chia.simulator.wallet_tools import WalletTool -from chia.timelord.timelord import Timelord -from chia.timelord.timelord_api import TimelordAPI # Set spawn after stdlib imports, but before other imports from chia.types.aliases import ( CrawlerService, - DataLayerService, FarmerService, FullNodeService, HarvesterService, @@ -92,7 +84,6 @@ from chia.util.task_timing import main as task_instrumentation_main from chia.util.task_timing import start_task_instrumentation, stop_task_instrumentation from chia.wallet.wallet_node import WalletNode -from chia.wallet.wallet_node_api import WalletNodeAPI multiprocessing.set_start_method("spawn") @@ -256,7 +247,7 @@ async def empty_blockchain(latest_db_version, blockchain_constants): """ from chia._tests.util.blockchain import create_blockchain - async with create_blockchain(blockchain_constants, latest_db_version) as (bc1, db_wrapper): + async with create_blockchain(blockchain_constants, latest_db_version) as (bc1, _): yield bc1 @@ -639,13 +630,12 @@ async def five_nodes(db_version: int, self_hostname, blockchain_constants): @pytest.fixture(scope="function") async def wallet_nodes(blockchain_constants, consensus_mode): - constants = blockchain_constants async with setup_simulators_and_wallets( 2, 1, blockchain_constants.replace(MEMPOOL_BLOCK_BUFFER=1, MAX_BLOCK_COST_CLVM=400000000), ) as new: - (nodes, wallets, bt) = make_old_setup_simulators_and_wallets(new=new) + (nodes, _wallets, bt) = make_old_setup_simulators_and_wallets(new=new) full_node_1 = nodes[0] full_node_2 = nodes[1] server_1 = full_node_1.full_node.server @@ -765,7 +755,7 @@ async def wallet_nodes_perf(blockchain_constants: ConsensusConstants): async with setup_simulators_and_wallets( 1, 1, blockchain_constants, config_overrides={"MEMPOOL_BLOCK_BUFFER": 1, "MAX_BLOCK_COST_CLVM": 11000000000} ) as new: - (nodes, wallets, bt) = make_old_setup_simulators_and_wallets(new=new) + (nodes, _wallets, bt) = make_old_setup_simulators_and_wallets(new=new) full_node_1 = nodes[0] server_1 = full_node_1.full_node.server wallet_a = bt.get_pool_wallet_tool() diff --git a/chia/_tests/connection_utils.py b/chia/_tests/connection_utils.py index ae124b218323..56d4c45915a8 100644 --- a/chia/_tests/connection_utils.py +++ b/chia/_tests/connection_utils.py @@ -10,6 +10,7 @@ from cryptography.hazmat.primitives import hashes, serialization from chia._tests.util.time_out_assert import time_out_assert +from chia.apis import ApiProtocolRegistry from chia.protocols.shared_protocol import default_capabilities from chia.server.outbound_message import NodeType from chia.server.server import ChiaServer, ssl_context_for_client @@ -97,6 +98,7 @@ async def add_dummy_connection_wsc( 100, 30, local_capabilities_for_handshake=default_capabilities[type] + additional_capabilities, + class_for_type=ApiProtocolRegistry, ) await wsc.perform_handshake(server._network_id, dummy_port, type) if wsc.incoming_message_task is not None: diff --git a/chia/_tests/core/daemon/test_daemon.py b/chia/_tests/core/daemon/test_daemon.py index a1a77be6b82f..e5d9033a0ed6 100644 --- a/chia/_tests/core/daemon/test_daemon.py +++ b/chia/_tests/core/daemon/test_daemon.py @@ -1035,7 +1035,7 @@ async def test_add_private_key(daemon_connection_and_temp_keychain): @pytest.mark.anyio async def test_add_private_key_label(daemon_connection_and_temp_keychain): - ws, keychain = daemon_connection_and_temp_keychain + ws, _keychain = daemon_connection_and_temp_keychain async def assert_add_private_key_with_label( key_data: KeyData, request: dict[str, object], add_private_key_response: dict[str, object] @@ -1763,7 +1763,7 @@ async def test_keyring_file_deleted( async def test_plotter_errors( daemon_connection_and_temp_keychain: tuple[aiohttp.ClientWebSocketResponse, Keychain], case: RouteCase ) -> None: - ws, keychain = daemon_connection_and_temp_keychain + ws, _keychain = daemon_connection_and_temp_keychain payload = create_payload( case.route, @@ -1878,7 +1878,7 @@ async def test_plotter_options( get_b_tools: BlockTools, case: RouteCase, ) -> None: - ws, keychain = daemon_connection_and_temp_keychain + ws, _keychain = daemon_connection_and_temp_keychain # register for chia_plotter events service_name = "chia_plotter" @@ -1942,7 +1942,7 @@ def check_plot_queue_log( async def test_plotter_roundtrip( daemon_connection_and_temp_keychain: tuple[aiohttp.ClientWebSocketResponse, Keychain], get_b_tools: BlockTools ) -> None: - ws, keychain = daemon_connection_and_temp_keychain + ws, _keychain = daemon_connection_and_temp_keychain # register for chia_plotter events service_name = "chia_plotter" @@ -2014,7 +2014,7 @@ async def test_plotter_roundtrip( async def test_plotter_stop_plotting( daemon_connection_and_temp_keychain: tuple[aiohttp.ClientWebSocketResponse, Keychain], get_b_tools: BlockTools ) -> None: - ws, keychain = daemon_connection_and_temp_keychain + ws, _keychain = daemon_connection_and_temp_keychain # register for chia_plotter events service_name = "chia_plotter" diff --git a/chia/_tests/core/data_layer/test_data_rpc.py b/chia/_tests/core/data_layer/test_data_rpc.py index 8f76c5227105..a79c2e483571 100644 --- a/chia/_tests/core/data_layer/test_data_rpc.py +++ b/chia/_tests/core/data_layer/test_data_rpc.py @@ -2054,7 +2054,7 @@ async def test_clear_pending_roots( layer: InterfaceLayer, bt: BlockTools, ) -> None: - wallet_rpc_api, full_node_api, wallet_rpc_port, ph, bt = await init_wallet_and_node( + _wallet_rpc_api, _full_node_api, wallet_rpc_port, _ph, bt = await init_wallet_and_node( self_hostname, one_wallet_and_one_simulator_services ) async with init_data_layer_service(wallet_rpc_port=wallet_rpc_port, bt=bt, db_path=tmp_path) as data_layer_service: @@ -2147,7 +2147,7 @@ async def test_clear_pending_roots( async def test_issue_15955_deadlock( self_hostname: str, one_wallet_and_one_simulator_services: SimulatorsAndWalletsServices, tmp_path: Path ) -> None: - wallet_rpc_api, full_node_api, wallet_rpc_port, ph, bt = await init_wallet_and_node( + wallet_rpc_api, full_node_api, wallet_rpc_port, _ph, bt = await init_wallet_and_node( self_hostname, one_wallet_and_one_simulator_services ) @@ -2366,7 +2366,7 @@ async def test_wallet_log_in_changes_active_fingerprint( one_wallet_and_one_simulator_services: SimulatorsAndWalletsServices, layer: InterfaceLayer, ) -> None: - wallet_rpc_api, full_node_api, wallet_rpc_port, ph, bt = await init_wallet_and_node( + wallet_rpc_api, _full_node_api, wallet_rpc_port, _ph, bt = await init_wallet_and_node( self_hostname, one_wallet_and_one_simulator_services ) primary_fingerprint = cast(int, (await wallet_rpc_api.get_logged_in_fingerprint(request={}))["fingerprint"]) @@ -3789,7 +3789,7 @@ async def test_auto_subscribe_to_local_stores( monkeypatch: Any, auto_subscribe_to_local_stores: bool, ) -> None: - wallet_rpc_api, full_node_api, wallet_rpc_port, ph, bt = await init_wallet_and_node( + _wallet_rpc_api, _full_node_api, wallet_rpc_port, _ph, bt = await init_wallet_and_node( self_hostname, one_wallet_and_one_simulator_services ) manage_data_interval = 5 @@ -3838,7 +3838,7 @@ async def test_local_store_exception( monkeypatch: Any, caplog: pytest.LogCaptureFixture, ) -> None: - wallet_rpc_api, full_node_api, wallet_rpc_port, ph, bt = await init_wallet_and_node( + _wallet_rpc_api, _full_node_api, wallet_rpc_port, _ph, bt = await init_wallet_and_node( self_hostname, one_wallet_and_one_simulator_services ) manage_data_interval = 5 diff --git a/chia/_tests/core/farmer/test_farmer_api.py b/chia/_tests/core/farmer/test_farmer_api.py index d05defe5fc36..57741c4d0825 100644 --- a/chia/_tests/core/farmer/test_farmer_api.py +++ b/chia/_tests/core/farmer/test_farmer_api.py @@ -39,7 +39,7 @@ async def test_farmer_ignores_concurrent_duplicate_signage_points( _, farmer_service, _ = farmer_one_harvester farmer_api: FarmerAPI = farmer_service._api farmer_server = farmer_service._server - incoming_queue, peer_id = await add_dummy_connection(farmer_server, self_hostname, 12312, NodeType.HARVESTER) + incoming_queue, _peer_id = await add_dummy_connection(farmer_server, self_hostname, 12312, NodeType.HARVESTER) # Consume the handshake response = (await incoming_queue.get()).type assert ProtocolMessageTypes(response).name == "harvester_handshake" diff --git a/chia/_tests/core/full_node/full_sync/test_full_sync.py b/chia/_tests/core/full_node/full_sync/test_full_sync.py index dff1924d47a3..2f1ed2f864fe 100644 --- a/chia/_tests/core/full_node/full_sync/test_full_sync.py +++ b/chia/_tests/core/full_node/full_sync/test_full_sync.py @@ -1,14 +1,11 @@ -# flake8: noqa: F811, F401 from __future__ import annotations import asyncio -import dataclasses import logging import time import pytest -from chia._tests.conftest import ConsensusMode from chia._tests.core.node_height import node_height_between, node_height_exactly from chia._tests.util.time_out_assert import time_out_assert from chia.full_node.full_node import FullNode @@ -116,7 +113,6 @@ async def test_long_sync_from_zero(self, five_nodes, default_400_blocks, bt, sel async def test_sync_from_fork_point_and_weight_proof( self, three_nodes, default_1000_blocks, default_400_blocks, self_hostname ): - start = time.time() # Must be larger than "sync_block_behind_threshold" in the config num_blocks_initial = len(default_1000_blocks) - 50 blocks_950 = default_1000_blocks[:num_blocks_initial] @@ -419,7 +415,7 @@ async def test_sync_none_wp_response_backward_comp(self, three_nodes, default_10 async def test_bad_peak_cache_invalidation( self, two_nodes, default_1000_blocks, blockchain_constants, consensus_mode ): - full_node_1, full_node_2, server_1, server_2, bt = two_nodes + full_node_1, _full_node_2, _server_1, _server_2, bt = two_nodes for block in default_1000_blocks[:-500]: await full_node_1.full_node.add_block(block) diff --git a/chia/_tests/core/full_node/stores/test_full_node_store.py b/chia/_tests/core/full_node/stores/test_full_node_store.py index dbb0a8a0eacb..be9fe45961d0 100644 --- a/chia/_tests/core/full_node/stores/test_full_node_store.py +++ b/chia/_tests/core/full_node/stores/test_full_node_store.py @@ -50,7 +50,7 @@ async def empty_blockchain(db_version: int, blockchain_constants: ConsensusConst DISCRIMINANT_SIZE_BITS=uint16(32), SUB_SLOT_ITERS_STARTING=uint64(2**12), ) - async with create_blockchain(patched_constants, db_version) as (bc1, db_wrapper): + async with create_blockchain(patched_constants, db_version) as (bc1, _): yield bc1 @@ -58,7 +58,7 @@ async def empty_blockchain(db_version: int, blockchain_constants: ConsensusConst async def empty_blockchain_with_original_constants( db_version: int, blockchain_constants: ConsensusConstants ) -> AsyncIterator[Blockchain]: - async with create_blockchain(blockchain_constants, db_version) as (bc1, db_wrapper): + async with create_blockchain(blockchain_constants, db_version) as (bc1, _): yield bc1 @@ -151,7 +151,7 @@ async def test_find_best_block( else: result[bytes32(b.to_bytes(1, "big") * 32)] = UnfinishedBlockEntry(unf, None, uint32(123)) - foliage_hash, block = find_best_block(result) + foliage_hash, _block = find_best_block(result) if expected is None: assert foliage_hash is None else: diff --git a/chia/_tests/core/full_node/stores/test_hint_store.py b/chia/_tests/core/full_node/stores/test_hint_store.py index 33d831975107..b13cadf8a5c8 100644 --- a/chia/_tests/core/full_node/stores/test_hint_store.py +++ b/chia/_tests/core/full_node/stores/test_hint_store.py @@ -144,7 +144,7 @@ async def test_hints_in_blockchain( FullNodeSimulator, FullNodeSimulator, ChiaServer, ChiaServer, WalletTool, WalletTool, BlockTools ], ) -> None: - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, _server_1, _server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes blocks = bt.get_consecutive_blocks( 5, diff --git a/chia/_tests/core/full_node/test_address_manager.py b/chia/_tests/core/full_node/test_address_manager.py index d0d58e9abc29..09bc29c96ae8 100644 --- a/chia/_tests/core/full_node/test_address_manager.py +++ b/chia/_tests/core/full_node/test_address_manager.py @@ -238,7 +238,7 @@ async def test_addrman_create(self): peer1 = PeerInfo("250.1.2.1", 8444) t_peer = TimestampedPeerInfo("250.1.2.1", 8444, 0) - info, node_id = addrman.create_(t_peer, peer1) + info, _node_id = addrman.create_(t_peer, peer1) assert info.peer_info == peer1 info, _ = addrman.find_(peer1) assert info.peer_info == peer1 @@ -250,7 +250,7 @@ async def test_addrman_delete(self): peer1 = PeerInfo("250.1.2.1", 8444) t_peer = TimestampedPeerInfo("250.1.2.1", 8444, 0) - info, node_id = addrman.create_(t_peer, peer1) + _info, node_id = addrman.create_(t_peer, peer1) # Test: Delete should actually delete the addr. assert await addrman.size() == 1 diff --git a/chia/_tests/core/full_node/test_conditions.py b/chia/_tests/core/full_node/test_conditions.py index b6d8c44bb51e..9f220a14a956 100644 --- a/chia/_tests/core/full_node/test_conditions.py +++ b/chia/_tests/core/full_node/test_conditions.py @@ -70,7 +70,7 @@ async def check_spend_bundle_validity( or fails with the correct error code. """ - async with create_ram_blockchain(bt.constants) as (db_wrapper, blockchain): + async with create_ram_blockchain(bt.constants) as (_, blockchain): for block in blocks: await _validate_and_add_block(blockchain, block) @@ -142,7 +142,7 @@ async def test_unknown_conditions_with_cost( self, opcode: int, expected_cost: int, bt: BlockTools, consensus_mode: ConsensusMode ) -> None: conditions = Program.to(assemble(f"(({opcode} 1337))")) - additions, removals, new_block = await check_conditions(bt, conditions) + _additions, _removals, new_block = await check_conditions(bt, conditions) # once the hard fork activates, blocks no longer pay the cost of the ROM # generator (which includes hashing all puzzles). @@ -165,7 +165,7 @@ async def test_softfork_condition( self, condition: str, expected_cost: int, bt: BlockTools, consensus_mode: ConsensusMode ) -> None: conditions = Program.to(assemble(condition)) - additions, removals, new_block = await check_conditions(bt, conditions) + _additions, _removals, new_block = await check_conditions(bt, conditions) if consensus_mode < ConsensusMode.HARD_FORK_2_0: block_base_cost = 737056 diff --git a/chia/_tests/core/full_node/test_full_node.py b/chia/_tests/core/full_node/test_full_node.py index b1a357839b92..81f1479a38c9 100644 --- a/chia/_tests/core/full_node/test_full_node.py +++ b/chia/_tests/core/full_node/test_full_node.py @@ -30,9 +30,8 @@ from chia.full_node.full_node_api import FullNodeAPI from chia.full_node.signage_point import SignagePoint from chia.full_node.sync_store import Peak -from chia.protocols import full_node_protocol +from chia.protocols import full_node_protocol, timelord_protocol, wallet_protocol from chia.protocols import full_node_protocol as fnp -from chia.protocols import timelord_protocol, wallet_protocol from chia.protocols.full_node_protocol import RespondTransaction from chia.protocols.protocol_message_types import ProtocolMessageTypes from chia.protocols.shared_protocol import Capability, default_capabilities @@ -121,7 +120,7 @@ async def test_sync_no_farmer( self_hostname: str, seeded_random: random.Random, ): - nodes, wallets, bt = setup_two_nodes_and_wallet + nodes, _wallets, _bt = setup_two_nodes_and_wallet server_1 = nodes[0].full_node.server server_2 = nodes[1].full_node.server full_node_1 = nodes[0] @@ -486,7 +485,7 @@ async def test_inbound_connection_limit(self, setup_four_nodes, self_hostname): @pytest.mark.anyio async def test_request_peers(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, _ = wallet_nodes + full_node_1, full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, _ = wallet_nodes full_node_2.full_node.full_node_peers.address_manager.make_private_subnets_valid() await server_2.start_client(PeerInfo(self_hostname, server_1.get_port())) @@ -507,7 +506,7 @@ async def have_msgs(): @pytest.mark.anyio async def test_basic_chain(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes incoming_queue, _ = await add_dummy_connection(server_1, self_hostname, 12312) expected_requests = 0 @@ -530,9 +529,9 @@ async def test_basic_chain(self, wallet_nodes, self_hostname): @pytest.mark.anyio async def test_respond_end_of_sub_slot(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes - incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) + incoming_queue, _dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) expected_requests = 0 if await full_node_1.full_node.synced(): expected_requests = 1 @@ -588,9 +587,9 @@ async def test_respond_end_of_sub_slot(self, wallet_nodes, self_hostname): @pytest.mark.anyio async def test_respond_end_of_sub_slot_no_reorg(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes - incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) + incoming_queue, _dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) expected_requests = 0 if await full_node_1.full_node.synced(): expected_requests = 1 @@ -625,9 +624,9 @@ async def test_respond_end_of_sub_slot_no_reorg(self, wallet_nodes, self_hostnam @pytest.mark.anyio async def test_respond_end_of_sub_slot_race(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes - incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) + incoming_queue, _dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) expected_requests = 0 if await full_node_1.full_node.synced(): expected_requests = 1 @@ -655,9 +654,9 @@ async def test_respond_end_of_sub_slot_race(self, wallet_nodes, self_hostname): @pytest.mark.anyio async def test_respond_unfinished(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes - incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) + incoming_queue, _dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) expected_requests = 0 if await full_node_1.full_node.synced(): expected_requests = 1 @@ -758,7 +757,7 @@ async def test_respond_unfinished(self, wallet_nodes, self_hostname): @pytest.mark.anyio async def test_new_peak(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) dummy_peer = server_1.all_connections[dummy_node_id] @@ -1012,7 +1011,7 @@ async def test_request_respond_transaction(self, wallet_nodes, self_hostname, se pool_reward_puzzle_hash=wallet_ph, ) - incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) + incoming_queue, _dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) peer = await connect_and_get_peer(server_1, server_2, self_hostname) @@ -1048,11 +1047,11 @@ async def test_request_respond_transaction(self, wallet_nodes, self_hostname, se @pytest.mark.anyio async def test_respond_transaction_fail(self, wallet_nodes, self_hostname, seeded_random: random.Random): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() cb_ph = wallet_a.get_new_puzzlehash() - incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) + incoming_queue, _dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12312) peer = await connect_and_get_peer(server_1, server_2, self_hostname) tx_id = bytes32.random(seeded_random) @@ -1095,7 +1094,7 @@ async def test_respond_transaction_fail(self, wallet_nodes, self_hostname, seede @pytest.mark.anyio async def test_request_block(self, wallet_nodes): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, _server_1, _server_2, wallet_a, wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() blocks = bt.get_consecutive_blocks( @@ -1137,7 +1136,7 @@ async def test_request_block(self, wallet_nodes): @pytest.mark.anyio async def test_request_blocks(self, wallet_nodes): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, _server_1, _server_2, wallet_a, wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() # create more blocks than constants.MAX_BLOCK_COUNT_PER_REQUEST (32) @@ -1200,7 +1199,7 @@ async def test_request_blocks(self, wallet_nodes): @pytest.mark.parametrize("peer_version", ["0.0.35", "0.0.36"]) @pytest.mark.parametrize("requesting", [0, 1, 2]) async def test_new_unfinished_block(self, wallet_nodes, peer_version: str, requesting: int, self_hostname: str): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() peer = await connect_and_get_peer(server_1, server_2, self_hostname) @@ -1256,7 +1255,7 @@ async def test_new_unfinished_block(self, wallet_nodes, peer_version: str, reque @pytest.mark.anyio @pytest.mark.parametrize("requesting", [0, 1, 2]) async def test_new_unfinished_block2(self, wallet_nodes, requesting: int, self_hostname: str): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() peer = await connect_and_get_peer(server_1, server_2, self_hostname) @@ -1295,7 +1294,7 @@ async def test_new_unfinished_block2(self, wallet_nodes, requesting: int, self_h @pytest.mark.anyio async def test_new_unfinished_block2_forward_limit(self, wallet_nodes, self_hostname: str): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes blocks = bt.get_consecutive_blocks(3, guarantee_transaction_block=True) for block in blocks: await full_node_1.full_node.add_block(block) @@ -1368,7 +1367,7 @@ def sort_key(b: UnfinishedBlock) -> bytes32: ], ) async def test_unfinished_block_with_replaced_generator(self, wallet_nodes, self_hostname, committment, expected): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() peer = await connect_and_get_peer(server_1, server_2, self_hostname) @@ -1546,7 +1545,7 @@ async def test_double_blocks_same_pospace(self, wallet_nodes, self_hostname): @pytest.mark.anyio async def test_request_unfinished_block(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() peer = await connect_and_get_peer(server_1, server_2, self_hostname) blocks = bt.get_consecutive_blocks(10, block_list_input=blocks, seed=b"12345") @@ -1565,7 +1564,7 @@ async def test_request_unfinished_block(self, wallet_nodes, self_hostname): @pytest.mark.anyio async def test_request_unfinished_block2(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() blocks = bt.get_consecutive_blocks(3, guarantee_transaction_block=True) for block in blocks: @@ -1620,7 +1619,7 @@ async def test_request_unfinished_block2(self, wallet_nodes, self_hostname): @pytest.mark.anyio async def test_new_signage_point_or_end_of_sub_slot(self, wallet_nodes, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() blocks = bt.get_consecutive_blocks(3, block_list_input=blocks, skip_slots=2) @@ -1662,7 +1661,7 @@ async def test_new_signage_point_or_end_of_sub_slot(self, wallet_nodes, self_hos await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer) assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots - 1 - incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12315) + _incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12315) dummy_peer = server_1.all_connections[dummy_node_id] await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slots[-1]), dummy_peer) @@ -1675,7 +1674,7 @@ def caught_up_slots(): @pytest.mark.anyio async def test_new_signage_point_caching(self, wallet_nodes, empty_blockchain, self_hostname): - full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver, bt = wallet_nodes + full_node_1, _full_node_2, server_1, server_2, _wallet_a, _wallet_receiver, bt = wallet_nodes blocks = await full_node_1.get_all_full_blocks() peer = await connect_and_get_peer(server_1, server_2, self_hostname) @@ -1750,7 +1749,7 @@ async def test_slot_catch_up_genesis(self, setup_two_nodes_fixture, self_hostnam await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer) assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots - 1 - incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12315) + _incoming_queue, dummy_node_id = await add_dummy_connection(server_1, self_hostname, 12315) dummy_peer = server_1.all_connections[dummy_node_id] await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slots[-1]), dummy_peer) @@ -2187,11 +2186,11 @@ async def test_invalid_capability_can_connect( # TODO: consider not testing this against both DB v1 and v2? [ - initiating_full_node_api, - listening_full_node_api, + _initiating_full_node_api, + _listening_full_node_api, initiating_server, listening_server, - bt, + _bt, ] = two_nodes initiating_server._local_capabilities_for_handshake = custom_capabilities @@ -2266,7 +2265,7 @@ async def test_long_reorg( test_long_reorg_1500_blocks_light: list[FullBlock], seeded_random: random.Random, ): - node, server, bt = one_node_one_block + node, _server, _bt = one_node_one_block fork_point = 1499 blocks = default_10000_blocks[:3000] diff --git a/chia/_tests/core/full_node/test_performance.py b/chia/_tests/core/full_node/test_performance.py index bc6d6e53e6ed..8dc2f924b45f 100644 --- a/chia/_tests/core/full_node/test_performance.py +++ b/chia/_tests/core/full_node/test_performance.py @@ -1,7 +1,5 @@ -# flake8: noqa: F811, F401 from __future__ import annotations -import dataclasses import logging import random @@ -60,7 +58,7 @@ async def test_full_block_performance( if full_node_1.full_node.blockchain.get_peak() is not None else -1 ) - incoming_queue, node_id = await add_dummy_connection(server_1, self_hostname, 12312) + _incoming_queue, node_id = await add_dummy_connection(server_1, self_hostname, 12312) fake_peer = server_1.all_connections[node_id] # Mempool has capacity of 100, make 110 unspents that we can use puzzle_hashes = [] diff --git a/chia/_tests/core/mempool/test_mempool.py b/chia/_tests/core/mempool/test_mempool.py index a6151d2fc260..72d334f9e072 100644 --- a/chia/_tests/core/mempool/test_mempool.py +++ b/chia/_tests/core/mempool/test_mempool.py @@ -307,7 +307,7 @@ class TestMempool: async def test_basic_mempool( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) @@ -396,7 +396,7 @@ async def test_basic_mempool_manager( wallet_a: WalletTool, self_hostname: str, ) -> None: - full_node_1, full_node_2, server_1, server_2, bt = two_nodes_one_block + full_node_1, _full_node_2, server_1, server_2, bt = two_nodes_one_block peer = await connect_and_get_peer(server_1, server_2, self_hostname) @@ -471,10 +471,10 @@ def test_fun(coin_1: Coin, coin_2: Coin) -> SpendBundle: bundle = SpendBundle.aggregate([tx1, tx2]) return bundle - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) - blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) + _blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) mempool_bundle = full_node_1.full_node.mempool_manager.get_spendbundle(bundle.name()) print(f"opcode={opcode} timelock_value={lock_value} expected={expected} status={status}") @@ -507,8 +507,8 @@ def test_fun(coin_1: Coin, coin_2: Coin) -> SpendBundle: bundle = SpendBundle.aggregate([spend_bundle1, spend_bundle2]) return bundle - full_node_1, server_1, bt = one_node_one_block - blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) + full_node_1, _server_1, _bt = one_node_one_block + _blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) mempool_bundle = full_node_1.full_node.mempool_manager.get_spendbundle(bundle.name()) assert err is None @@ -533,8 +533,8 @@ def test_fun(coin_1: Coin, coin_2: Coin) -> SpendBundle: bundle = SpendBundle.aggregate([spend_bundle1, spend_bundle2]) return bundle - full_node_1, server_1, bt = one_node_one_block - blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) + full_node_1, _server_1, _bt = one_node_one_block + _blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) mempool_bundle = full_node_1.full_node.mempool_manager.get_spendbundle(bundle.name()) assert err is None @@ -549,7 +549,7 @@ async def test_double_spend( self_hostname: str, ) -> None: reward_ph = wallet_a.get_new_puzzlehash() - full_node_1, full_node_2, server_1, server_2, bt = two_nodes_one_block + full_node_1, _full_node_2, server_1, server_2, bt = two_nodes_one_block blocks = await full_node_1.get_all_full_blocks() start_height = blocks[-1].height blocks = bt.get_consecutive_blocks( @@ -679,7 +679,7 @@ async def test_invalid_signature( ) -> None: reward_ph = wallet_a.get_new_puzzlehash() - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block blocks = await full_node_1.get_all_full_blocks() start_height = blocks[-1].height if len(blocks) > 0 else -1 blocks = bt.get_consecutive_blocks( @@ -797,7 +797,7 @@ async def condition_tester2( async def test_invalid_block_index( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block blocks = await full_node_1.get_all_full_blocks() start_height = blocks[-1].height cvp = ConditionWithArgs( @@ -805,7 +805,7 @@ async def test_invalid_block_index( [int_to_bytes(start_height + 5)], ) dic = {ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert sb1 is None # the transaction may become valid later @@ -816,10 +816,10 @@ async def test_invalid_block_index( async def test_block_index_missing_arg( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE, []) dic = {ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert sb1 is None # the transaction may become valid later @@ -830,10 +830,10 @@ async def test_block_index_missing_arg( async def test_correct_block_index( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE, [int_to_bytes(1)]) dic = {ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err is None assert sb1 == spend_bundle1 @@ -843,12 +843,12 @@ async def test_correct_block_index( async def test_block_index_garbage( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block # garbage at the end of the argument list is ignored in consensus mode, # but not in mempool-mode cvp = ConditionWithArgs(ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE, [int_to_bytes(1), b"garbage"]) dic = {ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err is Err.INVALID_CONDITION assert sb1 is None @@ -858,10 +858,10 @@ async def test_block_index_garbage( async def test_negative_block_index( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE, [int_to_bytes(-1)]) dic = {ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err is None assert sb1 == spend_bundle1 @@ -871,10 +871,10 @@ async def test_negative_block_index( async def test_invalid_block_age( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_HEIGHT_RELATIVE, [int_to_bytes(5)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err == Err.ASSERT_HEIGHT_RELATIVE_FAILED assert sb1 is None @@ -885,10 +885,10 @@ async def test_invalid_block_age( async def test_block_age_missing_arg( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_HEIGHT_RELATIVE, []) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err == Err.INVALID_CONDITION assert sb1 is None @@ -899,10 +899,10 @@ async def test_block_age_missing_arg( async def test_correct_block_age( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_HEIGHT_RELATIVE, [int_to_bytes(1)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, num_blocks=4 ) @@ -915,12 +915,12 @@ async def test_correct_block_age( async def test_block_age_garbage( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block # garbage at the end of the argument list is ignored in consensus mode, # but not in mempool mode cvp = ConditionWithArgs(ConditionOpcode.ASSERT_HEIGHT_RELATIVE, [int_to_bytes(1), b"garbage"]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, num_blocks=4 ) @@ -933,10 +933,10 @@ async def test_block_age_garbage( async def test_negative_block_age( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_HEIGHT_RELATIVE, [int_to_bytes(-1)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, num_blocks=4 ) @@ -949,14 +949,14 @@ async def test_negative_block_age( async def test_correct_my_id( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) coin = await next_block(full_node_1, wallet_a, bt) cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_COIN_ID, [coin.name()]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -969,7 +969,7 @@ async def test_correct_my_id( async def test_my_id_garbage( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) @@ -978,7 +978,7 @@ async def test_my_id_garbage( # but not in mempool mode cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_COIN_ID, [coin.name(), b"garbage"]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -991,7 +991,7 @@ async def test_my_id_garbage( async def test_invalid_my_id( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) @@ -999,7 +999,7 @@ async def test_invalid_my_id( coin_2 = await next_block(full_node_1, wallet_a, bt) cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_COIN_ID, [coin_2.name()]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -1012,10 +1012,10 @@ async def test_invalid_my_id( async def test_my_id_missing_arg( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_COIN_ID, []) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err == Err.INVALID_CONDITION @@ -1053,7 +1053,7 @@ async def test_assert_time_fail( cvp = ConditionWithArgs(ConditionOpcode.ASSERT_SECONDS_ABSOLUTE, [int_to_bytes(time_now)]) dic = {cvp.opcode: [cvp]} - _, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err == Err.ASSERT_SECONDS_ABSOLUTE_FAILED assert sb1 is None @@ -1080,12 +1080,12 @@ async def test_assert_height_pending( async def test_assert_time_negative( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block time_now = -1 cvp = ConditionWithArgs(ConditionOpcode.ASSERT_SECONDS_ABSOLUTE, [int_to_bytes(time_now)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err is None assert sb1 == spend_bundle1 @@ -1095,11 +1095,11 @@ async def test_assert_time_negative( async def test_assert_time_missing_arg( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_SECONDS_ABSOLUTE, []) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err == Err.INVALID_CONDITION assert sb1 is None @@ -1129,12 +1129,12 @@ async def test_assert_time_garbage( async def test_assert_time_relative_exceeds( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block time_relative = 3 cvp = ConditionWithArgs(ConditionOpcode.ASSERT_SECONDS_RELATIVE, [int_to_bytes(time_relative)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err == Err.ASSERT_SECONDS_RELATIVE_FAILED @@ -1157,14 +1157,14 @@ async def test_assert_time_relative_exceeds( async def test_assert_time_relative_garbage( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block time_relative = 0 # garbage at the end of the arguments is ignored in consensus mode, but # not in mempool mode cvp = ConditionWithArgs(ConditionOpcode.ASSERT_SECONDS_RELATIVE, [int_to_bytes(time_relative), b"garbage"]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err is Err.INVALID_CONDITION @@ -1175,11 +1175,11 @@ async def test_assert_time_relative_garbage( async def test_assert_time_relative_missing_arg( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_SECONDS_RELATIVE, []) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err == Err.INVALID_CONDITION @@ -1190,12 +1190,12 @@ async def test_assert_time_relative_missing_arg( async def test_assert_time_relative_negative( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block time_relative = -3 cvp = ConditionWithArgs(ConditionOpcode.ASSERT_SECONDS_RELATIVE, [int_to_bytes(time_relative)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err is None @@ -1219,8 +1219,8 @@ def test_fun(coin_1: Coin, coin_2: Coin) -> SpendBundle: bundle = SpendBundle.aggregate([spend_bundle1, spend_bundle2]) return bundle - full_node_1, server_1, bt = one_node_one_block - blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) + full_node_1, _server_1, _bt = one_node_one_block + _blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) mempool_bundle = full_node_1.full_node.mempool_manager.get_spendbundle(bundle.name()) assert err is None @@ -1268,8 +1268,8 @@ def test_fun(coin_1: Coin, coin_2: Coin) -> SpendBundle: bundle = SpendBundle.aggregate([spend_bundle1, spend_bundle2]) return bundle - full_node_1, server_1, bt = one_node_one_block - blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) + full_node_1, _server_1, _bt = one_node_one_block + _blocks, bundle, status, err = await self.condition_tester2(one_node_one_block, wallet_a, test_fun) assert err is expected assert status == expected_included @@ -1609,10 +1609,10 @@ def test_fun(coin_1: Coin, coin_2: Coin) -> SpendBundle: async def test_assert_fee_condition( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.RESERVE_FEE, [int_to_bytes(10)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, fee=10 ) mempool_bundle = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) @@ -1625,12 +1625,12 @@ async def test_assert_fee_condition( async def test_assert_fee_condition_garbage( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block # garbage at the end of the arguments is ignored in consensus mode, but # not in mempool mode cvp = ConditionWithArgs(ConditionOpcode.RESERVE_FEE, [int_to_bytes(10), b"garbage"]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, fee=10 ) mempool_bundle = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) @@ -1643,10 +1643,10 @@ async def test_assert_fee_condition_garbage( async def test_assert_fee_condition_missing_arg( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.RESERVE_FEE, []) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, fee=10 ) mempool_bundle = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) @@ -1659,10 +1659,10 @@ async def test_assert_fee_condition_missing_arg( async def test_assert_fee_condition_negative_fee( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.RESERVE_FEE, [int_to_bytes(-1)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, fee=10 ) assert err == Err.RESERVE_FEE_CONDITION_FAILED @@ -1679,10 +1679,10 @@ async def test_assert_fee_condition_negative_fee( async def test_assert_fee_condition_fee_too_large( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.RESERVE_FEE, [int_to_bytes(2**64)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, fee=10 ) assert err == Err.RESERVE_FEE_CONDITION_FAILED @@ -1699,11 +1699,13 @@ async def test_assert_fee_condition_fee_too_large( async def test_assert_fee_condition_wrong_fee( self, one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.RESERVE_FEE, [int_to_bytes(10)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic, fee=9) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( + one_node_one_block, wallet_a, dic, fee=9 + ) mempool_bundle = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) assert err == Err.RESERVE_FEE_CONDITION_FAILED @@ -1827,7 +1829,7 @@ async def test_agg_sig_condition( wallet_a: WalletTool, ) -> None: reward_ph = wallet_a.get_new_puzzlehash() - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block blocks = await full_node_1.get_all_full_blocks() start_height = blocks[-1].height blocks = bt.get_consecutive_blocks( @@ -1875,14 +1877,14 @@ async def test_correct_my_parent( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) coin = await next_block(full_node_1, wallet_a, bt) cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_PARENT_ID, [coin.parent_coin_info]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -1898,7 +1900,7 @@ async def test_my_parent_garbage( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) @@ -1907,7 +1909,7 @@ async def test_my_parent_garbage( # but not in mempool mode cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_PARENT_ID, [coin.parent_coin_info, b"garbage"]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -1923,10 +1925,10 @@ async def test_my_parent_missing_arg( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_PARENT_ID, []) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) @@ -1940,7 +1942,7 @@ async def test_invalid_my_parent( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) @@ -1948,7 +1950,7 @@ async def test_invalid_my_parent( coin_2 = await next_block(full_node_1, wallet_a, bt) cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_PARENT_ID, [coin_2.parent_coin_info]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -1964,14 +1966,14 @@ async def test_correct_my_puzhash( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) coin = await next_block(full_node_1, wallet_a, bt) cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_PUZZLEHASH, [coin.puzzle_hash]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -1987,7 +1989,7 @@ async def test_my_puzhash_garbage( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) @@ -1995,7 +1997,7 @@ async def test_my_puzhash_garbage( # garbage at the end of the arguments list is allowed but stripped cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_PUZZLEHASH, [coin.puzzle_hash, b"garbage"]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -2011,10 +2013,10 @@ async def test_my_puzhash_missing_arg( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_PUZZLEHASH, []) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) @@ -2028,14 +2030,14 @@ async def test_invalid_my_puzhash( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) coin = await next_block(full_node_1, wallet_a, bt) cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_PUZZLEHASH, [Program.to([]).get_tree_hash()]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -2051,14 +2053,14 @@ async def test_correct_my_amount( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) coin = await next_block(full_node_1, wallet_a, bt) cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_AMOUNT, [int_to_bytes(coin.amount)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -2074,7 +2076,7 @@ async def test_my_amount_garbage( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, bt = one_node_one_block _ = await next_block(full_node_1, wallet_a, bt) _ = await next_block(full_node_1, wallet_a, bt) @@ -2083,7 +2085,7 @@ async def test_my_amount_garbage( # but not in mempool mode cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_AMOUNT, [int_to_bytes(coin.amount), b"garbage"]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester( + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester( one_node_one_block, wallet_a, dic, coin=coin ) @@ -2099,10 +2101,10 @@ async def test_my_amount_missing_arg( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_AMOUNT, []) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) @@ -2116,10 +2118,10 @@ async def test_invalid_my_amount( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_AMOUNT, [int_to_bytes(1000)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) @@ -2133,10 +2135,10 @@ async def test_negative_my_amount( one_node_one_block: tuple[FullNodeSimulator, ChiaServer, BlockTools], wallet_a: WalletTool, ) -> None: - full_node_1, server_1, bt = one_node_one_block + full_node_1, _server_1, _bt = one_node_one_block cvp = ConditionWithArgs(ConditionOpcode.ASSERT_MY_AMOUNT, [int_to_bytes(-1)]) dic = {cvp.opcode: [cvp]} - blocks, spend_bundle1, peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) + _blocks, spend_bundle1, _peer, status, err = await self.condition_tester(one_node_one_block, wallet_a, dic) sb1 = full_node_1.full_node.mempool_manager.get_spendbundle(spend_bundle1.name()) diff --git a/chia/_tests/core/mempool/test_mempool_fee_protocol.py b/chia/_tests/core/mempool/test_mempool_fee_protocol.py index 8704afc98b12..972621477e76 100644 --- a/chia/_tests/core/mempool/test_mempool_fee_protocol.py +++ b/chia/_tests/core/mempool/test_mempool_fee_protocol.py @@ -24,7 +24,7 @@ async def test_protocol_messages( list[Union[FullNodeAPI, FullNodeSimulator]], list[tuple[Wallet, ChiaServer]], BlockTools ] ) -> None: - full_nodes, wallets, bt = simulator_and_wallet + full_nodes, _wallets, bt = simulator_and_wallet a_wallet = bt.get_pool_wallet_tool() reward_ph = a_wallet.get_new_puzzlehash() blocks = bt.get_consecutive_blocks( diff --git a/chia/_tests/core/server/flood.py b/chia/_tests/core/server/flood.py index 5e05f5286428..cafdccc8b07d 100644 --- a/chia/_tests/core/server/flood.py +++ b/chia/_tests/core/server/flood.py @@ -28,7 +28,7 @@ async def tcp_echo_client(task_counter: str, logger: logging.Logger) -> None: writer = None try: logger.info(f"Opening connection: {label}") - reader, writer = await asyncio.open_connection(IP, PORT) + _reader, writer = await asyncio.open_connection(IP, PORT) total_open_connections += 1 logger.info(f"Opened connection: {label} (total: {total_open_connections})") assert writer is not None diff --git a/chia/_tests/core/server/test_dos.py b/chia/_tests/core/server/test_dos.py index 3bec21ba1162..9885d952e9a6 100644 --- a/chia/_tests/core/server/test_dos.py +++ b/chia/_tests/core/server/test_dos.py @@ -1,4 +1,3 @@ -# flake8: noqa: F811, F401 from __future__ import annotations import asyncio @@ -175,7 +174,7 @@ async def test_invalid_protocol_handshake(self, setup_two_nodes_fixture, self_ho @pytest.mark.anyio async def test_spam_tx(self, setup_two_nodes_fixture, self_hostname): nodes, _, _ = setup_two_nodes_fixture - full_node_1, full_node_2 = nodes + _full_node_1, full_node_2 = nodes server_1 = nodes[0].full_node.server server_2 = nodes[1].full_node.server @@ -230,7 +229,7 @@ def is_banned(): @pytest.mark.anyio async def test_spam_message_non_tx(self, setup_two_nodes_fixture, self_hostname): nodes, _, _ = setup_two_nodes_fixture - full_node_1, full_node_2 = nodes + _full_node_1, full_node_2 = nodes server_1 = nodes[0].full_node.server server_2 = nodes[1].full_node.server @@ -279,7 +278,7 @@ def is_banned(): @pytest.mark.anyio async def test_spam_message_too_large(self, setup_two_nodes_fixture, self_hostname): nodes, _, _ = setup_two_nodes_fixture - full_node_1, full_node_2 = nodes + _full_node_1, full_node_2 = nodes server_1 = nodes[0].full_node.server server_2 = nodes[1].full_node.server diff --git a/chia/_tests/core/server/test_loop.py b/chia/_tests/core/server/test_loop.py index 515b9d401561..8009d78aa632 100644 --- a/chia/_tests/core/server/test_loop.py +++ b/chia/_tests/core/server/test_loop.py @@ -190,7 +190,7 @@ async def test_loop(tmp_path: pathlib.Path) -> None: try: logger.info(" ==== attempting a single new connection") with anyio.fail_after(delay=adjusted_timeout(1)): - reader, writer = await asyncio.open_connection(IP, PORT) + _reader, writer = await asyncio.open_connection(IP, PORT) logger.info(" ==== connection succeeded") post_connection_succeeded = True except (TimeoutError, ConnectionRefusedError) as e: diff --git a/chia/_tests/core/services/test_services.py b/chia/_tests/core/services/test_services.py index 86187ea7426b..f80648ad8d60 100644 --- a/chia/_tests/core/services/test_services.py +++ b/chia/_tests/core/services/test_services.py @@ -1,11 +1,13 @@ from __future__ import annotations import asyncio +import contextlib import signal import sys import time +from collections.abc import AsyncIterator from pathlib import Path -from typing import Any +from typing import Any, Optional, cast import aiohttp.client_exceptions import pytest @@ -34,13 +36,15 @@ class CreateServiceProtocol(Protocol): + @contextlib.asynccontextmanager async def __call__( self, self_hostname: str, port: uint16, root_path: Path, net_config: dict[str, Any], - ) -> RpcClient: ... + ) -> AsyncIterator[RpcClient]: + yield cast(RpcClient, None) # pragma: no cover async def wait_for_daemon_connection(root_path: Path, config: dict[str, Any], timeout: float = 15) -> DaemonProxy: @@ -82,34 +86,45 @@ async def test_daemon_terminates(signal_number: signal.Signals, chia_root: ChiaR @pytest.mark.parametrize( argnames=["create_service", "module_path", "service_config_name"], argvalues=[ - [DataLayerRpcClient.create, "chia.server.start_data_layer", "data_layer"], - [FarmerRpcClient.create, "chia.server.start_farmer", "farmer"], - [FullNodeRpcClient.create, "chia.server.start_full_node", "full_node"], - [HarvesterRpcClient.create, "chia.server.start_harvester", "harvester"], - [WalletRpcClient.create, "chia.server.start_wallet", "wallet"], - # TODO: review and somehow test the other services too - # [, "chia.server.start_introducer", "introducer"], - # [, "chia.seeder.start_crawler", ""], - # [, "chia.server.start_timelord", "timelord"], - # [, "chia.timelord.timelord_launcher", ], - # [, "chia.simulator.start_simulator", ], - # [, "chia.data_layer.data_layer_server", "data_layer"], + [DataLayerRpcClient.create_as_context, "chia.server.start_data_layer", "data_layer"], + [FarmerRpcClient.create_as_context, "chia.server.start_farmer", "farmer"], + [FullNodeRpcClient.create_as_context, "chia.server.start_full_node", "full_node"], + [HarvesterRpcClient.create_as_context, "chia.server.start_harvester", "harvester"], + [WalletRpcClient.create_as_context, "chia.server.start_wallet", "wallet"], + [None, "chia.server.start_introducer", "introducer"], + # TODO: fails... make it not do that + # [None, "chia.seeder.start_crawler", "crawler"], + [None, "chia.server.start_timelord", "timelord"], + pytest.param( + None, + "chia.timelord.timelord_launcher", + "timelord_launcher", + marks=pytest.mark.skipif( + sys.platform in ("win32", "cygwin"), + reason="windows is not supported by the timelord launcher", + ), + ), + [None, "chia.simulator.start_simulator", "simulator"], + # TODO: fails... make it not do that + # [None, "chia.data_layer.data_layer_server", "data_layer"], ], ) @pytest.mark.anyio async def test_services_terminate( signal_number: signal.Signals, chia_root: ChiaRoot, - create_service: CreateServiceProtocol, + create_service: Optional[CreateServiceProtocol], module_path: str, service_config_name: str, ) -> None: with lock_and_load_config(root_path=chia_root.path, filename="config.yaml") as config: config["daemon_port"] = find_available_listen_port(name="daemon") service_config = config[service_config_name] - if "port" in service_config: - port = find_available_listen_port(name="service") - service_config["port"] = port + api_port_group = service_config + if service_config_name == "timelord": + api_port_group = api_port_group["vdf_server"] + if "port" in api_port_group: + api_port_group["port"] = 0 rpc_port = find_available_listen_port(name="rpc") service_config["rpc_port"] = rpc_port save_config(root_path=chia_root.path, filename="config.yaml", config_data=config) @@ -125,17 +140,26 @@ async def test_services_terminate( daemon_client = await wait_for_daemon_connection(root_path=chia_root.path, config=config) await daemon_client.close() - with closing_chia_root_popen( - chia_root=chia_root, - args=[sys.executable, "-m", module_path], - ) as process: - client = await create_service( - self_hostname=config["self_hostname"], - port=uint16(rpc_port), - root_path=chia_root.path, - net_config=config, + async with contextlib.AsyncExitStack() as exit_stack: + process = exit_stack.enter_context( + closing_chia_root_popen( + chia_root=chia_root, + args=[sys.executable, "-m", module_path], + ) ) - try: + + if create_service is None: + await asyncio.sleep(5) + else: + client = await exit_stack.enter_async_context( + create_service( + self_hostname=config["self_hostname"], + port=uint16(rpc_port), + root_path=chia_root.path, + net_config=config, + ) + ) + start = time.monotonic() while time.monotonic() - start < 50: return_code = process.poll() @@ -156,11 +180,8 @@ async def test_services_terminate( else: raise Exception("unable to connect") - return_code = process.poll() - assert return_code is None + return_code = process.poll() + assert return_code is None - process.send_signal(signal_number) - process.communicate(timeout=adjusted_timeout(timeout=30)) - finally: - client.close() - await client.await_closed() + process.send_signal(signal_number) + process.communicate(timeout=adjusted_timeout(timeout=30)) diff --git a/chia/_tests/core/ssl/test_ssl.py b/chia/_tests/core/ssl/test_ssl.py index 544d35e1a4a9..dad1a57d9da3 100644 --- a/chia/_tests/core/ssl/test_ssl.py +++ b/chia/_tests/core/ssl/test_ssl.py @@ -8,6 +8,7 @@ import aiohttp import pytest +from chia.apis import ApiProtocolRegistry from chia.protocols.shared_protocol import default_capabilities from chia.server.outbound_message import NodeType from chia.server.server import ChiaServer, ssl_context_for_client @@ -37,6 +38,7 @@ async def establish_connection(server: ChiaServer, self_hostname: str, ssl_conte 100, 30, local_capabilities_for_handshake=default_capabilities[NodeType.FULL_NODE], + class_for_type=ApiProtocolRegistry, ) await wsc.perform_handshake(server._network_id, dummy_port, NodeType.FULL_NODE) await wsc.close() @@ -84,7 +86,7 @@ async def test_public_connections(self, simulator_and_wallet, self_hostname): full_nodes, wallets, _ = simulator_and_wallet full_node_api = full_nodes[0] server_1: ChiaServer = full_node_api.full_node.server - wallet_node, server_2 = wallets[0] + _wallet_node, server_2 = wallets[0] success = await server_2.start_client(PeerInfo(self_hostname, server_1.get_port()), None) assert success is True @@ -165,7 +167,7 @@ async def test_farmer_mismatch_context(self, farmer_one_harvester_not_started, s @pytest.mark.anyio async def test_full_node(self, simulator_and_wallet, self_hostname): - full_nodes, wallets, bt = simulator_and_wallet + full_nodes, _wallets, bt = simulator_and_wallet full_node_api = full_nodes[0] full_node_server = full_node_api.full_node.server chia_ca_crt_path, chia_ca_key_path = chia_ssl_ca_paths(bt.root_path, bt.config) diff --git a/chia/_tests/core/test_cost_calculation.py b/chia/_tests/core/test_cost_calculation.py index a80da5484ed3..cc638cbb53ca 100644 --- a/chia/_tests/core/test_cost_calculation.py +++ b/chia/_tests/core/test_cost_calculation.py @@ -276,7 +276,7 @@ async def test_standard_tx(benchmark_runner: BenchmarkRunner) -> None: with benchmark_runner.assert_runtime(seconds=0.1): total_cost = 0 for i in range(0, 1000): - cost, result = puzzle_program.run_with_cost(test_constants.MAX_BLOCK_COST_CLVM, solution_program) + cost, _result = puzzle_program.run_with_cost(test_constants.MAX_BLOCK_COST_CLVM, solution_program) total_cost += cost diff --git a/chia/_tests/core/test_db_conversion.py b/chia/_tests/core/test_db_conversion.py index 53892494aa2c..4693a8be50cb 100644 --- a/chia/_tests/core/test_db_conversion.py +++ b/chia/_tests/core/test_db_conversion.py @@ -76,7 +76,7 @@ async def test_blocks(default_1000_blocks, with_hints: bool): # await _validate_and_add_block(bc, block) results = PreValidationResult(None, uint64(1), None, False, uint32(0)) fork_info = ForkInfo(block.height - 1, block.height - 1, block.prev_header_hash) - result, err, _ = await bc.add_block( + _result, err, _ = await bc.add_block( block, results, None, sub_slot_iters=sub_slot_iters, fork_info=fork_info ) assert err is None diff --git a/chia/_tests/core/test_db_validation.py b/chia/_tests/core/test_db_validation.py index 1d661e04e457..2ec10386d81e 100644 --- a/chia/_tests/core/test_db_validation.py +++ b/chia/_tests/core/test_db_validation.py @@ -146,7 +146,7 @@ async def make_db(db_file: Path, blocks: list[FullBlock]) -> None: sub_slot_iters = block.finished_sub_slots[0].challenge_chain.new_sub_slot_iters results = PreValidationResult(None, uint64(1), None, False, uint32(0)) fork_info = ForkInfo(block.height - 1, block.height - 1, block.prev_header_hash) - result, err, _ = await bc.add_block( + _result, err, _ = await bc.add_block( block, results, None, sub_slot_iters=sub_slot_iters, fork_info=fork_info ) assert err is None diff --git a/chia/_tests/core/test_filter.py b/chia/_tests/core/test_filter.py index f776bc4e9861..f18729d79d12 100644 --- a/chia/_tests/core/test_filter.py +++ b/chia/_tests/core/test_filter.py @@ -6,8 +6,8 @@ @pytest.mark.anyio async def test_basic_filter_test(simulator_and_wallet): - full_nodes, wallets, bt = simulator_and_wallet - wallet_node, server_2 = wallets[0] + _full_nodes, wallets, bt = simulator_and_wallet + wallet_node, _server_2 = wallets[0] wallet = wallet_node.wallet_state_manager.main_wallet num_blocks = 2 diff --git a/chia/_tests/core/test_full_node_rpc.py b/chia/_tests/core/test_full_node_rpc.py index a91de8854468..b20463a76450 100644 --- a/chia/_tests/core/test_full_node_rpc.py +++ b/chia/_tests/core/test_full_node_rpc.py @@ -1,4 +1,3 @@ -# flake8: noqa: F811, F401 from __future__ import annotations import pytest @@ -7,7 +6,6 @@ from chia import __version__ from chia._tests.blockchain.blockchain_test_utils import _validate_and_add_block -from chia._tests.conftest import ConsensusMode from chia._tests.connection_utils import connect_and_get_peer from chia._tests.util.rpc import validate_get_routes from chia._tests.util.time_out_assert import time_out_assert @@ -559,7 +557,7 @@ async def test_signage_points(two_nodes_sim_and_wallets_services, empty_blockcha @pytest.mark.anyio async def test_get_network_info(one_wallet_and_one_simulator_services, self_hostname): - nodes, _, bt = one_wallet_and_one_simulator_services + nodes, _, _bt = one_wallet_and_one_simulator_services (full_node_service_1,) = nodes async with FullNodeRpcClient.create_as_context( @@ -580,7 +578,7 @@ async def test_get_network_info(one_wallet_and_one_simulator_services, self_host @pytest.mark.anyio async def test_get_version(one_wallet_and_one_simulator_services, self_hostname): - nodes, _, bt = one_wallet_and_one_simulator_services + nodes, _, _bt = one_wallet_and_one_simulator_services (full_node_service_1,) = nodes async with FullNodeRpcClient.create_as_context( self_hostname, @@ -713,7 +711,7 @@ async def test_coin_name_not_found_in_mempool(one_node, self_hostname): empty_coin_name = bytes32.zeros mempool_item = await client.get_mempool_items_by_coin_name(empty_coin_name) - assert mempool_item["success"] == True + assert mempool_item["success"] assert "mempool_items" in mempool_item assert len(mempool_item["mempool_items"]) == 0 finally: @@ -780,7 +778,7 @@ async def test_coin_name_found_in_mempool(one_node, self_hostname): mempool_item = await client.get_mempool_items_by_coin_name(coin_to_spend.name()) # found coin in coin spends - assert mempool_item["success"] == True + assert mempool_item["success"] assert "mempool_items" in mempool_item assert len(mempool_item["mempool_items"]) > 0 for item in mempool_item["mempool_items"]: diff --git a/chia/_tests/core/test_seeder.py b/chia/_tests/core/test_seeder.py index 9d4250273698..26cc5c692a07 100644 --- a/chia/_tests/core/test_seeder.py +++ b/chia/_tests/core/test_seeder.py @@ -216,7 +216,7 @@ async def test_error_conditions( r = await dns.asyncquery.tcp(q=no_peers, where=target_address, timeout=timeout, sock=socket) assert r.answer == no_peers_response.answer # send 120, as the first 2 bytes / the length of the packet, so that the server expects more. - await socket.sendall(int(120).to_bytes(2, byteorder="big"), int(time.time() + timeout)) + await socket.sendall((120).to_bytes(2, byteorder="big"), int(time.time() + timeout)) await socket.close() with pytest.raises(EOFError): await dns.asyncquery.receive_tcp(tcp_socket, timeout) diff --git a/chia/_tests/farmer_harvester/test_farmer.py b/chia/_tests/farmer_harvester/test_farmer.py index ab1ccec92354..28f9e4ebcab0 100644 --- a/chia/_tests/farmer_harvester/test_farmer.py +++ b/chia/_tests/farmer_harvester/test_farmer.py @@ -561,7 +561,7 @@ async def test_farmer_new_proof_of_space_for_pool_stats( harvester_farmer_environment: HarvesterFarmerEnvironment, case: NewProofOfSpaceCase, ) -> None: - farmer_service, farmer_rpc_client, _, _, _ = harvester_farmer_environment + farmer_service, _farmer_rpc_client, _, _, _ = harvester_farmer_environment farmer_api = farmer_service._api sp = farmer_protocol.NewSignagePoint( diff --git a/chia/_tests/farmer_harvester/test_farmer_harvester.py b/chia/_tests/farmer_harvester/test_farmer_harvester.py index acd3850e93db..0732dacee8b6 100644 --- a/chia/_tests/farmer_harvester/test_farmer_harvester.py +++ b/chia/_tests/farmer_harvester/test_farmer_harvester.py @@ -170,7 +170,7 @@ def log_is_ready() -> bool: @pytest.mark.anyio async def test_harvester_config(farmer_one_harvester: tuple[list[HarvesterService], FarmerService, BlockTools]) -> None: - harvester_services, farmer_service, bt = farmer_one_harvester + harvester_services, _farmer_service, bt = farmer_one_harvester harvester_service = harvester_services[0] assert harvester_service.rpc_server and harvester_service.rpc_server.webserver @@ -214,7 +214,7 @@ def check_config_match(config1: dict[str, Any], config2: dict[str, Any]) -> None async def test_missing_signage_point( farmer_one_harvester: tuple[list[HarvesterService], FarmerService, BlockTools] ) -> None: - _, farmer_service, bt = farmer_one_harvester + _, farmer_service, _bt = farmer_one_harvester farmer_api = farmer_service._api farmer = farmer_api.farmer @@ -286,7 +286,7 @@ def state_changed(change: str, data: dict[str, Any]) -> None: async def test_harvester_has_no_server( farmer_one_harvester: tuple[list[FarmerService], HarvesterService, BlockTools], ) -> None: - harvesters, _, bt = farmer_one_harvester + harvesters, _, _bt = farmer_one_harvester harvester_server = harvesters[0]._server assert harvester_server.webserver is None diff --git a/chia/_tests/farmer_harvester/test_third_party_harvesters.py b/chia/_tests/farmer_harvester/test_third_party_harvesters.py index 334f753580b9..d64741e4492f 100644 --- a/chia/_tests/farmer_harvester/test_third_party_harvesters.py +++ b/chia/_tests/farmer_harvester/test_third_party_harvesters.py @@ -253,7 +253,7 @@ async def intercept_farmer_request_signed_values(*args: Any) -> Optional[Message def did_finished_validating_data() -> bool: return finished_validating_data - await time_out_assert(60 * 60, did_finished_validating_data, True) + await time_out_assert(60, did_finished_validating_data, True) @pytest.mark.anyio diff --git a/chia/_tests/fee_estimation/test_fee_estimation_rpc.py b/chia/_tests/fee_estimation/test_fee_estimation_rpc.py index fea36c8be9f6..635d4ad0c32d 100644 --- a/chia/_tests/fee_estimation/test_fee_estimation_rpc.py +++ b/chia/_tests/fee_estimation/test_fee_estimation_rpc.py @@ -49,7 +49,7 @@ async def setup_node_and_rpc( async def one_node_no_blocks( one_node: tuple[list[SimulatorFullNodeService], list[WalletService], BlockTools] ) -> tuple[FullNodeRpcClient, FullNodeRpcApi]: - full_nodes, wallets, bt = one_node + full_nodes, _wallets, bt = one_node full_node_apis = [full_node_service._api for full_node_service in full_nodes] full_node_api: FullNodeSimulator = full_node_apis[0] full_node_service_1 = full_nodes[0] @@ -75,7 +75,7 @@ async def test_get_blockchain_state(setup_node_and_rpc: tuple[FullNodeRpcClient, @pytest.mark.anyio async def test_empty_request(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(ValueError): await full_node_rpc_api.get_fee_estimate({}) @@ -83,7 +83,7 @@ async def test_empty_request(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNo @pytest.mark.anyio async def test_empty_peak(one_node_no_blocks: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = one_node_no_blocks + _client, full_node_rpc_api = one_node_no_blocks response = await full_node_rpc_api.get_fee_estimate({"target_times": [], "cost": 1}) del response["node_time_utc"] assert response == { @@ -106,56 +106,56 @@ async def test_empty_peak(one_node_no_blocks: tuple[FullNodeRpcClient, FullNodeR @pytest.mark.anyio async def test_no_target_times(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(ValueError): await full_node_rpc_api.get_fee_estimate({"cost": 1}) @pytest.mark.anyio async def test_negative_time(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(ValueError): await full_node_rpc_api.get_fee_estimate({"cost": 1, "target_times": [-1]}) @pytest.mark.anyio async def test_negative_cost(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(ValueError): await full_node_rpc_api.get_fee_estimate({"cost": -1, "target_times": [1]}) @pytest.mark.anyio async def test_no_cost_or_tx(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(ValueError): await full_node_rpc_api.get_fee_estimate({"target_times": []}) @pytest.mark.anyio async def test_both_cost_and_tx(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(ValueError): await full_node_rpc_api.get_fee_estimate({"target_times": [], "cost": 1, "spend_bundle": "80"}) @pytest.mark.anyio async def test_target_times_invalid_type(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(TypeError): await full_node_rpc_api.get_fee_estimate({"target_times": 1, "cost": 1}) @pytest.mark.anyio async def test_cost_invalid_type(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(ValueError): await full_node_rpc_api.get_fee_estimate({"target_times": [], "cost": "a lot"}) @pytest.mark.anyio async def test_tx_invalid_type(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(TypeError): await full_node_rpc_api.get_fee_estimate({"target_times": [], "spend_bundle": {"coin_spends": 1}}) @@ -165,7 +165,7 @@ async def test_tx_invalid_type(setup_node_and_rpc: tuple[FullNodeRpcClient, Full @pytest.mark.anyio async def test_empty_target_times(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc response = await full_node_rpc_api.get_fee_estimate({"target_times": [], "cost": 1}) assert response["estimates"] == [] assert response["target_times"] == [] @@ -173,7 +173,7 @@ async def test_empty_target_times(setup_node_and_rpc: tuple[FullNodeRpcClient, F @pytest.mark.anyio async def test_cost(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc response = await full_node_rpc_api.get_fee_estimate({"target_times": [1], "cost": 1}) assert response["estimates"] == [0] assert response["target_times"] == [1] @@ -181,7 +181,7 @@ async def test_cost(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi] @pytest.mark.anyio async def test_tx(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi], bt: BlockTools) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc wallet_a: WalletTool = bt.get_pool_wallet_tool() my_puzzle_hash = wallet_a.get_new_puzzlehash() recevier_puzzle_hash = bytes32(b"0" * 32) @@ -198,7 +198,7 @@ async def test_tx(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi], @pytest.mark.anyio async def test_multiple(setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi]) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc response = await full_node_rpc_api.get_fee_estimate({"target_times": [1, 5, 10, 15, 60, 120, 180, 240], "cost": 1}) assert response["estimates"] == [0, 0, 0, 0, 0, 0, 0, 0] assert response["target_times"] == [1, 5, 10, 15, 60, 120, 180, 240] @@ -217,7 +217,7 @@ async def test_validate_fee_estimate_cost_err( setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi], bt: BlockTools ) -> None: spend_bundle = get_test_spendbundle(bt) - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc bad_arglist: list[list[Any]] = [ [["foo", "bar"]], [["spend_bundle", spend_bundle.to_json_dict()], ["cost", 1]], @@ -242,7 +242,7 @@ async def test_validate_fee_estimate_cost_ok( setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi], bt: BlockTools ) -> None: spend_bundle = get_test_spendbundle(bt) - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc good_arglist: list[list[Any]] = [ ["spend_bundle", spend_bundle.to_json_dict()], @@ -259,7 +259,7 @@ async def test_validate_fee_estimate_cost_ok( async def test_get_spendbundle_type_cost_missing( setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi], bt: BlockTools ) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(KeyError, match=re.escape("INVALID")): request = {"target_times": [1], "spend_type": "INVALID"} _ = await full_node_rpc_api.get_fee_estimate(request) @@ -269,7 +269,7 @@ async def test_get_spendbundle_type_cost_missing( async def test_get_spendbundle_type_cost_spend_count_ok( setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi], bt: BlockTools ) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc spend_counts = [0, 1, 2] for spend_count in spend_counts: request = {"target_times": [1], "spend_type": "send_xch_transaction", "spend_count": spend_count} @@ -281,7 +281,7 @@ async def test_get_spendbundle_type_cost_spend_count_ok( async def test_get_spendbundle_type_cost_spend_count_bad( setup_node_and_rpc: tuple[FullNodeRpcClient, FullNodeRpcApi], bt: BlockTools ) -> None: - client, full_node_rpc_api = setup_node_and_rpc + _client, full_node_rpc_api = setup_node_and_rpc with pytest.raises(ValueError): request = {"target_times": [1], "spend_type": "send_xch_transaction", "spend_count": -1} _ = await full_node_rpc_api.get_fee_estimate(request) diff --git a/chia/_tests/fee_estimation/test_mempoolitem_height_added.py b/chia/_tests/fee_estimation/test_mempoolitem_height_added.py index 62c7698541b7..913f047a7c03 100644 --- a/chia/_tests/fee_estimation/test_mempoolitem_height_added.py +++ b/chia/_tests/fee_estimation/test_mempoolitem_height_added.py @@ -79,11 +79,11 @@ async def init_test( @pytest.mark.anyio async def test_mempool_inclusion_filter_basic() -> None: async with sim_and_client(defaults=NEW_DEFAULT_CONSTANTS, pass_prefarm=False) as (sim, cli): - estimator, spend_coins, fee_coins = await init_test(sim, cli, the_puzzle_hash, 1) + _estimator, spend_coins, _fee_coins = await init_test(sim, cli, the_puzzle_hash, 1) assert sim.mempool_manager.mempool.size() == 0 spend_bundle: SpendBundle = make_tx_sb(spend_coins[0]) - status, error = await cli.push_tx(spend_bundle) + _status, error = await cli.push_tx(spend_bundle) assert sim.mempool_manager.mempool.size() == 1 assert error is None @@ -96,11 +96,11 @@ def include_none(bundle_name: bytes32) -> bool: def include_all(bundle_name: bytes32) -> bool: return True - additions, removals = await sim.farm_block(the_puzzle_hash, item_inclusion_filter=include_none) + _additions, removals = await sim.farm_block(the_puzzle_hash, item_inclusion_filter=include_none) assert sim.mempool_manager.mempool.size() == 1 assert removals == [] - additions, removals = await sim.farm_block(the_puzzle_hash, item_inclusion_filter=include_all) + _additions, removals = await sim.farm_block(the_puzzle_hash, item_inclusion_filter=include_all) assert sim.mempool_manager.mempool.size() == 0 removal_ids = [c.name() for c in removals] assert mempool_item.name not in removal_ids @@ -109,7 +109,7 @@ def include_all(bundle_name: bytes32) -> bool: @pytest.mark.anyio async def test_mempoolitem_height_added(db_version: int) -> None: async with sim_and_client(defaults=NEW_DEFAULT_CONSTANTS, pass_prefarm=False) as (sim, cli): - estimator, spend_coins, fee_coins = await init_test(sim, cli, the_puzzle_hash, 1) + _estimator, spend_coins, _fee_coins = await init_test(sim, cli, the_puzzle_hash, 1) assert sim.mempool_manager.mempool.size() == 0 spend_bundle: SpendBundle = make_tx_sb(spend_coins[0]) @@ -126,7 +126,7 @@ def ignore_spend(bundle_name: bytes32) -> bool: assert mempool_item return bundle_name != mempool_item.name - additions, removals = await sim.farm_block(the_puzzle_hash, item_inclusion_filter=ignore_spend) + _additions, removals = await sim.farm_block(the_puzzle_hash, item_inclusion_filter=ignore_spend) removal_ids = [c.name() for c in removals] assert mempool_item.name not in removal_ids @@ -139,7 +139,7 @@ def ignore_spend(bundle_name: bytes32) -> bool: assert mempool_item2.height_added_to_mempool == mempool_item2.height_added_to_mempool # Now farm it into the next block - additions, removals = await sim.farm_block(the_puzzle_hash) + _additions, removals = await sim.farm_block(the_puzzle_hash) assert sim.mempool_manager.mempool.size() == 0 assert len(removals) == 1 diff --git a/chia/_tests/generator/test_compression.py b/chia/_tests/generator/test_compression.py index e313c942f9be..b7eee8875673 100644 --- a/chia/_tests/generator/test_compression.py +++ b/chia/_tests/generator/test_compression.py @@ -1,24 +1,15 @@ -# flake8: noqa: F501 +# ruff: noqa: E501 from __future__ import annotations import io -from dataclasses import dataclass from typing import Any -import pytest -from chia_rs import ALLOW_BACKREFS +from chia_rs import serialized_length from clvm.serialize import sexp_from_stream from clvm.SExp import SExp from clvm_tools import binutils -from chia._tests.core.make_block_generator import make_spend_bundle -from chia._tests.generator.test_rom import run_generator -from chia.full_node.bundle_tools import simple_solution_generator, simple_solution_generator_backrefs -from chia.full_node.mempool_check_conditions import get_puzzle_and_solution_for_coin -from chia.simulator.block_tools import test_constants from chia.types.blockchain_format.program import INFINITE_COST, Program -from chia.types.blockchain_format.serialized_program import SerializedProgram -from chia.types.generator_types import BlockGenerator from chia.types.spend_bundle import SpendBundle from chia.util.byte_types import hexstr_to_bytes from chia.util.ints import uint32 @@ -51,8 +42,6 @@ FAKE_BLOCK_HEIGHT1 = uint32(100) FAKE_BLOCK_HEIGHT2 = uint32(200) -from chia_rs import serialized_length - assert serialized_length(original_generator) == len(original_generator) assert serialized_length(gen1) == len(gen1) assert serialized_length(gen2) == len(gen2) @@ -78,11 +67,11 @@ def test_compress_spend_bundle(self) -> None: class TestDecompression: def test_deserialization(self) -> None: - cost, out = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [bytes(Program.to("hello"))]) + _cost, out = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [bytes(Program.to("hello"))]) assert out == Program.to("hello") def test_deserialization_as_argument(self) -> None: - cost, out = TEST_GEN_DESERIALIZE.run_with_cost( + _cost, out = TEST_GEN_DESERIALIZE.run_with_cost( INFINITE_COST, [DESERIALIZE_MOD, Nil, bytes(Program.to("hello"))] ) print(bytes(Program.to("hello"))) @@ -91,7 +80,7 @@ def test_deserialization_as_argument(self) -> None: assert out == Program.to("hello") def test_decompress_puzzle(self) -> None: - cost, out = DECOMPRESS_PUZZLE.run_with_cost( + _cost, out = DECOMPRESS_PUZZLE.run_with_cost( INFINITE_COST, [DESERIALIZE_MOD, b"\xff", bytes(Program.to("pubkey")), b"\x80"] ) @@ -110,7 +99,7 @@ def test_decompress_cse(self) -> None: cse0 = binutils.assemble( "((0x0000000000000000000000000000000000000000000000000000000000000000 0x0186a0) (0xb081963921826355dcb6c355ccf9c2637c18adf7d38ee44d803ea9ca41587e48c913d8d46896eb830aeadfc13144a8eac3 (() (q (51 0x6b7a83babea1eec790c947db4464ab657dbe9b887fe9acc247062847b8c2a8a9 0x0186a0)) ())))" ) - cost, out = DECOMPRESS_CSE.run_with_cost( + _cost, out = DECOMPRESS_CSE.run_with_cost( INFINITE_COST, [DESERIALIZE_MOD, DECOMPRESS_PUZZLE, b"\xff", b"\x80", cse0] ) @@ -126,7 +115,7 @@ def test_decompress_cse_with_prefix(self) -> None: end = start + 238 prefix = original_generator[start:end] # (deserialize decompress_puzzle puzzle_prefix cse) - cost, out = DECOMPRESS_CSE_WITH_PREFIX.run_with_cost( + _cost, out = DECOMPRESS_CSE_WITH_PREFIX.run_with_cost( INFINITE_COST, [DESERIALIZE_MOD, DECOMPRESS_PUZZLE, prefix, cse0] ) @@ -135,9 +124,6 @@ def test_decompress_cse_with_prefix(self) -> None: def test_block_program_zero(self) -> None: "Decompress a list of CSEs" - cse1 = binutils.assemble( - "(((0x0000000000000000000000000000000000000000000000000000000000000000 0x0186a0) (0xb081963921826355dcb6c355ccf9c2637c18adf7d38ee44d803ea9ca41587e48c913d8d46896eb830aeadfc13144a8eac3 (() (q (51 0x6b7a83babea1eec790c947db4464ab657dbe9b887fe9acc247062847b8c2a8a9 0x0186a0)) ()))))" - ) cse2 = binutils.assemble( """ ( @@ -159,7 +145,7 @@ def test_block_program_zero(self) -> None: # (mod (decompress_puzzle decompress_coin_spend_entry start end compressed_cses deserialize generator_list reserved_arg) # cost, out = DECOMPRESS_BLOCK.run_with_cost(INFINITE_COST, [DECOMPRESS_PUZZLE, DECOMPRESS_CSE, start, Program.to(end), cse0, DESERIALIZE_MOD, bytes(original_generator)]) - cost, out = DECOMPRESS_BLOCK.run_with_cost( + _cost, out = DECOMPRESS_BLOCK.run_with_cost( INFINITE_COST, [ DECOMPRESS_PUZZLE, @@ -176,9 +162,6 @@ def test_block_program_zero(self) -> None: print(out) def test_block_program_zero_with_curry(self) -> None: - cse1 = binutils.assemble( - "(((0x0000000000000000000000000000000000000000000000000000000000000000 0x0186a0) (0xb081963921826355dcb6c355ccf9c2637c18adf7d38ee44d803ea9ca41587e48c913d8d46896eb830aeadfc13144a8eac3 (() (q (51 0x6b7a83babea1eec790c947db4464ab657dbe9b887fe9acc247062847b8c2a8a9 0x0186a0)) ()))))" - ) cse2 = binutils.assemble( """ ( @@ -201,7 +184,7 @@ def test_block_program_zero_with_curry(self) -> None: # (mod (decompress_puzzle decompress_coin_spend_entry start end compressed_cses deserialize generator_list reserved_arg) # cost, out = DECOMPRESS_BLOCK.run_with_cost(INFINITE_COST, [DECOMPRESS_PUZZLE, DECOMPRESS_CSE, start, Program.to(end), cse0, DESERIALIZE_MOD, bytes(original_generator)]) p = DECOMPRESS_BLOCK.curry(DECOMPRESS_PUZZLE, DECOMPRESS_CSE_WITH_PREFIX, start, Program.to(end)) - cost, out = p.run_with_cost(INFINITE_COST, [cse2, DESERIALIZE_MOD, [bytes(original_generator)]]) + _cost, out = p.run_with_cost(INFINITE_COST, [cse2, DESERIALIZE_MOD, [bytes(original_generator)]]) print() print(p) @@ -211,7 +194,7 @@ def test_block_program_zero_with_curry(self) -> None: DECOMPRESS_PUZZLE, DECOMPRESS_CSE_WITH_PREFIX, start, Program.to(end), cse2, DESERIALIZE_MOD ) generator_args = Program.to([[original_generator]]) - cost, out = p_with_cses.run_with_cost(INFINITE_COST, generator_args) + _cost, out = p_with_cses.run_with_cost(INFINITE_COST, generator_args) print() print(p_with_cses) diff --git a/chia/_tests/generator/test_rom.py b/chia/_tests/generator/test_rom.py index 8155c54f6377..b585194e4055 100644 --- a/chia/_tests/generator/test_rom.py +++ b/chia/_tests/generator/test_rom.py @@ -15,8 +15,8 @@ from chia.util.ints import uint32 from chia.wallet.puzzles.load_clvm import load_clvm, load_serialized_clvm_maybe_recompile -MAX_COST = int(1e15) -COST_PER_BYTE = int(12000) +MAX_COST = 10**15 +COST_PER_BYTE = 12000 DESERIALIZE_MOD = load_clvm("chialisp_deserialisation.clsp", package_or_requirement="chia.consensus.puzzles") @@ -165,7 +165,7 @@ def test_coin_extras(self) -> None: # the ROM supports extra data after a coin. This test checks that it actually gets passed through gen = block_generator() - cost, r = run_generator(gen) + _cost, r = run_generator(gen) coin_spends = r.first() for coin_spend in coin_spends.as_iter(): extra_data = coin_spend.rest().rest().rest().rest() @@ -175,6 +175,6 @@ def test_block_extras(self) -> None: # the ROM supports extra data after the coin spend list. This test checks that it actually gets passed through gen = block_generator() - cost, r = run_generator(gen) + _cost, r = run_generator(gen) extra_block_data = r.rest() assert as_atom_list(extra_block_data) == b"extra data for block".split() diff --git a/chia/_tests/plot_sync/test_receiver.py b/chia/_tests/plot_sync/test_receiver.py index ec3ec8383094..b45b95aa5a9e 100644 --- a/chia/_tests/plot_sync/test_receiver.py +++ b/chia/_tests/plot_sync/test_receiver.py @@ -223,7 +223,7 @@ def test_default_values(seeded_random: random.Random) -> None: @pytest.mark.anyio async def test_reset(seeded_random: random.Random) -> None: - receiver, sync_steps = plot_sync_setup(seeded_random=seeded_random) + receiver, _sync_steps = plot_sync_setup(seeded_random=seeded_random) connection_before = receiver.connection() # Assign some dummy values receiver._current_sync.state = State.done diff --git a/chia/_tests/plot_sync/test_sender.py b/chia/_tests/plot_sync/test_sender.py index 5d78be6393dc..c04035f722f0 100644 --- a/chia/_tests/plot_sync/test_sender.py +++ b/chia/_tests/plot_sync/test_sender.py @@ -45,7 +45,7 @@ def test_set_connection_values(bt: BlockTools, seeded_random: random.Random) -> # Test setting a valid connection works sender.set_connection(farmer_connection) # type:ignore[arg-type] assert sender._connection is not None - assert sender._connection == farmer_connection # type: ignore[comparison-overlap] + assert id(sender._connection) == id(farmer_connection) @pytest.mark.anyio diff --git a/chia/_tests/pools/test_pool_cmdline.py b/chia/_tests/pools/test_pool_cmdline.py index 2ab6e363f06f..d323ad503729 100644 --- a/chia/_tests/pools/test_pool_cmdline.py +++ b/chia/_tests/pools/test_pool_cmdline.py @@ -1,10 +1,7 @@ -# flake8: noqa: E501 - from __future__ import annotations -import click import pytest -from click.testing import CliRunner, Result +from click.testing import CliRunner from chia.cmds.plotnft import create_cmd, show_cmd diff --git a/chia/_tests/pools/test_pool_config.py b/chia/_tests/pools/test_pool_config.py index 3e73bc8c2960..c8db6f59c682 100644 --- a/chia/_tests/pools/test_pool_config.py +++ b/chia/_tests/pools/test_pool_config.py @@ -1,8 +1,5 @@ -# flake8: noqa: E501 from __future__ import annotations -from chia_rs import AugSchemeMPL, PrivateKey - from chia.pools.pool_config import PoolWalletConfig from chia.util.config import create_default_chia_config, load_config, lock_config, save_config @@ -18,9 +15,10 @@ def test_pool_config(tmp_path): eg_config.rename(to_config) config = load_config(test_root, "test_pool_config.yaml") - auth_sk: PrivateKey = AugSchemeMPL.key_gen(b"1" * 32) d = { - "owner_public_key": "84c3fcf9d5581c1ddc702cb0f3b4a06043303b334dd993ab42b2c320ebfa98e5ce558448615b3f69638ba92cf7f43da5", + "owner_public_key": ( + "84c3fcf9d5581c1ddc702cb0f3b4a06043303b334dd993ab42b2c320ebfa98e5ce558448615b3f69638ba92cf7f43da5" + ), "p2_singleton_puzzle_hash": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", "payout_instructions": "c2b08e41d766da4116e388357ed957d04ad754623a915f3fd65188a8746cf3e8", "pool_url": "localhost", diff --git a/chia/_tests/pools/test_pool_rpc.py b/chia/_tests/pools/test_pool_rpc.py index 257acc246800..c480f73836f0 100644 --- a/chia/_tests/pools/test_pool_rpc.py +++ b/chia/_tests/pools/test_pool_rpc.py @@ -140,7 +140,7 @@ async def setup( self_hostname: str, ) -> AsyncIterator[Setup]: rmtree(get_pool_plot_dir(), ignore_errors=True) - [full_node_service], [wallet_service], bt = one_wallet_and_one_simulator_services + [full_node_service], [wallet_service], _bt = one_wallet_and_one_simulator_services full_node_api: FullNodeSimulator = full_node_service._api wallet_node = wallet_service._node our_ph_record = await wallet_node.wallet_state_manager.get_unused_derivation_record(uint32(1), hardened=True) @@ -189,7 +189,7 @@ async def test_create_new_pool_wallet_self_farm( fee: uint64, self_hostname: str, ) -> None: - client, wallet_node, full_node_api, total_block_rewards, _ = one_wallet_node_and_rpc + client, wallet_node, full_node_api, _total_block_rewards, _ = one_wallet_node_and_rpc wallet = wallet_node.wallet_state_manager.main_wallet our_ph = await wallet.get_new_puzzlehash() @@ -241,7 +241,7 @@ async def test_create_new_pool_wallet_farm_to_pool( fee: uint64, self_hostname: str, ) -> None: - client, wallet_node, full_node_api, total_block_rewards, _ = one_wallet_node_and_rpc + client, wallet_node, full_node_api, _total_block_rewards, _ = one_wallet_node_and_rpc wallet = wallet_node.wallet_state_manager.main_wallet our_ph = await wallet.get_new_puzzlehash() @@ -295,7 +295,7 @@ async def test_create_multiple_pool_wallets( fee: uint64, self_hostname: str, ) -> None: - client, wallet_node, full_node_api, total_block_rewards, _ = one_wallet_node_and_rpc + client, wallet_node, full_node_api, _total_block_rewards, _ = one_wallet_node_and_rpc wallet = wallet_node.wallet_state_manager.main_wallet @@ -404,7 +404,7 @@ def mempool_empty() -> bool: async def test_absorb_self( self, one_wallet_node_and_rpc: OneWalletNodeAndRpc, fee: uint64, self_hostname: str ) -> None: - client, wallet_node, full_node_api, total_block_rewards, _ = one_wallet_node_and_rpc + client, wallet_node, full_node_api, _total_block_rewards, _ = one_wallet_node_and_rpc bt = full_node_api.bt wallet = wallet_node.wallet_state_manager.main_wallet @@ -680,7 +680,7 @@ async def test_self_pooling_to_pooling(self, setup: Setup, fee: uint64, self_hos if fee != 0: pytest.skip("need to fix this test for non-zero fees") - full_node_api, wallet_node, our_ph, total_block_rewards, client = setup + full_node_api, wallet_node, our_ph, _total_block_rewards, client = setup pool_ph = bytes32.zeros assert wallet_node._wallet_state_manager is not None @@ -761,7 +761,7 @@ async def status_is_farming_to_pool(w_id: int) -> bool: @pytest.mark.anyio async def test_leave_pool(self, setup: Setup, fee: uint64, self_hostname: str) -> None: """This tests self-pooling -> pooling -> escaping -> self pooling""" - full_node_api, wallet_node, our_ph, total_block_rewards, client = setup + full_node_api, wallet_node, our_ph, _total_block_rewards, client = setup pool_ph = bytes32.zeros assert len(await client.get_wallets(WalletType.POOLING_WALLET)) == 0 @@ -860,7 +860,7 @@ async def status_is_self_pooling() -> bool: @pytest.mark.anyio async def test_change_pools(self, setup: Setup, fee: uint64, self_hostname: str) -> None: """This tests Pool A -> escaping -> Pool B""" - full_node_api, wallet_node, our_ph, total_block_rewards, client = setup + full_node_api, wallet_node, our_ph, _total_block_rewards, client = setup pool_a_ph = bytes32.zeros pool_b_ph = bytes32.zeros @@ -928,7 +928,7 @@ async def status_is_leaving() -> bool: @pytest.mark.anyio async def test_change_pools_reorg(self, setup: Setup, fee: uint64, self_hostname: str) -> None: """This tests Pool A -> escaping -> reorg -> escaping -> Pool B""" - full_node_api, wallet_node, our_ph, total_block_rewards, client = setup + full_node_api, wallet_node, our_ph, _total_block_rewards, client = setup pool_a_ph = bytes32.zeros pool_b_ph = bytes32.zeros WAIT_SECS = 30 diff --git a/chia/_tests/simulation/test_simulation.py b/chia/_tests/simulation/test_simulation.py index 45be72bae296..9a05729745f9 100644 --- a/chia/_tests/simulation/test_simulation.py +++ b/chia/_tests/simulation/test_simulation.py @@ -194,7 +194,7 @@ async def test_simulator_auto_farm_and_get_coins( full_node_api = full_nodes[0] server_1 = full_node_api.full_node.server wallet_node, server_2 = wallets[0] - wallet_node_2, server_3 = wallets[1] + wallet_node_2, _server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() wallet_node.config["trusted_peers"] = {} diff --git a/chia/_tests/simulation/test_start_simulator.py b/chia/_tests/simulation/test_start_simulator.py index fa2bf9444077..70b382792fa3 100644 --- a/chia/_tests/simulation/test_start_simulator.py +++ b/chia/_tests/simulation/test_start_simulator.py @@ -37,7 +37,7 @@ async def get_chia_simulator( async def test_start_simulator( self, get_chia_simulator: tuple[FullNodeSimulator, Path, dict[str, Any], str, int, Keychain] ) -> None: - simulator, root_path, config, mnemonic, fingerprint, keychain = get_chia_simulator + simulator, root_path, config, _mnemonic, fingerprint, keychain = get_chia_simulator ph_1: bytes32 = get_puzzle_hash_from_key(keychain=keychain, fingerprint=fingerprint, key_id=1) ph_2: bytes32 = get_puzzle_hash_from_key(keychain=keychain, fingerprint=fingerprint, key_id=2) dummy_hash: bytes32 = std_hash(b"test") diff --git a/chia/_tests/timelord/test_new_peak.py b/chia/_tests/timelord/test_new_peak.py index 1891e0f0cc42..4827ad519248 100644 --- a/chia/_tests/timelord/test_new_peak.py +++ b/chia/_tests/timelord/test_new_peak.py @@ -29,8 +29,8 @@ class TestNewPeak: async def test_timelord_new_peak_basic( self, bt: BlockTools, timelord: tuple[TimelordAPI, ChiaServer], default_1000_blocks: list[FullBlock] ) -> None: - async with create_blockchain(bt.constants, 2) as (b1, db_wrapper1): - async with create_blockchain(bt.constants, 2) as (b2, db_wrapper2): + async with create_blockchain(bt.constants, 2) as (b1, _): + async with create_blockchain(bt.constants, 2) as (b2, _): timelord_api, _ = timelord for block in default_1000_blocks: await _validate_and_add_block(b1, block) @@ -67,7 +67,7 @@ async def test_timelord_new_peak_basic( async def test_timelord_new_peak_unfinished_not_orphaned( self, bt: BlockTools, timelord: tuple[TimelordAPI, ChiaServer], default_1000_blocks: list[FullBlock] ) -> None: - async with create_blockchain(bt.constants, 2) as (b1, db_wrapper1): + async with create_blockchain(bt.constants, 2) as (b1, _): timelord_api, _ = timelord for block in default_1000_blocks: await _validate_and_add_block(b1, block) @@ -122,8 +122,8 @@ async def test_timelord_new_peak_unfinished_orphaned( ) -> None: [full_node_service], _, bt = one_node full_node = full_node_service._node - async with create_blockchain(bt.constants, 2) as (b1, db_wrapper1): - async with create_blockchain(bt.constants, 2) as (b2, db_wrapper2): + async with create_blockchain(bt.constants, 2) as (b1, _): + async with create_blockchain(bt.constants, 2) as (b2, _): timelord_api, _ = timelord for block in default_1000_blocks: await _validate_and_add_block(b1, block) @@ -227,8 +227,8 @@ async def test_timelord_new_peak_unfinished_orphaned( async def test_timelord_new_peak_unfinished_orphaned_overflow( self, bt: BlockTools, timelord: tuple[TimelordAPI, ChiaServer], default_1000_blocks: list[FullBlock] ) -> None: - async with create_blockchain(bt.constants, 2) as (b1, db_wrapper1): - async with create_blockchain(bt.constants, 2) as (b2, db_wrapper2): + async with create_blockchain(bt.constants, 2) as (b1, _): + async with create_blockchain(bt.constants, 2) as (b2, _): timelord_api, _ = timelord for block in default_1000_blocks: await _validate_and_add_block(b1, block) @@ -288,8 +288,8 @@ async def test_timelord_new_peak_unfinished_orphaned_overflow( async def test_timelord_new_peak_unfinished_eos( self, bt: BlockTools, timelord: tuple[TimelordAPI, ChiaServer], default_1000_blocks: list[FullBlock] ) -> None: - async with create_blockchain(bt.constants, 2) as (b1, db_wrapper1): - async with create_blockchain(bt.constants, 2) as (b2, db_wrapper2): + async with create_blockchain(bt.constants, 2) as (b1, _): + async with create_blockchain(bt.constants, 2) as (b2, _): timelord_api, _ = timelord for block in default_1000_blocks: await _validate_and_add_block(b1, block) diff --git a/chia/_tests/util/benchmark_cost.py b/chia/_tests/util/benchmark_cost.py index 56d1a3ab3143..27071afde009 100644 --- a/chia/_tests/util/benchmark_cost.py +++ b/chia/_tests/util/benchmark_cost.py @@ -66,15 +66,15 @@ def benchmark_all_operators(): point_add = "(point_add" " (q 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb)" " (q 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb))" - point_add_cost, point_add_time = run_and_return_cost_time(point_add) + _point_add_cost, point_add_time = run_and_return_cost_time(point_add) addition_cost, addition_time = run_and_return_cost_time(addition) - substraction_cost, substraction_time = run_and_return_cost_time(substraction) - multiply_cost, multiply_time = run_and_return_cost_time(multiply) - greater_cost, greater_time = run_and_return_cost_time(greater) - equal_cost, equal_time = run_and_return_cost_time(equal) - if_cost, if_time = run_and_return_cost_time(if_clvm) - sha256tree_cost, sha256tree_time = run_and_return_cost_time(sha256tree) - pubkey_for_exp_cost, pubkey_for_exp_time = run_and_return_cost_time(pubkey_for_exp) + _substraction_cost, substraction_time = run_and_return_cost_time(substraction) + _multiply_cost, multiply_time = run_and_return_cost_time(multiply) + _greater_cost, greater_time = run_and_return_cost_time(greater) + _equal_cost, equal_time = run_and_return_cost_time(equal) + _if_cost, if_time = run_and_return_cost_time(if_clvm) + _sha256tree_cost, sha256tree_time = run_and_return_cost_time(sha256tree) + _pubkey_for_exp_cost, pubkey_for_exp_time = run_and_return_cost_time(pubkey_for_exp) one_addition = 1 one_substraction = get_cost_compared_to_addition(addition_cost, addition_time, substraction_time) / addition_cost @@ -167,4 +167,4 @@ def benchmark_all_operators(): constant = clvm_should_cost / clvm_cost format = float_to_str(constant) print(f"Constant factor: {format}") - print(f"CLVM RATIO MULTIPLIER: {1/constant}") + print(f"CLVM RATIO MULTIPLIER: {1 / constant}") diff --git a/chia/_tests/util/build_network_protocol_files.py b/chia/_tests/util/build_network_protocol_files.py index 1b5c324a344f..c81f748fcfd3 100644 --- a/chia/_tests/util/build_network_protocol_files.py +++ b/chia/_tests/util/build_network_protocol_files.py @@ -1,3 +1,4 @@ +# ruff: noqa: F405 from __future__ import annotations import os @@ -183,7 +184,8 @@ def visitor(obj: Any, name: str) -> None: def build_protocol_test() -> str: - result = """# this file is generated by build_network_protocol_files.py + result = """# ruff: noqa: F405 +# this file is generated by build_network_protocol_files.py from __future__ import annotations @@ -232,7 +234,8 @@ def visitor(obj: Any, name: str) -> None: def get_protocol_json() -> str: - result = """# this file is generated by build_network_protocol_files.py + result = """# ruff: noqa: E501 +# this file is generated by build_network_protocol_files.py from __future__ import annotations from typing import Any @@ -251,7 +254,8 @@ def visitor(obj: Any, name: str) -> None: def build_json_test() -> str: - result = """# this file is generated by build_network_protocol_files.py + result = """# ruff: noqa: F405 +# this file is generated by build_network_protocol_files.py from __future__ import annotations diff --git a/chia/_tests/util/full_sync.py b/chia/_tests/util/full_sync.py index a8d48573290f..3a2275bca1b0 100644 --- a/chia/_tests/util/full_sync.py +++ b/chia/_tests/util/full_sync.py @@ -212,7 +212,7 @@ async def run_sync_test( ) fork_height = block_batch[0].height - 1 header_hash = block_batch[0].prev_header_hash - success, summary, err = await full_node.add_block_batch( + success, summary, _err = await full_node.add_block_batch( AugmentedBlockchain(full_node.blockchain), block_batch, peer_info, diff --git a/chia/_tests/util/misc.py b/chia/_tests/util/misc.py index 3ea473c59479..886b08f70f77 100644 --- a/chia/_tests/util/misc.py +++ b/chia/_tests/util/misc.py @@ -562,7 +562,7 @@ def create(cls, node: Node, platform: str = sys.platform) -> TestId: temp_node = temp_node.parent # TODO: can we avoid parsing the id's etc from the node name? - test_name, delimiter, rest = node.name.partition("[") + _test_name, delimiter, rest = node.name.partition("[") ids: tuple[str, ...] if delimiter == "": ids = () diff --git a/chia/_tests/util/network_protocol_data.py b/chia/_tests/util/network_protocol_data.py index 76b0c60cd738..5598d82cb814 100644 --- a/chia/_tests/util/network_protocol_data.py +++ b/chia/_tests/util/network_protocol_data.py @@ -1,5 +1,3 @@ -# flake8: noqa - from __future__ import annotations from chia_rs import G1Element, G2Element, RewardChainBlockUnfinished @@ -46,7 +44,7 @@ error_with_data = Error(int16(Err.UNKNOWN.value), "Unknown", b"extra data") -### FARMER PROTOCOL +# FARMER PROTOCOL new_signage_point = farmer_protocol.NewSignagePoint( bytes32(bytes.fromhex("34b2a753b0dc864e7218f8facf23ca0e2b636351df5289b76f5845d9a78b7026")), bytes32(bytes.fromhex("9dc8b9d685c79acdf8780d994416dfcfb118e0adc99769ecfa94e1f40aa5bbe5")), @@ -142,7 +140,7 @@ ) -### FULL NODE PROTOCOL. +# FULL NODE PROTOCOL. new_peak = full_node_protocol.NewPeak( bytes32(bytes.fromhex("8a346e8dc02e9b44c0571caa74fd99f163d4c5d7deae9f8ddb00528721493f7a")), uint32(2653549198), @@ -503,7 +501,7 @@ respond_peers = full_node_protocol.RespondPeers([timestamped_peer_info]) -## WALLET PROTOCOL +# WALLET PROTOCOL request_puzzle_solution = wallet_protocol.RequestPuzzleSolution( bytes32(bytes.fromhex("6edddb46bd154f50566b49c95812e0f1131a0a7162630349fc8d1d696e463e47")), uint32(3905474497), @@ -755,7 +753,7 @@ ) -### HARVESTER PROTOCOL +# HARVESTER PROTOCOL pool_difficulty = harvester_protocol.PoolDifficulty( uint64(14819251421858580996), uint64(12852879676624401630), @@ -899,7 +897,7 @@ ["str"], ) -### INTRODUCER PROTOCOL +# INTRODUCER PROTOCOL request_peers_introducer = introducer_protocol.RequestPeersIntroducer() respond_peers_introducer = introducer_protocol.RespondPeersIntroducer( @@ -913,7 +911,7 @@ ) -### POOL PROTOCOL +# POOL PROTOCOL authentication_payload = pool_protocol.AuthenticationPayload( "method", bytes32(bytes.fromhex("0251e3b3a1aacc689091b6b085be7a8d319bd9d1a015faae969cb76d8a45607c")), @@ -1002,7 +1000,7 @@ "err", ) -### TIMELORD PROTOCOL +# TIMELORD PROTOCOL sub_epoch_summary = SubEpochSummary( bytes32(bytes.fromhex("2d0550de416467e7b57e56e962c712b79bee29cae29c73cc908da5978fc9789e")), bytes32(bytes.fromhex("3d29f5a3fe067ce7edea76c9cebaf3a3afdebc0eb9fbd530f807f1a28ed2df6d")), diff --git a/chia/_tests/util/protocol_messages_json.py b/chia/_tests/util/protocol_messages_json.py index 6aa5800fc207..dbc48e209290 100644 --- a/chia/_tests/util/protocol_messages_json.py +++ b/chia/_tests/util/protocol_messages_json.py @@ -1,3 +1,4 @@ +# ruff: noqa: E501 # this file is generated by build_network_protocol_files.py from __future__ import annotations diff --git a/chia/_tests/util/run_block.py b/chia/_tests/util/run_block.py index 6b029a19d425..dacf04137b3f 100644 --- a/chia/_tests/util/run_block.py +++ b/chia/_tests/util/run_block.py @@ -62,7 +62,7 @@ def npc_to_dict(npc: NPC) -> dict[str, Any]: def run_generator(block_generator: BlockGenerator, constants: ConsensusConstants, max_cost: int) -> list[CAT]: block_args = block_generator.generator_refs - cost, block_result = block_generator.program.run_with_cost(max_cost, [DESERIALIZE_MOD, block_args]) + _cost, block_result = block_generator.program.run_with_cost(max_cost, [DESERIALIZE_MOD, block_args]) coin_spends = block_result.first() diff --git a/chia/_tests/util/spend_sim.py b/chia/_tests/util/spend_sim.py index 0b4ce8cf9f4a..087aade92168 100644 --- a/chia/_tests/util/spend_sim.py +++ b/chia/_tests/util/spend_sim.py @@ -68,7 +68,7 @@ def __init__(self) -> None: def add_cost(self, descriptor: str, spend_bundle: T_SpendBundle) -> T_SpendBundle: program: BlockGenerator = simple_solution_generator(spend_bundle) flags = get_flags_for_height_and_constants(DEFAULT_CONSTANTS.HARD_FORK_HEIGHT, DEFAULT_CONSTANTS) - err, conds = run_block_generator2( + _err, conds = run_block_generator2( bytes(program.program), [], INFINITE_COST, diff --git a/chia/_tests/util/split_managers.py b/chia/_tests/util/split_managers.py index 75a44d0f82e2..cec90f40e56b 100644 --- a/chia/_tests/util/split_managers.py +++ b/chia/_tests/util/split_managers.py @@ -3,7 +3,7 @@ import contextlib from collections.abc import AsyncIterator, Iterator from dataclasses import dataclass -from typing import AsyncContextManager, ContextManager, Generic, TypeVar +from typing import Generic, TypeVar T = TypeVar("T") @@ -11,7 +11,7 @@ @dataclass class SplitManager(Generic[T]): # NOTE: only for transitional testing use, please avoid usage - manager: ContextManager[object] + manager: contextlib.AbstractContextManager[object] object: T _entered: bool = False _exited: bool = False @@ -47,7 +47,7 @@ def exit(self, if_needed: bool = False) -> None: @dataclass class SplitAsyncManager(Generic[T]): # NOTE: only for transitional testing use, please avoid usage - manager: AsyncContextManager[object] + manager: contextlib.AbstractAsyncContextManager[object] object: T _entered: bool = False _exited: bool = False @@ -81,7 +81,7 @@ async def exit(self, if_needed: bool = False) -> None: @contextlib.contextmanager -def split_manager(manager: ContextManager[object], object: T) -> Iterator[SplitManager[T]]: +def split_manager(manager: contextlib.AbstractContextManager[object], object: T) -> Iterator[SplitManager[T]]: # NOTE: only for transitional testing use, please avoid usage split = SplitManager(manager=manager, object=object) try: @@ -91,7 +91,9 @@ def split_manager(manager: ContextManager[object], object: T) -> Iterator[SplitM @contextlib.asynccontextmanager -async def split_async_manager(manager: AsyncContextManager[object], object: T) -> AsyncIterator[SplitAsyncManager[T]]: +async def split_async_manager( + manager: contextlib.AbstractAsyncContextManager[object], object: T +) -> AsyncIterator[SplitAsyncManager[T]]: # NOTE: only for transitional testing use, please avoid usage split = SplitAsyncManager(manager=manager, object=object) try: diff --git a/chia/_tests/util/test_network.py b/chia/_tests/util/test_network.py index 9d63459dd95c..e853b4f92e90 100644 --- a/chia/_tests/util/test_network.py +++ b/chia/_tests/util/test_network.py @@ -12,7 +12,7 @@ @pytest.mark.anyio -async def test_resolve4(): +async def test_resolve4() -> None: # Run these tests forcing IPv4 resolution prefer_ipv6 = False assert await resolve("127.0.0.1", prefer_ipv6=prefer_ipv6) == IPAddress.create("127.0.0.1") @@ -26,7 +26,7 @@ async def test_resolve4(): condition=("GITHUB_ACTIONS" in os.environ) and (sys.platform in {"darwin", "win32"}), reason="macOS and Windows runners in GitHub Actions do not seem to support IPv6", ) -async def test_resolve6(): +async def test_resolve6() -> None: # Run these tests forcing IPv6 resolution prefer_ipv6 = True assert await resolve("::1", prefer_ipv6=prefer_ipv6) == IPAddress.create("::1") diff --git a/chia/_tests/util/test_network_protocol_files.py b/chia/_tests/util/test_network_protocol_files.py index 5066af6e3750..0742e05bb71d 100644 --- a/chia/_tests/util/test_network_protocol_files.py +++ b/chia/_tests/util/test_network_protocol_files.py @@ -1,3 +1,4 @@ +# ruff: noqa: F405 # this file is generated by build_network_protocol_files.py from __future__ import annotations diff --git a/chia/_tests/util/test_network_protocol_json.py b/chia/_tests/util/test_network_protocol_json.py index d68571a3bde9..3acb9240a83e 100644 --- a/chia/_tests/util/test_network_protocol_json.py +++ b/chia/_tests/util/test_network_protocol_json.py @@ -1,3 +1,4 @@ +# ruff: noqa: F405 # this file is generated by build_network_protocol_files.py from __future__ import annotations diff --git a/chia/_tests/util/test_network_protocol_test.py b/chia/_tests/util/test_network_protocol_test.py index d0adb404e7da..32c6319bd4b1 100644 --- a/chia/_tests/util/test_network_protocol_test.py +++ b/chia/_tests/util/test_network_protocol_test.py @@ -1,4 +1,3 @@ -# flake8: noqa from __future__ import annotations import ast @@ -34,18 +33,17 @@ def types_in_module(mod: Any) -> set[str]: return types +STANDARD_ADVICE = "Make sure to update the protocol message regression test to include the new message" + + def test_missing_messages_state_machine() -> None: from chia.protocols.protocol_state_machine import NO_REPLY_EXPECTED, VALID_REPLY_MESSAGE_MAP # if these asserts fail, make sure to add the new network protocol messages # to the visitor in build_network_protocol_files.py and rerun it. Then # update this test - assert ( - len(VALID_REPLY_MESSAGE_MAP) == 26 - ), "A message was added to the protocol state machine. Make sure to update the protocol message regression test to include the new message" - assert ( - len(NO_REPLY_EXPECTED) == 10 - ), "A message was added to the protocol state machine. Make sure to update the protocol message regression test to include the new message" + assert len(VALID_REPLY_MESSAGE_MAP) == 26, f"A message was added to the protocol state machine. {STANDARD_ADVICE}" + assert len(NO_REPLY_EXPECTED) == 10, f"A message was added to the protocol state machine. {STANDARD_ADVICE}" def test_message_ids() -> None: @@ -63,7 +61,8 @@ def test_message_ids() -> None: message_name = entry.targets[0].id if message_id in message_ids: # pragma: no cover raise AssertionError( - f'protocol message ID clash between "{message_name}" and "{message_ids[message_id]}". Value {message_id}' + f'protocol message ID clash between "{message_name}" and "{message_ids[message_id]}". ' + f"Value {message_id}" ) message_ids[message_id] = message_name if message_id < 0 or message_id > 255: # pragma: no cover @@ -226,32 +225,32 @@ def test_missing_messages() -> None: # update this test assert ( types_in_module(wallet_protocol) == wallet_msgs - ), "message types were added or removed from wallet_protocol. Make sure to update the protocol message regression test to include the new message" + ), f"message types were added or removed from wallet_protocol. {STANDARD_ADVICE}" assert ( types_in_module(farmer_protocol) == farmer_msgs - ), "message types were added or removed from farmer_protocol. Make sure to update the protocol message regression test to include the new message" + ), f"message types were added or removed from farmer_protocol. {STANDARD_ADVICE}" assert ( types_in_module(full_node_protocol) == full_node_msgs - ), "message types were added or removed from full_node_protocol. Make sure to update the protocol message regression test to include the new message" + ), f"message types were added or removed from full_node_protocol. {STANDARD_ADVICE}" assert ( types_in_module(harvester_protocol) == harvester_msgs - ), "message types were added or removed from harvester_protocol. Make sure to update the protocol message regression test to include the new message" + ), f"message types were added or removed from harvester_protocol. {STANDARD_ADVICE}" assert ( types_in_module(introducer_protocol) == introducer_msgs - ), "message types were added or removed from introducer_protocol. Make sure to update the protocol message regression test to include the new message" + ), f"message types were added or removed from introducer_protocol. {STANDARD_ADVICE}" assert ( types_in_module(pool_protocol) == pool_msgs - ), "message types were added or removed from pool_protocol. Make sure to update the protocol message regression test to include the new message" + ), f"message types were added or removed from pool_protocol. {STANDARD_ADVICE}" assert ( types_in_module(timelord_protocol) == timelord_msgs - ), "message types were added or removed from timelord_protocol. Make sure to update the protocol message regression test to include the new message" + ), f"message types were added or removed from timelord_protocol. {STANDARD_ADVICE}" assert ( types_in_module(shared_protocol) == shared_msgs - ), "message types were added or removed from shared_protocol. Make sure to update the protocol message regression test to include the new message" + ), f"message types were added or removed from shared_protocol. {STANDARD_ADVICE}" diff --git a/chia/_tests/wallet/cat_wallet/test_cat_wallet.py b/chia/_tests/wallet/cat_wallet/test_cat_wallet.py index 2b0ddc9258d1..85e72df9cc2f 100644 --- a/chia/_tests/wallet/cat_wallet/test_cat_wallet.py +++ b/chia/_tests/wallet/cat_wallet/test_cat_wallet.py @@ -390,7 +390,6 @@ async def test_cat_spend(wallet_environments: WalletTestFramework) -> None: "cat": { "confirmed_wallet_balance": 60, "unconfirmed_wallet_balance": 60, - "pending_coin_removal_count": 0, "spendable_balance": 60, "max_send_amount": 60, "pending_change": 0, @@ -675,7 +674,6 @@ async def test_cat_doesnt_see_eve(wallet_environments: WalletTestFramework) -> N "cat": { "confirmed_wallet_balance": 60, "unconfirmed_wallet_balance": 60, - "pending_coin_removal_count": 0, "spendable_balance": 60, "max_send_amount": 60, "pending_change": 0, @@ -867,7 +865,6 @@ async def test_cat_spend_multiple(wallet_environments: WalletTestFramework) -> N "cat": { "confirmed_wallet_balance": 60, "unconfirmed_wallet_balance": 60, - "pending_coin_removal_count": 0, "spendable_balance": 60, "max_send_amount": 60, "pending_change": 0, @@ -893,7 +890,6 @@ async def test_cat_spend_multiple(wallet_environments: WalletTestFramework) -> N "cat": { "confirmed_wallet_balance": 20, "unconfirmed_wallet_balance": 20, - "pending_coin_removal_count": 0, "spendable_balance": 20, "max_send_amount": 20, "pending_change": 0, @@ -1557,7 +1553,7 @@ async def test_cat_change_detection(wallet_environments: WalletTestFramework) -> ), ], ) - await env.rpc_client.push_tx(PushTX(bytes(eve_spend))) + await env.rpc_client.push_tx(PushTX(eve_spend)) await time_out_assert_not_none(5, full_node_api.full_node.mempool_manager.get_spendbundle, eve_spend.name()) await wallet_environments.process_pending_states( [ @@ -1669,7 +1665,7 @@ async def test_cat_melt_balance(wallet_environments: WalletTestFramework) -> Non ) ], ) - await env.rpc_client.push_tx(PushTX(bytes(spend_to_wallet))) + await env.rpc_client.push_tx(PushTX(spend_to_wallet)) await time_out_assert(10, simulator.tx_id_in_mempool, True, spend_to_wallet.name()) await wallet_environments.process_pending_states( @@ -1721,7 +1717,7 @@ async def test_cat_melt_balance(wallet_environments: WalletTestFramework) -> Non ], ) signed_spend, _ = await env.wallet_state_manager.sign_bundle(new_spend.coin_spends) - await env.rpc_client.push_tx(PushTX(bytes(signed_spend))) + await env.rpc_client.push_tx(PushTX(signed_spend)) await time_out_assert(10, simulator.tx_id_in_mempool, True, signed_spend.name()) await wallet_environments.process_pending_states( diff --git a/chia/_tests/wallet/dao_wallet/test_dao_wallets.py b/chia/_tests/wallet/dao_wallet/test_dao_wallets.py index 790b4195c512..f01d14a4abbb 100644 --- a/chia/_tests/wallet/dao_wallet/test_dao_wallets.py +++ b/chia/_tests/wallet/dao_wallet/test_dao_wallets.py @@ -1626,7 +1626,7 @@ async def test_dao_rpc_api(self_hostname: str, two_wallet_nodes: Any, trusted: A async def test_dao_rpc_client( two_wallet_nodes_services: SimulatorsAndWalletsServices, trusted: bool, self_hostname: str ) -> None: - [full_node_service], wallet_services, bt = two_wallet_nodes_services + [full_node_service], wallet_services, _bt = two_wallet_nodes_services full_node_api = full_node_service._api full_node_server = full_node_api.full_node.server wallet_node_0 = wallet_services[0]._node @@ -2016,7 +2016,7 @@ async def test_dao_rpc_client( async def test_dao_complex_spends( two_wallet_nodes_services: SimulatorsAndWalletsServices, trusted: bool, self_hostname: str ) -> None: - [full_node_service], wallet_services, bt = two_wallet_nodes_services + [full_node_service], wallet_services, _bt = two_wallet_nodes_services full_node_api = full_node_service._api full_node_server = full_node_api.full_node.server wallet_node_0 = wallet_services[0]._node @@ -2617,7 +2617,7 @@ async def test_dao_concurrency(self_hostname: str, three_wallet_nodes: OldSimula async def test_dao_cat_exits( two_wallet_nodes_services: SimulatorsAndWalletsServices, trusted: bool, self_hostname: str ) -> None: - [full_node_service], wallet_services, bt = two_wallet_nodes_services + [full_node_service], wallet_services, _bt = two_wallet_nodes_services full_node_api = full_node_service._api full_node_server = full_node_api.full_node.server wallet_node_0 = wallet_services[0]._node diff --git a/chia/_tests/wallet/db_wallet/test_dl_offers.py b/chia/_tests/wallet/db_wallet/test_dl_offers.py index 49fc5830f920..8ad48cb39e46 100644 --- a/chia/_tests/wallet/db_wallet/test_dl_offers.py +++ b/chia/_tests/wallet/db_wallet/test_dl_offers.py @@ -136,7 +136,7 @@ async def test_dl_offers(wallets_prefarm: Any, trusted: bool) -> None: ] } - [maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( [Offer.from_bytes(offer_maker.offer)] ) async with trade_manager_taker.wallet_state_manager.new_action_scope( @@ -263,7 +263,7 @@ async def test_dl_offer_cancellation(wallets_prefarm: Any, trusted: bool) -> Non addition = bytes32([101] * 32) ROWS.append(addition) - root, proofs = build_merkle_tree(ROWS) + root, _proofs = build_merkle_tree(ROWS) async with trade_manager.wallet_state_manager.new_action_scope(DEFAULT_TX_CONFIG, push=False) as action_scope: success, offer, error = await trade_manager.create_offer_for_ids( @@ -414,7 +414,7 @@ async def test_multiple_dl_offers(wallets_prefarm: Any, trusted: bool) -> None: assert success is True assert offer_maker is not None - [maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( [Offer.from_bytes(offer_maker.offer)] ) async with trade_manager_taker.wallet_state_manager.new_action_scope( diff --git a/chia/_tests/wallet/nft_wallet/test_nft_1_offers.py b/chia/_tests/wallet/nft_wallet/test_nft_1_offers.py index 5dd761983a41..0def17e17585 100644 --- a/chia/_tests/wallet/nft_wallet/test_nft_1_offers.py +++ b/chia/_tests/wallet/nft_wallet/test_nft_1_offers.py @@ -174,7 +174,7 @@ async def test_nft_offer_sell_nft( assert not mempool_not_empty(full_node_api) peer = wallet_node_taker.get_full_node_peer() - [maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) async with trade_manager_taker.wallet_state_manager.new_action_scope( @@ -314,7 +314,7 @@ async def test_nft_offer_request_nft( taker_fee = 1 peer = wallet_node_taker.get_full_node_peer() - [maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) async with trade_manager_taker.wallet_state_manager.new_action_scope( @@ -459,7 +459,7 @@ async def test_nft_offer_sell_did_to_did( taker_fee = 1 peer = wallet_node_taker.get_full_node_peer() - [maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) async with trade_manager_taker.wallet_state_manager.new_action_scope( @@ -643,7 +643,7 @@ async def test_nft_offer_sell_nft_for_cat( taker_fee = 1 peer = wallet_node_taker.get_full_node_peer() - [maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) async with trade_manager_taker.wallet_state_manager.new_action_scope( @@ -832,7 +832,7 @@ async def test_nft_offer_request_nft_for_cat( taker_fee = 1 peer = wallet_node_taker.get_full_node_peer() - [maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_maker.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) async with trade_manager_taker.wallet_state_manager.new_action_scope( @@ -955,7 +955,7 @@ async def test_nft_offer_sell_cancel( offer_did_nft_for_xch = {nft_to_offer_asset_id: -1, wallet_maker.id(): xch_requested} async with trade_manager_maker.wallet_state_manager.new_action_scope(DEFAULT_TX_CONFIG, push=False) as action_scope: - success, trade_make, error = await trade_manager_maker.create_offer_for_ids( + _success, trade_make, _error = await trade_manager_maker.create_offer_for_ids( offer_did_nft_for_xch, action_scope, {}, fee=maker_fee ) @@ -1068,7 +1068,7 @@ async def test_nft_offer_sell_cancel_in_batch( offer_did_nft_for_xch = {nft_to_offer_asset_id: -1, wallet_maker.id(): xch_requested} async with trade_manager_maker.wallet_state_manager.new_action_scope(DEFAULT_TX_CONFIG, push=False) as action_scope: - success, trade_make, error = await trade_manager_maker.create_offer_for_ids( + _success, trade_make, _error = await trade_manager_maker.create_offer_for_ids( offer_did_nft_for_xch, action_scope, {}, fee=maker_fee ) diff --git a/chia/_tests/wallet/nft_wallet/test_nft_offers.py b/chia/_tests/wallet/nft_wallet/test_nft_offers.py index 5a1a4dea61a8..d75765905241 100644 --- a/chia/_tests/wallet/nft_wallet/test_nft_offers.py +++ b/chia/_tests/wallet/nft_wallet/test_nft_offers.py @@ -145,7 +145,7 @@ async def test_nft_offer_with_fee( taker_fee = uint64(1) - [maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) peer = wallet_node_1.get_full_node_peer() @@ -221,7 +221,7 @@ async def test_nft_offer_with_fee( taker_fee = uint64(1) - [maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) async with trade_manager_taker.wallet_state_manager.new_action_scope( @@ -488,7 +488,7 @@ async def test_nft_offer_with_metadata_update( taker_fee = uint64(1) - [maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) peer = wallet_node_1.get_full_node_peer() @@ -665,7 +665,7 @@ async def test_nft_offer_nft_for_cat( taker_fee = uint64(1) - [maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) peer = wallet_node_1.get_full_node_peer() @@ -753,7 +753,7 @@ async def test_nft_offer_nft_for_cat( taker_fee = uint64(1) - [maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) async with trade_manager_taker.wallet_state_manager.new_action_scope( @@ -907,7 +907,7 @@ async def test_nft_offer_nft_for_nft( taker_fee = uint64(1) - [maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( + [_maker_offer], signing_response = await wallet_node_0.wallet_state_manager.sign_offers( [Offer.from_bytes(trade_make.offer)] ) peer = wallet_node_1.get_full_node_peer() diff --git a/chia/_tests/wallet/rpc/test_dl_wallet_rpc.py b/chia/_tests/wallet/rpc/test_dl_wallet_rpc.py index 901f261b4151..ba8fcc226689 100644 --- a/chia/_tests/wallet/rpc/test_dl_wallet_rpc.py +++ b/chia/_tests/wallet/rpc/test_dl_wallet_rpc.py @@ -28,7 +28,7 @@ async def test_wallet_make_transaction( self, two_wallet_nodes_services: SimulatorsAndWalletsServices, trusted: bool, self_hostname: str ) -> None: num_blocks = 5 - [full_node_service], wallet_services, bt = two_wallet_nodes_services + [full_node_service], wallet_services, _bt = two_wallet_nodes_services full_node_api = full_node_service._api full_node_server = full_node_api.full_node.server wallet_node = wallet_services[0]._node @@ -238,7 +238,7 @@ async def is_singleton_generation(rpc_client: WalletRpcClient, lid: bytes32, gen async def test_wallet_dl_verify_proof( self, one_wallet_and_one_simulator_services: SimulatorsAndWalletsServices, trusted: bool, self_hostname: str ) -> None: - [full_node_service], [wallet_service], bt = one_wallet_and_one_simulator_services + [full_node_service], [wallet_service], _bt = one_wallet_and_one_simulator_services full_node_api = full_node_service._api full_node_server = full_node_api.full_node.server wallet_node = wallet_service._node diff --git a/chia/_tests/wallet/rpc/test_wallet_rpc.py b/chia/_tests/wallet/rpc/test_wallet_rpc.py index 6f9a93daa8f3..502257669b06 100644 --- a/chia/_tests/wallet/rpc/test_wallet_rpc.py +++ b/chia/_tests/wallet/rpc/test_wallet_rpc.py @@ -58,6 +58,7 @@ GetTimestampForHeight, LogIn, PushTransactions, + PushTX, SetWalletResyncOnStartup, SplitCoins, SplitCoinsResponse, @@ -433,6 +434,11 @@ async def test_push_transactions(wallet_rpc_environment: WalletRpcTestEnvironmen for tx in resp_client.transactions: assert (await client.get_transaction(transaction_id=tx.name)).confirmed + # Just testing NOT failure here really (parsing) + await client.push_tx(PushTX(spend_bundle)) + resp = await client.fetch("push_tx", {"spend_bundle": bytes(spend_bundle).hex()}) + assert resp["success"] + @pytest.mark.anyio async def test_get_balance(wallet_rpc_environment: WalletRpcTestEnvironment): @@ -1267,7 +1273,7 @@ async def test_offer_endpoints(wallet_rpc_environment: WalletRpcTestEnvironment) } assert advanced_summary == summary - id, valid = await wallet_1_rpc.check_offer_validity(offer) + id, _valid = await wallet_1_rpc.check_offer_validity(offer) assert id == offer.name() all_offers = await wallet_1_rpc.get_all_offers(file_contents=True) diff --git a/chia/_tests/wallet/test_singleton_lifecycle_fast.py b/chia/_tests/wallet/test_singleton_lifecycle_fast.py index 746571466dc7..6f3cdbad00fc 100644 --- a/chia/_tests/wallet/test_singleton_lifecycle_fast.py +++ b/chia/_tests/wallet/test_singleton_lifecycle_fast.py @@ -35,7 +35,7 @@ POOL_REWARD_PREFIX_MAINNET = bytes32.fromhex("ccd5bb71183532bff220ba46c268991a00000000000000000000000000000000") -MAX_BLOCK_COST_CLVM = int(1e18) +MAX_BLOCK_COST_CLVM = 10**18 T = TypeVar("T") diff --git a/chia/_tests/wallet/test_util.py b/chia/_tests/wallet/test_util.py index 5e56f425125c..ff88a669c391 100644 --- a/chia/_tests/wallet/test_util.py +++ b/chia/_tests/wallet/test_util.py @@ -21,6 +21,7 @@ CoinSelectionConfigLoader, TXConfigLoader, ) +from chia.wallet.util.wallet_types import WalletType def test_compute_spend_hints_and_additions() -> None: @@ -175,3 +176,12 @@ def test_lineage_proof_errors() -> None: LineageProof.from_program(Program.to([bytes32([1] * 32)]), [LineageProofField.AMOUNT]) with pytest.raises(ValueError): LineageProof.from_program(Program.to([uint64(0)]), [LineageProofField.PARENT_NAME]) + + +# this is the only test that has coverage for `WalletType.to_json_dict` +# it's possible it could even be deleted + + +def test_wallet_type_to_json() -> None: + for w in WalletType: + assert w.to_json_dict() == w.name diff --git a/chia/_tests/wallet/test_wallet.py b/chia/_tests/wallet/test_wallet.py index df16900081f1..66e08ba08b44 100644 --- a/chia/_tests/wallet/test_wallet.py +++ b/chia/_tests/wallet/test_wallet.py @@ -2135,7 +2135,7 @@ def test_get_wallet_db_path_testnet() -> None: async def test_wallet_has_no_server( simulator_and_wallet: tuple[list[FullNodeSimulator], list[tuple[WalletNode, ChiaServer]], BlockTools], ) -> None: - full_nodes, wallets, bt = simulator_and_wallet - wallet_node, wallet_server = wallets[0] + _full_nodes, wallets, _bt = simulator_and_wallet + _wallet_node, wallet_server = wallets[0] assert wallet_server.webserver is None diff --git a/chia/_tests/wallet/test_wallet_node.py b/chia/_tests/wallet/test_wallet_node.py index be6a4572928d..b72edc14f9dc 100644 --- a/chia/_tests/wallet/test_wallet_node.py +++ b/chia/_tests/wallet/test_wallet_node.py @@ -465,7 +465,7 @@ async def test_unique_puzzle_hash_subscriptions(simulator_and_wallet: OldSimulat async def test_get_balance( simulator_and_wallet: OldSimulatorsAndWallets, self_hostname: str, default_400_blocks: list[FullBlock] ) -> None: - [full_node_api], [(wallet_node, wallet_server)], bt = simulator_and_wallet + [full_node_api], [(wallet_node, wallet_server)], _bt = simulator_and_wallet full_node_server = full_node_api.full_node.server def wallet_synced() -> bool: @@ -720,7 +720,7 @@ async def validate_received_state_from_peer(*args: Any) -> bool: async def test_start_with_multiple_key_types( simulator_and_wallet: OldSimulatorsAndWallets, self_hostname: str, default_400_blocks: list[FullBlock] ) -> None: - [full_node_api], [(wallet_node, wallet_server)], bt = simulator_and_wallet + [_full_node_api], [(wallet_node, _wallet_server)], _bt = simulator_and_wallet async def restart_with_fingerprint(fingerprint: Optional[int]) -> None: wallet_node._close() @@ -753,7 +753,7 @@ async def restart_with_fingerprint(fingerprint: Optional[int]) -> None: async def test_start_with_multiple_keys( simulator_and_wallet: OldSimulatorsAndWallets, self_hostname: str, default_400_blocks: list[FullBlock] ) -> None: - [full_node_api], [(wallet_node, wallet_server)], bt = simulator_and_wallet + [_full_node_api], [(wallet_node, _wallet_server)], _bt = simulator_and_wallet async def restart_with_fingerprint(fingerprint: Optional[int]) -> None: wallet_node._close() diff --git a/chia/_tests/wallet/test_wallet_retry.py b/chia/_tests/wallet/test_wallet_retry.py index e9f7acc8702a..f3c570a5ef3d 100644 --- a/chia/_tests/wallet/test_wallet_retry.py +++ b/chia/_tests/wallet/test_wallet_retry.py @@ -40,7 +40,7 @@ async def test_wallet_tx_retry( self_hostname: str, ) -> None: wait_secs = 20 - nodes, wallets, bt = setup_two_nodes_and_wallet_fast_retry + nodes, wallets, _bt = setup_two_nodes_and_wallet_fast_retry server_1 = nodes[0].full_node.server full_node_1: FullNodeSimulator = nodes[0] wallet_node_1: WalletNode = wallets[0][0] diff --git a/chia/apis.py b/chia/apis.py new file mode 100644 index 000000000000..cbbb9710d18e --- /dev/null +++ b/chia/apis.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from chia.farmer.farmer_api import FarmerAPI +from chia.full_node.full_node_api import FullNodeAPI +from chia.harvester.harvester_api import HarvesterAPI +from chia.introducer.introducer_api import IntroducerAPI +from chia.server.api_protocol import ApiProtocol +from chia.server.outbound_message import NodeType +from chia.timelord.timelord_api import TimelordAPI +from chia.wallet.wallet_node_api import WalletNodeAPI + +ApiProtocolRegistry: dict[NodeType, type[ApiProtocol]] = { + NodeType.FULL_NODE: FullNodeAPI, + NodeType.WALLET: WalletNodeAPI, + NodeType.INTRODUCER: IntroducerAPI, + NodeType.TIMELORD: TimelordAPI, + NodeType.FARMER: FarmerAPI, + NodeType.HARVESTER: HarvesterAPI, +} diff --git a/chia/cmds/beta_funcs.py b/chia/cmds/beta_funcs.py index 9dcd358bff29..2b80410b74d8 100644 --- a/chia/cmds/beta_funcs.py +++ b/chia/cmds/beta_funcs.py @@ -5,7 +5,9 @@ from pathlib import Path from typing import Any, Callable, Optional -from chia.cmds.cmds_util import format_bytes, prompt_yes_no, validate_directory_writable +import click + +from chia.cmds.cmds_util import format_bytes, validate_directory_writable from chia.util.beta_metrics import metrics_log_interval_max, metrics_log_interval_min from chia.util.chia_logging import get_beta_logging_config from chia.util.errors import InvalidPathError @@ -25,11 +27,12 @@ def prompt_beta_warning() -> bool: # The `/ 5` is just a rough estimation for `gzip` being used by the log rotation in beta mode. It was like # 7-10x compressed in example tests with 2MB files. min_space = format_bytes(int(logging_config["log_maxfilesrotation"] * logging_config["log_maxbytesrotation"] / 5)) - return prompt_yes_no( + message = ( f"\nWARNING: Enabling the beta test mode increases disk writes and may lead to {min_space} of " "extra logfiles getting stored on your disk. This should only be done if you are part of the beta test " "program.\n\nDo you really want to enable the beta test mode?" ) + return click.confirm(message, default=None) def prompt_for_beta_path(default_path: Path) -> Path: @@ -40,8 +43,9 @@ def prompt_for_beta_path(default_path: Path) -> Path: f"[{str(default_path)}]:" ) test_path = Path(user_input) if user_input else default_path - if not test_path.is_dir() and prompt_yes_no( - f"\nDirectory {str(test_path)!r} doesn't exist.\n\nDo you want to create it?" + if not test_path.is_dir() and click.confirm( + f"\nDirectory {str(test_path)!r} doesn't exist.\n\nDo you want to create it?", + default=None, ): test_path.mkdir(parents=True) diff --git a/chia/cmds/cmds_util.py b/chia/cmds/cmds_util.py index 7fe2f1c106f3..bae931c60884 100644 --- a/chia/cmds/cmds_util.py +++ b/chia/cmds/cmds_util.py @@ -482,16 +482,6 @@ def format_unit(unit: str, count: int, unit_minutes: int, next_unit: str, next_u return "Unknown" -def prompt_yes_no(prompt: str) -> bool: - while True: - response = str(input(prompt + " (y/n): ")).lower().strip() - ch = response[:1] - if ch == "y": - return True - elif ch == "n": - return False - - def validate_directory_writable(path: Path) -> None: write_test_path = path / ".write_test" try: diff --git a/chia/cmds/data_funcs.py b/chia/cmds/data_funcs.py index 70757ca5ac74..da70886ddea8 100644 --- a/chia/cmds/data_funcs.py +++ b/chia/cmds/data_funcs.py @@ -32,7 +32,7 @@ async def wallet_log_in_cmd( fingerprint: int, root_path: Optional[Path] = None, ) -> None: - async with get_client(rpc_port=rpc_port, fingerprint=fingerprint, root_path=root_path) as (client, _): + async with get_client(rpc_port=rpc_port, fingerprint=fingerprint, root_path=root_path): pass diff --git a/chia/cmds/keys_funcs.py b/chia/cmds/keys_funcs.py index 742a91e5cd08..e8b358b97204 100644 --- a/chia/cmds/keys_funcs.py +++ b/chia/cmds/keys_funcs.py @@ -852,7 +852,7 @@ def prompt_for_fingerprint() -> Optional[int]: while True: print("Choose key:") for i, fp in enumerate(fingerprints): - print(f"{i+1}) {fp}") + print(f"{i + 1}) {fp}") val = None while val is None: val = input("Enter a number to pick or q to quit: ") diff --git a/chia/cmds/param_types.py b/chia/cmds/param_types.py index f51f89c3382f..894129ef817f 100644 --- a/chia/cmds/param_types.py +++ b/chia/cmds/param_types.py @@ -170,7 +170,7 @@ def convert(self, value: Any, param: Optional[click.Parameter], ctx: Optional[cl if not isinstance(value, str): self.fail("Invalid Type, address must be string.", param, ctx) try: - hrp, b32data = bech32_decode(value) + hrp, _b32data = bech32_decode(value) if hrp in ["xch", "txch"]: # I hate having to load the config here addr_type: AddressType = AddressType.XCH expected_prefix = ctx.obj.get("expected_prefix") if ctx else None # attempt to get cached prefix diff --git a/chia/cmds/passphrase_funcs.py b/chia/cmds/passphrase_funcs.py index aaec65e84722..2c87c53446c4 100644 --- a/chia/cmds/passphrase_funcs.py +++ b/chia/cmds/passphrase_funcs.py @@ -8,9 +8,9 @@ from pathlib import Path from typing import Any, Optional +import click import colorama -from chia.cmds.cmds_util import prompt_yes_no from chia.daemon.client import acquire_connection_to_daemon from chia.util.errors import KeychainMaxUnlockAttempts from chia.util.keychain import Keychain, supports_os_passphrase_storage @@ -122,7 +122,7 @@ def prompt_to_save_passphrase() -> bool: colorama.init() print(warning) - save = prompt_yes_no(f"Would you like to save your passphrase to the {location}?") + save = click.confirm(f"Would you like to save your passphrase to the {location}?", default=None) except Exception as e: print(f"Caught exception: {e}") diff --git a/chia/cmds/plotnft_funcs.py b/chia/cmds/plotnft_funcs.py index 8671925b9c66..aa942a7fdb6c 100644 --- a/chia/cmds/plotnft_funcs.py +++ b/chia/cmds/plotnft_funcs.py @@ -200,7 +200,7 @@ async def pprint_all_pool_wallet_state( async def show(wallet_rpc_port: Optional[int], fp: Optional[int], wallet_id_passed_in: Optional[int]) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, _): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): try: async with get_any_service_client(FarmerRpcClient) as (farmer_client, config): address_prefix = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"] diff --git a/chia/cmds/show_funcs.py b/chia/cmds/show_funcs.py index 89a1f3ff8656..ed49055f305e 100644 --- a/chia/cmds/show_funcs.py +++ b/chia/cmds/show_funcs.py @@ -43,7 +43,8 @@ async def print_blockchain_state(node_client: FullNodeRpcClient, config: dict[st sync_current_block = blockchain_state["sync"]["sync_progress_height"] print( f"Current Blockchain Status: Syncing {sync_current_block}/{sync_max_block} " - f"({sync_max_block - sync_current_block} behind). ({sync_current_block*100.0/sync_max_block:2.2f}% synced)" + f"({sync_max_block - sync_current_block} behind). " + f"({sync_current_block * 100.0 / sync_max_block:2.2f}% synced)" ) print("Peak: Hash:", bytes32(peak.header_hash) if peak is not None else "") elif peak is not None: diff --git a/chia/cmds/wallet_funcs.py b/chia/cmds/wallet_funcs.py index da407b33bfa7..439cd134cba8 100644 --- a/chia/cmds/wallet_funcs.py +++ b/chia/cmds/wallet_funcs.py @@ -188,7 +188,7 @@ async def get_transactions( reverse: bool, clawback: bool, ) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, config): if paginate is None: paginate = sys.stdout.isatty() type_filter = ( @@ -367,7 +367,7 @@ async def send( async def get_address(wallet_rpc_port: Optional[int], fp: Optional[int], wallet_id: int, new_address: bool) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): res = await wallet_client.get_next_address(wallet_id, new_address) print(res) @@ -660,7 +660,7 @@ async def get_offers( summaries: bool = False, reverse: bool = False, ) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): file_contents: bool = (filepath is not None) or summaries records: list[TradeRecord] = [] if offer_id is None: @@ -960,7 +960,7 @@ async def create_did_wallet( async def did_set_wallet_name(wallet_rpc_port: Optional[int], fp: Optional[int], wallet_id: int, name: str) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): try: await wallet_client.did_set_wallet_name(wallet_id, name) print(f"Successfully set a new name for DID wallet with id {wallet_id}: {name}") @@ -969,7 +969,7 @@ async def did_set_wallet_name(wallet_rpc_port: Optional[int], fp: Optional[int], async def get_did(wallet_rpc_port: Optional[int], fp: Optional[int], did_wallet_id: int) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): try: response = await wallet_client.get_did_id(did_wallet_id) my_did = response["my_did"] @@ -981,7 +981,7 @@ async def get_did(wallet_rpc_port: Optional[int], fp: Optional[int], did_wallet_ async def get_did_info(wallet_rpc_port: Optional[int], fp: Optional[int], coin_id: str, latest: bool) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): did_padding_length = 23 try: response = await wallet_client.get_did_info(coin_id, latest) @@ -1105,7 +1105,7 @@ async def find_lost_did( recovery_list_hash: Optional[str], num_verification: Optional[int], ) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): try: response = await wallet_client.find_lost_did( coin_id, @@ -1124,7 +1124,7 @@ async def find_lost_did( async def create_nft_wallet( wallet_rpc_port: Optional[int], fp: Optional[int], did_id: Optional[CliAddress] = None, name: Optional[str] = None ) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, _): try: response = await wallet_client.create_new_nft_wallet(did_id.original_address if did_id else None, name) wallet_id = response["wallet_id"] @@ -1377,7 +1377,7 @@ async def set_nft_did( async def get_nft_info(wallet_rpc_port: Optional[int], fp: Optional[int], nft_coin_id: str) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, config): try: response = await wallet_client.get_nft_info(nft_coin_id) nft_info = NFTInfo.from_json_dict(response["nft_info"]) @@ -1453,7 +1453,7 @@ async def send_notification( push: bool, condition_valid_times: ConditionValidTimes, ) -> list[TransactionRecord]: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, _): amount: uint64 = cli_amount.convert_amount(units["chia"]) tx = await wallet_client.send_notification( @@ -1478,7 +1478,7 @@ async def get_notifications( start: Optional[int], end: Optional[int], ) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): if ids is not None: ids = None if len(ids) == 0 else list(ids) response = await wallet_client.get_notifications( @@ -1494,7 +1494,7 @@ async def get_notifications( async def delete_notifications( wallet_rpc_port: Optional[int], fp: Optional[int], ids: Sequence[bytes32], delete_all: bool ) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): if delete_all: print(f"Success: {await wallet_client.delete_notifications()}") else: @@ -1511,7 +1511,7 @@ async def sign_message( did_id: Optional[CliAddress] = None, nft_id: Optional[CliAddress] = None, ) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): if addr_type == AddressType.XCH: if address is None: print("Address is required for XCH address type.") @@ -1605,7 +1605,7 @@ async def mint_vc( async def get_vcs(wallet_rpc_port: Optional[int], fp: Optional[int], start: int, count: int) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, config): vc_records, proofs = await wallet_client.vc_get_list(start, count) print("Proofs:") for hash, proof_dict in proofs.items(): @@ -1672,7 +1672,7 @@ async def spend_vc( async def add_proof_reveal( wallet_rpc_port: Optional[int], fp: Optional[int], proofs: Sequence[str], root_only: bool ) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): if len(proofs) == 0: print("Must specify at least one proof") return @@ -1688,7 +1688,7 @@ async def add_proof_reveal( async def get_proofs_for_root(wallet_rpc_port: Optional[int], fp: Optional[int], proof_hash: str) -> None: - async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, fingerprint, config): + async with get_wallet_client(wallet_rpc_port, fp) as (wallet_client, _, _): proof_dict: dict[str, str] = await wallet_client.vc_get_proofs_for_root(bytes32.from_hexstr(proof_hash)) print("Proofs:") for proof in proof_dict: diff --git a/chia/consensus/block_body_validation.py b/chia/consensus/block_body_validation.py index 796a0699f055..7bc5dbf41eaf 100644 --- a/chia/consensus/block_body_validation.py +++ b/chia/consensus/block_body_validation.py @@ -6,17 +6,16 @@ from dataclasses import dataclass, field from typing import Callable, Optional, Union -from chia_rs import AugSchemeMPL, BLSCache, G1Element, SpendBundleConditions +from chia_rs import AugSchemeMPL, BLSCache, G1Element, SpendBundleConditions, compute_merkle_set_root from chiabip158 import PyBIP158 from chia.consensus.block_record import BlockRecord from chia.consensus.block_rewards import calculate_base_farmer_reward, calculate_pool_reward -from chia.consensus.block_root_validation import validate_block_merkle_roots from chia.consensus.blockchain_interface import BlockRecordsProtocol from chia.consensus.coinbase import create_farmer_coin, create_pool_coin from chia.consensus.constants import ConsensusConstants from chia.full_node.mempool_check_conditions import mempool_check_time_locks -from chia.types.blockchain_format.coin import Coin +from chia.types.blockchain_format.coin import Coin, hash_coin_ids from chia.types.blockchain_format.sized_bytes import bytes32 from chia.types.coin_record import CoinRecord from chia.types.full_block import FullBlock @@ -149,6 +148,38 @@ def rollback(self, header_hash: bytes32, height: int) -> None: self.removals_since_fork = {k: v for k, v in self.removals_since_fork.items() if v.height <= height} +def validate_block_merkle_roots( + block_additions_root: bytes32, + block_removals_root: bytes32, + tx_additions: list[tuple[Coin, bytes32]], + tx_removals: list[bytes32], +) -> Optional[Err]: + # Create addition Merkle set + puzzlehash_coins_map: dict[bytes32, list[bytes32]] = {} + + for coin, coin_name in tx_additions: + if coin.puzzle_hash in puzzlehash_coins_map: + puzzlehash_coins_map[coin.puzzle_hash].append(coin_name) + else: + puzzlehash_coins_map[coin.puzzle_hash] = [coin_name] + + # Addition Merkle set contains puzzlehash and hash of all coins with that puzzlehash + additions_merkle_items: list[bytes32] = [] + for puzzle, coin_ids in puzzlehash_coins_map.items(): + additions_merkle_items.append(puzzle) + additions_merkle_items.append(hash_coin_ids(coin_ids)) + + additions_root = bytes32(compute_merkle_set_root(additions_merkle_items)) + removals_root = bytes32(compute_merkle_set_root(tx_removals)) + + if block_additions_root != additions_root: + return Err.BAD_ADDITION_ROOT + if block_removals_root != removals_root: + return Err.BAD_REMOVAL_ROOT + + return None + + async def validate_block_body( constants: ConsensusConstants, records: BlockRecordsProtocol, diff --git a/chia/consensus/block_root_validation.py b/chia/consensus/block_root_validation.py deleted file mode 100644 index cdda927f3611..000000000000 --- a/chia/consensus/block_root_validation.py +++ /dev/null @@ -1,41 +0,0 @@ -from __future__ import annotations - -from typing import Optional - -from chia_rs import compute_merkle_set_root - -from chia.types.blockchain_format.coin import Coin, hash_coin_ids -from chia.types.blockchain_format.sized_bytes import bytes32 -from chia.util.errors import Err - - -def validate_block_merkle_roots( - block_additions_root: bytes32, - block_removals_root: bytes32, - tx_additions: list[tuple[Coin, bytes32]], - tx_removals: list[bytes32], -) -> Optional[Err]: - # Create addition Merkle set - puzzlehash_coins_map: dict[bytes32, list[bytes32]] = {} - - for coin, coin_name in tx_additions: - if coin.puzzle_hash in puzzlehash_coins_map: - puzzlehash_coins_map[coin.puzzle_hash].append(coin_name) - else: - puzzlehash_coins_map[coin.puzzle_hash] = [coin_name] - - # Addition Merkle set contains puzzlehash and hash of all coins with that puzzlehash - additions_merkle_items: list[bytes32] = [] - for puzzle, coin_ids in puzzlehash_coins_map.items(): - additions_merkle_items.append(puzzle) - additions_merkle_items.append(hash_coin_ids(coin_ids)) - - additions_root = bytes32(compute_merkle_set_root(additions_merkle_items)) - removals_root = bytes32(compute_merkle_set_root(tx_removals)) - - if block_additions_root != additions_root: - return Err.BAD_ADDITION_ROOT - if block_removals_root != removals_root: - return Err.BAD_REMOVAL_ROOT - - return None diff --git a/chia/daemon/server.py b/chia/daemon/server.py index 6b6991bb3998..d04d37a00f6c 100644 --- a/chia/daemon/server.py +++ b/chia/daemon/server.py @@ -1104,7 +1104,7 @@ async def _start_plotting(self, id: str, loop: asyncio.AbstractEventLoop, queue: self.log.debug(f"command_args before launch_plotter are {command_args}") self.log.debug(f"self.root_path before launch_plotter is {self.root_path}") - process, pid_path = launch_plotter(self.root_path, service_name, command_args, id) + process, _pid_path = launch_plotter(self.root_path, service_name, command_args, id) current_process = process @@ -1285,7 +1285,7 @@ async def start_service(self, websocket: WebSocketResponse, request: dict[str, A exe_command = service_command if testing is True: exe_command = f"{service_command} --testing=true" - process, pid_path = launch_service(self.root_path, exe_command) + process, _pid_path = launch_service(self.root_path, exe_command) self.services[service_command] = [process] success = True except (subprocess.SubprocessError, OSError): diff --git a/chia/data_layer/data_layer_api.py b/chia/data_layer/data_layer_api.py index b772906d17d9..0e355ead205b 100644 --- a/chia/data_layer/data_layer_api.py +++ b/chia/data_layer/data_layer_api.py @@ -1,12 +1,18 @@ from __future__ import annotations import logging +from typing import TYPE_CHECKING, ClassVar, cast from chia.data_layer.data_layer import DataLayer from chia.server.server import ChiaServer class DataLayerAPI: + if TYPE_CHECKING: + from chia.server.api_protocol import ApiProtocol + + _protocol_check: ClassVar[ApiProtocol] = cast("DataLayerAPI", None) + log: logging.Logger data_layer: DataLayer diff --git a/chia/farmer/farmer_api.py b/chia/farmer/farmer_api.py index b6796148cf43..0f631938266f 100644 --- a/chia/farmer/farmer_api.py +++ b/chia/farmer/farmer_api.py @@ -3,7 +3,7 @@ import json import logging import time -from typing import Any, Optional, Union +from typing import TYPE_CHECKING, Any, ClassVar, Optional, Union, cast import aiohttp from chia_rs import AugSchemeMPL, G2Element, PrivateKey @@ -48,6 +48,11 @@ class FarmerAPI: + if TYPE_CHECKING: + from chia.server.api_protocol import ApiProtocol + + _protocol_check: ClassVar[ApiProtocol] = cast("FarmerAPI", None) + log: logging.Logger farmer: Farmer diff --git a/chia/full_node/block_height_map.py b/chia/full_node/block_height_map.py index 1ef90473afcc..bd9875237988 100644 --- a/chia/full_node/block_height_map.py +++ b/chia/full_node/block_height_map.py @@ -124,7 +124,7 @@ async def create(cls, blockchain_dir: Path, db: DBWrapper2) -> BlockHeightMap: log.info( f"Loaded sub-epoch-summaries: {len(self.__sub_epoch_summaries)} " - f"height-to-hash: {len(self.__height_to_hash)//32}" + f"height-to-hash: {len(self.__height_to_hash) // 32}" ) # prepopulate the height -> hash mapping diff --git a/chia/full_node/full_node.py b/chia/full_node/full_node.py index 10d58f82f89b..7fed92b95143 100644 --- a/chia/full_node/full_node.py +++ b/chia/full_node/full_node.py @@ -86,6 +86,7 @@ from chia.util.errors import ConsensusError, Err, TimestampError, ValidationError from chia.util.ints import uint8, uint32, uint64, uint128 from chia.util.limited_semaphore import LimitedSemaphore +from chia.util.network import is_localhost from chia.util.path import path_from_root from chia.util.profiler import enable_profiler, mem_profile_task, profile_task from chia.util.safe_cancel_task import cancel_task_safe @@ -609,7 +610,7 @@ async def short_sync_batch(self, peer: WSChiaConnection, start_height: uint32, t self.constants, new_slot, prev_b, self.blockchain ) vs = ValidationState(ssi, diff, None) - success, state_change_summary, err = await self.add_block_batch( + success, state_change_summary, _err = await self.add_block_batch( AugmentedBlockchain(self.blockchain), response.blocks, peer_info, fork_info, vs ) if not success: @@ -950,7 +951,7 @@ async def _sync(self) -> None: # Wait until we have 3 peaks or up to a max of 30 seconds max_iterations = int(self.config.get("max_sync_wait", 30)) * 10 - self.log.info(f"Waiting to receive peaks from peers. (timeout: {max_iterations/10}s)") + self.log.info(f"Waiting to receive peaks from peers. (timeout: {max_iterations / 10}s)") peaks = [] for i in range(max_iterations): peaks = [peak.header_hash for peak in self.sync_store.get_peak_of_each_peer().values()] @@ -1124,8 +1125,28 @@ async def sync_from_fork_point( blockchain = AugmentedBlockchain(self.blockchain) async def fetch_blocks(output_queue: asyncio.Queue[Optional[tuple[WSChiaConnection, list[FullBlock]]]]) -> None: + # the rate limit for respond_blocks is 100 messages / 60 seconds. + # But the limit is scaled to 30% for outbound messages, so that's 30 + # messages per 60 seconds. + # That's 2 seconds per request. + seconds_per_request = 2 start_height, end_height = 0, 0 - new_peers_with_peak: list[WSChiaConnection] = peers_with_peak[:] + + # the timestamp of when the next request_block message is allowed to + # be sent. It's initialized to the current time, and bumped by the + # seconds_per_request every time we send a request. This ensures we + # won't exceed the 100 requests / 60 seconds rate limit. + # Whichever peer has the lowest timestamp is the one we request + # from. peers that take more than 5 seconds to respond are pushed to + # the end of the queue, to be less likely to request from. + + # This should be cleaned up to not be a hard coded value, and maybe + # allow higher request rates (and align the request_blocks and + # respond_blocks rate limits). + now = time.monotonic() + new_peers_with_peak: list[tuple[WSChiaConnection, float]] = [(c, now) for c in peers_with_peak[:]] + self.log.info(f"peers with peak: {len(new_peers_with_peak)}") + random.shuffle(new_peers_with_peak) try: # block request ranges are *inclusive*, this requires some # gymnastics of this range (+1 to make it exclusive, like normal @@ -1133,24 +1154,61 @@ async def fetch_blocks(output_queue: asyncio.Queue[Optional[tuple[WSChiaConnecti for start_height in range(fork_point_height, target_peak_sb_height + 1, batch_size): end_height = min(target_peak_sb_height, start_height + batch_size - 1) request = RequestBlocks(uint32(start_height), uint32(end_height), True) + new_peers_with_peak.sort(key=lambda pair: pair[1]) fetched = False - for peer in random.sample(new_peers_with_peak, len(new_peers_with_peak)): + for idx, (peer, timestamp) in enumerate(new_peers_with_peak): if peer.closed: continue + start = time.monotonic() + if start < timestamp: + # rate limit ourselves, since we sent a message to + # this peer too recently + await asyncio.sleep(timestamp - start) + start = time.monotonic() + + # update the timestamp, now that we're sending a request + # it's OK for the timestamp to fall behind wall-clock + # time. It just means we're allowed to send more + # requests to catch up + if is_localhost(peer.peer_info.host): + # we don't apply rate limits to localhost, and our + # tests depend on it + bump = 0.1 + else: + bump = seconds_per_request + + new_peers_with_peak[idx] = ( + new_peers_with_peak[idx][0], + new_peers_with_peak[idx][1] + bump, + ) response = await peer.call_api(FullNodeAPI.request_blocks, request, timeout=30) end = time.monotonic() if end - start > 5: - self.log.info(f"sync pipeline, peer took {end-start:0.2f} to respond to request_blocks") + self.log.info(f"sync pipeline, peer took {end - start:0.2f} to respond to request_blocks") if response is None: + self.log.info(f"peer timed out after {end - start:.1f} s") await peer.close() elif isinstance(response, RespondBlocks): + if end - start > 5: + self.log.info(f"peer took {end - start:.1f} s to respond to request_blocks") + # this isn't a great peer, reduce its priority + # to prefer any peers that had to wait for it. + # By setting the next allowed timestamp to now, + # means that any other peer that has waited for + # this will have its next allowed timestamp in + # the passed, and be prefered multiple times + # over this peer. + new_peers_with_peak[idx] = ( + new_peers_with_peak[idx][0], + end, + ) start = time.monotonic() await output_queue.put((peer, response.blocks)) end = time.monotonic() if end - start > 1: self.log.info( - f"sync pipeline back-pressure. stalled {end-start:0.2f} " + f"sync pipeline back-pressure. stalled {end - start:0.2f} " "seconds on prevalidate block" ) fetched = True @@ -1159,8 +1217,12 @@ async def fetch_blocks(output_queue: asyncio.Queue[Optional[tuple[WSChiaConnecti self.log.error(f"failed fetching {start_height} to {end_height} from peers") return if self.sync_store.peers_changed.is_set(): - new_peers_with_peak = self.get_peers_with_peak(peak_hash) + existing_peers = {id(c): timestamp for c, timestamp in new_peers_with_peak} + peers = self.get_peers_with_peak(peak_hash) + new_peers_with_peak = [(c, existing_peers.get(id(c), end)) for c in peers] + random.shuffle(new_peers_with_peak) self.sync_store.peers_changed.clear() + self.log.info(f"peers with peak: {len(new_peers_with_peak)}") except Exception as e: self.log.error(f"Exception fetching {start_height} to {end_height} from peer {e}") finally: @@ -1217,7 +1279,7 @@ async def validate_blocks( await output_queue.put((peer, next_validation_state, list(futures), blocks_to_validate)) end = time.monotonic() if end - start > 1: - self.log.info(f"sync pipeline back-pressure. stalled {end-start:0.2f} seconds on add_block()") + self.log.info(f"sync pipeline back-pressure. stalled {end - start:0.2f} seconds on add_block()") except Exception: self.log.exception("Exception validating") finally: @@ -1267,7 +1329,9 @@ async def ingest_blocks( block_rate_time = now block_rate_height = end_height - self.log.info(f"Added blocks {start_height} to {end_height} ({block_rate} blocks/s)") + self.log.info( + f"Added blocks {start_height} to {end_height} ({block_rate} blocks/s) (from: {peer.peer_info.ip})" + ) peak: Optional[BlockRecord] = self.blockchain.get_peak() if state_change_summary is not None: assert peak is not None @@ -2080,7 +2144,7 @@ async def add_block( logging.WARNING if validation_time > 2 else logging.DEBUG, f"Block validation: {validation_time:0.2f}s, " f"pre_validation: {pre_validation_time:0.2f}s, " - f"CLVM: {pre_validation_results[0].timing/1000.0:0.2f}s, " + f"CLVM: {pre_validation_results[0].timing / 1000.0:0.2f}s, " f"post-process: {post_process_time:0.2f}s, " f"cost: {block.transactions_info.cost if block.transactions_info is not None else 'None'}" f"{percent_full_str} header_hash: {header_hash.hex()} height: {block.height}", diff --git a/chia/full_node/full_node_api.py b/chia/full_node/full_node_api.py index 55f5b2301f99..d4e651cd60d3 100644 --- a/chia/full_node/full_node_api.py +++ b/chia/full_node/full_node_api.py @@ -6,7 +6,7 @@ import traceback from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone -from typing import TYPE_CHECKING, Optional, cast +from typing import TYPE_CHECKING, ClassVar, Optional, cast import anyio from chia_rs import ( @@ -80,6 +80,11 @@ class FullNodeAPI: + if TYPE_CHECKING: + from chia.server.api_protocol import ApiProtocol + + _protocol_check: ClassVar[ApiProtocol] = cast("FullNodeAPI", None) + log: logging.Logger full_node: FullNode executor: ThreadPoolExecutor diff --git a/chia/full_node/full_node_store.py b/chia/full_node/full_node_store.py index 3f77f5f4f7a1..f08f5b783e5c 100644 --- a/chia/full_node/full_node_store.py +++ b/chia/full_node/full_node_store.py @@ -268,7 +268,7 @@ def get_unfinished_block(self, unfinished_reward_hash: bytes32) -> Optional[Unfi # deterministic property. # this sorts the UnfinishedBlocks by the foliage hash, and picks the # smallest hash - foliage_hash, block = find_best_block(result) + _foliage_hash, block = find_best_block(result) return block def get_unfinished_block2( diff --git a/chia/full_node/mempool_check_conditions.py b/chia/full_node/mempool_check_conditions.py index fd37f0b9f158..e12bb407ae83 100644 --- a/chia/full_node/mempool_check_conditions.py +++ b/chia/full_node/mempool_check_conditions.py @@ -3,9 +3,16 @@ import logging from typing import Optional -from chia_rs import DONT_VALIDATE_SIGNATURE, MEMPOOL_MODE, G2Element, get_flags_for_height_and_constants +from chia_rs import ( + DONT_VALIDATE_SIGNATURE, + MEMPOOL_MODE, + G2Element, + get_flags_for_height_and_constants, + run_block_generator, + run_block_generator2, + run_chia_program, +) from chia_rs import get_puzzle_and_solution_for_coin2 as get_puzzle_and_solution_for_coin_rust -from chia_rs import run_block_generator, run_block_generator2, run_chia_program from chia.consensus.constants import ConsensusConstants from chia.consensus.cost_calculator import NPCResult diff --git a/chia/full_node/mempool_manager.py b/chia/full_node/mempool_manager.py index ad73c40b8582..6a627c08cb94 100644 --- a/chia/full_node/mempool_manager.py +++ b/chia/full_node/mempool_manager.py @@ -581,7 +581,7 @@ async def validate_spend_bundle( log.log( logging.DEBUG if duration < 2 else logging.WARNING, f"add_spendbundle {spend_name} took {duration:0.2f} seconds. " - f"Cost: {cost} ({round(100.0 * cost/self.constants.MAX_BLOCK_COST_CLVM, 3)}% of max block cost)", + f"Cost: {cost} ({round(100.0 * cost / self.constants.MAX_BLOCK_COST_CLVM, 3)}% of max block cost)", ) return None, potential, [item.name for item in conflicts] diff --git a/chia/full_node/weight_proof.py b/chia/full_node/weight_proof.py index 1f03af771efb..4c8f195f310f 100644 --- a/chia/full_node/weight_proof.py +++ b/chia/full_node/weight_proof.py @@ -881,7 +881,7 @@ def _map_sub_epoch_summaries( delta = 0 if idx > 0: delta = sub_epoch_data[idx].num_blocks_overflow - log.debug(f"sub epoch {idx} start weight is {total_weight+curr_difficulty} ") + log.debug(f"sub epoch {idx} start weight is {total_weight + curr_difficulty} ") sub_epoch_weight_list.append(uint128(total_weight + curr_difficulty)) total_weight = uint128( total_weight diff --git a/chia/harvester/harvester_api.py b/chia/harvester/harvester_api.py index 2631aac8281f..42bd85d1fa8d 100644 --- a/chia/harvester/harvester_api.py +++ b/chia/harvester/harvester_api.py @@ -4,7 +4,7 @@ import logging import time from pathlib import Path -from typing import Optional +from typing import TYPE_CHECKING, ClassVar, Optional, cast from chia_rs import AugSchemeMPL, G1Element, G2Element @@ -30,6 +30,11 @@ class HarvesterAPI: + if TYPE_CHECKING: + from chia.server.api_protocol import ApiProtocol + + _protocol_check: ClassVar[ApiProtocol] = cast("HarvesterAPI", None) + log: logging.Logger harvester: Harvester diff --git a/chia/introducer/introducer.py b/chia/introducer/introducer.py index d2142ef5ca26..11bad7e6140b 100644 --- a/chia/introducer/introducer.py +++ b/chia/introducer/introducer.py @@ -100,7 +100,7 @@ async def _vetting_loop(self): peer.last_attempt = uint64(time.time()) self.log.info(f"Vetting peer {peer.host} {peer.port}") - r, w = await asyncio.wait_for( + _r, w = await asyncio.wait_for( asyncio.open_connection(peer.host, int(peer.port)), timeout=3, ) diff --git a/chia/introducer/introducer_api.py b/chia/introducer/introducer_api.py index 44067bb30c8b..6021b3280fe1 100644 --- a/chia/introducer/introducer_api.py +++ b/chia/introducer/introducer_api.py @@ -1,7 +1,7 @@ from __future__ import annotations import logging -from typing import Optional +from typing import TYPE_CHECKING, ClassVar, Optional, cast from chia.introducer.introducer import Introducer from chia.protocols.introducer_protocol import RequestPeersIntroducer, RespondPeersIntroducer @@ -15,6 +15,11 @@ class IntroducerAPI: + if TYPE_CHECKING: + from chia.server.api_protocol import ApiProtocol + + _protocol_check: ClassVar[ApiProtocol] = cast("IntroducerAPI", None) + log: logging.Logger introducer: Introducer diff --git a/chia/legacy/keyring.py b/chia/legacy/keyring.py index eeaafa541957..cf1b41a68df4 100644 --- a/chia/legacy/keyring.py +++ b/chia/legacy/keyring.py @@ -23,7 +23,6 @@ CryptFileKeyring = None -from chia.cmds.cmds_util import prompt_yes_no from chia.util.errors import KeychainUserNotFound from chia.util.keychain import MAX_KEYS, KeyData, KeyDataSecrets, KeyTypes, get_private_key_user @@ -146,7 +145,9 @@ def clear() -> None: print_keys(keyring) - if not prompt_yes_no("\nDo you really want to remove all the keys from the legacy keyring? This can't be undone."): + if not click.confirm( + "\nDo you really want to remove all the keys from the legacy keyring? This can't be undone.", default=None + ): raise click.ClickException("Aborted!") remove_keys(keyring) diff --git a/chia/plotters/madmax.py b/chia/plotters/madmax.py index fb5e49c068b8..8ad8de27543f 100644 --- a/chia/plotters/madmax.py +++ b/chia/plotters/madmax.py @@ -160,7 +160,7 @@ def plot_madmax(args, chia_root_path: Path, plotters_root_path: Path): # madMAx has a ulimit -n requirement > 296: # "Cannot open at least 296 files, please raise maximum open file limit in OS." - soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE) + _soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE) # Set soft limit to max (hard limit) resource.setrlimit(resource.RLIMIT_NOFILE, (hard_limit, hard_limit)) else: diff --git a/chia/plotting/check_plots.py b/chia/plotting/check_plots.py index a3e9a69f12b1..4f999a691e2d 100644 --- a/chia/plotting/check_plots.py +++ b/chia/plotting/check_plots.py @@ -148,7 +148,7 @@ def process_plot(plot_path: Path, plot_info: PlotInfo, num_start: int, num_end: # Look up local_sk from plot to save locked memory ( - pool_public_key_or_puzzle_hash, + _pool_public_key_or_puzzle_hash, farmer_public_key, local_master_sk, ) = parse_plot_info(pr.get_memo()) @@ -161,8 +161,8 @@ def process_plot(plot_path: Path, plot_info: PlotInfo, num_start: int, num_end: if plot_info.pool_contract_puzzle_hash is not None: pca: str = encode_puzzle_hash(plot_info.pool_contract_puzzle_hash, address_prefix) log.info(f"\t{'Pool contract address:':<23} {pca}") - log.info(f"\t{'Farmer public key:' :<23} {farmer_public_key}") - log.info(f"\t{'Local sk:' :<23} {local_sk}") + log.info(f"\t{'Farmer public key:':<23} {farmer_public_key}") + log.info(f"\t{'Local sk:':<23} {local_sk}") total_proofs = 0 caught_exception: bool = False @@ -229,14 +229,14 @@ def process_plot(plot_path: Path, plot_info: PlotInfo, num_start: int, num_end: if total_proofs > 0 and caught_exception is False: log.info( - f"\tProofs {total_proofs} / {challenges}, {round(total_proofs/float(challenges), 4)}. " + f"\tProofs {total_proofs} / {challenges}, {round(total_proofs / float(challenges), 4)}. " f"Filepath: {plot_path}" ) total_good_plots[pr.get_size()] += 1 total_size += plot_path.stat().st_size else: log.error( - f"\tProofs {total_proofs} / {challenges}, {round(total_proofs/float(challenges), 4)} " + f"\tProofs {total_proofs} / {challenges}, {round(total_proofs / float(challenges), 4)} " f"Filepath: {plot_path}" ) bad_plots_list.append(plot_path) diff --git a/chia/plotting/manager.py b/chia/plotting/manager.py index 89990cb3a036..cb7ce2872434 100644 --- a/chia/plotting/manager.py +++ b/chia/plotting/manager.py @@ -310,7 +310,7 @@ def process_file(file_path: Path) -> Optional[PlotInfo]: entry: Optional[tuple[str, set[str]]] = self.plot_filename_paths.get(file_path.name) if entry is not None: - loaded_parent, duplicates = entry + _loaded_parent, duplicates = entry if str(file_path.parent) in duplicates: log.debug(f"Skip duplicated plot {str(file_path)}") return None diff --git a/chia/pools/pool_puzzles.py b/chia/pools/pool_puzzles.py index d2d6fd242814..8c9844d6f113 100644 --- a/chia/pools/pool_puzzles.py +++ b/chia/pools/pool_puzzles.py @@ -143,7 +143,7 @@ def get_template_singleton_inner_puzzle(inner_puzzle: Program) -> Program: r = inner_puzzle.uncurry() if r is None: return False - uncurried_inner_puzzle, args = r + uncurried_inner_puzzle, _args = r return uncurried_inner_puzzle @@ -362,9 +362,9 @@ def uncurry_pool_waitingroom_inner_puzzle(inner_puzzle: Program) -> tuple[Progra r = inner_puzzle.uncurry() if r is None: raise ValueError("Failed to unpack inner puzzle") - inner_f, args = r + _inner_f, args = r v = args.as_iter() - target_puzzle_hash, p2_singleton_hash, owner_pubkey, genesis_challenge, relative_lock_height = tuple(v) + target_puzzle_hash, p2_singleton_hash, owner_pubkey, _genesis_challenge, relative_lock_height = tuple(v) return target_puzzle_hash, relative_lock_height, owner_pubkey, p2_singleton_hash diff --git a/chia/pools/pool_wallet.py b/chia/pools/pool_wallet.py index 670827db0b87..87bfca1fc699 100644 --- a/chia/pools/pool_wallet.py +++ b/chia/pools/pool_wallet.py @@ -420,7 +420,7 @@ async def create_new_pool_wallet_transaction( # Verify Parameters - raise if invalid PoolWallet._verify_initial_target_state(initial_target_state) - singleton_puzzle_hash, launcher_coin_id = await PoolWallet.generate_launcher_spend( + _singleton_puzzle_hash, launcher_coin_id = await PoolWallet.generate_launcher_spend( standard_wallet, uint64(1), fee, @@ -517,19 +517,19 @@ async def generate_travel_transactions(self, fee: uint64, action_scope: WalletAc assert new_inner_puzzle != inner_puzzle if is_pool_member_inner_puzzle(inner_puzzle): ( - inner_f, - target_puzzle_hash, - p2_singleton_hash, - pubkey_as_program, - pool_reward_prefix, - escape_puzzle_hash, + _inner_f, + _target_puzzle_hash, + _p2_singleton_hash, + _pubkey_as_program, + _pool_reward_prefix, + _escape_puzzle_hash, ) = uncurry_pool_member_inner_puzzle(inner_puzzle) elif is_pool_waitingroom_inner_puzzle(inner_puzzle): ( - target_puzzle_hash, # payout_puzzle_hash - relative_lock_height, - pubkey_as_program, - p2_singleton_hash, + _target_puzzle_hash, # payout_puzzle_hash + _relative_lock_height, + _pubkey_as_program, + _p2_singleton_hash, ) = uncurry_pool_waitingroom_inner_puzzle(inner_puzzle) else: raise RuntimeError("Invalid state") diff --git a/chia/rpc/crawler_rpc_api.py b/chia/rpc/crawler_rpc_api.py index 3d7ff0aee842..eb55c23841af 100644 --- a/chia/rpc/crawler_rpc_api.py +++ b/chia/rpc/crawler_rpc_api.py @@ -1,7 +1,7 @@ from __future__ import annotations import ipaddress -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, ClassVar, Optional, cast from chia.rpc.rpc_server import Endpoint, EndpointResult from chia.seeder.crawler import Crawler @@ -9,6 +9,11 @@ class CrawlerRpcApi: + if TYPE_CHECKING: + from chia.rpc.rpc_server import RpcApiProtocol + + _protocol_check: ClassVar[RpcApiProtocol] = cast("CrawlerRpcApi", None) + def __init__(self, crawler: Crawler): self.service = crawler self.service_name = "chia_crawler" diff --git a/chia/rpc/data_layer_rpc_api.py b/chia/rpc/data_layer_rpc_api.py index dbd93a18916b..4f0f985edee6 100644 --- a/chia/rpc/data_layer_rpc_api.py +++ b/chia/rpc/data_layer_rpc_api.py @@ -2,7 +2,7 @@ import dataclasses from pathlib import Path -from typing import TYPE_CHECKING, Any, Optional, Union, cast +from typing import TYPE_CHECKING, Any, ClassVar, Optional, Union, cast from chia.data_layer.data_layer_errors import OfferIntegrityError from chia.data_layer.data_layer_util import ( @@ -89,6 +89,11 @@ def get_fee(config: dict[str, Any], request: dict[str, Any]) -> uint64: class DataLayerRpcApi: + if TYPE_CHECKING: + from chia.rpc.rpc_server import RpcApiProtocol + + _protocol_check: ClassVar[RpcApiProtocol] = cast("DataLayerRpcApi", None) + # TODO: other RPC APIs do not accept a wallet and the service start does not expect to provide one def __init__(self, data_layer: DataLayer): # , wallet: DataLayerWallet): self.service: DataLayer = data_layer diff --git a/chia/rpc/farmer_rpc_api.py b/chia/rpc/farmer_rpc_api.py index 3e608080b89b..722faa6b1b8c 100644 --- a/chia/rpc/farmer_rpc_api.py +++ b/chia/rpc/farmer_rpc_api.py @@ -2,7 +2,7 @@ import dataclasses import operator -from typing import Any, Callable, ClassVar, Optional +from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional, cast from typing_extensions import Protocol @@ -78,6 +78,11 @@ def plot_matches_filter(plot: Plot, filter_item: FilterItem) -> bool: class FarmerRpcApi: + if TYPE_CHECKING: + from chia.rpc.rpc_server import RpcApiProtocol + + _protocol_check: ClassVar[RpcApiProtocol] = cast("FarmerRpcApi", None) + def __init__(self, farmer: Farmer): self.service = farmer self.service_name = "chia_farmer" diff --git a/chia/rpc/full_node_rpc_api.py b/chia/rpc/full_node_rpc_api.py index 8f413ad02bb1..10087338357e 100644 --- a/chia/rpc/full_node_rpc_api.py +++ b/chia/rpc/full_node_rpc_api.py @@ -1,7 +1,7 @@ from __future__ import annotations from datetime import datetime, timezone -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, ClassVar, Optional, cast from chia.consensus.block_record import BlockRecord from chia.consensus.blockchain import Blockchain, BlockchainMutexPriority @@ -82,6 +82,11 @@ async def get_average_block_time( class FullNodeRpcApi: + if TYPE_CHECKING: + from chia.rpc.rpc_server import RpcApiProtocol + + _protocol_check: ClassVar[RpcApiProtocol] = cast("FullNodeRpcApi", None) + def __init__(self, service: FullNode) -> None: self.service = service self.service_name = "chia_full_node" diff --git a/chia/rpc/harvester_rpc_api.py b/chia/rpc/harvester_rpc_api.py index 8da6cfe12795..c54d0712287d 100644 --- a/chia/rpc/harvester_rpc_api.py +++ b/chia/rpc/harvester_rpc_api.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, ClassVar, Optional, cast from chia.harvester.harvester import Harvester from chia.rpc.rpc_server import Endpoint, EndpointResult @@ -9,6 +9,11 @@ class HarvesterRpcApi: + if TYPE_CHECKING: + from chia.rpc.rpc_server import RpcApiProtocol + + _protocol_check: ClassVar[RpcApiProtocol] = cast("HarvesterRpcApi", None) + def __init__(self, harvester: Harvester): self.service = harvester self.service_name = "chia_harvester" diff --git a/chia/rpc/timelord_rpc_api.py b/chia/rpc/timelord_rpc_api.py index 62b99ed1e696..4141fe962679 100644 --- a/chia/rpc/timelord_rpc_api.py +++ b/chia/rpc/timelord_rpc_api.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, ClassVar, Optional, cast from chia.rpc.rpc_server import Endpoint from chia.timelord.timelord import Timelord @@ -8,6 +8,11 @@ class TimelordRpcApi: + if TYPE_CHECKING: + from chia.rpc.rpc_server import RpcApiProtocol + + _protocol_check: ClassVar[RpcApiProtocol] = cast("TimelordRpcApi", None) + def __init__(self, timelord: Timelord): self.service = timelord self.service_name = "chia_timelord" diff --git a/chia/rpc/wallet_request_types.py b/chia/rpc/wallet_request_types.py index 74649ca0e9c8..29c44c29d22b 100644 --- a/chia/rpc/wallet_request_types.py +++ b/chia/rpc/wallet_request_types.py @@ -180,7 +180,18 @@ class GetHeightInfoResponse(Streamable): @streamable @dataclass(frozen=True) class PushTX(Streamable): - spend_bundle: bytes + spend_bundle: WalletSpendBundle + + # We allow for flexibility in transaction parsing here so we need to override + @classmethod + def from_json_dict(cls, json_dict: dict[str, Any]) -> PushTX: + if isinstance(json_dict["spend_bundle"], str): + spend_bundle = WalletSpendBundle.from_bytes(hexstr_to_bytes(json_dict["spend_bundle"])) + else: + spend_bundle = WalletSpendBundle.from_json_dict(json_dict["spend_bundle"]) + + json_dict["spend_bundle"] = spend_bundle.to_json_dict() + return super().from_json_dict(json_dict) @streamable diff --git a/chia/rpc/wallet_rpc_api.py b/chia/rpc/wallet_rpc_api.py index 5839aa1e6f39..c1dda8ebf338 100644 --- a/chia/rpc/wallet_rpc_api.py +++ b/chia/rpc/wallet_rpc_api.py @@ -5,7 +5,7 @@ import logging import zlib from pathlib import Path -from typing import Any, ClassVar, Optional, Union +from typing import TYPE_CHECKING, Any, ClassVar, Optional, Union, cast from chia_rs import AugSchemeMPL, G1Element, G2Element, PrivateKey from clvm_tools.binutils import assemble @@ -172,6 +172,11 @@ class WalletRpcApi: + if TYPE_CHECKING: + from chia.rpc.rpc_server import RpcApiProtocol + + _protocol_check: ClassVar[RpcApiProtocol] = cast("WalletRpcApi", None) + max_get_coin_records_limit: ClassVar[uint32] = uint32(1000) max_get_coin_records_filter_items: ClassVar[uint32] = uint32(1000) @@ -648,7 +653,7 @@ async def push_tx(self, request: PushTX) -> Empty: nodes = self.service.server.get_connections(NodeType.FULL_NODE) if len(nodes) == 0: raise ValueError("Wallet is not currently connected to any full node peers") - await self.service.push_tx(WalletSpendBundle.from_bytes(request.spend_bundle)) + await self.service.push_tx(request.spend_bundle) return Empty() @tx_endpoint(push=True) @@ -1589,7 +1594,7 @@ async def get_spendable_coins(self, request: dict[str, Any]) -> EndpointResult: excluded_coin_amounts = [] excluded_coins_input: Optional[dict[str, dict[str, Any]]] = request.get("excluded_coins") if excluded_coins_input is not None: - excluded_coins = [Coin.from_json_dict(json_coin) for json_coin in excluded_coins_input] + excluded_coins = [Coin.from_json_dict(json_coin) for json_coin in excluded_coins_input.values()] else: excluded_coins = [] excluded_coin_ids_input: Optional[list[str]] = request.get("excluded_coin_ids") @@ -2112,7 +2117,7 @@ async def create_offer_for_ids( extra_conditions=extra_conditions, ) if result[0]: - success, trade_record, error = result + _success, trade_record, _error = result return { "offer": Offer.from_bytes(trade_record.offer).to_bech32(), "trade_record": trade_record.to_json_dict_convenience(), @@ -2129,7 +2134,7 @@ async def get_offer_summary(self, request: dict[str, Any]) -> EndpointResult: from chia.util.bech32m import bech32_decode, convertbits from chia.wallet.util.puzzle_compression import OFFER_MOD_OLD, decompress_object_with_puzzles - hrpgot, data = bech32_decode(offer_hex, max_length=len(offer_hex)) + _hrpgot, data = bech32_decode(offer_hex, max_length=len(offer_hex)) if data is None: raise ValueError("Invalid Offer") decoded = convertbits(list(data), 5, 8, False) @@ -2208,7 +2213,7 @@ async def check_offer_validity(self, request: dict[str, Any]) -> EndpointResult: from chia.util.bech32m import bech32_decode, convertbits from chia.wallet.util.puzzle_compression import OFFER_MOD_OLD, decompress_object_with_puzzles - hrpgot, data = bech32_decode(offer_hex, max_length=len(offer_hex)) + _hrpgot, data = bech32_decode(offer_hex, max_length=len(offer_hex)) if data is None: raise ValueError("Invalid Offer") # pragma: no cover decoded = convertbits(list(data), 5, 8, False) @@ -2243,7 +2248,7 @@ async def take_offer( from chia.util.bech32m import bech32_decode, convertbits from chia.wallet.util.puzzle_compression import OFFER_MOD_OLD, decompress_object_with_puzzles - hrpgot, data = bech32_decode(offer_hex, max_length=len(offer_hex)) + _hrpgot, data = bech32_decode(offer_hex, max_length=len(offer_hex)) if data is None: raise ValueError("Invalid Offer") # pragma: no cover decoded = convertbits(list(data), 5, 8, False) diff --git a/chia/rpc/wallet_rpc_client.py b/chia/rpc/wallet_rpc_client.py index 3b5afe1d2dd1..afe0d965aa1b 100644 --- a/chia/rpc/wallet_rpc_client.py +++ b/chia/rpc/wallet_rpc_client.py @@ -965,7 +965,6 @@ async def cancel_offers( { "secure": secure, "batch_fee": batch_fee, - "secure": secure, "batch_size": batch_size, "cancel_all": cancel_all, "asset_id": None if asset_id is None else asset_id.hex(), diff --git a/chia/seeder/crawler_api.py b/chia/seeder/crawler_api.py index 86ad9cc657de..cdcace487d0f 100644 --- a/chia/seeder/crawler_api.py +++ b/chia/seeder/crawler_api.py @@ -1,7 +1,7 @@ from __future__ import annotations import logging -from typing import Optional +from typing import TYPE_CHECKING, ClassVar, Optional, cast from chia.protocols import full_node_protocol, wallet_protocol from chia.seeder.crawler import Crawler @@ -12,6 +12,11 @@ class CrawlerAPI: + if TYPE_CHECKING: + from chia.server.api_protocol import ApiProtocol + + _protocol_check: ClassVar[ApiProtocol] = cast("CrawlerAPI", None) + log: logging.Logger crawler: Crawler diff --git a/chia/seeder/start_crawler.py b/chia/seeder/start_crawler.py index ae14c3b6a44f..a5fa0d7426dd 100644 --- a/chia/seeder/start_crawler.py +++ b/chia/seeder/start_crawler.py @@ -6,6 +6,7 @@ from multiprocessing import freeze_support from typing import Any, Optional +from chia.apis import ApiProtocolRegistry from chia.consensus.constants import ConsensusConstants, replace_str_to_bytes from chia.consensus.default_constants import DEFAULT_CONSTANTS from chia.rpc.crawler_rpc_api import CrawlerRpcApi @@ -60,6 +61,7 @@ def create_full_node_crawler_service( network_id=network_id, rpc_info=rpc_info, connect_to_daemon=connect_to_daemon, + class_for_type=ApiProtocolRegistry, ) diff --git a/chia/server/server.py b/chia/server/server.py index a0fa73927d6d..71f75279998b 100644 --- a/chia/server/server.py +++ b/chia/server/server.py @@ -131,6 +131,7 @@ class ChiaServer: ssl_client_context: ssl.SSLContext node_id: bytes32 exempt_peer_networks: list[Union[IPv4Network, IPv6Network]] + class_for_type: dict[NodeType, type[ApiProtocol]] all_connections: dict[bytes32, WSChiaConnection] = field(default_factory=dict) on_connect: Optional[ConnectionCallback] = None shut_down_event: asyncio.Event = field(default_factory=asyncio.Event) @@ -158,6 +159,7 @@ def create( config: dict[str, Any], private_ca_crt_key: tuple[Path, Path], chia_ca_crt_key: tuple[Path, Path], + class_for_type: dict[NodeType, type[ApiProtocol]], name: str = __name__, ) -> ChiaServer: log = logging.getLogger(name) @@ -233,6 +235,7 @@ def create( node_id=calculate_node_id(node_id_cert_path), exempt_peer_networks=[ip_network(net, strict=False) for net in config.get("exempt_peer_networks", [])], introducer_peers=IntroducerPeers() if local_type is NodeType.INTRODUCER else None, + class_for_type=class_for_type, ) def set_received_message_callback(self, callback: ConnectionCallback) -> None: @@ -333,6 +336,7 @@ async def incoming_connection(self, request: web.Request) -> web.StreamResponse: inbound_rate_limit_percent=self._inbound_rate_limit_percent, outbound_rate_limit_percent=self._outbound_rate_limit_percent, local_capabilities_for_handshake=self._local_capabilities_for_handshake, + class_for_type=self.class_for_type, ) await connection.perform_handshake(self._network_id, self.get_port(), self._local_type) assert connection.connection_type is not None, "handshake failed to set connection type, still None" @@ -483,6 +487,7 @@ async def start_client( inbound_rate_limit_percent=self._inbound_rate_limit_percent, outbound_rate_limit_percent=self._outbound_rate_limit_percent, local_capabilities_for_handshake=self._local_capabilities_for_handshake, + class_for_type=self.class_for_type, session=session, ) await connection.perform_handshake(self._network_id, server_port, self._local_type) diff --git a/chia/server/start_data_layer.py b/chia/server/start_data_layer.py index db0bfabfd085..e9aaac952285 100644 --- a/chia/server/start_data_layer.py +++ b/chia/server/start_data_layer.py @@ -5,6 +5,7 @@ import sys from typing import Any, Optional, cast +from chia.apis import ApiProtocolRegistry from chia.data_layer.data_layer import DataLayer from chia.data_layer.data_layer_api import DataLayerAPI from chia.data_layer.data_layer_util import PluginRemote @@ -79,6 +80,7 @@ def create_data_layer_service( max_request_body_size=service_config.get("rpc_server_max_request_body_size", 26214400), rpc_info=rpc_info, connect_to_daemon=connect_to_daemon, + class_for_type=ApiProtocolRegistry, ) diff --git a/chia/server/start_farmer.py b/chia/server/start_farmer.py index 0c9e0b82b75e..1278e326dea1 100644 --- a/chia/server/start_farmer.py +++ b/chia/server/start_farmer.py @@ -4,6 +4,7 @@ import sys from typing import Any, Optional +from chia.apis import ApiProtocolRegistry from chia.consensus.constants import ConsensusConstants, replace_str_to_bytes from chia.consensus.default_constants import DEFAULT_CONSTANTS, update_testnet_overrides from chia.farmer.farmer import Farmer @@ -59,6 +60,7 @@ def create_farmer_service( network_id=network_id, rpc_info=rpc_info, connect_to_daemon=connect_to_daemon, + class_for_type=ApiProtocolRegistry, ) diff --git a/chia/server/start_full_node.py b/chia/server/start_full_node.py index f439f5354f90..e0c675a14cef 100644 --- a/chia/server/start_full_node.py +++ b/chia/server/start_full_node.py @@ -7,6 +7,7 @@ from multiprocessing import freeze_support from typing import Any, Optional +from chia.apis import ApiProtocolRegistry from chia.consensus.constants import ConsensusConstants, replace_str_to_bytes from chia.consensus.default_constants import DEFAULT_CONSTANTS, update_testnet_overrides from chia.full_node.full_node import FullNode @@ -67,6 +68,7 @@ async def create_full_node_service( rpc_info=rpc_info, connect_to_daemon=connect_to_daemon, override_capabilities=override_capabilities, + class_for_type=ApiProtocolRegistry, ) diff --git a/chia/server/start_harvester.py b/chia/server/start_harvester.py index 896270edd3f4..03051ba2fc4d 100644 --- a/chia/server/start_harvester.py +++ b/chia/server/start_harvester.py @@ -4,6 +4,7 @@ import sys from typing import Any, Optional +from chia.apis import ApiProtocolRegistry from chia.consensus.constants import ConsensusConstants, replace_str_to_bytes from chia.consensus.default_constants import DEFAULT_CONSTANTS from chia.harvester.harvester import Harvester @@ -54,6 +55,7 @@ def create_harvester_service( network_id=network_id, rpc_info=rpc_info, connect_to_daemon=connect_to_daemon, + class_for_type=ApiProtocolRegistry, ) diff --git a/chia/server/start_introducer.py b/chia/server/start_introducer.py index 134c646dc9cb..9e78a0fcb3a5 100644 --- a/chia/server/start_introducer.py +++ b/chia/server/start_introducer.py @@ -4,6 +4,7 @@ import sys from typing import Any, Optional +from chia.apis import ApiProtocolRegistry from chia.introducer.introducer import Introducer from chia.introducer.introducer_api import IntroducerAPI from chia.server.outbound_message import NodeType @@ -44,6 +45,7 @@ def create_introducer_service( network_id=network_id, advertised_port=advertised_port, connect_to_daemon=connect_to_daemon, + class_for_type=ApiProtocolRegistry, ) diff --git a/chia/server/start_service.py b/chia/server/start_service.py index d140614d0412..a39384532dac 100644 --- a/chia/server/start_service.py +++ b/chia/server/start_service.py @@ -61,6 +61,7 @@ def __init__( network_id: str, *, config: dict[str, Any], + class_for_type: dict[NodeType, type[ApiProtocol]], upnp_ports: Optional[list[int]] = None, connect_peers: Optional[set[UnresolvedPeerInfo]] = None, on_connect_callback: Optional[Callable[[WSChiaConnection], Awaitable[None]]] = None, @@ -122,6 +123,7 @@ def __init__( self.service_config, (private_ca_crt, private_ca_key), (chia_ca_crt, chia_ca_key), + class_for_type=class_for_type, name=f"{service_name}_server", ) f = getattr(node, "set_server", None) diff --git a/chia/server/start_timelord.py b/chia/server/start_timelord.py index fe3efe603f3e..46d53ece1ee4 100644 --- a/chia/server/start_timelord.py +++ b/chia/server/start_timelord.py @@ -5,6 +5,7 @@ import sys from typing import Any, Optional +from chia.apis import ApiProtocolRegistry from chia.consensus.constants import ConsensusConstants, replace_str_to_bytes from chia.consensus.default_constants import DEFAULT_CONSTANTS from chia.rpc.timelord_rpc_api import TimelordRpcApi @@ -57,6 +58,7 @@ def create_timelord_service( network_id=network_id, rpc_info=rpc_info, connect_to_daemon=connect_to_daemon, + class_for_type=ApiProtocolRegistry, ) diff --git a/chia/server/start_wallet.py b/chia/server/start_wallet.py index 7bc8196c059c..45fae72153a2 100644 --- a/chia/server/start_wallet.py +++ b/chia/server/start_wallet.py @@ -6,6 +6,7 @@ from multiprocessing import freeze_support from typing import Any, Optional +from chia.apis import ApiProtocolRegistry from chia.consensus.constants import ConsensusConstants, replace_str_to_bytes from chia.consensus.default_constants import DEFAULT_CONSTANTS from chia.rpc.wallet_rpc_api import WalletRpcApi @@ -69,6 +70,7 @@ def create_wallet_service( rpc_info=rpc_info, advertised_port=None, connect_to_daemon=connect_to_daemon, + class_for_type=ApiProtocolRegistry, ) diff --git a/chia/server/ws_connection.py b/chia/server/ws_connection.py index 40c634385481..ddfff06972aa 100644 --- a/chia/server/ws_connection.py +++ b/chia/server/ws_connection.py @@ -36,7 +36,7 @@ from chia.util.log_exceptions import log_exceptions # Each message is prepended with LENGTH_BYTES bytes specifying the length -from chia.util.network import class_for_type, is_localhost +from chia.util.network import is_localhost from chia.util.streamable import Streamable # Max size 2^(8*4) which is around 4GiB @@ -83,6 +83,7 @@ class WSChiaConnection: close_callback: Optional[ConnectionClosedCallbackProtocol] = field(repr=False) outbound_rate_limiter: RateLimiter inbound_rate_limiter: RateLimiter + class_for_type: dict[NodeType, type[ApiProtocol]] = field(repr=False) # connection properties is_outbound: bool @@ -138,6 +139,7 @@ def create( inbound_rate_limit_percent: int, outbound_rate_limit_percent: int, local_capabilities_for_handshake: list[tuple[uint16, str]], + class_for_type: dict[NodeType, type[ApiProtocol]], session: Optional[ClientSession] = None, ) -> WSChiaConnection: assert ws._writer is not None @@ -169,6 +171,7 @@ def create( inbound_rate_limiter=RateLimiter(incoming=True, percentage_of_limit=inbound_rate_limit_percent), is_outbound=is_outbound, received_message_callback=received_message_callback, + class_for_type=class_for_type, session=session, ) @@ -540,7 +543,7 @@ async def call_api( raise ValueError("handshake not done yet") request_metadata = get_metadata(request_method) assert request_metadata is not None, f"ApiMetadata unavailable for {request_method}" - attribute = getattr(class_for_type(self.connection_type), request_metadata.request_type.name, None) + attribute = getattr(self.class_for_type[self.connection_type], request_metadata.request_type.name, None) if attribute is None: raise AttributeError( f"Node type {self.connection_type} does not have method {request_metadata.request_type.name}" @@ -567,7 +570,7 @@ async def call_api( await self.ban_peer_bad_protocol(error_message) raise ProtocolError(Err.INVALID_PROTOCOL_MESSAGE, [error_message]) - recv_method = getattr(class_for_type(self.local_type), recv_message_type.name) + recv_method = getattr(self.class_for_type[self.local_type], recv_message_type.name) receive_metadata = get_metadata(recv_method) assert receive_metadata is not None, f"ApiMetadata unavailable for {recv_method}" return receive_metadata.message_class.from_bytes(response.data) diff --git a/chia/simulator/add_blocks_in_batches.py b/chia/simulator/add_blocks_in_batches.py index 7919fbb59098..bee55a4eec87 100644 --- a/chia/simulator/add_blocks_in_batches.py +++ b/chia/simulator/add_blocks_in_batches.py @@ -55,4 +55,8 @@ async def add_blocks_in_batches( peak_fb, state_change_summary, None ) await full_node.peak_post_processing_2(peak_fb, None, state_change_summary, ppp_result) - await full_node._finish_sync() + # this is commented out because we already call post_processing_peak2 which already sends + # the peak to the wallet this causes finish_sync to resend a peak the wallet already received + # that will cause the wallet to reorg the peak (even though its redundant) which causes it to + # go out of sync momentarily. When this redundant behavior is fixed, this line can be uncommented. + # await full_node._finish_sync() diff --git a/chia/simulator/block_tools.py b/chia/simulator/block_tools.py index 1f365c11ddac..fbfcfd3f5d47 100644 --- a/chia/simulator/block_tools.py +++ b/chia/simulator/block_tools.py @@ -970,7 +970,7 @@ def get_consecutive_blocks( new_sub_slot_iters: Optional[uint64] = sub_epoch_summary.new_sub_slot_iters new_difficulty: Optional[uint64] = sub_epoch_summary.new_difficulty - self.log.info(f"Sub epoch summary: {sub_epoch_summary} for block {latest_block.height+1}") + self.log.info(f"Sub epoch summary: {sub_epoch_summary} for block {latest_block.height + 1}") else: # the previous block is not the last block of the sub-epoch or epoch pending_ses = False ses_hash = None @@ -1053,7 +1053,7 @@ def get_consecutive_blocks( sub_slots_finished += 1 self.log.info( f"Sub slot finished. blocks included: {blocks_added_this_sub_slot} blocks_per_slot: " - f"{(len(block_list) - initial_block_list_len)/sub_slots_finished}" + f"{(len(block_list) - initial_block_list_len) / sub_slots_finished}" f"Sub Epoch Summary Included: {sub_epoch_summary is not None} " ) blocks_added_this_sub_slot = 0 # Sub slot ended, overflows are in next sub slot diff --git a/chia/simulator/start_simulator.py b/chia/simulator/start_simulator.py index f049daefad35..0cd4c418eed7 100644 --- a/chia/simulator/start_simulator.py +++ b/chia/simulator/start_simulator.py @@ -7,6 +7,7 @@ from pathlib import Path from typing import Any, Optional +from chia.apis import ApiProtocolRegistry from chia.full_node.full_node import FullNode from chia.server.outbound_message import NodeType from chia.server.signal_handlers import SignalHandlers @@ -63,6 +64,7 @@ async def create_full_node_simulator_service( rpc_info=(SimulatorFullNodeRpcApi, service_config["rpc_port"]), connect_to_daemon=connect_to_daemon, override_capabilities=override_capabilities, + class_for_type=ApiProtocolRegistry, ) diff --git a/chia/timelord/timelord_api.py b/chia/timelord/timelord_api.py index 232a9b763f6a..295514f78962 100644 --- a/chia/timelord/timelord_api.py +++ b/chia/timelord/timelord_api.py @@ -2,7 +2,7 @@ import logging import time -from typing import Optional +from typing import TYPE_CHECKING, ClassVar, Optional, cast from chia.protocols import timelord_protocol from chia.protocols.timelord_protocol import NewPeakTimelord @@ -17,6 +17,11 @@ class TimelordAPI: + if TYPE_CHECKING: + from chia.server.api_protocol import ApiProtocol + + _protocol_check: ClassVar[ApiProtocol] = cast("TimelordAPI", None) + log: logging.Logger timelord: Timelord diff --git a/chia/timelord/timelord_launcher.py b/chia/timelord/timelord_launcher.py index 89df71d5748a..93cf657eab72 100644 --- a/chia/timelord/timelord_launcher.py +++ b/chia/timelord/timelord_launcher.py @@ -175,7 +175,7 @@ async def stop( def main(): if os.name == "nt": log.info("Timelord launcher not supported on Windows.") - return + return 1 root_path = DEFAULT_ROOT_PATH setproctitle("chia_timelord_launcher") net_config = load_config(root_path, "config.yaml") @@ -186,4 +186,4 @@ def main(): if __name__ == "__main__": - main() + sys.exit(main()) diff --git a/chia/types/blockchain_format/program.py b/chia/types/blockchain_format/program.py index ad64e902ff9d..56cd3495b623 100644 --- a/chia/types/blockchain_format/program.py +++ b/chia/types/blockchain_format/program.py @@ -42,7 +42,7 @@ def from_bytes(cls: type[T_Program], blob: bytes) -> T_Program: # the first argument is the buffer we want to parse. This effectively # leverages the rust parser and LazyNode, making it a lot faster to # parse serialized programs into a python compatible structure - cost, ret = run_chia_program( + _cost, ret = run_chia_program( b"\x01", blob, 50, @@ -135,7 +135,7 @@ def run_with_cost(self, max_cost: int, args: Any, flags=DEFAULT_FLAGS) -> tuple[ return self._run(max_cost, flags, args) def run(self, args: Any, max_cost=INFINITE_COST, flags=DEFAULT_FLAGS) -> Program: - cost, r = self._run(max_cost, flags, args) + _cost, r = self._run(max_cost, flags, args) return r def run_with_flags(self, max_cost: int, flags: int, args: Any) -> tuple[int, Program]: diff --git a/chia/util/bech32m.py b/chia/util/bech32m.py index 66e3ff496a78..465726b05654 100644 --- a/chia/util/bech32m.py +++ b/chia/util/bech32m.py @@ -118,7 +118,7 @@ def encode_puzzle_hash(puzzle_hash: bytes32, prefix: str) -> str: def decode_puzzle_hash(address: str) -> bytes32: - hrpgot, data = bech32_decode(address) + _hrpgot, data = bech32_decode(address) if data is None: raise ValueError("Invalid Address") decoded = convertbits(data, 5, 8, False) diff --git a/chia/util/chia_logging.py b/chia/util/chia_logging.py index 3cd525fdf3d1..b36a758c0b9d 100644 --- a/chia/util/chia_logging.py +++ b/chia/util/chia_logging.py @@ -49,12 +49,17 @@ def initialize_logging( root_path: Path, beta_root_path: Optional[Path] = None, ) -> None: + log_backcompat = logging_config.get("log_backcompat", False) log_level = logging_config.get("log_level", default_log_level) file_name_length = 33 - len(service_name) log_date_format = "%Y-%m-%dT%H:%M:%S" file_log_formatter = logging.Formatter( - fmt=f"%(asctime)s.%(msecs)03d {__version__} {service_name} %(name)-{file_name_length}s: " - f"%(levelname)-8s %(message)s", + fmt=( + f"%(asctime)s.%(msecs)03d {service_name} %(name)-{file_name_length}s: %(levelname)-8s %(message)s" + if log_backcompat + else f"%(asctime)s.%(msecs)03d {__version__} {service_name} %(name)-{file_name_length}s: " + f"%(levelname)-8s %(message)s" + ), datefmt=log_date_format, ) handlers: list[logging.Handler] = [] @@ -62,8 +67,13 @@ def initialize_logging( stdout_handler = colorlog.StreamHandler() stdout_handler.setFormatter( colorlog.ColoredFormatter( - f"%(asctime)s.%(msecs)03d {__version__} {service_name} %(name)-{file_name_length}s: " - f"%(log_color)s%(levelname)-8s%(reset)s %(message)s", + ( + f"%(asctime)s.%(msecs)03d {service_name} %(name)-{file_name_length}s: " + f"%(log_color)s%(levelname)-8s%(reset)s %(message)s" + if log_backcompat + else f"%(asctime)s.%(msecs)03d {__version__} {service_name} %(name)-{file_name_length}s: " + f"%(log_color)s%(levelname)-8s%(reset)s %(message)s" + ), datefmt=log_date_format, reset=True, ) diff --git a/chia/util/condition_tools.py b/chia/util/condition_tools.py index cf664652b1ad..dc1446f30aea 100644 --- a/chia/util/condition_tools.py +++ b/chia/util/condition_tools.py @@ -195,7 +195,7 @@ def conditions_for_solution( ) -> list[ConditionWithArgs]: # get the standard script for a puzzle hash and feed in the solution try: - cost, r = puzzle_reveal.run_with_cost(max_cost, solution) + _cost, r = puzzle_reveal.run_with_cost(max_cost, solution) return parse_sexp_to_conditions(r) except Program.EvalError as e: raise ConsensusError(Err.SEXP_ERROR, [str(e)]) from e diff --git a/chia/util/file_keyring.py b/chia/util/file_keyring.py index a5fbfdedbda1..e8148e6c123a 100644 --- a/chia/util/file_keyring.py +++ b/chia/util/file_keyring.py @@ -6,7 +6,6 @@ import contextlib import os import shutil -import sys import threading from collections.abc import Iterator from dataclasses import asdict, dataclass, field @@ -55,18 +54,6 @@ def symmetric_key_from_passphrase(passphrase: str, salt: bytes) -> bytes: return pbkdf2_hmac("sha256", passphrase.encode(), salt, HASH_ITERS) -def get_symmetric_key(salt: bytes) -> bytes: - from chia.cmds.passphrase_funcs import obtain_current_passphrase - - try: - passphrase = obtain_current_passphrase(use_passphrase_cache=True) - except Exception as e: - print(f"Unable to unlock the keyring: {e}") - sys.exit(1) - - return symmetric_key_from_passphrase(passphrase, salt) - - def encrypt_data(input_data: bytes, key: bytes, nonce: bytes) -> bytes: encryptor = ChaCha20Poly1305(key) data = encryptor.encrypt(nonce, CHECKBYTES_VALUE + input_data, None) diff --git a/chia/util/full_block_utils.py b/chia/util/full_block_utils.py index 04a4e9f3f1c2..daacaf852433 100644 --- a/chia/util/full_block_utils.py +++ b/chia/util/full_block_utils.py @@ -297,7 +297,7 @@ def header_block_from_block( transactions_info_optional = bytes([0]) else: transactions_info_optional = bytes([1]) - transactions_info, advance = TransactionsInfo.parse_rust(buf2[1:]) + transactions_info, _advance = TransactionsInfo.parse_rust(buf2[1:]) byte_array_tx: list[bytearray] = [] if is_transaction_block and transactions_info: addition_coins = tx_addition_coins + list(transactions_info.reward_claims_incorporated) diff --git a/chia/util/initial-config.yaml b/chia/util/initial-config.yaml index f913ae4c9b54..74419854ffe4 100644 --- a/chia/util/initial-config.yaml +++ b/chia/util/initial-config.yaml @@ -86,6 +86,7 @@ daemon_ssl: # Controls logging of all servers (harvester, farmer, etc..). Each one can be overridden. logging: &logging log_stdout: False # If True, outputs to stdout instead of a file + log_backcompat: False log_filename: "log/debug.log" log_level: "WARNING" # Can be CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET log_maxfilesrotation: 7 # Max files in rotation. Default value 7 if the key is not set diff --git a/chia/util/json_util.py b/chia/util/json_util.py index 40b8b30b11ea..16a02d374474 100644 --- a/chia/util/json_util.py +++ b/chia/util/json_util.py @@ -5,8 +5,6 @@ from aiohttp import web -from chia.wallet.util.wallet_types import WalletType - class EnhancedJSONEncoder(json.JSONEncoder): """ @@ -16,8 +14,6 @@ class EnhancedJSONEncoder(json.JSONEncoder): def default(self, o: Any) -> Any: if hasattr(type(o), "to_json_dict"): return o.to_json_dict() - elif isinstance(o, WalletType): - return o.name elif hasattr(type(o), "__bytes__"): return f"0x{bytes(o).hex()}" elif isinstance(o, bytes): diff --git a/chia/util/network.py b/chia/util/network.py index aaba02b33ff8..614d2db1f262 100644 --- a/chia/util/network.py +++ b/chia/util/network.py @@ -14,7 +14,6 @@ from aiohttp.log import web_logger from typing_extensions import final -from chia.server.outbound_message import NodeType from chia.types.blockchain_format.sized_bytes import bytes32 from chia.util.ints import uint16 from chia.util.ip_address import IPAddress @@ -138,34 +137,6 @@ def is_trusted_peer( return not testing and is_localhost(host) or node_id.hex() in trusted_peers or is_trusted_cidr(host, trusted_cidrs) -def class_for_type(type: NodeType) -> Any: - if type is NodeType.FULL_NODE: - from chia.full_node.full_node_api import FullNodeAPI - - return FullNodeAPI - elif type is NodeType.WALLET: - from chia.wallet.wallet_node_api import WalletNodeAPI - - return WalletNodeAPI - elif type is NodeType.INTRODUCER: - from chia.introducer.introducer_api import IntroducerAPI - - return IntroducerAPI - elif type is NodeType.TIMELORD: - from chia.timelord.timelord_api import TimelordAPI - - return TimelordAPI - elif type is NodeType.FARMER: - from chia.farmer.farmer_api import FarmerAPI - - return FarmerAPI - elif type is NodeType.HARVESTER: - from chia.harvester.harvester_api import HarvesterAPI - - return HarvesterAPI - raise ValueError("No class for type") - - async def resolve(host: str, *, prefer_ipv6: bool = False) -> IPAddress: try: return IPAddress.create(host) diff --git a/chia/util/profiler.py b/chia/util/profiler.py index a1020c0a57c5..80973293aedd 100644 --- a/chia/util/profiler.py +++ b/chia/util/profiler.py @@ -177,7 +177,7 @@ async def mem_profile_task(root_path: pathlib.Path, service: str, log: logging.L await asyncio.sleep(60) snapshot = tracemalloc.take_snapshot() snapshot.dump(str(profile_dir / f"heap-{counter:05d}.profile")) - log.info(f"Heap usage: {tracemalloc.get_traced_memory()[0]/1000000:0.3f} MB profile {counter:05d}") + log.info(f"Heap usage: {tracemalloc.get_traced_memory()[0] / 1000000:0.3f} MB profile {counter:05d}") counter += 1 finally: tracemalloc.stop() diff --git a/chia/util/ssl_check.py b/chia/util/ssl_check.py index 1aecce4d120c..6073e4bcee56 100644 --- a/chia/util/ssl_check.py +++ b/chia/util/ssl_check.py @@ -168,7 +168,7 @@ def check_and_fix_permissions_for_ssl_file(file: Path, mask: int, updated_mode: # Check that the file permissions are not too permissive try: - (good_perms, mode) = verify_file_permissions(file, mask) + (good_perms, _mode) = verify_file_permissions(file, mask) if not good_perms: valid = False print( diff --git a/chia/util/streamable.py b/chia/util/streamable.py index 3b4684789185..787be2a0fa0e 100644 --- a/chia/util/streamable.py +++ b/chia/util/streamable.py @@ -112,7 +112,7 @@ def create_fields(cls: type[DataclassInstance]) -> StreamableFields: def is_type_List(f_type: object) -> bool: - return get_origin(f_type) == list or f_type == list + return get_origin(f_type) is list or f_type is list def is_type_SpecificOptional(f_type: object) -> bool: @@ -123,7 +123,7 @@ def is_type_SpecificOptional(f_type: object) -> bool: def is_type_Tuple(f_type: object) -> bool: - return get_origin(f_type) == tuple or f_type == tuple + return get_origin(f_type) is tuple or f_type is tuple def convert_optional(convert_func: ConvertFunctionType, item: Any) -> Any: @@ -389,7 +389,7 @@ def function_to_parse_one_item(f_type: type[Any]) -> ParseFunctionType: if hasattr(f_type, "parse"): # Ignoring for now as the proper solution isn't obvious return f_type.parse # type: ignore[no-any-return] - if f_type == bytes: + if f_type is bytes: return parse_bytes if is_type_List(f_type): inner_type = get_args(f_type)[0] @@ -453,7 +453,7 @@ def function_to_stream_one_item(f_type: type[Any]) -> StreamFunctionType: inner_type = get_args(f_type)[0] stream_inner_type_func = function_to_stream_one_item(inner_type) return lambda item, f: stream_optional(stream_inner_type_func, item, f) - elif f_type == bytes: + elif f_type is bytes: return stream_bytes elif hasattr(f_type, "stream"): return stream_streamable diff --git a/chia/util/task_timing.py b/chia/util/task_timing.py index e951afb10a4b..311013ba5cf7 100644 --- a/chia/util/task_timing.py +++ b/chia/util/task_timing.py @@ -248,7 +248,7 @@ def start_task_instrumentation() -> None: def color(pct: float) -> str: assert pct >= 0 and pct <= 100 - return f"{int((100.-pct)//10)+1}" + return f"{int((100. - pct) // 10) + 1}" def fontcolor(pct: float) -> str: @@ -300,7 +300,7 @@ def stop_task_instrumentation(target_dir: str = f"task-profile-{os.getpid()}") - f'frame_{fun_info.fun_id} [shape=box, label="{fun_info.name}()\\l' f"{fun_info.file}\\l" f"{percent:0.2f}%\\n" - f"{fun_info.duration*1000:0.2f}ms\\n" + f"{fun_info.duration * 1000:0.2f}ms\\n" f'{fun_info.num_calls}x\\n",' f"fillcolor={color(percent)}, " f"color={color(percent)}, " @@ -327,7 +327,7 @@ def stop_task_instrumentation(target_dir: str = f"task-profile-{os.getpid()}") - f.write( f"frame_{caller_info.fun_id} -> frame_{fun_info.fun_id} " f'[label="{percent:0.2f}%\\n{ci.calls}x",' - f"penwidth={0.3+(ci.duration*6/total_duration):0.2f}," + f"penwidth={0.3 + (ci.duration * 6 / total_duration):0.2f}," f"color={color(percent)}]\n" ) f.write("}\n") diff --git a/chia/wallet/dao_wallet/dao_utils.py b/chia/wallet/dao_wallet/dao_utils.py index 7ea9b4450592..ddd7e127f3c4 100644 --- a/chia/wallet/dao_wallet/dao_utils.py +++ b/chia/wallet/dao_wallet/dao_utils.py @@ -241,13 +241,13 @@ def add_proposal_to_active_list( ) -> Program: curried_args, c_a = uncurry_lockup(lockup_puzzle) ( - SINGLETON_MOD_HASH, - SINGLETON_LAUNCHER_PUZHASH, - DAO_FINISHED_STATE_HASH, - CAT_MOD_HASH, + _SINGLETON_MOD_HASH, + _SINGLETON_LAUNCHER_PUZHASH, + _DAO_FINISHED_STATE_HASH, + _CAT_MOD_HASH, CAT_TAIL_HASH, ) = c_a.as_iter() - (SELF_HASH, ACTIVE_VOTES, INNERPUZ) = curried_args.as_iter() + (_SELF_HASH, ACTIVE_VOTES, INNERPUZ) = curried_args.as_iter() new_active_votes = Program.to(proposal_id).cons(ACTIVE_VOTES) # (c proposal_id ACTIVE_VOTES) if inner_puzzle is None: inner_puzzle = INNERPUZ @@ -264,7 +264,7 @@ def get_active_votes_from_lockup_puzzle(lockup_puzzle: Program) -> Program: _CAT_TAIL_HASH, ) = list(c_a.as_iter()) ( - self_hash, + _self_hash, ACTIVE_VOTES, _INNERPUZ, ) = curried_args.as_iter() @@ -285,7 +285,7 @@ def get_innerpuz_from_lockup_puzzle(lockup_puzzle: Program) -> Optional[Program] _CAT_TAIL_HASH, ) = list(c_a.as_iter()) ( - self_hash, + _self_hash, _ACTIVE_VOTES, INNERPUZ, ) = list(curried_args.as_iter()) @@ -395,10 +395,10 @@ def get_treasury_rules_from_puzzle(puzzle_reveal: Optional[Program]) -> DAORules ) = curried_args curried_args_prg = uncurry_proposal_validator(proposal_validator) ( - SINGLETON_STRUCT, - PROPOSAL_SELF_HASH, + _SINGLETON_STRUCT, + _PROPOSAL_SELF_HASH, PROPOSAL_MINIMUM_AMOUNT, - PAYOUT_PUZHASH, + _PAYOUT_PUZHASH, ) = curried_args_prg.as_iter() return DAORules( uint64(proposal_timelock.as_int()), @@ -420,7 +420,7 @@ def get_new_puzzle_from_treasury_solution(puzzle_reveal: Program, solution: Prog if mod == DAO_UPDATE_PROPOSAL_MOD: ( DAO_TREASURY_MOD_HASH, - DAO_VALIDATOR_MOD_HASH, + _DAO_VALIDATOR_MOD_HASH, TREASURY_SINGLETON_STRUCT, PROPOSAL_SELF_HASH, proposal_minimum_amount, @@ -463,19 +463,19 @@ def get_new_puzzle_from_proposal_solution(puzzle_reveal: Program, solution: Prog c_a, curried_args = uncurry_proposal(puzzle_reveal) assert isinstance(curried_args, Program) ( - DAO_PROPOSAL_TIMER_MOD_HASH, - SINGLETON_MOD_HASH, - SINGLETON_LAUNCHER_PUZHASH, - CAT_MOD_HASH, - DAO_FINISHED_STATE_HASH, - DAO_TREASURY_MOD_HASH, - lockup_self_hash, + _DAO_PROPOSAL_TIMER_MOD_HASH, + _SINGLETON_MOD_HASH, + _SINGLETON_LAUNCHER_PUZHASH, + _CAT_MOD_HASH, + _DAO_FINISHED_STATE_HASH, + _DAO_TREASURY_MOD_HASH, + _lockup_self_hash, cat_tail_hash, treasury_id, ) = curried_args.as_iter() assert isinstance(c_a, Program) ( - curry_one, + _curry_one, proposal_id, proposed_puzzle_hash, yes_votes, @@ -509,25 +509,25 @@ def get_new_puzzle_from_proposal_solution(puzzle_reveal: Program, solution: Prog if mod.uncurry()[0] == DAO_PROPOSAL_MOD: c_a, curried_args = uncurry_proposal(puzzle_reveal) ( - DAO_PROPOSAL_TIMER_MOD_HASH, - SINGLETON_MOD_HASH, - SINGLETON_LAUNCHER_PUZHASH, - CAT_MOD_HASH, - DAO_FINISHED_STATE_HASH, - DAO_TREASURY_MOD_HASH, - lockup_self_hash, + _DAO_PROPOSAL_TIMER_MOD_HASH, + _SINGLETON_MOD_HASH, + _SINGLETON_LAUNCHER_PUZHASH, + _CAT_MOD_HASH, + _DAO_FINISHED_STATE_HASH, + _DAO_TREASURY_MOD_HASH, + _lockup_self_hash, cat_tail_hash, treasury_id, ) = curried_args.as_iter() ( - curry_one, + _curry_one, proposal_id, proposed_puzzle_hash, yes_votes, total_votes, ) = c_a.as_iter() else: # pragma: no cover - SINGLETON_STRUCT, dao_finished_hash = currieds.as_iter() + SINGLETON_STRUCT, _dao_finished_hash = currieds.as_iter() proposal_id = SINGLETON_STRUCT.rest().first() return get_finished_state_inner_puzzle(bytes32(proposal_id.as_atom())) @@ -711,7 +711,7 @@ def match_funding_puzzle( inner_puz, _ = uncurried.args.at("rf").uncurry() if inner_puz == DAO_TREASURY_MOD: delegated_puz = solution.at("rrfrrf") - delegated_mod, delegated_args = delegated_puz.uncurry() + _delegated_mod, delegated_args = delegated_puz.uncurry() if delegated_puz.uncurry()[0] == SPEND_P2_SINGLETON_MOD: if coin.puzzle_hash == delegated_args.at("rrrrf").as_atom(): # pragma: no cover return True diff --git a/chia/wallet/dao_wallet/dao_wallet.py b/chia/wallet/dao_wallet/dao_wallet.py index cb4c4a322fad..a07b5fb50683 100644 --- a/chia/wallet/dao_wallet/dao_wallet.py +++ b/chia/wallet/dao_wallet/dao_wallet.py @@ -21,9 +21,13 @@ from chia.types.condition_opcodes import ConditionOpcode from chia.util.ints import uint32, uint64, uint128 from chia.wallet import singleton -from chia.wallet.cat_wallet.cat_utils import CAT_MOD, SpendableCAT, construct_cat_puzzle +from chia.wallet.cat_wallet.cat_utils import ( + CAT_MOD, + SpendableCAT, + construct_cat_puzzle, + unsigned_spend_bundle_for_spendable_cats, +) from chia.wallet.cat_wallet.cat_utils import get_innerpuzzle_from_puzzle as get_innerpuzzle_from_cat_puzzle -from chia.wallet.cat_wallet.cat_utils import unsigned_spend_bundle_for_spendable_cats from chia.wallet.cat_wallet.cat_wallet import CATWallet from chia.wallet.cat_wallet.dao_cat_wallet import DAOCATWallet from chia.wallet.coin_selection import select_coins @@ -1222,8 +1226,8 @@ async def create_proposal_close_spend( ) c_a, curried_args_prg = uncurry_proposal(proposal_info.current_innerpuz) ( - SELF_HASH, - PROPOSAL_ID, + _SELF_HASH, + _PROPOSAL_ID, PROPOSED_PUZ_HASH, YES_VOTES, TOTAL_VOTES, @@ -1264,11 +1268,11 @@ async def create_proposal_close_spend( proposal_type, curried_args_prg = get_proposal_args(puzzle_reveal) if proposal_type == ProposalType.SPEND: ( - TREASURY_SINGLETON_STRUCT, - CAT_MOD_HASH, + _TREASURY_SINGLETON_STRUCT, + _CAT_MOD_HASH, CONDITIONS, LIST_OF_TAILHASH_CONDITIONS, - P2_SINGLETON_VIA_DELEGATED_PUZZLE_PUZHASH, + _P2_SINGLETON_VIA_DELEGATED_PUZZLE_PUZHASH, ) = curried_args_prg.as_iter() sum = 0 @@ -1428,18 +1432,18 @@ async def create_proposal_close_spend( elif proposal_type == ProposalType.UPDATE: ( - TREASURY_MOD_HASH, - VALIDATOR_MOD_HASH, - SINGLETON_STRUCT, - PROPOSAL_SELF_HASH, - PROPOSAL_MINIMUM_AMOUNT, - PROPOSAL_EXCESS_PAYOUT_PUZHASH, - PROPOSAL_LENGTH, - PROPOSAL_SOFTCLOSE_LENGTH, - ATTENDANCE_REQUIRED, - PASS_MARGIN, - PROPOSAL_SELF_DESTRUCT_TIME, - ORACLE_SPEND_DELAY, + _TREASURY_MOD_HASH, + _VALIDATOR_MOD_HASH, + _SINGLETON_STRUCT, + _PROPOSAL_SELF_HASH, + _PROPOSAL_MINIMUM_AMOUNT, + _PROPOSAL_EXCESS_PAYOUT_PUZHASH, + _PROPOSAL_LENGTH, + _PROPOSAL_SOFTCLOSE_LENGTH, + _ATTENDANCE_REQUIRED, + _PASS_MARGIN, + _PROPOSAL_SELF_DESTRUCT_TIME, + _ORACLE_SPEND_DELAY, ) = curried_args_prg.as_iter() coin_spends = [] treasury_inner_puzhash = self.dao_info.current_treasury_innerpuz.get_tree_hash() @@ -1663,11 +1667,11 @@ async def parse_proposal(self, proposal_id: bytes32) -> dict[str, Any]: if proposal_type == ProposalType.SPEND: cat_launcher = create_cat_launcher_for_singleton_id(self.dao_info.treasury_id) ( - TREASURY_SINGLETON_STRUCT, - CAT_MOD_HASH, + _TREASURY_SINGLETON_STRUCT, + _CAT_MOD_HASH, CONDITIONS, LIST_OF_TAILHASH_CONDITIONS, - P2_SINGLETON_VIA_DELEGATED_PUZZLE_PUZHASH, + _P2_SINGLETON_VIA_DELEGATED_PUZZLE_PUZHASH, ) = curried_args.as_iter() mint_amount = None new_cat_puzhash = None @@ -1837,20 +1841,20 @@ async def add_or_update_proposal_info( c_a, curried_args = uncurry_proposal(puzzle) ( - DAO_PROPOSAL_TIMER_MOD_HASH, - SINGLETON_MOD_HASH, - SINGLETON_LAUNCHER_PUZHASH, - CAT_MOD_HASH, - DAO_FINISHED_STATE_HASH, + _DAO_PROPOSAL_TIMER_MOD_HASH, + _SINGLETON_MOD_HASH, + _SINGLETON_LAUNCHER_PUZHASH, + _CAT_MOD_HASH, + _DAO_FINISHED_STATE_HASH, _DAO_TREASURY_MOD_HASH, - lockup_self_hash, + _lockup_self_hash, cat_tail_hash, - treasury_id, + _treasury_id, ) = curried_args.as_iter() ( - curry_one, - proposal_id, - proposed_puzzle_hash, + _curry_one, + _proposal_id, + _proposed_puzzle_hash, yes_votes, total_votes, ) = c_a.as_iter() @@ -2111,7 +2115,7 @@ async def apply_state_transition(self, new_state: CoinSpend, block_height: uint3 puzzle = get_inner_puzzle_from_singleton(new_state.puzzle_reveal) assert puzzle try: - mod, curried_args = puzzle.uncurry() + mod, _curried_args = puzzle.uncurry() except ValueError as e: # pragma: no cover self.log.warning("Cannot uncurry puzzle in DAO Wallet: error: %s", e) raise e diff --git a/chia/wallet/singleton.py b/chia/wallet/singleton.py index 9ad8d9787adf..95fa2966936f 100644 --- a/chia/wallet/singleton.py +++ b/chia/wallet/singleton.py @@ -36,7 +36,7 @@ def get_inner_puzzle_from_singleton(puzzle: Union[Program, SerializedProgram]) - inner_f, args = r if not is_singleton(inner_f): return None - SINGLETON_STRUCT, INNER_PUZZLE = list(args.as_iter()) + _SINGLETON_STRUCT, INNER_PUZZLE = list(args.as_iter()) return Program(INNER_PUZZLE) @@ -52,7 +52,7 @@ def get_singleton_id_from_puzzle(puzzle: Union[Program, SerializedProgram]) -> O inner_f, args = r if not is_singleton(inner_f): return None - SINGLETON_STRUCT, INNER_PUZZLE = list(args.as_iter()) + SINGLETON_STRUCT, _INNER_PUZZLE = list(args.as_iter()) return bytes32(Program(SINGLETON_STRUCT).rest().first().as_atom()) diff --git a/chia/wallet/trade_manager.py b/chia/wallet/trade_manager.py index 37b964887c2c..37957c1ec39e 100644 --- a/chia/wallet/trade_manager.py +++ b/chia/wallet/trade_manager.py @@ -4,7 +4,7 @@ import logging import time from collections import deque -from typing import TYPE_CHECKING, Any, Deque, Optional, Union +from typing import TYPE_CHECKING, Any, Optional, Union from typing_extensions import Literal @@ -257,8 +257,8 @@ async def cancel_pending_offers( announcement_nonce: bytes32 = std_hash(b"".join(trades)) trade_records: list[TradeRecord] = [] all_cancellation_coins: list[list[Coin]] = [] - announcement_creations: Deque[CreateCoinAnnouncement] = deque() - announcement_assertions: Deque[AssertCoinAnnouncement] = deque() + announcement_creations: deque[CreateCoinAnnouncement] = deque() + announcement_assertions: deque[AssertCoinAnnouncement] = deque() for trade_id in trades: if trade_id in trade_cache: trade = trade_cache[trade_id] @@ -878,7 +878,7 @@ async def respond_to_offer( if not result[0] or result[1] is None: raise ValueError(result[2]) - success, take_offer, error = result + _success, take_offer, _error = result complete_offer, valid_spend_solver = await self.check_for_final_modifications( Offer.aggregate([offer, take_offer]), solver, inner_action_scope diff --git a/chia/wallet/trading/offer.py b/chia/wallet/trading/offer.py index 89e9d3c38922..3aa58fdc94d7 100644 --- a/chia/wallet/trading/offer.py +++ b/chia/wallet/trading/offer.py @@ -674,7 +674,7 @@ def to_bech32(self, prefix: str = "offer", compression_version: Optional[int] = @classmethod def from_bech32(cls, offer_bech32: str) -> Offer: - hrpgot, data = bech32_decode(offer_bech32, max_length=len(offer_bech32)) + _hrpgot, data = bech32_decode(offer_bech32, max_length=len(offer_bech32)) if data is None: raise ValueError("Invalid Offer") decoded = convertbits(list(data), 5, 8, False) diff --git a/chia/wallet/util/debug_spend_bundle.py b/chia/wallet/util/debug_spend_bundle.py index 7247ecca0a4d..6fff45b8c4a2 100644 --- a/chia/wallet/util/debug_spend_bundle.py +++ b/chia/wallet/util/debug_spend_bundle.py @@ -108,7 +108,7 @@ def debug_spend_bundle(spend_bundle, agg_sig_additional_data=DEFAULT_CONSTANTS.A pks.append(pk) msgs.append(m) print() - cost, r = puzzle_reveal.run_with_cost(INFINITE_COST, solution) + _cost, r = puzzle_reveal.run_with_cost(INFINITE_COST, solution) print(disassemble(r)) create_coin_conditions = [con for con in r.as_iter() if con.first().as_int() == 51] print() diff --git a/chia/wallet/util/wallet_types.py b/chia/wallet/util/wallet_types.py index 96fd4c06c96f..93be99573d32 100644 --- a/chia/wallet/util/wallet_types.py +++ b/chia/wallet/util/wallet_types.py @@ -30,6 +30,13 @@ class WalletType(IntEnum): DAO_CAT = 15 CRCAT = 57 + def to_json_dict(self) -> str: + # yes, this isn't a `dict`, but it is json and + # unfortunately the magic method name is misleading + # not sure this code is used + # TODO: determine if this code is used and if not, remove it + return self.name + class CoinType(IntEnum): NORMAL = 0 diff --git a/chia/wallet/vc_wallet/vc_wallet.py b/chia/wallet/vc_wallet/vc_wallet.py index f664bb7e5e4b..04c4fe043cd5 100644 --- a/chia/wallet/vc_wallet/vc_wallet.py +++ b/chia/wallet/vc_wallet/vc_wallet.py @@ -302,7 +302,7 @@ async def generate_signed_transaction( action_scope=action_scope, conditions=extra_conditions, ) - did_announcement, coin_spend, vc = vc_record.vc.do_spend(inner_puzzle, innersol, new_proof_hash) + did_announcement, coin_spend, _vc = vc_record.vc.do_spend(inner_puzzle, innersol, new_proof_hash) spend_bundle = WalletSpendBundle([coin_spend], G2Element()) if did_announcement is not None: # Need to spend DID diff --git a/chia/wallet/wallet_node_api.py b/chia/wallet/wallet_node_api.py index fb3bf8f8210d..0cba2db8652a 100644 --- a/chia/wallet/wallet_node_api.py +++ b/chia/wallet/wallet_node_api.py @@ -1,6 +1,7 @@ from __future__ import annotations import logging +from typing import TYPE_CHECKING, ClassVar, cast from chia.protocols import full_node_protocol, introducer_protocol, wallet_protocol from chia.server.outbound_message import NodeType @@ -12,6 +13,11 @@ class WalletNodeAPI: + if TYPE_CHECKING: + from chia.server.api_protocol import ApiProtocol + + _protocol_check: ClassVar[ApiProtocol] = cast("WalletNodeAPI", None) + log: logging.Logger wallet_node: WalletNode diff --git a/chia/wallet/wallet_state_manager.py b/chia/wallet/wallet_state_manager.py index 2ff6c4cb9222..fd4fe2cf2da8 100644 --- a/chia/wallet/wallet_state_manager.py +++ b/chia/wallet/wallet_state_manager.py @@ -923,7 +923,7 @@ async def determine_coin_type( return await self.handle_clawback(clawback_coin_data, coin_state, coin_spend, peer), clawback_coin_data # Check if the coin is a VC - is_vc, err_msg = VerifiedCredential.is_vc(uncurried) + is_vc, _err_msg = VerifiedCredential.is_vc(uncurried) if is_vc: vc: VerifiedCredential = VerifiedCredential.get_next_from_coin_spend(coin_spend) return await self.handle_vc(vc), vc @@ -1163,7 +1163,7 @@ async def handle_dao_cat( """ Handle the new coin when it is a DAO CAT """ - mod_hash, tail_hash, inner_puzzle = curried_args + _mod_hash, tail_hash, _inner_puzzle = curried_args asset_id: bytes32 = bytes32(bytes(tail_hash)[1:]) for wallet in self.wallets.values(): if wallet.type() == WalletType.DAO_CAT: @@ -1438,7 +1438,7 @@ async def get_minter_did(self, launcher_coin: Coin, peer: WSChiaConnection) -> O uncurried = uncurry_puzzle(did_spend.puzzle_reveal) did_curried_args = match_did_puzzle(uncurried.mod, uncurried.args) if did_curried_args is not None: - p2_puzzle, recovery_list_hash, num_verification, singleton_struct, metadata = did_curried_args + _p2_puzzle, _recovery_list_hash, _num_verification, singleton_struct, _metadata = did_curried_args minter_did = bytes32(bytes(singleton_struct.rest().first())[1:]) return minter_did @@ -1470,20 +1470,20 @@ async def handle_dao_proposal( ) -> Optional[WalletIdentifier]: ( # ; second hash - SELF_HASH, - PROPOSAL_ID, - PROPOSED_PUZ_HASH, - YES_VOTES, - TOTAL_VOTES, + _SELF_HASH, + _PROPOSAL_ID, + _PROPOSED_PUZ_HASH, + _YES_VOTES, + _TOTAL_VOTES, # ; first hash - PROPOSAL_TIMER_MOD_HASH, - SINGLETON_MOD_HASH, - SINGLETON_LAUNCHER_PUZHASH, - CAT_MOD_HASH, - DAO_FINISHED_STATE_MOD_HASH, - TREASURY_MOD_HASH, - LOCKUP_SELF_HASH, - CAT_TAIL_HASH, + _PROPOSAL_TIMER_MOD_HASH, + _SINGLETON_MOD_HASH, + _SINGLETON_LAUNCHER_PUZHASH, + _CAT_MOD_HASH, + _DAO_FINISHED_STATE_MOD_HASH, + _TREASURY_MOD_HASH, + _LOCKUP_SELF_HASH, + _CAT_TAIL_HASH, TREASURY_ID, ) = uncurried_args for wallet in self.wallets.values(): @@ -1506,7 +1506,7 @@ async def handle_dao_finished_proposals( raise ValueError("coin_state argument to handle_dao_finished_proposals cannot have created_height of None") ( SINGLETON_STRUCT, # (SINGLETON_MOD_HASH, (SINGLETON_ID, LAUNCHER_PUZZLE_HASH)) - FINISHED_STATE_MOD_HASH, + _FINISHED_STATE_MOD_HASH, ) = uncurried_args proposal_id = SINGLETON_STRUCT.rest().first().as_atom() for wallet in self.wallets.values(): @@ -1546,7 +1546,7 @@ async def handle_nft( # P2 puzzle hash determines if we should ignore the NFT uncurried_nft: UncurriedNFT = nft_data.uncurried_nft old_p2_puzhash = uncurried_nft.p2_puzzle.get_tree_hash() - metadata, new_p2_puzhash = get_metadata_and_phs( + _metadata, new_p2_puzhash = get_metadata_and_phs( uncurried_nft, nft_data.parent_coin_spend.solution, ) diff --git a/install-timelord.sh b/install-timelord.sh index c3c476c646be..1f5a1f4ba286 100755 --- a/install-timelord.sh +++ b/install-timelord.sh @@ -131,7 +131,7 @@ else symlink_vdf_bench "$PYTHON_VERSION" elif [ -e venv/bin/python ] && test "$MACOS"; then echo "Installing chiavdf dependencies for MacOS." - brew install boost cmake gmp + brew install --formula --quiet boost cmake gmp echo "Installing chiavdf from source." # User needs to provide required packages echo venv/bin/python -m pip install --force --no-binary chiavdf "$CHIAVDF_VERSION" diff --git a/install.sh b/install.sh index efed665b91d1..6bd2e52218bc 100755 --- a/install.sh +++ b/install.sh @@ -168,7 +168,10 @@ if [ "$OPENSSL_VERSION_INT" -lt "269488367" ]; then echo "Your OS may have patched OpenSSL and not updated the version to 1.1.1n" fi -./setup-poetry.sh -c "${INSTALL_PYTHON_PATH}" +if [ ! -f .penv/bin/poetry ]; then + ./setup-poetry.sh -c "${INSTALL_PYTHON_PATH}" +fi + .penv/bin/poetry env use "${INSTALL_PYTHON_PATH}" # shellcheck disable=SC2086 .penv/bin/poetry install ${EXTRAS} @@ -185,7 +188,7 @@ else fi if [ ! -f "activate" ]; then - ln -s venv/bin/activate . + ln -s .venv/bin/activate . fi if [ -z "$EDITABLE" ]; then @@ -194,11 +197,11 @@ fi if [ -n "$PLOTTER_INSTALL" ]; then set +e - PREV_VENV="$VIRTUAL_ENV" - export VIRTUAL_ENV="venv" + # shellcheck disable=SC1091 + . .venv/bin/activate ./install-plotter.sh bladebit ./install-plotter.sh madmax - export VIRTUAL_ENV="$PREV_VENV" + deactivate set -e fi diff --git a/mypy-exclusions.txt b/mypy-exclusions.txt index eddedd786fe2..41510b51961c 100644 --- a/mypy-exclusions.txt +++ b/mypy-exclusions.txt @@ -87,7 +87,6 @@ chia._tests.tools.test_run_block chia._tests.util.benchmark_cost chia._tests.util.test_full_block_utils chia._tests.util.test_misc -chia._tests.util.test_network chia._tests.util.time_out_assert chia._tests.wallet.did_wallet.test_did chia._tests.wallet.rpc.test_wallet_rpc diff --git a/poetry.lock b/poetry.lock index c3e0cc4ca81f..bd4de5af415f 100644 --- a/poetry.lock +++ b/poetry.lock @@ -882,36 +882,36 @@ chialisp_loader = ">=0.1.2" [[package]] name = "chiapos" -version = "2.0.4" +version = "2.0.7" description = "Chia proof of space plotting, proving, and verifying (wraps C++)" optional = false python-versions = ">=3.7" files = [ - {file = "chiapos-2.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:fa7d13ad72c97d6081ab494f41ea5dbb1e8e7898ba644b45f4512443a4368f45"}, - {file = "chiapos-2.0.4-cp310-cp310-macosx_11_0_x86_64.whl", hash = "sha256:a9e2cf709690efafa16fa1f66c5b5b8a0e00ed0fa4c66ce6939828035f4bb9f9"}, - {file = "chiapos-2.0.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:86a6822b5aa7c5855cd5ff59c6644a441a01c2ce09c38a47a292f8bebb0a042c"}, - {file = "chiapos-2.0.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9394d1c02c56829951379d6a2ef155f33760a3722e926f03e5e1e771e7161cd6"}, - {file = "chiapos-2.0.4-cp310-cp310-win_amd64.whl", hash = "sha256:579c87cd8e028f008fe75fb37ad0aea8a80a81774ac269c4bbb6195a5a4f7937"}, - {file = "chiapos-2.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8d691cf50beae2f8f7e751a9a376701997b72c8e0c1d8fa56d2c441f4290c30a"}, - {file = "chiapos-2.0.4-cp311-cp311-macosx_11_0_x86_64.whl", hash = "sha256:c8c6a0d4a302edb8cecddc253db876ca1727149ddc6911dd255ee058d39c1d78"}, - {file = "chiapos-2.0.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2729ca64281b31d05bc1160860a8ed654f2a34a92775ef13292f25e5b64d34ad"}, - {file = "chiapos-2.0.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ca1a2f4fe886b71af206966b5c8001df5703d0d3b5a47bf7c207325b25ab784d"}, - {file = "chiapos-2.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:2c11c6891217ab49e20ef4b9ae1e2e6aaed752fd41e360515b65ee36c0ec29f8"}, - {file = "chiapos-2.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cc946f0bb74313c85a5fd769ba2d36a9a3684a111cde38293c8ed7b54f9a4d12"}, - {file = "chiapos-2.0.4-cp312-cp312-macosx_11_0_x86_64.whl", hash = "sha256:0c9f315b12ddb9b7a726b19711c841b7f199c568963dd6473495074fc23b8f63"}, - {file = "chiapos-2.0.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fe238271df585a8277b46775124f4cef1dc28a2a475e9950ec292eadacac1c3f"}, - {file = "chiapos-2.0.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e120bbca94b511c7fb1c011efbfdd12d2a569a084fed26e53051650fdf28bf2"}, - {file = "chiapos-2.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:f662b5b58edc1aebee14e7e0085e9e19793efdf2dfb09956e0fb082bffcd48bd"}, - {file = "chiapos-2.0.4-cp38-cp38-macosx_11_0_x86_64.whl", hash = "sha256:f1e2f828b340160813c573bd0c7b11011332203e1c36fa791a685db9c54f2c5b"}, - {file = "chiapos-2.0.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b5a259f2557d38b4b775ea1943e553b47db599bbd2ba6784f1c26e9ac1cdead8"}, - {file = "chiapos-2.0.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a286924cbba2770551bea1b315741d9980a67f242fe99629d84708a4e3b926df"}, - {file = "chiapos-2.0.4-cp38-cp38-win_amd64.whl", hash = "sha256:f75920e0a6355b4882834b74d6a325f7bc9b4f20ca776ac79ecbc8dab91dd640"}, - {file = "chiapos-2.0.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:86ec4db0980ed9a9e1d72a6a0874c2b51ba58af42f1765fa8b32e674ad46af75"}, - {file = "chiapos-2.0.4-cp39-cp39-macosx_11_0_x86_64.whl", hash = "sha256:82f7c5b2ef0f514321b7edd2ef864e8927ba8b7c15c27a6621ea6fb7a7ad2d19"}, - {file = "chiapos-2.0.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ae108016b0cad03cd3fa25caf57924781e6e62c99151be581e976966bf48f7d"}, - {file = "chiapos-2.0.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4060e71c468c654778458a47a05a68b6599aeb2f66e2794a820e11b89c6e3c33"}, - {file = "chiapos-2.0.4-cp39-cp39-win_amd64.whl", hash = "sha256:1dbc6d7e3ce961ecd99c48e9df8d1448ea8623b228927ff91517b903fcf1486f"}, - {file = "chiapos-2.0.4.tar.gz", hash = "sha256:6498d75a7ac01bb64055055b2937f7f964270582a2f82be9a332aa828fc3e3ce"}, + {file = "chiapos-2.0.7-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:65f2aa723b8c8e37af2d529429ac277ffe818879203e4d5e55c7db193db99d2a"}, + {file = "chiapos-2.0.7-cp310-cp310-macosx_11_0_x86_64.whl", hash = "sha256:d4629faeee3963c91e0d4b4880d28b47d371428ef3471412d74b8e3a5b84a9cd"}, + {file = "chiapos-2.0.7-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:8eba7dfe2e36aa701085bd89a5e977dae162fdeba90c7b407e28ba1f306bda01"}, + {file = "chiapos-2.0.7-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:a0d616c503bf1f6a0c4497f5ca77d05da05dc382888c377e53ad8586e67ea891"}, + {file = "chiapos-2.0.7-cp310-cp310-win_amd64.whl", hash = "sha256:950643079c0523c5f0fad376ec7df27836d189944ce9303604e4f72f7a58d31f"}, + {file = "chiapos-2.0.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8ca1d50b09ed4f99cc0317b45fa9a5e892c60304f4436632d6e6a759a53f9dfc"}, + {file = "chiapos-2.0.7-cp311-cp311-macosx_11_0_x86_64.whl", hash = "sha256:1e8e514a00ee86b300ec6f72632b4116b4e19791498a91d6183f5301f91310b2"}, + {file = "chiapos-2.0.7-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:20bd73256db48b4bdc235f6e6485acfbcf25191b4d51d0df6f01f7430fc3cd10"}, + {file = "chiapos-2.0.7-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:6cb076637d803b95eaff72afb78f65cfbc170875bcb066d90699196a930a251e"}, + {file = "chiapos-2.0.7-cp311-cp311-win_amd64.whl", hash = "sha256:e4b876c598a0be96fa57568c00856400a8db13dec6675690b39866b5a8c4f616"}, + {file = "chiapos-2.0.7-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0c03caf22a6394a55fc2bcc125857c7de2cc8bf59d1fa48e0bd652857a436a01"}, + {file = "chiapos-2.0.7-cp312-cp312-macosx_11_0_x86_64.whl", hash = "sha256:a70c9341f557e5fa2273fb89c0051832fecba39b65c172e6260c127ccb07a5e4"}, + {file = "chiapos-2.0.7-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:34dff6233bfbc329251c63b324a0d2002614af9a34dcc19731ccb1652c8e929e"}, + {file = "chiapos-2.0.7-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:de1f87746d77b8eeb9552dd1c73ff03585cf1b66e95db1fe6b645c202a93aac2"}, + {file = "chiapos-2.0.7-cp312-cp312-win_amd64.whl", hash = "sha256:28608b841ec313a924c5c4f0bbdd1409267bab4f9b02a8b42dbb79a6250eae53"}, + {file = "chiapos-2.0.7-cp38-cp38-macosx_11_0_x86_64.whl", hash = "sha256:97a66ef35e198436c15f5ca45910760db56e2708e425890dfaa4a991ffb08c57"}, + {file = "chiapos-2.0.7-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:c30d1f89399e631899e947cb5472d2cb9a39577edc7d1508646748b2f89e3cbd"}, + {file = "chiapos-2.0.7-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:a3f58cded9cf47c3b2eca3fc571daf19feb3f6ef085bfc33d99144c96c025bc7"}, + {file = "chiapos-2.0.7-cp38-cp38-win_amd64.whl", hash = "sha256:e7ffe0df3f6d22063f9b59d0e5d393e3b7dada3d268edeee2c9058dd98f447e2"}, + {file = "chiapos-2.0.7-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:ec4e2199f82822400c2e6c4afee3cd180b8523dd512e178d46a915a75cdf8ea2"}, + {file = "chiapos-2.0.7-cp39-cp39-macosx_11_0_x86_64.whl", hash = "sha256:c103d7ef5697177820731551e7d223a431d3181d61c9adb6c3b8b4b8ccc2bee4"}, + {file = "chiapos-2.0.7-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:37acd69a89b7b5c6e5465d4c22125d0d1a818db420e00ca0d3f3f4412d7e9937"}, + {file = "chiapos-2.0.7-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:fd9fd7cd4ec2b74886f88bc9f10a46b64ad8b778472859595f31db240291beb4"}, + {file = "chiapos-2.0.7-cp39-cp39-win_amd64.whl", hash = "sha256:0fa42d07d317b16039ac9c511da90810b8e176c785c66c0ec010e4fd5cf7b170"}, + {file = "chiapos-2.0.7.tar.gz", hash = "sha256:f0c8742b9e92e5d27ced06e80cdcae7f29d1752ffa38ea30930a4a61ee03072e"}, ] [[package]] @@ -1305,22 +1305,6 @@ docs = ["furo (>=2023.9.10)", "sphinx (>=7.2.6)", "sphinx-autodoc-typehints (>=1 testing = ["covdefaults (>=2.3)", "coverage (>=7.3.2)", "diff-cover (>=8.0.1)", "pytest (>=7.4.3)", "pytest-asyncio (>=0.21)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)", "pytest-timeout (>=2.2)", "virtualenv (>=20.26.2)"] typing = ["typing-extensions (>=4.8)"] -[[package]] -name = "flake8" -version = "7.1.1" -description = "the modular source code checker: pep8 pyflakes and co" -optional = true -python-versions = ">=3.8.1" -files = [ - {file = "flake8-7.1.1-py2.py3-none-any.whl", hash = "sha256:597477df7860daa5aa0fdd84bf5208a043ab96b8e96ab708770ae0364dd03213"}, - {file = "flake8-7.1.1.tar.gz", hash = "sha256:049d058491e228e03e67b390f311bbf88fce2dbaa8fa673e7aea87b7198b8d38"}, -] - -[package.dependencies] -mccabe = ">=0.7.0,<0.8.0" -pycodestyle = ">=2.12.0,<2.13.0" -pyflakes = ">=3.2.0,<3.3.0" - [[package]] name = "frozenlist" version = "1.4.1" @@ -1499,20 +1483,6 @@ files = [ {file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"}, ] -[[package]] -name = "isort" -version = "5.13.2" -description = "A Python utility / library to sort Python imports." -optional = true -python-versions = ">=3.8.0" -files = [ - {file = "isort-5.13.2-py3-none-any.whl", hash = "sha256:8ca5e72a8d85860d5a3fa69b8745237f2939afe12dbf656afbcb47fe72d947a6"}, - {file = "isort-5.13.2.tar.gz", hash = "sha256:48fdfcb9face5d58a4f6dde2e72a1fb8dcaf8ab26f95ab49fab84c2ddefb0109"}, -] - -[package.extras] -colors = ["colorama (>=0.4.6)"] - [[package]] name = "jaraco-classes" version = "3.3.0" @@ -1892,17 +1862,6 @@ files = [ {file = "MarkupSafe-2.1.3.tar.gz", hash = "sha256:af598ed32d6ae86f1b747b82783958b1a4ab8f617b06fe68795c7f026abbdcad"}, ] -[[package]] -name = "mccabe" -version = "0.7.0" -description = "McCabe checker, plugin for flake8" -optional = true -python-versions = ">=3.6" -files = [ - {file = "mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e"}, - {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"}, -] - [[package]] name = "memory-profiler" version = "0.61.0" @@ -2266,49 +2225,33 @@ virtualenv = ">=20.10.0" [[package]] name = "psutil" -version = "5.9.4" -description = "Cross-platform lib for process and system monitoring in Python." -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "psutil-5.9.4-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:c1ca331af862803a42677c120aff8a814a804e09832f166f226bfd22b56feee8"}, - {file = "psutil-5.9.4-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:68908971daf802203f3d37e78d3f8831b6d1014864d7a85937941bb35f09aefe"}, - {file = "psutil-5.9.4-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:3ff89f9b835100a825b14c2808a106b6fdcc4b15483141482a12c725e7f78549"}, - {file = "psutil-5.9.4-cp27-cp27m-win32.whl", hash = "sha256:852dd5d9f8a47169fe62fd4a971aa07859476c2ba22c2254d4a1baa4e10b95ad"}, - {file = "psutil-5.9.4-cp27-cp27m-win_amd64.whl", hash = "sha256:9120cd39dca5c5e1c54b59a41d205023d436799b1c8c4d3ff71af18535728e94"}, - {file = "psutil-5.9.4-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:6b92c532979bafc2df23ddc785ed116fced1f492ad90a6830cf24f4d1ea27d24"}, - {file = "psutil-5.9.4-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:efeae04f9516907be44904cc7ce08defb6b665128992a56957abc9b61dca94b7"}, - {file = "psutil-5.9.4-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:54d5b184728298f2ca8567bf83c422b706200bcbbfafdc06718264f9393cfeb7"}, - {file = "psutil-5.9.4-cp36-abi3-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:16653106f3b59386ffe10e0bad3bb6299e169d5327d3f187614b1cb8f24cf2e1"}, - {file = "psutil-5.9.4-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:54c0d3d8e0078b7666984e11b12b88af2db11d11249a8ac8920dd5ef68a66e08"}, - {file = "psutil-5.9.4-cp36-abi3-win32.whl", hash = "sha256:149555f59a69b33f056ba1c4eb22bb7bf24332ce631c44a319cec09f876aaeff"}, - {file = "psutil-5.9.4-cp36-abi3-win_amd64.whl", hash = "sha256:fd8522436a6ada7b4aad6638662966de0d61d241cb821239b2ae7013d41a43d4"}, - {file = "psutil-5.9.4-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:6001c809253a29599bc0dfd5179d9f8a5779f9dffea1da0f13c53ee568115e1e"}, - {file = "psutil-5.9.4.tar.gz", hash = "sha256:3d7f9739eb435d4b1338944abe23f49584bde5395f27487d2ee25ad9a8774a62"}, -] - -[package.extras] -test = ["enum34", "ipaddress", "mock", "pywin32", "wmi"] - -[[package]] -name = "psutil" -version = "5.9.4" +version = "6.1.0" description = "Cross-platform lib for process and system monitoring in Python." optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,>=2.7" files = [ - {file = "psutil-5.9.4-cp37-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:56d557d85b8464e9b8ace0995705a146225b94bdad8fa52f266beae0c3211ca3"}, - {file = "psutil-5.9.4-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a21eb32d5ef5782a29b02b06912336a211d9665d6f6de39b0928c7f0481d1e16"}, - {file = "psutil-5.9.4-cp38-abi3-macosx_10_14_x86_64.whl", hash = "sha256:6a8d6bfca2cdb7d52299446a13985ceaa889be39d5701410c21be567e32c3ede"}, + {file = "psutil-6.1.0-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:ff34df86226c0227c52f38b919213157588a678d049688eded74c76c8ba4a5d0"}, + {file = "psutil-6.1.0-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:c0e0c00aa18ca2d3b2b991643b799a15fc8f0563d2ebb6040f64ce8dc027b942"}, + {file = "psutil-6.1.0-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:000d1d1ebd634b4efb383f4034437384e44a6d455260aaee2eca1e9c1b55f047"}, + {file = "psutil-6.1.0-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:5cd2bcdc75b452ba2e10f0e8ecc0b57b827dd5d7aaffbc6821b2a9a242823a76"}, + {file = "psutil-6.1.0-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:045f00a43c737f960d273a83973b2511430d61f283a44c96bf13a6e829ba8fdc"}, + {file = "psutil-6.1.0-cp27-none-win32.whl", hash = "sha256:9118f27452b70bb1d9ab3198c1f626c2499384935aaf55388211ad982611407e"}, + {file = "psutil-6.1.0-cp27-none-win_amd64.whl", hash = "sha256:a8506f6119cff7015678e2bce904a4da21025cc70ad283a53b099e7620061d85"}, + {file = "psutil-6.1.0-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:6e2dcd475ce8b80522e51d923d10c7871e45f20918e027ab682f94f1c6351688"}, + {file = "psutil-6.1.0-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:0895b8414afafc526712c498bd9de2b063deaac4021a3b3c34566283464aff8e"}, + {file = "psutil-6.1.0-cp36-abi3-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9dcbfce5d89f1d1f2546a2090f4fcf87c7f669d1d90aacb7d7582addece9fb38"}, + {file = "psutil-6.1.0-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:498c6979f9c6637ebc3a73b3f87f9eb1ec24e1ce53a7c5173b8508981614a90b"}, + {file = "psutil-6.1.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d905186d647b16755a800e7263d43df08b790d709d575105d419f8b6ef65423a"}, + {file = "psutil-6.1.0-cp36-cp36m-win32.whl", hash = "sha256:6d3fbbc8d23fcdcb500d2c9f94e07b1342df8ed71b948a2649b5cb060a7c94ca"}, + {file = "psutil-6.1.0-cp36-cp36m-win_amd64.whl", hash = "sha256:1209036fbd0421afde505a4879dee3b2fd7b1e14fee81c0069807adcbbcca747"}, + {file = "psutil-6.1.0-cp37-abi3-win32.whl", hash = "sha256:1ad45a1f5d0b608253b11508f80940985d1d0c8f6111b5cb637533a0e6ddc13e"}, + {file = "psutil-6.1.0-cp37-abi3-win_amd64.whl", hash = "sha256:a8fb3752b491d246034fa4d279ff076501588ce8cbcdbb62c32fd7a377d996be"}, + {file = "psutil-6.1.0.tar.gz", hash = "sha256:353815f59a7f64cdaca1c0307ee13558a0512f6db064e92fe833784f08539c7a"}, ] [package.extras] -test = ["enum34", "ipaddress", "mock", "pywin32", "wmi"] - -[package.source] -type = "legacy" -url = "https://pypi.chia.net/simple" -reference = "chia" +dev = ["black", "check-manifest", "coverage", "packaging", "pylint", "pyperf", "pypinfo", "pytest-cov", "requests", "rstcheck", "ruff", "sphinx", "sphinx_rtd_theme", "toml-sort", "twine", "virtualenv", "wheel"] +test = ["pytest", "pytest-xdist", "setuptools"] [[package]] name = "py3createtorrent" @@ -2324,17 +2267,6 @@ files = [ [package.dependencies] "bencode.py" = "*" -[[package]] -name = "pycodestyle" -version = "2.12.1" -description = "Python style guide checker" -optional = true -python-versions = ">=3.8" -files = [ - {file = "pycodestyle-2.12.1-py2.py3-none-any.whl", hash = "sha256:46f0fb92069a7c28ab7bb558f05bfc0110dac69a0cd23c61ea0040283a9d78b3"}, - {file = "pycodestyle-2.12.1.tar.gz", hash = "sha256:6838eae08bbce4f6accd5d5572075c63626a15ee3e6f842df996bf62f6d73521"}, -] - [[package]] name = "pycparser" version = "2.21" @@ -2387,17 +2319,6 @@ files = [ {file = "pycryptodome-3.20.0.tar.gz", hash = "sha256:09609209ed7de61c2b560cc5c8c4fbf892f8b15b1faf7e4cbffac97db1fffda7"}, ] -[[package]] -name = "pyflakes" -version = "3.2.0" -description = "passive checker of Python programs" -optional = true -python-versions = ">=3.8" -files = [ - {file = "pyflakes-3.2.0-py2.py3-none-any.whl", hash = "sha256:84b5be138a2dfbb40689ca07e2152deb896a65c3a3e24c251c5c62489568074a"}, - {file = "pyflakes-3.2.0.tar.gz", hash = "sha256:1c61603ff154621fb2a9172037d84dca3500def8c8b630657d1701f026f8af3f"}, -] - [[package]] name = "pygments" version = "2.16.1" @@ -2586,20 +2507,6 @@ files = [ [package.dependencies] six = ">=1.5" -[[package]] -name = "pyupgrade" -version = "3.16.0" -description = "A tool to automatically upgrade syntax for newer versions." -optional = true -python-versions = ">=3.8.1" -files = [ - {file = "pyupgrade-3.16.0-py2.py3-none-any.whl", hash = "sha256:7a54ee28f3024d027048d49d101e5c702e88c85edc3a1d08b636c50ebef2a97d"}, - {file = "pyupgrade-3.16.0.tar.gz", hash = "sha256:237893a05d5b117259b31b423f23cbae4bce0b7eae57ba9a52c06098c2ddd76f"}, -] - -[package.dependencies] -tokenize-rt = ">=5.2.0" - [[package]] name = "pywin32" version = "306" @@ -2719,7 +2626,7 @@ use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"] name = "ruff" version = "0.7.1" description = "An extremely fast Python linter and code formatter, written in Rust." -optional = false +optional = true python-versions = ">=3.7" files = [ {file = "ruff-0.7.1-py3-none-linux_armv6l.whl", hash = "sha256:cb1bc5ed9403daa7da05475d615739cc0212e861b7306f314379d958592aaa89"}, @@ -2938,17 +2845,6 @@ files = [ {file = "sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88"}, ] -[[package]] -name = "tokenize-rt" -version = "5.2.0" -description = "A wrapper around the stdlib `tokenize` which roundtrips." -optional = true -python-versions = ">=3.8" -files = [ - {file = "tokenize_rt-5.2.0-py2.py3-none-any.whl", hash = "sha256:b79d41a65cfec71285433511b50271b05da3584a1da144a0752e9c621a285289"}, - {file = "tokenize_rt-5.2.0.tar.gz", hash = "sha256:9fe80f8a5c1edad2d3ede0f37481cc0cc1538a2f442c9c2f9e4feacd2792d054"}, -] - [[package]] name = "tomli" version = "2.0.1" @@ -3369,11 +3265,11 @@ url = "https://pypi.chia.net/simple" reference = "chia" [extras] -dev = ["aiohttp_cors", "black", "build", "coverage", "diff-cover", "flake8", "isort", "lxml", "mypy", "pre-commit", "pre-commit", "py3createtorrent", "pyinstaller", "pytest", "pytest-cov", "pytest-mock", "pytest-monitor", "pytest-xdist", "pyupgrade", "types-aiofiles", "types-pyyaml", "types-setuptools"] +dev = ["aiohttp_cors", "black", "build", "coverage", "diff-cover", "lxml", "mypy", "pre-commit", "pre-commit", "py3createtorrent", "pyinstaller", "pytest", "pytest-cov", "pytest-mock", "pytest-monitor", "pytest-xdist", "ruff", "types-aiofiles", "types-pyyaml", "types-setuptools"] legacy-keyring = ["keyrings.cryptfile"] upnp = ["miniupnpc"] [metadata] lock-version = "2.0" python-versions = ">=3.9, <3.13" -content-hash = "a78ed18bd01ad2bc357807114d0318b18cf9ba308d887dbd8b90a986e0872a00" +content-hash = "06a52b7b1c4fe3d76e6775746d1cffa2c6ca218c1f38f20ef51432b25999d04d" diff --git a/pyproject.toml b/pyproject.toml index 938ec4d3e7b2..ac185c55dc43 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,7 +45,7 @@ anyio = "4.6.2.post1" bitstring = "4.1.4" # Binary data management library boto3 = "1.35.43" # AWS S3 for Data Layer S3 plugin chiabip158 = "1.5.1" # bip158-style wallet filters -chiapos = "2.0.4" # proof of space +chiapos = "2.0.7" # proof of space chia_rs = "0.15.0" chiavdf = "1.1.8" # timelord and vdf verification click = "8.1.7" # For the CLI @@ -62,10 +62,7 @@ filelock = "3.15.4" # For reading and writing config multiprocess and multithre keyring = "25.2.1" # Store keys in MacOS Keychain, Windows Credential Locker packaging = "24.0" pip = "24.2" -psutil = [ - {version="5.9.4", markers="platform_machine!='aarch64'"}, - {version="5.9.4", markers="platform_machine=='aarch64'", source="chia"}, -] +psutil = "6.1.0" pyyaml = "6.0.1" # Used for config file format setproctitle = "1.3.3" # Gives the chia processes readable names setuptools = "75.1.0" @@ -83,8 +80,6 @@ black = { version = "24.8.0", optional = true } build = { version = "1.2.1", optional = true } coverage = { version = "7.6.4", optional = true } diff-cover = { version = "9.2.0", optional = true } -flake8 = { version = "7.1.1", optional = true } -isort = { version = "5.13.2", optional = true } # TODO: but... keyrings_cryptfile goes 15 minutes without locking while this does in 75 seconds "keyrings.cryptfile" = { version = "1.3.9", optional = true } mypy = { version = "1.11.1", optional = true } @@ -101,16 +96,15 @@ types-pyyaml = { version = "6.0.12.20240311", optional = true } types-setuptools = { version = "70.0.0.20240524", optional = true } lxml = { version = "5.2.2", optional = true } miniupnpc = { version = "2.2.2", source = "chia", optional = true } -pyupgrade = { version = "3.16.0", optional = true } # big-o = {version = "0.11.0", optional = true} # numpy = [ # {version="1.24.4", python = "<3.9", optional = true}, # {version="1.26.4", python = ">=3.9", optional = true}] -ruff = "0.7.1" +ruff = { version = "0.7.1", optional = true } [tool.poetry.extras] -dev = ["aiohttp_cors", "black", "build", "coverage", "diff-cover", "flake8", "isort", "mypy", "pre-commit", "py3createtorrent", "pyinstaller", "pytest", "pytest-cov", "pytest-mock", "pytest-monitor", "pytest-xdist", "types-aiofiles", "types-pyyaml", "types-setuptools", "pyupgrade", "lxml"] +dev = ["aiohttp_cors", "black", "build", "coverage", "diff-cover", "mypy", "pre-commit", "py3createtorrent", "pyinstaller", "pytest", "pytest-cov", "pytest-mock", "pytest-monitor", "pytest-xdist", "ruff", "types-aiofiles", "types-pyyaml", "types-setuptools", "lxml"] upnp = ["miniupnpc"] legacy_keyring = ["keyrings.cryptfile"] @@ -158,12 +152,25 @@ include = ''' ''' exclude = '' +[project] +# This has to match the poetry python entry above +requires-python = ">=3.9, <3.13" + [tool.ruff] line-length = 120 [tool.ruff.lint] preview = true -select = ["PL"] +select = [ + "PL", # Pylint + "I", # Isort + "FA", # Flake8: future-annotations + "UP", # Pyupgrade + # Flake8 core + "F", + "E", + "W", +] explicit-preview-rules = false ignore = [ # Pylint convention @@ -206,8 +213,15 @@ ignore = [ "PLW0108", # unnecessary-lambda "PLW1510", # subprocess-run-without-check "PLW0120", # useless-else-on-loop + + # Flake8 core + # "F841", # unused-variable (540) ] + +[tool.ruff.lint.isort] +required-imports = ["from __future__ import annotations"] + [tool.ruff.lint.pylint] max-args = 5 max-locals = 15 @@ -217,3 +231,6 @@ max-statements = 50 max-nested-blocks = 5 max-public-methods = 20 max-bool-expr = 5 + +[tool.ruff.lint.pyupgrade] +keep-runtime-typing = true diff --git a/tools/analyze_memory_profile.py b/tools/analyze_memory_profile.py index ffe08b4532e7..ab7f99cd450e 100644 --- a/tools/analyze_memory_profile.py +++ b/tools/analyze_memory_profile.py @@ -35,7 +35,7 @@ def add(self, size: int) -> None: def color(pct: float) -> str: - return f"{int((100.-pct)//10)+1}" + return f"{int((100. - pct) // 10) + 1}" def fontcolor(pct: float) -> str: @@ -126,7 +126,7 @@ def analyze_slot(ctx: click.Context, slot: int) -> None: total_size += trace.size calls += 1 if ((calls - 1) & 255) == 0: - stdout.write(f"\rtotal size: {total_size/1000000:0.3f} MB ({calls} allocs) ") + stdout.write(f"\rtotal size: {total_size / 1000000:0.3f} MB ({calls} allocs) ") # to support recursive functions, make sure we only visit each frame # once during traversal visited: set[str] = set() @@ -171,7 +171,7 @@ def analyze_slot(ctx: click.Context, slot: int) -> None: f.write( f'frame_{fr.fun_id} [shape=box, label="{name}()\\l' f"{percent:0.2f}%\\n" - f"{fr.size/1000000:0.3f}MB\\n" + f"{fr.size / 1000000:0.3f}MB\\n" f'{fr.count}x\\n",' f"fillcolor={color(percent)}, " f"color={color(percent)}, " @@ -201,7 +201,7 @@ def analyze_slot(ctx: click.Context, slot: int) -> None: f.write( f"frame_{caller_id} -> frame_{fr.fun_id} " f'[label="{percent:0.2f}%\\n{ci.calls}x",' - f"penwidth={0.3+(ci.size*6/total_size):0.2f}," + f"penwidth={0.3 + (ci.size * 6 / total_size):0.2f}," f"color={color(percent)}]\n" ) f.write("}\n") diff --git a/tools/cpu_utilization.py b/tools/cpu_utilization.py index 40cb24d87f9b..41333f014c68 100644 --- a/tools/cpu_utilization.py +++ b/tools/cpu_utilization.py @@ -76,11 +76,11 @@ def main(pid: int, output: str, threads: bool) -> None: if row == 0: continue time_delta = ts - timestamps[row - 1] - out.write(f"{ts-start_time:10f} ") + out.write(f"{ts - start_time:10f} ") for _, c in cols: if row in c and (row - 1) in c: - out.write(f" {(c[row].user_time - c[row - 1].user_time)*100/time_delta:6.2f}% ") - out.write(f" {(c[row].system_time - c[row - 1].system_time)*100/time_delta:6.2f}% ") + out.write(f" {(c[row].user_time - c[row - 1].user_time) * 100 / time_delta:6.2f}% ") + out.write(f" {(c[row].system_time - c[row - 1].system_time) * 100 / time_delta:6.2f}% ") else: out.write(" 0.00% 0.00% ") row += 1 @@ -89,7 +89,7 @@ def main(pid: int, output: str, threads: bool) -> None: with open("plot-cpu.gnuplot", "w+") as out: out.write( f""" -set term png small size 1500, {120*len(cols)} +set term png small size 1500, {120 * len(cols)} set output "cpu.png" set yrange [0:100] unset xtics @@ -106,8 +106,8 @@ def main(pid: int, output: str, threads: bool) -> None: if idx == len(cols) - 1: out.write('set xlabel "time (s)"\n') out.write( - f'plot "{output}" using 1:(${idx*2+2}+${idx*2+3}) title "User" with filledcurves y=0, ' - f'"{output}" using 1:{idx*2+3} title "System" with filledcurves y=0\n' + f'plot "{output}" using 1:(${idx * 2 + 2}+${idx * 2 + 3}) title "User" with filledcurves y=0, ' + f'"{output}" using 1:{idx * 2 + 3} title "System" with filledcurves y=0\n' ) print('running "gnuplot plot-cpu.gnuplot"') diff --git a/tools/generate_chain.py b/tools/generate_chain.py index 4d3b0d59823b..5c4c4a9acae9 100644 --- a/tools/generate_chain.py +++ b/tools/generate_chain.py @@ -194,15 +194,15 @@ def main(length: int, fill_rate: int, profile: bool, block_refs: bool, output: O print( f"height: {b.height} " - f"spends: {i+1} " + f"spends: {i + 1} " f"refs: {len(block_references)} " - f"fill_rate: {actual_fill_rate*100:.1f}% " + f"fill_rate: {actual_fill_rate * 100:.1f}% " f"new coins: {len(new_coins)} " f"unspent: {len(unspent_coins)} " f"difficulty: {b.weight - prev_block.weight} " f"timestamp: {ts} " f"time: {end_time - start_time:0.2f}s " - f"tx-block-ratio: {len(transaction_blocks)*100/b.height:0.0f}% " + f"tx-block-ratio: {len(transaction_blocks) * 100 / b.height:0.0f}% " ) new_blocks = [ diff --git a/tools/test_full_sync.py b/tools/test_full_sync.py index ef928ea667ca..2da879713b54 100755 --- a/tools/test_full_sync.py +++ b/tools/test_full_sync.py @@ -165,7 +165,7 @@ async def run_sync_checkpoint( fork_height = block_batch[0].height - 1 header_hash = block_batch[0].prev_header_hash - success, _, err = await full_node.add_block_batch( + success, _, _err = await full_node.add_block_batch( AugmentedBlockchain(full_node.blockchain), block_batch, peer_info, @@ -189,7 +189,7 @@ async def run_sync_checkpoint( ) fork_height = block_batch[0].height - 1 fork_header_hash = block_batch[0].prev_header_hash - success, _, err = await full_node.add_block_batch( + success, _, _err = await full_node.add_block_batch( AugmentedBlockchain(full_node.blockchain), block_batch, peer_info,