chia-blockchain/chia/simulator/setup_services.py

407 lines
15 KiB
Python
Raw Normal View History

from __future__ import annotations
import asyncio
import gc
import logging
import signal
import sqlite3
from contextlib import contextmanager
chia|tests|github: Implement, integrate and test plot sync protocol (#9695) * protocols|server: Define new harvester plot refreshing protocol messages * protocols: Bump `protocol_version` to `0.0.34` * tests: Introduce `setup_farmer_multi_harvester` Allows to run a test setup with 1 farmer and mutiple harvesters. * plotting: Add an initial plot loading indication to `PlotManager` * plotting|tests: Don't add removed duplicates to `total_result.removed` `PlotRefreshResult.removed` should only contain plots that were loaded properly before they were removed. It shouldn't contain e.g. removed duplicates or invalid plots since those are synced in an extra sync step and not as diff but as whole list every time. * harvester: Reset `PlotManager` on shutdown * plot_sync: Implement plot sync protocol * farmer|harvester: Integrate and enable plot sync * tests: Implement tests for the plot sync protocol * farmer|tests: Drop obsolete harvester caching code * setup: Add `chia.plot_sync` to packages * plot_sync: Type hints in `DeltaType` * plot_sync: Drop parameters in `super()` calls * plot_sync: Introduce `send_response` helper in `Receiver._process` * plot_sync: Add some parentheses Co-authored-by: Kyle Altendorf <sda@fstab.net> * plot_sync: Additional hint for a `Receiver.process_path_list` parameter * plot_sync: Force named parameters in `Receiver.process_path_list` * test: Fix fixtures after rebase * tests: Fix sorting after rebase * tests: Return type hint for `plot_sync_setup` * tests: Rename `WSChiaConnection` and move it in the outer scope * tests|plot_sync: More type hints * tests: Rework some delta tests * tests: Drop a `range` and iterate over the list directly * tests: Use the proper flags to overwrite * test: More missing duplicates tests * tests: Drop `ExpectedResult.reset` * tests: Reduce some asserts * tests: Add messages to some `assert False` statements * tests: Introduce `ErrorSimulation` enum in `test_sync_simulated.py` * tests: Use `secrects` instead of `Crypto.Random` * Fixes after rebase * Import from `typing_extensions` to support python 3.7 * Drop task name to support python 3.7 * Introduce `Sender.syncing`, `Sender.connected` and a log about the task * Add `tests/plot_sync/config.py` * Align the multi harvester fixture with what we do in other places * Update the workflows Co-authored-by: Kyle Altendorf <sda@fstab.net>
2022-04-08 03:10:44 +03:00
from pathlib import Path
from secrets import token_bytes
from typing import Any, AsyncGenerator, Dict, Iterator, List, Optional, Tuple
from chia.cmds.init_funcs import init
from chia.consensus.constants import ConsensusConstants
from chia.daemon.server import WebSocketServer, daemon_launch_lock_path
2022-11-23 02:01:01 +03:00
from chia.farmer.farmer import Farmer
from chia.full_node.full_node import FullNode
from chia.harvester.harvester import Harvester
from chia.introducer.introducer import Introducer
Request header blocks, and new rate limits (#11636) * new blob block api method integrated into wallet * direct msg streaming of headers, rename, tests * perform_handshake call fix * updated trusted sync with new block header calls * add max blocks limit to fetch * added tests for rejected block header msgs * avoid parsing transactions info if not required * avoid looking up capabilities setting * move block tests out of a class * test fix * Merge changes * added docs and increased rate limits * increased block header request interval from 32 to 128 * remove fetching hashes and use height range * fetching by height in db v2 * update capabilities, other fixes * fixed range block header call * Add type hints * Start work on optimizing fetch_last_tx_from_peer * Huge speedup in trusted wallet sync * Revert unintentional changes * Fix trade issue * Improve the code * Str format * Optimize handling of farming rewards * Fix bug * Performance fixes * Optimizations to wallet syncing * Don't return all coins in respond_additions * Revert concurrency numbers * More optimization of the caches * Small optimization in coin_added * Optimize request_additions significantly by using a cache * fixes from feedback * capabilities check fixes * Increase rate limits to allow 250tps in verification requests * Start work on rate limits * New rate limit versioning support * Revert unrelated changes * revert return False * Lint * Revert cbi * try tests with trusted peer * Revert unrelated wallet changes * Revert more debug changes * Add test and throw on an error if not found * Reject invalid requests * Revert bad change with uint32, and change warning to info * Parametrize wallet sync test * Merge and LGTM * More clean way to choose peers * Fix lint * add the new RejectBlockHeaders, RequestBlockHeaders and RespondBlockHeaders to the network protocol regression test and regenerate test files * Rate limit diffs only * Improve performance * Simpler * Lint Co-authored-by: Sebastjan <trepca@gmail.com> Co-authored-by: arvidn <arvid@libtorrent.org>
2022-06-11 09:35:41 +03:00
from chia.protocols.shared_protocol import Capability, capabilities
from chia.server.start_farmer import create_farmer_service
from chia.server.start_full_node import create_full_node_service
from chia.server.start_harvester import create_harvester_service
from chia.server.start_introducer import create_introducer_service
2022-11-23 02:01:01 +03:00
from chia.server.start_service import Service
from chia.server.start_timelord import create_timelord_service
from chia.server.start_wallet import create_wallet_service
from chia.simulator.block_tools import BlockTools
from chia.simulator.keyring import TempKeyring
from chia.simulator.start_simulator import create_full_node_simulator_service
2022-11-23 02:01:01 +03:00
from chia.timelord.timelord import Timelord
from chia.timelord.timelord_launcher import kill_processes, spawn_process
from chia.types.peer_info import UnresolvedPeerInfo
from chia.util.bech32m import encode_puzzle_hash
from chia.util.config import config_path_for_filename, lock_and_load_config, save_config
from chia.util.ints import uint16
from chia.util.keychain import bytes_to_mnemonic
from chia.util.lock import Lockfile
2022-11-23 02:01:01 +03:00
from chia.wallet.wallet_node import WalletNode
log = logging.getLogger(__name__)
@contextmanager
def create_lock_and_load_config(certs_path: Path, root_path: Path) -> Iterator[Dict[str, Any]]:
init(None, root_path)
init(certs_path, root_path)
path = config_path_for_filename(root_path=root_path, filename="config.yaml")
# Using localhost leads to flakiness on CI
path.write_text(path.read_text().replace("localhost", "127.0.0.1"))
with lock_and_load_config(root_path, "config.yaml") as config:
yield config
Request header blocks, and new rate limits (#11636) * new blob block api method integrated into wallet * direct msg streaming of headers, rename, tests * perform_handshake call fix * updated trusted sync with new block header calls * add max blocks limit to fetch * added tests for rejected block header msgs * avoid parsing transactions info if not required * avoid looking up capabilities setting * move block tests out of a class * test fix * Merge changes * added docs and increased rate limits * increased block header request interval from 32 to 128 * remove fetching hashes and use height range * fetching by height in db v2 * update capabilities, other fixes * fixed range block header call * Add type hints * Start work on optimizing fetch_last_tx_from_peer * Huge speedup in trusted wallet sync * Revert unintentional changes * Fix trade issue * Improve the code * Str format * Optimize handling of farming rewards * Fix bug * Performance fixes * Optimizations to wallet syncing * Don't return all coins in respond_additions * Revert concurrency numbers * More optimization of the caches * Small optimization in coin_added * Optimize request_additions significantly by using a cache * fixes from feedback * capabilities check fixes * Increase rate limits to allow 250tps in verification requests * Start work on rate limits * New rate limit versioning support * Revert unrelated changes * revert return False * Lint * Revert cbi * try tests with trusted peer * Revert unrelated wallet changes * Revert more debug changes * Add test and throw on an error if not found * Reject invalid requests * Revert bad change with uint32, and change warning to info * Parametrize wallet sync test * Merge and LGTM * More clean way to choose peers * Fix lint * add the new RejectBlockHeaders, RequestBlockHeaders and RespondBlockHeaders to the network protocol regression test and regenerate test files * Rate limit diffs only * Improve performance * Simpler * Lint Co-authored-by: Sebastjan <trepca@gmail.com> Co-authored-by: arvidn <arvid@libtorrent.org>
2022-06-11 09:35:41 +03:00
def get_capabilities(disable_capabilities_values: Optional[List[Capability]]) -> List[Tuple[uint16, str]]:
if disable_capabilities_values is not None:
try:
if Capability.BASE in disable_capabilities_values:
# BASE capability cannot be removed
disable_capabilities_values.remove(Capability.BASE)
updated_capabilities = []
for capability in capabilities:
if Capability(int(capability[0])) in disable_capabilities_values:
# "0" means capability is disabled
updated_capabilities.append((capability[0], "0"))
else:
updated_capabilities.append(capability)
return updated_capabilities
except Exception:
logging.getLogger(__name__).exception("Error disabling capabilities, defaulting to all capabilities")
return capabilities.copy()
async def setup_daemon(btools: BlockTools) -> AsyncGenerator[WebSocketServer, None]:
root_path = btools.root_path
config = btools.config
assert "daemon_port" in config
crt_path = root_path / config["daemon_ssl"]["private_crt"]
key_path = root_path / config["daemon_ssl"]["private_key"]
ca_crt_path = root_path / config["private_ssl_ca"]["crt"]
ca_key_path = root_path / config["private_ssl_ca"]["key"]
with Lockfile.create(daemon_launch_lock_path(root_path)):
ws_server = WebSocketServer(root_path, ca_crt_path, ca_key_path, crt_path, key_path)
async with ws_server.run():
yield ws_server
async def setup_full_node(
consensus_constants: ConsensusConstants,
Bind port 0 to fix race condition when grabbing available ports (#11578) * port 0 to fix flakiness * Try fixing setup_full_system * Try fixing setup_full_system, and lint * More attempts to fix * No more calls to get random ports in setup_nodes * Revert accidental changes * Timelord extra arg * Try with port 0 * Fix daemon test, and lint * Try without 0.0.0.0 * Back to 0.0.0.0 * Try a few timelord changes to get test running * Increase timeout again * Use the correct interface to get the port * INFO logging to debug issue * Revert "INFO logging to debug issue" This reverts commit 7c379e5ccafbf7c30f9bd467cb1b5868dc8b3f6e. * Fix advertised port log * Add extra log * Logging back * Rollback the timelord changes * Try port 0 timelord * Revert "Try port 0 timelord" This reverts commit 4997faf3b22c0946cba52b1d1719552d24755355. * Try full green, change ordering * Remove unused var * speed up simulation and cleanup * Now try without the port config * Fix a flaky call to get_event_loop * Try getting the port dynamically * No dynamic port * Try changing the ordering * Try adding a sleep * Back to what works * Timelord before vdf clients * Dynamic port for 1st timelord * Revert "Dynamic port for 1st timelord" This reverts commit 0f322a15b7fbc85d41b2758b2625072ac847f350. * Revert "Timelord before vdf clients" This reverts commit 3286c34696d9d2f12304a88511763ac612bc7928. * Revert "Back to what works" This reverts commit 30380dffb76507a5171e2e2f8bb0ce4108039ad6. * Revert "Try adding a sleep" This reverts commit 9212b665a62a86c4c98d52cbd405ffb76221dd8b. * Revert "Try changing the ordering" This reverts commit a62597d70d1dfffde19ca5d82f73847798304ae1. * Revert "No dynamic port" This reverts commit 5d2e15749b3772b375b66317151044556a0e77fa. * Revert "Try getting the port dynamically" This reverts commit ef9cd75679bd235d6767fe30f8371cbca9b6e244. * Revert "Fix a flaky call to get_event_loop" This reverts commit 01a000fdfbe66353edc5ea432ee84e520b2e53d3. * Try one to 0 * Just not 0 * Don't get port dynamically * Cleanup a bit * Fix * Some cleanup work * Some cleanup work * Fix daemon test * Cleanup * Remove arguments
2022-05-23 18:13:49 +03:00
db_name: str,
self_hostname: str,
local_bt: BlockTools,
2022-11-23 02:01:01 +03:00
introducer_port: Optional[int] = None,
simulator: bool = False,
send_uncompact_interval: int = 0,
sanitize_weight_proof_only: bool = False,
connect_to_daemon: bool = False,
db_version: int = 1,
Request header blocks, and new rate limits (#11636) * new blob block api method integrated into wallet * direct msg streaming of headers, rename, tests * perform_handshake call fix * updated trusted sync with new block header calls * add max blocks limit to fetch * added tests for rejected block header msgs * avoid parsing transactions info if not required * avoid looking up capabilities setting * move block tests out of a class * test fix * Merge changes * added docs and increased rate limits * increased block header request interval from 32 to 128 * remove fetching hashes and use height range * fetching by height in db v2 * update capabilities, other fixes * fixed range block header call * Add type hints * Start work on optimizing fetch_last_tx_from_peer * Huge speedup in trusted wallet sync * Revert unintentional changes * Fix trade issue * Improve the code * Str format * Optimize handling of farming rewards * Fix bug * Performance fixes * Optimizations to wallet syncing * Don't return all coins in respond_additions * Revert concurrency numbers * More optimization of the caches * Small optimization in coin_added * Optimize request_additions significantly by using a cache * fixes from feedback * capabilities check fixes * Increase rate limits to allow 250tps in verification requests * Start work on rate limits * New rate limit versioning support * Revert unrelated changes * revert return False * Lint * Revert cbi * try tests with trusted peer * Revert unrelated wallet changes * Revert more debug changes * Add test and throw on an error if not found * Reject invalid requests * Revert bad change with uint32, and change warning to info * Parametrize wallet sync test * Merge and LGTM * More clean way to choose peers * Fix lint * add the new RejectBlockHeaders, RequestBlockHeaders and RespondBlockHeaders to the network protocol regression test and regenerate test files * Rate limit diffs only * Improve performance * Simpler * Lint Co-authored-by: Sebastjan <trepca@gmail.com> Co-authored-by: arvidn <arvid@libtorrent.org>
2022-06-11 09:35:41 +03:00
disable_capabilities: Optional[List[Capability]] = None,
2022-11-23 02:01:01 +03:00
) -> AsyncGenerator[Service[FullNode], None]:
db_path = local_bt.root_path / f"{db_name}"
if db_path.exists():
# TODO: remove (maybe) when fixed https://github.com/python/cpython/issues/97641
gc.collect()
db_path.unlink()
if db_version > 1:
with sqlite3.connect(db_path) as connection:
connection.execute("CREATE TABLE database_version(version int)")
connection.execute("INSERT INTO database_version VALUES (?)", (db_version,))
connection.commit()
if connect_to_daemon:
assert local_bt.config["daemon_port"] is not None
config = local_bt.config
service_config = config["full_node"]
service_config["database_path"] = db_name
service_config["testing"] = True
service_config["send_uncompact_interval"] = send_uncompact_interval
service_config["target_uncompact_proofs"] = 30
service_config["peer_connect_interval"] = 50
service_config["sanitize_weight_proof_only"] = sanitize_weight_proof_only
if introducer_port is not None:
service_config["introducer_peer"]["host"] = self_hostname
service_config["introducer_peer"]["port"] = introducer_port
else:
service_config["introducer_peer"] = None
service_config["dns_servers"] = []
service_config["port"] = 0
service_config["rpc_port"] = 0
Replace existing simulator config & Fix simulator (#12072) * redesign simulator config loader * edit initial config file and use it in start_simulator also final lint cleanup * small change * aarggggghhhh LINTTTTTTTTTTTTTTTT * fix lint for the last time DAMN END OF LINE * Add Types & change port * fix config loading for tests * change config options remove unnecessary options & change ports back * Add additional config options for old simulator * Get working simulator & implement the requirements i hope my code makes sense:) * remove extra part of config * fix config typos * add callback for autofarm we can call this to tell the node to farm a block * add auto farm rpc to simulator * add plot_directory to config add separate plot dir to avoid issues where the plot dir is shared with tests and an assert fails * remove port from config no longer needed due to existing gui simulator being broken * switch to dedicated plot creation function * modify api for greater block customization Added block type option & amount of block option * disable auto farm for tests breaks them all ;) Also made sure to run autofarm while a transaction is in mempool if the mode was just changed * change farm_block for the better * clean up autofarm remove unnecessary optional * update create block tools and allow additional plot creation tweaks & do requested fixes * change to k18's * minor nitpick * testing some changes stop reading these descriptions, just ask me on keybase * change plot directory name stuff * add editing of root level keys * use config_overrides * update plot info * re separate create_block_tools * revert some changes as requested change back get_plot_dir & undo change to asyncio.run * replace unnessary catch while adding plot locations switch to better if logic * combine simulator_bt function into main fix block_tools logic too * fix lint windows bad * test auto_farming * remove change that causes more harm then good * move test over and unflake it * make test do the bare minimum * add proper block waiting or wait avoidance * fix failing test * add new rpc client & a small fix * add new test & add some minor changes to start_sim to support it New test tests whole user facing simulator with real keychain, gui and daemon. * merge fixes * update block-cache version CHANGE TO MY USER, REVERT THIS LATER PLS REVERT BEFORE MERGE fix version * Revert "update block-cache version" This reverts commit 3afbbc5f51df002b84af3ce8f0f48e91cb503225. * block args from reaching simulator * clean up test plot creation * remove extra bt's being called this reduces load time * fix stupid bug * damn lint * Revert "remove extra bt's being called" This reverts commit f78debcc26c45a95bba6a369ddbd9e50c979c61d. * Revert "clean up test plot creation" This reverts commit d006a1a1963182531a97e69f258255d4ea2ce0be. * align with 12204 * rename RPC's for clarity * disable cache error when not running in automated mode * update tests with new rpc's oops i forgor * finalize sim api * something funky going on * Revert "something funky going on" This reverts commit afa1ddde27b3a45bd5d5ea4fabfd00e885266973. * fix config * add get_farming_ph rpc * remove random simulation thing, why are we even using this. * update tests * simplify test code & fix lint * lol one of my own pr's broke another one of my pr's git funny
2022-07-16 04:49:40 +03:00
config["simulator"]["auto_farm"] = False # Disable Auto Farm for tests
config["simulator"]["use_current_time"] = False # Disable Real timestamps when running tests
overrides = service_config["network_overrides"]["constants"][service_config["selected_network"]]
updated_constants = consensus_constants.replace_str_to_bytes(**overrides)
Replace existing simulator config & Fix simulator (#12072) * redesign simulator config loader * edit initial config file and use it in start_simulator also final lint cleanup * small change * aarggggghhhh LINTTTTTTTTTTTTTTTT * fix lint for the last time DAMN END OF LINE * Add Types & change port * fix config loading for tests * change config options remove unnecessary options & change ports back * Add additional config options for old simulator * Get working simulator & implement the requirements i hope my code makes sense:) * remove extra part of config * fix config typos * add callback for autofarm we can call this to tell the node to farm a block * add auto farm rpc to simulator * add plot_directory to config add separate plot dir to avoid issues where the plot dir is shared with tests and an assert fails * remove port from config no longer needed due to existing gui simulator being broken * switch to dedicated plot creation function * modify api for greater block customization Added block type option & amount of block option * disable auto farm for tests breaks them all ;) Also made sure to run autofarm while a transaction is in mempool if the mode was just changed * change farm_block for the better * clean up autofarm remove unnecessary optional * update create block tools and allow additional plot creation tweaks & do requested fixes * change to k18's * minor nitpick * testing some changes stop reading these descriptions, just ask me on keybase * change plot directory name stuff * add editing of root level keys * use config_overrides * update plot info * re separate create_block_tools * revert some changes as requested change back get_plot_dir & undo change to asyncio.run * replace unnessary catch while adding plot locations switch to better if logic * combine simulator_bt function into main fix block_tools logic too * fix lint windows bad * test auto_farming * remove change that causes more harm then good * move test over and unflake it * make test do the bare minimum * add proper block waiting or wait avoidance * fix failing test * add new rpc client & a small fix * add new test & add some minor changes to start_sim to support it New test tests whole user facing simulator with real keychain, gui and daemon. * merge fixes * update block-cache version CHANGE TO MY USER, REVERT THIS LATER PLS REVERT BEFORE MERGE fix version * Revert "update block-cache version" This reverts commit 3afbbc5f51df002b84af3ce8f0f48e91cb503225. * block args from reaching simulator * clean up test plot creation * remove extra bt's being called this reduces load time * fix stupid bug * damn lint * Revert "remove extra bt's being called" This reverts commit f78debcc26c45a95bba6a369ddbd9e50c979c61d. * Revert "clean up test plot creation" This reverts commit d006a1a1963182531a97e69f258255d4ea2ce0be. * align with 12204 * rename RPC's for clarity * disable cache error when not running in automated mode * update tests with new rpc's oops i forgor * finalize sim api * something funky going on * Revert "something funky going on" This reverts commit afa1ddde27b3a45bd5d5ea4fabfd00e885266973. * fix config * add get_farming_ph rpc * remove random simulation thing, why are we even using this. * update tests * simplify test code & fix lint * lol one of my own pr's broke another one of my pr's git funny
2022-07-16 04:49:40 +03:00
local_bt.change_config(config)
override_capabilities = None if disable_capabilities is None else get_capabilities(disable_capabilities)
if simulator:
service = create_full_node_simulator_service(
local_bt.root_path,
config,
local_bt,
connect_to_daemon=connect_to_daemon,
override_capabilities=override_capabilities,
)
else:
service = create_full_node_service(
local_bt.root_path,
config,
updated_constants,
connect_to_daemon=connect_to_daemon,
override_capabilities=override_capabilities,
)
await service.start()
yield service
service.stop()
await service.wait_closed()
if db_path.exists():
# TODO: remove (maybe) when fixed https://github.com/python/cpython/issues/97641
gc.collect()
db_path.unlink()
# Note: convert these setup functions to fixtures, or push it one layer up,
# keeping these usable independently?
async def setup_wallet_node(
self_hostname: str,
consensus_constants: ConsensusConstants,
local_bt: BlockTools,
spam_filter_after_n_txs: Optional[int] = 200,
xch_spam_amount: int = 1000000,
full_node_port: Optional[uint16] = None,
introducer_port: Optional[uint16] = None,
key_seed: Optional[bytes] = None,
initial_num_public_keys: int = 5,
2022-11-23 02:01:01 +03:00
) -> AsyncGenerator[Service[WalletNode], None]:
with TempKeyring(populate=True) as keychain:
config = local_bt.config
service_config = config["wallet"]
service_config["testing"] = True
service_config["port"] = 0
service_config["rpc_port"] = 0
service_config["initial_num_public_keys"] = initial_num_public_keys
service_config["spam_filter_after_n_txs"] = spam_filter_after_n_txs
service_config["xch_spam_amount"] = xch_spam_amount
entropy = token_bytes(32)
if key_seed is None:
key_seed = entropy
keychain.add_private_key(bytes_to_mnemonic(key_seed))
first_pk = keychain.get_first_public_key()
assert first_pk is not None
db_path_key_suffix = str(first_pk.get_fingerprint())
Bind port 0 to fix race condition when grabbing available ports (#11578) * port 0 to fix flakiness * Try fixing setup_full_system * Try fixing setup_full_system, and lint * More attempts to fix * No more calls to get random ports in setup_nodes * Revert accidental changes * Timelord extra arg * Try with port 0 * Fix daemon test, and lint * Try without 0.0.0.0 * Back to 0.0.0.0 * Try a few timelord changes to get test running * Increase timeout again * Use the correct interface to get the port * INFO logging to debug issue * Revert "INFO logging to debug issue" This reverts commit 7c379e5ccafbf7c30f9bd467cb1b5868dc8b3f6e. * Fix advertised port log * Add extra log * Logging back * Rollback the timelord changes * Try port 0 timelord * Revert "Try port 0 timelord" This reverts commit 4997faf3b22c0946cba52b1d1719552d24755355. * Try full green, change ordering * Remove unused var * speed up simulation and cleanup * Now try without the port config * Fix a flaky call to get_event_loop * Try getting the port dynamically * No dynamic port * Try changing the ordering * Try adding a sleep * Back to what works * Timelord before vdf clients * Dynamic port for 1st timelord * Revert "Dynamic port for 1st timelord" This reverts commit 0f322a15b7fbc85d41b2758b2625072ac847f350. * Revert "Timelord before vdf clients" This reverts commit 3286c34696d9d2f12304a88511763ac612bc7928. * Revert "Back to what works" This reverts commit 30380dffb76507a5171e2e2f8bb0ce4108039ad6. * Revert "Try adding a sleep" This reverts commit 9212b665a62a86c4c98d52cbd405ffb76221dd8b. * Revert "Try changing the ordering" This reverts commit a62597d70d1dfffde19ca5d82f73847798304ae1. * Revert "No dynamic port" This reverts commit 5d2e15749b3772b375b66317151044556a0e77fa. * Revert "Try getting the port dynamically" This reverts commit ef9cd75679bd235d6767fe30f8371cbca9b6e244. * Revert "Fix a flaky call to get_event_loop" This reverts commit 01a000fdfbe66353edc5ea432ee84e520b2e53d3. * Try one to 0 * Just not 0 * Don't get port dynamically * Cleanup a bit * Fix * Some cleanup work * Some cleanup work * Fix daemon test * Cleanup * Remove arguments
2022-05-23 18:13:49 +03:00
db_name = f"test-wallet-db-{full_node_port}-KEY.sqlite"
db_path_replaced: str = db_name.replace("KEY", db_path_key_suffix)
db_path = local_bt.root_path / db_path_replaced
if db_path.exists():
# TODO: remove (maybe) when fixed https://github.com/python/cpython/issues/97641
gc.collect()
db_path.unlink()
service_config["database_path"] = str(db_name)
service_config["testing"] = True
service_config["introducer_peer"]["host"] = self_hostname
if introducer_port is not None:
service_config["introducer_peer"]["port"] = introducer_port
service_config["peer_connect_interval"] = 10
else:
service_config["introducer_peer"] = None
if full_node_port is not None:
service_config["full_node_peer"] = {}
service_config["full_node_peer"]["host"] = self_hostname
service_config["full_node_peer"]["port"] = full_node_port
else:
del service_config["full_node_peer"]
service = create_wallet_service(
local_bt.root_path,
config,
consensus_constants,
keychain,
connect_to_daemon=False,
)
await service.start()
yield service
service.stop()
await service.wait_closed()
if db_path.exists():
# TODO: remove (maybe) when fixed https://github.com/python/cpython/issues/97641
gc.collect()
db_path.unlink()
keychain.delete_all_keys()
async def setup_harvester(
b_tools: BlockTools,
chia|tests|github: Implement, integrate and test plot sync protocol (#9695) * protocols|server: Define new harvester plot refreshing protocol messages * protocols: Bump `protocol_version` to `0.0.34` * tests: Introduce `setup_farmer_multi_harvester` Allows to run a test setup with 1 farmer and mutiple harvesters. * plotting: Add an initial plot loading indication to `PlotManager` * plotting|tests: Don't add removed duplicates to `total_result.removed` `PlotRefreshResult.removed` should only contain plots that were loaded properly before they were removed. It shouldn't contain e.g. removed duplicates or invalid plots since those are synced in an extra sync step and not as diff but as whole list every time. * harvester: Reset `PlotManager` on shutdown * plot_sync: Implement plot sync protocol * farmer|harvester: Integrate and enable plot sync * tests: Implement tests for the plot sync protocol * farmer|tests: Drop obsolete harvester caching code * setup: Add `chia.plot_sync` to packages * plot_sync: Type hints in `DeltaType` * plot_sync: Drop parameters in `super()` calls * plot_sync: Introduce `send_response` helper in `Receiver._process` * plot_sync: Add some parentheses Co-authored-by: Kyle Altendorf <sda@fstab.net> * plot_sync: Additional hint for a `Receiver.process_path_list` parameter * plot_sync: Force named parameters in `Receiver.process_path_list` * test: Fix fixtures after rebase * tests: Fix sorting after rebase * tests: Return type hint for `plot_sync_setup` * tests: Rename `WSChiaConnection` and move it in the outer scope * tests|plot_sync: More type hints * tests: Rework some delta tests * tests: Drop a `range` and iterate over the list directly * tests: Use the proper flags to overwrite * test: More missing duplicates tests * tests: Drop `ExpectedResult.reset` * tests: Reduce some asserts * tests: Add messages to some `assert False` statements * tests: Introduce `ErrorSimulation` enum in `test_sync_simulated.py` * tests: Use `secrects` instead of `Crypto.Random` * Fixes after rebase * Import from `typing_extensions` to support python 3.7 * Drop task name to support python 3.7 * Introduce `Sender.syncing`, `Sender.connected` and a log about the task * Add `tests/plot_sync/config.py` * Align the multi harvester fixture with what we do in other places * Update the workflows Co-authored-by: Kyle Altendorf <sda@fstab.net>
2022-04-08 03:10:44 +03:00
root_path: Path,
farmer_peer: Optional[UnresolvedPeerInfo],
consensus_constants: ConsensusConstants,
start_service: bool = True,
2022-11-23 02:01:01 +03:00
) -> AsyncGenerator[Service[Harvester], None]:
with create_lock_and_load_config(b_tools.root_path / "config" / "ssl" / "ca", root_path) as config:
config["logging"]["log_stdout"] = True
config["selected_network"] = "testnet0"
config["harvester"]["selected_network"] = "testnet0"
Bind port 0 to fix race condition when grabbing available ports (#11578) * port 0 to fix flakiness * Try fixing setup_full_system * Try fixing setup_full_system, and lint * More attempts to fix * No more calls to get random ports in setup_nodes * Revert accidental changes * Timelord extra arg * Try with port 0 * Fix daemon test, and lint * Try without 0.0.0.0 * Back to 0.0.0.0 * Try a few timelord changes to get test running * Increase timeout again * Use the correct interface to get the port * INFO logging to debug issue * Revert "INFO logging to debug issue" This reverts commit 7c379e5ccafbf7c30f9bd467cb1b5868dc8b3f6e. * Fix advertised port log * Add extra log * Logging back * Rollback the timelord changes * Try port 0 timelord * Revert "Try port 0 timelord" This reverts commit 4997faf3b22c0946cba52b1d1719552d24755355. * Try full green, change ordering * Remove unused var * speed up simulation and cleanup * Now try without the port config * Fix a flaky call to get_event_loop * Try getting the port dynamically * No dynamic port * Try changing the ordering * Try adding a sleep * Back to what works * Timelord before vdf clients * Dynamic port for 1st timelord * Revert "Dynamic port for 1st timelord" This reverts commit 0f322a15b7fbc85d41b2758b2625072ac847f350. * Revert "Timelord before vdf clients" This reverts commit 3286c34696d9d2f12304a88511763ac612bc7928. * Revert "Back to what works" This reverts commit 30380dffb76507a5171e2e2f8bb0ce4108039ad6. * Revert "Try adding a sleep" This reverts commit 9212b665a62a86c4c98d52cbd405ffb76221dd8b. * Revert "Try changing the ordering" This reverts commit a62597d70d1dfffde19ca5d82f73847798304ae1. * Revert "No dynamic port" This reverts commit 5d2e15749b3772b375b66317151044556a0e77fa. * Revert "Try getting the port dynamically" This reverts commit ef9cd75679bd235d6767fe30f8371cbca9b6e244. * Revert "Fix a flaky call to get_event_loop" This reverts commit 01a000fdfbe66353edc5ea432ee84e520b2e53d3. * Try one to 0 * Just not 0 * Don't get port dynamically * Cleanup a bit * Fix * Some cleanup work * Some cleanup work * Fix daemon test * Cleanup * Remove arguments
2022-05-23 18:13:49 +03:00
config["harvester"]["port"] = 0
config["harvester"]["rpc_port"] = 0
config["harvester"]["plot_directories"] = [str(b_tools.plot_dir.resolve())]
save_config(root_path, "config.yaml", config)
service = create_harvester_service(
root_path,
config,
consensus_constants,
farmer_peer=farmer_peer,
connect_to_daemon=False,
)
if start_service:
await service.start()
yield service
service.stop()
await service.wait_closed()
async def setup_farmer(
b_tools: BlockTools,
root_path: Path,
self_hostname: str,
consensus_constants: ConsensusConstants,
full_node_port: Optional[uint16] = None,
start_service: bool = True,
Bind port 0 to fix race condition when grabbing available ports (#11578) * port 0 to fix flakiness * Try fixing setup_full_system * Try fixing setup_full_system, and lint * More attempts to fix * No more calls to get random ports in setup_nodes * Revert accidental changes * Timelord extra arg * Try with port 0 * Fix daemon test, and lint * Try without 0.0.0.0 * Back to 0.0.0.0 * Try a few timelord changes to get test running * Increase timeout again * Use the correct interface to get the port * INFO logging to debug issue * Revert "INFO logging to debug issue" This reverts commit 7c379e5ccafbf7c30f9bd467cb1b5868dc8b3f6e. * Fix advertised port log * Add extra log * Logging back * Rollback the timelord changes * Try port 0 timelord * Revert "Try port 0 timelord" This reverts commit 4997faf3b22c0946cba52b1d1719552d24755355. * Try full green, change ordering * Remove unused var * speed up simulation and cleanup * Now try without the port config * Fix a flaky call to get_event_loop * Try getting the port dynamically * No dynamic port * Try changing the ordering * Try adding a sleep * Back to what works * Timelord before vdf clients * Dynamic port for 1st timelord * Revert "Dynamic port for 1st timelord" This reverts commit 0f322a15b7fbc85d41b2758b2625072ac847f350. * Revert "Timelord before vdf clients" This reverts commit 3286c34696d9d2f12304a88511763ac612bc7928. * Revert "Back to what works" This reverts commit 30380dffb76507a5171e2e2f8bb0ce4108039ad6. * Revert "Try adding a sleep" This reverts commit 9212b665a62a86c4c98d52cbd405ffb76221dd8b. * Revert "Try changing the ordering" This reverts commit a62597d70d1dfffde19ca5d82f73847798304ae1. * Revert "No dynamic port" This reverts commit 5d2e15749b3772b375b66317151044556a0e77fa. * Revert "Try getting the port dynamically" This reverts commit ef9cd75679bd235d6767fe30f8371cbca9b6e244. * Revert "Fix a flaky call to get_event_loop" This reverts commit 01a000fdfbe66353edc5ea432ee84e520b2e53d3. * Try one to 0 * Just not 0 * Don't get port dynamically * Cleanup a bit * Fix * Some cleanup work * Some cleanup work * Fix daemon test * Cleanup * Remove arguments
2022-05-23 18:13:49 +03:00
port: uint16 = uint16(0),
2022-11-23 02:01:01 +03:00
) -> AsyncGenerator[Service[Farmer], None]:
with create_lock_and_load_config(b_tools.root_path / "config" / "ssl" / "ca", root_path) as root_config:
root_config["logging"]["log_stdout"] = True
root_config["selected_network"] = "testnet0"
root_config["farmer"]["selected_network"] = "testnet0"
save_config(root_path, "config.yaml", root_config)
service_config = root_config["farmer"]
config_pool = root_config["pool"]
service_config["xch_target_address"] = encode_puzzle_hash(b_tools.farmer_ph, "xch")
service_config["pool_public_keys"] = [bytes(pk).hex() for pk in b_tools.pool_pubkeys]
service_config["port"] = port
service_config["rpc_port"] = uint16(0)
config_pool["xch_target_address"] = encode_puzzle_hash(b_tools.pool_ph, "xch")
if full_node_port:
service_config["full_node_peer"]["host"] = self_hostname
service_config["full_node_peer"]["port"] = full_node_port
else:
del service_config["full_node_peer"]
service = create_farmer_service(
root_path,
root_config,
config_pool,
consensus_constants,
b_tools.local_keychain,
connect_to_daemon=False,
)
if start_service:
await service.start()
yield service
service.stop()
await service.wait_closed()
2022-11-23 02:01:01 +03:00
async def setup_introducer(bt: BlockTools, port: int) -> AsyncGenerator[Service[Introducer], None]:
service = create_introducer_service(
bt.root_path,
bt.config,
advertised_port=port,
connect_to_daemon=False,
)
await service.start()
yield service
service.stop()
await service.wait_closed()
2022-11-23 02:01:01 +03:00
async def setup_vdf_client(bt: BlockTools, self_hostname: str, port: int) -> AsyncGenerator[asyncio.Task[Any], None]:
lock = asyncio.Lock()
vdf_task_1 = asyncio.create_task(
spawn_process(self_hostname, port, 1, lock, prefer_ipv6=bt.config.get("prefer_ipv6", False))
)
def stop() -> None:
asyncio.create_task(kill_processes(lock))
asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, stop)
asyncio.get_running_loop().add_signal_handler(signal.SIGINT, stop)
yield vdf_task_1
await kill_processes(lock)
async def setup_vdf_clients(
2022-11-23 02:01:01 +03:00
bt: BlockTools, self_hostname: str, port: int
) -> AsyncGenerator[Tuple[asyncio.Task[Any], asyncio.Task[Any], asyncio.Task[Any]], None]:
lock = asyncio.Lock()
vdf_task_1 = asyncio.create_task(
spawn_process(self_hostname, port, 1, lock, prefer_ipv6=bt.config.get("prefer_ipv6", False))
)
vdf_task_2 = asyncio.create_task(
spawn_process(self_hostname, port, 2, lock, prefer_ipv6=bt.config.get("prefer_ipv6", False))
)
vdf_task_3 = asyncio.create_task(
spawn_process(self_hostname, port, 3, lock, prefer_ipv6=bt.config.get("prefer_ipv6", False))
)
def stop() -> None:
asyncio.create_task(kill_processes(lock))
asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, stop)
asyncio.get_running_loop().add_signal_handler(signal.SIGINT, stop)
yield vdf_task_1, vdf_task_2, vdf_task_3
await kill_processes(lock)
async def setup_timelord(
2022-11-23 02:01:01 +03:00
full_node_port: int,
sanitizer: bool,
Bind port 0 to fix race condition when grabbing available ports (#11578) * port 0 to fix flakiness * Try fixing setup_full_system * Try fixing setup_full_system, and lint * More attempts to fix * No more calls to get random ports in setup_nodes * Revert accidental changes * Timelord extra arg * Try with port 0 * Fix daemon test, and lint * Try without 0.0.0.0 * Back to 0.0.0.0 * Try a few timelord changes to get test running * Increase timeout again * Use the correct interface to get the port * INFO logging to debug issue * Revert "INFO logging to debug issue" This reverts commit 7c379e5ccafbf7c30f9bd467cb1b5868dc8b3f6e. * Fix advertised port log * Add extra log * Logging back * Rollback the timelord changes * Try port 0 timelord * Revert "Try port 0 timelord" This reverts commit 4997faf3b22c0946cba52b1d1719552d24755355. * Try full green, change ordering * Remove unused var * speed up simulation and cleanup * Now try without the port config * Fix a flaky call to get_event_loop * Try getting the port dynamically * No dynamic port * Try changing the ordering * Try adding a sleep * Back to what works * Timelord before vdf clients * Dynamic port for 1st timelord * Revert "Dynamic port for 1st timelord" This reverts commit 0f322a15b7fbc85d41b2758b2625072ac847f350. * Revert "Timelord before vdf clients" This reverts commit 3286c34696d9d2f12304a88511763ac612bc7928. * Revert "Back to what works" This reverts commit 30380dffb76507a5171e2e2f8bb0ce4108039ad6. * Revert "Try adding a sleep" This reverts commit 9212b665a62a86c4c98d52cbd405ffb76221dd8b. * Revert "Try changing the ordering" This reverts commit a62597d70d1dfffde19ca5d82f73847798304ae1. * Revert "No dynamic port" This reverts commit 5d2e15749b3772b375b66317151044556a0e77fa. * Revert "Try getting the port dynamically" This reverts commit ef9cd75679bd235d6767fe30f8371cbca9b6e244. * Revert "Fix a flaky call to get_event_loop" This reverts commit 01a000fdfbe66353edc5ea432ee84e520b2e53d3. * Try one to 0 * Just not 0 * Don't get port dynamically * Cleanup a bit * Fix * Some cleanup work * Some cleanup work * Fix daemon test * Cleanup * Remove arguments
2022-05-23 18:13:49 +03:00
consensus_constants: ConsensusConstants,
b_tools: BlockTools,
vdf_port: uint16 = uint16(0),
2022-11-23 02:01:01 +03:00
) -> AsyncGenerator[Service[Timelord], None]:
config = b_tools.config
service_config = config["timelord"]
service_config["full_node_peer"]["port"] = full_node_port
service_config["bluebox_mode"] = sanitizer
service_config["fast_algorithm"] = False
service_config["vdf_server"]["port"] = vdf_port
service_config["start_rpc_server"] = True
service_config["rpc_port"] = uint16(0)
service = create_timelord_service(
b_tools.root_path,
config,
consensus_constants,
connect_to_daemon=False,
)
await service.start()
yield service
service.stop()
await service.wait_closed()