From 21bce632d6eb5eec1b9acb0b2376e89c0af5ab8f Mon Sep 17 00:00:00 2001 From: derekpierre Date: Fri, 29 Sep 2023 11:52:41 -0400 Subject: [PATCH 01/63] Create implicit mapping of TACo network name to entries for eth network and poly network. Provider class level SUPPORTED_NETWORKS and SUPPORTED_NETWORK_NAMES constants. --- nucypher/blockchain/eth/networks.py | 100 +++++++++++++++------------- 1 file changed, 54 insertions(+), 46 deletions(-) diff --git a/nucypher/blockchain/eth/networks.py b/nucypher/blockchain/eth/networks.py index b1cd572e6..ffb6f9736 100644 --- a/nucypher/blockchain/eth/networks.py +++ b/nucypher/blockchain/eth/networks.py @@ -1,57 +1,65 @@ -class NetworksInventory: # TODO: See #1564 +from enum import Enum +from typing import List, NamedTuple - MAINNET = "mainnet" - LYNX = "lynx" - IBEX = "ibex" # this is required for configuration file migrations (backwards compatibility) - ETH = "ethereum" - TAPIR = "tapir" - ORYX = "oryx" - # TODO: Use naming scheme to preserve multiple compatibility with multiple deployments to a single network? - POLYGON = 'polygon' - MUMBAI = 'mumbai' +class EthNetwork(Enum): + MAINNET = 1 + GOERLI = 5 + SEPOLIA = 11155111 + # testing + TESTERCHAIN = 131277322940537 - UNKNOWN = 'unknown' # TODO: Is there a better way to signal an unknown network? - DEFAULT = MAINNET - __to_chain_id_eth = { - MAINNET: 1, # Ethereum Mainnet - IBEX: 5, # this is required for configuration file migrations (backwards compatibility) - LYNX: 5, # Goerli - TAPIR: 11155111, # Sepolia - ORYX: 5, # Goerli - } - __to_chain_id_polygon = { - # TODO: Use naming scheme? - POLYGON: 137, # Polygon Mainnet - MUMBAI: 80001, # Polygon Testnet (Mumbai) - } +class PolyNetwork(Enum): + POLYGON = 137 + MUMBAI = 80001 + # testing + TESTERCHAIN = 131277322940537 - ETH_NETWORKS = tuple(__to_chain_id_eth.keys()) - POLY_NETWORKS = tuple(__to_chain_id_polygon.keys()) - NETWORKS = ETH_NETWORKS + POLY_NETWORKS +class TACoNetwork(NamedTuple): + name: str + eth_network: EthNetwork + poly_network: PolyNetwork - class UnrecognizedNetwork(RuntimeError): - pass + +class UnrecognizedNetwork(RuntimeError): + """Raised when a provided network name is not recognized.""" + pass + + +class NetworksInventory: + MAINNET = TACoNetwork("mainnet", EthNetwork.MAINNET, PolyNetwork.POLYGON) + # Testnets + ORYX = TACoNetwork("oryx", EthNetwork.GOERLI, PolyNetwork.POLYGON) + LYNX = TACoNetwork("lynx", EthNetwork.GOERLI, PolyNetwork.MUMBAI) + TAPIR = TACoNetwork("tapir", EthNetwork.SEPOLIA, PolyNetwork.MUMBAI) + # TODO did Ibex even use a PolyNetwork? + IBEX = TACoNetwork( + "ibex", EthNetwork.GOERLI, PolyNetwork.MUMBAI + ) # this is required for configuration file migrations (backwards compatibility) + + SUPPORTED_NETWORKS = [ + MAINNET, + ORYX, + LYNX, + TAPIR, + IBEX, + ] + + SUPPORTED_NETWORK_NAMES = {network.name for network in SUPPORTED_NETWORKS} + + DEFAULT: str = MAINNET.name @classmethod - def get_ethereum_chain_id(cls, network): - try: - return cls.__to_chain_id_eth[network] - except KeyError: - raise cls.UnrecognizedNetwork(network) + def get_network(cls, network_name: str) -> TACoNetwork: + for network in cls.SUPPORTED_NETWORKS: + if network.name == network_name: + return network + + raise UnrecognizedNetwork(f"{network_name} is not a recognized network.") @classmethod - def get_polygon_chain_id(cls, network): - try: - return cls.__to_chain_id_polygon[network] - except KeyError: - raise cls.UnrecognizedNetwork(network) - - @classmethod - def validate_network_name(cls, network_name: str): - if network_name not in cls.NETWORKS: - raise cls.UnrecognizedNetwork( - f"{network_name} is not a recognized network." - ) + def get_network_names(cls) -> List[str]: + networks = [network.name for network in cls.SUPPORTED_NETWORKS] + return networks From 751140384c43301d0f0b47e5cf902115f766797f Mon Sep 17 00:00:00 2001 From: derekpierre Date: Fri, 29 Sep 2023 12:23:56 -0400 Subject: [PATCH 02/63] Update network selection logic via the CLI and update test. --- nucypher/cli/actions/select.py | 13 +++--------- .../cli/actions/test_select_network.py | 20 +++++++------------ 2 files changed, 10 insertions(+), 23 deletions(-) diff --git a/nucypher/cli/actions/select.py b/nucypher/cli/actions/select.py index 94c55919d..adead84f1 100644 --- a/nucypher/cli/actions/select.py +++ b/nucypher/cli/actions/select.py @@ -1,5 +1,3 @@ - - import os from pathlib import Path from typing import Optional, Type @@ -70,7 +68,7 @@ def select_client_account( blockchain = BlockchainInterfaceFactory.get_interface(eth_provider_uri=eth_provider_uri) if signer_uri and not signer: - testnet = network != NetworksInventory.MAINNET + testnet = network != NetworksInventory.MAINNET.name signer = Signer.from_signer_uri(signer_uri, testnet=testnet) # Display accounts info @@ -120,15 +118,10 @@ def select_client_account( return chosen_account -def select_network(emitter: StdoutEmitter, network_type: str, message: Optional[str] = None) -> str: +def select_network(emitter: StdoutEmitter, message: Optional[str] = None) -> str: """Interactively select a network from nucypher networks inventory list""" emitter.message(message=message or str(), color="yellow") - if network_type == NetworksInventory.ETH: - network_list = NetworksInventory.ETH_NETWORKS - elif network_type == NetworksInventory.POLYGON: - network_list = NetworksInventory.POLY_NETWORKS - else: - raise(ValueError("Network type must be either 'eth' or 'polygon'")) + network_list = NetworksInventory.SUPPORTED_NETWORK_NAMES rows = [[n] for n in network_list] emitter.echo(tabulate(rows, showindex="always")) choice = click.prompt( diff --git a/tests/integration/cli/actions/test_select_network.py b/tests/integration/cli/actions/test_select_network.py index dafd8a518..a41ee2df0 100644 --- a/tests/integration/cli/actions/test_select_network.py +++ b/tests/integration/cli/actions/test_select_network.py @@ -3,22 +3,16 @@ import pytest from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.cli.actions.select import select_network +__NETWORKS = NetworksInventory.SUPPORTED_NETWORK_NAMES -@pytest.mark.parametrize( - "user_input", range(0, len(NetworksInventory.ETH_NETWORKS) - 1) -) -def test_select_network_cli_action_eth(test_emitter, capsys, mock_stdin, user_input): + +@pytest.mark.parametrize("user_input", range(0, len(__NETWORKS) - 1)) +def test_select_network_cli_action(test_emitter, capsys, mock_stdin, user_input: int): mock_stdin.line(str(user_input)) - selection = NetworksInventory.ETH_NETWORKS[user_input] - result = select_network(emitter=test_emitter, network_type=NetworksInventory.ETH) + selection = __NETWORKS[user_input] + result = select_network(emitter=test_emitter) assert result == selection - assert result not in NetworksInventory.POLY_NETWORKS captured = capsys.readouterr() - for name in NetworksInventory.ETH_NETWORKS: + for name in __NETWORKS: assert name in captured.out assert mock_stdin.empty() - - -def test_select_network_cli_action_neither(test_emitter): - with pytest.raises(Exception): - select_network(emitter=test_emitter, network_type="FAKE COIN") From 66021923687a2eee965c696158db2bc95bf4d57b Mon Sep 17 00:00:00 2001 From: derekpierre Date: Fri, 29 Sep 2023 13:00:58 -0400 Subject: [PATCH 03/63] Update mocking for NetworksInventory class in tests. --- tests/conftest.py | 19 ++++++++++++++----- tests/utils/registry.py | 20 ++++++++++---------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 634b01924..fa4be4f7d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,7 +4,13 @@ import pytest from eth_utils.crypto import keccak from nucypher.blockchain.eth.actors import Operator -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth.networks import ( + EthNetwork, + NetworksInventory, + PolyNetwork, + TACoNetwork, +) +from nucypher.config.constants import TEMPORARY_DOMAIN from nucypher.crypto.powers import TransactingPower from nucypher.network.nodes import Learner from nucypher.utilities.logging import GlobalLoggerSettings @@ -141,13 +147,16 @@ def mock_condition_blockchains(session_mocker): "nucypher.policy.conditions.evm._CONDITION_CHAINS", {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - - session_mocker.patch.object( - NetworksInventory, "get_polygon_chain_id", return_value=TESTERCHAIN_CHAIN_ID + testing_network = TACoNetwork( + TEMPORARY_DOMAIN, EthNetwork.TESTERCHAIN, PolyNetwork.TESTERCHAIN ) session_mocker.patch.object( - NetworksInventory, "get_ethereum_chain_id", return_value=TESTERCHAIN_CHAIN_ID + NetworksInventory, "get_network_names", return_value=[TEMPORARY_DOMAIN] + ) + + session_mocker.patch.object( + NetworksInventory, "get_network", return_value=testing_network ) diff --git a/tests/utils/registry.py b/tests/utils/registry.py index 44303d541..1aa3782a0 100644 --- a/tests/utils/registry.py +++ b/tests/utils/registry.py @@ -5,7 +5,7 @@ from typing import List from ape.contracts import ContractInstance from eth_utils import to_checksum_address -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth.networks import EthNetwork, NetworksInventory, PolyNetwork, TACoNetwork from nucypher.blockchain.eth.registry import ( RegistryData, RegistrySource, @@ -17,24 +17,24 @@ from nucypher.config.constants import TEMPORARY_DOMAIN @contextmanager def mock_registry_sources(): # capture the real values - real_networks = NetworksInventory.NETWORKS - real_eth_networks = NetworksInventory.ETH_NETWORKS - real_poly_networks = NetworksInventory.POLY_NETWORKS + real_network_names = NetworksInventory.SUPPORTED_NETWORK_NAMES + real_networks = NetworksInventory.SUPPORTED_NETWORKS real_registry_sources = RegistrySourceManager._FALLBACK_CHAIN # set the mock values + NetworksInventory.SUPPORTED_NETWORK_NAMES = {TEMPORARY_DOMAIN} + testing_network = TACoNetwork( + TEMPORARY_DOMAIN, EthNetwork.TESTERCHAIN, PolyNetwork.TESTERCHAIN + ) + NetworksInventory.SUPPORTED_NETWORKS = [testing_network] RegistrySourceManager._FALLBACK_CHAIN = (MockRegistrySource,) - NetworksInventory.NETWORKS = (TEMPORARY_DOMAIN,) - NetworksInventory.ETH_NETWORKS = (TEMPORARY_DOMAIN,) - NetworksInventory.POLY_NETWORKS = (TEMPORARY_DOMAIN,) yield # run the test # restore the real values + NetworksInventory.SUPPORTED_NETWORK_NAMES = real_network_names + NetworksInventory.SUPPORTED_NETWORKS = real_networks RegistrySourceManager._FALLBACK_CHAIN = real_registry_sources - NetworksInventory.NETWORKS = real_networks - NetworksInventory.ETH_NETWORKS = real_eth_networks - NetworksInventory.POLY_NETWORKS = real_poly_networks class MockRegistrySource(RegistrySource): From 9d869f5f088df1726a9668a8183d967a9f53bf42 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Fri, 29 Sep 2023 13:03:17 -0400 Subject: [PATCH 04/63] Update calls to NetworksInventory as they pertain to unit tests passing. --- nucypher/blockchain/eth/registry.py | 4 ++-- nucypher/cli/commands/taco.py | 2 +- nucypher/cli/commands/ursula.py | 15 ++++----------- nucypher/config/characters.py | 9 ++++----- 4 files changed, 11 insertions(+), 19 deletions(-) diff --git a/nucypher/blockchain/eth/registry.py b/nucypher/blockchain/eth/registry.py index f5e5d0bc2..ad1adad09 100644 --- a/nucypher/blockchain/eth/registry.py +++ b/nucypher/blockchain/eth/registry.py @@ -34,10 +34,10 @@ class RegistrySource(ABC): """Raised when there are no available registry sources""" def __init__(self, domain: str, *args, **kwargs): - if domain not in NetworksInventory.NETWORKS: + if domain not in NetworksInventory.SUPPORTED_NETWORK_NAMES: raise ValueError( f"{self.__class__.__name__} not available for domain '{domain}'. " - f"Valid options are: {', '.join(list(NetworksInventory.NETWORKS))}" + f"Valid options are: {', '.join(list(NetworksInventory.SUPPORTED_NETWORK_NAMES))}" ) self.domain = domain self.data = self.get() diff --git a/nucypher/cli/commands/taco.py b/nucypher/cli/commands/taco.py index a7bdfc752..c0a44fdd9 100644 --- a/nucypher/cli/commands/taco.py +++ b/nucypher/cli/commands/taco.py @@ -42,7 +42,7 @@ option_network = click.option( "--network", help="TACo Network", type=click.STRING, - default=click.Choice(NetworksInventory.NETWORKS), + default=click.Choice(NetworksInventory.SUPPORTED_NETWORK_NAMES), required=True, ) diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index 37082dc0d..c62da98d7 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -2,7 +2,6 @@ from pathlib import Path import click -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.cli.actions.auth import ( get_client_password, get_nucypher_password, @@ -15,7 +14,9 @@ from nucypher.cli.actions.configure import ( handle_missing_configuration_file, perform_startup_ip_check, ) -from nucypher.cli.actions.configure import forget as forget_nodes +from nucypher.cli.actions.configure import ( + forget as forget_nodes, +) from nucypher.cli.actions.select import ( select_client_account, select_config_file, @@ -26,7 +27,6 @@ from nucypher.cli.literature import ( DEVELOPMENT_MODE_WARNING, FORCE_MODE_WARNING, SELECT_OPERATOR_ACCOUNT, - SELECT_PRE_PAYMENT_NETWORK, ) from nucypher.cli.options import ( group_options, @@ -351,14 +351,7 @@ def init(general_config, config_options, force, config_root, key_material): if not config_options.domain: config_options.domain = select_network( emitter, - message="Select Staking Network", - network_type=NetworksInventory.ETH, - ) - if not config_options.pre_payment_network: - config_options.pre_payment_network = select_network( - emitter, - message=SELECT_PRE_PAYMENT_NETWORK, - network_type=NetworksInventory.POLYGON, + message="Select TACo Network", ) ursula_config = config_options.generate_config( emitter=emitter, config_root=config_root, force=force, key_material=key_material diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index e79882ab1..aa9b25c79 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -69,12 +69,11 @@ class UrsulaConfiguration(CharacterConfiguration): self.configure_condition_provider_uris() def configure_condition_provider_uris(self) -> None: - """Configure default condition provider URIs for mainnet and polygon network.""" + """Configure default condition provider URIs for eth and polygon network.""" + taco_network = NetworksInventory.get_network(self.domain) # Polygon - polygon_chain_id = NetworksInventory.get_polygon_chain_id( - self.pre_payment_network - ) + polygon_chain_id = taco_network.poly_network.value polygon_provider_uris = self.condition_provider_uris.get(polygon_chain_id, []) if not polygon_provider_uris: self.condition_provider_uris[polygon_chain_id] = polygon_provider_uris @@ -83,7 +82,7 @@ class UrsulaConfiguration(CharacterConfiguration): polygon_provider_uris.append(self.pre_payment_provider) # Ethereum - staking_chain_id = NetworksInventory.get_ethereum_chain_id(self.domain) + staking_chain_id = taco_network.eth_network.value staking_provider_uris = self.condition_provider_uris.get(staking_chain_id, []) if not staking_provider_uris: self.condition_provider_uris[staking_chain_id] = staking_provider_uris From bfa4d0bc79c216e12a9a638d76eebd6413e29c31 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Fri, 29 Sep 2023 13:12:54 -0400 Subject: [PATCH 05/63] Integration tests mock modifications for network resolution. --- tests/integration/conftest.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 0f1199177..399946c2f 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -18,7 +18,12 @@ from nucypher.blockchain.eth.interfaces import ( BlockchainInterface, BlockchainInterfaceFactory, ) -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth.networks import ( + EthNetwork, + NetworksInventory, + PolyNetwork, + TACoNetwork, +) from nucypher.blockchain.eth.registry import ( ContractRegistry, ) @@ -286,12 +291,16 @@ def mock_condition_blockchains(session_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - session_mocker.patch.object( - NetworksInventory, "get_polygon_chain_id", return_value=TESTERCHAIN_CHAIN_ID + testing_network = TACoNetwork( + TEMPORARY_DOMAIN, EthNetwork.TESTERCHAIN, PolyNetwork.TESTERCHAIN ) session_mocker.patch.object( - NetworksInventory, "get_ethereum_chain_id", return_value=TESTERCHAIN_CHAIN_ID + NetworksInventory, "get_network_names", return_value=[TEMPORARY_DOMAIN] + ) + + session_mocker.patch.object( + NetworksInventory, "get_network", return_value=testing_network ) From f278b9d9f14b2440d77ce5089903d9fd4dcd0ff0 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Fri, 29 Sep 2023 13:20:44 -0400 Subject: [PATCH 06/63] Acceptance tests mock modifications for network resolution. --- tests/acceptance/conftest.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index e57bc7c22..7405af85e 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -12,7 +12,12 @@ from nucypher.blockchain.eth.agents import ( TACoChildApplicationAgent, ) from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth.networks import ( + EthNetwork, + NetworksInventory, + PolyNetwork, + TACoNetwork, +) from nucypher.blockchain.eth.registry import ContractRegistry, RegistrySourceManager from nucypher.blockchain.eth.signers.software import Web3Signer from nucypher.config.constants import TEMPORARY_DOMAIN @@ -434,12 +439,16 @@ def mock_condition_blockchains(session_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - session_mocker.patch.object( - NetworksInventory, "get_polygon_chain_id", return_value=TESTERCHAIN_CHAIN_ID + testing_network = TACoNetwork( + TEMPORARY_DOMAIN, EthNetwork.TESTERCHAIN, PolyNetwork.TESTERCHAIN ) session_mocker.patch.object( - NetworksInventory, "get_ethereum_chain_id", return_value=TESTERCHAIN_CHAIN_ID + NetworksInventory, "get_network_names", return_value=[TEMPORARY_DOMAIN] + ) + + session_mocker.patch.object( + NetworksInventory, "get_network", return_value=testing_network ) From 4166c7dae95e5e301c95a74bbe5a18d611acdfd6 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Fri, 29 Sep 2023 14:47:18 -0400 Subject: [PATCH 07/63] Rename eth_provider_uri to eth_endpoint as it pertains to Characters/nodes/CLI options. --- .../finnegans-wake-demo-l2.py | 4 +-- examples/pre/heartbeat_demo/alicia.py | 2 +- examples/pre/heartbeat_demo/doctor.py | 2 +- examples/testnet_compound_multichain_taco.py | 2 +- examples/testnet_simple_taco.py | 2 +- nucypher/blockchain/eth/actors.py | 10 +++---- nucypher/blockchain/eth/trackers/bonding.py | 2 +- nucypher/characters/base.py | 14 +++++---- nucypher/characters/lawful.py | 22 +++++++------- nucypher/characters/unlawful.py | 2 +- nucypher/cli/actions/configure.py | 2 +- nucypher/cli/commands/ursula.py | 30 +++++++++---------- nucypher/cli/options.py | 5 ++-- nucypher/config/base.py | 20 ++++++------- nucypher/config/characters.py | 4 +-- .../migrations/configuration_v5_to_v6.py | 5 ++-- nucypher/network/middleware.py | 6 +++- nucypher/network/nodes.py | 26 ++++++++-------- nucypher/utilities/prometheus/metrics.py | 6 ++-- .../characters/test_fault_tolerance.py | 8 ++--- tests/acceptance/characters/test_operator.py | 4 +-- .../characters/test_transacting_power.py | 2 +- tests/acceptance/cli/test_ursula_init.py | 2 +- tests/acceptance/cli/test_ursula_run.py | 8 ++--- tests/fixtures.py | 20 +++++++------ .../test_bob_joins_policy_and_retrieves.py | 2 +- tests/integration/cli/test_cli_config.py | 17 +++++++---- tests/integration/cli/test_mixed_config.py | 4 +-- .../cli/test_ursula_cli_ip_detection.py | 6 ++-- .../integration/cli/test_ursula_config_cli.py | 4 +-- ...ursula_local_keystore_cli_functionality.py | 2 +- .../config/test_character_configuration.py | 8 ++--- .../config/test_configuration_persistence.py | 4 +-- .../config/test_keystore_integration.py | 8 ++--- tests/integration/config/test_storages.py | 2 +- tests/metrics/grant_availability.py | 2 +- tests/unit/test_character_sign_and_verify.py | 8 ++--- tests/utils/config.py | 6 ++-- 38 files changed, 148 insertions(+), 135 deletions(-) diff --git a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py index 3744db254..c0b7c7376 100644 --- a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py +++ b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py @@ -55,7 +55,7 @@ L2_NETWORK = "mumbai" # rest of the network from the seednode. bob = Bob( domain=L1_NETWORK, - eth_provider_uri=L1_PROVIDER, + eth_endpoint=L1_PROVIDER, ) # Bob puts his public keys somewhere alice can find them. @@ -90,7 +90,7 @@ alice = Alice( checksum_address=ALICE_ADDRESS, signer=wallet, domain=L1_NETWORK, - eth_provider_uri=L1_PROVIDER, + eth_endpoint=L1_PROVIDER, pre_payment_method=pre_payment_method, ) diff --git a/examples/pre/heartbeat_demo/alicia.py b/examples/pre/heartbeat_demo/alicia.py index 8611a1d49..e431f2c7e 100644 --- a/examples/pre/heartbeat_demo/alicia.py +++ b/examples/pre/heartbeat_demo/alicia.py @@ -88,7 +88,7 @@ alicia = Alice( checksum_address=ALICE_ADDRESS, signer=wallet, domain=L1_NETWORK, - eth_provider_uri=L1_PROVIDER, + eth_endpoint=L1_PROVIDER, pre_payment_method=pre_payment_method, ) diff --git a/examples/pre/heartbeat_demo/doctor.py b/examples/pre/heartbeat_demo/doctor.py index 8c151fa0e..df93f633b 100644 --- a/examples/pre/heartbeat_demo/doctor.py +++ b/examples/pre/heartbeat_demo/doctor.py @@ -45,7 +45,7 @@ print("Creating the Doctor ...") doctor = Bob( domain=L1_NETWORK, crypto_power_ups=power_ups, - eth_provider_uri=L1_PROVIDER, + eth_endpoint=L1_PROVIDER, ) print("Doctor = ", doctor) diff --git a/examples/testnet_compound_multichain_taco.py b/examples/testnet_compound_multichain_taco.py index 7ed0fcff2..6afda0a91 100644 --- a/examples/testnet_compound_multichain_taco.py +++ b/examples/testnet_compound_multichain_taco.py @@ -96,7 +96,7 @@ print(f"\nEncrypted message:\n{bytes(threshold_message_kit).hex()}") print("--------- Threshold Decryption ---------") bob = Bob( - eth_provider_uri=staking_provider_uri, + eth_endpoint=staking_provider_uri, domain=network, coordinator_provider_uri=coordinator_provider_uri, coordinator_network=coordinator_network, diff --git a/examples/testnet_simple_taco.py b/examples/testnet_simple_taco.py index 21778f19d..3befd6f05 100644 --- a/examples/testnet_simple_taco.py +++ b/examples/testnet_simple_taco.py @@ -73,7 +73,7 @@ print(f"\nEncrypted message:\n{bytes(threshold_message_kit).hex()}") print("--------- Threshold Decryption ---------") bob = Bob( - eth_provider_uri=staking_provider_uri, + eth_endpoint=staking_provider_uri, domain=network, coordinator_provider_uri=coordinator_provider_uri, coordinator_network=coordinator_network, diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index 20380cfc9..017f2a0e1 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -158,7 +158,7 @@ class Operator(BaseActor): def __init__( self, - eth_provider_uri: str, + eth_endpoint: str, coordinator_provider_uri: str, coordinator_network: str, pre_payment_method: ContractPayment, @@ -173,7 +173,7 @@ class Operator(BaseActor): **kwargs, ): # Falsy values may be passed down from the superclass - if not eth_provider_uri: + if not eth_endpoint: raise ValueError("Ethereum Provider URI is required to init an operator.") if not coordinator_provider_uri: raise ValueError("Polygon Provider URI is required to init an operator.") @@ -204,7 +204,7 @@ class Operator(BaseActor): self.application_agent = ContractAgency.get_agent( TACoApplicationAgent, - provider_uri=eth_provider_uri, + provider_uri=eth_endpoint, registry=self.registry, ) @@ -742,10 +742,10 @@ class Operator(BaseActor): class PolicyAuthor(NucypherTokenActor): """Alice base class for blockchain operations, mocking up new policies!""" - def __init__(self, eth_provider_uri: str, *args, **kwargs): + def __init__(self, eth_endpoint: str, *args, **kwargs): super().__init__(*args, **kwargs) self.application_agent = ContractAgency.get_agent( - TACoApplicationAgent, registry=self.registry, provider_uri=eth_provider_uri + TACoApplicationAgent, registry=self.registry, provider_uri=eth_endpoint ) def create_policy(self, *args, **kwargs): diff --git a/nucypher/blockchain/eth/trackers/bonding.py b/nucypher/blockchain/eth/trackers/bonding.py index 0e966de13..ffe0051ac 100644 --- a/nucypher/blockchain/eth/trackers/bonding.py +++ b/nucypher/blockchain/eth/trackers/bonding.py @@ -20,7 +20,7 @@ class OperatorBondedTracker(SimpleTask): application_agent = ContractAgency.get_agent( TACoApplicationAgent, registry=self._ursula.registry, - provider_uri=self._ursula.eth_provider_uri, + provider_uri=self._ursula.eth_endpoint, ) # use TACo root since unbonding happens at root and not child (more immediate this way) staking_provider_address = application_agent.get_staking_provider_from_operator( diff --git a/nucypher/characters/base.py b/nucypher/characters/base.py index fedd22d96..0180b254b 100644 --- a/nucypher/characters/base.py +++ b/nucypher/characters/base.py @@ -34,7 +34,7 @@ class Character(Learner): def __init__( self, domain: str, - eth_provider_uri: str = None, + eth_endpoint: str = None, known_node_class: object = None, is_me: bool = True, checksum_address: str = None, @@ -113,14 +113,16 @@ class Character(Learner): except NoSigningPower: self._stamp = NO_SIGNING_POWER - self.eth_provider_uri = eth_provider_uri - self.registry = registry or ContractRegistry.from_latest_publication( - domain=domain + self.eth_endpoint = eth_endpoint + self.registry = ( + registry + or ContractRegistry.from_latest_publication(domain=domain) ) # See #1580 # REST - self.network_middleware = network_middleware or RestMiddleware(registry=self.registry, - eth_provider_uri=eth_provider_uri) + self.network_middleware = network_middleware or RestMiddleware( + registry=self.registry, eth_provider_uri=eth_endpoint + ) # Learner Learner.__init__(self, diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index 803f2729e..ca15ec094 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -131,7 +131,7 @@ class Alice(Character, actors.PolicyAuthor): self, # Mode is_me: bool = True, - eth_provider_uri: str = None, + eth_endpoint: str = None, signer=None, # Ownership checksum_address: Optional[ChecksumAddress] = None, @@ -170,7 +170,7 @@ class Alice(Character, actors.PolicyAuthor): self, known_node_class=Ursula, is_me=is_me, - eth_provider_uri=eth_provider_uri, + eth_endpoint=eth_endpoint, checksum_address=checksum_address, network_middleware=network_middleware, *args, @@ -179,7 +179,7 @@ class Alice(Character, actors.PolicyAuthor): if is_me: # TODO: #289 blockchain = BlockchainInterfaceFactory.get_interface( - eth_provider_uri=self.eth_provider_uri + eth_provider_uri=self.eth_endpoint ) signer = signer or Web3Signer( blockchain.client @@ -193,7 +193,7 @@ class Alice(Character, actors.PolicyAuthor): domain=self.domain, transacting_power=self.transacting_power, registry=self.registry, - eth_provider_uri=eth_provider_uri, + eth_endpoint=eth_endpoint, ) self.log = Logger(self.__class__.__name__) @@ -458,7 +458,7 @@ class Bob(Character): self, is_me: bool = True, verify_node_bonding: bool = False, - eth_provider_uri: str = None, + eth_endpoint: str = None, coordinator_provider_uri: str = None, # TODO: Move to a higher level and formalize coordinator_network: str = None, # TODO: Move to a higher level and formalize *args, @@ -469,7 +469,7 @@ class Bob(Character): is_me=is_me, known_node_class=Ursula, verify_node_bonding=verify_node_bonding, - eth_provider_uri=eth_provider_uri, + eth_endpoint=eth_endpoint, *args, **kwargs, ) @@ -825,7 +825,7 @@ class Ursula(Teacher, Character, Operator): client_password: Optional[str] = None, transacting_power: Optional[TransactingPower] = None, operator_signature_from_metadata=NOT_SIGNED, - eth_provider_uri: Optional[str] = None, + eth_endpoint: Optional[str] = None, condition_provider_uris: Optional[Dict[int, List[str]]] = None, pre_payment_method: Optional[Union[PaymentMethod, ContractPayment]] = None, # Character @@ -844,7 +844,7 @@ class Ursula(Teacher, Character, Operator): domain=domain, known_node_class=Ursula, include_self_in_the_state=True, - eth_provider_uri=eth_provider_uri, + eth_endpoint=eth_endpoint, **character_kwargs, ) @@ -863,7 +863,7 @@ class Ursula(Teacher, Character, Operator): signer=self.signer, crypto_power=self._crypto_power, operator_address=operator_address, - eth_provider_uri=eth_provider_uri, + eth_endpoint=eth_endpoint, pre_payment_method=pre_payment_method, client_password=client_password, condition_provider_uris=condition_provider_uris, @@ -997,10 +997,10 @@ class Ursula(Teacher, Character, Operator): # Connect to Provider if not BlockchainInterfaceFactory.is_interface_initialized( - eth_provider_uri=self.eth_provider_uri + eth_provider_uri=self.eth_endpoint ): BlockchainInterfaceFactory.initialize_interface( - eth_provider_uri=self.eth_provider_uri + eth_provider_uri=self.eth_endpoint ) if preflight: diff --git a/nucypher/characters/unlawful.py b/nucypher/characters/unlawful.py index 46abdac8f..2b384cc20 100644 --- a/nucypher/characters/unlawful.py +++ b/nucypher/characters/unlawful.py @@ -75,7 +75,7 @@ class Vladimir(Ursula): checksum_address=cls.fraud_address, operator_address=cls.fraud_address, signer=Web3Signer(blockchain.client), - eth_provider_uri=blockchain.eth_provider_uri, + eth_endpoint=blockchain.eth_provider_uri, pre_payment_method=bogus_pre_payment_method, ) diff --git a/nucypher/cli/actions/configure.py b/nucypher/cli/actions/configure.py index 909749f70..228ea0b95 100644 --- a/nucypher/cli/actions/configure.py +++ b/nucypher/cli/actions/configure.py @@ -159,7 +159,7 @@ def perform_startup_ip_check(emitter: StdoutEmitter, ursula: Ursula, force: bool external_ip = determine_external_ip_address( network=ursula.domain, known_nodes=ursula.known_nodes, - provider_uri=ursula.eth_provider_uri, + provider_uri=ursula.eth_endpoint, ) except UnknownIPAddress: message = 'Cannot automatically determine external IP address' diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index c62da98d7..d448d18a1 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -34,7 +34,7 @@ from nucypher.cli.options import ( option_config_root, option_dev, option_dry_run, - option_eth_provider_uri, + option_eth_endpoint, option_force, option_gas_strategy, option_key_material, @@ -74,7 +74,7 @@ class UrsulaConfigOptions: def __init__( self, - eth_provider_uri: str, + eth_endpoint: str, operator_address: str, rest_host: str, rest_port: int, @@ -93,7 +93,7 @@ class UrsulaConfigOptions: pre_payment_network: str, ): - self.eth_provider_uri = eth_provider_uri + self.eth_endpoint = eth_endpoint self.signer_uri = signer_uri self.operator_address = operator_address self.rest_host = rest_host @@ -121,7 +121,7 @@ class UrsulaConfigOptions: light=self.light, registry_filepath=self.registry_filepath, policy_registry_filepath=self.policy_registry_filepath, - eth_provider_uri=self.eth_provider_uri, + eth_endpoint=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, @@ -144,7 +144,7 @@ class UrsulaConfigOptions: domain=self.domain, registry_filepath=self.registry_filepath, policy_registry_filepath=self.policy_registry_filepath, - eth_provider_uri=self.eth_provider_uri, + eth_endpoint=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, @@ -175,7 +175,7 @@ class UrsulaConfigOptions: self.operator_address = select_client_account( emitter=emitter, prompt=prompt, - eth_provider_uri=self.eth_provider_uri, + eth_provider_uri=self.eth_endpoint, signer_uri=self.signer_uri, ) @@ -185,7 +185,7 @@ class UrsulaConfigOptions: emitter, network=self.domain, force=force, - provider_uri=self.eth_provider_uri, + provider_uri=self.eth_endpoint, ) return UrsulaConfiguration.generate( @@ -198,7 +198,7 @@ class UrsulaConfigOptions: operator_address=self.operator_address, registry_filepath=self.registry_filepath, policy_registry_filepath=self.policy_registry_filepath, - eth_provider_uri=self.eth_provider_uri, + eth_provider_uri=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, @@ -217,7 +217,7 @@ class UrsulaConfigOptions: operator_address=self.operator_address, registry_filepath=self.registry_filepath, policy_registry_filepath=self.policy_registry_filepath, - eth_provider_uri=self.eth_provider_uri, + eth_provider_uri=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, @@ -235,7 +235,7 @@ class UrsulaConfigOptions: group_config_options = group_options( # NOTE: Don't set defaults here or they will be applied to config updates. Use the Config API. UrsulaConfigOptions, - eth_provider_uri=option_eth_provider_uri(), + eth_endpoint=option_eth_endpoint(), signer_uri=option_signer_uri, gas_strategy=option_gas_strategy, max_gas_price=option_max_gas_price, @@ -290,7 +290,7 @@ class UrsulaCharacterOptions: URSULA = make_cli_character( character_config=ursula_config, emitter=emitter, - provider_uri=ursula_config.eth_provider_uri, + provider_uri=ursula_config.eth_endpoint, min_stake=self.min_stake, teacher_uri=self.teacher_uri, unlock_keystore=not self.config_options.dev, @@ -333,11 +333,11 @@ def init(general_config, config_options, force, config_root, key_material): _pre_launch_warnings(emitter, dev=None, force=force) if not config_root: config_root = general_config.config_root - if not config_options.eth_provider_uri: + if not config_options.eth_endpoint: raise click.BadOptionUsage( - "--eth-provider", + "--eth-endpoint", message=click.style( - "--eth-provider is required to initialize a new ursula.", fg="red" + "--eth-endpoint is required to initialize a new ursula.", fg="red" ), ) if not config_options.pre_payment_provider: @@ -491,7 +491,7 @@ def config(general_config, config_options, config_file, force, action): emitter=emitter, network=config_options.domain, force=force, - provider_uri=config_options.eth_provider_uri, + provider_uri=config_options.eth_endpoint, ) config_options.rest_host = rest_host if action == "migrate": diff --git a/nucypher/cli/options.py b/nucypher/cli/options.py index 574dafa21..059b1ff26 100644 --- a/nucypher/cli/options.py +++ b/nucypher/cli/options.py @@ -199,9 +199,10 @@ def option_policy_encrypting_key(required: bool = False): required=required) -def option_eth_provider_uri(default=None, required: bool = False): +def option_eth_endpoint(default=None, required: bool = False): return click.option( - '--eth-provider', 'eth_provider_uri', + "--eth-endpoint", + "eth_endpoint", help="Blockchain provider's URI i.e. 'file:///path/to/geth.ipc'", type=click.STRING, required=required, diff --git a/nucypher/config/base.py b/nucypher/config/base.py index fcaaf1d51..9b41f854d 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -368,7 +368,7 @@ class CharacterConfiguration(BaseConfiguration): # Blockchain poa: Optional[bool] = None, light: bool = False, - eth_provider_uri: Optional[str] = None, + eth_endpoint: Optional[str] = None, gas_strategy: Union[Callable, str] = DEFAULT_GAS_STRATEGY, max_gas_price: Optional[int] = None, signer_uri: Optional[str] = None, @@ -418,7 +418,7 @@ class CharacterConfiguration(BaseConfiguration): # Blockchain self.poa = poa self.is_light = light - self.eth_provider_uri = eth_provider_uri or NO_BLOCKCHAIN_CONNECTION + self.eth_endpoint = eth_endpoint or NO_BLOCKCHAIN_CONNECTION self.signer_uri = signer_uri or None # Learner @@ -443,11 +443,11 @@ class CharacterConfiguration(BaseConfiguration): self.gas_strategy = gas_strategy self.max_gas_price = max_gas_price # gwei is_initialized = BlockchainInterfaceFactory.is_interface_initialized( - eth_provider_uri=self.eth_provider_uri + eth_provider_uri=self.eth_endpoint ) - if not is_initialized and eth_provider_uri: + if not is_initialized and eth_endpoint: BlockchainInterfaceFactory.initialize_interface( - eth_provider_uri=self.eth_provider_uri, + eth_provider_uri=self.eth_endpoint, poa=self.poa, light=self.is_light, emitter=emitter, @@ -456,7 +456,7 @@ class CharacterConfiguration(BaseConfiguration): ) else: self.log.warn( - f"Using existing blockchain interface connection ({self.eth_provider_uri})." + f"Using existing blockchain interface connection ({self.eth_endpoint})." ) # TODO: this is potential fix for multichain connection, if we want to use it build it out into a loop @@ -533,7 +533,7 @@ class CharacterConfiguration(BaseConfiguration): # Network self.network_middleware = network_middleware or self.DEFAULT_NETWORK_MIDDLEWARE( - registry=self.registry, eth_provider_uri=self.eth_provider_uri + registry=self.registry, eth_provider_uri=self.eth_endpoint ) super().__init__(filepath=self.config_file_location, config_root=self.config_root) @@ -703,12 +703,12 @@ class CharacterConfiguration(BaseConfiguration): ) # Optional values (mode) - if self.eth_provider_uri: + if self.eth_endpoint: if not self.signer_uri: - self.signer_uri = self.eth_provider_uri + self.signer_uri = self.eth_endpoint payload.update( dict( - eth_provider_uri=self.eth_provider_uri, + eth_endpoint=self.eth_endpoint, poa=self.poa, light=self.is_light, signer_uri=self.signer_uri, diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index aa9b25c79..c536a122d 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -87,8 +87,8 @@ class UrsulaConfiguration(CharacterConfiguration): if not staking_provider_uris: self.condition_provider_uris[staking_chain_id] = staking_provider_uris - if self.eth_provider_uri not in staking_provider_uris: - staking_provider_uris.append(self.eth_provider_uri) + if self.eth_endpoint not in staking_provider_uris: + staking_provider_uris.append(self.eth_endpoint) @classmethod def address_from_filepath(cls, filepath: Path) -> str: diff --git a/nucypher/config/migrations/configuration_v5_to_v6.py b/nucypher/config/migrations/configuration_v5_to_v6.py index 47b4acbf4..5ff35994f 100644 --- a/nucypher/config/migrations/configuration_v5_to_v6.py +++ b/nucypher/config/migrations/configuration_v5_to_v6.py @@ -5,10 +5,11 @@ from nucypher.config.migrations.common import perform_migration def __migration(config: Dict) -> Dict: + taco_network = NetworksInventory.get_network(config["domain"]) eth_provider = config["eth_provider_uri"] - eth_chain_id = NetworksInventory.get_ethereum_chain_id(config["domain"]) + eth_chain_id = taco_network.eth_network.value polygon_provider = config["payment_provider"] - polygon_chain_id = NetworksInventory.get_polygon_chain_id(config["payment_network"]) + polygon_chain_id = taco_network.poly_network.value if "condition_provider_uris" in config: return config config["condition_provider_uris"] = { diff --git a/nucypher/network/middleware.py b/nucypher/network/middleware.py index ce8dcd912..79a9771ec 100644 --- a/nucypher/network/middleware.py +++ b/nucypher/network/middleware.py @@ -88,7 +88,11 @@ class NucypherMiddlewareClient: if node_or_sprout: if node_or_sprout is not EXEMPT_FROM_VERIFICATION: node = node_or_sprout.mature() # Morph into a node. - node.verify_node(network_middleware_client=self, registry=self.registry, eth_provider_uri=self.eth_provider_uri) + node.verify_node( + network_middleware_client=self, + registry=self.registry, + eth_endpoint=self.eth_provider_uri, + ) return self.parse_node_or_host_and_port(node_or_sprout, host, port) def parse_node_or_host_and_port(self, node, host, port): diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index 0fb24993a..b53fe0fad 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -272,7 +272,7 @@ class Learner: self.learning_deferred = Deferred() self.domain = domain default_middleware = self.__DEFAULT_MIDDLEWARE_CLASS( - registry=self.registry, eth_provider_uri=self.eth_provider_uri + registry=self.registry, eth_provider_uri=self.eth_endpoint ) self.network_middleware = network_middleware or default_middleware self.save_metadata = save_metadata @@ -359,7 +359,7 @@ class Learner: maybe_sage_node = self.node_class.from_teacher_uri( teacher_uri=uri, min_stake=0, - provider_uri=self.eth_provider_uri, + provider_uri=self.eth_endpoint, network_middleware=self.network_middleware, registry=self.registry, ) @@ -383,7 +383,7 @@ class Learner: seed_node = self.node_class.from_seednode_metadata( seednode_metadata=seednode_metadata, network_middleware=self.network_middleware, - provider_uri=self.eth_provider_uri, + provider_uri=self.eth_endpoint, ) except Exception as e: # TODO: log traceback here? @@ -472,7 +472,7 @@ class Learner: force=force_verification_recheck, network_middleware_client=self.network_middleware.client, registry=registry, - eth_provider_uri=self.eth_provider_uri, + eth_endpoint=self.eth_endpoint, ) except SSLError: # TODO: Bucket this node as having bad TLS info - maybe it's an update that hasn't fully propagated? 567 @@ -1056,14 +1056,14 @@ class Teacher: return staking_provider_address == self.checksum_address def _staking_provider_is_really_staking( - self, registry: ContractRegistry, eth_provider_uri: Optional[str] = None + self, registry: ContractRegistry, eth_endpoint: Optional[str] = None ) -> bool: """ This method assumes the stamp's signature is valid and accurate. As a follow-up, this checks that the staking provider is, indeed, staking. """ application_agent = ContractAgency.get_agent( - TACoApplicationAgent, registry=registry, provider_uri=eth_provider_uri + TACoApplicationAgent, registry=registry, provider_uri=eth_endpoint ) # type: TACoApplicationAgent is_staking = application_agent.is_authorized(staking_provider=self.checksum_address) # checksum address here is staking provider return is_staking @@ -1071,7 +1071,7 @@ class Teacher: def validate_operator( self, registry: ContractRegistry = None, - eth_provider_uri: Optional[str] = None, + eth_endpoint: Optional[str] = None, ) -> None: # TODO: restore this enforcement # if registry and not eth_provider_uri: @@ -1088,14 +1088,14 @@ class Teacher: # On-chain staking check, if registry is present if registry: if not self._operator_is_bonded( - registry=registry, provider_uri=eth_provider_uri + registry=registry, provider_uri=eth_endpoint ): # <-- Blockchain CALL message = f"Operator {self.operator_address} is not bonded to staking provider {self.checksum_address}" self.log.debug(message) raise self.UnbondedOperator(message) if self._staking_provider_is_really_staking( - registry=registry, eth_provider_uri=eth_provider_uri + registry=registry, eth_endpoint=eth_endpoint ): # <-- Blockchain CALL self.log.info(f"Verified operator {self}") self.verified_operator = True @@ -1115,7 +1115,7 @@ class Teacher: raise self.InvalidNode("Metadata signature is invalid") def validate_metadata( - self, registry: ContractRegistry = None, eth_provider_uri: Optional[str] = None + self, registry: ContractRegistry = None, eth_endpoint: Optional[str] = None ): # Verify the metadata signature if not self.verified_metadata: @@ -1126,13 +1126,13 @@ class Teacher: return # Offline check of valid stamp signature by worker - self.validate_operator(registry=registry, eth_provider_uri=eth_provider_uri) + self.validate_operator(registry=registry, eth_endpoint=eth_endpoint) def verify_node( self, network_middleware_client, registry: ContractRegistry = None, - eth_provider_uri: Optional[str] = None, + eth_endpoint: Optional[str] = None, certificate_filepath: Optional[Path] = None, force: bool = False, ) -> bool: @@ -1165,7 +1165,7 @@ class Teacher: ) # This is both the stamp's client signature and interface metadata check; May raise InvalidNode - self.validate_metadata(registry=registry, eth_provider_uri=eth_provider_uri) + self.validate_metadata(registry=registry, eth_endpoint=eth_endpoint) # The node's metadata is valid; let's be sure the interface is in order. if not certificate_filepath: diff --git a/nucypher/utilities/prometheus/metrics.py b/nucypher/utilities/prometheus/metrics.py index 40978b4ea..02a0a822c 100644 --- a/nucypher/utilities/prometheus/metrics.py +++ b/nucypher/utilities/prometheus/metrics.py @@ -157,16 +157,14 @@ def create_metrics_collectors(ursula: "lawful.Ursula") -> List[MetricsCollector] # Blockchain prometheus # TODO possible include information about payment - collectors.append( - BlockchainMetricsCollector(eth_provider_uri=ursula.eth_provider_uri) - ) + collectors.append(BlockchainMetricsCollector(eth_provider_uri=ursula.eth_endpoint)) # Staking Provider prometheus collectors.append( StakingProviderMetricsCollector( staking_provider_address=ursula.checksum_address, contract_registry=ursula.registry, - eth_provider_uri=ursula.eth_provider_uri, + eth_provider_uri=ursula.eth_endpoint, ) ) diff --git a/tests/acceptance/characters/test_fault_tolerance.py b/tests/acceptance/characters/test_fault_tolerance.py index d9f406769..020a1f574 100644 --- a/tests/acceptance/characters/test_fault_tolerance.py +++ b/tests/acceptance/characters/test_fault_tolerance.py @@ -137,12 +137,12 @@ def test_invalid_operators_tolerance( force=True, registry=test_registry, network_middleware_client=ursula.network_middleware.client, - eth_provider_uri=ursula.eth_provider_uri, + eth_endpoint=ursula.eth_endpoint, ) # In particular, we know that it's bonded to a staker who is really staking. assert ursula.is_confirmed assert ursula._staking_provider_is_really_staking( - registry=test_registry, eth_provider_uri=TEST_ETH_PROVIDER_URI + registry=test_registry, eth_endpoint=TEST_ETH_PROVIDER_URI ) # OK. Now we learn about this new worker. @@ -161,7 +161,7 @@ def test_invalid_operators_tolerance( # OK...so...the staker is not staking anymore ... assert not ursula._staking_provider_is_really_staking( - registry=test_registry, eth_provider_uri=TEST_ETH_PROVIDER_URI + registry=test_registry, eth_endpoint=TEST_ETH_PROVIDER_URI ) # ... but the worker node still is "verified" (since we're not forcing on-chain verification) @@ -176,7 +176,7 @@ def test_invalid_operators_tolerance( force=True, registry=test_registry, network_middleware_client=ursula.network_middleware.client, - eth_provider_uri=TEST_ETH_PROVIDER_URI, + eth_endpoint=TEST_ETH_PROVIDER_URI, ) # diff --git a/tests/acceptance/characters/test_operator.py b/tests/acceptance/characters/test_operator.py index f6a4a4383..8a2fbef2d 100644 --- a/tests/acceptance/characters/test_operator.py +++ b/tests/acceptance/characters/test_operator.py @@ -16,7 +16,7 @@ def test_stakers_bond_to_ursulas(ursulas, test_registry, staking_providers): assert len(ursulas) == len(staking_providers) for ursula in ursulas: ursula.validate_operator( - registry=test_registry, eth_provider_uri=TEST_ETH_PROVIDER_URI + registry=test_registry, eth_endpoint=TEST_ETH_PROVIDER_URI ) assert ursula.verified_operator @@ -106,7 +106,7 @@ def test_vladimir_uses_his_own_signing_key(alice, ursulas, test_registry): message = f"Operator {vladimir.operator_address} is not bonded" with pytest.raises(vladimir.UnbondedOperator, match=message): vladimir.validate_metadata( - registry=test_registry, eth_provider_uri=TEST_ETH_PROVIDER_URI + registry=test_registry, eth_endpoint=TEST_ETH_PROVIDER_URI ) diff --git a/tests/acceptance/characters/test_transacting_power.py b/tests/acceptance/characters/test_transacting_power.py index c79100a20..52fce395e 100644 --- a/tests/acceptance/characters/test_transacting_power.py +++ b/tests/acceptance/characters/test_transacting_power.py @@ -21,7 +21,7 @@ def test_character_transacting_power_signing(testerchain, test_registry): signer = Character( is_me=True, domain=TEMPORARY_DOMAIN, - eth_provider_uri=TEST_ETH_PROVIDER_URI, + eth_endpoint=TEST_ETH_PROVIDER_URI, registry=test_registry, checksum_address=eth_address, ) diff --git a/tests/acceptance/cli/test_ursula_init.py b/tests/acceptance/cli/test_ursula_init.py index de932f4f5..63e9c1b4d 100644 --- a/tests/acceptance/cli/test_ursula_init.py +++ b/tests/acceptance/cli/test_ursula_init.py @@ -131,7 +131,7 @@ def test_ursula_and_local_keystore_signer_integration( worker_account.address, "--config-root", str(config_root_path.absolute()), - "--eth-provider", + "--eth-endpoint", TEST_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_POLYGON_PROVIDER_URI, diff --git a/tests/acceptance/cli/test_ursula_run.py b/tests/acceptance/cli/test_ursula_run.py index db1b9338f..7c4ad29d9 100644 --- a/tests/acceptance/cli/test_ursula_run.py +++ b/tests/acceptance/cli/test_ursula_run.py @@ -45,7 +45,7 @@ def test_ursula_run_with_prometheus_but_no_metrics_port(click_runner): "--dry-run", # Disable twisted reactor in subprocess "--lonely", # Do not load seednodes "--prometheus", # Specify collection of prometheus metrics - "--eth-provider", + "--eth-endpoint", TEST_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_POLYGON_PROVIDER_URI, @@ -74,7 +74,7 @@ def test_run_lone_default_development_ursula(click_runner, ursulas, testerchain) "--lonely", # Do not load seednodes, "--operator-address", ursulas[0].operator_address, - "--eth-provider", + "--eth-endpoint", TEST_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_ETH_PROVIDER_URI, @@ -128,7 +128,7 @@ def test_ursula_learns_via_cli(click_runner, ursulas, testerchain): "--dry-run", # Disable twisted reactor "--operator-address", ursulas[0].operator_address, - "--eth-provider", + "--eth-endpoint", TEST_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_ETH_PROVIDER_URI, @@ -180,7 +180,7 @@ def test_persistent_node_storage_integration( init_args = ( "ursula", "init", - "--eth-provider", + "--eth-endpoint", TEST_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_POLYGON_PROVIDER_URI, diff --git a/tests/fixtures.py b/tests/fixtures.py index 21f769d64..b60ecf97d 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -130,8 +130,8 @@ def random_address(random_account): @pytest.fixture(scope="module") def ursula_test_config(test_registry, temp_dir_path, testerchain): config = make_ursula_test_configuration( - eth_provider_uri=TEST_ETH_PROVIDER_URI, - pre_payment_provider=TEST_ETH_PROVIDER_URI, + eth_endpoint=TEST_ETH_PROVIDER_URI, + polygon_endpoint=TEST_ETH_PROVIDER_URI, test_registry=test_registry, rest_port=select_test_port(), operator_address=testerchain.ursulas_accounts.pop(), @@ -145,8 +145,8 @@ def ursula_test_config(test_registry, temp_dir_path, testerchain): @pytest.fixture(scope="module") def alice_test_config(ursulas, testerchain, test_registry): config = make_alice_test_configuration( - eth_provider_uri=TEST_ETH_PROVIDER_URI, - pre_payment_provider=TEST_ETH_PROVIDER_URI, + eth_endpoint=TEST_ETH_PROVIDER_URI, + polygon_endpoint=TEST_ETH_PROVIDER_URI, known_nodes=ursulas, checksum_address=testerchain.alice_account, test_registry=test_registry, @@ -157,9 +157,11 @@ def alice_test_config(ursulas, testerchain, test_registry): @pytest.fixture(scope="module") def bob_test_config(testerchain, test_registry): - config = make_bob_test_configuration(eth_provider_uri=TEST_ETH_PROVIDER_URI, - test_registry=test_registry, - checksum_address=testerchain.bob_account) + config = make_bob_test_configuration( + eth_endpoint=TEST_ETH_PROVIDER_URI, + test_registry=test_registry, + checksum_address=testerchain.bob_account, + ) yield config config.cleanup() @@ -338,7 +340,7 @@ def light_ursula(temp_dir_path, random_account, mocker): pre_payment_method=pre_payment_method, checksum_address=random_account.address, operator_address=random_account.address, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, signer=KeystoreSigner(path=temp_dir_path), ) return ursula @@ -462,7 +464,7 @@ def highperf_mocked_alice( def highperf_mocked_bob(fleet_of_highperf_mocked_ursulas): config = BobConfiguration( dev_mode=True, - eth_provider_uri=TEST_ETH_PROVIDER_URI, + eth_endpoint=TEST_ETH_PROVIDER_URI, domain=TEMPORARY_DOMAIN, network_middleware=MockRestMiddlewareForLargeFleetTests( eth_provider_uri=TEST_ETH_PROVIDER_URI diff --git a/tests/integration/characters/test_bob_joins_policy_and_retrieves.py b/tests/integration/characters/test_bob_joins_policy_and_retrieves.py index a79241d0f..40d4ebdb6 100644 --- a/tests/integration/characters/test_bob_joins_policy_and_retrieves.py +++ b/tests/integration/characters/test_bob_joins_policy_and_retrieves.py @@ -49,7 +49,7 @@ def test_bob_retrieves(alice, ursulas, certificates_tempdir): bob = Bob( domain=TEMPORARY_DOMAIN, start_learning_now=True, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), abort_on_learning_error=True, known_nodes=a_couple_of_ursulas, diff --git a/tests/integration/cli/test_cli_config.py b/tests/integration/cli/test_cli_config.py index ceda1eec7..ec10365ba 100644 --- a/tests/integration/cli/test_cli_config.py +++ b/tests/integration/cli/test_cli_config.py @@ -42,7 +42,7 @@ def test_initialize_via_cli( "init", "--network", TEMPORARY_DOMAIN, - "--eth-provider", + "--eth-endpoint", MOCK_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_ETH_PROVIDER_URI, @@ -103,13 +103,18 @@ def test_reconfigure_via_cli( # Read pre-edit state config = config_class.from_configuration_file(custom_config_filepath) - assert config.eth_provider_uri != TEST_ETH_PROVIDER_URI + assert config.eth_endpoint != TEST_ETH_PROVIDER_URI del config # Write - view_args = (config_class.CHARACTER_CLASS.__name__.lower(), 'config', - '--config-file', str(custom_config_filepath.absolute()), - '--eth-provider', TEST_ETH_PROVIDER_URI) + view_args = ( + config_class.CHARACTER_CLASS.__name__.lower(), + "config", + "--config-file", + str(custom_config_filepath.absolute()), + "--eth-endpoint", + TEST_ETH_PROVIDER_URI, + ) result = click_runner.invoke(nucypher_cli, view_args, env=ENV) assert result.exit_code == 0 @@ -121,4 +126,4 @@ def test_reconfigure_via_cli( assert str(custom_filepath) in result.output # After editing the fields have been updated - assert config.eth_provider_uri == TEST_ETH_PROVIDER_URI + assert config.eth_endpoint == TEST_ETH_PROVIDER_URI diff --git a/tests/integration/cli/test_mixed_config.py b/tests/integration/cli/test_mixed_config.py index 40ea09170..d852f7674 100644 --- a/tests/integration/cli/test_mixed_config.py +++ b/tests/integration/cli/test_mixed_config.py @@ -62,7 +62,7 @@ def test_corrupted_configuration( init_args = ( "ursula", "init", - "--eth-provider", + "--eth-endpoint", MOCK_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_POLYGON_PROVIDER_URI, @@ -109,7 +109,7 @@ def test_corrupted_configuration( TEMPORARY_DOMAIN, "--pre-payment-network", TEMPORARY_DOMAIN, - "--eth-provider", + "--eth-endpoint", MOCK_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_POLYGON_PROVIDER_URI, diff --git a/tests/integration/cli/test_ursula_cli_ip_detection.py b/tests/integration/cli/test_ursula_cli_ip_detection.py index 0ecdbec86..81d43d138 100644 --- a/tests/integration/cli/test_ursula_cli_ip_detection.py +++ b/tests/integration/cli/test_ursula_cli_ip_detection.py @@ -36,7 +36,7 @@ def test_ursula_startup_ip_checkup(click_runner, mocker): "init", "--network", TEMPORARY_DOMAIN, - "--eth-provider", + "--eth-endpoint", MOCK_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_POLYGON_PROVIDER_URI, @@ -55,7 +55,7 @@ def test_ursula_startup_ip_checkup(click_runner, mocker): "--network", TEMPORARY_DOMAIN, "--force", - "--eth-provider", + "--eth-endpoint", MOCK_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_POLYGON_PROVIDER_URI, @@ -73,7 +73,7 @@ def test_ursula_startup_ip_checkup(click_runner, mocker): "--network", TEMPORARY_DOMAIN, "--force", - "--eth-provider", + "--eth-endpoint", MOCK_ETH_PROVIDER_URI, "--pre-payment-provider", TEST_POLYGON_PROVIDER_URI, diff --git a/tests/integration/cli/test_ursula_config_cli.py b/tests/integration/cli/test_ursula_config_cli.py index 281daf4da..c3bd45f9d 100644 --- a/tests/integration/cli/test_ursula_config_cli.py +++ b/tests/integration/cli/test_ursula_config_cli.py @@ -60,7 +60,7 @@ def test_interactive_initialize_ursula(click_runner, mocker, tmpdir): "init", "--network", TEMPORARY_DOMAIN, - "--eth-provider", + "--eth-endpoint", MOCK_ETH_PROVIDER_URI, "--pre-payment-provider", MOCK_ETH_PROVIDER_URI, @@ -100,7 +100,7 @@ def test_initialize_custom_configuration_root( MOCK_IP_ADDRESS, "--rest-port", deploy_port, - "--eth-provider", + "--eth-endpoint", MOCK_ETH_PROVIDER_URI, "--pre-payment-provider", MOCK_ETH_PROVIDER_URI, diff --git a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py index 756c5af36..cbbe3e291 100644 --- a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py +++ b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py @@ -50,7 +50,7 @@ def test_ursula_init_with_local_keystore_signer( # Layer 1 "--network", TEMPORARY_DOMAIN, - "--eth-provider", + "--eth-endpoint", testerchain.eth_provider_uri, # Layer 2 "--pre-payment-network", diff --git a/tests/integration/config/test_character_configuration.py b/tests/integration/config/test_character_configuration.py index 5d017f037..fd7a22154 100644 --- a/tests/integration/config/test_character_configuration.py +++ b/tests/integration/config/test_character_configuration.py @@ -52,7 +52,7 @@ def test_development_character_configurations( lonely=True, domain=TEMPORARY_DOMAIN, checksum_address=testerchain.unassigned_accounts[0], - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) if character is Ursula: params.update(dict(operator_address=testerchain.unassigned_accounts[0])) @@ -125,7 +125,7 @@ def test_default_character_configuration_preservation( keystore.signing_public_key = SecretKey.random().public_key() character_config = configuration_class( checksum_address=fake_address, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, domain=network, rest_host=MOCK_IP_ADDRESS, pre_payment_provider=MOCK_ETH_PROVIDER_URI, @@ -137,7 +137,7 @@ def test_default_character_configuration_preservation( else: character_config = configuration_class( checksum_address=fake_address, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, domain=network, pre_payment_network=TEMPORARY_DOMAIN, policy_registry=test_registry, @@ -178,7 +178,7 @@ def test_ursula_development_configuration(testerchain): operator_address=testerchain.unassigned_accounts[1], domain=TEMPORARY_DOMAIN, pre_payment_network=TEMPORARY_DOMAIN, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) assert config.is_me is True assert config.dev_mode is True diff --git a/tests/integration/config/test_configuration_persistence.py b/tests/integration/config/test_configuration_persistence.py index 02161ae01..0d2104ef2 100644 --- a/tests/integration/config/test_configuration_persistence.py +++ b/tests/integration/config/test_configuration_persistence.py @@ -57,7 +57,7 @@ def test_alices_powers_are_persistent(ursulas, temp_dir_path, testerchain): bob = Bob( start_learning_now=False, domain=TEMPORARY_DOMAIN, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), ) @@ -98,7 +98,7 @@ def test_alices_powers_are_persistent(ursulas, temp_dir_path, testerchain): # Bob's eldest brother, Roberto, appears too roberto = Bob( domain=TEMPORARY_DOMAIN, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, start_learning_now=False, network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), ) diff --git a/tests/integration/config/test_keystore_integration.py b/tests/integration/config/test_keystore_integration.py index cc085b209..b11937c03 100644 --- a/tests/integration/config/test_keystore_integration.py +++ b/tests/integration/config/test_keystore_integration.py @@ -81,18 +81,18 @@ def test_characters_use_keystore(temp_dir_path, testerchain): start_learning_now=False, keystore=keystore, domain=TEMPORARY_DOMAIN, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, checksum_address=testerchain.alice_account, pre_payment_method=pre_payment_method, ) Bob( - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, start_learning_now=False, keystore=keystore, domain=TEMPORARY_DOMAIN, ) Ursula( - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, start_learning_now=False, keystore=keystore, rest_host=LOOPBACK_ADDRESS, @@ -170,7 +170,7 @@ def test_ritualist(temp_dir_path, testerchain, dkg_public_key): pre_payment_method=pre_payment_method, operator_address=testerchain.ursulas_accounts[0], signer=Web3Signer(testerchain.client), - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) ritual_id = 23 diff --git a/tests/integration/config/test_storages.py b/tests/integration/config/test_storages.py index c5dc4387f..f7a96cbca 100644 --- a/tests/integration/config/test_storages.py +++ b/tests/integration/config/test_storages.py @@ -46,7 +46,7 @@ class BaseTestNodeStorageBackends: rest_port=select_test_port(), domain=TEMPORARY_DOMAIN, signer=signer, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, checksum_address=operator_addresses[i], operator_address=operator_addresses[i], pre_payment_method=pre_payment_method, diff --git a/tests/metrics/grant_availability.py b/tests/metrics/grant_availability.py index 27bc32b65..0343b467c 100755 --- a/tests/metrics/grant_availability.py +++ b/tests/metrics/grant_availability.py @@ -162,7 +162,7 @@ def make_alice(known_nodes: Optional[Set[Ursula]] = None): wallet.unlock_account(account=ALICE_ADDRESS, password=SIGNER_PASSWORD) alice_config = AliceConfiguration( - eth_provider_uri=ETHEREUM_PROVIDER_URI, + eth_endpoint=ETHEREUM_PROVIDER_URI, checksum_address=ALICE_ADDRESS, signer_uri=f'keystore://{SIGNER_URI}', config_root=TEMP_ALICE_DIR, diff --git a/tests/unit/test_character_sign_and_verify.py b/tests/unit/test_character_sign_and_verify.py index eedc4f897..61be5cfe2 100644 --- a/tests/unit/test_character_sign_and_verify.py +++ b/tests/unit/test_character_sign_and_verify.py @@ -22,7 +22,7 @@ def test_actor_without_signing_power_cannot_sign(): crypto_power=cannot_sign, start_learning_now=False, domain=TEMPORARY_DOMAIN, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) # The non-signer's stamp doesn't work for signing... @@ -47,7 +47,7 @@ def test_actor_with_signing_power_can_sign(): is_me=True, start_learning_now=False, domain=TEMPORARY_DOMAIN, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) stamp_of_the_signer = signer.stamp @@ -73,14 +73,14 @@ def test_anybody_can_verify(random_address): domain=TEMPORARY_DOMAIN, checksum_address=random_address, pre_payment_method=FreeReencryptions(), - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) # So, our story is fairly simple: an everyman meets Alice. somebody = Character( start_learning_now=False, domain=TEMPORARY_DOMAIN, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) # Alice signs a message. diff --git a/tests/utils/config.py b/tests/utils/config.py index b2cc281b8..422ba8033 100644 --- a/tests/utils/config.py +++ b/tests/utils/config.py @@ -25,16 +25,16 @@ TEST_CHARACTER_CONFIG_BASE_PARAMS = dict( def assemble( checksum_address: str = None, - eth_provider_uri: str = None, + eth_endpoint: str = None, test_registry: ContractRegistry = None, known_nodes: List[Ursula] = None, ) -> dict: """Assemble a dictionary of keyword arguments to use when constructing a test configuration.""" # Generate runtime config params runtime_params = dict( - eth_provider_uri=eth_provider_uri, + eth_endpoint=eth_endpoint, registry=test_registry, - network_middleware=MockRestMiddleware(eth_provider_uri=eth_provider_uri), + network_middleware=MockRestMiddleware(eth_provider_uri=eth_endpoint), known_nodes=known_nodes, checksum_address=checksum_address, ) From 33068070fc08ba10bf10ebc8b2190fee2c5903e5 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Fri, 29 Sep 2023 14:50:52 -0400 Subject: [PATCH 08/63] Rename pre_payment_provider to polygon_endpoint as it pertains to Characters/Configurations/CLI parameters. --- nucypher/cli/commands/ursula.py | 22 +++++++++---------- nucypher/cli/options.py | 6 ++--- nucypher/config/base.py | 16 +++++++------- nucypher/config/characters.py | 8 +++---- tests/acceptance/cli/test_ursula_init.py | 2 +- tests/acceptance/cli/test_ursula_run.py | 8 +++---- tests/integration/cli/test_cli_config.py | 2 +- tests/integration/cli/test_mixed_config.py | 4 ++-- .../cli/test_ursula_cli_ip_detection.py | 6 ++--- .../integration/cli/test_ursula_config_cli.py | 4 ++-- ...ursula_local_keystore_cli_functionality.py | 2 +- .../config/test_character_configuration.py | 2 +- tests/utils/config.py | 8 +++---- 13 files changed, 45 insertions(+), 45 deletions(-) diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index d448d18a1..25802807b 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -45,9 +45,9 @@ from nucypher.cli.options import ( option_network, option_poa, option_policy_registry_filepath, + option_polygon_endpoint, option_pre_payment_method, option_pre_payment_network, - option_pre_payment_provider, option_registry_filepath, option_signer_uri, option_teacher_uri, @@ -89,7 +89,7 @@ class UrsulaConfigOptions: signer_uri: str, lonely: bool, pre_payment_method: str, - pre_payment_provider: str, + polygon_endpoint: str, pre_payment_network: str, ): @@ -108,7 +108,7 @@ class UrsulaConfigOptions: self.max_gas_price = max_gas_price self.lonely = lonely self.pre_payment_method = pre_payment_method - self.pre_payment_provider = pre_payment_provider + self.polygon_endpoint = polygon_endpoint self.pre_payment_network = pre_payment_network def create_config(self, emitter, config_file): @@ -129,7 +129,7 @@ class UrsulaConfigOptions: rest_host=self.rest_host, rest_port=self.rest_port, pre_payment_method=self.pre_payment_method, - pre_payment_provider=self.pre_payment_provider, + polygon_endpoint=self.polygon_endpoint, pre_payment_network=self.pre_payment_network, ) else: @@ -153,7 +153,7 @@ class UrsulaConfigOptions: poa=self.poa, light=self.light, pre_payment_method=self.pre_payment_method, - pre_payment_provider=self.pre_payment_provider, + polygon_endpoint=self.polygon_endpoint, pre_payment_network=self.pre_payment_network, ) except FileNotFoundError: @@ -205,7 +205,7 @@ class UrsulaConfigOptions: poa=self.poa, light=self.light, pre_payment_method=self.pre_payment_method, - pre_payment_provider=self.pre_payment_provider, + polygon_endpoint=self.polygon_endpoint, pre_payment_network=self.pre_payment_network, ) @@ -224,7 +224,7 @@ class UrsulaConfigOptions: poa=self.poa, light=self.light, pre_payment_method=self.pre_payment_method, - pre_payment_provider=self.pre_payment_provider, + polygon_endpoint=self.polygon_endpoint, pre_payment_network=self.pre_payment_network, ) # Depends on defaults being set on Configuration classes, filtrates None values @@ -261,7 +261,7 @@ group_config_options = group_options( light=option_light, dev=option_dev, lonely=option_lonely, - pre_payment_provider=option_pre_payment_provider, + polygon_endpoint=option_polygon_endpoint, pre_payment_network=option_pre_payment_network, pre_payment_method=option_pre_payment_method, ) @@ -340,11 +340,11 @@ def init(general_config, config_options, force, config_root, key_material): "--eth-endpoint is required to initialize a new ursula.", fg="red" ), ) - if not config_options.pre_payment_provider: + if not config_options.polygon_endpoint: raise click.BadOptionUsage( - "--pre-payment-provider", + "--polygon-endpoint", message=click.style( - "--pre-payment-provider is required to initialize a new ursula.", + "--polygon-endpoint is required to initialize a new ursula.", fg="red", ), ) diff --git a/nucypher/cli/options.py b/nucypher/cli/options.py index 059b1ff26..7b409b2ef 100644 --- a/nucypher/cli/options.py +++ b/nucypher/cli/options.py @@ -79,9 +79,9 @@ option_parameters = click.option( help="Filepath to a JSON file containing additional parameters", type=EXISTING_READABLE_FILE, ) -option_pre_payment_provider = click.option( - "--pre-payment-provider", - "pre_payment_provider", +option_polygon_endpoint = click.option( + "--polygon-endpoint", + "polygon_endpoint", help="Connection URL for PRE payment method", type=click.STRING, required=False, diff --git a/nucypher/config/base.py b/nucypher/config/base.py index 9b41f854d..6e95df030 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -334,7 +334,7 @@ class CharacterConfiguration(BaseConfiguration): "max_gas_price", # gwei "signer_uri", "keystore_path", - "pre_payment_provider", + "polygon_endpoint", "pre_payment_network", ) @@ -375,7 +375,7 @@ class CharacterConfiguration(BaseConfiguration): # Payments # TODO: Resolve code prefixing below, possibly with the use of nested configuration fields pre_payment_method: Optional[str] = None, - pre_payment_provider: Optional[str] = None, + polygon_endpoint: Optional[str] = None, pre_payment_network: Optional[str] = None, # Registries registry: Optional[ContractRegistry] = None, @@ -462,7 +462,7 @@ class CharacterConfiguration(BaseConfiguration): # TODO: this is potential fix for multichain connection, if we want to use it build it out into a loop # for uri in eth_provider_uri (list of uris fom config): BlockchainInterfaceFactory.get_or_create_interface( - eth_provider_uri=pre_payment_provider, + eth_provider_uri=polygon_endpoint, poa=self.poa, light=self.is_light, emitter=emitter, @@ -494,7 +494,7 @@ class CharacterConfiguration(BaseConfiguration): from nucypher.config.characters import BobConfiguration if not isinstance(self, BobConfiguration): - # if not pre_payment_provider: + # if not polygon_endpoint: # raise self.ConfigurationError("payment provider is required.") self.pre_payment_method = ( pre_payment_method or self.DEFAULT_PRE_PAYMENT_METHOD @@ -502,8 +502,8 @@ class CharacterConfiguration(BaseConfiguration): self.pre_payment_network = ( pre_payment_network or self.DEFAULT_PRE_PAYMENT_NETWORK ) - self.pre_payment_provider = pre_payment_provider or ( - self.eth_provider_uri or None + self.polygon_endpoint = polygon_endpoint or ( + self.eth_endpoint or None ) # default to L1 payments # TODO: Dedupe @@ -841,7 +841,7 @@ class CharacterConfiguration(BaseConfiguration): # Strategy-Based (current implementation, inflexible & hardcoded) # 'pre_payment_strategy': 'SubscriptionManager' # 'pre_payment_network': 'matic' - # 'pre_payment_provider': 'https:///matic.infura.io....' + # 'polygon_endpoint': 'https:///matic.infura.io....' # # Contract-Targeted (alternative implementation, flexible & generic) # 'pre_payment': { @@ -861,7 +861,7 @@ class CharacterConfiguration(BaseConfiguration): # on-chain payment strategies require a blockchain connection pre_payment_strategy = pre_payment_class( network=self.pre_payment_network, - eth_provider=self.pre_payment_provider, + eth_provider=self.polygon_endpoint, registry=self.policy_registry, ) else: diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index c536a122d..777322d74 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -78,8 +78,8 @@ class UrsulaConfiguration(CharacterConfiguration): if not polygon_provider_uris: self.condition_provider_uris[polygon_chain_id] = polygon_provider_uris - if self.pre_payment_provider not in polygon_provider_uris: - polygon_provider_uris.append(self.pre_payment_provider) + if self.polygon_endpoint not in polygon_provider_uris: + polygon_provider_uris.append(self.polygon_endpoint) # Ethereum staking_chain_id = taco_network.eth_network.value @@ -118,7 +118,7 @@ class UrsulaConfiguration(CharacterConfiguration): # PRE Payments # TODO: Resolve variable prefixing below (uses nested configuration fields?) pre_payment_method=self.pre_payment_method, - pre_payment_provider=self.pre_payment_provider, + polygon_endpoint=self.polygon_endpoint, pre_payment_network=self.pre_payment_network, ) return {**super().static_payload(), **payload} @@ -181,7 +181,7 @@ class AliceConfiguration(CharacterConfiguration): threshold=self.threshold, shares=self.shares, pre_payment_network=self.pre_payment_network, - pre_payment_provider=self.pre_payment_provider, + polygon_endpoint=self.polygon_endpoint, pre_payment_method=self.pre_payment_method, rate=self.rate, duration=self.duration, diff --git a/tests/acceptance/cli/test_ursula_init.py b/tests/acceptance/cli/test_ursula_init.py index 63e9c1b4d..2ed4be782 100644 --- a/tests/acceptance/cli/test_ursula_init.py +++ b/tests/acceptance/cli/test_ursula_init.py @@ -133,7 +133,7 @@ def test_ursula_and_local_keystore_signer_integration( str(config_root_path.absolute()), "--eth-endpoint", TEST_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_POLYGON_PROVIDER_URI, "--rest-host", MOCK_IP_ADDRESS, diff --git a/tests/acceptance/cli/test_ursula_run.py b/tests/acceptance/cli/test_ursula_run.py index 7c4ad29d9..e0240aa81 100644 --- a/tests/acceptance/cli/test_ursula_run.py +++ b/tests/acceptance/cli/test_ursula_run.py @@ -47,7 +47,7 @@ def test_ursula_run_with_prometheus_but_no_metrics_port(click_runner): "--prometheus", # Specify collection of prometheus metrics "--eth-endpoint", TEST_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_POLYGON_PROVIDER_URI, ) @@ -76,7 +76,7 @@ def test_run_lone_default_development_ursula(click_runner, ursulas, testerchain) ursulas[0].operator_address, "--eth-endpoint", TEST_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_ETH_PROVIDER_URI, "--pre-payment-network", TEMPORARY_DOMAIN, @@ -130,7 +130,7 @@ def test_ursula_learns_via_cli(click_runner, ursulas, testerchain): ursulas[0].operator_address, "--eth-endpoint", TEST_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_ETH_PROVIDER_URI, "--pre-payment-network", TEMPORARY_DOMAIN, @@ -182,7 +182,7 @@ def test_persistent_node_storage_integration( "init", "--eth-endpoint", TEST_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_POLYGON_PROVIDER_URI, "--operator-address", another_ursula, diff --git a/tests/integration/cli/test_cli_config.py b/tests/integration/cli/test_cli_config.py index ec10365ba..9433f0be1 100644 --- a/tests/integration/cli/test_cli_config.py +++ b/tests/integration/cli/test_cli_config.py @@ -44,7 +44,7 @@ def test_initialize_via_cli( TEMPORARY_DOMAIN, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_ETH_PROVIDER_URI, "--config-root", str(custom_filepath.absolute()), diff --git a/tests/integration/cli/test_mixed_config.py b/tests/integration/cli/test_mixed_config.py index d852f7674..581a41314 100644 --- a/tests/integration/cli/test_mixed_config.py +++ b/tests/integration/cli/test_mixed_config.py @@ -64,7 +64,7 @@ def test_corrupted_configuration( "init", "--eth-endpoint", MOCK_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_POLYGON_PROVIDER_URI, "--operator-address", another_ursula, @@ -111,7 +111,7 @@ def test_corrupted_configuration( TEMPORARY_DOMAIN, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_POLYGON_PROVIDER_URI, "--operator-address", another_ursula, diff --git a/tests/integration/cli/test_ursula_cli_ip_detection.py b/tests/integration/cli/test_ursula_cli_ip_detection.py index 81d43d138..771ed822f 100644 --- a/tests/integration/cli/test_ursula_cli_ip_detection.py +++ b/tests/integration/cli/test_ursula_cli_ip_detection.py @@ -38,7 +38,7 @@ def test_ursula_startup_ip_checkup(click_runner, mocker): TEMPORARY_DOMAIN, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_POLYGON_PROVIDER_URI, "--force", ) @@ -57,7 +57,7 @@ def test_ursula_startup_ip_checkup(click_runner, mocker): "--force", "--eth-endpoint", MOCK_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_POLYGON_PROVIDER_URI, ) result = click_runner.invoke( @@ -75,7 +75,7 @@ def test_ursula_startup_ip_checkup(click_runner, mocker): "--force", "--eth-endpoint", MOCK_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", TEST_POLYGON_PROVIDER_URI, ) result = click_runner.invoke( diff --git a/tests/integration/cli/test_ursula_config_cli.py b/tests/integration/cli/test_ursula_config_cli.py index c3bd45f9d..43d4860a6 100644 --- a/tests/integration/cli/test_ursula_config_cli.py +++ b/tests/integration/cli/test_ursula_config_cli.py @@ -62,7 +62,7 @@ def test_interactive_initialize_ursula(click_runner, mocker, tmpdir): TEMPORARY_DOMAIN, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", MOCK_ETH_PROVIDER_URI, ) @@ -102,7 +102,7 @@ def test_initialize_custom_configuration_root( deploy_port, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, - "--pre-payment-provider", + "--polygon-endpoint", MOCK_ETH_PROVIDER_URI, "--pre-payment-network", TEMPORARY_DOMAIN, diff --git a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py index cbbe3e291..ab032fe38 100644 --- a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py +++ b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py @@ -55,7 +55,7 @@ def test_ursula_init_with_local_keystore_signer( # Layer 2 "--pre-payment-network", TEMPORARY_DOMAIN, - "--pre-payment-provider", + "--polygon-endpoint", testerchain.eth_provider_uri, "--rest-host", MOCK_IP_ADDRESS, diff --git a/tests/integration/config/test_character_configuration.py b/tests/integration/config/test_character_configuration.py index fd7a22154..7c8848aab 100644 --- a/tests/integration/config/test_character_configuration.py +++ b/tests/integration/config/test_character_configuration.py @@ -128,7 +128,7 @@ def test_default_character_configuration_preservation( eth_endpoint=MOCK_ETH_PROVIDER_URI, domain=network, rest_host=MOCK_IP_ADDRESS, - pre_payment_provider=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, policy_registry=test_registry, pre_payment_network=TEMPORARY_DOMAIN, keystore=keystore, diff --git a/tests/utils/config.py b/tests/utils/config.py index 422ba8033..37ccdb80a 100644 --- a/tests/utils/config.py +++ b/tests/utils/config.py @@ -47,14 +47,14 @@ def assemble( def make_ursula_test_configuration( operator_address: ChecksumAddress, rest_port: int = select_test_port(), - pre_payment_provider: str = None, + polygon_endpoint: str = None, **assemble_kwargs ) -> UrsulaConfiguration: test_params = assemble(**assemble_kwargs) ursula_config = UrsulaConfiguration( **test_params, rest_port=rest_port, - pre_payment_provider=pre_payment_provider, + polygon_endpoint=polygon_endpoint, pre_payment_network=TEMPORARY_DOMAIN, operator_address=operator_address, policy_registry=test_params["registry"] @@ -63,12 +63,12 @@ def make_ursula_test_configuration( def make_alice_test_configuration( - pre_payment_provider: str = None, **assemble_kwargs + polygon_endpoint: str = None, **assemble_kwargs ) -> AliceConfiguration: test_params = assemble(**assemble_kwargs) config = AliceConfiguration( **test_params, - pre_payment_provider=pre_payment_provider, + polygon_endpoint=polygon_endpoint, pre_payment_network=TEMPORARY_DOMAIN, policy_registry=test_params["registry"] ) From 94dc933c7353cb6e4ebf4fbb667def6e106bdee1 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Fri, 29 Sep 2023 14:52:34 -0400 Subject: [PATCH 09/63] Bump character configuration to v8 and add migration script. --- nucypher/config/base.py | 2 +- nucypher/config/migrations/__init__.py | 2 ++ .../migrations/configuration_v7_to_v8.py | 24 +++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 nucypher/config/migrations/configuration_v7_to_v8.py diff --git a/nucypher/config/base.py b/nucypher/config/base.py index 6e95df030..114f77206 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -303,7 +303,7 @@ class CharacterConfiguration(BaseConfiguration): 'Sideways Engagement' of Character classes; a reflection of input parameters. """ - VERSION = 7 # bump when static payload scheme changes + VERSION = 8 # bump when static payload scheme changes CHARACTER_CLASS = NotImplemented MNEMONIC_KEYSTORE = False diff --git a/nucypher/config/migrations/__init__.py b/nucypher/config/migrations/__init__.py index 52184c467..b34cbc1ec 100644 --- a/nucypher/config/migrations/__init__.py +++ b/nucypher/config/migrations/__init__.py @@ -5,6 +5,7 @@ from .configuration_v3_to_v4 import configuration_v3_to_v4 from .configuration_v4_to_v5 import configuration_v4_to_v5 from .configuration_v5_to_v6 import configuration_v5_to_v6 from .configuration_v6_to_v7 import configuration_v6_to_v7 +from .configuration_v7_to_v8 import configuration_v7_to_v8 MIGRATIONS = OrderedDict( { @@ -14,5 +15,6 @@ MIGRATIONS = OrderedDict( (4, 5): configuration_v4_to_v5, (5, 6): configuration_v5_to_v6, (6, 7): configuration_v6_to_v7, + (7, 8): configuration_v7_to_v8, } ) diff --git a/nucypher/config/migrations/configuration_v7_to_v8.py b/nucypher/config/migrations/configuration_v7_to_v8.py new file mode 100644 index 000000000..62da58a05 --- /dev/null +++ b/nucypher/config/migrations/configuration_v7_to_v8.py @@ -0,0 +1,24 @@ +from typing import Dict + +from nucypher.config.migrations.common import perform_migration + + +def __migration(config: Dict) -> Dict: + # deprecations + del config["pre_payment_network"] + + # eth_provider_uri -> eth_endpoint + config["eth_endpoint"] = config["eth_provider_uri"] + del config["eth_provider_uri"] + + # pre_payment_provider -> polygon_endpoint + config["polygon_endpoint"] = config["pre_payment_provider"] + del config["pre_payment_provider"] + + return config + + +def configuration_v7_to_v8(filepath) -> None: + perform_migration( + old_version=7, new_version=8, migration=__migration, filepath=filepath + ) From 32a3b432d7bd8834377bd2f0bea487ee05d16027 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 09:07:20 -0400 Subject: [PATCH 10/63] Provide richer chain information from TACoNetwork class including chain id and name for underlying blockchain networks. --- nucypher/blockchain/eth/networks.py | 37 ++++++++++++++++++++--------- nucypher/config/base.py | 2 +- tests/utils/registry.py | 6 ++--- 3 files changed, 30 insertions(+), 15 deletions(-) diff --git a/nucypher/blockchain/eth/networks.py b/nucypher/blockchain/eth/networks.py index ffb6f9736..8f139c329 100644 --- a/nucypher/blockchain/eth/networks.py +++ b/nucypher/blockchain/eth/networks.py @@ -1,20 +1,32 @@ from enum import Enum from typing import List, NamedTuple +from nucypher.config.constants import TEMPORARY_DOMAIN -class EthNetwork(Enum): - MAINNET = 1 - GOERLI = 5 - SEPOLIA = 11155111 + +class ChainInfo(NamedTuple): + chain_id: int + chain_name: str + + # Override eventual Enum name. TODO: better way? + @property + def name(self) -> str: + return self.chain_name + + +class EthNetwork(ChainInfo, Enum): + MAINNET = ChainInfo(1, "mainnet") + GOERLI = ChainInfo(5, "goerli") + SEPOLIA = ChainInfo(11155111, "sepolia") # testing - TESTERCHAIN = 131277322940537 + TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) -class PolyNetwork(Enum): - POLYGON = 137 - MUMBAI = 80001 +class PolyNetwork(ChainInfo, Enum): + POLYGON = ChainInfo(137, "polygon") + MUMBAI = ChainInfo(80001, "mumbai") # testing - TESTERCHAIN = 131277322940537 + TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) class TACoNetwork(NamedTuple): @@ -22,6 +34,9 @@ class TACoNetwork(NamedTuple): eth_network: EthNetwork poly_network: PolyNetwork + def is_testnet(self) -> bool: + return self.eth_network != EthNetwork.MAINNET + class UnrecognizedNetwork(RuntimeError): """Raised when a provided network name is not recognized.""" @@ -47,9 +62,9 @@ class NetworksInventory: IBEX, ] - SUPPORTED_NETWORK_NAMES = {network.name for network in SUPPORTED_NETWORKS} + SUPPORTED_NETWORK_NAMES = [network.name for network in SUPPORTED_NETWORKS] - DEFAULT: str = MAINNET.name + DEFAULT_NETWORK_NAME: str = MAINNET.name @classmethod def get_network(cls, network_name: str) -> TACoNetwork: diff --git a/nucypher/config/base.py b/nucypher/config/base.py index 114f77206..2add4689d 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -307,7 +307,7 @@ class CharacterConfiguration(BaseConfiguration): CHARACTER_CLASS = NotImplemented MNEMONIC_KEYSTORE = False - DEFAULT_DOMAIN = NetworksInventory.DEFAULT + DEFAULT_DOMAIN = NetworksInventory.DEFAULT_NETWORK_NAME DEFAULT_NETWORK_MIDDLEWARE = RestMiddleware TEMP_CONFIGURATION_DIR_PREFIX = 'tmp-nucypher' SIGNER_ENVVAR = None diff --git a/tests/utils/registry.py b/tests/utils/registry.py index 1aa3782a0..91dd1d464 100644 --- a/tests/utils/registry.py +++ b/tests/utils/registry.py @@ -17,12 +17,12 @@ from nucypher.config.constants import TEMPORARY_DOMAIN @contextmanager def mock_registry_sources(): # capture the real values - real_network_names = NetworksInventory.SUPPORTED_NETWORK_NAMES real_networks = NetworksInventory.SUPPORTED_NETWORKS + real_network_names = NetworksInventory.SUPPORTED_NETWORK_NAMES real_registry_sources = RegistrySourceManager._FALLBACK_CHAIN # set the mock values - NetworksInventory.SUPPORTED_NETWORK_NAMES = {TEMPORARY_DOMAIN} + NetworksInventory.SUPPORTED_NETWORK_NAMES = [TEMPORARY_DOMAIN] testing_network = TACoNetwork( TEMPORARY_DOMAIN, EthNetwork.TESTERCHAIN, PolyNetwork.TESTERCHAIN ) @@ -32,8 +32,8 @@ def mock_registry_sources(): yield # run the test # restore the real values - NetworksInventory.SUPPORTED_NETWORK_NAMES = real_network_names NetworksInventory.SUPPORTED_NETWORKS = real_networks + NetworksInventory.SUPPORTED_NETWORK_NAMES = real_network_names RegistrySourceManager._FALLBACK_CHAIN = real_registry_sources From 738182ab9829ebc05f1ca4f47dd79aaad2fc9ce6 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 09:33:22 -0400 Subject: [PATCH 11/63] Remove use of pre_payment_network and coordinator_network since the corresponding polygon network is always implied based on the TACo network used. Remove coordinator_provider_uri, use of pre_payment_network.provider because all characters now define polygon_endpoint parameter. --- nucypher/blockchain/eth/actors.py | 25 ++++++------ nucypher/characters/base.py | 3 ++ nucypher/characters/lawful.py | 24 ++++-------- nucypher/cli/commands/ursula.py | 10 +---- nucypher/cli/literature.py | 4 +- nucypher/cli/options.py | 6 --- nucypher/config/base.py | 38 +++++++++---------- nucypher/config/characters.py | 8 +--- .../migrations/configuration_v5_to_v6.py | 4 +- nucypher/network/nodes.py | 1 + tests/acceptance/cli/test_ursula_init.py | 2 - tests/acceptance/cli/test_ursula_run.py | 6 --- tests/fixtures.py | 10 +---- tests/integration/cli/test_cli_config.py | 5 +-- tests/integration/cli/test_mixed_config.py | 4 -- .../integration/cli/test_ursula_config_cli.py | 12 ++---- ...ursula_local_keystore_cli_functionality.py | 2 - .../config/test_character_configuration.py | 8 +--- .../config/test_configuration_persistence.py | 1 - .../config/test_keystore_integration.py | 3 ++ tests/integration/config/test_storages.py | 1 + tests/utils/config.py | 2 - 22 files changed, 62 insertions(+), 117 deletions(-) diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index 017f2a0e1..609628b19 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -38,6 +38,7 @@ from nucypher.blockchain.eth.clients import PUBLIC_CHAINS from nucypher.blockchain.eth.constants import NULL_ADDRESS from nucypher.blockchain.eth.decorators import validate_checksum_address from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory +from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ( ContractRegistry, ) @@ -70,7 +71,7 @@ class BaseActor: @validate_checksum_address def __init__( self, - domain: Optional[str], + domain: str, registry: ContractRegistry, transacting_power: Optional[TransactingPower] = None, checksum_address: Optional[ChecksumAddress] = None, @@ -94,6 +95,7 @@ class BaseActor: self.transacting_power = transacting_power self.registry = registry self.network = domain + self.taco_network = NetworksInventory.get_network(self.network) self._saved_receipts = list() # track receipts of transmitted transactions def __repr__(self): @@ -159,8 +161,7 @@ class Operator(BaseActor): def __init__( self, eth_endpoint: str, - coordinator_provider_uri: str, - coordinator_network: str, + polygon_endpoint: str, pre_payment_method: ContractPayment, transacting_power: TransactingPower, signer: Signer = None, @@ -174,9 +175,9 @@ class Operator(BaseActor): ): # Falsy values may be passed down from the superclass if not eth_endpoint: - raise ValueError("Ethereum Provider URI is required to init an operator.") - if not coordinator_provider_uri: - raise ValueError("Polygon Provider URI is required to init an operator.") + raise ValueError("Ethereum endpoint URI is required to init an operator.") + if not polygon_endpoint: + raise ValueError("Polygon endpoint URI is required to init an operator.") if not pre_payment_method: raise ValueError("PRE payment method is required to init an operator.") @@ -209,19 +210,19 @@ class Operator(BaseActor): ) # TODO: registry usage (and subsequently "network") is inconsistent here - coordinator_network_registry = ContractRegistry.from_latest_publication( - domain=coordinator_network + registry = ContractRegistry.from_latest_publication( + network=self.network ) self.child_application_agent = ContractAgency.get_agent( TACoChildApplicationAgent, - registry=coordinator_network_registry, - provider_uri=coordinator_provider_uri, + registry=registry, + provider_uri=polygon_endpoint, ) self.coordinator_agent = ContractAgency.get_agent( CoordinatorAgent, - registry=coordinator_network_registry, - provider_uri=coordinator_provider_uri, + registry=registry, + provider_uri=polygon_endpoint, ) # track active onchain rituals diff --git a/nucypher/characters/base.py b/nucypher/characters/base.py index 0180b254b..77e2e49d4 100644 --- a/nucypher/characters/base.py +++ b/nucypher/characters/base.py @@ -35,6 +35,7 @@ class Character(Learner): self, domain: str, eth_endpoint: str = None, + polygon_endpoint: str = None, known_node_class: object = None, is_me: bool = True, checksum_address: str = None, @@ -114,6 +115,8 @@ class Character(Learner): self._stamp = NO_SIGNING_POWER self.eth_endpoint = eth_endpoint + self.polygon_endpoint = polygon_endpoint + self.registry = ( registry or ContractRegistry.from_latest_publication(domain=domain) diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index ca15ec094..8184b8a08 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -459,8 +459,7 @@ class Bob(Character): is_me: bool = True, verify_node_bonding: bool = False, eth_endpoint: str = None, - coordinator_provider_uri: str = None, # TODO: Move to a higher level and formalize - coordinator_network: str = None, # TODO: Move to a higher level and formalize + polygon_endpoint: str = None, # TODO: Move to a higher level and formalize *args, **kwargs, ) -> None: @@ -475,20 +474,15 @@ class Bob(Character): ) coordinator_agent = None - if coordinator_provider_uri: - if not coordinator_network: - raise ValueError( - "If coordinator_provider_uri is set, coordinator_network must also be set" - ) + if polygon_endpoint: coordinator_agent = ContractAgency.get_agent( CoordinatorAgent, - provider_uri=coordinator_provider_uri, + provider_uri=polygon_endpoint, registry=ContractRegistry.from_latest_publication( - domain=coordinator_network + domain=self.domain, ), ) self.coordinator_agent = coordinator_agent - self.coordinator_network = coordinator_network # Cache of decrypted treasure maps self._treasure_maps: Dict[int, TreasureMap] = {} @@ -705,9 +699,7 @@ class Bob(Character): def _get_coordinator_agent(self) -> CoordinatorAgent: if not self.coordinator_agent: - raise ValueError( - "No coordinator provider URI provided in Bob's constructor." - ) + raise ValueError("No polygon endpoint URI provided in Bob's constructor.") return self.coordinator_agent @@ -824,8 +816,8 @@ class Ursula(Teacher, Character, Operator): operator_address: Optional[ChecksumAddress] = None, client_password: Optional[str] = None, transacting_power: Optional[TransactingPower] = None, - operator_signature_from_metadata=NOT_SIGNED, eth_endpoint: Optional[str] = None, + polygon_endpoint: Optional[str] = None, condition_provider_uris: Optional[Dict[int, List[str]]] = None, pre_payment_method: Optional[Union[PaymentMethod, ContractPayment]] = None, # Character @@ -845,6 +837,7 @@ class Ursula(Teacher, Character, Operator): known_node_class=Ursula, include_self_in_the_state=True, eth_endpoint=eth_endpoint, + polygon_endpoint=polygon_endpoint, **character_kwargs, ) @@ -864,12 +857,11 @@ class Ursula(Teacher, Character, Operator): crypto_power=self._crypto_power, operator_address=operator_address, eth_endpoint=eth_endpoint, + polygon_endpoint=polygon_endpoint, pre_payment_method=pre_payment_method, client_password=client_password, condition_provider_uris=condition_provider_uris, - coordinator_provider_uri=pre_payment_method.provider, transacting_power=transacting_power, - coordinator_network=pre_payment_method.network, ) except Exception: diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index 25802807b..01436ceb3 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -47,7 +47,6 @@ from nucypher.cli.options import ( option_policy_registry_filepath, option_polygon_endpoint, option_pre_payment_method, - option_pre_payment_network, option_registry_filepath, option_signer_uri, option_teacher_uri, @@ -88,9 +87,8 @@ class UrsulaConfigOptions: max_gas_price: int, # gwei signer_uri: str, lonely: bool, - pre_payment_method: str, polygon_endpoint: str, - pre_payment_network: str, + pre_payment_method: str, ): self.eth_endpoint = eth_endpoint @@ -109,7 +107,6 @@ class UrsulaConfigOptions: self.lonely = lonely self.pre_payment_method = pre_payment_method self.polygon_endpoint = polygon_endpoint - self.pre_payment_network = pre_payment_network def create_config(self, emitter, config_file): if self.dev: @@ -130,7 +127,6 @@ class UrsulaConfigOptions: rest_port=self.rest_port, pre_payment_method=self.pre_payment_method, polygon_endpoint=self.polygon_endpoint, - pre_payment_network=self.pre_payment_network, ) else: if not config_file: @@ -154,7 +150,6 @@ class UrsulaConfigOptions: light=self.light, pre_payment_method=self.pre_payment_method, polygon_endpoint=self.polygon_endpoint, - pre_payment_network=self.pre_payment_network, ) except FileNotFoundError: return handle_missing_configuration_file(character_config_class=UrsulaConfiguration, config_file=config_file) @@ -206,7 +201,6 @@ class UrsulaConfigOptions: light=self.light, pre_payment_method=self.pre_payment_method, polygon_endpoint=self.polygon_endpoint, - pre_payment_network=self.pre_payment_network, ) def get_updates(self) -> dict: @@ -225,7 +219,6 @@ class UrsulaConfigOptions: light=self.light, pre_payment_method=self.pre_payment_method, polygon_endpoint=self.polygon_endpoint, - pre_payment_network=self.pre_payment_network, ) # Depends on defaults being set on Configuration classes, filtrates None values updates = {k: v for k, v in payload.items() if v is not None} @@ -262,7 +255,6 @@ group_config_options = group_options( dev=option_dev, lonely=option_lonely, polygon_endpoint=option_polygon_endpoint, - pre_payment_network=option_pre_payment_network, pre_payment_method=option_pre_payment_method, ) diff --git a/nucypher/cli/literature.py b/nucypher/cli/literature.py index 79d729ac2..987fc17f6 100644 --- a/nucypher/cli/literature.py +++ b/nucypher/cli/literature.py @@ -43,9 +43,7 @@ nucypher {init_command} """ -SELECT_NETWORK = "Select Network" - -SELECT_PRE_PAYMENT_NETWORK = "Select PRE Payment Network" +SELECT_NETWORK = "Select TACo Network" NO_CONFIGURATIONS_ON_DISK = "No {name} configurations found. Run 'nucypher {command} init' then try again." diff --git a/nucypher/cli/options.py b/nucypher/cli/options.py index 7b409b2ef..5987d6731 100644 --- a/nucypher/cli/options.py +++ b/nucypher/cli/options.py @@ -86,12 +86,6 @@ option_polygon_endpoint = click.option( type=click.STRING, required=False, ) -option_pre_payment_network = click.option( - "--pre-payment-network", - help="PRE payment network name", - type=click.STRING, - required=False, -) # TODO: Choices option_pre_payment_method = click.option( "--pre-payment-method", help="PRE payment method name", diff --git a/nucypher/config/base.py b/nucypher/config/base.py index 2add4689d..00b12c42a 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -321,7 +321,6 @@ class CharacterConfiguration(BaseConfiguration): # Payments DEFAULT_PRE_PAYMENT_METHOD = "SubscriptionManager" - DEFAULT_PRE_PAYMENT_NETWORK = "polygon" # Fields specified here are *not* passed into the Character's constructor # and can be understood as configuration fields only. @@ -334,8 +333,6 @@ class CharacterConfiguration(BaseConfiguration): "max_gas_price", # gwei "signer_uri", "keystore_path", - "polygon_endpoint", - "pre_payment_network", ) def __init__( @@ -369,14 +366,13 @@ class CharacterConfiguration(BaseConfiguration): poa: Optional[bool] = None, light: bool = False, eth_endpoint: Optional[str] = None, + polygon_endpoint: Optional[str] = None, gas_strategy: Union[Callable, str] = DEFAULT_GAS_STRATEGY, max_gas_price: Optional[int] = None, signer_uri: Optional[str] = None, # Payments # TODO: Resolve code prefixing below, possibly with the use of nested configuration fields pre_payment_method: Optional[str] = None, - polygon_endpoint: Optional[str] = None, - pre_payment_network: Optional[str] = None, # Registries registry: Optional[ContractRegistry] = None, registry_filepath: Optional[Path] = None, @@ -419,10 +415,12 @@ class CharacterConfiguration(BaseConfiguration): self.poa = poa self.is_light = light self.eth_endpoint = eth_endpoint or NO_BLOCKCHAIN_CONNECTION + self.polygon_endpoint = polygon_endpoint or NO_BLOCKCHAIN_CONNECTION self.signer_uri = signer_uri or None # Learner self.domain = domain + self.taco_network = NetworksInventory.get_network(self.domain) self.learn_on_same_thread = learn_on_same_thread self.abort_on_learning_error = abort_on_learning_error self.start_learning_now = start_learning_now @@ -440,6 +438,8 @@ class CharacterConfiguration(BaseConfiguration): # Decentralized # + # TODO should this be an iteration on [eth_endpoint, polygon_endpoint]? + self.gas_strategy = gas_strategy self.max_gas_price = max_gas_price # gwei is_initialized = BlockchainInterfaceFactory.is_interface_initialized( @@ -483,8 +483,9 @@ class CharacterConfiguration(BaseConfiguration): self.registry = ContractRegistry(source=source) self.log.info(f"Using local registry ({self.registry}).") - self.testnet = self.domain != NetworksInventory.MAINNET - self.signer = Signer.from_signer_uri(self.signer_uri, testnet=self.testnet) + self.signer = Signer.from_signer_uri( + self.signer_uri, testnet=self.taco_network.is_testnet() + ) # # Onchain Payments & Policies @@ -494,24 +495,16 @@ class CharacterConfiguration(BaseConfiguration): from nucypher.config.characters import BobConfiguration if not isinstance(self, BobConfiguration): - # if not polygon_endpoint: - # raise self.ConfigurationError("payment provider is required.") self.pre_payment_method = ( pre_payment_method or self.DEFAULT_PRE_PAYMENT_METHOD ) - self.pre_payment_network = ( - pre_payment_network or self.DEFAULT_PRE_PAYMENT_NETWORK - ) - self.polygon_endpoint = polygon_endpoint or ( - self.eth_endpoint or None - ) # default to L1 payments # TODO: Dedupe if not self.policy_registry: if not self.policy_registry_filepath: self.log.info("Fetching latest policy registry from source.") self.policy_registry = ContractRegistry.from_latest_publication( - domain=self.pre_payment_network + domain=self.taco_network.name ) else: self.policy_registry = ContractRegistry( @@ -717,6 +710,11 @@ class CharacterConfiguration(BaseConfiguration): if self.registry_filepath: payload.update(dict(registry_filepath=self.registry_filepath)) + if self.polygon_endpoint: + payload.update( + polygon_endpoint=self.polygon_endpoint, + ) + # Gas Price __max_price = str(self.max_gas_price) if self.max_gas_price else None payload.update(dict(gas_strategy=self.gas_strategy, max_gas_price=__max_price)) @@ -840,8 +838,8 @@ class CharacterConfiguration(BaseConfiguration): # # Strategy-Based (current implementation, inflexible & hardcoded) # 'pre_payment_strategy': 'SubscriptionManager' - # 'pre_payment_network': 'matic' - # 'polygon_endpoint': 'https:///matic.infura.io....' + # 'network': 'polygon' + # 'blockchain_endpoint': 'https:///polygon.infura.io....' # # Contract-Targeted (alternative implementation, flexible & generic) # 'pre_payment': { @@ -860,8 +858,8 @@ class CharacterConfiguration(BaseConfiguration): if pre_payment_class.ONCHAIN: # on-chain payment strategies require a blockchain connection pre_payment_strategy = pre_payment_class( - network=self.pre_payment_network, - eth_provider=self.polygon_endpoint, + network=self.taco_network.name, + blockchain_endpoint=self.polygon_endpoint, registry=self.policy_registry, ) else: diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index 777322d74..f0e489bac 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -73,7 +73,7 @@ class UrsulaConfiguration(CharacterConfiguration): taco_network = NetworksInventory.get_network(self.domain) # Polygon - polygon_chain_id = taco_network.poly_network.value + polygon_chain_id = taco_network.poly_network.chain_id polygon_provider_uris = self.condition_provider_uris.get(polygon_chain_id, []) if not polygon_provider_uris: self.condition_provider_uris[polygon_chain_id] = polygon_provider_uris @@ -82,7 +82,7 @@ class UrsulaConfiguration(CharacterConfiguration): polygon_provider_uris.append(self.polygon_endpoint) # Ethereum - staking_chain_id = taco_network.eth_network.value + staking_chain_id = taco_network.eth_network.chain_id staking_provider_uris = self.condition_provider_uris.get(staking_chain_id, []) if not staking_provider_uris: self.condition_provider_uris[staking_chain_id] = staking_provider_uris @@ -118,8 +118,6 @@ class UrsulaConfiguration(CharacterConfiguration): # PRE Payments # TODO: Resolve variable prefixing below (uses nested configuration fields?) pre_payment_method=self.pre_payment_method, - polygon_endpoint=self.polygon_endpoint, - pre_payment_network=self.pre_payment_network, ) return {**super().static_payload(), **payload} @@ -180,8 +178,6 @@ class AliceConfiguration(CharacterConfiguration): payload = dict( threshold=self.threshold, shares=self.shares, - pre_payment_network=self.pre_payment_network, - polygon_endpoint=self.polygon_endpoint, pre_payment_method=self.pre_payment_method, rate=self.rate, duration=self.duration, diff --git a/nucypher/config/migrations/configuration_v5_to_v6.py b/nucypher/config/migrations/configuration_v5_to_v6.py index 5ff35994f..9ee0c2321 100644 --- a/nucypher/config/migrations/configuration_v5_to_v6.py +++ b/nucypher/config/migrations/configuration_v5_to_v6.py @@ -7,9 +7,9 @@ from nucypher.config.migrations.common import perform_migration def __migration(config: Dict) -> Dict: taco_network = NetworksInventory.get_network(config["domain"]) eth_provider = config["eth_provider_uri"] - eth_chain_id = taco_network.eth_network.value + eth_chain_id = taco_network.eth_network.chain_id polygon_provider = config["payment_provider"] - polygon_chain_id = taco_network.poly_network.value + polygon_chain_id = taco_network.poly_network.chain_id if "condition_provider_uris" in config: return config config["condition_provider_uris"] = { diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index b53fe0fad..354ff5151 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -271,6 +271,7 @@ class Learner: self.learning_deferred = Deferred() self.domain = domain + self.taco_network = NetworksInventory.get_network(self.domain) default_middleware = self.__DEFAULT_MIDDLEWARE_CLASS( registry=self.registry, eth_provider_uri=self.eth_endpoint ) diff --git a/tests/acceptance/cli/test_ursula_init.py b/tests/acceptance/cli/test_ursula_init.py index 2ed4be782..47972e77a 100644 --- a/tests/acceptance/cli/test_ursula_init.py +++ b/tests/acceptance/cli/test_ursula_init.py @@ -125,8 +125,6 @@ def test_ursula_and_local_keystore_signer_integration( "init", "--network", TEMPORARY_DOMAIN, - "--pre-payment-network", - TEMPORARY_DOMAIN, "--operator-address", worker_account.address, "--config-root", diff --git a/tests/acceptance/cli/test_ursula_run.py b/tests/acceptance/cli/test_ursula_run.py index e0240aa81..635c75077 100644 --- a/tests/acceptance/cli/test_ursula_run.py +++ b/tests/acceptance/cli/test_ursula_run.py @@ -78,8 +78,6 @@ def test_run_lone_default_development_ursula(click_runner, ursulas, testerchain) TEST_ETH_PROVIDER_URI, "--polygon-endpoint", TEST_ETH_PROVIDER_URI, - "--pre-payment-network", - TEMPORARY_DOMAIN, ) result = yield threads.deferToThread( @@ -132,8 +130,6 @@ def test_ursula_learns_via_cli(click_runner, ursulas, testerchain): TEST_ETH_PROVIDER_URI, "--polygon-endpoint", TEST_ETH_PROVIDER_URI, - "--pre-payment-network", - TEMPORARY_DOMAIN, ) return threads.deferToThread( @@ -188,8 +184,6 @@ def test_persistent_node_storage_integration( another_ursula, "--network", TEMPORARY_DOMAIN, - "--pre-payment-network", - TEMPORARY_DOMAIN, "--rest-host", MOCK_IP_ADDRESS, "--config-root", diff --git a/tests/fixtures.py b/tests/fixtures.py index b60ecf97d..c47c3ebc1 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -23,7 +23,6 @@ from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.signers.software import KeystoreSigner from nucypher.blockchain.eth.trackers.dkg import EventScannerTask from nucypher.characters.lawful import Enrico, Ursula -from nucypher.config.base import CharacterConfiguration from nucypher.config.characters import ( AliceConfiguration, BobConfiguration, @@ -264,8 +263,7 @@ def alice(alice_test_config, ursulas, testerchain): @pytest.fixture(scope="module") def bob(bob_test_config, testerchain): bob = bob_test_config.produce( - coordinator_provider_uri=MOCK_ETH_PROVIDER_URI, - coordinator_network=TEMPORARY_DOMAIN, + polygon_endpoint=TEST_ETH_PROVIDER_URI, ) yield bob bob.disenchant() @@ -341,6 +339,7 @@ def light_ursula(temp_dir_path, random_account, mocker): checksum_address=random_account.address, operator_address=random_account.address, eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, signer=KeystoreSigner(path=temp_dir_path), ) return ursula @@ -436,10 +435,6 @@ def highperf_mocked_alice( monkeymodule, testerchain, ): - monkeymodule.setattr( - CharacterConfiguration, "DEFAULT_PRE_PAYMENT_NETWORK", TEMPORARY_DOMAIN - ) - config = AliceConfiguration( dev_mode=True, domain=TEMPORARY_DOMAIN, @@ -503,7 +498,6 @@ def click_runner(): def nominal_configuration_fields(): config = UrsulaConfiguration( dev_mode=True, - pre_payment_network=TEMPORARY_DOMAIN, domain=TEMPORARY_DOMAIN, eth_provider_uri=TEST_ETH_PROVIDER_URI, ) diff --git a/tests/integration/cli/test_cli_config.py b/tests/integration/cli/test_cli_config.py index 9433f0be1..dd93140c7 100644 --- a/tests/integration/cli/test_cli_config.py +++ b/tests/integration/cli/test_cli_config.py @@ -5,7 +5,7 @@ import pytest from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.cli.main import nucypher_cli -from nucypher.config.characters import CharacterConfiguration, UrsulaConfiguration +from nucypher.config.characters import UrsulaConfiguration from nucypher.config.constants import ( NUCYPHER_ENVVAR_KEYSTORE_PASSWORD, TEMPORARY_DOMAIN, @@ -82,9 +82,6 @@ def test_reconfigure_via_cli( monkeypatch.setattr( ContractRegistry, "from_latest_publication", fake_get_latest_registry ) - monkeypatch.setattr( - CharacterConfiguration, "DEFAULT_PRE_PAYMENT_NETWORK", TEMPORARY_DOMAIN - ) custom_config_filepath = custom_filepath / config_class.generate_filename() diff --git a/tests/integration/cli/test_mixed_config.py b/tests/integration/cli/test_mixed_config.py index 581a41314..f127a9868 100644 --- a/tests/integration/cli/test_mixed_config.py +++ b/tests/integration/cli/test_mixed_config.py @@ -70,8 +70,6 @@ def test_corrupted_configuration( another_ursula, "--network", TEMPORARY_DOMAIN, - "--pre-payment-network", - TEMPORARY_DOMAIN, "--rest-host", MOCK_IP_ADDRESS, "--config-root", @@ -107,8 +105,6 @@ def test_corrupted_configuration( "init", "--network", TEMPORARY_DOMAIN, - "--pre-payment-network", - TEMPORARY_DOMAIN, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, "--polygon-endpoint", diff --git a/tests/integration/cli/test_ursula_config_cli.py b/tests/integration/cli/test_ursula_config_cli.py index 43d4860a6..df59fa0b0 100644 --- a/tests/integration/cli/test_ursula_config_cli.py +++ b/tests/integration/cli/test_ursula_config_cli.py @@ -11,7 +11,6 @@ from nucypher.cli.literature import ( CONFIRM_IPV4_ADDRESS_QUESTION, REPEAT_FOR_CONFIRMATION, SELECT_OPERATOR_ACCOUNT, - SELECT_PRE_PAYMENT_NETWORK, SUCCESSFUL_DESTRUCTION, ) from nucypher.cli.main import nucypher_cli @@ -66,13 +65,12 @@ def test_interactive_initialize_ursula(click_runner, mocker, tmpdir): MOCK_ETH_PROVIDER_URI, ) - user_input = '0\n' + '0\n' + YES_ENTER + FAKE_PASSWORD_CONFIRMED - result = click_runner.invoke(nucypher_cli, init_args, input=user_input, catch_exceptions=False) + user_input = "0\n" + YES_ENTER + FAKE_PASSWORD_CONFIRMED + result = click_runner.invoke( + nucypher_cli, init_args, input=user_input, catch_exceptions=False + ) assert result.exit_code == 0, result.output - # Select network - assert SELECT_PRE_PAYMENT_NETWORK in result.output - # Select account assert SELECT_OPERATOR_ACCOUNT in result.output @@ -104,8 +102,6 @@ def test_initialize_custom_configuration_root( MOCK_ETH_PROVIDER_URI, "--polygon-endpoint", MOCK_ETH_PROVIDER_URI, - "--pre-payment-network", - TEMPORARY_DOMAIN, "--operator-address", testerchain.ursulas_accounts[0], ) diff --git a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py index ab032fe38..1e439fa83 100644 --- a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py +++ b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py @@ -53,8 +53,6 @@ def test_ursula_init_with_local_keystore_signer( "--eth-endpoint", testerchain.eth_provider_uri, # Layer 2 - "--pre-payment-network", - TEMPORARY_DOMAIN, "--polygon-endpoint", testerchain.eth_provider_uri, "--rest-host", diff --git a/tests/integration/config/test_character_configuration.py b/tests/integration/config/test_character_configuration.py index 7c8848aab..5ecc7b992 100644 --- a/tests/integration/config/test_character_configuration.py +++ b/tests/integration/config/test_character_configuration.py @@ -44,15 +44,13 @@ all_configurations = tuple( def test_development_character_configurations( character, configuration, mocker, testerchain ): - mocker.patch.object( - CharacterConfiguration, "DEFAULT_PRE_PAYMENT_NETWORK", TEMPORARY_DOMAIN - ) params = dict( dev_mode=True, lonely=True, domain=TEMPORARY_DOMAIN, checksum_address=testerchain.unassigned_accounts[0], eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, ) if character is Ursula: params.update(dict(operator_address=testerchain.unassigned_accounts[0])) @@ -130,7 +128,6 @@ def test_default_character_configuration_preservation( rest_host=MOCK_IP_ADDRESS, polygon_endpoint=MOCK_ETH_PROVIDER_URI, policy_registry=test_registry, - pre_payment_network=TEMPORARY_DOMAIN, keystore=keystore, ) @@ -139,7 +136,6 @@ def test_default_character_configuration_preservation( checksum_address=fake_address, eth_endpoint=MOCK_ETH_PROVIDER_URI, domain=network, - pre_payment_network=TEMPORARY_DOMAIN, policy_registry=test_registry, ) @@ -177,8 +173,8 @@ def test_ursula_development_configuration(testerchain): checksum_address=testerchain.unassigned_accounts[0], operator_address=testerchain.unassigned_accounts[1], domain=TEMPORARY_DOMAIN, - pre_payment_network=TEMPORARY_DOMAIN, eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, ) assert config.is_me is True assert config.dev_mode is True diff --git a/tests/integration/config/test_configuration_persistence.py b/tests/integration/config/test_configuration_persistence.py index 0d2104ef2..78bbc57f1 100644 --- a/tests/integration/config/test_configuration_persistence.py +++ b/tests/integration/config/test_configuration_persistence.py @@ -18,7 +18,6 @@ def test_alices_powers_are_persistent(ursulas, temp_dir_path, testerchain): config_root=config_root, network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), domain=TEMPORARY_DOMAIN, - pre_payment_network=TEMPORARY_DOMAIN, checksum_address=testerchain.alice_account, start_learning_now=False, save_metadata=False, diff --git a/tests/integration/config/test_keystore_integration.py b/tests/integration/config/test_keystore_integration.py index b11937c03..cdfd1bc84 100644 --- a/tests/integration/config/test_keystore_integration.py +++ b/tests/integration/config/test_keystore_integration.py @@ -82,6 +82,7 @@ def test_characters_use_keystore(temp_dir_path, testerchain): keystore=keystore, domain=TEMPORARY_DOMAIN, eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, checksum_address=testerchain.alice_account, pre_payment_method=pre_payment_method, ) @@ -93,6 +94,7 @@ def test_characters_use_keystore(temp_dir_path, testerchain): ) Ursula( eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, start_learning_now=False, keystore=keystore, rest_host=LOOPBACK_ADDRESS, @@ -171,6 +173,7 @@ def test_ritualist(temp_dir_path, testerchain, dkg_public_key): operator_address=testerchain.ursulas_accounts[0], signer=Web3Signer(testerchain.client), eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, ) ritual_id = 23 diff --git a/tests/integration/config/test_storages.py b/tests/integration/config/test_storages.py index f7a96cbca..53c05e49c 100644 --- a/tests/integration/config/test_storages.py +++ b/tests/integration/config/test_storages.py @@ -47,6 +47,7 @@ class BaseTestNodeStorageBackends: domain=TEMPORARY_DOMAIN, signer=signer, eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, checksum_address=operator_addresses[i], operator_address=operator_addresses[i], pre_payment_method=pre_payment_method, diff --git a/tests/utils/config.py b/tests/utils/config.py index 37ccdb80a..718a9c70d 100644 --- a/tests/utils/config.py +++ b/tests/utils/config.py @@ -55,7 +55,6 @@ def make_ursula_test_configuration( **test_params, rest_port=rest_port, polygon_endpoint=polygon_endpoint, - pre_payment_network=TEMPORARY_DOMAIN, operator_address=operator_address, policy_registry=test_params["registry"] ) @@ -69,7 +68,6 @@ def make_alice_test_configuration( config = AliceConfiguration( **test_params, polygon_endpoint=polygon_endpoint, - pre_payment_network=TEMPORARY_DOMAIN, policy_registry=test_params["registry"] ) return config From c8b5264c7ceab95cc2f2e55796b9c6eda189c007 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 09:41:46 -0400 Subject: [PATCH 12/63] Rename eth_provider_uri to eth_endpoint in various spots specific to payment, config, characters. --- nucypher/characters/unlawful.py | 17 ++++---- nucypher/cli/actions/select.py | 20 ++++++---- nucypher/cli/commands/ursula.py | 6 +-- nucypher/cli/utils.py | 2 +- nucypher/policy/payment.py | 7 ++-- .../characters/test_decentralized_grant.py | 2 +- tests/fixtures.py | 7 ++-- .../characters/test_dkg_and_testnet_bypass.py | 2 +- .../cli/actions/test_select_client_account.py | 40 +++++++++++-------- .../config/test_configuration_persistence.py | 2 +- .../config/test_keystore_integration.py | 4 +- tests/integration/config/test_storages.py | 2 +- 12 files changed, 63 insertions(+), 48 deletions(-) diff --git a/nucypher/characters/unlawful.py b/nucypher/characters/unlawful.py index 2b384cc20..2bbc3a06b 100644 --- a/nucypher/characters/unlawful.py +++ b/nucypher/characters/unlawful.py @@ -42,14 +42,16 @@ class Vladimir(Ursula): raise DevelopmentInstallationRequired( importable_name="tests.utils.middleware.EvilMiddleWare" ) - blockchain = target_ursula.application_agent.blockchain + eth_blockchain = target_ursula.application_agent.blockchain cls.network_middleware = EvilMiddleWare( - eth_provider_uri=blockchain.eth_provider_uri + eth_provider_uri=eth_blockchain.eth_provider_uri ) + polygon_blockchain = target_ursula.child_application_agent.blockchain + crypto_power = CryptoPower(power_ups=target_ursula._default_crypto_powerups) - cls.attach_transacting_key(blockchain=blockchain) + cls.attach_transacting_key(blockchain=eth_blockchain) # Vladimir does not care about payment. bogus_pre_payment_method = FreeReencryptions() @@ -57,11 +59,11 @@ class Vladimir(Ursula): bogus_pre_payment_method.agent = Mock() bogus_pre_payment_method.network = TEMPORARY_DOMAIN bogus_pre_payment_method.agent.blockchain.client.chain_id = ( - blockchain.client.chain_id + polygon_blockchain.client.chain_id ) mock.patch( "mock.interfaces.MockBlockchain.client.chain_id", - new_callable=mock.PropertyMock(return_value=blockchain.client.chain_id), + new_callable=mock.PropertyMock(return_value=eth_blockchain.client.chain_id), ) vladimir = cls( @@ -74,8 +76,9 @@ class Vladimir(Ursula): network_middleware=cls.network_middleware, checksum_address=cls.fraud_address, operator_address=cls.fraud_address, - signer=Web3Signer(blockchain.client), - eth_endpoint=blockchain.eth_provider_uri, + signer=Web3Signer(eth_blockchain.client), + eth_endpoint=eth_blockchain.eth_provider_uri, + polygon_endpoint=polygon_blockchain.eth_provider_uri, pre_payment_method=bogus_pre_payment_method, ) diff --git a/nucypher/cli/actions/select.py b/nucypher/cli/actions/select.py index adead84f1..0692ea8a9 100644 --- a/nucypher/cli/actions/select.py +++ b/nucypher/cli/actions/select.py @@ -34,7 +34,7 @@ from nucypher.utilities.emitters import StdoutEmitter def select_client_account( emitter, - eth_provider_uri: str = None, + eth_endpoint: str = None, signer: Signer = None, signer_uri: str = None, prompt: str = None, @@ -55,17 +55,21 @@ def select_client_account( if signer and signer_uri: raise ValueError('Pass either signer or signer_uri but not both.') - if not any((eth_provider_uri, signer_uri, signer)): + if not any((eth_endpoint, signer_uri, signer)): raise ValueError("At least a provider URI, signer URI or signer must be provided to select an account") - if eth_provider_uri: + if eth_endpoint: # Connect to the blockchain in order to select an account - if not BlockchainInterfaceFactory.is_interface_initialized(eth_provider_uri=eth_provider_uri): - BlockchainInterfaceFactory.initialize_interface(eth_provider_uri=eth_provider_uri, poa=poa, emitter=emitter) + if not BlockchainInterfaceFactory.is_interface_initialized( + eth_provider_uri=eth_endpoint + ): + BlockchainInterfaceFactory.initialize_interface( + eth_provider_uri=eth_endpoint, poa=poa, emitter=emitter + ) if not signer_uri: - signer_uri = eth_provider_uri + signer_uri = eth_endpoint - blockchain = BlockchainInterfaceFactory.get_interface(eth_provider_uri=eth_provider_uri) + blockchain = BlockchainInterfaceFactory.get_interface(eth_provider_uri=eth_endpoint) if signer_uri and not signer: testnet = network != NetworksInventory.MAINNET.name @@ -101,7 +105,7 @@ def select_client_account( row.append(f'{ether_balance} ETH') if show_nu_balance: token_agent = ContractAgency.get_agent( - NucypherTokenAgent, registry=registry, provider_uri=eth_provider_uri + NucypherTokenAgent, registry=registry, provider_uri=eth_endpoint ) token_balance = NU.from_units(token_agent.get_balance(account, registry)) row.append(token_balance) diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index 01436ceb3..fbf0c1a2e 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -170,7 +170,7 @@ class UrsulaConfigOptions: self.operator_address = select_client_account( emitter=emitter, prompt=prompt, - eth_provider_uri=self.eth_endpoint, + eth_endpoint=self.eth_endpoint, signer_uri=self.signer_uri, ) @@ -193,7 +193,7 @@ class UrsulaConfigOptions: operator_address=self.operator_address, registry_filepath=self.registry_filepath, policy_registry_filepath=self.policy_registry_filepath, - eth_provider_uri=self.eth_endpoint, + eth_endpoint=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, @@ -211,7 +211,7 @@ class UrsulaConfigOptions: operator_address=self.operator_address, registry_filepath=self.registry_filepath, policy_registry_filepath=self.policy_registry_filepath, - eth_provider_uri=self.eth_endpoint, + eth_endpoint=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, diff --git a/nucypher/cli/utils.py b/nucypher/cli/utils.py index e8cdff188..9d6312166 100644 --- a/nucypher/cli/utils.py +++ b/nucypher/cli/utils.py @@ -89,7 +89,7 @@ def make_cli_character( CHARACTER = character_config( known_nodes=sage_nodes, network_middleware=character_config.network_middleware, - eth_provider_uri=provider_uri, + eth_endpoint=provider_uri, **config_args, ) diff --git a/nucypher/policy/payment.py b/nucypher/policy/payment.py index b148ad942..94d034e79 100644 --- a/nucypher/policy/payment.py +++ b/nucypher/policy/payment.py @@ -6,6 +6,7 @@ from nucypher_core import ReencryptionRequest from web3.types import ChecksumAddress, Timestamp, TxReceipt, Wei from nucypher.blockchain.eth.agents import ContractAgency, SubscriptionManagerAgent +from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.policy import policies @@ -64,15 +65,15 @@ class ContractPayment(PaymentMethod, ABC): def __init__( self, - eth_provider: str, + blockchain_endpoint: str, network: str, registry: Optional[ContractRegistry] = None, *args, **kwargs, ): super().__init__(*args, **kwargs) - self.provider = eth_provider - self.network = network + self.provider = blockchain_endpoint + self.taco_network = NetworksInventory.get_network(network) if not registry: registry = ContractRegistry.from_latest_publication(domain=network) self.registry = registry diff --git a/tests/acceptance/characters/test_decentralized_grant.py b/tests/acceptance/characters/test_decentralized_grant.py index b862744b9..80542f403 100644 --- a/tests/acceptance/characters/test_decentralized_grant.py +++ b/tests/acceptance/characters/test_decentralized_grant.py @@ -30,7 +30,7 @@ def check(policy, bob, ursulas): def test_grant_subscription_manager(alice, bob, ursulas): pre_payment_method = SubscriptionManagerPayment( - eth_provider=TEST_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN + blockchain_endpoint=TEST_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN ) alice.pre_payment_method = pre_payment_method policy = alice.grant( diff --git a/tests/fixtures.py b/tests/fixtures.py index c47c3ebc1..af9312e17 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -323,8 +323,7 @@ def light_ursula(temp_dir_path, random_account, mocker): KeystoreSigner, "_KeystoreSigner__get_signer", return_value=random_account ) pre_payment_method = SubscriptionManagerPayment( - eth_provider=MOCK_ETH_PROVIDER_URI, - network=TEMPORARY_DOMAIN, + blockchain_endpoint=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN ) mocker.patch.object( @@ -438,7 +437,7 @@ def highperf_mocked_alice( config = AliceConfiguration( dev_mode=True, domain=TEMPORARY_DOMAIN, - eth_provider_uri=TEST_ETH_PROVIDER_URI, + eth_endpoint=TEST_ETH_PROVIDER_URI, checksum_address=testerchain.alice_account, network_middleware=MockRestMiddlewareForLargeFleetTests( eth_provider_uri=TEST_ETH_PROVIDER_URI @@ -499,7 +498,7 @@ def nominal_configuration_fields(): config = UrsulaConfiguration( dev_mode=True, domain=TEMPORARY_DOMAIN, - eth_provider_uri=TEST_ETH_PROVIDER_URI, + eth_endpoint=TEST_ETH_PROVIDER_URI, ) config_fields = config.static_payload() yield tuple(config_fields.keys()) diff --git a/tests/integration/characters/test_dkg_and_testnet_bypass.py b/tests/integration/characters/test_dkg_and_testnet_bypass.py index d42845d3d..3e6014660 100644 --- a/tests/integration/characters/test_dkg_and_testnet_bypass.py +++ b/tests/integration/characters/test_dkg_and_testnet_bypass.py @@ -23,7 +23,7 @@ def _attempt_decryption(BobClass, plaintext, testerchain): bob = BobClass( registry=MOCK_REGISTRY_FILEPATH, domain="lynx", - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) definitely_false_condition = { diff --git a/tests/integration/cli/actions/test_select_client_account.py b/tests/integration/cli/actions/test_select_client_account.py index 01451c5ed..1f0a81624 100644 --- a/tests/integration/cli/actions/test_select_client_account.py +++ b/tests/integration/cli/actions/test_select_client_account.py @@ -33,7 +33,7 @@ def test_select_client_account( selected_account = select_client_account( emitter=test_emitter, signer=Web3Signer(testerchain.client), - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) assert selected_account, "Account selection returned Falsy instead of an address" assert isinstance(selected_account, str), "Selection is not a str" @@ -56,7 +56,7 @@ def test_select_client_account_with_no_accounts( select_client_account( emitter=test_emitter, signer=Web3Signer(testerchain.client), - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) captured = capsys.readouterr() assert NO_ETH_ACCOUNTS in captured.out @@ -120,7 +120,9 @@ def test_select_client_account_valid_sources( # From pre-initialized Provider mock_stdin.line(str(selection)) expected_account = testerchain.client.accounts[selection] - selected_account = select_client_account(emitter=test_emitter, eth_provider_uri=MOCK_ETH_PROVIDER_URI) + selected_account = select_client_account( + emitter=test_emitter, eth_endpoint=MOCK_ETH_PROVIDER_URI + ) assert selected_account == expected_account assert mock_stdin.empty() captured = capsys.readouterr() @@ -136,7 +138,7 @@ def test_select_client_account_valid_sources( BlockchainInterfaceFactory, "get_interface", return_value=testerchain ) selected_account = select_client_account( - emitter=test_emitter, eth_provider_uri=MOCK_ETH_PROVIDER_URI + emitter=test_emitter, eth_endpoint=MOCK_ETH_PROVIDER_URI ) assert selected_account == expected_account assert mock_stdin.empty() @@ -175,21 +177,27 @@ def test_select_client_account_with_balance_display( # Missing network kwarg with balance display active blockchain_read_required = any((show_staking, show_eth, show_tokens)) if blockchain_read_required: - with pytest.raises(ValueError, match='Pass network name or registry; Got neither.'): - select_client_account(emitter=test_emitter, - show_eth_balance=show_eth, - show_nu_balance=show_tokens, - show_staking=show_staking, - eth_provider_uri=MOCK_ETH_PROVIDER_URI) + with pytest.raises( + ValueError, match="Pass network name or registry; Got neither." + ): + select_client_account( + emitter=test_emitter, + show_eth_balance=show_eth, + show_nu_balance=show_tokens, + show_staking=show_staking, + eth_endpoint=MOCK_ETH_PROVIDER_URI, + ) # Good selection mock_stdin.line(str(selection)) - selected_account = select_client_account(emitter=test_emitter, - network=TEMPORARY_DOMAIN, - show_eth_balance=show_eth, - show_nu_balance=show_tokens, - show_staking=show_staking, - eth_provider_uri=MOCK_ETH_PROVIDER_URI) + selected_account = select_client_account( + emitter=test_emitter, + network=TEMPORARY_DOMAIN, + show_eth_balance=show_eth, + show_nu_balance=show_tokens, + show_staking=show_staking, + eth_endpoint=MOCK_ETH_PROVIDER_URI, + ) # check for accurate selection consistency with client index assert selected_account == testerchain.client.accounts[selection] diff --git a/tests/integration/config/test_configuration_persistence.py b/tests/integration/config/test_configuration_persistence.py index 78bbc57f1..1dd6b3c6e 100644 --- a/tests/integration/config/test_configuration_persistence.py +++ b/tests/integration/config/test_configuration_persistence.py @@ -14,7 +14,7 @@ def test_alices_powers_are_persistent(ursulas, temp_dir_path, testerchain): # Create a non-learning AliceConfiguration config_root = temp_dir_path / 'nucypher-custom-alice-config' alice_config = AliceConfiguration( - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, config_root=config_root, network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), domain=TEMPORARY_DOMAIN, diff --git a/tests/integration/config/test_keystore_integration.py b/tests/integration/config/test_keystore_integration.py index cdfd1bc84..5881ae7a3 100644 --- a/tests/integration/config/test_keystore_integration.py +++ b/tests/integration/config/test_keystore_integration.py @@ -74,7 +74,7 @@ def test_characters_use_keystore(temp_dir_path, testerchain): keystore.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) pre_payment_method = SubscriptionManagerPayment( - eth_provider=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN + blockchain_endpoint=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN ) alice = Alice( @@ -160,7 +160,7 @@ def test_ritualist(temp_dir_path, testerchain, dkg_public_key): keystore.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) pre_payment_method = SubscriptionManagerPayment( - eth_provider=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN + blockchain_endpoint=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN ) ursula = Ursula( diff --git a/tests/integration/config/test_storages.py b/tests/integration/config/test_storages.py index 53c05e49c..a832a7a60 100644 --- a/tests/integration/config/test_storages.py +++ b/tests/integration/config/test_storages.py @@ -35,7 +35,7 @@ class BaseTestNodeStorageBackends: assert ursula == node_from_storage, "Node storage {} failed".format(node_storage) pre_payment_method = SubscriptionManagerPayment( - eth_provider=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN + blockchain_endpoint=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN ) # Save more nodes From 80d6d536efa5c1865390d21eef2171ba22901f51 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 09:58:52 -0400 Subject: [PATCH 13/63] Temporary workaround until single registry changes are used. --- nucypher/blockchain/eth/networks.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/nucypher/blockchain/eth/networks.py b/nucypher/blockchain/eth/networks.py index 8f139c329..b0bcca880 100644 --- a/nucypher/blockchain/eth/networks.py +++ b/nucypher/blockchain/eth/networks.py @@ -64,6 +64,9 @@ class NetworksInventory: SUPPORTED_NETWORK_NAMES = [network.name for network in SUPPORTED_NETWORKS] + # TODO not needed once merged with registry changes + POLY_NETWORKS = [network.poly_network.chain_name for network in SUPPORTED_NETWORKS] + DEFAULT_NETWORK_NAME: str = MAINNET.name @classmethod From 0411ab4be6ab6d93b13d1af988148fd1b2f909ec Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 09:57:36 -0400 Subject: [PATCH 14/63] Update nucypher_agents script. --- scripts/hooks/nucypher_agents.py | 63 +++++++++++++------------------- 1 file changed, 26 insertions(+), 37 deletions(-) diff --git a/scripts/hooks/nucypher_agents.py b/scripts/hooks/nucypher_agents.py index 63034e2ec..e2b7f2dc7 100644 --- a/scripts/hooks/nucypher_agents.py +++ b/scripts/hooks/nucypher_agents.py @@ -42,71 +42,60 @@ emitter = StdoutEmitter(verbosity=2) @click.command() @click.option( - "--eth-provider", - "eth_provider_uri", + "--network", + "network", + help="TACo network", + type=click.Choice(NetworksInventory.SUPPORTED_NETWORK_NAMES), + default="lynx", +) +@click.option( + "--eth-endpoint", + "eth_endpoint", help="ETH staking network provider URI", type=click.STRING, required=True, ) @click.option( - "--eth-staking-network", - "eth_staking_network", - help="ETH staking network", - type=click.Choice(NetworksInventory.ETH_NETWORKS), - default="lynx", -) -@click.option( - "--coordinator-provider", - "coordinator_provider_uri", - help="Coordinator network provider URI", + "--polygon-endpoint", + "polygon_endpoint", + help="Polygon network provider URI", type=click.STRING, required=True, ) -@click.option( - "--coordinator-network", - "coordinator_network", - help="Coordinator network", - type=click.Choice(NetworksInventory.POLY_NETWORKS), - default="mumbai", -) def nucypher_agents( - eth_provider_uri, - eth_staking_network, - coordinator_provider_uri, - coordinator_network, + network, + eth_endpoint, + polygon_endpoint, ): - staking_registry = ContractRegistry.from_latest_publication( - domain=eth_staking_network - ) - emitter.echo(f"NOTICE: Connecting to {eth_staking_network} network", color="yellow") + staking_registry = ContractRegistry.from_latest_publication(domain=network) + emitter.echo(f"NOTICE: Connecting to {network} network", color="yellow") taco_application_agent = ContractAgency.get_agent( agent_class=TACoApplicationAgent, registry=staking_registry, - provider_uri=eth_provider_uri, + provider_uri=eth_endpoint, ) # type: TACoApplicationAgent - coordinator_network_registry = ContractRegistry.from_latest_publication( - domain=coordinator_network + registry = ContractRegistry.from_latest_publication( + domain=network ) - emitter.echo(f"NOTICE: Connecting to {coordinator_network} network", color="yellow") taco_child_application_agent = ContractAgency.get_agent( agent_class=TACoChildApplicationAgent, - registry=coordinator_network_registry, - provider_uri=coordinator_provider_uri, + registry=registry, + provider_uri=polygon_endpoint, ) # type: TACoChildApplicationAgent coordinator_agent = ContractAgency.get_agent( agent_class=CoordinatorAgent, - registry=coordinator_network_registry, - provider_uri=coordinator_provider_uri, + registry=registry, + provider_uri=polygon_endpoint, ) # type: CoordinatorAgent subscription_manager_agent = ContractAgency.get_agent( agent_class=SubscriptionManagerAgent, - registry=coordinator_network_registry, - provider_uri=coordinator_provider_uri, + registry=registry, + provider_uri=polygon_endpoint, ) # type: SubscriptionManagerAgent message = ( From 8d799f623d6900ee58cafa5e3b6bb8250ecb27e4 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 10:26:26 -0400 Subject: [PATCH 15/63] Make sure Bob passes along polygon_endpoint parameter value to Character. --- nucypher/characters/lawful.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index 8184b8a08..6298b8278 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -459,7 +459,7 @@ class Bob(Character): is_me: bool = True, verify_node_bonding: bool = False, eth_endpoint: str = None, - polygon_endpoint: str = None, # TODO: Move to a higher level and formalize + polygon_endpoint: str = None, *args, **kwargs, ) -> None: @@ -469,6 +469,7 @@ class Bob(Character): known_node_class=Ursula, verify_node_bonding=verify_node_bonding, eth_endpoint=eth_endpoint, + polygon_endpoint=polygon_endpoint, *args, **kwargs, ) From 74517534f5c88fc9a562ce293781c5fce8be45df Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 10:42:40 -0400 Subject: [PATCH 16/63] Use correct value from enum for teacher nodes. Add unit test for supported taco networks. --- nucypher/network/nodes.py | 8 ++++---- tests/unit/test_teacher_nodes.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 tests/unit/test_teacher_nodes.py diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index 354ff5151..b6e778f08 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -46,14 +46,14 @@ from nucypher.network.protocols import InterfaceInfo, SuspiciousActivity from nucypher.utilities.logging import Logger TEACHER_NODES = { - NetworksInventory.MAINNET: ( + NetworksInventory.MAINNET.name: ( 'https://closest-seed.nucypher.network:9151', 'https://seeds.nucypher.network', 'https://mainnet.nucypher.network:9151', ), - NetworksInventory.LYNX: ("https://lynx.nucypher.network:9151",), - NetworksInventory.TAPIR: ("https://tapir.nucypher.network:9151",), - NetworksInventory.ORYX: ("https://oryx.nucypher.network:9151",), + NetworksInventory.LYNX.name: ("https://lynx.nucypher.network:9151",), + NetworksInventory.TAPIR.name: ("https://tapir.nucypher.network:9151",), + NetworksInventory.ORYX.name: ("https://oryx.nucypher.network:9151",), } diff --git a/tests/unit/test_teacher_nodes.py b/tests/unit/test_teacher_nodes.py new file mode 100644 index 000000000..078c3ad00 --- /dev/null +++ b/tests/unit/test_teacher_nodes.py @@ -0,0 +1,19 @@ +import pytest + +from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.network.nodes import TEACHER_NODES + + +@pytest.fixture(autouse=True) +def mock_teacher_nodes(mocker): + # override fixture + yield + + +def test_default_teacher_seednodes_defined(): + for network_name in NetworksInventory.SUPPORTED_NETWORK_NAMES: + if network_name == NetworksInventory.IBEX.name: + # skip + continue + teacher_nodes = TEACHER_NODES[network_name] + assert len(teacher_nodes) > 0 From d3e175a8005deeb8cdff755045291a480a9eff58 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 10:43:55 -0400 Subject: [PATCH 17/63] Update nucypher_dkg script to accomodate naming/philosophy changes regarding not needing redundant parameters for associated polygon network. --- scripts/hooks/nucypher_dkg.py | 68 +++++++++++++++-------------------- 1 file changed, 29 insertions(+), 39 deletions(-) diff --git a/scripts/hooks/nucypher_dkg.py b/scripts/hooks/nucypher_dkg.py index 63441c5f7..cd6b9f24d 100644 --- a/scripts/hooks/nucypher_dkg.py +++ b/scripts/hooks/nucypher_dkg.py @@ -11,6 +11,7 @@ from nucypher.blockchain.eth.agents import ( CoordinatorAgent, TACoApplicationAgent, ) +from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner, Signer from nucypher.characters.lawful import Bob, Enrico @@ -43,33 +44,26 @@ def get_transacting_power(signer: Signer): @click.command() @click.option( - "--eth-provider", - "eth_provider_uri", + "--network", + "network", + help="TACo Network", + type=click.Choice(["tapir", "lynx"]), + default="lynx", +) +@click.option( + "--eth-endpoint", + "eth_endpoint", help="ETH staking network provider URI", type=click.STRING, required=True, ) @click.option( - "--eth-staking-network", - "eth_staking_network", - help="ETH staking network", - type=click.Choice(["tapir", "lynx"]), - default="lynx", -) -@click.option( - "--coordinator-provider", - "coordinator_provider_uri", - help="Coordinator network provider URI", + "--polygon-endpoint", + "polygon_endpoint", + help="Polygon network provider URI", type=click.STRING, required=True, ) -@click.option( - "--coordinator-network", - "coordinator_network", - help="Coordinator network", - type=click.Choice(["mumbai"]), - default="mumbai", -) @click.option( "--ritual-id", "ritual_id", @@ -117,10 +111,9 @@ def get_transacting_power(signer: Signer): default=False, ) def nucypher_dkg( - eth_provider_uri, - eth_staking_network, - coordinator_provider_uri, - coordinator_network, + network, + eth_endpoint, + polygon_endpoint, ritual_id, signer_uri, dkg_size, @@ -161,22 +154,20 @@ def nucypher_dkg( ), ) - coordinator_network_registry = ContractRegistry.from_latest_publication( - domain=coordinator_network + taco_network = NetworksInventory.get_network(network) + registry = ContractRegistry.from_latest_publication( + domain=network ) coordinator_agent = ContractAgency.get_agent( agent_class=CoordinatorAgent, - registry=coordinator_network_registry, - provider_uri=coordinator_provider_uri, + registry=registry, + provider_uri=polygon_endpoint, ) # type: CoordinatorAgent - staking_network_registry = ContractRegistry.from_latest_publication( - domain=eth_staking_network - ) application_agent = ContractAgency.get_agent( agent_class=TACoApplicationAgent, - registry=staking_network_registry, - provider_uri=eth_provider_uri, + registry=registry, + provider_uri=eth_endpoint, ) # type: TACoApplicationAgent # @@ -188,7 +179,7 @@ def nucypher_dkg( # Get GlobalAllowList contract blockchain = coordinator_agent.blockchain allow_list = blockchain.get_contract_by_name( - registry=coordinator_network_registry, contract_name=GLOBAL_ALLOW_LIST + registry=registry, contract_name=GLOBAL_ALLOW_LIST ) # @@ -202,7 +193,7 @@ def nucypher_dkg( emitter.echo("--------- Initiating Ritual ---------", color="yellow") emitter.echo( - f"Commencing DKG Ritual(s) on {coordinator_network} using {account_address}", + f"Commencing DKG Ritual(s) on {taco_network.poly_network.chain_name} using {account_address}", color="green", ) @@ -389,11 +380,10 @@ def nucypher_dkg( # emitter.echo("--------- Threshold Decryption ---------") bob = Bob( - eth_provider_uri=eth_provider_uri, - domain=eth_staking_network, - registry=staking_network_registry, - coordinator_network=coordinator_network, - coordinator_provider_uri=coordinator_provider_uri, + domain=network, + eth_endpoint=eth_endpoint, + polygon_endpoint=polygon_endpoint, + registry=registry, ) bob.start_learning_loop(now=True) From 4ab26188e9bb021a9dcd0f81b179ee3938c4f59d Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 10:50:00 -0400 Subject: [PATCH 18/63] Update TACo example scripts to no longer use redundant parameters with respect to polygon network. --- examples/local_simple_taco.py | 2 +- examples/testnet_compound_multichain_taco.py | 25 +++++++++++--------- examples/testnet_simple_taco.py | 25 +++++++++++--------- 3 files changed, 29 insertions(+), 23 deletions(-) diff --git a/examples/local_simple_taco.py b/examples/local_simple_taco.py index 4273757a4..d0c7038a5 100644 --- a/examples/local_simple_taco.py +++ b/examples/local_simple_taco.py @@ -8,7 +8,7 @@ THIS_IS_NOT_A_TRINKET = 55 # sometimes called "public key" signer = InMemorySigner() enrico = _Enrico(encrypting_key=THIS_IS_NOT_A_TRINKET, signer=signer) -bob = ThisBobAlwaysDecrypts(domain="lynx", eth_provider_uri="Nowhere") +bob = ThisBobAlwaysDecrypts(domain="lynx", eth_endpoint="Nowhere") ANYTHING_CAN_BE_PASSED_AS_RITUAL_ID = 55 diff --git a/examples/testnet_compound_multichain_taco.py b/examples/testnet_compound_multichain_taco.py index 6afda0a91..896d22dd8 100644 --- a/examples/testnet_compound_multichain_taco.py +++ b/examples/testnet_compound_multichain_taco.py @@ -3,6 +3,7 @@ import os from nucypher_core.ferveo import DkgPublicKey from nucypher.blockchain.eth.agents import CoordinatorAgent +from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner from nucypher.characters.lawful import Bob, Enrico @@ -18,11 +19,10 @@ LOG_LEVEL = "info" GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() -staking_provider_uri = os.environ["DEMO_L1_PROVIDER_URI"] -network = "lynx" +eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] +taco_network = NetworksInventory.get_network("lynx") -coordinator_provider_uri = os.environ["DEMO_L2_PROVIDER_URI"] -coordinator_network = "mumbai" +polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] ############### # Enrico @@ -30,9 +30,13 @@ coordinator_network = "mumbai" print("--------- Threshold Encryption ---------") +registry = ContractRegistry.from_latest_publication( + domain=taco_network.name, +) + coordinator_agent = CoordinatorAgent( - provider_uri=coordinator_provider_uri, - registry=ContractRegistry.from_latest_publication(domain=coordinator_network), + provider_uri=polygon_endpoint, + registry=registry, ) ritual_id = 1 # got this from a side channel ritual = coordinator_agent.get_ritual(ritual_id) @@ -96,11 +100,10 @@ print(f"\nEncrypted message:\n{bytes(threshold_message_kit).hex()}") print("--------- Threshold Decryption ---------") bob = Bob( - eth_endpoint=staking_provider_uri, - domain=network, - coordinator_provider_uri=coordinator_provider_uri, - coordinator_network=coordinator_network, - registry=ContractRegistry.from_latest_publication(domain=network), + domain=taco_network.name, + eth_endpoint=eth_endpoint, + polygon_endpoint=polygon_endpoint, + registry=registry, ) bob.start_learning_loop(now=True) diff --git a/examples/testnet_simple_taco.py b/examples/testnet_simple_taco.py index 3befd6f05..79c7b7bcb 100644 --- a/examples/testnet_simple_taco.py +++ b/examples/testnet_simple_taco.py @@ -3,6 +3,7 @@ import os from nucypher_core.ferveo import DkgPublicKey from nucypher.blockchain.eth.agents import CoordinatorAgent +from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner from nucypher.characters.lawful import Bob, Enrico @@ -18,11 +19,10 @@ LOG_LEVEL = "info" GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() -staking_provider_uri = os.environ["DEMO_L1_PROVIDER_URI"] -network = "lynx" +eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] +taco_network = NetworksInventory.get_network("lynx") -coordinator_provider_uri = os.environ["DEMO_L2_PROVIDER_URI"] -coordinator_network = "mumbai" +polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] ############### # Enrico @@ -30,9 +30,13 @@ coordinator_network = "mumbai" print("--------- Threshold Encryption ---------") +registry = ContractRegistry.from_latest_publication( + domain=taco_network.name, +) + coordinator_agent = CoordinatorAgent( - provider_uri=coordinator_provider_uri, - registry=ContractRegistry.from_latest_publication(domain=coordinator_network), + provider_uri=polygon_endpoint, + registry=registry, ) ritual_id = 1 # got this from a side channel ritual = coordinator_agent.get_ritual(ritual_id) @@ -73,11 +77,10 @@ print(f"\nEncrypted message:\n{bytes(threshold_message_kit).hex()}") print("--------- Threshold Decryption ---------") bob = Bob( - eth_endpoint=staking_provider_uri, - domain=network, - coordinator_provider_uri=coordinator_provider_uri, - coordinator_network=coordinator_network, - registry=ContractRegistry.from_latest_publication(domain=network), + domain=taco_network.name, + eth_endpoint=eth_endpoint, + polygon_endpoint=polygon_endpoint, + registry=registry, ) bob.start_learning_loop(now=True) From 55c6e6a971b488f7908ee21a42ac1e14bd9f237e Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 11:18:46 -0400 Subject: [PATCH 19/63] Update PRE examples to no longer require specifying an L2_NETWORK since it is implied based on the TACo Network being used. --- examples/pre/finnegans_wake_demo/README.md | 3 +-- .../pre/finnegans_wake_demo/finnegans-wake-demo-l2.py | 10 +++++----- examples/pre/heartbeat_demo/alicia.py | 8 ++++---- examples/pre/heartbeat_demo/doctor.py | 4 ++-- examples/pre/heartbeat_demo/heartbeat_demo.md | 3 +-- 5 files changed, 13 insertions(+), 15 deletions(-) diff --git a/examples/pre/finnegans_wake_demo/README.md b/examples/pre/finnegans_wake_demo/README.md index e5e86b77f..22edcfcd9 100644 --- a/examples/pre/finnegans_wake_demo/README.md +++ b/examples/pre/finnegans_wake_demo/README.md @@ -20,8 +20,7 @@ and adding your provider and wallet details. To set the variables in your curre Optionally, you can change the network the demo is running on by changing the value of `L1_NETWORK` and `L2_NETWORK`. If you change these values be sure to also change `L1_PROVIDER_URI` and `L2_PROVIDER_URI` accordingly. -Available options for `L1_NETWORK` are `tapir` or `mainnet`. -Available options for `L2_NETWORK` are `mumbai` or `mainnet` +Available options for `TACO_NETWORK` are `lynx`, `tapir` or `mainnet`. Ensure Alice's account has a bit of MATIC on polygon to pay for the policy. diff --git a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py index c0b7c7376..584079c38 100644 --- a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py +++ b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py @@ -44,8 +44,7 @@ print("\n************** Setup **************\n") # Network # ########### -L1_NETWORK = "lynx" -L2_NETWORK = "mumbai" +TACO_NETWORK = "lynx" ##################### # Bob the BUIDLer ## @@ -54,7 +53,7 @@ L2_NETWORK = "mumbai" # Then, there was bob. Bob learns about the # rest of the network from the seednode. bob = Bob( - domain=L1_NETWORK, + domain=TACO_NETWORK, eth_endpoint=L1_PROVIDER, ) @@ -82,15 +81,16 @@ wallet.unlock_account(account=ALICE_ADDRESS, password=password) # This is Alice's PRE payment method. pre_payment_method = SubscriptionManagerPayment( - network=L2_NETWORK, eth_provider=L2_PROVIDER + network=TACO_NETWORK, blockchain_endpoint=L2_PROVIDER ) # This is Alice. alice = Alice( checksum_address=ALICE_ADDRESS, signer=wallet, - domain=L1_NETWORK, + domain=TACO_NETWORK, eth_endpoint=L1_PROVIDER, + polygon_endpoint=L2_PROVIDER, pre_payment_method=pre_payment_method, ) diff --git a/examples/pre/heartbeat_demo/alicia.py b/examples/pre/heartbeat_demo/alicia.py index e431f2c7e..93b836886 100644 --- a/examples/pre/heartbeat_demo/alicia.py +++ b/examples/pre/heartbeat_demo/alicia.py @@ -57,8 +57,7 @@ try: except KeyError: raise RuntimeError("Missing environment variables to run demo.") -L1_NETWORK = "lynx" -L2_NETWORK = "mumbai" +TACO_NETWORK = "lynx" ####################################### @@ -80,15 +79,16 @@ wallet.unlock_account(account=ALICE_ADDRESS, password=password) # This is Alice's PRE payment method. pre_payment_method = SubscriptionManagerPayment( - network=L2_NETWORK, eth_provider=L2_PROVIDER + network=TACO_NETWORK, blockchain_endpoint=L2_PROVIDER ) # This is Alicia. alicia = Alice( checksum_address=ALICE_ADDRESS, signer=wallet, - domain=L1_NETWORK, + domain=TACO_NETWORK, eth_endpoint=L1_PROVIDER, + polygon_endpoint=L2_PROVIDER, pre_payment_method=pre_payment_method, ) diff --git a/examples/pre/heartbeat_demo/doctor.py b/examples/pre/heartbeat_demo/doctor.py index df93f633b..c2594d6c5 100644 --- a/examples/pre/heartbeat_demo/doctor.py +++ b/examples/pre/heartbeat_demo/doctor.py @@ -27,7 +27,7 @@ except KeyError: raise RuntimeError("Missing environment variables to run demo.") -L1_NETWORK = "lynx" +TACO_NETWORK = "lynx" # To create a Bob, we need the doctor's private keys previously generated. from doctor_keys import get_doctor_privkeys # noqa: E402 @@ -43,7 +43,7 @@ power_ups = [enc_power, sig_power] print("Creating the Doctor ...") doctor = Bob( - domain=L1_NETWORK, + domain=TACO_NETWORK, crypto_power_ups=power_ups, eth_endpoint=L1_PROVIDER, ) diff --git a/examples/pre/heartbeat_demo/heartbeat_demo.md b/examples/pre/heartbeat_demo/heartbeat_demo.md index fcebf9a5b..ffb5f6eaf 100644 --- a/examples/pre/heartbeat_demo/heartbeat_demo.md +++ b/examples/pre/heartbeat_demo/heartbeat_demo.md @@ -47,8 +47,7 @@ and adding your provider and wallet details. To set the variables in your curre Optionally, you can change the network the demo is running on by changing the value of `L1_NETWORK` and `L2_NETWORK`. If you change these values be sure to also change `L1_PROVIDER_URI` and `L2_PROVIDER_URI` accordingly. -Available options for `L1_NETOWRK` are `tapir` or `mainnet`. -Available options for `L2_NETWORK` are `mumbai` or `polygon` +Available options for `TACO_NETWORK` are `lynx`, `tapir` or `mainnet`. Ensure Alice's account has a bit of MATIC on polygon to pay for the policy. From 1d8c05bb33ec04c45a08c8844707ba053bdcb63b Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 12:12:44 -0400 Subject: [PATCH 20/63] Update grant availability script to use taco network philosophy and no longer specify l2 network since it is now implied. --- tests/metrics/grant_availability.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/metrics/grant_availability.py b/tests/metrics/grant_availability.py index 0343b467c..f501b493a 100755 --- a/tests/metrics/grant_availability.py +++ b/tests/metrics/grant_availability.py @@ -22,6 +22,7 @@ from nucypher_core.umbral import SecretKey from web3 import Web3 from web3.types import Wei +from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.signers import Signer from nucypher.characters.lawful import Alice, Bob, Ursula from nucypher.config.characters import AliceConfiguration @@ -53,9 +54,9 @@ except KeyError: raise RuntimeError(message) # Alice Configuration -DOMAIN: str = 'mainnet' # tapir +TACO_NETWORK: str = NetworksInventory.LYNX.name # mainnet DEFAULT_SEEDNODE_URIS: List[str] = [ - *TEACHER_NODES[DOMAIN], + *TEACHER_NODES[TACO_NETWORK], ] INSECURE_PASSWORD: str = "METRICS_INSECURE_DEVELOPMENT_PASSWORD" TEMP_ALICE_DIR: Path = Path('/', 'tmp', 'grant-metrics') @@ -154,8 +155,7 @@ def make_alice(known_nodes: Optional[Set[Ursula]] = None): # This is Alice's PRE payment method. pre_payment_method = SubscriptionManagerPayment( - network='polygon', - eth_provider=POLYGON_PROVIDER_URI + network=TACO_NETWORK, blockchain_endpoint=POLYGON_PROVIDER_URI ) wallet = Signer.from_signer_uri(f'keystore://{SIGNER_URI}') @@ -163,10 +163,11 @@ def make_alice(known_nodes: Optional[Set[Ursula]] = None): alice_config = AliceConfiguration( eth_endpoint=ETHEREUM_PROVIDER_URI, + polygon_endpoint=POLYGON_PROVIDER_URI, checksum_address=ALICE_ADDRESS, signer_uri=f'keystore://{SIGNER_URI}', config_root=TEMP_ALICE_DIR, - domain=DOMAIN, + domain=TACO_NETWORK, known_nodes=known_nodes, start_learning_now=False, learn_on_same_thread=True, From 45f00c20db35d14a55d9344d2dd78d2448023885 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 12:43:33 -0400 Subject: [PATCH 21/63] Rename members in ChainInfo to avoid smurfing. --- nucypher/blockchain/eth/actors.py | 2 +- nucypher/blockchain/eth/networks.py | 14 +++----------- nucypher/config/characters.py | 4 ++-- .../config/migrations/configuration_v5_to_v6.py | 4 ++-- scripts/hooks/nucypher_dkg.py | 2 +- 5 files changed, 9 insertions(+), 17 deletions(-) diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index 609628b19..f7681908e 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -211,7 +211,7 @@ class Operator(BaseActor): # TODO: registry usage (and subsequently "network") is inconsistent here registry = ContractRegistry.from_latest_publication( - network=self.network + domain=self.network ) self.child_application_agent = ContractAgency.get_agent( TACoChildApplicationAgent, diff --git a/nucypher/blockchain/eth/networks.py b/nucypher/blockchain/eth/networks.py index b0bcca880..8145e456c 100644 --- a/nucypher/blockchain/eth/networks.py +++ b/nucypher/blockchain/eth/networks.py @@ -5,27 +5,20 @@ from nucypher.config.constants import TEMPORARY_DOMAIN class ChainInfo(NamedTuple): - chain_id: int - chain_name: str - - # Override eventual Enum name. TODO: better way? - @property - def name(self) -> str: - return self.chain_name + id: int + name: str class EthNetwork(ChainInfo, Enum): MAINNET = ChainInfo(1, "mainnet") GOERLI = ChainInfo(5, "goerli") SEPOLIA = ChainInfo(11155111, "sepolia") - # testing TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) class PolyNetwork(ChainInfo, Enum): POLYGON = ChainInfo(137, "polygon") MUMBAI = ChainInfo(80001, "mumbai") - # testing TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) @@ -40,7 +33,6 @@ class TACoNetwork(NamedTuple): class UnrecognizedNetwork(RuntimeError): """Raised when a provided network name is not recognized.""" - pass class NetworksInventory: @@ -65,7 +57,7 @@ class NetworksInventory: SUPPORTED_NETWORK_NAMES = [network.name for network in SUPPORTED_NETWORKS] # TODO not needed once merged with registry changes - POLY_NETWORKS = [network.poly_network.chain_name for network in SUPPORTED_NETWORKS] + POLY_NETWORKS = [network.poly_network.name for network in SUPPORTED_NETWORKS] DEFAULT_NETWORK_NAME: str = MAINNET.name diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index f0e489bac..935def773 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -73,7 +73,7 @@ class UrsulaConfiguration(CharacterConfiguration): taco_network = NetworksInventory.get_network(self.domain) # Polygon - polygon_chain_id = taco_network.poly_network.chain_id + polygon_chain_id = taco_network.poly_network.id polygon_provider_uris = self.condition_provider_uris.get(polygon_chain_id, []) if not polygon_provider_uris: self.condition_provider_uris[polygon_chain_id] = polygon_provider_uris @@ -82,7 +82,7 @@ class UrsulaConfiguration(CharacterConfiguration): polygon_provider_uris.append(self.polygon_endpoint) # Ethereum - staking_chain_id = taco_network.eth_network.chain_id + staking_chain_id = taco_network.eth_network.id staking_provider_uris = self.condition_provider_uris.get(staking_chain_id, []) if not staking_provider_uris: self.condition_provider_uris[staking_chain_id] = staking_provider_uris diff --git a/nucypher/config/migrations/configuration_v5_to_v6.py b/nucypher/config/migrations/configuration_v5_to_v6.py index 9ee0c2321..5f5fbb426 100644 --- a/nucypher/config/migrations/configuration_v5_to_v6.py +++ b/nucypher/config/migrations/configuration_v5_to_v6.py @@ -7,9 +7,9 @@ from nucypher.config.migrations.common import perform_migration def __migration(config: Dict) -> Dict: taco_network = NetworksInventory.get_network(config["domain"]) eth_provider = config["eth_provider_uri"] - eth_chain_id = taco_network.eth_network.chain_id + eth_chain_id = taco_network.eth_network.id polygon_provider = config["payment_provider"] - polygon_chain_id = taco_network.poly_network.chain_id + polygon_chain_id = taco_network.poly_network.id if "condition_provider_uris" in config: return config config["condition_provider_uris"] = { diff --git a/scripts/hooks/nucypher_dkg.py b/scripts/hooks/nucypher_dkg.py index cd6b9f24d..f088a924e 100644 --- a/scripts/hooks/nucypher_dkg.py +++ b/scripts/hooks/nucypher_dkg.py @@ -193,7 +193,7 @@ def nucypher_dkg( emitter.echo("--------- Initiating Ritual ---------", color="yellow") emitter.echo( - f"Commencing DKG Ritual(s) on {taco_network.poly_network.chain_name} using {account_address}", + f"Commencing DKG Ritual(s) on {taco_network.poly_network.name} using {account_address}", color="green", ) From fa4051d504a2728066c7331742e97ea6eb07bd22 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 12:51:38 -0400 Subject: [PATCH 22/63] Rename Eth/PolyNetwork to Eth/PolyChain to better reflect their usage. --- nucypher/blockchain/eth/networks.py | 22 +++++++++---------- nucypher/config/characters.py | 4 ++-- .../migrations/configuration_v5_to_v6.py | 4 ++-- scripts/hooks/nucypher_dkg.py | 2 +- tests/acceptance/conftest.py | 6 ++--- tests/conftest.py | 6 ++--- tests/integration/conftest.py | 6 ++--- tests/utils/registry.py | 9 ++++++-- 8 files changed, 32 insertions(+), 27 deletions(-) diff --git a/nucypher/blockchain/eth/networks.py b/nucypher/blockchain/eth/networks.py index 8145e456c..21164a7fb 100644 --- a/nucypher/blockchain/eth/networks.py +++ b/nucypher/blockchain/eth/networks.py @@ -9,14 +9,14 @@ class ChainInfo(NamedTuple): name: str -class EthNetwork(ChainInfo, Enum): +class EthChain(ChainInfo, Enum): MAINNET = ChainInfo(1, "mainnet") GOERLI = ChainInfo(5, "goerli") SEPOLIA = ChainInfo(11155111, "sepolia") TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) -class PolyNetwork(ChainInfo, Enum): +class PolygonChain(ChainInfo, Enum): POLYGON = ChainInfo(137, "polygon") MUMBAI = ChainInfo(80001, "mumbai") TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) @@ -24,11 +24,11 @@ class PolyNetwork(ChainInfo, Enum): class TACoNetwork(NamedTuple): name: str - eth_network: EthNetwork - poly_network: PolyNetwork + eth_chain: EthChain + polygon_chain: PolygonChain def is_testnet(self) -> bool: - return self.eth_network != EthNetwork.MAINNET + return self.eth_chain != EthChain.MAINNET class UnrecognizedNetwork(RuntimeError): @@ -36,14 +36,14 @@ class UnrecognizedNetwork(RuntimeError): class NetworksInventory: - MAINNET = TACoNetwork("mainnet", EthNetwork.MAINNET, PolyNetwork.POLYGON) + MAINNET = TACoNetwork("mainnet", EthChain.MAINNET, PolygonChain.POLYGON) # Testnets - ORYX = TACoNetwork("oryx", EthNetwork.GOERLI, PolyNetwork.POLYGON) - LYNX = TACoNetwork("lynx", EthNetwork.GOERLI, PolyNetwork.MUMBAI) - TAPIR = TACoNetwork("tapir", EthNetwork.SEPOLIA, PolyNetwork.MUMBAI) + ORYX = TACoNetwork("oryx", EthChain.GOERLI, PolygonChain.POLYGON) + LYNX = TACoNetwork("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) + TAPIR = TACoNetwork("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) # TODO did Ibex even use a PolyNetwork? IBEX = TACoNetwork( - "ibex", EthNetwork.GOERLI, PolyNetwork.MUMBAI + "ibex", EthChain.GOERLI, PolygonChain.MUMBAI ) # this is required for configuration file migrations (backwards compatibility) SUPPORTED_NETWORKS = [ @@ -57,7 +57,7 @@ class NetworksInventory: SUPPORTED_NETWORK_NAMES = [network.name for network in SUPPORTED_NETWORKS] # TODO not needed once merged with registry changes - POLY_NETWORKS = [network.poly_network.name for network in SUPPORTED_NETWORKS] + POLYGON_CHAINS = [network.polygon_chain.name for network in SUPPORTED_NETWORKS] DEFAULT_NETWORK_NAME: str = MAINNET.name diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index 935def773..904bfc797 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -73,7 +73,7 @@ class UrsulaConfiguration(CharacterConfiguration): taco_network = NetworksInventory.get_network(self.domain) # Polygon - polygon_chain_id = taco_network.poly_network.id + polygon_chain_id = taco_network.polygon_chain.id polygon_provider_uris = self.condition_provider_uris.get(polygon_chain_id, []) if not polygon_provider_uris: self.condition_provider_uris[polygon_chain_id] = polygon_provider_uris @@ -82,7 +82,7 @@ class UrsulaConfiguration(CharacterConfiguration): polygon_provider_uris.append(self.polygon_endpoint) # Ethereum - staking_chain_id = taco_network.eth_network.id + staking_chain_id = taco_network.eth_chain.id staking_provider_uris = self.condition_provider_uris.get(staking_chain_id, []) if not staking_provider_uris: self.condition_provider_uris[staking_chain_id] = staking_provider_uris diff --git a/nucypher/config/migrations/configuration_v5_to_v6.py b/nucypher/config/migrations/configuration_v5_to_v6.py index 5f5fbb426..61ef2b568 100644 --- a/nucypher/config/migrations/configuration_v5_to_v6.py +++ b/nucypher/config/migrations/configuration_v5_to_v6.py @@ -7,9 +7,9 @@ from nucypher.config.migrations.common import perform_migration def __migration(config: Dict) -> Dict: taco_network = NetworksInventory.get_network(config["domain"]) eth_provider = config["eth_provider_uri"] - eth_chain_id = taco_network.eth_network.id + eth_chain_id = taco_network.eth_chain.id polygon_provider = config["payment_provider"] - polygon_chain_id = taco_network.poly_network.id + polygon_chain_id = taco_network.polygon_chain.id if "condition_provider_uris" in config: return config config["condition_provider_uris"] = { diff --git a/scripts/hooks/nucypher_dkg.py b/scripts/hooks/nucypher_dkg.py index f088a924e..f9fcc3589 100644 --- a/scripts/hooks/nucypher_dkg.py +++ b/scripts/hooks/nucypher_dkg.py @@ -193,7 +193,7 @@ def nucypher_dkg( emitter.echo("--------- Initiating Ritual ---------", color="yellow") emitter.echo( - f"Commencing DKG Ritual(s) on {taco_network.poly_network.name} using {account_address}", + f"Commencing DKG Ritual(s) on {taco_network.polygon_chain.name} using {account_address}", color="green", ) diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index 7405af85e..c8d4e4e71 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -13,9 +13,9 @@ from nucypher.blockchain.eth.agents import ( ) from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.networks import ( - EthNetwork, + EthChain, NetworksInventory, - PolyNetwork, + PolygonChain, TACoNetwork, ) from nucypher.blockchain.eth.registry import ContractRegistry, RegistrySourceManager @@ -440,7 +440,7 @@ def mock_condition_blockchains(session_mocker): ) testing_network = TACoNetwork( - TEMPORARY_DOMAIN, EthNetwork.TESTERCHAIN, PolyNetwork.TESTERCHAIN + TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) session_mocker.patch.object( diff --git a/tests/conftest.py b/tests/conftest.py index fa4be4f7d..d7b832df6 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,9 +5,9 @@ from eth_utils.crypto import keccak from nucypher.blockchain.eth.actors import Operator from nucypher.blockchain.eth.networks import ( - EthNetwork, + EthChain, NetworksInventory, - PolyNetwork, + PolygonChain, TACoNetwork, ) from nucypher.config.constants import TEMPORARY_DOMAIN @@ -148,7 +148,7 @@ def mock_condition_blockchains(session_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) testing_network = TACoNetwork( - TEMPORARY_DOMAIN, EthNetwork.TESTERCHAIN, PolyNetwork.TESTERCHAIN + TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) session_mocker.patch.object( diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 399946c2f..acb894ee6 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -19,9 +19,9 @@ from nucypher.blockchain.eth.interfaces import ( BlockchainInterfaceFactory, ) from nucypher.blockchain.eth.networks import ( - EthNetwork, + EthChain, NetworksInventory, - PolyNetwork, + PolygonChain, TACoNetwork, ) from nucypher.blockchain.eth.registry import ( @@ -292,7 +292,7 @@ def mock_condition_blockchains(session_mocker): ) testing_network = TACoNetwork( - TEMPORARY_DOMAIN, EthNetwork.TESTERCHAIN, PolyNetwork.TESTERCHAIN + TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) session_mocker.patch.object( diff --git a/tests/utils/registry.py b/tests/utils/registry.py index 91dd1d464..3c170e0c4 100644 --- a/tests/utils/registry.py +++ b/tests/utils/registry.py @@ -5,7 +5,12 @@ from typing import List from ape.contracts import ContractInstance from eth_utils import to_checksum_address -from nucypher.blockchain.eth.networks import EthNetwork, NetworksInventory, PolyNetwork, TACoNetwork +from nucypher.blockchain.eth.networks import ( + EthChain, + NetworksInventory, + PolygonChain, + TACoNetwork, +) from nucypher.blockchain.eth.registry import ( RegistryData, RegistrySource, @@ -24,7 +29,7 @@ def mock_registry_sources(): # set the mock values NetworksInventory.SUPPORTED_NETWORK_NAMES = [TEMPORARY_DOMAIN] testing_network = TACoNetwork( - TEMPORARY_DOMAIN, EthNetwork.TESTERCHAIN, PolyNetwork.TESTERCHAIN + TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) NetworksInventory.SUPPORTED_NETWORKS = [testing_network] RegistrySourceManager._FALLBACK_CHAIN = (MockRegistrySource,) From 8fcf422728ceb700f11d9d0a3b6dbea47aab7e4b Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 13:06:58 -0400 Subject: [PATCH 23/63] During Ursula interactive configuration, don't show NU balance since is/will be no longer applicable to Threshold Network. Show MATIC balance instead of ETH. --- nucypher/cli/actions/select.py | 49 +++++++-------- nucypher/cli/commands/ursula.py | 2 +- nucypher/cli/literature.py | 2 +- .../cli/actions/test_select_client_account.py | 60 ++++++++----------- 4 files changed, 49 insertions(+), 64 deletions(-) diff --git a/nucypher/cli/actions/select.py b/nucypher/cli/actions/select.py index 0692ea8a9..44f5e2d07 100644 --- a/nucypher/cli/actions/select.py +++ b/nucypher/cli/actions/select.py @@ -6,21 +6,19 @@ import click from tabulate import tabulate from web3.main import Web3 -from nucypher.blockchain.eth.agents import ContractAgency, NucypherTokenAgent from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ( ContractRegistry, ) from nucypher.blockchain.eth.signers.base import Signer -from nucypher.blockchain.eth.token import NU from nucypher.cli.actions.configure import get_config_filepaths from nucypher.cli.literature import ( DEFAULT_TO_LONE_CONFIG_FILE, GENERIC_SELECT_ACCOUNT, IGNORE_OLD_CONFIGURATION, + NO_ACCOUNTS, NO_CONFIGURATIONS_ON_DISK, - NO_ETH_ACCOUNTS, SELECT_NETWORK, SELECTED_ACCOUNT, ) @@ -34,49 +32,50 @@ from nucypher.utilities.emitters import StdoutEmitter def select_client_account( emitter, - eth_endpoint: str = None, + polygon_endpoint: str = None, signer: Signer = None, signer_uri: str = None, prompt: str = None, default: int = 0, registry: ContractRegistry = None, - show_eth_balance: bool = False, - show_nu_balance: bool = False, + show_matic_balance: bool = False, show_staking: bool = False, network: str = None, poa: bool = None, ) -> str: """ - Interactively select an ethereum wallet account from a table of nucypher account metadata. + Interactively select an ethereum wallet account from a table of account metadata. - Note: Showing ETH and/or NU balances, causes an eager blockchain connection. + Note: Showing MATIC balance causes an eager blockchain connection. """ if signer and signer_uri: raise ValueError('Pass either signer or signer_uri but not both.') - if not any((eth_endpoint, signer_uri, signer)): + if not any((polygon_endpoint, signer_uri, signer)): raise ValueError("At least a provider URI, signer URI or signer must be provided to select an account") - if eth_endpoint: + if polygon_endpoint: # Connect to the blockchain in order to select an account if not BlockchainInterfaceFactory.is_interface_initialized( - eth_provider_uri=eth_endpoint + eth_provider_uri=polygon_endpoint ): BlockchainInterfaceFactory.initialize_interface( - eth_provider_uri=eth_endpoint, poa=poa, emitter=emitter + eth_provider_uri=polygon_endpoint, poa=poa, emitter=emitter ) if not signer_uri: - signer_uri = eth_endpoint + signer_uri = polygon_endpoint - blockchain = BlockchainInterfaceFactory.get_interface(eth_provider_uri=eth_endpoint) + blockchain = BlockchainInterfaceFactory.get_interface( + eth_provider_uri=polygon_endpoint + ) if signer_uri and not signer: testnet = network != NetworksInventory.MAINNET.name signer = Signer.from_signer_uri(signer_uri, testnet=testnet) # Display accounts info - if show_nu_balance or show_staking: # Lazy registry fetching + if show_staking: # Lazy registry fetching if not registry: if not network: raise ValueError("Pass network name or registry; Got neither.") @@ -84,7 +83,7 @@ def select_client_account( enumerated_accounts = dict(enumerate(signer.accounts)) if len(enumerated_accounts) < 1: - emitter.echo(NO_ETH_ACCOUNTS, color='red', bold=True) + emitter.echo(NO_ACCOUNTS, color="red", bold=True) raise click.Abort() elif len(enumerated_accounts) == 1: # There are no choices if there is only one available address. @@ -92,23 +91,17 @@ def select_client_account( # Display account info headers = ['Account'] - if show_eth_balance: - headers.append('ETH') - if show_nu_balance: - headers.append('NU') + if show_matic_balance: + headers.append("MATIC") rows = list() for index, account in enumerated_accounts.items(): row = [account] - if show_eth_balance: - ether_balance = Web3.from_wei(blockchain.client.get_balance(account), 'ether') - row.append(f'{ether_balance} ETH') - if show_nu_balance: - token_agent = ContractAgency.get_agent( - NucypherTokenAgent, registry=registry, provider_uri=eth_endpoint + if show_matic_balance: + matic_balance = Web3.from_wei( + blockchain.client.get_balance(account), "ether" ) - token_balance = NU.from_units(token_agent.get_balance(account, registry)) - row.append(token_balance) + row.append(f"{matic_balance} MATIC") rows.append(row) emitter.echo(tabulate(rows, headers=headers, showindex='always')) diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index fbf0c1a2e..7dd14c883 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -170,7 +170,7 @@ class UrsulaConfigOptions: self.operator_address = select_client_account( emitter=emitter, prompt=prompt, - eth_endpoint=self.eth_endpoint, + polygon_endpoint=self.polygon_endpoint, signer_uri=self.signer_uri, ) diff --git a/nucypher/cli/literature.py b/nucypher/cli/literature.py index 987fc17f6..5cc3b4037 100644 --- a/nucypher/cli/literature.py +++ b/nucypher/cli/literature.py @@ -53,7 +53,7 @@ INVALID_JSON_IN_CONFIGURATION_WARNING = "Invalid JSON in Configuration File at { INVALID_CONFIGURATION_FILE_WARNING = "Invalid Configuration at {filepath}." -NO_ETH_ACCOUNTS = "No ETH accounts were found." +NO_ACCOUNTS = "No accounts were found." GENERIC_SELECT_ACCOUNT = "Select index of account" diff --git a/tests/integration/cli/actions/test_select_client_account.py b/tests/integration/cli/actions/test_select_client_account.py index 1f0a81624..9e1fdb452 100644 --- a/tests/integration/cli/actions/test_select_client_account.py +++ b/tests/integration/cli/actions/test_select_client_account.py @@ -12,9 +12,8 @@ from nucypher.blockchain.eth.clients import EthereumClient from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.signers import KeystoreSigner from nucypher.blockchain.eth.signers.software import Web3Signer -from nucypher.blockchain.eth.token import NU from nucypher.cli.actions.select import select_client_account -from nucypher.cli.literature import GENERIC_SELECT_ACCOUNT, NO_ETH_ACCOUNTS +from nucypher.cli.literature import GENERIC_SELECT_ACCOUNT, NO_ACCOUNTS from nucypher.config.constants import TEMPORARY_DOMAIN from tests.constants import ( MOCK_ETH_PROVIDER_URI, @@ -33,7 +32,7 @@ def test_select_client_account( selected_account = select_client_account( emitter=test_emitter, signer=Web3Signer(testerchain.client), - eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, ) assert selected_account, "Account selection returned Falsy instead of an address" assert isinstance(selected_account, str), "Selection is not a str" @@ -56,10 +55,10 @@ def test_select_client_account_with_no_accounts( select_client_account( emitter=test_emitter, signer=Web3Signer(testerchain.client), - eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, ) captured = capsys.readouterr() - assert NO_ETH_ACCOUNTS in captured.out + assert NO_ACCOUNTS in captured.out def test_select_client_account_ambiguous_source( @@ -121,7 +120,7 @@ def test_select_client_account_valid_sources( mock_stdin.line(str(selection)) expected_account = testerchain.client.accounts[selection] selected_account = select_client_account( - emitter=test_emitter, eth_endpoint=MOCK_ETH_PROVIDER_URI + emitter=test_emitter, polygon_endpoint=MOCK_ETH_PROVIDER_URI ) assert selected_account == expected_account assert mock_stdin.empty() @@ -138,7 +137,7 @@ def test_select_client_account_valid_sources( BlockchainInterfaceFactory, "get_interface", return_value=testerchain ) selected_account = select_client_account( - emitter=test_emitter, eth_endpoint=MOCK_ETH_PROVIDER_URI + emitter=test_emitter, polygon_endpoint=MOCK_ETH_PROVIDER_URI ) assert selected_account == expected_account assert mock_stdin.empty() @@ -146,15 +145,17 @@ def test_select_client_account_valid_sources( assert GENERIC_SELECT_ACCOUNT in captured.out and f"Selected {selection}" in captured.out -@pytest.mark.skip('fix me') -@pytest.mark.parametrize('selection,show_staking,show_eth,show_tokens,stake_info', ( - (0, True, True, True, []), - (1, True, True, True, []), - (5, True, True, True, []), - (NUMBER_OF_ETH_TEST_ACCOUNTS-1, True, True, True, []), - (0, False, True, True, []), - (0, False, False, True, []), - (0, False, False, False, []), +@pytest.mark.skip("fix me") +@pytest.mark.parametrize( + "selection,show_staking,show_matic,stake_info", + ( + (0, True, True, []), + (1, True, True, []), + (5, True, True, []), + (NUMBER_OF_ETH_TEST_ACCOUNTS - 1, True, True, []), + (0, False, True, []), + (0, False, False, []), + (0, False, False, []), ), ) def test_select_client_account_with_balance_display( @@ -166,8 +167,7 @@ def test_select_client_account_with_balance_display( mock_token_agent, selection, show_staking, - show_eth, - show_tokens, + show_matic, stake_info, ): @@ -175,17 +175,16 @@ def test_select_client_account_with_balance_display( mock_staking_agent.get_all_stakes.return_value = stake_info # Missing network kwarg with balance display active - blockchain_read_required = any((show_staking, show_eth, show_tokens)) + blockchain_read_required = any((show_staking, show_matic)) if blockchain_read_required: with pytest.raises( ValueError, match="Pass network name or registry; Got neither." ): select_client_account( emitter=test_emitter, - show_eth_balance=show_eth, - show_nu_balance=show_tokens, + show_matic_balance=show_matic, show_staking=show_staking, - eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, ) # Good selection @@ -193,10 +192,9 @@ def test_select_client_account_with_balance_display( selected_account = select_client_account( emitter=test_emitter, network=TEMPORARY_DOMAIN, - show_eth_balance=show_eth, - show_nu_balance=show_tokens, + show_matic_balance=show_matic, show_staking=show_staking, - eth_endpoint=MOCK_ETH_PROVIDER_URI, + polygon_endpoint=MOCK_ETH_PROVIDER_URI, ) # check for accurate selection consistency with client index @@ -207,10 +205,8 @@ def test_select_client_account_with_balance_display( headers = ['Account'] if show_staking: headers.append('Staking') - if show_eth: - headers.append('ETH') - if show_tokens: - headers.append('NU') + if show_matic: + headers.append("MATIC") captured = capsys.readouterr() for column_name in headers: @@ -219,11 +215,7 @@ def test_select_client_account_with_balance_display( for account in testerchain.client.accounts: assert account in captured.out - if show_tokens: - balance = mock_token_agent.get_balance(address=account) - assert str(NU.from_units(balance)) in captured.out - - if show_eth: + if show_matic: balance = testerchain.client.get_balance(account=account) assert str(Web3.from_wei(balance, 'ether')) in captured.out From 941b21f34f9af32e21bd73b63806a310f6a45a32 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 13:46:29 -0400 Subject: [PATCH 24/63] More renames of instances of eth_provider_uri to either blockchain_endpoint or eth_endpoint. --- .../finnegans-wake-demo-l2.py | 6 +- examples/pre/heartbeat_demo/alicia.py | 8 +- nucypher/blockchain/eth/agents.py | 18 +- nucypher/blockchain/eth/interfaces.py | 185 +++++++++++------- nucypher/blockchain/eth/providers.py | 30 +-- nucypher/blockchain/eth/signers/software.py | 4 +- nucypher/characters/base.py | 2 +- nucypher/characters/lawful.py | 8 +- nucypher/characters/unlawful.py | 6 +- nucypher/cli/actions/select.py | 6 +- nucypher/cli/painting/transactions.py | 16 +- nucypher/cli/utils.py | 25 ++- nucypher/config/base.py | 8 +- nucypher/network/middleware.py | 16 +- nucypher/network/nodes.py | 2 +- nucypher/utilities/ethereum.py | 16 +- nucypher/utilities/networking.py | 4 +- nucypher/utilities/prometheus/collector.py | 15 +- nucypher/utilities/prometheus/metrics.py | 4 +- tests/acceptance/characters/test_operator.py | 4 +- tests/acceptance/conftest.py | 2 +- tests/acceptance/test_testerchain.py | 6 +- tests/fixtures.py | 8 +- .../characters/test_bob_handles_frags.py | 4 +- .../test_bob_joins_policy_and_retrieves.py | 2 +- ...ursula_local_keystore_cli_functionality.py | 4 +- .../config/test_configuration_persistence.py | 8 +- .../learning/test_firstula_circumstances.py | 2 +- .../integration/network/test_failure_modes.py | 8 +- .../network/test_network_actors.py | 2 +- .../utilities/test_prometheus_collectors.py | 4 +- tests/unit/test_web3_clients.py | 110 +++++++---- tests/utils/blockchain.py | 29 +-- tests/utils/config.py | 2 +- tests/utils/middleware.py | 4 +- 35 files changed, 333 insertions(+), 245 deletions(-) diff --git a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py index 584079c38..8e913c36a 100644 --- a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py +++ b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py @@ -66,9 +66,9 @@ encrypting_key = bob.public_keys(DecryptingPower) ###################################### # Connect to the ethereum provider. -connect_web3_provider(eth_provider_uri=L1_PROVIDER) +connect_web3_provider(blockchain_endpoint=L1_PROVIDER) # Connect to the layer 2 provider. -connect_web3_provider(eth_provider_uri=L2_PROVIDER) +connect_web3_provider(blockchain_endpoint=L2_PROVIDER) # Setup and unlock alice's ethereum wallet. # WARNING: Never give your mainnet password or mnemonic phrase to anyone. @@ -111,7 +111,7 @@ policy_public_key = alice.get_policy_encrypting_key_from_label(label) remote_bob = Bob.from_public_keys( encrypting_key=encrypting_key, verifying_key=verifying_key, - eth_provider_uri=L1_PROVIDER, + eth_endpoint=L1_PROVIDER, ) # These are the policy details. diff --git a/examples/pre/heartbeat_demo/alicia.py b/examples/pre/heartbeat_demo/alicia.py index 93b836886..8156751b8 100644 --- a/examples/pre/heartbeat_demo/alicia.py +++ b/examples/pre/heartbeat_demo/alicia.py @@ -64,8 +64,12 @@ TACO_NETWORK = "lynx" # Alicia, the Authority of the Policy # ####################################### -connect_web3_provider(eth_provider_uri=L1_PROVIDER) # Connect to the ethereum provider. -connect_web3_provider(eth_provider_uri=L2_PROVIDER) # Connect to the layer 2 provider. +connect_web3_provider( + blockchain_endpoint=L1_PROVIDER +) # Connect to the ethereum provider. +connect_web3_provider( + blockchain_endpoint=L2_PROVIDER +) # Connect to the layer 2 provider. # Setup and unlock alice's ethereum wallet. diff --git a/nucypher/blockchain/eth/agents.py b/nucypher/blockchain/eth/agents.py index 948e1539e..78ad39a22 100644 --- a/nucypher/blockchain/eth/agents.py +++ b/nucypher/blockchain/eth/agents.py @@ -91,7 +91,7 @@ class EthereumContractAgent: self.registry = registry self.blockchain = BlockchainInterfaceFactory.get_or_create_interface( - eth_provider_uri=provider_uri + blockchain_endpoint=provider_uri ) if not contract: # Fetch the contract @@ -106,12 +106,14 @@ class EthereumContractAgent: transaction_gas = EthereumContractAgent.DEFAULT_TRANSACTION_GAS_LIMITS['default'] self.transaction_gas = transaction_gas - self.log.info("Initialized new {} for {} with {} and {}".format( - self.__class__.__name__, - self.contract.address, - self.blockchain.eth_provider_uri, - str(self.registry) - )) + self.log.info( + "Initialized new {} for {} with {} and {}".format( + self.__class__.__name__, + self.contract.address, + self.blockchain.blockchain_endpoint, + str(self.registry), + ) + ) def __repr__(self) -> str: class_name = self.__class__.__name__ @@ -853,7 +855,7 @@ class ContractAgency: if not provider_uri: raise ValueError( - "Need to specify an Ethereum provider URI in order to get an agent from the ContractAgency" + "Need to specify a blockchain provider URI in order to get an agent from the ContractAgency" ) if not registry: diff --git a/nucypher/blockchain/eth/interfaces.py b/nucypher/blockchain/eth/interfaces.py index 84fc9715a..5875469a7 100644 --- a/nucypher/blockchain/eth/interfaces.py +++ b/nucypher/blockchain/eth/interfaces.py @@ -6,7 +6,7 @@ from urllib.parse import urlparse import requests from constant_sorrow.constants import ( - INSUFFICIENT_ETH, + INSUFFICIENT_FUNDS, NO_BLOCKCHAIN_CONNECTION, UNKNOWN_TX_STATUS, ) @@ -82,7 +82,7 @@ class BlockchainInterface: pass REASONS = { - INSUFFICIENT_ETH: 'insufficient funds for gas * price + value', + INSUFFICIENT_FUNDS: "insufficient funds for gas * price + value", } class TransactionFailed(InterfaceError): @@ -100,7 +100,7 @@ class BlockchainInterface: self.payload = transaction_dict self.contract_function = contract_function self.failures = { - BlockchainInterface.REASONS[INSUFFICIENT_ETH]: self.insufficient_eth + BlockchainInterface.REASONS[INSUFFICIENT_FUNDS]: self.insufficient_funds } self.message = self.failures.get(self.base_message, self.default) super().__init__(self.message, *args) @@ -120,7 +120,7 @@ class BlockchainInterface: return balance @property - def insufficient_eth(self) -> str: + def insufficient_funds(self) -> str: try: transaction_fee = self.payload['gas'] * self.payload['gasPrice'] except KeyError: @@ -132,15 +132,16 @@ class BlockchainInterface: f'but sender only has {prettify_eth_amount(self.get_balance())}.' return message - def __init__(self, - emitter=None, # TODO # 1754 - poa: bool = None, - light: bool = False, - eth_provider_uri: str = NO_BLOCKCHAIN_CONNECTION, - eth_provider: BaseProvider = NO_BLOCKCHAIN_CONNECTION, - gas_strategy: Optional[Union[str, Callable]] = None, - max_gas_price: Optional[int] = None): - + def __init__( + self, + emitter=None, # TODO # 1754 + poa: bool = None, + light: bool = False, + blockchain_endpoint: str = NO_BLOCKCHAIN_CONNECTION, + blockchain_provider: BaseProvider = NO_BLOCKCHAIN_CONNECTION, + gas_strategy: Optional[Union[str, Callable]] = None, + max_gas_price: Optional[int] = None, + ): """ TODO: #1502 - Move to API docs. @@ -206,8 +207,8 @@ class BlockchainInterface: self.log = Logger('Blockchain') self.poa = poa - self.eth_provider_uri = eth_provider_uri - self._eth_provider = eth_provider + self.blockchain_endpoint = blockchain_endpoint + self._blockchain_provider = blockchain_provider self.w3 = NO_BLOCKCHAIN_CONNECTION self.client = NO_BLOCKCHAIN_CONNECTION self.is_light = light @@ -219,7 +220,9 @@ class BlockchainInterface: self.max_gas_price = max_gas_price def __repr__(self): - r = '{name}({uri})'.format(name=self.__class__.__name__, uri=self.eth_provider_uri) + r = "{name}({uri})".format( + name=self.__class__.__name__, uri=self.blockchain_endpoint + ) return r def get_blocktime(self): @@ -292,23 +295,30 @@ class BlockchainInterface: def connect(self): - eth_provider_uri = self.eth_provider_uri - self.log.info(f"Using external Web3 Provider '{self.eth_provider_uri}'") + blockchain_endpoint = self.blockchain_endpoint + self.log.info(f"Using external Web3 Provider '{self.blockchain_endpoint}'") # Attach Provider - self._attach_eth_provider(eth_provider=self._eth_provider, eth_provider_uri=eth_provider_uri) - self.log.info("Connecting to {}".format(self.eth_provider_uri)) - if self._eth_provider is NO_BLOCKCHAIN_CONNECTION: + self._attach_blockchain_provider( + blockchain_provider=self._blockchain_provider, + blockchain_endpoint=blockchain_endpoint, + ) + self.log.info("Connecting to {}".format(self.blockchain_endpoint)) + if self._blockchain_provider is NO_BLOCKCHAIN_CONNECTION: raise self.NoProvider("There are no configured blockchain providers") # Connect if not connected try: - self.w3 = self.Web3(provider=self._eth_provider) + self.w3 = self.Web3(provider=self._blockchain_provider) self.client = EthereumClient.from_w3(w3=self.w3) except requests.ConnectionError: # RPC - raise self.ConnectionFailed(f'Connection Failed - {str(self.eth_provider_uri)} - is RPC enabled?') - except FileNotFoundError: # IPC File Protocol - raise self.ConnectionFailed(f'Connection Failed - {str(self.eth_provider_uri)} - is IPC enabled?') + raise self.ConnectionFailed( + f"Connection Failed - {str(self.blockchain_endpoint)} - is RPC enabled?" + ) + except FileNotFoundError: # IPC File Protocol + raise self.ConnectionFailed( + f"Connection Failed - {str(self.blockchain_endpoint)} - is IPC enabled?" + ) else: self.attach_middleware() @@ -316,20 +326,22 @@ class BlockchainInterface: @property def provider(self) -> BaseProvider: - return self._eth_provider + return self._blockchain_provider - def _attach_eth_provider(self, - eth_provider: Optional[BaseProvider] = None, - eth_provider_uri: str = None) -> None: + def _attach_blockchain_provider( + self, + blockchain_provider: Optional[BaseProvider] = None, + blockchain_endpoint: str = None, + ) -> None: """ https://web3py.readthedocs.io/en/latest/providers.html#providers """ - if not eth_provider_uri and not eth_provider: + if not blockchain_endpoint and not blockchain_provider: raise self.NoProvider("No URI or provider instances supplied.") - if eth_provider_uri and not eth_provider: - uri_breakdown = urlparse(eth_provider_uri) + if blockchain_endpoint and not blockchain_provider: + uri_breakdown = urlparse(blockchain_endpoint) if uri_breakdown.scheme == 'tester': providers = { @@ -352,19 +364,27 @@ class BlockchainInterface: # auto-detect for file based ipc if not provider_scheme: - if Path(eth_provider_uri).is_file(): + if Path(blockchain_endpoint).is_file(): # file is available - assume ipc/file scheme - provider_scheme = 'file' - self.log.info(f"Auto-detected provider scheme as 'file://' for provider {eth_provider_uri}") + provider_scheme = "file" + self.log.info( + f"Auto-detected provider scheme as 'file://' for provider {blockchain_endpoint}" + ) try: - self._eth_provider = providers[provider_scheme](eth_provider_uri) + self._blockchain_provider = providers[provider_scheme]( + blockchain_endpoint + ) except KeyError: - raise self.UnsupportedProvider(f"{eth_provider_uri} is an invalid or unsupported blockchain provider URI") + raise self.UnsupportedProvider( + f"{blockchain_endpoint} is an invalid or unsupported blockchain provider URI" + ) else: - self.eth_provider_uri = eth_provider_uri or NO_BLOCKCHAIN_CONNECTION + self.blockchain_endpoint = ( + blockchain_endpoint or NO_BLOCKCHAIN_CONNECTION + ) else: - self._eth_provider = eth_provider + self._blockchain_provider = blockchain_provider @classmethod def _handle_failed_transaction(cls, @@ -689,11 +709,11 @@ class BlockchainInterfaceFactory: return cls._instance @classmethod - def is_interface_initialized(cls, eth_provider_uri: str) -> bool: + def is_interface_initialized(cls, blockchain_endpoint: str) -> bool: """ - Returns True if there is an existing connection with an equal eth_provider_uri. + Returns True if there is an existing connection with an equal blockchain_endpoint. """ - return bool(cls._interfaces.get(eth_provider_uri, False)) + return bool(cls._interfaces.get(blockchain_endpoint, False)) @classmethod def register_interface(cls, @@ -702,48 +722,59 @@ class BlockchainInterfaceFactory: force: bool = False ) -> None: - eth_provider_uri = interface.eth_provider_uri - if (eth_provider_uri in cls._interfaces) and not force: - raise cls.InterfaceAlreadyInitialized(f"A connection already exists for {eth_provider_uri}. " - "Use .get_interface instead.") + blockchain_endpoint = interface.blockchain_endpoint + if (blockchain_endpoint in cls._interfaces) and not force: + raise cls.InterfaceAlreadyInitialized( + f"A connection already exists for {blockchain_endpoint}. " + "Use .get_interface instead." + ) cached = cls.CachedInterface(interface=interface, emitter=emitter) - cls._interfaces[eth_provider_uri] = cached + cls._interfaces[blockchain_endpoint] = cached @classmethod - def initialize_interface(cls, - eth_provider_uri: str, - emitter=None, - interface_class: Interfaces = None, - *interface_args, - **interface_kwargs - ) -> None: - if not eth_provider_uri: + def initialize_interface( + cls, + blockchain_endpoint: str, + emitter=None, + interface_class: Interfaces = None, + *interface_args, + **interface_kwargs, + ) -> None: + if not blockchain_endpoint: # Prevent empty strings and Falsy - raise BlockchainInterface.UnsupportedProvider(f"'{eth_provider_uri}' is not a valid provider URI") + raise BlockchainInterface.UnsupportedProvider( + f"'{blockchain_endpoint}' is not a valid provider URI" + ) - if eth_provider_uri in cls._interfaces: - raise cls.InterfaceAlreadyInitialized(f"A connection already exists for {eth_provider_uri}. " - f"Use .get_interface instead.") + if blockchain_endpoint in cls._interfaces: + raise cls.InterfaceAlreadyInitialized( + f"A connection already exists for {blockchain_endpoint}. " + f"Use .get_interface instead." + ) # Interface does not exist, initialize a new one. if not interface_class: interface_class = cls._default_interface_class - interface = interface_class(eth_provider_uri=eth_provider_uri, - *interface_args, - **interface_kwargs) + interface = interface_class( + blockchain_endpoint=blockchain_endpoint, *interface_args, **interface_kwargs + ) interface.connect() - cls._interfaces[eth_provider_uri] = cls.CachedInterface(interface=interface, emitter=emitter) + cls._interfaces[blockchain_endpoint] = cls.CachedInterface( + interface=interface, emitter=emitter + ) @classmethod - def get_interface(cls, eth_provider_uri: str = None) -> Interfaces: + def get_interface(cls, blockchain_endpoint: str = None) -> Interfaces: # Try to get an existing cached interface. - if eth_provider_uri: + if blockchain_endpoint: try: - cached_interface = cls._interfaces[eth_provider_uri] + cached_interface = cls._interfaces[blockchain_endpoint] except KeyError: - raise cls.InterfaceNotInitialized(f"There is no connection for {eth_provider_uri}. " - f"Call .initialize_connection, then try again.") + raise cls.InterfaceNotInitialized( + f"There is no connection for {blockchain_endpoint}. " + f"Call .initialize_connection, then try again." + ) # Try to use the most recently created interface by default. else: @@ -761,14 +792,16 @@ class BlockchainInterfaceFactory: return interface @classmethod - def get_or_create_interface(cls, - eth_provider_uri: str, - *interface_args, - **interface_kwargs - ) -> BlockchainInterface: + def get_or_create_interface( + cls, blockchain_endpoint: str, *interface_args, **interface_kwargs + ) -> BlockchainInterface: try: - interface = cls.get_interface(eth_provider_uri=eth_provider_uri) + interface = cls.get_interface(blockchain_endpoint=blockchain_endpoint) except (cls.InterfaceNotInitialized, cls.NoRegisteredInterfaces): - cls.initialize_interface(eth_provider_uri=eth_provider_uri, *interface_args, **interface_kwargs) - interface = cls.get_interface(eth_provider_uri=eth_provider_uri) + cls.initialize_interface( + blockchain_endpoint=blockchain_endpoint, + *interface_args, + **interface_kwargs, + ) + interface = cls.get_interface(blockchain_endpoint=blockchain_endpoint) return interface diff --git a/nucypher/blockchain/eth/providers.py b/nucypher/blockchain/eth/providers.py index ac681fa95..2df935a39 100644 --- a/nucypher/blockchain/eth/providers.py +++ b/nucypher/blockchain/eth/providers.py @@ -14,25 +14,33 @@ class ProviderError(Exception): pass -def _get_IPC_provider(eth_provider_uri) -> BaseProvider: - uri_breakdown = urlparse(eth_provider_uri) +def _get_IPC_provider(blockchain_endpoint) -> BaseProvider: + uri_breakdown = urlparse(blockchain_endpoint) from nucypher.blockchain.eth.interfaces import BlockchainInterface return IPCProvider(ipc_path=uri_breakdown.path, timeout=BlockchainInterface.TIMEOUT, request_kwargs={'timeout': BlockchainInterface.TIMEOUT}) -def _get_HTTP_provider(eth_provider_uri) -> BaseProvider: +def _get_HTTP_provider(blockchain_endpoint) -> BaseProvider: from nucypher.blockchain.eth.interfaces import BlockchainInterface - return HTTPProvider(endpoint_uri=eth_provider_uri, request_kwargs={'timeout': BlockchainInterface.TIMEOUT}) + + return HTTPProvider( + endpoint_uri=blockchain_endpoint, + request_kwargs={"timeout": BlockchainInterface.TIMEOUT}, + ) -def _get_websocket_provider(eth_provider_uri) -> BaseProvider: +def _get_websocket_provider(blockchain_endpoint) -> BaseProvider: from nucypher.blockchain.eth.interfaces import BlockchainInterface - return WebsocketProvider(endpoint_uri=eth_provider_uri, websocket_kwargs={'timeout': BlockchainInterface.TIMEOUT}) + + return WebsocketProvider( + endpoint_uri=blockchain_endpoint, + websocket_kwargs={"timeout": BlockchainInterface.TIMEOUT}, + ) -def _get_auto_provider(eth_provider_uri) -> BaseProvider: +def _get_auto_provider(blockchain_endpoint) -> BaseProvider: from web3.auto import w3 # how-automated-detection-works: https://web3py.readthedocs.io/en/latest/providers.html connected = w3.isConnected() @@ -61,7 +69,7 @@ def _get_ethereum_tester(test_backend: Union[PyEVMBackend, MockBackend]) -> Ethe return provider -def _get_pyevm_test_provider(eth_provider_uri) -> BaseProvider: +def _get_pyevm_test_provider(blockchain_endpoint) -> BaseProvider: """ Test provider entry-point""" # https://github.com/ethereum/eth-tester#pyevm-experimental pyevm_eth_tester = _get_pyevm_test_backend() @@ -69,13 +77,13 @@ def _get_pyevm_test_provider(eth_provider_uri) -> BaseProvider: return provider -def _get_mock_test_provider(eth_provider_uri) -> BaseProvider: +def _get_mock_test_provider(blockchain_endpoint) -> BaseProvider: # https://github.com/ethereum/eth-tester#mockbackend mock_backend = MockBackend() provider = _get_ethereum_tester(test_backend=mock_backend) return provider -def _get_tester_ganache(eth_provider_uri=None) -> BaseProvider: - endpoint_uri = eth_provider_uri or 'http://localhost:7545' +def _get_tester_ganache(blockchain_endpoint=None) -> BaseProvider: + endpoint_uri = blockchain_endpoint or "http://localhost:7545" return HTTPProvider(endpoint_uri=endpoint_uri) diff --git a/nucypher/blockchain/eth/signers/software.py b/nucypher/blockchain/eth/signers/software.py index 22334fc87..f878dda2c 100644 --- a/nucypher/blockchain/eth/signers/software.py +++ b/nucypher/blockchain/eth/signers/software.py @@ -34,7 +34,9 @@ class Web3Signer(Signer): BlockchainInterfaceFactory, ) try: - blockchain = BlockchainInterfaceFactory.get_or_create_interface(eth_provider_uri=uri) + blockchain = BlockchainInterfaceFactory.get_or_create_interface( + blockchain_endpoint=uri + ) except BlockchainInterface.UnsupportedProvider: raise cls.InvalidSignerURI(uri) signer = cls(client=blockchain.client) diff --git a/nucypher/characters/base.py b/nucypher/characters/base.py index 77e2e49d4..529aed9c2 100644 --- a/nucypher/characters/base.py +++ b/nucypher/characters/base.py @@ -124,7 +124,7 @@ class Character(Learner): # REST self.network_middleware = network_middleware or RestMiddleware( - registry=self.registry, eth_provider_uri=eth_endpoint + registry=self.registry, eth_endpoint=eth_endpoint ) # Learner diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index 6298b8278..31d46fe3d 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -179,7 +179,7 @@ class Alice(Character, actors.PolicyAuthor): if is_me: # TODO: #289 blockchain = BlockchainInterfaceFactory.get_interface( - eth_provider_uri=self.eth_endpoint + blockchain_endpoint=self.eth_endpoint ) signer = signer or Web3Signer( blockchain.client @@ -990,10 +990,10 @@ class Ursula(Teacher, Character, Operator): # Connect to Provider if not BlockchainInterfaceFactory.is_interface_initialized( - eth_provider_uri=self.eth_endpoint + blockchain_endpoint=self.eth_endpoint ): BlockchainInterfaceFactory.initialize_interface( - eth_provider_uri=self.eth_endpoint + blockchain_endpoint=self.eth_endpoint ) if preflight: @@ -1244,7 +1244,7 @@ class Ursula(Teacher, Character, Operator): ) -> Union["Ursula", "NodeSprout"]: if network_middleware is None: network_middleware = RestMiddleware( - registry=registry, eth_provider_uri=provider_uri + registry=registry, eth_endpoint=provider_uri ) # Parse node URI diff --git a/nucypher/characters/unlawful.py b/nucypher/characters/unlawful.py index 2bbc3a06b..bf43ae4c3 100644 --- a/nucypher/characters/unlawful.py +++ b/nucypher/characters/unlawful.py @@ -44,7 +44,7 @@ class Vladimir(Ursula): ) eth_blockchain = target_ursula.application_agent.blockchain cls.network_middleware = EvilMiddleWare( - eth_provider_uri=eth_blockchain.eth_provider_uri + eth_endpoint=eth_blockchain.blockchain_endpoint ) polygon_blockchain = target_ursula.child_application_agent.blockchain @@ -77,8 +77,8 @@ class Vladimir(Ursula): checksum_address=cls.fraud_address, operator_address=cls.fraud_address, signer=Web3Signer(eth_blockchain.client), - eth_endpoint=eth_blockchain.eth_provider_uri, - polygon_endpoint=polygon_blockchain.eth_provider_uri, + eth_endpoint=eth_blockchain.blockchain_endpoint, + polygon_endpoint=polygon_blockchain.blockchain_endpoint, pre_payment_method=bogus_pre_payment_method, ) diff --git a/nucypher/cli/actions/select.py b/nucypher/cli/actions/select.py index 44f5e2d07..24e096a07 100644 --- a/nucypher/cli/actions/select.py +++ b/nucypher/cli/actions/select.py @@ -58,16 +58,16 @@ def select_client_account( if polygon_endpoint: # Connect to the blockchain in order to select an account if not BlockchainInterfaceFactory.is_interface_initialized( - eth_provider_uri=polygon_endpoint + blockchain_endpoint=polygon_endpoint ): BlockchainInterfaceFactory.initialize_interface( - eth_provider_uri=polygon_endpoint, poa=poa, emitter=emitter + blockchain_endpoint=polygon_endpoint, poa=poa, emitter=emitter ) if not signer_uri: signer_uri = polygon_endpoint blockchain = BlockchainInterfaceFactory.get_interface( - eth_provider_uri=polygon_endpoint + blockchain_endpoint=polygon_endpoint ) if signer_uri and not signer: diff --git a/nucypher/cli/painting/transactions.py b/nucypher/cli/painting/transactions.py index 63c0ccaf0..3ad272e51 100644 --- a/nucypher/cli/painting/transactions.py +++ b/nucypher/cli/painting/transactions.py @@ -5,9 +5,15 @@ from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.utils import etherscan_url -def paint_receipt_summary(emitter, receipt, chain_name: str = None, transaction_type=None, eth_provider_uri: str = None): - tx_hash = receipt['transactionHash'].hex() - emitter.echo("OK", color='green', nl=False, bold=True) +def paint_receipt_summary( + emitter, + receipt, + chain_name: str = None, + transaction_type=None, + blockchain_endpoint: str = None, +): + tx_hash = receipt["transactionHash"].hex() + emitter.echo("OK", color="green", nl=False, bold=True) if transaction_type: emitter.echo(f" | {transaction_type} | {tx_hash}", color='yellow', nl=False) else: @@ -16,7 +22,9 @@ def paint_receipt_summary(emitter, receipt, chain_name: str = None, transaction_ emitter.echo(f"Block #{receipt['blockNumber']} | {receipt['blockHash'].hex()}") if not chain_name: - blockchain = BlockchainInterfaceFactory.get_interface(eth_provider_uri=eth_provider_uri) + blockchain = BlockchainInterfaceFactory.get_interface( + blockchain_endpoint=blockchain_endpoint + ) chain_name = blockchain.client.chain_name try: url = etherscan_url(item=tx_hash, network=chain_name) diff --git a/nucypher/cli/utils.py b/nucypher/cli/utils.py index 9d6312166..bd037017d 100644 --- a/nucypher/cli/utils.py +++ b/nucypher/cli/utils.py @@ -111,19 +111,24 @@ def get_registry( return registry -def connect_to_blockchain(emitter: StdoutEmitter, - eth_provider_uri: str, - debug: bool = False, - light: bool = False - ) -> BlockchainInterface: +def connect_to_blockchain( + emitter: StdoutEmitter, + blockchain_endpoint: str, + debug: bool = False, + light: bool = False, +) -> BlockchainInterface: try: # Note: Conditional for test compatibility. - if not BlockchainInterfaceFactory.is_interface_initialized(eth_provider_uri=eth_provider_uri): - BlockchainInterfaceFactory.initialize_interface(eth_provider_uri=eth_provider_uri, - light=light, - emitter=emitter) + if not BlockchainInterfaceFactory.is_interface_initialized( + blockchain_endpoint=blockchain_endpoint + ): + BlockchainInterfaceFactory.initialize_interface( + blockchain_endpoint=blockchain_endpoint, light=light, emitter=emitter + ) emitter.echo(message=CONNECTING_TO_BLOCKCHAIN) - blockchain = BlockchainInterfaceFactory.get_interface(eth_provider_uri=eth_provider_uri) + blockchain = BlockchainInterfaceFactory.get_interface( + blockchain_endpoint=blockchain_endpoint + ) return blockchain except Exception as e: if debug: diff --git a/nucypher/config/base.py b/nucypher/config/base.py index 00b12c42a..e86b07ba7 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -443,11 +443,11 @@ class CharacterConfiguration(BaseConfiguration): self.gas_strategy = gas_strategy self.max_gas_price = max_gas_price # gwei is_initialized = BlockchainInterfaceFactory.is_interface_initialized( - eth_provider_uri=self.eth_endpoint + blockchain_endpoint=self.eth_endpoint ) if not is_initialized and eth_endpoint: BlockchainInterfaceFactory.initialize_interface( - eth_provider_uri=self.eth_endpoint, + blockchain_endpoint=self.eth_endpoint, poa=self.poa, light=self.is_light, emitter=emitter, @@ -462,7 +462,7 @@ class CharacterConfiguration(BaseConfiguration): # TODO: this is potential fix for multichain connection, if we want to use it build it out into a loop # for uri in eth_provider_uri (list of uris fom config): BlockchainInterfaceFactory.get_or_create_interface( - eth_provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, poa=self.poa, light=self.is_light, emitter=emitter, @@ -526,7 +526,7 @@ class CharacterConfiguration(BaseConfiguration): # Network self.network_middleware = network_middleware or self.DEFAULT_NETWORK_MIDDLEWARE( - registry=self.registry, eth_provider_uri=self.eth_endpoint + registry=self.registry, eth_endpoint=self.eth_endpoint ) super().__init__(filepath=self.config_file_location, config_root=self.config_root) diff --git a/nucypher/network/middleware.py b/nucypher/network/middleware.py index 79a9771ec..eabbdbdc5 100644 --- a/nucypher/network/middleware.py +++ b/nucypher/network/middleware.py @@ -28,19 +28,17 @@ class NucypherMiddlewareClient: def __init__( self, - eth_provider_uri: Optional[str], + eth_endpoint: Optional[str], registry: Optional[ContractRegistry] = None, storage: Optional[NodeStorage] = None, *args, **kwargs, ): - if not eth_provider_uri: - raise ValueError( - "eth_provider_uri is required for NucypherMiddlewareClient" - ) + if not eth_endpoint: + raise ValueError("eth_endpoint is required for NucypherMiddlewareClient") self.registry = registry - self.eth_provider_uri = eth_provider_uri + self.eth_endpoint = eth_endpoint self.storage = storage or ForgetfulNodeStorage() # for certificate storage def get_certificate(self, @@ -91,7 +89,7 @@ class NucypherMiddlewareClient: node.verify_node( network_middleware_client=self, registry=self.registry, - eth_endpoint=self.eth_provider_uri, + eth_endpoint=self.eth_endpoint, ) return self.parse_node_or_host_and_port(node_or_sprout, host, port) @@ -253,8 +251,8 @@ class RestMiddleware: def __init__(self, *args, **kwargs): super().__init__(status=HTTPStatus.FORBIDDEN, *args, **kwargs) - def __init__(self, eth_provider_uri: str, registry=None): - self.client = self._client_class(registry=registry, eth_provider_uri=eth_provider_uri) + def __init__(self, eth_endpoint: str, registry=None): + self.client = self._client_class(registry=registry, eth_endpoint=eth_endpoint) def request_revocation(self, ursula, revocation): # TODO: Implement offchain revocation #2787 diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index b6e778f08..d1d2dc0b2 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -273,7 +273,7 @@ class Learner: self.domain = domain self.taco_network = NetworksInventory.get_network(self.domain) default_middleware = self.__DEFAULT_MIDDLEWARE_CLASS( - registry=self.registry, eth_provider_uri=self.eth_endpoint + registry=self.registry, eth_endpoint=self.eth_endpoint ) self.network_middleware = network_middleware or default_middleware self.save_metadata = save_metadata diff --git a/nucypher/utilities/ethereum.py b/nucypher/utilities/ethereum.py index cdcb19df1..ecf81fb3c 100644 --- a/nucypher/utilities/ethereum.py +++ b/nucypher/utilities/ethereum.py @@ -22,15 +22,21 @@ def encode_constructor_arguments(web3: Web3, return data -def connect_web3_provider(eth_provider_uri: str) -> None: +def connect_web3_provider(blockchain_endpoint: str) -> None: """ - Convenience function for connecting to an ethereum provider now. + Convenience function for connecting to a blockchain provider now. This may be used to optimize the startup time of some applications by establishing the connection eagerly. """ from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory - if not BlockchainInterfaceFactory.is_interface_initialized(eth_provider_uri=eth_provider_uri): - BlockchainInterfaceFactory.initialize_interface(eth_provider_uri=eth_provider_uri) - interface = BlockchainInterfaceFactory.get_interface(eth_provider_uri=eth_provider_uri) + if not BlockchainInterfaceFactory.is_interface_initialized( + blockchain_endpoint=blockchain_endpoint + ): + BlockchainInterfaceFactory.initialize_interface( + blockchain_endpoint=blockchain_endpoint + ) + interface = BlockchainInterfaceFactory.get_interface( + blockchain_endpoint=blockchain_endpoint + ) interface.connect() diff --git a/nucypher/utilities/networking.py b/nucypher/utilities/networking.py index 9216c4acc..c30d79725 100644 --- a/nucypher/utilities/networking.py +++ b/nucypher/utilities/networking.py @@ -75,7 +75,7 @@ def _request_from_node( log: Logger = IP_DETECTION_LOGGER, ) -> Union[str, None]: if not client: - client = NucypherMiddlewareClient(eth_provider_uri=provider_uri) + client = NucypherMiddlewareClient(eth_endpoint=provider_uri) try: response = client.get( node_or_sprout=teacher, path="ping", timeout=timeout @@ -154,7 +154,7 @@ def get_external_ip_from_known_nodes( if len(known_nodes) < sample_size: return # There are too few known nodes sample = random.sample(list(known_nodes), sample_size) - client = NucypherMiddlewareClient(eth_provider_uri=provider_uri) + client = NucypherMiddlewareClient(eth_endpoint=provider_uri) for node in sample: ip = _request_from_node(teacher=node, client=client, provider_uri=provider_uri) if ip: diff --git a/nucypher/utilities/prometheus/collector.py b/nucypher/utilities/prometheus/collector.py index 37ad3da2d..c10e58072 100644 --- a/nucypher/utilities/prometheus/collector.py +++ b/nucypher/utilities/prometheus/collector.py @@ -121,9 +121,10 @@ class UrsulaInfoMetricsCollector(BaseMetricsCollector): class BlockchainMetricsCollector(BaseMetricsCollector): """Collector for Blockchain specific metrics.""" - def __init__(self, eth_provider_uri: str): + + def __init__(self, eth_endpoint: str): super().__init__() - self.eth_provider_uri = eth_provider_uri + self.eth_endpoint = eth_endpoint def initialize(self, metrics_prefix: str, registry: CollectorRegistry) -> None: self.metrics = { @@ -138,7 +139,9 @@ class BlockchainMetricsCollector(BaseMetricsCollector): } def _collect_internal(self) -> None: - blockchain = BlockchainInterfaceFactory.get_or_create_interface(eth_provider_uri=self.eth_provider_uri) + blockchain = BlockchainInterfaceFactory.get_or_create_interface( + blockchain_endpoint=self.eth_endpoint + ) self.metrics["eth_chain_id"].set(blockchain.client.chain_id) self.metrics["eth_current_block_number"].set(blockchain.client.block_number) @@ -150,12 +153,12 @@ class StakingProviderMetricsCollector(BaseMetricsCollector): self, staking_provider_address: ChecksumAddress, contract_registry: ContractRegistry, - eth_provider_uri: str, + eth_endpoint: str, ): super().__init__() self.staking_provider_address = staking_provider_address self.contract_registry = contract_registry - self.eth_provider_uri = eth_provider_uri + self.eth_endpoint = eth_endpoint def initialize(self, metrics_prefix: str, registry: CollectorRegistry) -> None: self.metrics = { @@ -180,7 +183,7 @@ class StakingProviderMetricsCollector(BaseMetricsCollector): application_agent = ContractAgency.get_agent( TACoApplicationAgent, registry=self.contract_registry, - provider_uri=self.eth_provider_uri, + provider_uri=self.eth_endpoint, ) authorized = application_agent.get_authorized_stake( staking_provider=self.staking_provider_address diff --git a/nucypher/utilities/prometheus/metrics.py b/nucypher/utilities/prometheus/metrics.py index 02a0a822c..fc06a3e90 100644 --- a/nucypher/utilities/prometheus/metrics.py +++ b/nucypher/utilities/prometheus/metrics.py @@ -157,14 +157,14 @@ def create_metrics_collectors(ursula: "lawful.Ursula") -> List[MetricsCollector] # Blockchain prometheus # TODO possible include information about payment - collectors.append(BlockchainMetricsCollector(eth_provider_uri=ursula.eth_endpoint)) + collectors.append(BlockchainMetricsCollector(eth_endpoint=ursula.eth_endpoint)) # Staking Provider prometheus collectors.append( StakingProviderMetricsCollector( staking_provider_address=ursula.checksum_address, contract_registry=ursula.registry, - eth_provider_uri=ursula.eth_endpoint, + eth_endpoint=ursula.eth_endpoint, ) ) diff --git a/tests/acceptance/characters/test_operator.py b/tests/acceptance/characters/test_operator.py index 8a2fbef2d..5be008b30 100644 --- a/tests/acceptance/characters/test_operator.py +++ b/tests/acceptance/characters/test_operator.py @@ -159,9 +159,7 @@ def test_ursulas_reencrypt(ursulas, alice, bob, policy_value): assert plaintexts == [message] # Let's consider also that a node may be down when granting - alice.network_middleware = NodeIsDownMiddleware( - eth_provider_uri=MOCK_ETH_PROVIDER_URI - ) + alice.network_middleware = NodeIsDownMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI) alice.network_middleware.node_is_down(ursulas[0]) with pytest.raises(Policy.NotEnoughUrsulas): diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index c8d4e4e71..971695c64 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -317,7 +317,7 @@ def test_registry(deployed_contracts): def testerchain(project) -> TesterBlockchain: # Extract the web3 provider containing EthereumTester from the ape project's chain manager provider = project.chain_manager.provider.web3.provider - testerchain = TesterBlockchain(eth_provider=provider) + testerchain = TesterBlockchain(blockchain_provider=provider) BlockchainInterfaceFactory.register_interface(interface=testerchain, force=True) yield testerchain diff --git a/tests/acceptance/test_testerchain.py b/tests/acceptance/test_testerchain.py index 33b5e2730..51078efcc 100644 --- a/tests/acceptance/test_testerchain.py +++ b/tests/acceptance/test_testerchain.py @@ -1,14 +1,12 @@ import pytest -from nucypher.blockchain.eth.clients import EthereumClient -from nucypher.blockchain.eth.signers.software import Web3Signer -from nucypher.crypto.powers import TransactingPower from tests.constants import ( DEVELOPMENT_ETH_AIRDROP_AMOUNT, NUMBER_OF_ETH_TEST_ACCOUNTS, NUMBER_OF_STAKING_PROVIDERS_IN_BLOCKCHAIN_TESTS, NUMBER_OF_URSULAS_IN_BLOCKCHAIN_TESTS, ) + # Prevents TesterBlockchain to be picked up by py.test as a test class from tests.utils.blockchain import TesterBlockchain as _TesterBlockchain @@ -28,7 +26,7 @@ def test_testerchain_creation(testerchain, another_testerchain): for chain in chains: # Ensure we are testing on the correct network... - assert 'tester' in chain.eth_provider_uri + assert "tester" in chain.blockchain_endpoint # ... and that there are already some blocks mined chain.w3.eth.w3.testing.mine(1) diff --git a/tests/fixtures.py b/tests/fixtures.py index af9312e17..4f5a48147 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -198,7 +198,7 @@ def enacted_policy(idle_policy, ursulas): # cannot set them again # deposit = NON_PAYMENT(b"0000000") # contract_end_datetime = maya.now() + datetime.timedelta(days=5) - network_middleware = MockRestMiddleware(eth_provider_uri=TEST_ETH_PROVIDER_URI) + network_middleware = MockRestMiddleware(eth_endpoint=TEST_ETH_PROVIDER_URI) # REST call happens here, as does population of TreasureMap. enacted_policy = idle_policy.enact( @@ -440,7 +440,7 @@ def highperf_mocked_alice( eth_endpoint=TEST_ETH_PROVIDER_URI, checksum_address=testerchain.alice_account, network_middleware=MockRestMiddlewareForLargeFleetTests( - eth_provider_uri=TEST_ETH_PROVIDER_URI + eth_endpoint=TEST_ETH_PROVIDER_URI ), abort_on_learning_error=True, save_metadata=False, @@ -461,7 +461,7 @@ def highperf_mocked_bob(fleet_of_highperf_mocked_ursulas): eth_endpoint=TEST_ETH_PROVIDER_URI, domain=TEMPORARY_DOMAIN, network_middleware=MockRestMiddlewareForLargeFleetTests( - eth_provider_uri=TEST_ETH_PROVIDER_URI + eth_endpoint=TEST_ETH_PROVIDER_URI ), abort_on_learning_error=True, save_metadata=False, @@ -560,7 +560,7 @@ def basic_auth_file(temp_dir_path): @pytest.fixture(scope='module') def mock_rest_middleware(): - return MockRestMiddleware(eth_provider_uri=TEST_ETH_PROVIDER_URI) + return MockRestMiddleware(eth_endpoint=TEST_ETH_PROVIDER_URI) # diff --git a/tests/integration/characters/test_bob_handles_frags.py b/tests/integration/characters/test_bob_handles_frags.py index a548532ae..a383dba2b 100644 --- a/tests/integration/characters/test_bob_handles_frags.py +++ b/tests/integration/characters/test_bob_handles_frags.py @@ -83,9 +83,7 @@ def test_use_external_cache(enacted_policy, bob, ursulas): ursulas = list(ursulas) # All Ursulas are down except for two - bob.network_middleware = NodeIsDownMiddleware( - eth_provider_uri=MOCK_ETH_PROVIDER_URI - ) + bob.network_middleware = NodeIsDownMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI) for ursula in ursulas[2:]: bob.network_middleware.node_is_down(ursula) diff --git a/tests/integration/characters/test_bob_joins_policy_and_retrieves.py b/tests/integration/characters/test_bob_joins_policy_and_retrieves.py index 40d4ebdb6..656b3d803 100644 --- a/tests/integration/characters/test_bob_joins_policy_and_retrieves.py +++ b/tests/integration/characters/test_bob_joins_policy_and_retrieves.py @@ -50,7 +50,7 @@ def test_bob_retrieves(alice, ursulas, certificates_tempdir): domain=TEMPORARY_DOMAIN, start_learning_now=True, eth_endpoint=MOCK_ETH_PROVIDER_URI, - network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), + network_middleware=MockRestMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI), abort_on_learning_error=True, known_nodes=a_couple_of_ursulas, ) diff --git a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py index 1e439fa83..e472c8fb9 100644 --- a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py +++ b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py @@ -51,10 +51,10 @@ def test_ursula_init_with_local_keystore_signer( "--network", TEMPORARY_DOMAIN, "--eth-endpoint", - testerchain.eth_provider_uri, + testerchain.blockchain_endpoint, # Layer 2 "--polygon-endpoint", - testerchain.eth_provider_uri, + testerchain.blockchain_endpoint, "--rest-host", MOCK_IP_ADDRESS, "--rest-port", diff --git a/tests/integration/config/test_configuration_persistence.py b/tests/integration/config/test_configuration_persistence.py index 1dd6b3c6e..2bcf687df 100644 --- a/tests/integration/config/test_configuration_persistence.py +++ b/tests/integration/config/test_configuration_persistence.py @@ -16,7 +16,7 @@ def test_alices_powers_are_persistent(ursulas, temp_dir_path, testerchain): alice_config = AliceConfiguration( eth_endpoint=MOCK_ETH_PROVIDER_URI, config_root=config_root, - network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), + network_middleware=MockRestMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI), domain=TEMPORARY_DOMAIN, checksum_address=testerchain.alice_account, start_learning_now=False, @@ -57,7 +57,7 @@ def test_alices_powers_are_persistent(ursulas, temp_dir_path, testerchain): start_learning_now=False, domain=TEMPORARY_DOMAIN, eth_endpoint=MOCK_ETH_PROVIDER_URI, - network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), + network_middleware=MockRestMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI), ) bob_policy = alice.grant(bob, label, threshold=threshold, shares=shares, expiration=policy_end_datetime) @@ -80,7 +80,7 @@ def test_alices_powers_are_persistent(ursulas, temp_dir_path, testerchain): # A new Alice is restored from the configuration file new_alice_config = AliceConfiguration.from_configuration_file( filepath=alice_config_file, - network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), + network_middleware=MockRestMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI), start_learning_now=False, config_root=config_root, known_nodes=ursulas, @@ -99,7 +99,7 @@ def test_alices_powers_are_persistent(ursulas, temp_dir_path, testerchain): domain=TEMPORARY_DOMAIN, eth_endpoint=MOCK_ETH_PROVIDER_URI, start_learning_now=False, - network_middleware=MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), + network_middleware=MockRestMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI), ) # Alice creates a new policy for Roberto. Note how all the parameters diff --git a/tests/integration/learning/test_firstula_circumstances.py b/tests/integration/learning/test_firstula_circumstances.py index 5d17affac..31f6eb92a 100644 --- a/tests/integration/learning/test_firstula_circumstances.py +++ b/tests/integration/learning/test_firstula_circumstances.py @@ -33,7 +33,7 @@ def test_get_cert_from_running_seed_node(lonely_ursula_maker): firstula_as_seed_node = firstula.seed_node_metadata() any_other_ursula = lonely_ursula_maker( seed_nodes=[firstula_as_seed_node], - network_middleware=RestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI), + network_middleware=RestMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI), ).pop() assert not any_other_ursula.known_nodes diff --git a/tests/integration/network/test_failure_modes.py b/tests/integration/network/test_failure_modes.py index bf6fc91cd..0957e3bea 100644 --- a/tests/integration/network/test_failure_modes.py +++ b/tests/integration/network/test_failure_modes.py @@ -20,9 +20,7 @@ def test_alice_can_grant_even_when_the_first_nodes_she_tries_are_down( label = b"this_is_the_path_to_which_access_is_being_granted" alice.known_nodes.current_state._nodes = {} - alice.network_middleware = NodeIsDownMiddleware( - eth_provider_uri=MOCK_ETH_PROVIDER_URI - ) + alice.network_middleware = NodeIsDownMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI) # OK, her first and only node is down. down_node = list(ursulas)[0] @@ -78,9 +76,7 @@ def test_alice_can_grant_even_when_the_first_nodes_she_tries_are_down( def test_node_has_changed_cert(alice, ursulas): alice.known_nodes.current_state._nodes = {} - alice.network_middleware = NodeIsDownMiddleware( - eth_provider_uri=MOCK_ETH_PROVIDER_URI - ) + alice.network_middleware = NodeIsDownMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI) alice.network_middleware.client.certs_are_broken = True firstula = list(ursulas)[0] diff --git a/tests/integration/network/test_network_actors.py b/tests/integration/network/test_network_actors.py index 8ab399f63..1c15f5ff3 100644 --- a/tests/integration/network/test_network_actors.py +++ b/tests/integration/network/test_network_actors.py @@ -67,7 +67,7 @@ def test_vladimir_illegal_interface_key_does_not_propagate(ursulas): # This Ursula is totally legit... ursula_whom_vladimir_will_imitate.verify_node( - MockRestMiddleware(eth_provider_uri=MOCK_ETH_PROVIDER_URI) + MockRestMiddleware(eth_endpoint=MOCK_ETH_PROVIDER_URI) ) globalLogPublisher.addObserver(warning_trapper) diff --git a/tests/integration/utilities/test_prometheus_collectors.py b/tests/integration/utilities/test_prometheus_collectors.py index 7d530898f..0292edaf3 100644 --- a/tests/integration/utilities/test_prometheus_collectors.py +++ b/tests/integration/utilities/test_prometheus_collectors.py @@ -70,7 +70,7 @@ def test_ursula_info_metrics_collector(test_registry, ursulas): @pytest.mark.skipif(condition=(not PROMETHEUS_INSTALLED), reason="prometheus_client is required for test") def test_blockchain_metrics_collector(testerchain): - collector = BlockchainMetricsCollector(eth_provider_uri=MOCK_ETH_PROVIDER_URI) + collector = BlockchainMetricsCollector(eth_endpoint=MOCK_ETH_PROVIDER_URI) collector_registry = CollectorRegistry() prefix = 'test_blockchain_metrics_collector' @@ -96,7 +96,7 @@ def test_staking_provider_metrics_collector(test_registry, staking_providers): collector = StakingProviderMetricsCollector( staking_provider_address=staking_provider_address, contract_registry=test_registry, - eth_provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) collector_registry = CollectorRegistry() prefix = "test_staking_provider_metrics_collector" diff --git a/tests/unit/test_web3_clients.py b/tests/unit/test_web3_clients.py index fe71cb953..6a1f1c717 100644 --- a/tests/unit/test_web3_clients.py +++ b/tests/unit/test_web3_clients.py @@ -1,13 +1,18 @@ import datetime -from unittest.mock import PropertyMock, Mock +from unittest.mock import Mock, PropertyMock import pytest from web3 import HTTPProvider, IPCProvider, WebsocketProvider -from nucypher.blockchain.eth.clients import (GanacheClient, GethClient, InfuraClient, PUBLIC_CHAINS, - ParityClient, AlchemyClient) +from nucypher.blockchain.eth.clients import ( + AlchemyClient, + GanacheClient, + GethClient, + InfuraClient, + ParityClient, +) from nucypher.blockchain.eth.interfaces import BlockchainInterface from nucypher.utilities.networking import LOOPBACK_ADDRESS @@ -139,53 +144,55 @@ class ProviderTypeTestClient(BlockchainInterfaceTestBase): self.expected_provider_class = expected_provider_class self.test_provider_to_attach = actual_provider_to_attach - def _attach_eth_provider(self, *args, **kwargs) -> None: - super()._attach_eth_provider(*args, **kwargs) + def _attach_blockchain_provider(self, *args, **kwargs) -> None: + super()._attach_blockchain_provider(*args, **kwargs) # check type assert isinstance(self.provider, self.expected_provider_class) - super()._attach_eth_provider(eth_provider=self.test_provider_to_attach) + super()._attach_blockchain_provider( + blockchain_provider=self.test_provider_to_attach + ) class InfuraTestClient(BlockchainInterfaceTestBase): - def _attach_eth_provider(self, *args, **kwargs) -> None: - super()._attach_eth_provider(eth_provider=MockInfuraProvider()) + def _attach_blockchain_provider(self, *args, **kwargs) -> None: + super()._attach_blockchain_provider(blockchain_provider=MockInfuraProvider()) class AlchemyTestClient(BlockchainInterfaceTestBase): - def _attach_eth_provider(self, *args, **kwargs) -> None: - super()._attach_eth_provider(eth_provider=MockAlchemyProvider()) + def _attach_blockchain_provider(self, *args, **kwargs) -> None: + super()._attach_blockchain_provider(blockchain_provider=MockAlchemyProvider()) class GethClientTestBlockchain(BlockchainInterfaceTestBase): - def _attach_eth_provider(self, *args, **kwargs) -> None: - super()._attach_eth_provider(eth_provider=MockGethProvider()) + def _attach_blockchain_provider(self, *args, **kwargs) -> None: + super()._attach_blockchain_provider(blockchain_provider=MockGethProvider()) class ParityClientTestInterface(BlockchainInterfaceTestBase): - def _attach_eth_provider(self, *args, **kwargs) -> None: - super()._attach_eth_provider(eth_provider=MockParityProvider()) + def _attach_blockchain_provider(self, *args, **kwargs) -> None: + super()._attach_blockchain_provider(blockchain_provider=MockParityProvider()) class GanacheClientTestInterface(BlockchainInterfaceTestBase): - def _attach_eth_provider(self, *args, **kwargs) -> None: - super()._attach_eth_provider(eth_provider=MockGanacheProvider()) + def _attach_blockchain_provider(self, *args, **kwargs) -> None: + super()._attach_blockchain_provider(blockchain_provider=MockGanacheProvider()) def test_client_no_provider(): - with pytest.raises(BlockchainInterface.NoProvider) as e: + with pytest.raises(BlockchainInterface.NoProvider): interface = BlockchainInterfaceTestBase() interface.connect() def test_geth_web3_client(): - interface = GethClientTestBlockchain(eth_provider_uri='file:///ipc.geth') + interface = GethClientTestBlockchain(blockchain_endpoint="file:///ipc.geth") interface.connect() assert isinstance(interface.client, GethClient) @@ -199,62 +206,77 @@ def test_geth_web3_client(): def test_autodetect_provider_type_file(tempfile_path): - - interface = ProviderTypeTestClient(eth_provider_uri=str(tempfile_path), # existing file for test - expected_provider_class=IPCProvider, - actual_provider_to_attach=MockGethProvider()) + interface = ProviderTypeTestClient( + blockchain_endpoint=str(tempfile_path), # existing file for test + expected_provider_class=IPCProvider, + actual_provider_to_attach=MockGethProvider(), + ) interface.connect() assert isinstance(interface.client, GethClient) def test_autodetect_provider_type_file_none_existent(): - with pytest.raises(BlockchainInterface.UnsupportedProvider) as e: - interface = BlockchainInterfaceTestBase(eth_provider_uri='/none_existent.ipc.geth') + with pytest.raises(BlockchainInterface.UnsupportedProvider): + interface = BlockchainInterfaceTestBase( + blockchain_endpoint="/none_existent.ipc.geth" + ) interface.connect() def test_detect_provider_type_file(): - interface = ProviderTypeTestClient(eth_provider_uri='file:///ipc.geth', - expected_provider_class=IPCProvider, - actual_provider_to_attach=MockGethProvider()) + interface = ProviderTypeTestClient( + blockchain_endpoint="file:///ipc.geth", + expected_provider_class=IPCProvider, + actual_provider_to_attach=MockGethProvider(), + ) interface.connect() assert isinstance(interface.client, GethClient) def test_detect_provider_type_ipc(): - interface = ProviderTypeTestClient(eth_provider_uri='ipc:///ipc.geth', - expected_provider_class=IPCProvider, - actual_provider_to_attach=MockGethProvider()) + interface = ProviderTypeTestClient( + blockchain_endpoint="ipc:///ipc.geth", + expected_provider_class=IPCProvider, + actual_provider_to_attach=MockGethProvider(), + ) interface.connect() assert isinstance(interface.client, GethClient) def test_detect_provider_type_http(): - interface = ProviderTypeTestClient(eth_provider_uri='http://ganache:8445', - expected_provider_class=HTTPProvider, - actual_provider_to_attach=MockGanacheProvider()) + interface = ProviderTypeTestClient( + blockchain_endpoint="http://ganache:8445", + expected_provider_class=HTTPProvider, + actual_provider_to_attach=MockGanacheProvider(), + ) interface.connect() assert isinstance(interface.client, GanacheClient) def test_detect_provider_type_https(): - interface = ProviderTypeTestClient(eth_provider_uri='https://ganache:8445', - expected_provider_class=HTTPProvider, - actual_provider_to_attach=MockGanacheProvider()) + interface = ProviderTypeTestClient( + blockchain_endpoint="https://ganache:8445", + expected_provider_class=HTTPProvider, + actual_provider_to_attach=MockGanacheProvider(), + ) interface.connect() assert isinstance(interface.client, GanacheClient) def test_detect_provider_type_ws(): - interface = ProviderTypeTestClient(eth_provider_uri=f'ws://{LOOPBACK_ADDRESS}:8546', - expected_provider_class=WebsocketProvider, - actual_provider_to_attach=MockWebSocketProvider()) + interface = ProviderTypeTestClient( + blockchain_endpoint=f"ws://{LOOPBACK_ADDRESS}:8546", + expected_provider_class=WebsocketProvider, + actual_provider_to_attach=MockWebSocketProvider(), + ) interface.connect() assert isinstance(interface.client, GethClient) def test_infura_web3_client(): - interface = InfuraTestClient(eth_provider_uri='wss://:@goerli.infura.io/ws/v3/1234567890987654321abcdef') + interface = InfuraTestClient( + blockchain_endpoint="wss://:@goerli.infura.io/ws/v3/1234567890987654321abcdef" + ) interface.connect() assert isinstance(interface.client, InfuraClient) @@ -270,7 +292,9 @@ def test_infura_web3_client(): def test_alchemy_web3_client(): - interface = AlchemyTestClient(eth_provider_uri='https://eth-rinkeby.alchemyapi.io/v2/1234567890987654321abcdef') + interface = AlchemyTestClient( + blockchain_endpoint="https://eth-rinkeby.alchemyapi.io/v2/1234567890987654321abcdef" + ) interface.connect() assert isinstance(interface.client, AlchemyClient) @@ -282,7 +306,7 @@ def test_alchemy_web3_client(): def test_parity_web3_client(): - interface = ParityClientTestInterface(eth_provider_uri='file:///ipc.parity') + interface = ParityClientTestInterface(blockchain_endpoint="file:///ipc.parity") interface.connect() assert isinstance(interface.client, ParityClient) @@ -293,7 +317,7 @@ def test_parity_web3_client(): def test_ganache_web3_client(): - interface = GanacheClientTestInterface(eth_provider_uri='http://ganache:8445') + interface = GanacheClientTestInterface(blockchain_endpoint="http://ganache:8445") interface.connect() assert isinstance(interface.client, GanacheClient) diff --git a/tests/utils/blockchain.py b/tests/utils/blockchain.py index fb16aa5be..8fe25a9a9 100644 --- a/tests/utils/blockchain.py +++ b/tests/utils/blockchain.py @@ -73,18 +73,23 @@ class TesterBlockchain(BlockchainInterface): __OPERATORS_RANGE = range(NUMBER_OF_URSULAS_IN_BLOCKCHAIN_TESTS) __ACCOUNT_CACHE = list() - def __init__(self, - test_accounts: int = NUMBER_OF_ETH_TEST_ACCOUNTS, - poa: bool = True, - light: bool = False, - eth_airdrop: bool = False, - *args, **kwargs): - - EXPECTED_CONFIRMATION_TIME_IN_SECONDS['free'] = 5 # Just some upper-limit - super().__init__(eth_provider_uri=self.ETH_PROVIDER_URI, - poa=poa, - light=light, - *args, **kwargs) + def __init__( + self, + test_accounts: int = NUMBER_OF_ETH_TEST_ACCOUNTS, + poa: bool = True, + light: bool = False, + eth_airdrop: bool = False, + *args, + **kwargs, + ): + EXPECTED_CONFIRMATION_TIME_IN_SECONDS["free"] = 5 # Just some upper-limit + super().__init__( + blockchain_endpoint=self.ETH_PROVIDER_URI, + poa=poa, + light=light, + *args, + **kwargs, + ) self.log = Logger("test-blockchain") self.connect() diff --git a/tests/utils/config.py b/tests/utils/config.py index 718a9c70d..c864930c2 100644 --- a/tests/utils/config.py +++ b/tests/utils/config.py @@ -34,7 +34,7 @@ def assemble( runtime_params = dict( eth_endpoint=eth_endpoint, registry=test_registry, - network_middleware=MockRestMiddleware(eth_provider_uri=eth_endpoint), + network_middleware=MockRestMiddleware(eth_endpoint=eth_endpoint), known_nodes=known_nodes, checksum_address=checksum_address, ) diff --git a/tests/utils/middleware.py b/tests/utils/middleware.py index 9f5146354..e50227eb0 100644 --- a/tests/utils/middleware.py +++ b/tests/utils/middleware.py @@ -5,7 +5,7 @@ from pathlib import Path import requests from flask import Response -from nucypher_core import MetadataRequest, FleetStateChecksum +from nucypher_core import FleetStateChecksum, MetadataRequest from nucypher.characters.lawful import Ursula from nucypher.network.middleware import NucypherMiddlewareClient, RestMiddleware @@ -143,7 +143,7 @@ class NodeIsDownMiddleware(MockRestMiddleware): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.client = _MiddlewareClientWithConnectionProblems( - eth_provider_uri=TEST_ETH_PROVIDER_URI + eth_endpoint=TEST_ETH_PROVIDER_URI ) def node_is_down(self, node): From eafe4b65a9d5fa51eccf4588f500d59ebafbdc5b Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 14:02:29 -0400 Subject: [PATCH 25/63] Rename provider_uri parameter for ContractAgents.get_agent to blockchain_endpoint. --- examples/testnet_compound_multichain_taco.py | 2 +- examples/testnet_simple_taco.py | 2 +- nucypher/blockchain/eth/actors.py | 12 +++++++----- nucypher/blockchain/eth/agents.py | 12 ++++++------ nucypher/blockchain/eth/trackers/bonding.py | 2 +- nucypher/characters/lawful.py | 16 +++++++++------- nucypher/cli/commands/taco.py | 2 +- nucypher/cli/painting/status.py | 2 +- nucypher/network/nodes.py | 4 ++-- nucypher/policy/payment.py | 4 +++- nucypher/utilities/prometheus/collector.py | 2 +- scripts/hooks/nucypher_agents.py | 8 ++++---- scripts/hooks/nucypher_dkg.py | 4 ++-- tests/acceptance/agents/test_contract_agency.py | 4 ++-- tests/acceptance/agents/test_token_agent.py | 4 +++- tests/acceptance/cli/test_ursula_init.py | 2 +- tests/acceptance/conditions/conftest.py | 8 ++++---- tests/acceptance/conditions/test_conditions.py | 4 ++-- tests/acceptance/conftest.py | 8 +++++--- tests/metrics/grant_availability.py | 4 ++-- tests/unit/test_ritualist.py | 2 +- 21 files changed, 59 insertions(+), 49 deletions(-) diff --git a/examples/testnet_compound_multichain_taco.py b/examples/testnet_compound_multichain_taco.py index 896d22dd8..21947be0b 100644 --- a/examples/testnet_compound_multichain_taco.py +++ b/examples/testnet_compound_multichain_taco.py @@ -35,7 +35,7 @@ registry = ContractRegistry.from_latest_publication( ) coordinator_agent = CoordinatorAgent( - provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, registry=registry, ) ritual_id = 1 # got this from a side channel diff --git a/examples/testnet_simple_taco.py b/examples/testnet_simple_taco.py index 79c7b7bcb..e1887becc 100644 --- a/examples/testnet_simple_taco.py +++ b/examples/testnet_simple_taco.py @@ -35,7 +35,7 @@ registry = ContractRegistry.from_latest_publication( ) coordinator_agent = CoordinatorAgent( - provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, registry=registry, ) ritual_id = 1 # got this from a side channel diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index f7681908e..bc0546d6a 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -138,7 +138,7 @@ class NucypherTokenActor(BaseActor): return self.__token_agent self.__token_agent = ContractAgency.get_agent( NucypherTokenAgent, - provider_uri=self.eth_provider_uri, + blockchain_endpoint=self.eth_provider_uri, registry=self.registry, ) return self.__token_agent @@ -205,7 +205,7 @@ class Operator(BaseActor): self.application_agent = ContractAgency.get_agent( TACoApplicationAgent, - provider_uri=eth_endpoint, + blockchain_endpoint=eth_endpoint, registry=self.registry, ) @@ -216,13 +216,13 @@ class Operator(BaseActor): self.child_application_agent = ContractAgency.get_agent( TACoChildApplicationAgent, registry=registry, - provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, ) self.coordinator_agent = ContractAgency.get_agent( CoordinatorAgent, registry=registry, - provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, ) # track active onchain rituals @@ -746,7 +746,9 @@ class PolicyAuthor(NucypherTokenActor): def __init__(self, eth_endpoint: str, *args, **kwargs): super().__init__(*args, **kwargs) self.application_agent = ContractAgency.get_agent( - TACoApplicationAgent, registry=self.registry, provider_uri=eth_endpoint + TACoApplicationAgent, + registry=self.registry, + blockchain_endpoint=eth_endpoint, ) def create_policy(self, *args, **kwargs): diff --git a/nucypher/blockchain/eth/agents.py b/nucypher/blockchain/eth/agents.py index 78ad39a22..edd9ab08c 100644 --- a/nucypher/blockchain/eth/agents.py +++ b/nucypher/blockchain/eth/agents.py @@ -81,7 +81,7 @@ class EthereumContractAgent: def __init__( self, - provider_uri: str, + blockchain_endpoint: str, registry: ContractRegistry, contract: Optional[Contract] = None, transaction_gas: Optional[Wei] = None, @@ -91,7 +91,7 @@ class EthereumContractAgent: self.registry = registry self.blockchain = BlockchainInterfaceFactory.get_or_create_interface( - blockchain_endpoint=provider_uri + blockchain_endpoint=blockchain_endpoint ) if not contract: # Fetch the contract @@ -847,13 +847,13 @@ class ContractAgency: cls, agent_class: Type[types.Agent], registry: Optional[ContractRegistry], - provider_uri: Optional[str], + blockchain_endpoint: Optional[str], contract_version: Optional[str] = None, ) -> types.Agent: if not issubclass(agent_class, EthereumContractAgent): raise TypeError("Only agent subclasses can be used from the agency.") - if not provider_uri: + if not blockchain_endpoint: raise ValueError( "Need to specify a blockchain provider URI in order to get an agent from the ContractAgency" ) @@ -871,7 +871,7 @@ class ContractAgency: types.Agent, agent_class( registry=registry, - provider_uri=provider_uri, + blockchain_endpoint=blockchain_endpoint, ), ) cls.__agents[registry_id] = cls.__agents.get(registry_id, dict()) @@ -900,7 +900,7 @@ class ContractAgency: agent: EthereumContractAgent = cls.get_agent( agent_class=agent_class, registry=registry, - provider_uri=provider_uri, + blockchain_endpoint=provider_uri, contract_version=contract_version ) return agent diff --git a/nucypher/blockchain/eth/trackers/bonding.py b/nucypher/blockchain/eth/trackers/bonding.py index ffe0051ac..cb8c8e409 100644 --- a/nucypher/blockchain/eth/trackers/bonding.py +++ b/nucypher/blockchain/eth/trackers/bonding.py @@ -20,7 +20,7 @@ class OperatorBondedTracker(SimpleTask): application_agent = ContractAgency.get_agent( TACoApplicationAgent, registry=self._ursula.registry, - provider_uri=self._ursula.eth_endpoint, + blockchain_endpoint=self._ursula.eth_endpoint, ) # use TACo root since unbonding happens at root and not child (more immediate this way) staking_provider_address = application_agent.get_staking_provider_from_operator( diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index 31d46fe3d..2bc2ec2ab 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -478,7 +478,7 @@ class Bob(Character): if polygon_endpoint: coordinator_agent = ContractAgency.get_agent( CoordinatorAgent, - provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, registry=ContractRegistry.from_latest_publication( domain=self.domain, ), @@ -1182,7 +1182,7 @@ class Ursula(Teacher, Character, Operator): return cls.from_seed_and_stake_info(seed_uri=seed_uri, *args, **kwargs) @classmethod - def seednode_for_network(cls, network: str, provider_uri: str) -> "Ursula": + def seednode_for_network(cls, network: str, eth_endpoint: str) -> "Ursula": """Returns a default seednode ursula for a given network.""" try: url = TEACHER_NODES[network][0] @@ -1190,7 +1190,7 @@ class Ursula(Teacher, Character, Operator): raise ValueError(f'"{network}" is not a known network.') except IndexError: raise ValueError(f'No default seednodes available for "{network}".') - ursula = cls.from_seed_and_stake_info(seed_uri=url, provider_uri=provider_uri) + ursula = cls.from_seed_and_stake_info(seed_uri=url, eth_endpoint=eth_endpoint) return ursula @classmethod @@ -1213,7 +1213,7 @@ class Ursula(Teacher, Character, Operator): try: teacher = cls.from_seed_and_stake_info( seed_uri=teacher_uri, - provider_uri=provider_uri, + eth_endpoint=provider_uri, minimum_stake=min_stake, network_middleware=network_middleware, registry=registry, @@ -1237,14 +1237,14 @@ class Ursula(Teacher, Character, Operator): def from_seed_and_stake_info( cls, seed_uri: str, - provider_uri: str, + eth_endpoint: str, registry: ContractRegistry = None, minimum_stake: int = 0, network_middleware: RestMiddleware = None, ) -> Union["Ursula", "NodeSprout"]: if network_middleware is None: network_middleware = RestMiddleware( - registry=registry, eth_endpoint=provider_uri + registry=registry, eth_endpoint=eth_endpoint ) # Parse node URI @@ -1273,7 +1273,9 @@ class Ursula(Teacher, Character, Operator): # Check the node's stake (optional) if minimum_stake > 0 and staking_provider_address: application_agent = ContractAgency.get_agent( - TACoApplicationAgent, provider_uri=provider_uri, registry=registry + TACoApplicationAgent, + blockchain_endpoint=eth_endpoint, + registry=registry, ) seednode_stake = application_agent.get_authorized_stake( staking_provider=staking_provider_address diff --git a/nucypher/cli/commands/taco.py b/nucypher/cli/commands/taco.py index c0a44fdd9..3cd97009b 100644 --- a/nucypher/cli/commands/taco.py +++ b/nucypher/cli/commands/taco.py @@ -134,7 +134,7 @@ def active_providers(general_config, registry_options): general_config=general_config ) application_agent = ContractAgency.get_agent( - TACoApplicationAgent, registry=registry, provider_uri=provider_uri + TACoApplicationAgent, registry=registry, blockchain_endpoint=provider_uri ) ( total_staked, diff --git a/nucypher/cli/painting/status.py b/nucypher/cli/painting/status.py index af2d8bed0..53d15e694 100644 --- a/nucypher/cli/painting/status.py +++ b/nucypher/cli/painting/status.py @@ -6,7 +6,7 @@ from nucypher.blockchain.eth.agents import ( def paint_application_contract_status(emitter, registry, provider_uri): application_agent = ContractAgency.get_agent( - TACoApplicationAgent, registry=registry, provider_uri=provider_uri + TACoApplicationAgent, registry=registry, blockchain_endpoint=provider_uri ) blockchain = application_agent.blockchain diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index d1d2dc0b2..733c9077d 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -1049,7 +1049,7 @@ class Teacher: the case that the "staking provider" isn't "staking" (e.g., all her tokens have been slashed). """ application_agent = ContractAgency.get_agent( - TACoApplicationAgent, provider_uri=provider_uri, registry=registry + TACoApplicationAgent, blockchain_endpoint=provider_uri, registry=registry ) # type: TACoApplicationAgent staking_provider_address = application_agent.get_staking_provider_from_operator(operator_address=self.operator_address) if staking_provider_address == NULL_ADDRESS: @@ -1064,7 +1064,7 @@ class Teacher: As a follow-up, this checks that the staking provider is, indeed, staking. """ application_agent = ContractAgency.get_agent( - TACoApplicationAgent, registry=registry, provider_uri=eth_endpoint + TACoApplicationAgent, registry=registry, blockchain_endpoint=eth_endpoint ) # type: TACoApplicationAgent is_staking = application_agent.is_authorized(staking_provider=self.checksum_address) # checksum address here is staking provider return is_staking diff --git a/nucypher/policy/payment.py b/nucypher/policy/payment.py index 94d034e79..5a9e390dd 100644 --- a/nucypher/policy/payment.py +++ b/nucypher/policy/payment.py @@ -85,7 +85,9 @@ class ContractPayment(PaymentMethod, ABC): if self.__agent: return self.__agent # get cache agent = ContractAgency.get_agent( - agent_class=self._AGENT, provider_uri=self.provider, registry=self.registry + agent_class=self._AGENT, + blockchain_endpoint=self.provider, + registry=self.registry, ) self.__agent = agent return self.__agent # set cache diff --git a/nucypher/utilities/prometheus/collector.py b/nucypher/utilities/prometheus/collector.py index c10e58072..63484b317 100644 --- a/nucypher/utilities/prometheus/collector.py +++ b/nucypher/utilities/prometheus/collector.py @@ -183,7 +183,7 @@ class StakingProviderMetricsCollector(BaseMetricsCollector): application_agent = ContractAgency.get_agent( TACoApplicationAgent, registry=self.contract_registry, - provider_uri=self.eth_endpoint, + blockchain_endpoint=self.eth_endpoint, ) authorized = application_agent.get_authorized_stake( staking_provider=self.staking_provider_address diff --git a/scripts/hooks/nucypher_agents.py b/scripts/hooks/nucypher_agents.py index e2b7f2dc7..830dff201 100644 --- a/scripts/hooks/nucypher_agents.py +++ b/scripts/hooks/nucypher_agents.py @@ -73,7 +73,7 @@ def nucypher_agents( taco_application_agent = ContractAgency.get_agent( agent_class=TACoApplicationAgent, registry=staking_registry, - provider_uri=eth_endpoint, + blockchain_endpoint=eth_endpoint, ) # type: TACoApplicationAgent registry = ContractRegistry.from_latest_publication( @@ -83,19 +83,19 @@ def nucypher_agents( taco_child_application_agent = ContractAgency.get_agent( agent_class=TACoChildApplicationAgent, registry=registry, - provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, ) # type: TACoChildApplicationAgent coordinator_agent = ContractAgency.get_agent( agent_class=CoordinatorAgent, registry=registry, - provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, ) # type: CoordinatorAgent subscription_manager_agent = ContractAgency.get_agent( agent_class=SubscriptionManagerAgent, registry=registry, - provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, ) # type: SubscriptionManagerAgent message = ( diff --git a/scripts/hooks/nucypher_dkg.py b/scripts/hooks/nucypher_dkg.py index f9fcc3589..3ea529b09 100644 --- a/scripts/hooks/nucypher_dkg.py +++ b/scripts/hooks/nucypher_dkg.py @@ -161,13 +161,13 @@ def nucypher_dkg( coordinator_agent = ContractAgency.get_agent( agent_class=CoordinatorAgent, registry=registry, - provider_uri=polygon_endpoint, + blockchain_endpoint=polygon_endpoint, ) # type: CoordinatorAgent application_agent = ContractAgency.get_agent( agent_class=TACoApplicationAgent, registry=registry, - provider_uri=eth_endpoint, + blockchain_endpoint=eth_endpoint, ) # type: TACoApplicationAgent # diff --git a/tests/acceptance/agents/test_contract_agency.py b/tests/acceptance/agents/test_contract_agency.py index 9fe139c33..e893c6803 100644 --- a/tests/acceptance/agents/test_contract_agency.py +++ b/tests/acceptance/agents/test_contract_agency.py @@ -7,12 +7,12 @@ def test_get_agent_with_different_registries(test_registry): application_agent_1 = ContractAgency.get_agent( TACoApplicationAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) application_agent_2 = ContractAgency.get_agent( TACoApplicationAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) assert application_agent_2.registry == application_agent_1.registry == test_registry assert application_agent_2 is application_agent_1 diff --git a/tests/acceptance/agents/test_token_agent.py b/tests/acceptance/agents/test_token_agent.py index 89fb607c5..ee9755c3f 100644 --- a/tests/acceptance/agents/test_token_agent.py +++ b/tests/acceptance/agents/test_token_agent.py @@ -13,7 +13,9 @@ from tests.constants import TEST_ETH_PROVIDER_URI @pytest.fixture(scope='module') def agent(testerchain, test_registry) -> NucypherTokenAgent: token_agent = ContractAgency.get_agent( - NucypherTokenAgent, registry=test_registry, provider_uri=TEST_ETH_PROVIDER_URI + NucypherTokenAgent, + registry=test_registry, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) return token_agent diff --git a/tests/acceptance/cli/test_ursula_init.py b/tests/acceptance/cli/test_ursula_init.py index 47972e77a..40ac51d23 100644 --- a/tests/acceptance/cli/test_ursula_init.py +++ b/tests/acceptance/cli/test_ursula_init.py @@ -73,7 +73,7 @@ def mock_funded_account_password_keystore( taco_application_agent = ContractAgency.get_agent( TACoApplicationAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) taco_application_agent.bond_operator( staking_provider=provider_address, diff --git a/tests/acceptance/conditions/conftest.py b/tests/acceptance/conditions/conftest.py index fc10b5b17..6dbbbb518 100644 --- a/tests/acceptance/conditions/conftest.py +++ b/tests/acceptance/conditions/conftest.py @@ -52,7 +52,7 @@ def erc20_evm_condition_balanceof(testerchain, test_registry): token = ContractAgency.get_agent( NucypherTokenAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) condition = ContractCondition( contract_address=token.contract.address, @@ -115,7 +115,7 @@ def subscription_manager_get_policy_zeroized_policy_struct_condition( subscription_manager = ContractAgency.get_agent( SubscriptionManagerAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) condition = ContractCondition( contract_address=subscription_manager.contract.address, @@ -135,7 +135,7 @@ def subscription_manager_is_active_policy_condition(testerchain, test_registry): subscription_manager = ContractAgency.get_agent( SubscriptionManagerAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) condition = ContractCondition( contract_address=subscription_manager.contract.address, @@ -157,7 +157,7 @@ def custom_context_variable_erc20_condition( token = ContractAgency.get_agent( NucypherTokenAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) condition = ContractCondition( contract_address=token.contract.address, diff --git a/tests/acceptance/conditions/test_conditions.py b/tests/acceptance/conditions/test_conditions.py index a35cdf720..3047a68f4 100644 --- a/tests/acceptance/conditions/test_conditions.py +++ b/tests/acceptance/conditions/test_conditions.py @@ -346,7 +346,7 @@ def test_subscription_manager_get_policy_policy_struct_condition_key_tuple_evalu subscription_manager = ContractAgency.get_agent( SubscriptionManagerAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) # test "sponsor" key (owner is the same as sponsor for this policy) @@ -464,7 +464,7 @@ def test_subscription_manager_get_policy_policy_struct_condition_index_and_value subscription_manager = ContractAgency.get_agent( SubscriptionManagerAgent, registry=test_registry, - provider_uri=TEST_POLYGON_PROVIDER_URI, + blockchain_endpoint=TEST_POLYGON_PROVIDER_URI, ) # test "sponsor" index not equal to correct value diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index 971695c64..6c9ace724 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -375,7 +375,9 @@ def staking_providers( def coordinator_agent(testerchain, test_registry): """Creates a coordinator agent""" coordinator = ContractAgency.get_agent( - CoordinatorAgent, registry=test_registry, provider_uri=TEST_ETH_PROVIDER_URI + CoordinatorAgent, + registry=test_registry, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) return coordinator @@ -385,7 +387,7 @@ def taco_application_agent(test_registry): _taco_application_agent = ContractAgency.get_agent( TACoApplicationAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) return _taco_application_agent @@ -396,7 +398,7 @@ def taco_child_application_agent(testerchain, test_registry): _taco_child_application_agent = ContractAgency.get_agent( TACoChildApplicationAgent, registry=test_registry, - provider_uri=TEST_ETH_PROVIDER_URI, + blockchain_endpoint=TEST_ETH_PROVIDER_URI, ) return _taco_child_application_agent diff --git a/tests/metrics/grant_availability.py b/tests/metrics/grant_availability.py index f501b493a..2f7b34776 100755 --- a/tests/metrics/grant_availability.py +++ b/tests/metrics/grant_availability.py @@ -197,7 +197,7 @@ def aggregate_nodes(provider_uri: str) -> Tuple[Set[Ursula], Set[Ursula]]: if DEFAULT_SEEDNODE_URIS: for uri in DEFAULT_SEEDNODE_URIS: ursula = Ursula.from_seed_and_stake_info( - seed_uri=uri, provider_uri=provider_uri + seed_uri=uri, eth_endpoint=provider_uri ) seednodes.add(ursula) @@ -205,7 +205,7 @@ def aggregate_nodes(provider_uri: str) -> Tuple[Set[Ursula], Set[Ursula]]: if HANDPICKED_URSULA_URIS: for uri in HANDPICKED_URSULA_URIS: ursula = Ursula.from_seed_and_stake_info( - seed_uri=uri, provider_uri=provider_uri + seed_uri=uri, eth_endpoint=provider_uri ) ursulas.add(ursula) diff --git a/tests/unit/test_ritualist.py b/tests/unit/test_ritualist.py index 51b74e46e..7e749fc5a 100644 --- a/tests/unit/test_ritualist.py +++ b/tests/unit/test_ritualist.py @@ -10,7 +10,7 @@ from tests.mock.coordinator import MockCoordinatorAgent @pytest.fixture(scope="module") def agent(mock_contract_agency) -> MockCoordinatorAgent: coordinator_agent: CoordinatorAgent = mock_contract_agency.get_agent( - CoordinatorAgent, registry=None, provider_uri=MOCK_ETH_PROVIDER_URI + CoordinatorAgent, registry=None, blockchain_endpoint=MOCK_ETH_PROVIDER_URI ) return coordinator_agent From fbed56665e0ba5547afcabd6a59632ae2edb82aa Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 15:13:30 -0400 Subject: [PATCH 26/63] Update renames for call to from_seednode_metadata. --- nucypher/network/nodes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index 733c9077d..3be878688 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -384,7 +384,7 @@ class Learner: seed_node = self.node_class.from_seednode_metadata( seednode_metadata=seednode_metadata, network_middleware=self.network_middleware, - provider_uri=self.eth_endpoint, + eth_endpoint=self.eth_endpoint, ) except Exception as e: # TODO: log traceback here? @@ -759,7 +759,7 @@ class Learner: try: node_on_the_other_end = self.node_class.from_seednode_metadata( stranger.seed_node_metadata(), - provider_uri=self.provider_uri, + eth_endpoint=self.eth_endpoint, network_middleware=self.network_middleware, ) if node_on_the_other_end != stranger: From 05fba15c1e9cbd888c8c3ba8e15e26b07eca3734 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 15:22:44 -0400 Subject: [PATCH 27/63] More renames of provider_uri to blockchain_/eth_ endpoint. --- nucypher/blockchain/eth/actors.py | 36 +++++++++++------------- nucypher/blockchain/eth/agents.py | 4 +-- nucypher/characters/lawful.py | 4 +-- nucypher/cli/actions/configure.py | 6 ++-- nucypher/cli/commands/taco.py | 28 +++++++++--------- nucypher/cli/commands/ursula.py | 6 ++-- nucypher/cli/painting/status.py | 4 +-- nucypher/cli/utils.py | 6 ++-- nucypher/config/characters.py | 20 ++++++------- nucypher/network/nodes.py | 8 +++--- nucypher/utilities/networking.py | 22 +++++++-------- tests/metrics/grant_availability.py | 8 +++--- tests/unit/test_external_ip_utilities.py | 20 ++++++------- tests/utils/ursula.py | 8 ++++-- 14 files changed, 91 insertions(+), 89 deletions(-) diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index bc0546d6a..b48eab710 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -30,7 +30,6 @@ from nucypher.acumen.nicknames import Nickname from nucypher.blockchain.eth.agents import ( ContractAgency, CoordinatorAgent, - NucypherTokenAgent, TACoApplicationAgent, TACoChildApplicationAgent, ) @@ -43,7 +42,6 @@ from nucypher.blockchain.eth.registry import ( ContractRegistry, ) from nucypher.blockchain.eth.signers import Signer -from nucypher.blockchain.eth.token import NU from nucypher.blockchain.eth.trackers import dkg from nucypher.blockchain.eth.trackers.bonding import OperatorBondedTracker from nucypher.blockchain.eth.utils import truncate_checksum_address @@ -132,23 +130,23 @@ class NucypherTokenActor(BaseActor): super().__init__(registry=registry, **kwargs) self.__token_agent = None - @property - def token_agent(self): - if self.__token_agent: - return self.__token_agent - self.__token_agent = ContractAgency.get_agent( - NucypherTokenAgent, - blockchain_endpoint=self.eth_provider_uri, - registry=self.registry, - ) - return self.__token_agent - - @property - def token_balance(self) -> NU: - """Return this actor's current token balance""" - balance = int(self.token_agent.get_balance(address=self.checksum_address)) - nu_balance = NU(balance, 'NuNit') - return nu_balance + # @property + # def token_agent(self): + # if self.__token_agent: + # return self.__token_agent + # self.__token_agent = ContractAgency.get_agent( + # NucypherTokenAgent, + # blockchain_endpoint=self.eth_provider_uri, # TODO this is fishy - and doesn't seem needed? + # registry=self.registry, + # ) + # return self.__token_agent + # + # @property + # def token_balance(self) -> NU: + # """Return this actor's current token balance""" + # balance = int(self.token_agent.get_balance(address=self.checksum_address)) + # nu_balance = NU(balance, 'NuNit') + # return nu_balance class Operator(BaseActor): diff --git a/nucypher/blockchain/eth/agents.py b/nucypher/blockchain/eth/agents.py index edd9ab08c..ebdab8d4a 100644 --- a/nucypher/blockchain/eth/agents.py +++ b/nucypher/blockchain/eth/agents.py @@ -891,7 +891,7 @@ class ContractAgency: cls, contract_name: str, registry: ContractRegistry, - provider_uri: str, + blockchain_endpoint: str, contract_version: Optional[str] = None, ) -> EthereumContractAgent: agent_name: str = cls._contract_name_to_agent_name(name=contract_name) @@ -900,7 +900,7 @@ class ContractAgency: agent: EthereumContractAgent = cls.get_agent( agent_class=agent_class, registry=registry, - blockchain_endpoint=provider_uri, + blockchain_endpoint=blockchain_endpoint, contract_version=contract_version ) return agent diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index 2bc2ec2ab..63f0058fe 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -1198,7 +1198,7 @@ class Ursula(Teacher, Character, Operator): cls, teacher_uri: str, min_stake: int, - provider_uri: str, + eth_endpoint: str, registry: ContractRegistry = None, network_middleware: RestMiddleware = None, retry_attempts: int = 2, @@ -1213,7 +1213,7 @@ class Ursula(Teacher, Character, Operator): try: teacher = cls.from_seed_and_stake_info( seed_uri=teacher_uri, - eth_endpoint=provider_uri, + eth_endpoint=eth_endpoint, minimum_stake=min_stake, network_middleware=network_middleware, registry=registry, diff --git a/nucypher/cli/actions/configure.py b/nucypher/cli/actions/configure.py index 228ea0b95..68bc30a95 100644 --- a/nucypher/cli/actions/configure.py +++ b/nucypher/cli/actions/configure.py @@ -126,13 +126,13 @@ def handle_invalid_configuration_file(emitter: StdoutEmitter, def collect_operator_ip_address( - emitter: StdoutEmitter, network: str, provider_uri: str, force: bool = False + emitter: StdoutEmitter, network: str, eth_endpoint: str, force: bool = False ) -> str: # From node swarm try: message = "Detecting external IP address automatically" emitter.message(message, verbosity=2) - ip = determine_external_ip_address(network=network, provider_uri=provider_uri) + ip = determine_external_ip_address(network=network, eth_endpoint=eth_endpoint) except UnknownIPAddress: if force: raise @@ -159,7 +159,7 @@ def perform_startup_ip_check(emitter: StdoutEmitter, ursula: Ursula, force: bool external_ip = determine_external_ip_address( network=ursula.domain, known_nodes=ursula.known_nodes, - provider_uri=ursula.eth_endpoint, + eth_endpoint=ursula.eth_endpoint, ) except UnknownIPAddress: message = 'Cannot automatically determine external IP address' diff --git a/nucypher/cli/commands/taco.py b/nucypher/cli/commands/taco.py index 3cd97009b..79a3df42f 100644 --- a/nucypher/cli/commands/taco.py +++ b/nucypher/cli/commands/taco.py @@ -30,9 +30,9 @@ from nucypher.cli.utils import ( ) from nucypher.utilities.events import generate_events_csv_filepath -option_provider_uri = click.option( - "--provider-uri", - "provider_uri", +option_blockchain_endpoint = click.option( + "--blockchain-endpoint", + "blockchain_endpoint", help="Blockchain provider's URI i.e. 'file:///path/to/geth.ipc'", type=click.STRING, required=True, @@ -50,8 +50,8 @@ option_network = click.option( class RegistryOptions: __option_name__ = "registry_options" - def __init__(self, provider_uri, poa, registry_filepath, light, network): - self.provider_uri = provider_uri + def __init__(self, blockchain_endpoint, poa, registry_filepath, light, network): + self.blockchain_endpoint = blockchain_endpoint self.poa = poa self.registry_filepath = registry_filepath self.light = light @@ -62,7 +62,7 @@ class RegistryOptions: registry = get_registry( network=self.network, registry_filepath=self.registry_filepath ) - return emitter, registry, self.provider_uri + return emitter, registry, self.blockchain_endpoint group_registry_options = group_options( @@ -71,7 +71,7 @@ group_registry_options = group_options( light=option_light, registry_filepath=option_registry_filepath, network=option_network, - provider_uri=option_provider_uri, + blockchain_endpoint=option_blockchain_endpoint, ) option_csv = click.option( @@ -117,11 +117,11 @@ def taco(): @group_general_config def application_info(general_config, registry_options): """Overall information for the TACo Application.""" - emitter, registry, provider_uri = registry_options.setup( + emitter, registry, blockchain_endpoint = registry_options.setup( general_config=general_config ) paint_application_contract_status( - emitter=emitter, registry=registry, provider_uri=provider_uri + emitter=emitter, registry=registry, eth_endpoint=blockchain_endpoint ) @@ -130,11 +130,11 @@ def application_info(general_config, registry_options): @group_general_config def active_providers(general_config, registry_options): """List of active stakers for the TACo Application""" - emitter, registry, provider_uri = registry_options.setup( + emitter, registry, blockchain_endpoint = registry_options.setup( general_config=general_config ) application_agent = ContractAgency.get_agent( - TACoApplicationAgent, registry=registry, blockchain_endpoint=provider_uri + TACoApplicationAgent, registry=registry, blockchain_endpoint=blockchain_endpoint ) ( total_staked, @@ -194,12 +194,14 @@ def events( ), ) - emitter, registry, provider_uri = registry_options.setup( + emitter, registry, blockchain_endpoint = registry_options.setup( general_config=general_config ) contract_agent = ContractAgency.get_agent_by_contract_name( - contract_name=contract_name, registry=registry, provider_uri=provider_uri + contract_name=contract_name, + registry=registry, + blockchain_endpoint=blockchain_endpoint, ) if from_block is None: diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index 7dd14c883..17214ded4 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -180,7 +180,7 @@ class UrsulaConfigOptions: emitter, network=self.domain, force=force, - provider_uri=self.eth_endpoint, + eth_endpoint=self.eth_endpoint, ) return UrsulaConfiguration.generate( @@ -282,7 +282,7 @@ class UrsulaCharacterOptions: URSULA = make_cli_character( character_config=ursula_config, emitter=emitter, - provider_uri=ursula_config.eth_endpoint, + eth_endpoint=ursula_config.eth_endpoint, min_stake=self.min_stake, teacher_uri=self.teacher_uri, unlock_keystore=not self.config_options.dev, @@ -483,7 +483,7 @@ def config(general_config, config_options, config_file, force, action): emitter=emitter, network=config_options.domain, force=force, - provider_uri=config_options.eth_endpoint, + eth_endpoint=config_options.eth_endpoint, ) config_options.rest_host = rest_host if action == "migrate": diff --git a/nucypher/cli/painting/status.py b/nucypher/cli/painting/status.py index 53d15e694..ba15681b0 100644 --- a/nucypher/cli/painting/status.py +++ b/nucypher/cli/painting/status.py @@ -4,9 +4,9 @@ from nucypher.blockchain.eth.agents import ( ) -def paint_application_contract_status(emitter, registry, provider_uri): +def paint_application_contract_status(emitter, registry, eth_endpoint): application_agent = ContractAgency.get_agent( - TACoApplicationAgent, registry=registry, blockchain_endpoint=provider_uri + TACoApplicationAgent, registry=registry, blockchain_endpoint=eth_endpoint ) blockchain = application_agent.blockchain diff --git a/nucypher/cli/utils.py b/nucypher/cli/utils.py index bd037017d..305e95ae3 100644 --- a/nucypher/cli/utils.py +++ b/nucypher/cli/utils.py @@ -45,7 +45,7 @@ def setup_emitter(general_config, banner: str = None) -> StdoutEmitter: def make_cli_character( character_config, emitter, - provider_uri: str, + eth_endpoint: str, unlock_keystore: bool = True, unlock_signer: bool = True, teacher_uri: str = None, @@ -82,14 +82,14 @@ def make_cli_character( min_stake=min_stake, network_middleware=character_config.network_middleware, registry=character_config.registry, - provider_uri=provider_uri, + eth_endpoint=eth_endpoint, ) sage_nodes.append(maybe_sage_node) CHARACTER = character_config( known_nodes=sage_nodes, network_middleware=character_config.network_middleware, - eth_endpoint=provider_uri, + eth_endpoint=eth_endpoint, **config_args, ) diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index 904bfc797..d4d91a890 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -74,21 +74,21 @@ class UrsulaConfiguration(CharacterConfiguration): # Polygon polygon_chain_id = taco_network.polygon_chain.id - polygon_provider_uris = self.condition_provider_uris.get(polygon_chain_id, []) - if not polygon_provider_uris: - self.condition_provider_uris[polygon_chain_id] = polygon_provider_uris + polygon_endpoints = self.condition_provider_uris.get(polygon_chain_id, []) + if not polygon_endpoints: + self.condition_provider_uris[polygon_chain_id] = polygon_endpoints - if self.polygon_endpoint not in polygon_provider_uris: - polygon_provider_uris.append(self.polygon_endpoint) + if self.polygon_endpoint not in polygon_endpoints: + polygon_endpoints.append(self.polygon_endpoint) # Ethereum staking_chain_id = taco_network.eth_chain.id - staking_provider_uris = self.condition_provider_uris.get(staking_chain_id, []) - if not staking_provider_uris: - self.condition_provider_uris[staking_chain_id] = staking_provider_uris + staking_chain_endpoints = self.condition_provider_uris.get(staking_chain_id, []) + if not staking_chain_endpoints: + self.condition_provider_uris[staking_chain_id] = staking_chain_endpoints - if self.eth_endpoint not in staking_provider_uris: - staking_provider_uris.append(self.eth_endpoint) + if self.eth_endpoint not in staking_chain_endpoints: + staking_chain_endpoints.append(self.eth_endpoint) @classmethod def address_from_filepath(cls, filepath: Path) -> str: diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index 3be878688..947b0a612 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -360,7 +360,7 @@ class Learner: maybe_sage_node = self.node_class.from_teacher_uri( teacher_uri=uri, min_stake=0, - provider_uri=self.eth_endpoint, + eth_endpoint=self.eth_endpoint, network_middleware=self.network_middleware, registry=self.registry, ) @@ -1041,7 +1041,7 @@ class Teacher: return bytes(response) def _operator_is_bonded( - self, provider_uri: str, registry: ContractRegistry + self, eth_endpoint: str, registry: ContractRegistry ) -> bool: """ This method assumes the stamp's signature is valid and accurate. @@ -1049,7 +1049,7 @@ class Teacher: the case that the "staking provider" isn't "staking" (e.g., all her tokens have been slashed). """ application_agent = ContractAgency.get_agent( - TACoApplicationAgent, blockchain_endpoint=provider_uri, registry=registry + TACoApplicationAgent, blockchain_endpoint=eth_endpoint, registry=registry ) # type: TACoApplicationAgent staking_provider_address = application_agent.get_staking_provider_from_operator(operator_address=self.operator_address) if staking_provider_address == NULL_ADDRESS: @@ -1089,7 +1089,7 @@ class Teacher: # On-chain staking check, if registry is present if registry: if not self._operator_is_bonded( - registry=registry, provider_uri=eth_endpoint + registry=registry, eth_endpoint=eth_endpoint ): # <-- Blockchain CALL message = f"Operator {self.operator_address} is not bonded to staking provider {self.checksum_address}" self.log.debug(message) diff --git a/nucypher/utilities/networking.py b/nucypher/utilities/networking.py index c30d79725..f8a797c70 100644 --- a/nucypher/utilities/networking.py +++ b/nucypher/utilities/networking.py @@ -69,13 +69,13 @@ def _request(url: str, certificate=None) -> Union[str, None]: def _request_from_node( teacher, - provider_uri: str, + eth_endpoint: str, client: Optional[NucypherMiddlewareClient] = None, timeout: int = 2, log: Logger = IP_DETECTION_LOGGER, ) -> Union[str, None]: if not client: - client = NucypherMiddlewareClient(eth_endpoint=provider_uri) + client = NucypherMiddlewareClient(eth_endpoint=eth_endpoint) try: response = client.get( node_or_sprout=teacher, path="ping", timeout=timeout @@ -101,7 +101,7 @@ def _request_from_node( def get_external_ip_from_default_teacher( network: str, - provider_uri: str, + eth_endpoint: str, registry: Optional[ContractRegistry] = None, log: Logger = IP_DETECTION_LOGGER, ) -> Union[str, None]: @@ -122,10 +122,10 @@ def get_external_ip_from_default_teacher( for teacher_uri in TEACHER_NODES[network]: try: teacher = Ursula.from_teacher_uri( - teacher_uri=teacher_uri, provider_uri=provider_uri, min_stake=0 + teacher_uri=teacher_uri, eth_endpoint=eth_endpoint, min_stake=0 ) # TODO: Handle customized min stake here. # TODO: Pass registry here to verify stake (not essential here since it's a hardcoded node) - external_ip = _request_from_node(teacher=teacher, provider_uri=provider_uri) + external_ip = _request_from_node(teacher=teacher, eth_endpoint=eth_endpoint) # Found a reachable teacher, return from loop if external_ip: break @@ -142,7 +142,7 @@ def get_external_ip_from_default_teacher( def get_external_ip_from_known_nodes( known_nodes: FleetSensor, - provider_uri: str, + eth_endpoint: str, sample_size: int = 3, log: Logger = IP_DETECTION_LOGGER, ) -> Union[str, None]: @@ -154,9 +154,9 @@ def get_external_ip_from_known_nodes( if len(known_nodes) < sample_size: return # There are too few known nodes sample = random.sample(list(known_nodes), sample_size) - client = NucypherMiddlewareClient(eth_endpoint=provider_uri) + client = NucypherMiddlewareClient(eth_endpoint=eth_endpoint) for node in sample: - ip = _request_from_node(teacher=node, client=client, provider_uri=provider_uri) + ip = _request_from_node(teacher=node, client=client, eth_endpoint=eth_endpoint) if ip: log.info(f'Fetched external IP address ({ip}) from randomly selected known nodes.') return ip @@ -171,7 +171,7 @@ def get_external_ip_from_centralized_source(log: Logger = IP_DETECTION_LOGGER) - def determine_external_ip_address( - network: str, provider_uri: str, known_nodes: FleetSensor = None + network: str, eth_endpoint: str, known_nodes: FleetSensor = None ) -> str: """ Attempts to automatically determine the external IP in the following priority: @@ -186,13 +186,13 @@ def determine_external_ip_address( # primary source if known_nodes: rest_host = get_external_ip_from_known_nodes( - known_nodes=known_nodes, provider_uri=provider_uri + known_nodes=known_nodes, eth_endpoint=eth_endpoint ) # fallback 1 if not rest_host: rest_host = get_external_ip_from_default_teacher( - network=network, provider_uri=provider_uri + network=network, eth_endpoint=eth_endpoint ) # fallback 2 diff --git a/tests/metrics/grant_availability.py b/tests/metrics/grant_availability.py index 2f7b34776..cb3b98465 100755 --- a/tests/metrics/grant_availability.py +++ b/tests/metrics/grant_availability.py @@ -190,14 +190,14 @@ def setup(): GlobalLoggerSettings.set_log_level('info') -def aggregate_nodes(provider_uri: str) -> Tuple[Set[Ursula], Set[Ursula]]: +def aggregate_nodes(eth_endpoint: str) -> Tuple[Set[Ursula], Set[Ursula]]: """generates ursulas from URIs used in grant metrics collection""" seednodes = set() if DEFAULT_SEEDNODE_URIS: for uri in DEFAULT_SEEDNODE_URIS: ursula = Ursula.from_seed_and_stake_info( - seed_uri=uri, eth_endpoint=provider_uri + seed_uri=uri, eth_endpoint=eth_endpoint ) seednodes.add(ursula) @@ -205,7 +205,7 @@ def aggregate_nodes(provider_uri: str) -> Tuple[Set[Ursula], Set[Ursula]]: if HANDPICKED_URSULA_URIS: for uri in HANDPICKED_URSULA_URIS: ursula = Ursula.from_seed_and_stake_info( - seed_uri=uri, eth_endpoint=provider_uri + seed_uri=uri, eth_endpoint=eth_endpoint ) ursulas.add(ursula) @@ -214,6 +214,6 @@ def aggregate_nodes(provider_uri: str) -> Tuple[Set[Ursula], Set[Ursula]]: if __name__ == '__main__': setup() - seednodes, ursulas = aggregate_nodes(provider_uri=ETHEREUM_PROVIDER_URI) + seednodes, ursulas = aggregate_nodes(eth_endpoint=ETHEREUM_PROVIDER_URI) alice = make_alice(known_nodes=seednodes) collect(alice=alice, ursulas=ursulas) diff --git a/tests/unit/test_external_ip_utilities.py b/tests/unit/test_external_ip_utilities.py index aba0b4894..046d62d5c 100644 --- a/tests/unit/test_external_ip_utilities.py +++ b/tests/unit/test_external_ip_utilities.py @@ -109,7 +109,7 @@ def test_get_external_ip_from_empty_known_nodes(mock_requests): sensor = FleetSensor(domain=MOCK_NETWORK) assert len(sensor) == 0 get_external_ip_from_known_nodes( - known_nodes=sensor, provider_uri=MOCK_ETH_PROVIDER_URI + known_nodes=sensor, eth_endpoint=MOCK_ETH_PROVIDER_URI ) # skipped because there are no known nodes mock_requests.assert_not_called() @@ -121,7 +121,7 @@ def test_get_external_ip_from_known_nodes_with_one_known_node(mock_requests): sensor.record_fleet_state() assert len(sensor) == 1 get_external_ip_from_known_nodes( - known_nodes=sensor, provider_uri=MOCK_ETH_PROVIDER_URI + known_nodes=sensor, eth_endpoint=MOCK_ETH_PROVIDER_URI ) # skipped because there are too few known nodes mock_requests.assert_not_called() @@ -140,7 +140,7 @@ def test_get_external_ip_from_known_nodes(mock_client): # First sampled node replies get_external_ip_from_known_nodes( - known_nodes=sensor, sample_size=sample_size, provider_uri=MOCK_ETH_PROVIDER_URI + known_nodes=sensor, sample_size=sample_size, eth_endpoint=MOCK_ETH_PROVIDER_URI ) assert mock_client.call_count == 1 mock_client.call_count = 0 # reset @@ -148,7 +148,7 @@ def test_get_external_ip_from_known_nodes(mock_client): # All sampled nodes dont respond mock_client.return_value = Dummy.BadResponse get_external_ip_from_known_nodes( - known_nodes=sensor, sample_size=sample_size, provider_uri=MOCK_ETH_PROVIDER_URI + known_nodes=sensor, sample_size=sample_size, eth_endpoint=MOCK_ETH_PROVIDER_URI ) assert mock_client.call_count == sample_size @@ -169,7 +169,7 @@ def test_get_external_ip_from_known_nodes_client(mocker, mock_client): teacher_uri = TEACHER_NODES[MOCK_NETWORK][0] get_external_ip_from_known_nodes( - known_nodes=sensor, sample_size=sample_size, provider_uri=MOCK_ETH_PROVIDER_URI + known_nodes=sensor, sample_size=sample_size, eth_endpoint=MOCK_ETH_PROVIDER_URI ) assert mock_client.call_count == 1 # first node responded @@ -183,7 +183,7 @@ def test_get_external_ip_default_teacher_unreachable(mocker): # Default seednode is down mocker.patch.object(Ursula, "from_teacher_uri", side_effect=error) ip = get_external_ip_from_default_teacher( - network=MOCK_NETWORK, provider_uri=MOCK_ETH_PROVIDER_URI + network=MOCK_NETWORK, eth_endpoint=MOCK_ETH_PROVIDER_URI ) assert ip is None @@ -196,7 +196,7 @@ def test_get_external_ip_from_default_teacher(mocker, mock_client, mock_requests # "Success" ip = get_external_ip_from_default_teacher( - network=MOCK_NETWORK, provider_uri=MOCK_ETH_PROVIDER_URI + network=MOCK_NETWORK, eth_endpoint=MOCK_ETH_PROVIDER_URI ) assert ip == MOCK_IP_ADDRESS @@ -214,7 +214,7 @@ def test_get_external_ip_default_unknown_network(): # Without fleet sensor with pytest.raises(UnknownIPAddress): determine_external_ip_address( - network=unknown_domain, provider_uri=MOCK_ETH_PROVIDER_URI + network=unknown_domain, eth_endpoint=MOCK_ETH_PROVIDER_URI ) # with fleet sensor @@ -223,7 +223,7 @@ def test_get_external_ip_default_unknown_network(): determine_external_ip_address( known_nodes=sensor, network=unknown_domain, - provider_uri=MOCK_ETH_PROVIDER_URI, + eth_endpoint=MOCK_ETH_PROVIDER_URI, ) @@ -238,7 +238,7 @@ def test_get_external_ip_cascade_failure(mocker, mock_requests): with pytest.raises(UnknownIPAddress, match="External IP address detection failed"): determine_external_ip_address( - network=MOCK_NETWORK, known_nodes=sensor, provider_uri=MOCK_ETH_PROVIDER_URI + network=MOCK_NETWORK, known_nodes=sensor, eth_endpoint=MOCK_ETH_PROVIDER_URI ) first.assert_called_once() diff --git a/tests/utils/ursula.py b/tests/utils/ursula.py index df4e662ca..5ff09f3b5 100644 --- a/tests/utils/ursula.py +++ b/tests/utils/ursula.py @@ -133,13 +133,15 @@ def mock_permitted_multichain_connections(mocker) -> List[int]: def setup_multichain_ursulas(chain_ids: List[int], ursulas: List[Ursula]) -> None: base_uri = "tester://multichain.{}" base_fallback_uri = "tester://multichain.fallback.{}" - provider_uris = [base_uri.format(i) for i in range(len(chain_ids))] - fallback_provider_uris = [ + blockchain_endpoints = [base_uri.format(i) for i in range(len(chain_ids))] + fallback_blockchain_endpoints = [ base_fallback_uri.format(i) for i in range(len(chain_ids)) ] mocked_condition_providers = { cid: {HTTPProvider(uri), HTTPProvider(furi)} - for cid, uri, furi in zip(chain_ids, provider_uris, fallback_provider_uris) + for cid, uri, furi in zip( + chain_ids, blockchain_endpoints, fallback_blockchain_endpoints + ) } for ursula in ursulas: ursula.condition_providers = mocked_condition_providers From 57d683ee58f99af11c7c5aff9c0f5c2e446c9dbb Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 15:23:24 -0400 Subject: [PATCH 28/63] Update mocking of list of polygon chains. --- tests/mock/interfaces.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/mock/interfaces.py b/tests/mock/interfaces.py index 6d57eaa47..5bad91b1d 100644 --- a/tests/mock/interfaces.py +++ b/tests/mock/interfaces.py @@ -1,6 +1,3 @@ - - - from typing import Union from hexbytes import HexBytes From 1c333bddaa7187e0abd58f2da8fc1e35feae5773 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 16:42:44 -0400 Subject: [PATCH 29/63] Deprecate condition_provider_uris in favour of condition_blockchain_endpoints. --- nucypher/blockchain/eth/actors.py | 17 ++++++----- nucypher/characters/lawful.py | 4 +-- nucypher/config/characters.py | 30 +++++++++++-------- .../migrations/configuration_v7_to_v8.py | 4 +++ .../characters/test_ursula_startup.py | 2 +- 5 files changed, 35 insertions(+), 22 deletions(-) diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index b48eab710..e9ad80234 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -166,7 +166,7 @@ class Operator(BaseActor): crypto_power: CryptoPower = None, client_password: str = None, operator_address: Optional[ChecksumAddress] = None, - condition_provider_uris: Optional[Dict[int, List[str]]] = None, + condition_blockchain_endpoints: Optional[Dict[int, List[str]]] = None, publish_finalization: bool = True, # TODO: Remove this *args, **kwargs, @@ -241,7 +241,7 @@ class Operator(BaseActor): ) # used for secure decryption request channel self.condition_providers = self.connect_condition_providers( - condition_provider_uris + condition_blockchain_endpoints ) def set_provider_public_key(self) -> Union[TxReceipt, None]: @@ -265,19 +265,22 @@ class Operator(BaseActor): return provider def connect_condition_providers( - self, condition_provider_uris: Optional[Dict[int, List[str]]] = None + self, condition_blockchain_endpoints: Optional[Dict[int, List[str]]] = None ) -> DefaultDict[int, Set[HTTPProvider]]: """Multi-provider support""" - # If condition_provider_uris is None the node operator + # If condition_blockchain_endpoints is None the node operator # did not configure any additional condition providers. - condition_provider_uris = condition_provider_uris or dict() + condition_blockchain_endpoints = condition_blockchain_endpoints or dict() # These are the chains that the Operator will connect to for conditions evaluation (read-only). condition_providers = defaultdict(set) # Now, add any additional providers that were passed in. - for chain_id, condition_provider_uris in condition_provider_uris.items(): + for ( + chain_id, + condition_blockchain_endpoints, + ) in condition_blockchain_endpoints.items(): if not self._is_permitted_condition_chain(chain_id): # this is a safety check to prevent the Operator from connecting to # chains that are not supported by ursulas on the network; @@ -287,7 +290,7 @@ class Operator(BaseActor): ) providers = set() - for uri in condition_provider_uris: + for uri in condition_blockchain_endpoints: provider = self._make_condition_provider(uri) providers.add(provider) diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index 63f0058fe..584a169a9 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -819,7 +819,7 @@ class Ursula(Teacher, Character, Operator): transacting_power: Optional[TransactingPower] = None, eth_endpoint: Optional[str] = None, polygon_endpoint: Optional[str] = None, - condition_provider_uris: Optional[Dict[int, List[str]]] = None, + condition_blockchain_endpoints: Optional[Dict[int, List[str]]] = None, pre_payment_method: Optional[Union[PaymentMethod, ContractPayment]] = None, # Character abort_on_learning_error: bool = False, @@ -861,7 +861,7 @@ class Ursula(Teacher, Character, Operator): polygon_endpoint=polygon_endpoint, pre_payment_method=pre_payment_method, client_password=client_password, - condition_provider_uris=condition_provider_uris, + condition_blockchain_endpoints=condition_blockchain_endpoints, transacting_power=transacting_power, ) diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index d4d91a890..37937a7f2 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -36,7 +36,7 @@ class UrsulaConfiguration(CharacterConfiguration): keystore_path: Optional[Path] = None, rest_port: Optional[int] = None, certificate: Optional[Certificate] = None, - condition_provider_uris: Optional[Dict[str, List[str]]] = None, + condition_blockchain_endpoints: Optional[Dict[str, List[str]]] = None, *args, **kwargs, ) -> None: @@ -61,31 +61,37 @@ class UrsulaConfiguration(CharacterConfiguration): # json configurations don't allow for integer keyed dictionaries # so convert string chain id to integer - self.condition_provider_uris = dict() - if condition_provider_uris: - for chain, providers in condition_provider_uris.items(): + self.condition_blockchain_endpoints = dict() + if condition_blockchain_endpoints: + for chain, blockchain_endpoint in condition_blockchain_endpoints.items(): # convert chain from string key (for json) to integer - self.condition_provider_uris[int(chain)] = providers - self.configure_condition_provider_uris() + self.condition_blockchain_endpoints[int(chain)] = blockchain_endpoint + self.configure_condition_blockchain_endpoints() - def configure_condition_provider_uris(self) -> None: + def configure_condition_blockchain_endpoints(self) -> None: """Configure default condition provider URIs for eth and polygon network.""" taco_network = NetworksInventory.get_network(self.domain) # Polygon polygon_chain_id = taco_network.polygon_chain.id - polygon_endpoints = self.condition_provider_uris.get(polygon_chain_id, []) + polygon_endpoints = self.condition_blockchain_endpoints.get( + polygon_chain_id, [] + ) if not polygon_endpoints: - self.condition_provider_uris[polygon_chain_id] = polygon_endpoints + self.condition_blockchain_endpoints[polygon_chain_id] = polygon_endpoints if self.polygon_endpoint not in polygon_endpoints: polygon_endpoints.append(self.polygon_endpoint) # Ethereum staking_chain_id = taco_network.eth_chain.id - staking_chain_endpoints = self.condition_provider_uris.get(staking_chain_id, []) + staking_chain_endpoints = self.condition_blockchain_endpoints.get( + staking_chain_id, [] + ) if not staking_chain_endpoints: - self.condition_provider_uris[staking_chain_id] = staking_chain_endpoints + self.condition_blockchain_endpoints[ + staking_chain_id + ] = staking_chain_endpoints if self.eth_endpoint not in staking_chain_endpoints: staking_chain_endpoints.append(self.eth_endpoint) @@ -113,7 +119,7 @@ class UrsulaConfiguration(CharacterConfiguration): operator_address=self.operator_address, rest_host=self.rest_host, rest_port=self.rest_port, - condition_provider_uris=self.condition_provider_uris, + condition_blockchain_endpoints=self.condition_blockchain_endpoints, # PRE Payments # TODO: Resolve variable prefixing below (uses nested configuration fields?) diff --git a/nucypher/config/migrations/configuration_v7_to_v8.py b/nucypher/config/migrations/configuration_v7_to_v8.py index 62da58a05..794c78b76 100644 --- a/nucypher/config/migrations/configuration_v7_to_v8.py +++ b/nucypher/config/migrations/configuration_v7_to_v8.py @@ -15,6 +15,10 @@ def __migration(config: Dict) -> Dict: config["polygon_endpoint"] = config["pre_payment_provider"] del config["pre_payment_provider"] + # condition_provider_uris -> condition_blockchain_endpoints + config["condition_blockchain_endpoints"] = config["condition_provider_uris"] + del config["condition_provider_uris"] + return config diff --git a/tests/integration/characters/test_ursula_startup.py b/tests/integration/characters/test_ursula_startup.py index faac39382..1ae13479c 100644 --- a/tests/integration/characters/test_ursula_startup.py +++ b/tests/integration/characters/test_ursula_startup.py @@ -37,7 +37,7 @@ def test_goerli_and_mumbai_as_conditions_providers(lonely_ursula_maker): _ursula_who_tries_to_connect_to_an_invalid_chain = lonely_ursula_maker( quantity=1, domain="useless_domain", - condition_provider_uris={ + condition_blockchain_endpoints={ INVALID_CHAIN_ID: "this is a provider URI, but it doesn't matter what we pass here because the chain_id is invalid." }, ) From bbfda74e80d136a445dcdc3e5e6add77bd549528 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Mon, 2 Oct 2023 16:49:31 -0400 Subject: [PATCH 30/63] Add newsfragments for #3262. --- newsfragments/3262.misc.txt | 3 +++ newsfragments/3262.removal.rst | 1 + 2 files changed, 4 insertions(+) create mode 100644 newsfragments/3262.misc.txt create mode 100644 newsfragments/3262.removal.rst diff --git a/newsfragments/3262.misc.txt b/newsfragments/3262.misc.txt new file mode 100644 index 000000000..a62add568 --- /dev/null +++ b/newsfragments/3262.misc.txt @@ -0,0 +1,3 @@ +Since the L2 network is always implied based on the TACo network connected to, we no longer need those config/parameters across the codebase, it can be inferred. +Each Character now takes optional eth and polygon endpoints. +Remove various usages of redundant L2 values. General rename from ``[eth_]provider[_uri]`` to ``[blockchain/eth/polygon]_endpoint``. diff --git a/newsfragments/3262.removal.rst b/newsfragments/3262.removal.rst new file mode 100644 index 000000000..68cc6e776 --- /dev/null +++ b/newsfragments/3262.removal.rst @@ -0,0 +1 @@ +Deprecate configuration config/parameters ``pre-payment-network``, ``coordinator_uri`` since the L2 network is implied based on TACo network used. From b2b265b03fe72e0061a93b29bb5440952e83a134 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 11:15:19 -0400 Subject: [PATCH 31/63] Re-add unused `operator_signature_from_metadata` parameter, some concerns about usage - something to address later. --- nucypher/characters/lawful.py | 1 + 1 file changed, 1 insertion(+) diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index 584a169a9..8899569cb 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -817,6 +817,7 @@ class Ursula(Teacher, Character, Operator): operator_address: Optional[ChecksumAddress] = None, client_password: Optional[str] = None, transacting_power: Optional[TransactingPower] = None, + operator_signature_from_metadata=NOT_SIGNED, eth_endpoint: Optional[str] = None, polygon_endpoint: Optional[str] = None, condition_blockchain_endpoints: Optional[Dict[int, List[str]]] = None, From 8c2c358e1b598106c5c9554d5574c4abe5123c92 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 11:19:30 -0400 Subject: [PATCH 32/63] Initialize blockchain connection for both eth_endpoint and polygon_endpoint using common code. --- nucypher/config/base.py | 50 +++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/nucypher/config/base.py b/nucypher/config/base.py index e86b07ba7..b7de59250 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -438,36 +438,11 @@ class CharacterConfiguration(BaseConfiguration): # Decentralized # - # TODO should this be an iteration on [eth_endpoint, polygon_endpoint]? - self.gas_strategy = gas_strategy self.max_gas_price = max_gas_price # gwei - is_initialized = BlockchainInterfaceFactory.is_interface_initialized( - blockchain_endpoint=self.eth_endpoint - ) - if not is_initialized and eth_endpoint: - BlockchainInterfaceFactory.initialize_interface( - blockchain_endpoint=self.eth_endpoint, - poa=self.poa, - light=self.is_light, - emitter=emitter, - gas_strategy=self.gas_strategy, - max_gas_price=self.max_gas_price, - ) - else: - self.log.warn( - f"Using existing blockchain interface connection ({self.eth_endpoint})." - ) - # TODO: this is potential fix for multichain connection, if we want to use it build it out into a loop - # for uri in eth_provider_uri (list of uris fom config): - BlockchainInterfaceFactory.get_or_create_interface( - blockchain_endpoint=polygon_endpoint, - poa=self.poa, - light=self.is_light, - emitter=emitter, - gas_strategy=self.gas_strategy, - max_gas_price=self.max_gas_price, + self._connect_to_endpoints( + emitter=emitter, endpoints=[self.eth_endpoint, self.polygon_endpoint] ) if not self.registry: @@ -531,6 +506,27 @@ class CharacterConfiguration(BaseConfiguration): super().__init__(filepath=self.config_file_location, config_root=self.config_root) + def _connect_to_endpoints(self, emitter, endpoints: List[str]) -> None: + for endpoint in endpoints: + if endpoint and endpoint != NO_BLOCKCHAIN_CONNECTION: + is_initialized = BlockchainInterfaceFactory.is_interface_initialized( + blockchain_endpoint=endpoint + ) + + if not is_initialized: + BlockchainInterfaceFactory.initialize_interface( + blockchain_endpoint=endpoint, + poa=self.poa, + light=self.is_light, + emitter=emitter, + gas_strategy=self.gas_strategy, + max_gas_price=self.max_gas_price, + ) + else: + self.log.warn( + f"Using existing blockchain interface connection ({endpoint})." + ) + def __call__(self, **character_kwargs): return self.produce(**character_kwargs) From 2d2b67e5d2de04ad6e16938ca5eb71001b0b1f80 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 12:50:54 -0400 Subject: [PATCH 33/63] Rename of various functions/constants from NetworksInventory to use domain instead of network. Rename variables obtained by calling into NetworksInventory to use domain instead of network. Rename NuCypherNetworkName CLI validation object into NuCypherDomainName. --- .../finnegans-wake-demo-l2.py | 8 ++-- examples/pre/heartbeat_demo/alicia.py | 6 +-- examples/pre/heartbeat_demo/doctor.py | 4 +- examples/testnet_compound_multichain_taco.py | 6 +-- examples/testnet_simple_taco.py | 6 +-- nucypher/blockchain/eth/actors.py | 2 +- nucypher/blockchain/eth/networks.py | 41 ++++++++----------- nucypher/blockchain/eth/registry.py | 4 +- nucypher/cli/actions/select.py | 22 +++++----- nucypher/cli/commands/taco.py | 16 ++++---- nucypher/cli/commands/ursula.py | 6 +-- nucypher/cli/literature.py | 2 +- nucypher/cli/options.py | 4 +- nucypher/cli/types.py | 12 +++--- nucypher/config/base.py | 15 +++---- nucypher/config/characters.py | 6 +-- .../migrations/configuration_v5_to_v6.py | 6 +-- nucypher/network/nodes.py | 2 +- nucypher/policy/payment.py | 10 ++--- scripts/hooks/nucypher_agents.py | 20 ++++----- scripts/hooks/nucypher_dkg.py | 4 +- .../characters/test_decentralized_grant.py | 2 +- tests/acceptance/conftest.py | 10 ++--- tests/conftest.py | 10 ++--- tests/fixtures.py | 2 +- .../cli/actions/test_select_client_account.py | 2 +- .../cli/actions/test_select_network.py | 12 +++--- .../config/test_keystore_integration.py | 4 +- tests/integration/config/test_storages.py | 2 +- tests/integration/conftest.py | 10 ++--- tests/metrics/grant_availability.py | 8 ++-- tests/unit/test_teacher_nodes.py | 6 +-- tests/utils/registry.py | 16 ++++---- 33 files changed, 133 insertions(+), 153 deletions(-) diff --git a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py index 8e913c36a..e04dab5b3 100644 --- a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py +++ b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py @@ -44,7 +44,7 @@ print("\n************** Setup **************\n") # Network # ########### -TACO_NETWORK = "lynx" +TACO_DOMAIN = "lynx" ##################### # Bob the BUIDLer ## @@ -53,7 +53,7 @@ TACO_NETWORK = "lynx" # Then, there was bob. Bob learns about the # rest of the network from the seednode. bob = Bob( - domain=TACO_NETWORK, + domain=TACO_DOMAIN, eth_endpoint=L1_PROVIDER, ) @@ -81,14 +81,14 @@ wallet.unlock_account(account=ALICE_ADDRESS, password=password) # This is Alice's PRE payment method. pre_payment_method = SubscriptionManagerPayment( - network=TACO_NETWORK, blockchain_endpoint=L2_PROVIDER + domain=TACO_DOMAIN, blockchain_endpoint=L2_PROVIDER ) # This is Alice. alice = Alice( checksum_address=ALICE_ADDRESS, signer=wallet, - domain=TACO_NETWORK, + domain=TACO_DOMAIN, eth_endpoint=L1_PROVIDER, polygon_endpoint=L2_PROVIDER, pre_payment_method=pre_payment_method, diff --git a/examples/pre/heartbeat_demo/alicia.py b/examples/pre/heartbeat_demo/alicia.py index 8156751b8..0cbfb1fa4 100644 --- a/examples/pre/heartbeat_demo/alicia.py +++ b/examples/pre/heartbeat_demo/alicia.py @@ -57,7 +57,7 @@ try: except KeyError: raise RuntimeError("Missing environment variables to run demo.") -TACO_NETWORK = "lynx" +TACO_DOMAIN = "lynx" ####################################### @@ -83,14 +83,14 @@ wallet.unlock_account(account=ALICE_ADDRESS, password=password) # This is Alice's PRE payment method. pre_payment_method = SubscriptionManagerPayment( - network=TACO_NETWORK, blockchain_endpoint=L2_PROVIDER + domain=TACO_DOMAIN, blockchain_endpoint=L2_PROVIDER ) # This is Alicia. alicia = Alice( checksum_address=ALICE_ADDRESS, signer=wallet, - domain=TACO_NETWORK, + domain=TACO_DOMAIN, eth_endpoint=L1_PROVIDER, polygon_endpoint=L2_PROVIDER, pre_payment_method=pre_payment_method, diff --git a/examples/pre/heartbeat_demo/doctor.py b/examples/pre/heartbeat_demo/doctor.py index c2594d6c5..21b1cd286 100644 --- a/examples/pre/heartbeat_demo/doctor.py +++ b/examples/pre/heartbeat_demo/doctor.py @@ -27,7 +27,7 @@ except KeyError: raise RuntimeError("Missing environment variables to run demo.") -TACO_NETWORK = "lynx" +TACO_DOMAIN = "lynx" # To create a Bob, we need the doctor's private keys previously generated. from doctor_keys import get_doctor_privkeys # noqa: E402 @@ -43,7 +43,7 @@ power_ups = [enc_power, sig_power] print("Creating the Doctor ...") doctor = Bob( - domain=TACO_NETWORK, + domain=TACO_DOMAIN, crypto_power_ups=power_ups, eth_endpoint=L1_PROVIDER, ) diff --git a/examples/testnet_compound_multichain_taco.py b/examples/testnet_compound_multichain_taco.py index 21947be0b..9638cb08b 100644 --- a/examples/testnet_compound_multichain_taco.py +++ b/examples/testnet_compound_multichain_taco.py @@ -20,7 +20,7 @@ GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] -taco_network = NetworksInventory.get_network("lynx") +taco_domain = NetworksInventory.from_domain_name("lynx") polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] @@ -31,7 +31,7 @@ polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] print("--------- Threshold Encryption ---------") registry = ContractRegistry.from_latest_publication( - domain=taco_network.name, + domain=taco_domain.name, ) coordinator_agent = CoordinatorAgent( @@ -100,7 +100,7 @@ print(f"\nEncrypted message:\n{bytes(threshold_message_kit).hex()}") print("--------- Threshold Decryption ---------") bob = Bob( - domain=taco_network.name, + domain=taco_domain.name, eth_endpoint=eth_endpoint, polygon_endpoint=polygon_endpoint, registry=registry, diff --git a/examples/testnet_simple_taco.py b/examples/testnet_simple_taco.py index e1887becc..500cf5b36 100644 --- a/examples/testnet_simple_taco.py +++ b/examples/testnet_simple_taco.py @@ -20,7 +20,7 @@ GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] -taco_network = NetworksInventory.get_network("lynx") +taco_domain = NetworksInventory.from_domain_name("lynx") polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] @@ -31,7 +31,7 @@ polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] print("--------- Threshold Encryption ---------") registry = ContractRegistry.from_latest_publication( - domain=taco_network.name, + domain=taco_domain.name, ) coordinator_agent = CoordinatorAgent( @@ -77,7 +77,7 @@ print(f"\nEncrypted message:\n{bytes(threshold_message_kit).hex()}") print("--------- Threshold Decryption ---------") bob = Bob( - domain=taco_network.name, + domain=taco_domain.name, eth_endpoint=eth_endpoint, polygon_endpoint=polygon_endpoint, registry=registry, diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index e9ad80234..4d3572641 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -93,7 +93,7 @@ class BaseActor: self.transacting_power = transacting_power self.registry = registry self.network = domain - self.taco_network = NetworksInventory.get_network(self.network) + self.taco_domain = NetworksInventory.from_domain_name(self.network) self._saved_receipts = list() # track receipts of transmitted transactions def __repr__(self): diff --git a/nucypher/blockchain/eth/networks.py b/nucypher/blockchain/eth/networks.py index 21164a7fb..8087e804a 100644 --- a/nucypher/blockchain/eth/networks.py +++ b/nucypher/blockchain/eth/networks.py @@ -1,5 +1,5 @@ from enum import Enum -from typing import List, NamedTuple +from typing import NamedTuple from nucypher.config.constants import TEMPORARY_DOMAIN @@ -22,7 +22,7 @@ class PolygonChain(ChainInfo, Enum): TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) -class TACoNetwork(NamedTuple): +class TACoDomain(NamedTuple): name: str eth_chain: EthChain polygon_chain: PolygonChain @@ -31,22 +31,22 @@ class TACoNetwork(NamedTuple): return self.eth_chain != EthChain.MAINNET -class UnrecognizedNetwork(RuntimeError): - """Raised when a provided network name is not recognized.""" +class UnrecognizedDomain(RuntimeError): + """Raised when a provided domain name is not recognized.""" class NetworksInventory: - MAINNET = TACoNetwork("mainnet", EthChain.MAINNET, PolygonChain.POLYGON) + MAINNET = TACoDomain("mainnet", EthChain.MAINNET, PolygonChain.POLYGON) # Testnets - ORYX = TACoNetwork("oryx", EthChain.GOERLI, PolygonChain.POLYGON) - LYNX = TACoNetwork("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) - TAPIR = TACoNetwork("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) + ORYX = TACoDomain("oryx", EthChain.GOERLI, PolygonChain.POLYGON) + LYNX = TACoDomain("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) + TAPIR = TACoDomain("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) # TODO did Ibex even use a PolyNetwork? - IBEX = TACoNetwork( + IBEX = TACoDomain( "ibex", EthChain.GOERLI, PolygonChain.MUMBAI ) # this is required for configuration file migrations (backwards compatibility) - SUPPORTED_NETWORKS = [ + SUPPORTED_DOMAINS = [ MAINNET, ORYX, LYNX, @@ -54,22 +54,17 @@ class NetworksInventory: IBEX, ] - SUPPORTED_NETWORK_NAMES = [network.name for network in SUPPORTED_NETWORKS] + SUPPORTED_DOMAIN_NAMES = [network.name for network in SUPPORTED_DOMAINS] # TODO not needed once merged with registry changes - POLYGON_CHAINS = [network.polygon_chain.name for network in SUPPORTED_NETWORKS] + POLYGON_CHAINS = [network.polygon_chain.name for network in SUPPORTED_DOMAINS] - DEFAULT_NETWORK_NAME: str = MAINNET.name + DEFAULT_DOMAIN_NAME: str = MAINNET.name @classmethod - def get_network(cls, network_name: str) -> TACoNetwork: - for network in cls.SUPPORTED_NETWORKS: - if network.name == network_name: - return network + def from_domain_name(cls, domain: str) -> TACoDomain: + for taco_domain in cls.SUPPORTED_DOMAINS: + if taco_domain.name == domain: + return taco_domain - raise UnrecognizedNetwork(f"{network_name} is not a recognized network.") - - @classmethod - def get_network_names(cls) -> List[str]: - networks = [network.name for network in cls.SUPPORTED_NETWORKS] - return networks + raise UnrecognizedDomain(f"{domain} is not a recognized domain.") diff --git a/nucypher/blockchain/eth/registry.py b/nucypher/blockchain/eth/registry.py index ad1adad09..51d2fb6ee 100644 --- a/nucypher/blockchain/eth/registry.py +++ b/nucypher/blockchain/eth/registry.py @@ -34,10 +34,10 @@ class RegistrySource(ABC): """Raised when there are no available registry sources""" def __init__(self, domain: str, *args, **kwargs): - if domain not in NetworksInventory.SUPPORTED_NETWORK_NAMES: + if domain not in NetworksInventory.SUPPORTED_DOMAIN_NAMES: raise ValueError( f"{self.__class__.__name__} not available for domain '{domain}'. " - f"Valid options are: {', '.join(list(NetworksInventory.SUPPORTED_NETWORK_NAMES))}" + f"Valid options are: {', '.join(list(NetworksInventory.SUPPORTED_DOMAIN_NAMES))}" ) self.domain = domain self.data = self.get() diff --git a/nucypher/cli/actions/select.py b/nucypher/cli/actions/select.py index 24e096a07..6d536fdfc 100644 --- a/nucypher/cli/actions/select.py +++ b/nucypher/cli/actions/select.py @@ -19,7 +19,7 @@ from nucypher.cli.literature import ( IGNORE_OLD_CONFIGURATION, NO_ACCOUNTS, NO_CONFIGURATIONS_ON_DISK, - SELECT_NETWORK, + SELECT_DOMAIN, SELECTED_ACCOUNT, ) from nucypher.config.base import CharacterConfiguration @@ -40,7 +40,7 @@ def select_client_account( registry: ContractRegistry = None, show_matic_balance: bool = False, show_staking: bool = False, - network: str = None, + domain: str = None, poa: bool = None, ) -> str: """ @@ -71,15 +71,15 @@ def select_client_account( ) if signer_uri and not signer: - testnet = network != NetworksInventory.MAINNET.name + testnet = domain != NetworksInventory.MAINNET.name signer = Signer.from_signer_uri(signer_uri, testnet=testnet) # Display accounts info if show_staking: # Lazy registry fetching if not registry: - if not network: + if not domain: raise ValueError("Pass network name or registry; Got neither.") - registry = ContractRegistry.from_latest_publication(domain=network) + registry = ContractRegistry.from_latest_publication(domain=domain) enumerated_accounts = dict(enumerate(signer.accounts)) if len(enumerated_accounts) < 1: @@ -115,19 +115,19 @@ def select_client_account( return chosen_account -def select_network(emitter: StdoutEmitter, message: Optional[str] = None) -> str: +def select_domain(emitter: StdoutEmitter, message: Optional[str] = None) -> str: """Interactively select a network from nucypher networks inventory list""" emitter.message(message=message or str(), color="yellow") - network_list = NetworksInventory.SUPPORTED_NETWORK_NAMES - rows = [[n] for n in network_list] + domain_list = NetworksInventory.SUPPORTED_DOMAIN_NAMES + rows = [[n] for n in domain_list] emitter.echo(tabulate(rows, showindex="always")) choice = click.prompt( - SELECT_NETWORK, + SELECT_DOMAIN, default=0, type=click.IntRange(0, len(rows) - 1), ) - network = network_list[choice] - return network + domain = domain_list[choice] + return domain def select_config_file(emitter: StdoutEmitter, diff --git a/nucypher/cli/commands/taco.py b/nucypher/cli/commands/taco.py index 79a3df42f..4a08fd6d4 100644 --- a/nucypher/cli/commands/taco.py +++ b/nucypher/cli/commands/taco.py @@ -38,11 +38,11 @@ option_blockchain_endpoint = click.option( required=True, ) -option_network = click.option( - "--network", - help="TACo Network", +option_domain = click.option( + "--domain", + help="TACo Domain", type=click.STRING, - default=click.Choice(NetworksInventory.SUPPORTED_NETWORK_NAMES), + default=click.Choice(NetworksInventory.SUPPORTED_DOMAIN_NAMES), required=True, ) @@ -50,17 +50,17 @@ option_network = click.option( class RegistryOptions: __option_name__ = "registry_options" - def __init__(self, blockchain_endpoint, poa, registry_filepath, light, network): + def __init__(self, blockchain_endpoint, poa, registry_filepath, light, domain): self.blockchain_endpoint = blockchain_endpoint self.poa = poa self.registry_filepath = registry_filepath self.light = light - self.network = network + self.domain = domain def setup(self, general_config) -> tuple: emitter = setup_emitter(general_config) registry = get_registry( - network=self.network, registry_filepath=self.registry_filepath + network=self.domain, registry_filepath=self.registry_filepath ) return emitter, registry, self.blockchain_endpoint @@ -70,7 +70,7 @@ group_registry_options = group_options( poa=option_poa, light=option_light, registry_filepath=option_registry_filepath, - network=option_network, + domain=option_domain, blockchain_endpoint=option_blockchain_endpoint, ) diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index 17214ded4..34d5daf2b 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -20,7 +20,7 @@ from nucypher.cli.actions.configure import ( from nucypher.cli.actions.select import ( select_client_account, select_config_file, - select_network, + select_domain, ) from nucypher.cli.config import group_general_config from nucypher.cli.literature import ( @@ -341,9 +341,9 @@ def init(general_config, config_options, force, config_root, key_material): ), ) if not config_options.domain: - config_options.domain = select_network( + config_options.domain = select_domain( emitter, - message="Select TACo Network", + message="Select TACo Domain", ) ursula_config = config_options.generate_config( emitter=emitter, config_root=config_root, force=force, key_material=key_material diff --git a/nucypher/cli/literature.py b/nucypher/cli/literature.py index 5cc3b4037..4a6024442 100644 --- a/nucypher/cli/literature.py +++ b/nucypher/cli/literature.py @@ -43,7 +43,7 @@ nucypher {init_command} """ -SELECT_NETWORK = "Select TACo Network" +SELECT_DOMAIN = "Select TACo Domain" NO_CONFIGURATIONS_ON_DISK = "No {name} configurations found. Run 'nucypher {command} init' then try again." diff --git a/nucypher/cli/options.py b/nucypher/cli/options.py index 5987d6731..179a99ddb 100644 --- a/nucypher/cli/options.py +++ b/nucypher/cli/options.py @@ -14,7 +14,7 @@ from nucypher.cli.types import ( NETWORK_PORT, PRE_PAYMENT_METHOD_CHOICES, STAKED_TOKENS_RANGE, - NuCypherNetworkName, + NuCypherDomainName, ) from nucypher.utilities.logging import Logger @@ -180,7 +180,7 @@ def option_network(required: bool = False, return click.option( '--network', help="NuCypher Network/Domain Name", - type=NuCypherNetworkName(validate=validate), + type=NuCypherDomainName(validate=validate), required=required, default=default) diff --git a/nucypher/cli/types.py b/nucypher/cli/types.py index f5c11ff88..7b5780136 100644 --- a/nucypher/cli/types.py +++ b/nucypher/cli/types.py @@ -88,21 +88,21 @@ class DecimalRange(DecimalType): return rv -class NuCypherNetworkName(click.ParamType): - name = 'nucypher_network_name' +class NuCypherDomainName(click.ParamType): + name = "nucypher_domain_name" def __init__(self, validate: bool = True): self.validate = bool(validate) def convert(self, value, param, ctx): if self.validate: - network = str(value).lower() - if network not in NetworksInventory.ETH_NETWORKS: + domain = str(value).lower() + if domain not in NetworksInventory.SUPPORTED_DOMAIN_NAMES: self.fail( - f"'{value}' is not a recognized network. Valid options are: {list(NetworksInventory.ETH_NETWORKS)}" + f"'{value}' is not a recognized domain. Valid options are: {list(NetworksInventory.SUPPORTED_DOMAIN_NAMES)}" ) else: - return network + return domain else: return value diff --git a/nucypher/config/base.py b/nucypher/config/base.py index b7de59250..17f66afc3 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -307,7 +307,7 @@ class CharacterConfiguration(BaseConfiguration): CHARACTER_CLASS = NotImplemented MNEMONIC_KEYSTORE = False - DEFAULT_DOMAIN = NetworksInventory.DEFAULT_NETWORK_NAME + DEFAULT_DOMAIN = NetworksInventory.DEFAULT_DOMAIN_NAME DEFAULT_NETWORK_MIDDLEWARE = RestMiddleware TEMP_CONFIGURATION_DIR_PREFIX = 'tmp-nucypher' SIGNER_ENVVAR = None @@ -420,7 +420,7 @@ class CharacterConfiguration(BaseConfiguration): # Learner self.domain = domain - self.taco_network = NetworksInventory.get_network(self.domain) + self.taco_domain = NetworksInventory.from_domain_name(self.domain) self.learn_on_same_thread = learn_on_same_thread self.abort_on_learning_error = abort_on_learning_error self.start_learning_now = start_learning_now @@ -459,7 +459,7 @@ class CharacterConfiguration(BaseConfiguration): self.log.info(f"Using local registry ({self.registry}).") self.signer = Signer.from_signer_uri( - self.signer_uri, testnet=self.taco_network.is_testnet() + self.signer_uri, testnet=self.taco_domain.is_testnet() ) # @@ -479,12 +479,13 @@ class CharacterConfiguration(BaseConfiguration): if not self.policy_registry_filepath: self.log.info("Fetching latest policy registry from source.") self.policy_registry = ContractRegistry.from_latest_publication( - domain=self.taco_network.name + domain=self.taco_domain.name ) else: - self.policy_registry = ContractRegistry( - filepath=self.policy_registry_filepath + source = LocalRegistrySource( + domain=self.domain, filepath=self.policy_registry_filepath ) + self.policy_registry = ContractRegistry(source=source) self.log.info( f"Using local policy registry ({self.policy_registry})." ) @@ -854,7 +855,7 @@ class CharacterConfiguration(BaseConfiguration): if pre_payment_class.ONCHAIN: # on-chain payment strategies require a blockchain connection pre_payment_strategy = pre_payment_class( - network=self.taco_network.name, + domain=self.taco_domain.name, blockchain_endpoint=self.polygon_endpoint, registry=self.policy_registry, ) diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index 37937a7f2..14ea8cf68 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -70,10 +70,10 @@ class UrsulaConfiguration(CharacterConfiguration): def configure_condition_blockchain_endpoints(self) -> None: """Configure default condition provider URIs for eth and polygon network.""" - taco_network = NetworksInventory.get_network(self.domain) + taco_domain = NetworksInventory.from_domain_name(self.domain) # Polygon - polygon_chain_id = taco_network.polygon_chain.id + polygon_chain_id = taco_domain.polygon_chain.id polygon_endpoints = self.condition_blockchain_endpoints.get( polygon_chain_id, [] ) @@ -84,7 +84,7 @@ class UrsulaConfiguration(CharacterConfiguration): polygon_endpoints.append(self.polygon_endpoint) # Ethereum - staking_chain_id = taco_network.eth_chain.id + staking_chain_id = taco_domain.eth_chain.id staking_chain_endpoints = self.condition_blockchain_endpoints.get( staking_chain_id, [] ) diff --git a/nucypher/config/migrations/configuration_v5_to_v6.py b/nucypher/config/migrations/configuration_v5_to_v6.py index 61ef2b568..7d35ee877 100644 --- a/nucypher/config/migrations/configuration_v5_to_v6.py +++ b/nucypher/config/migrations/configuration_v5_to_v6.py @@ -5,11 +5,11 @@ from nucypher.config.migrations.common import perform_migration def __migration(config: Dict) -> Dict: - taco_network = NetworksInventory.get_network(config["domain"]) + taco_domain = NetworksInventory.from_domain_name(config["domain"]) eth_provider = config["eth_provider_uri"] - eth_chain_id = taco_network.eth_chain.id + eth_chain_id = taco_domain.eth_chain.id polygon_provider = config["payment_provider"] - polygon_chain_id = taco_network.polygon_chain.id + polygon_chain_id = taco_domain.polygon_chain.id if "condition_provider_uris" in config: return config config["condition_provider_uris"] = { diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index 947b0a612..c28943aec 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -271,7 +271,7 @@ class Learner: self.learning_deferred = Deferred() self.domain = domain - self.taco_network = NetworksInventory.get_network(self.domain) + self.taco_domain = NetworksInventory.from_domain_name(self.domain) default_middleware = self.__DEFAULT_MIDDLEWARE_CLASS( registry=self.registry, eth_endpoint=self.eth_endpoint ) diff --git a/nucypher/policy/payment.py b/nucypher/policy/payment.py index 5a9e390dd..5c9f62a8f 100644 --- a/nucypher/policy/payment.py +++ b/nucypher/policy/payment.py @@ -66,16 +66,16 @@ class ContractPayment(PaymentMethod, ABC): def __init__( self, blockchain_endpoint: str, - network: str, + domain: str, registry: Optional[ContractRegistry] = None, *args, **kwargs, ): super().__init__(*args, **kwargs) - self.provider = blockchain_endpoint - self.taco_network = NetworksInventory.get_network(network) + self.blockchain_endpoint = blockchain_endpoint + self.taco_domain = NetworksInventory.from_domain_name(domain) if not registry: - registry = ContractRegistry.from_latest_publication(domain=network) + registry = ContractRegistry.from_latest_publication(domain=domain) self.registry = registry self.__agent = None # delay blockchain/registry reads until later @@ -86,7 +86,7 @@ class ContractPayment(PaymentMethod, ABC): return self.__agent # get cache agent = ContractAgency.get_agent( agent_class=self._AGENT, - blockchain_endpoint=self.provider, + blockchain_endpoint=self.blockchain_endpoint, registry=self.registry, ) self.__agent = agent diff --git a/scripts/hooks/nucypher_agents.py b/scripts/hooks/nucypher_agents.py index 830dff201..34a7d7cf4 100644 --- a/scripts/hooks/nucypher_agents.py +++ b/scripts/hooks/nucypher_agents.py @@ -42,10 +42,10 @@ emitter = StdoutEmitter(verbosity=2) @click.command() @click.option( - "--network", - "network", - help="TACo network", - type=click.Choice(NetworksInventory.SUPPORTED_NETWORK_NAMES), + "--domain", + "domain", + help="TACo domain", + type=click.Choice(NetworksInventory.SUPPORTED_DOMAIN_NAMES), default="lynx", ) @click.option( @@ -63,23 +63,19 @@ emitter = StdoutEmitter(verbosity=2) required=True, ) def nucypher_agents( - network, + domain, eth_endpoint, polygon_endpoint, ): - staking_registry = ContractRegistry.from_latest_publication(domain=network) - emitter.echo(f"NOTICE: Connecting to {network} network", color="yellow") + registry = ContractRegistry.from_latest_publication(domain=domain) + emitter.echo(f"NOTICE: Connecting to {domain} network", color="yellow") taco_application_agent = ContractAgency.get_agent( agent_class=TACoApplicationAgent, - registry=staking_registry, + registry=registry, blockchain_endpoint=eth_endpoint, ) # type: TACoApplicationAgent - registry = ContractRegistry.from_latest_publication( - domain=network - ) - taco_child_application_agent = ContractAgency.get_agent( agent_class=TACoChildApplicationAgent, registry=registry, diff --git a/scripts/hooks/nucypher_dkg.py b/scripts/hooks/nucypher_dkg.py index 3ea529b09..524db475f 100644 --- a/scripts/hooks/nucypher_dkg.py +++ b/scripts/hooks/nucypher_dkg.py @@ -154,7 +154,7 @@ def nucypher_dkg( ), ) - taco_network = NetworksInventory.get_network(network) + taco_domain = NetworksInventory.from_domain_name(network) registry = ContractRegistry.from_latest_publication( domain=network ) @@ -193,7 +193,7 @@ def nucypher_dkg( emitter.echo("--------- Initiating Ritual ---------", color="yellow") emitter.echo( - f"Commencing DKG Ritual(s) on {taco_network.polygon_chain.name} using {account_address}", + f"Commencing DKG Ritual(s) on {taco_domain.polygon_chain.name} using {account_address}", color="green", ) diff --git a/tests/acceptance/characters/test_decentralized_grant.py b/tests/acceptance/characters/test_decentralized_grant.py index 80542f403..140b5bd99 100644 --- a/tests/acceptance/characters/test_decentralized_grant.py +++ b/tests/acceptance/characters/test_decentralized_grant.py @@ -30,7 +30,7 @@ def check(policy, bob, ursulas): def test_grant_subscription_manager(alice, bob, ursulas): pre_payment_method = SubscriptionManagerPayment( - blockchain_endpoint=TEST_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN + blockchain_endpoint=TEST_ETH_PROVIDER_URI, domain=TEMPORARY_DOMAIN ) alice.pre_payment_method = pre_payment_method policy = alice.grant( diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index 6c9ace724..95b520120 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -16,7 +16,7 @@ from nucypher.blockchain.eth.networks import ( EthChain, NetworksInventory, PolygonChain, - TACoNetwork, + TACoDomain, ) from nucypher.blockchain.eth.registry import ContractRegistry, RegistrySourceManager from nucypher.blockchain.eth.signers.software import Web3Signer @@ -441,16 +441,12 @@ def mock_condition_blockchains(session_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - testing_network = TACoNetwork( + testing_network = TACoDomain( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) session_mocker.patch.object( - NetworksInventory, "get_network_names", return_value=[TEMPORARY_DOMAIN] - ) - - session_mocker.patch.object( - NetworksInventory, "get_network", return_value=testing_network + NetworksInventory, "from_domain_name", return_value=testing_network ) diff --git a/tests/conftest.py b/tests/conftest.py index d7b832df6..f36787d74 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,7 +8,7 @@ from nucypher.blockchain.eth.networks import ( EthChain, NetworksInventory, PolygonChain, - TACoNetwork, + TACoDomain, ) from nucypher.config.constants import TEMPORARY_DOMAIN from nucypher.crypto.powers import TransactingPower @@ -147,16 +147,12 @@ def mock_condition_blockchains(session_mocker): "nucypher.policy.conditions.evm._CONDITION_CHAINS", {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - testing_network = TACoNetwork( + testing_network = TACoDomain( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) session_mocker.patch.object( - NetworksInventory, "get_network_names", return_value=[TEMPORARY_DOMAIN] - ) - - session_mocker.patch.object( - NetworksInventory, "get_network", return_value=testing_network + NetworksInventory, "from_domain_name", return_value=testing_network ) diff --git a/tests/fixtures.py b/tests/fixtures.py index 4f5a48147..86f63afa2 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -323,7 +323,7 @@ def light_ursula(temp_dir_path, random_account, mocker): KeystoreSigner, "_KeystoreSigner__get_signer", return_value=random_account ) pre_payment_method = SubscriptionManagerPayment( - blockchain_endpoint=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN + blockchain_endpoint=MOCK_ETH_PROVIDER_URI, domain=TEMPORARY_DOMAIN ) mocker.patch.object( diff --git a/tests/integration/cli/actions/test_select_client_account.py b/tests/integration/cli/actions/test_select_client_account.py index 9e1fdb452..56148fd15 100644 --- a/tests/integration/cli/actions/test_select_client_account.py +++ b/tests/integration/cli/actions/test_select_client_account.py @@ -191,7 +191,7 @@ def test_select_client_account_with_balance_display( mock_stdin.line(str(selection)) selected_account = select_client_account( emitter=test_emitter, - network=TEMPORARY_DOMAIN, + domain=TEMPORARY_DOMAIN, show_matic_balance=show_matic, show_staking=show_staking, polygon_endpoint=MOCK_ETH_PROVIDER_URI, diff --git a/tests/integration/cli/actions/test_select_network.py b/tests/integration/cli/actions/test_select_network.py index a41ee2df0..09f26b39d 100644 --- a/tests/integration/cli/actions/test_select_network.py +++ b/tests/integration/cli/actions/test_select_network.py @@ -1,18 +1,18 @@ import pytest from nucypher.blockchain.eth.networks import NetworksInventory -from nucypher.cli.actions.select import select_network +from nucypher.cli.actions.select import select_domain -__NETWORKS = NetworksInventory.SUPPORTED_NETWORK_NAMES +__DOMAINS = NetworksInventory.SUPPORTED_DOMAIN_NAMES -@pytest.mark.parametrize("user_input", range(0, len(__NETWORKS) - 1)) +@pytest.mark.parametrize("user_input", range(0, len(__DOMAINS) - 1)) def test_select_network_cli_action(test_emitter, capsys, mock_stdin, user_input: int): mock_stdin.line(str(user_input)) - selection = __NETWORKS[user_input] - result = select_network(emitter=test_emitter) + selection = __DOMAINS[user_input] + result = select_domain(emitter=test_emitter) assert result == selection captured = capsys.readouterr() - for name in __NETWORKS: + for name in __DOMAINS: assert name in captured.out assert mock_stdin.empty() diff --git a/tests/integration/config/test_keystore_integration.py b/tests/integration/config/test_keystore_integration.py index 5881ae7a3..4b7388c61 100644 --- a/tests/integration/config/test_keystore_integration.py +++ b/tests/integration/config/test_keystore_integration.py @@ -74,7 +74,7 @@ def test_characters_use_keystore(temp_dir_path, testerchain): keystore.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) pre_payment_method = SubscriptionManagerPayment( - blockchain_endpoint=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN + blockchain_endpoint=MOCK_ETH_PROVIDER_URI, domain=TEMPORARY_DOMAIN ) alice = Alice( @@ -160,7 +160,7 @@ def test_ritualist(temp_dir_path, testerchain, dkg_public_key): keystore.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) pre_payment_method = SubscriptionManagerPayment( - blockchain_endpoint=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN + blockchain_endpoint=MOCK_ETH_PROVIDER_URI, domain=TEMPORARY_DOMAIN ) ursula = Ursula( diff --git a/tests/integration/config/test_storages.py b/tests/integration/config/test_storages.py index a832a7a60..cea3b0649 100644 --- a/tests/integration/config/test_storages.py +++ b/tests/integration/config/test_storages.py @@ -35,7 +35,7 @@ class BaseTestNodeStorageBackends: assert ursula == node_from_storage, "Node storage {} failed".format(node_storage) pre_payment_method = SubscriptionManagerPayment( - blockchain_endpoint=MOCK_ETH_PROVIDER_URI, network=TEMPORARY_DOMAIN + blockchain_endpoint=MOCK_ETH_PROVIDER_URI, domain=TEMPORARY_DOMAIN ) # Save more nodes diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index acb894ee6..4084c2509 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -22,7 +22,7 @@ from nucypher.blockchain.eth.networks import ( EthChain, NetworksInventory, PolygonChain, - TACoNetwork, + TACoDomain, ) from nucypher.blockchain.eth.registry import ( ContractRegistry, @@ -291,16 +291,12 @@ def mock_condition_blockchains(session_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - testing_network = TACoNetwork( + testing_network = TACoDomain( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) session_mocker.patch.object( - NetworksInventory, "get_network_names", return_value=[TEMPORARY_DOMAIN] - ) - - session_mocker.patch.object( - NetworksInventory, "get_network", return_value=testing_network + NetworksInventory, "from_domain_name", return_value=testing_network ) diff --git a/tests/metrics/grant_availability.py b/tests/metrics/grant_availability.py index cb3b98465..7e1bfe2ac 100755 --- a/tests/metrics/grant_availability.py +++ b/tests/metrics/grant_availability.py @@ -54,9 +54,9 @@ except KeyError: raise RuntimeError(message) # Alice Configuration -TACO_NETWORK: str = NetworksInventory.LYNX.name # mainnet +TACO_DOMAIN: str = NetworksInventory.LYNX.name # mainnet DEFAULT_SEEDNODE_URIS: List[str] = [ - *TEACHER_NODES[TACO_NETWORK], + *TEACHER_NODES[TACO_DOMAIN], ] INSECURE_PASSWORD: str = "METRICS_INSECURE_DEVELOPMENT_PASSWORD" TEMP_ALICE_DIR: Path = Path('/', 'tmp', 'grant-metrics') @@ -155,7 +155,7 @@ def make_alice(known_nodes: Optional[Set[Ursula]] = None): # This is Alice's PRE payment method. pre_payment_method = SubscriptionManagerPayment( - network=TACO_NETWORK, blockchain_endpoint=POLYGON_PROVIDER_URI + domain=TACO_DOMAIN, blockchain_endpoint=POLYGON_PROVIDER_URI ) wallet = Signer.from_signer_uri(f'keystore://{SIGNER_URI}') @@ -167,7 +167,7 @@ def make_alice(known_nodes: Optional[Set[Ursula]] = None): checksum_address=ALICE_ADDRESS, signer_uri=f'keystore://{SIGNER_URI}', config_root=TEMP_ALICE_DIR, - domain=TACO_NETWORK, + domain=TACO_DOMAIN, known_nodes=known_nodes, start_learning_now=False, learn_on_same_thread=True, diff --git a/tests/unit/test_teacher_nodes.py b/tests/unit/test_teacher_nodes.py index 078c3ad00..faeb0c87a 100644 --- a/tests/unit/test_teacher_nodes.py +++ b/tests/unit/test_teacher_nodes.py @@ -11,9 +11,9 @@ def mock_teacher_nodes(mocker): def test_default_teacher_seednodes_defined(): - for network_name in NetworksInventory.SUPPORTED_NETWORK_NAMES: - if network_name == NetworksInventory.IBEX.name: + for domain in NetworksInventory.SUPPORTED_DOMAIN_NAMES: + if domain == NetworksInventory.IBEX.name: # skip continue - teacher_nodes = TEACHER_NODES[network_name] + teacher_nodes = TEACHER_NODES[domain] assert len(teacher_nodes) > 0 diff --git a/tests/utils/registry.py b/tests/utils/registry.py index 3c170e0c4..90d776336 100644 --- a/tests/utils/registry.py +++ b/tests/utils/registry.py @@ -9,7 +9,7 @@ from nucypher.blockchain.eth.networks import ( EthChain, NetworksInventory, PolygonChain, - TACoNetwork, + TACoDomain, ) from nucypher.blockchain.eth.registry import ( RegistryData, @@ -22,23 +22,23 @@ from nucypher.config.constants import TEMPORARY_DOMAIN @contextmanager def mock_registry_sources(): # capture the real values - real_networks = NetworksInventory.SUPPORTED_NETWORKS - real_network_names = NetworksInventory.SUPPORTED_NETWORK_NAMES + real_domains = NetworksInventory.SUPPORTED_DOMAINS + real_domain_names = NetworksInventory.SUPPORTED_DOMAIN_NAMES real_registry_sources = RegistrySourceManager._FALLBACK_CHAIN # set the mock values - NetworksInventory.SUPPORTED_NETWORK_NAMES = [TEMPORARY_DOMAIN] - testing_network = TACoNetwork( + NetworksInventory.SUPPORTED_DOMAIN_NAMES = [TEMPORARY_DOMAIN] + test_domain = TACoDomain( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - NetworksInventory.SUPPORTED_NETWORKS = [testing_network] + NetworksInventory.SUPPORTED_DOMAINS = [test_domain] RegistrySourceManager._FALLBACK_CHAIN = (MockRegistrySource,) yield # run the test # restore the real values - NetworksInventory.SUPPORTED_NETWORKS = real_networks - NetworksInventory.SUPPORTED_NETWORK_NAMES = real_network_names + NetworksInventory.SUPPORTED_DOMAINS = real_domains + NetworksInventory.SUPPORTED_DOMAIN_NAMES = real_domain_names RegistrySourceManager._FALLBACK_CHAIN = real_registry_sources From 0ca3303b9509a912e0a1abc0ff439e522e32f6b7 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 12:54:07 -0400 Subject: [PATCH 34/63] Remove IBEX as a supported domain. Update IBEX TACoDomain to use None for PolygonChain since it never used polygon. --- nucypher/blockchain/eth/networks.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/nucypher/blockchain/eth/networks.py b/nucypher/blockchain/eth/networks.py index 8087e804a..7a78771e3 100644 --- a/nucypher/blockchain/eth/networks.py +++ b/nucypher/blockchain/eth/networks.py @@ -41,9 +41,8 @@ class NetworksInventory: ORYX = TACoDomain("oryx", EthChain.GOERLI, PolygonChain.POLYGON) LYNX = TACoDomain("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) TAPIR = TACoDomain("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) - # TODO did Ibex even use a PolyNetwork? IBEX = TACoDomain( - "ibex", EthChain.GOERLI, PolygonChain.MUMBAI + "ibex", EthChain.GOERLI, None ) # this is required for configuration file migrations (backwards compatibility) SUPPORTED_DOMAINS = [ @@ -51,7 +50,6 @@ class NetworksInventory: ORYX, LYNX, TAPIR, - IBEX, ] SUPPORTED_DOMAIN_NAMES = [network.name for network in SUPPORTED_DOMAINS] From e11a200bc258268c57639c6f20f0cb4256f70d26 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 13:01:07 -0400 Subject: [PATCH 35/63] Unskip test_domains integration tests. --- tests/integration/learning/test_domains.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/tests/integration/learning/test_domains.py b/tests/integration/learning/test_domains.py index 1feb69a12..e7a9a9e50 100644 --- a/tests/integration/learning/test_domains.py +++ b/tests/integration/learning/test_domains.py @@ -9,7 +9,7 @@ from nucypher.network.nodes import TEACHER_NODES from tests.utils.ursula import make_ursulas -@pytest.mark.skip +@pytest.mark.usefixtures("test_registry_source_manager") def test_learner_learns_about_domains_separately(lonely_ursula_maker, caplog): hero_learner, other_first_domain_learner = lonely_ursula_maker( domain="nucypher1.test_suite", quantity=2 @@ -52,7 +52,6 @@ def test_learner_learns_about_domains_separately(lonely_ursula_maker, caplog): assert _nobody in new_first_domain_learner.known_nodes -@pytest.mark.skip def test_learner_restores_metadata_from_storage(lonely_ursula_maker, tmpdir): # Create a local file-based node storage root = tmpdir.mkdir("known_nodes") @@ -88,7 +87,6 @@ def test_learner_restores_metadata_from_storage(lonely_ursula_maker, tmpdir): assert set(learner.known_nodes) == {buddy} -@pytest.mark.skip def test_learner_ignores_stored_nodes_from_other_domains( lonely_ursula_maker, tmpdir, testerchain, ursula_test_config ): @@ -131,7 +129,6 @@ def test_learner_ignores_stored_nodes_from_other_domains( assert pest not in other_staker.known_nodes # But not anymore. -@pytest.mark.skip def test_learner_with_empty_storage_uses_fallback_nodes(lonely_ursula_maker, mocker): domain = "learner-domain" mocker.patch.dict(TEACHER_NODES, {domain: ("teacher-uri",)}, clear=True) @@ -145,7 +142,6 @@ def test_learner_with_empty_storage_uses_fallback_nodes(lonely_ursula_maker, moc assert set(learner.known_nodes) == {teacher} -@pytest.mark.skip def test_learner_uses_both_nodes_from_storage_and_fallback_nodes( lonely_ursula_maker, tmpdir, mocker, test_registry, ursula_test_config, testerchain ): From 206ebb4d8e26c4bfc824ae674d461736ddee0670 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 14:09:39 -0400 Subject: [PATCH 36/63] IBEX no longer a supported domain name. --- tests/unit/test_teacher_nodes.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/unit/test_teacher_nodes.py b/tests/unit/test_teacher_nodes.py index faeb0c87a..5150e6627 100644 --- a/tests/unit/test_teacher_nodes.py +++ b/tests/unit/test_teacher_nodes.py @@ -12,8 +12,5 @@ def mock_teacher_nodes(mocker): def test_default_teacher_seednodes_defined(): for domain in NetworksInventory.SUPPORTED_DOMAIN_NAMES: - if domain == NetworksInventory.IBEX.name: - # skip - continue teacher_nodes = TEACHER_NODES[domain] assert len(teacher_nodes) > 0 From aa6e53191fbc21401ab66769c53e1b5c0a713807 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 14:13:07 -0400 Subject: [PATCH 37/63] Remove use of network when dealing with NetworksInventory class. --- nucypher/blockchain/eth/networks.py | 4 ++-- tests/acceptance/conftest.py | 4 ++-- tests/conftest.py | 4 ++-- tests/integration/conftest.py | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/nucypher/blockchain/eth/networks.py b/nucypher/blockchain/eth/networks.py index 7a78771e3..1b82bef84 100644 --- a/nucypher/blockchain/eth/networks.py +++ b/nucypher/blockchain/eth/networks.py @@ -52,10 +52,10 @@ class NetworksInventory: TAPIR, ] - SUPPORTED_DOMAIN_NAMES = [network.name for network in SUPPORTED_DOMAINS] + SUPPORTED_DOMAIN_NAMES = [domain.name for domain in SUPPORTED_DOMAINS] # TODO not needed once merged with registry changes - POLYGON_CHAINS = [network.polygon_chain.name for network in SUPPORTED_DOMAINS] + POLYGON_CHAINS = [domain.polygon_chain.name for domain in SUPPORTED_DOMAINS] DEFAULT_DOMAIN_NAME: str = MAINNET.name diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index 95b520120..d1bde7755 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -441,12 +441,12 @@ def mock_condition_blockchains(session_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - testing_network = TACoDomain( + test_domain = TACoDomain( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) session_mocker.patch.object( - NetworksInventory, "from_domain_name", return_value=testing_network + NetworksInventory, "from_domain_name", return_value=test_domain ) diff --git a/tests/conftest.py b/tests/conftest.py index f36787d74..7f822dbbc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -147,12 +147,12 @@ def mock_condition_blockchains(session_mocker): "nucypher.policy.conditions.evm._CONDITION_CHAINS", {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - testing_network = TACoDomain( + test_domain = TACoDomain( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) session_mocker.patch.object( - NetworksInventory, "from_domain_name", return_value=testing_network + NetworksInventory, "from_domain_name", return_value=test_domain ) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 4084c2509..b430823b9 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -291,12 +291,12 @@ def mock_condition_blockchains(session_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - testing_network = TACoDomain( + test_domain = TACoDomain( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) session_mocker.patch.object( - NetworksInventory, "from_domain_name", return_value=testing_network + NetworksInventory, "from_domain_name", return_value=test_domain ) From 450758019669931476270dab151ad0e86ed24a56 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 14:23:43 -0400 Subject: [PATCH 38/63] Update CLI --network option to be --domain. Update subsequent function calls to use domain as well instead of network. Update some constants to use _DOMAIN instead of _NETWORK. --- .../finnegans-wake-demo-l2.py | 8 ++--- nucypher/characters/lawful.py | 10 +++--- nucypher/characters/unlawful.py | 1 - nucypher/cli/actions/configure.py | 6 ++-- nucypher/cli/actions/select.py | 4 +-- nucypher/cli/commands/ursula.py | 12 +++---- nucypher/cli/options.py | 12 ++++--- nucypher/utilities/networking.py | 14 ++++---- scripts/hooks/nucypher_agents.py | 2 +- scripts/hooks/nucypher_dkg.py | 14 ++++---- tests/acceptance/cli/test_ursula_init.py | 2 +- tests/acceptance/cli/test_ursula_run.py | 4 +-- tests/constants.py | 2 +- .../test_bob_joins_policy_and_retrieves.py | 4 +-- .../cli/actions/test_select_client_account.py | 2 +- tests/integration/cli/test_cli_config.py | 2 +- tests/integration/cli/test_mixed_config.py | 4 +-- .../cli/test_ursula_cli_ip_detection.py | 6 ++-- .../integration/cli/test_ursula_config_cli.py | 4 +-- ...ursula_local_keystore_cli_functionality.py | 2 +- .../config/test_character_configuration.py | 6 ++-- tests/unit/test_external_ip_utilities.py | 32 +++++++++---------- tests/utils/ursula.py | 4 +-- 23 files changed, 79 insertions(+), 78 deletions(-) diff --git a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py index e04dab5b3..dd81aa17f 100644 --- a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py +++ b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py @@ -40,9 +40,9 @@ except KeyError: print("\n************** Setup **************\n") -########### -# Network # -########### +########## +# DOMAIN # +########## TACO_DOMAIN = "lynx" @@ -51,7 +51,7 @@ TACO_DOMAIN = "lynx" ##################### # Then, there was bob. Bob learns about the -# rest of the network from the seednode. +# rest of the domain from the seednode. bob = Bob( domain=TACO_DOMAIN, eth_endpoint=L1_PROVIDER, diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index 8899569cb..a664fe946 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -216,7 +216,7 @@ class Alice(Character, actors.PolicyAuthor): def add_active_policy(self, active_policy): """ - Adds a Policy object that is active on the NuCypher network to Alice's + Adds a Policy object that is active on the TACo network to Alice's `active_policies` dictionary by the policy ID. """ if active_policy.hrac in self.active_policies: @@ -1183,14 +1183,14 @@ class Ursula(Teacher, Character, Operator): return cls.from_seed_and_stake_info(seed_uri=seed_uri, *args, **kwargs) @classmethod - def seednode_for_network(cls, network: str, eth_endpoint: str) -> "Ursula": + def seednode_for_domain(cls, domain: str, eth_endpoint: str) -> "Ursula": """Returns a default seednode ursula for a given network.""" try: - url = TEACHER_NODES[network][0] + url = TEACHER_NODES[domain][0] except KeyError: - raise ValueError(f'"{network}" is not a known network.') + raise ValueError(f'"{domain}" is not a known domain.') except IndexError: - raise ValueError(f'No default seednodes available for "{network}".') + raise ValueError(f'No default seednodes available for "{domain}".') ursula = cls.from_seed_and_stake_info(seed_uri=url, eth_endpoint=eth_endpoint) return ursula diff --git a/nucypher/characters/unlawful.py b/nucypher/characters/unlawful.py index bf43ae4c3..cb73cb388 100644 --- a/nucypher/characters/unlawful.py +++ b/nucypher/characters/unlawful.py @@ -57,7 +57,6 @@ class Vladimir(Ursula): bogus_pre_payment_method = FreeReencryptions() bogus_pre_payment_method.provider = Mock() bogus_pre_payment_method.agent = Mock() - bogus_pre_payment_method.network = TEMPORARY_DOMAIN bogus_pre_payment_method.agent.blockchain.client.chain_id = ( polygon_blockchain.client.chain_id ) diff --git a/nucypher/cli/actions/configure.py b/nucypher/cli/actions/configure.py index 68bc30a95..513e06e9d 100644 --- a/nucypher/cli/actions/configure.py +++ b/nucypher/cli/actions/configure.py @@ -126,13 +126,13 @@ def handle_invalid_configuration_file(emitter: StdoutEmitter, def collect_operator_ip_address( - emitter: StdoutEmitter, network: str, eth_endpoint: str, force: bool = False + emitter: StdoutEmitter, domain: str, eth_endpoint: str, force: bool = False ) -> str: # From node swarm try: message = "Detecting external IP address automatically" emitter.message(message, verbosity=2) - ip = determine_external_ip_address(network=network, eth_endpoint=eth_endpoint) + ip = determine_external_ip_address(domain=domain, eth_endpoint=eth_endpoint) except UnknownIPAddress: if force: raise @@ -157,7 +157,7 @@ def perform_startup_ip_check(emitter: StdoutEmitter, ursula: Ursula, force: bool """ try: external_ip = determine_external_ip_address( - network=ursula.domain, + domain=ursula.domain, known_nodes=ursula.known_nodes, eth_endpoint=ursula.eth_endpoint, ) diff --git a/nucypher/cli/actions/select.py b/nucypher/cli/actions/select.py index 6d536fdfc..6477a04f5 100644 --- a/nucypher/cli/actions/select.py +++ b/nucypher/cli/actions/select.py @@ -78,7 +78,7 @@ def select_client_account( if show_staking: # Lazy registry fetching if not registry: if not domain: - raise ValueError("Pass network name or registry; Got neither.") + raise ValueError("Pass domain name or registry; Got neither.") registry = ContractRegistry.from_latest_publication(domain=domain) enumerated_accounts = dict(enumerate(signer.accounts)) @@ -116,7 +116,7 @@ def select_client_account( def select_domain(emitter: StdoutEmitter, message: Optional[str] = None) -> str: - """Interactively select a network from nucypher networks inventory list""" + """Interactively select a domain from TACo domain inventory list""" emitter.message(message=message or str(), color="yellow") domain_list = NetworksInventory.SUPPORTED_DOMAIN_NAMES rows = [[n] for n in domain_list] diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index 34d5daf2b..fe1053274 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -33,6 +33,7 @@ from nucypher.cli.options import ( option_config_file, option_config_root, option_dev, + option_domain, option_dry_run, option_eth_endpoint, option_force, @@ -42,7 +43,6 @@ from nucypher.cli.options import ( option_lonely, option_max_gas_price, option_min_stake, - option_network, option_poa, option_policy_registry_filepath, option_polygon_endpoint, @@ -77,7 +77,7 @@ class UrsulaConfigOptions: operator_address: str, rest_host: str, rest_port: int, - network: str, + domain: str, registry_filepath: Path, policy_registry_filepath: Path, dev: bool, @@ -96,7 +96,7 @@ class UrsulaConfigOptions: self.operator_address = operator_address self.rest_host = rest_host self.rest_port = rest_port # FIXME: not used in generate() - self.domain = network + self.domain = domain self.registry_filepath = registry_filepath self.policy_registry_filepath = policy_registry_filepath self.dev = dev @@ -178,7 +178,7 @@ class UrsulaConfigOptions: if not self.rest_host: self.rest_host = collect_operator_ip_address( emitter, - network=self.domain, + domain=self.domain, force=force, eth_endpoint=self.eth_endpoint, ) @@ -247,7 +247,7 @@ group_config_options = group_options( help="The host port to run Ursula network services on", type=NETWORK_PORT, ), - network=option_network(), + domain=option_domain(), registry_filepath=option_registry_filepath, policy_registry_filepath=option_policy_registry_filepath, poa=option_poa, @@ -481,7 +481,7 @@ def config(general_config, config_options, config_file, force, action): if action == "ip-address": rest_host = collect_operator_ip_address( emitter=emitter, - network=config_options.domain, + domain=config_options.domain, force=force, eth_endpoint=config_options.eth_endpoint, ) diff --git a/nucypher/cli/options.py b/nucypher/cli/options.py index 179a99ddb..a95444f52 100644 --- a/nucypher/cli/options.py +++ b/nucypher/cli/options.py @@ -174,12 +174,14 @@ def option_message_kit(required: bool = False, multiple: bool = False): required=required) -def option_network(required: bool = False, - default: str = None, # NetworksInventory.DEFAULT is not a good global default (2214) - validate: bool = False): +def option_domain( + required: bool = False, + default: str = None, # NetworksInventory.DEFAULT is not a good global default (2214) + validate: bool = False, +): return click.option( - '--network', - help="NuCypher Network/Domain Name", + "--domain", + help="TACo Domain Name", type=NuCypherDomainName(validate=validate), required=required, default=default) diff --git a/nucypher/utilities/networking.py b/nucypher/utilities/networking.py index f8a797c70..272d0e267 100644 --- a/nucypher/utilities/networking.py +++ b/nucypher/utilities/networking.py @@ -100,7 +100,7 @@ def _request_from_node( def get_external_ip_from_default_teacher( - network: str, + domain: str, eth_endpoint: str, registry: Optional[ContractRegistry] = None, log: Logger = IP_DETECTION_LOGGER, @@ -111,15 +111,15 @@ def get_external_ip_from_default_teacher( base_error = 'Cannot determine IP using default teacher' - if network not in TEACHER_NODES: - log.debug(f'{base_error}: Unknown network "{network}".') + if domain not in TEACHER_NODES: + log.debug(f'{base_error}: Unknown domain "{domain}".') return node_storage = LocalFileBasedNodeStorage() Ursula.set_cert_storage_function(node_storage.store_node_certificate) external_ip = None - for teacher_uri in TEACHER_NODES[network]: + for teacher_uri in TEACHER_NODES[domain]: try: teacher = Ursula.from_teacher_uri( teacher_uri=teacher_uri, eth_endpoint=eth_endpoint, min_stake=0 @@ -134,7 +134,7 @@ def get_external_ip_from_default_teacher( continue if not external_ip: - log.debug(f'{base_error}: No teacher available for network "{network}".') + log.debug(f'{base_error}: No teacher available for domain "{domain}".') return return external_ip @@ -171,7 +171,7 @@ def get_external_ip_from_centralized_source(log: Logger = IP_DETECTION_LOGGER) - def determine_external_ip_address( - network: str, eth_endpoint: str, known_nodes: FleetSensor = None + domain: str, eth_endpoint: str, known_nodes: FleetSensor = None ) -> str: """ Attempts to automatically determine the external IP in the following priority: @@ -192,7 +192,7 @@ def determine_external_ip_address( # fallback 1 if not rest_host: rest_host = get_external_ip_from_default_teacher( - network=network, eth_endpoint=eth_endpoint + domain=domain, eth_endpoint=eth_endpoint ) # fallback 2 diff --git a/scripts/hooks/nucypher_agents.py b/scripts/hooks/nucypher_agents.py index 34a7d7cf4..285b85acc 100644 --- a/scripts/hooks/nucypher_agents.py +++ b/scripts/hooks/nucypher_agents.py @@ -68,7 +68,7 @@ def nucypher_agents( polygon_endpoint, ): registry = ContractRegistry.from_latest_publication(domain=domain) - emitter.echo(f"NOTICE: Connecting to {domain} network", color="yellow") + emitter.echo(f"NOTICE: Connecting to {domain} domain", color="yellow") taco_application_agent = ContractAgency.get_agent( agent_class=TACoApplicationAgent, diff --git a/scripts/hooks/nucypher_dkg.py b/scripts/hooks/nucypher_dkg.py index 524db475f..b364430ac 100644 --- a/scripts/hooks/nucypher_dkg.py +++ b/scripts/hooks/nucypher_dkg.py @@ -44,9 +44,9 @@ def get_transacting_power(signer: Signer): @click.command() @click.option( - "--network", - "network", - help="TACo Network", + "--domain", + "domain", + help="TACo Domain", type=click.Choice(["tapir", "lynx"]), default="lynx", ) @@ -111,7 +111,7 @@ def get_transacting_power(signer: Signer): default=False, ) def nucypher_dkg( - network, + domain, eth_endpoint, polygon_endpoint, ritual_id, @@ -154,9 +154,9 @@ def nucypher_dkg( ), ) - taco_domain = NetworksInventory.from_domain_name(network) + taco_domain = NetworksInventory.from_domain_name(domain) registry = ContractRegistry.from_latest_publication( - domain=network + domain=domain ) coordinator_agent = ContractAgency.get_agent( agent_class=CoordinatorAgent, @@ -380,7 +380,7 @@ def nucypher_dkg( # emitter.echo("--------- Threshold Decryption ---------") bob = Bob( - domain=network, + domain=domain, eth_endpoint=eth_endpoint, polygon_endpoint=polygon_endpoint, registry=registry, diff --git a/tests/acceptance/cli/test_ursula_init.py b/tests/acceptance/cli/test_ursula_init.py index 40ac51d23..8f84c9187 100644 --- a/tests/acceptance/cli/test_ursula_init.py +++ b/tests/acceptance/cli/test_ursula_init.py @@ -123,7 +123,7 @@ def test_ursula_and_local_keystore_signer_integration( init_args = ( "ursula", "init", - "--network", + "--domain", TEMPORARY_DOMAIN, "--operator-address", worker_account.address, diff --git a/tests/acceptance/cli/test_ursula_run.py b/tests/acceptance/cli/test_ursula_run.py index 635c75077..ebb64aba1 100644 --- a/tests/acceptance/cli/test_ursula_run.py +++ b/tests/acceptance/cli/test_ursula_run.py @@ -27,7 +27,7 @@ from tests.utils.ursula import select_test_port, start_pytest_ursula_services @mock.patch('glob.glob', return_value=list()) def test_missing_configuration_file(_default_filepath_mock, click_runner): - cmd_args = ('ursula', 'run', '--network', TEMPORARY_DOMAIN) + cmd_args = ("ursula", "run", "--domain", TEMPORARY_DOMAIN) result = click_runner.invoke(nucypher_cli, cmd_args, catch_exceptions=False) assert result.exit_code != 0 configuration_type = UrsulaConfiguration.NAME @@ -182,7 +182,7 @@ def test_persistent_node_storage_integration( TEST_POLYGON_PROVIDER_URI, "--operator-address", another_ursula, - "--network", + "--domain", TEMPORARY_DOMAIN, "--rest-host", MOCK_IP_ADDRESS, diff --git a/tests/constants.py b/tests/constants.py index 2ca1db4f8..ce9bcdb0c 100644 --- a/tests/constants.py +++ b/tests/constants.py @@ -37,7 +37,7 @@ NUMBER_OF_STAKING_PROVIDERS_IN_BLOCKCHAIN_TESTS = NUMBER_OF_URSULAS_IN_BLOCKCHAI # Ursulas (Operators) and Staking Providers have their own account NUMBER_OF_ETH_TEST_ACCOUNTS = NUMBER_OF_URSULAS_IN_BLOCKCHAIN_TESTS + NUMBER_OF_STAKING_PROVIDERS_IN_BLOCKCHAIN_TESTS + 10 -NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK = NUMBER_OF_URSULAS_IN_BLOCKCHAIN_TESTS +NUMBER_OF_URSULAS_IN_DEVELOPMENT_DOMAIN = NUMBER_OF_URSULAS_IN_BLOCKCHAIN_TESTS # # Local Signer Keystore diff --git a/tests/integration/characters/test_bob_joins_policy_and_retrieves.py b/tests/integration/characters/test_bob_joins_policy_and_retrieves.py index 656b3d803..a4b79b335 100644 --- a/tests/integration/characters/test_bob_joins_policy_and_retrieves.py +++ b/tests/integration/characters/test_bob_joins_policy_and_retrieves.py @@ -10,7 +10,7 @@ from nucypher.characters.lawful import Bob, Enrico from nucypher.config.constants import TEMPORARY_DOMAIN from tests.constants import ( MOCK_ETH_PROVIDER_URI, - NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK, + NUMBER_OF_URSULAS_IN_DEVELOPMENT_DOMAIN, ) from tests.utils.middleware import MockRestMiddleware @@ -60,7 +60,7 @@ def test_bob_retrieves(alice, ursulas, certificates_tempdir): # Alice creates a policy granting access to Bob # Just for fun, let's assume she distributes KFrags among Ursulas unknown to Bob - shares = NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK - 2 + shares = NUMBER_OF_URSULAS_IN_DEVELOPMENT_DOMAIN - 2 label = b'label://' + os.urandom(32) contract_end_datetime = maya.now() + datetime.timedelta(days=5) policy = alice.grant( diff --git a/tests/integration/cli/actions/test_select_client_account.py b/tests/integration/cli/actions/test_select_client_account.py index 56148fd15..9a015b2c4 100644 --- a/tests/integration/cli/actions/test_select_client_account.py +++ b/tests/integration/cli/actions/test_select_client_account.py @@ -178,7 +178,7 @@ def test_select_client_account_with_balance_display( blockchain_read_required = any((show_staking, show_matic)) if blockchain_read_required: with pytest.raises( - ValueError, match="Pass network name or registry; Got neither." + ValueError, match="Pass domain name or registry; Got neither." ): select_client_account( emitter=test_emitter, diff --git a/tests/integration/cli/test_cli_config.py b/tests/integration/cli/test_cli_config.py index dd93140c7..2dae91160 100644 --- a/tests/integration/cli/test_cli_config.py +++ b/tests/integration/cli/test_cli_config.py @@ -40,7 +40,7 @@ def test_initialize_via_cli( init_args = ( command, "init", - "--network", + "--domain", TEMPORARY_DOMAIN, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, diff --git a/tests/integration/cli/test_mixed_config.py b/tests/integration/cli/test_mixed_config.py index f127a9868..818699e2d 100644 --- a/tests/integration/cli/test_mixed_config.py +++ b/tests/integration/cli/test_mixed_config.py @@ -68,7 +68,7 @@ def test_corrupted_configuration( TEST_POLYGON_PROVIDER_URI, "--operator-address", another_ursula, - "--network", + "--domain", TEMPORARY_DOMAIN, "--rest-host", MOCK_IP_ADDRESS, @@ -103,7 +103,7 @@ def test_corrupted_configuration( init_args = ( "ursula", "init", - "--network", + "--domain", TEMPORARY_DOMAIN, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, diff --git a/tests/integration/cli/test_ursula_cli_ip_detection.py b/tests/integration/cli/test_ursula_cli_ip_detection.py index 771ed822f..23214c071 100644 --- a/tests/integration/cli/test_ursula_cli_ip_detection.py +++ b/tests/integration/cli/test_ursula_cli_ip_detection.py @@ -34,7 +34,7 @@ def test_ursula_startup_ip_checkup(click_runner, mocker): args = ( "ursula", "init", - "--network", + "--domain", TEMPORARY_DOMAIN, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, @@ -52,7 +52,7 @@ def test_ursula_startup_ip_checkup(click_runner, mocker): args = ( "ursula", "init", - "--network", + "--domain", TEMPORARY_DOMAIN, "--force", "--eth-endpoint", @@ -70,7 +70,7 @@ def test_ursula_startup_ip_checkup(click_runner, mocker): args = ( "ursula", "init", - "--network", + "--domain", TEMPORARY_DOMAIN, "--force", "--eth-endpoint", diff --git a/tests/integration/cli/test_ursula_config_cli.py b/tests/integration/cli/test_ursula_config_cli.py index df59fa0b0..3e6ae07de 100644 --- a/tests/integration/cli/test_ursula_config_cli.py +++ b/tests/integration/cli/test_ursula_config_cli.py @@ -57,7 +57,7 @@ def test_interactive_initialize_ursula(click_runner, mocker, tmpdir): init_args = ( "ursula", "init", - "--network", + "--domain", TEMPORARY_DOMAIN, "--eth-endpoint", MOCK_ETH_PROVIDER_URI, @@ -90,7 +90,7 @@ def test_initialize_custom_configuration_root( init_args = ( "ursula", "init", - "--network", + "--domain", TEMPORARY_DOMAIN, "--config-root", str(custom_filepath.absolute()), diff --git a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py index e472c8fb9..680428c2c 100644 --- a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py +++ b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py @@ -48,7 +48,7 @@ def test_ursula_init_with_local_keystore_signer( "ursula", "init", # Layer 1 - "--network", + "--domain", TEMPORARY_DOMAIN, "--eth-endpoint", testerchain.blockchain_endpoint, diff --git a/tests/integration/config/test_character_configuration.py b/tests/integration/config/test_character_configuration.py index 5ecc7b992..3ff7c2ce6 100644 --- a/tests/integration/config/test_character_configuration.py +++ b/tests/integration/config/test_character_configuration.py @@ -101,7 +101,7 @@ def test_default_character_configuration_preservation( ): configuration_class.DEFAULT_CONFIG_ROOT = Path("/tmp") fake_address = "0xdeadbeef" - network = TEMPORARY_DOMAIN + domain = TEMPORARY_DOMAIN expected_filename = ( f"{configuration_class.NAME}.{configuration_class._CONFIG_FILE_EXTENSION}" @@ -124,7 +124,7 @@ def test_default_character_configuration_preservation( character_config = configuration_class( checksum_address=fake_address, eth_endpoint=MOCK_ETH_PROVIDER_URI, - domain=network, + domain=domain, rest_host=MOCK_IP_ADDRESS, polygon_endpoint=MOCK_ETH_PROVIDER_URI, policy_registry=test_registry, @@ -135,7 +135,7 @@ def test_default_character_configuration_preservation( character_config = configuration_class( checksum_address=fake_address, eth_endpoint=MOCK_ETH_PROVIDER_URI, - domain=network, + domain=domain, policy_registry=test_registry, ) diff --git a/tests/unit/test_external_ip_utilities.py b/tests/unit/test_external_ip_utilities.py index 046d62d5c..dc33f79f5 100644 --- a/tests/unit/test_external_ip_utilities.py +++ b/tests/unit/test_external_ip_utilities.py @@ -23,7 +23,7 @@ from nucypher.utilities.networking import ( ) from tests.constants import MOCK_ETH_PROVIDER_URI, MOCK_IP_ADDRESS -MOCK_NETWORK = 'holodeck' +MOCK_DOMAIN = "holodeck" MOCK_PORT = 1111 @@ -33,7 +33,7 @@ class Dummy: # Teacher self.canonical_address = canonical_address self.checksum_address = to_checksum_address(canonical_address) self.certificate_filepath = None - self.domain = MOCK_NETWORK + self.domain = MOCK_DOMAIN class GoodResponse: status_code = 200 @@ -96,7 +96,7 @@ def mock_client(mocker): @pytest.fixture(autouse=True) def mock_default_teachers(mocker): - teachers = {MOCK_NETWORK: (f"{MOCK_IP_ADDRESS}:{MOCK_PORT}", )} + teachers = {MOCK_DOMAIN: (f"{MOCK_IP_ADDRESS}:{MOCK_PORT}",)} mocker.patch.dict(TEACHER_NODES, teachers, clear=True) @@ -106,7 +106,7 @@ def test_get_external_ip_from_centralized_source(mock_requests): def test_get_external_ip_from_empty_known_nodes(mock_requests): - sensor = FleetSensor(domain=MOCK_NETWORK) + sensor = FleetSensor(domain=MOCK_DOMAIN) assert len(sensor) == 0 get_external_ip_from_known_nodes( known_nodes=sensor, eth_endpoint=MOCK_ETH_PROVIDER_URI @@ -116,7 +116,7 @@ def test_get_external_ip_from_empty_known_nodes(mock_requests): def test_get_external_ip_from_known_nodes_with_one_known_node(mock_requests): - sensor = FleetSensor(domain=MOCK_NETWORK) + sensor = FleetSensor(domain=MOCK_DOMAIN) sensor.record_node(Dummy(b'deadbeefdeadbeefdead')) sensor.record_fleet_state() assert len(sensor) == 1 @@ -130,7 +130,7 @@ def test_get_external_ip_from_known_nodes_with_one_known_node(mock_requests): def test_get_external_ip_from_known_nodes(mock_client): # Setup FleetSensor - sensor = FleetSensor(domain=MOCK_NETWORK) + sensor = FleetSensor(domain=MOCK_DOMAIN) sample_size = 3 sensor.record_node(Dummy(b'deadbeefdeadbeefdead')) sensor.record_node(Dummy(b'deadllamadeadllamade')) @@ -156,7 +156,7 @@ def test_get_external_ip_from_known_nodes(mock_client): def test_get_external_ip_from_known_nodes_client(mocker, mock_client): # Setup FleetSensor - sensor = FleetSensor(domain=MOCK_NETWORK) + sensor = FleetSensor(domain=MOCK_DOMAIN) sample_size = 3 sensor.record_node(Dummy(b'deadbeefdeadbeefdead')) sensor.record_node(Dummy(b'deadllamadeadllamade')) @@ -166,7 +166,7 @@ def test_get_external_ip_from_known_nodes_client(mocker, mock_client): # Setup HTTP Client mocker.patch.object(Ursula, 'from_teacher_uri', return_value=Dummy(b'deadporkdeadporkdead')) - teacher_uri = TEACHER_NODES[MOCK_NETWORK][0] + teacher_uri = TEACHER_NODES[MOCK_DOMAIN][0] get_external_ip_from_known_nodes( known_nodes=sensor, sample_size=sample_size, eth_endpoint=MOCK_ETH_PROVIDER_URI @@ -183,7 +183,7 @@ def test_get_external_ip_default_teacher_unreachable(mocker): # Default seednode is down mocker.patch.object(Ursula, "from_teacher_uri", side_effect=error) ip = get_external_ip_from_default_teacher( - network=MOCK_NETWORK, eth_endpoint=MOCK_ETH_PROVIDER_URI + domain=MOCK_DOMAIN, eth_endpoint=MOCK_ETH_PROVIDER_URI ) assert ip is None @@ -191,12 +191,12 @@ def test_get_external_ip_default_teacher_unreachable(mocker): def test_get_external_ip_from_default_teacher(mocker, mock_client, mock_requests): mock_client.return_value = Dummy.GoodResponse - teacher_uri = TEACHER_NODES[MOCK_NETWORK][0] + teacher_uri = TEACHER_NODES[MOCK_DOMAIN][0] mocker.patch.object(Ursula, 'from_teacher_uri', return_value=Dummy(b'deadbeefdeadbeefdead')) # "Success" ip = get_external_ip_from_default_teacher( - network=MOCK_NETWORK, eth_endpoint=MOCK_ETH_PROVIDER_URI + domain=MOCK_DOMAIN, eth_endpoint=MOCK_ETH_PROVIDER_URI ) assert ip == MOCK_IP_ADDRESS @@ -208,13 +208,13 @@ def test_get_external_ip_from_default_teacher(mocker, mock_client, mock_requests assert endpoint == f'https://{teacher_uri}/ping' -def test_get_external_ip_default_unknown_network(): +def test_get_external_ip_default_unknown_domain(): unknown_domain = 'thisisnotarealdomain' # Without fleet sensor with pytest.raises(UnknownIPAddress): determine_external_ip_address( - network=unknown_domain, eth_endpoint=MOCK_ETH_PROVIDER_URI + domain=unknown_domain, eth_endpoint=MOCK_ETH_PROVIDER_URI ) # with fleet sensor @@ -222,7 +222,7 @@ def test_get_external_ip_default_unknown_network(): with pytest.raises(UnknownIPAddress): determine_external_ip_address( known_nodes=sensor, - network=unknown_domain, + domain=unknown_domain, eth_endpoint=MOCK_ETH_PROVIDER_URI, ) @@ -232,13 +232,13 @@ def test_get_external_ip_cascade_failure(mocker, mock_requests): second = mocker.patch('nucypher.utilities.networking.get_external_ip_from_default_teacher', return_value=None) third = mocker.patch('nucypher.utilities.networking.get_external_ip_from_centralized_source', return_value=None) - sensor = FleetSensor(domain=MOCK_NETWORK) + sensor = FleetSensor(domain=MOCK_DOMAIN) sensor.record_node(Dummy(b'deadbeefdeadbeefdead')) sensor.record_fleet_state() with pytest.raises(UnknownIPAddress, match="External IP address detection failed"): determine_external_ip_address( - network=MOCK_NETWORK, known_nodes=sensor, eth_endpoint=MOCK_ETH_PROVIDER_URI + domain=MOCK_DOMAIN, known_nodes=sensor, eth_endpoint=MOCK_ETH_PROVIDER_URI ) first.assert_called_once() diff --git a/tests/utils/ursula.py b/tests/utils/ursula.py index 5ff09f3b5..fafb9f244 100644 --- a/tests/utils/ursula.py +++ b/tests/utils/ursula.py @@ -10,7 +10,7 @@ from nucypher.characters.lawful import Ursula from nucypher.config.characters import UrsulaConfiguration from nucypher.policy.conditions.evm import _CONDITION_CHAINS from tests.constants import ( - NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK, + NUMBER_OF_URSULAS_IN_DEVELOPMENT_DOMAIN, TESTERCHAIN_CHAIN_ID, ) @@ -68,7 +68,7 @@ def make_ursulas( ursula_config: UrsulaConfiguration, staking_provider_addresses: Iterable[str], operator_addresses: Iterable[str], - quantity: int = NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK, + quantity: int = NUMBER_OF_URSULAS_IN_DEVELOPMENT_DOMAIN, know_each_other: bool = True, **ursula_overrides ) -> List[Ursula]: From 0f119934f4a7f7387713973a6b52427b38f3b6ad Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 14:29:27 -0400 Subject: [PATCH 39/63] Update description to no longer include "proxy re-encryption". --- docs/source/conf.py | 12 +++++++++--- nucypher/__about__.py | 2 +- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index e40b3da23..0015f2be0 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -178,9 +178,15 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (main_doc, 'NuCypher', 'NuCypher Documentation', - author, 'NuCypher', 'A proxy re-encryption network to empower privacy in decentralized systems.', - 'Miscellaneous'), + ( + main_doc, + "NuCypher", + "NuCypher Documentation", + author, + "NuCypher", + "A threshold access control application to empower privacy in decentralized systems.", + "Miscellaneous", + ), ] diff --git a/nucypher/__about__.py b/nucypher/__about__.py index 0edc4fea1..9e3f0acd0 100644 --- a/nucypher/__about__.py +++ b/nucypher/__about__.py @@ -14,7 +14,7 @@ __title__ = "nucypher" __url__ = "https://github.com/nucypher/nucypher" -__summary__ = 'A proxy re-encryption network to empower privacy in decentralized systems.' +__summary__ = "A threshold access control application to empower privacy in decentralized systems." __version__ = "6.2.0" From bee3c926d48b31c476820da3f474a5d6f6f59e19 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 16:06:10 -0400 Subject: [PATCH 40/63] Rename networks module to domains, and remove NetworksInventory class; module contains all values and methods now. --- examples/testnet_compound_multichain_taco.py | 4 +- examples/testnet_simple_taco.py | 4 +- nucypher/blockchain/eth/actors.py | 4 +- nucypher/blockchain/eth/domains.py | 67 ++++++++++++++++++ nucypher/blockchain/eth/networks.py | 68 ------------------- nucypher/blockchain/eth/registry.py | 6 +- nucypher/cli/actions/select.py | 6 +- nucypher/cli/commands/taco.py | 4 +- nucypher/cli/options.py | 2 +- nucypher/cli/types.py | 6 +- nucypher/config/base.py | 6 +- nucypher/config/characters.py | 4 +- .../migrations/configuration_v5_to_v6.py | 4 +- nucypher/network/nodes.py | 12 ++-- nucypher/policy/payment.py | 4 +- scripts/hooks/nucypher_agents.py | 4 +- scripts/hooks/nucypher_dkg.py | 4 +- tests/acceptance/conftest.py | 13 ++-- tests/conftest.py | 7 +- tests/fixtures.py | 4 +- .../cli/actions/test_select_network.py | 4 +- tests/integration/conftest.py | 19 +++--- tests/metrics/grant_availability.py | 4 +- tests/unit/conftest.py | 4 +- tests/unit/test_teacher_nodes.py | 4 +- tests/utils/registry.py | 23 ++----- 26 files changed, 138 insertions(+), 153 deletions(-) create mode 100644 nucypher/blockchain/eth/domains.py delete mode 100644 nucypher/blockchain/eth/networks.py diff --git a/examples/testnet_compound_multichain_taco.py b/examples/testnet_compound_multichain_taco.py index 9638cb08b..001840387 100644 --- a/examples/testnet_compound_multichain_taco.py +++ b/examples/testnet_compound_multichain_taco.py @@ -2,8 +2,8 @@ import os from nucypher_core.ferveo import DkgPublicKey +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import CoordinatorAgent -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner from nucypher.characters.lawful import Bob, Enrico @@ -20,7 +20,7 @@ GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] -taco_domain = NetworksInventory.from_domain_name("lynx") +taco_domain = domains.from_domain_name("lynx") polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] diff --git a/examples/testnet_simple_taco.py b/examples/testnet_simple_taco.py index 500cf5b36..34bafdf97 100644 --- a/examples/testnet_simple_taco.py +++ b/examples/testnet_simple_taco.py @@ -2,8 +2,8 @@ import os from nucypher_core.ferveo import DkgPublicKey +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import CoordinatorAgent -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner from nucypher.characters.lawful import Bob, Enrico @@ -20,7 +20,7 @@ GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] -taco_domain = NetworksInventory.from_domain_name("lynx") +taco_domain = domains.from_domain_name("lynx") polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index 4d3572641..7056b2da3 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -27,6 +27,7 @@ from web3 import HTTPProvider, Web3 from web3.types import TxReceipt from nucypher.acumen.nicknames import Nickname +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ( ContractAgency, CoordinatorAgent, @@ -37,7 +38,6 @@ from nucypher.blockchain.eth.clients import PUBLIC_CHAINS from nucypher.blockchain.eth.constants import NULL_ADDRESS from nucypher.blockchain.eth.decorators import validate_checksum_address from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ( ContractRegistry, ) @@ -93,7 +93,7 @@ class BaseActor: self.transacting_power = transacting_power self.registry = registry self.network = domain - self.taco_domain = NetworksInventory.from_domain_name(self.network) + self.taco_domain = domains.from_domain_name(self.network) self._saved_receipts = list() # track receipts of transmitted transactions def __repr__(self): diff --git a/nucypher/blockchain/eth/domains.py b/nucypher/blockchain/eth/domains.py new file mode 100644 index 000000000..0000b16fc --- /dev/null +++ b/nucypher/blockchain/eth/domains.py @@ -0,0 +1,67 @@ +from enum import Enum +from typing import NamedTuple + +from nucypher.config.constants import TEMPORARY_DOMAIN + + +class ChainInfo(NamedTuple): + id: int + name: str + + +class EthChain(ChainInfo, Enum): + MAINNET = ChainInfo(1, "mainnet") + GOERLI = ChainInfo(5, "goerli") + SEPOLIA = ChainInfo(11155111, "sepolia") + TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) + + +class PolygonChain(ChainInfo, Enum): + POLYGON = ChainInfo(137, "polygon") + MUMBAI = ChainInfo(80001, "mumbai") + TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) + + +class TACoDomain(NamedTuple): + name: str + eth_chain: EthChain + polygon_chain: PolygonChain + + def is_testnet(self) -> bool: + return self.eth_chain != EthChain.MAINNET + + +class UnrecognizedDomain(RuntimeError): + """Raised when a provided domain name is not recognized.""" + + +MAINNET = TACoDomain("mainnet", EthChain.MAINNET, PolygonChain.POLYGON) +# Testnets +ORYX = TACoDomain("oryx", EthChain.GOERLI, PolygonChain.POLYGON) +LYNX = TACoDomain("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) +TAPIR = TACoDomain("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) +IBEX = TACoDomain( + "ibex", EthChain.GOERLI, None +) # this is required for configuration file migrations (backwards compatibility) + +DEFAULT_DOMAIN_NAME: str = MAINNET.name + +SUPPORTED_DOMAINS = [ + MAINNET, + ORYX, + LYNX, + TAPIR, +] + +SUPPORTED_DOMAIN_NAMES = [domain.name for domain in SUPPORTED_DOMAINS] + +# TODO not needed once merged with registry changes +POLYGON_CHAINS = [domain.polygon_chain.name for domain in SUPPORTED_DOMAINS] + + +def from_domain_name(domain: str) -> TACoDomain: + for taco_domain in SUPPORTED_DOMAINS: + if taco_domain.name == domain: + return taco_domain + + raise UnrecognizedDomain(f"{domain} is not a recognized domain.") diff --git a/nucypher/blockchain/eth/networks.py b/nucypher/blockchain/eth/networks.py deleted file mode 100644 index 1b82bef84..000000000 --- a/nucypher/blockchain/eth/networks.py +++ /dev/null @@ -1,68 +0,0 @@ -from enum import Enum -from typing import NamedTuple - -from nucypher.config.constants import TEMPORARY_DOMAIN - - -class ChainInfo(NamedTuple): - id: int - name: str - - -class EthChain(ChainInfo, Enum): - MAINNET = ChainInfo(1, "mainnet") - GOERLI = ChainInfo(5, "goerli") - SEPOLIA = ChainInfo(11155111, "sepolia") - TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) - - -class PolygonChain(ChainInfo, Enum): - POLYGON = ChainInfo(137, "polygon") - MUMBAI = ChainInfo(80001, "mumbai") - TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) - - -class TACoDomain(NamedTuple): - name: str - eth_chain: EthChain - polygon_chain: PolygonChain - - def is_testnet(self) -> bool: - return self.eth_chain != EthChain.MAINNET - - -class UnrecognizedDomain(RuntimeError): - """Raised when a provided domain name is not recognized.""" - - -class NetworksInventory: - MAINNET = TACoDomain("mainnet", EthChain.MAINNET, PolygonChain.POLYGON) - # Testnets - ORYX = TACoDomain("oryx", EthChain.GOERLI, PolygonChain.POLYGON) - LYNX = TACoDomain("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) - TAPIR = TACoDomain("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) - IBEX = TACoDomain( - "ibex", EthChain.GOERLI, None - ) # this is required for configuration file migrations (backwards compatibility) - - SUPPORTED_DOMAINS = [ - MAINNET, - ORYX, - LYNX, - TAPIR, - ] - - SUPPORTED_DOMAIN_NAMES = [domain.name for domain in SUPPORTED_DOMAINS] - - # TODO not needed once merged with registry changes - POLYGON_CHAINS = [domain.polygon_chain.name for domain in SUPPORTED_DOMAINS] - - DEFAULT_DOMAIN_NAME: str = MAINNET.name - - @classmethod - def from_domain_name(cls, domain: str) -> TACoDomain: - for taco_domain in cls.SUPPORTED_DOMAINS: - if taco_domain.name == domain: - return taco_domain - - raise UnrecognizedDomain(f"{domain} is not a recognized domain.") diff --git a/nucypher/blockchain/eth/registry.py b/nucypher/blockchain/eth/registry.py index 51d2fb6ee..79b3e6ec1 100644 --- a/nucypher/blockchain/eth/registry.py +++ b/nucypher/blockchain/eth/registry.py @@ -9,7 +9,7 @@ import requests from requests import Response from web3.types import ABI -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth import domains from nucypher.utilities.logging import Logger RegistryArtifact = Dict[str, Union[str, ABI]] @@ -34,10 +34,10 @@ class RegistrySource(ABC): """Raised when there are no available registry sources""" def __init__(self, domain: str, *args, **kwargs): - if domain not in NetworksInventory.SUPPORTED_DOMAIN_NAMES: + if domain not in domains.SUPPORTED_DOMAIN_NAMES: raise ValueError( f"{self.__class__.__name__} not available for domain '{domain}'. " - f"Valid options are: {', '.join(list(NetworksInventory.SUPPORTED_DOMAIN_NAMES))}" + f"Valid options are: {', '.join(list(domains.SUPPORTED_DOMAIN_NAMES))}" ) self.domain = domain self.data = self.get() diff --git a/nucypher/cli/actions/select.py b/nucypher/cli/actions/select.py index 6477a04f5..c06fae5d0 100644 --- a/nucypher/cli/actions/select.py +++ b/nucypher/cli/actions/select.py @@ -6,8 +6,8 @@ import click from tabulate import tabulate from web3.main import Web3 +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ( ContractRegistry, ) @@ -71,7 +71,7 @@ def select_client_account( ) if signer_uri and not signer: - testnet = domain != NetworksInventory.MAINNET.name + testnet = domain != domains.MAINNET.name signer = Signer.from_signer_uri(signer_uri, testnet=testnet) # Display accounts info @@ -118,7 +118,7 @@ def select_client_account( def select_domain(emitter: StdoutEmitter, message: Optional[str] = None) -> str: """Interactively select a domain from TACo domain inventory list""" emitter.message(message=message or str(), color="yellow") - domain_list = NetworksInventory.SUPPORTED_DOMAIN_NAMES + domain_list = domains.SUPPORTED_DOMAIN_NAMES rows = [[n] for n in domain_list] emitter.echo(tabulate(rows, showindex="always")) choice = click.prompt( diff --git a/nucypher/cli/commands/taco.py b/nucypher/cli/commands/taco.py index 4a08fd6d4..5467bcae0 100644 --- a/nucypher/cli/commands/taco.py +++ b/nucypher/cli/commands/taco.py @@ -3,6 +3,7 @@ from pathlib import Path import click from web3 import Web3 +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ( ContractAgency, TACoApplicationAgent, @@ -11,7 +12,6 @@ from nucypher.blockchain.eth.constants import ( AVERAGE_BLOCK_TIME_IN_SECONDS, TACO_CONTRACT_NAMES, ) -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.cli.config import group_general_config from nucypher.cli.options import ( group_options, @@ -42,7 +42,7 @@ option_domain = click.option( "--domain", help="TACo Domain", type=click.STRING, - default=click.Choice(NetworksInventory.SUPPORTED_DOMAIN_NAMES), + default=click.Choice(domains.SUPPORTED_DOMAIN_NAMES), required=True, ) diff --git a/nucypher/cli/options.py b/nucypher/cli/options.py index a95444f52..a32ad4edf 100644 --- a/nucypher/cli/options.py +++ b/nucypher/cli/options.py @@ -176,7 +176,7 @@ def option_message_kit(required: bool = False, multiple: bool = False): def option_domain( required: bool = False, - default: str = None, # NetworksInventory.DEFAULT is not a good global default (2214) + default: str = None, # nucypher.blockchain.eth.domains.DEFAULT.name is not a good global default (#2214) validate: bool = False, ): return click.option( diff --git a/nucypher/cli/types.py b/nucypher/cli/types.py index 7b5780136..cfe11f280 100644 --- a/nucypher/cli/types.py +++ b/nucypher/cli/types.py @@ -10,7 +10,7 @@ from cryptography.exceptions import InternalError from eth_utils import to_checksum_address from nucypher_core.umbral import PublicKey -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.token import TToken from nucypher.policy.payment import PRE_PAYMENT_METHODS from nucypher.utilities.networking import InvalidOperatorIP, validate_operator_ip @@ -97,9 +97,9 @@ class NuCypherDomainName(click.ParamType): def convert(self, value, param, ctx): if self.validate: domain = str(value).lower() - if domain not in NetworksInventory.SUPPORTED_DOMAIN_NAMES: + if domain not in domains.SUPPORTED_DOMAIN_NAMES: self.fail( - f"'{value}' is not a recognized domain. Valid options are: {list(NetworksInventory.SUPPORTED_DOMAIN_NAMES)}" + f"'{value}' is not a recognized domain. Valid options are: {list(domains.SUPPORTED_DOMAIN_NAMES)}" ) else: return domain diff --git a/nucypher/config/base.py b/nucypher/config/base.py index 17f66afc3..4520fddad 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -16,8 +16,8 @@ from constant_sorrow.constants import ( ) from eth_utils.address import is_checksum_address +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ( ContractRegistry, LocalRegistrySource, @@ -307,7 +307,7 @@ class CharacterConfiguration(BaseConfiguration): CHARACTER_CLASS = NotImplemented MNEMONIC_KEYSTORE = False - DEFAULT_DOMAIN = NetworksInventory.DEFAULT_DOMAIN_NAME + DEFAULT_DOMAIN = domains.DEFAULT_DOMAIN_NAME DEFAULT_NETWORK_MIDDLEWARE = RestMiddleware TEMP_CONFIGURATION_DIR_PREFIX = 'tmp-nucypher' SIGNER_ENVVAR = None @@ -420,7 +420,7 @@ class CharacterConfiguration(BaseConfiguration): # Learner self.domain = domain - self.taco_domain = NetworksInventory.from_domain_name(self.domain) + self.taco_domain = domains.from_domain_name(self.domain) self.learn_on_same_thread = learn_on_same_thread self.abort_on_learning_error = abort_on_learning_error self.start_learning_now = start_learning_now diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index 14ea8cf68..781e3a0bf 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -5,7 +5,7 @@ from typing import Dict, List, Optional from cryptography.x509 import Certificate from eth_utils import is_checksum_address -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth import domains from nucypher.config.base import CharacterConfiguration from nucypher.config.constants import ( NUCYPHER_ENVVAR_ALICE_ETH_PASSWORD, @@ -70,7 +70,7 @@ class UrsulaConfiguration(CharacterConfiguration): def configure_condition_blockchain_endpoints(self) -> None: """Configure default condition provider URIs for eth and polygon network.""" - taco_domain = NetworksInventory.from_domain_name(self.domain) + taco_domain = domains.from_domain_name(self.domain) # Polygon polygon_chain_id = taco_domain.polygon_chain.id diff --git a/nucypher/config/migrations/configuration_v5_to_v6.py b/nucypher/config/migrations/configuration_v5_to_v6.py index 7d35ee877..0417ef39e 100644 --- a/nucypher/config/migrations/configuration_v5_to_v6.py +++ b/nucypher/config/migrations/configuration_v5_to_v6.py @@ -1,11 +1,11 @@ from typing import Dict -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth import domains from nucypher.config.migrations.common import perform_migration def __migration(config: Dict) -> Dict: - taco_domain = NetworksInventory.from_domain_name(config["domain"]) + taco_domain = domains.from_domain_name(config["domain"]) eth_provider = config["eth_provider_uri"] eth_chain_id = taco_domain.eth_chain.id polygon_provider = config["payment_provider"] diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index c28943aec..403d0b1eb 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -26,9 +26,9 @@ from twisted.internet.defer import Deferred from nucypher import characters from nucypher.acumen.nicknames import Nickname from nucypher.acumen.perception import FleetSensor +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ContractAgency, TACoApplicationAgent from nucypher.blockchain.eth.constants import NULL_ADDRESS -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.config.constants import SeednodeMetadata from nucypher.config.storages import ForgetfulNodeStorage @@ -46,14 +46,14 @@ from nucypher.network.protocols import InterfaceInfo, SuspiciousActivity from nucypher.utilities.logging import Logger TEACHER_NODES = { - NetworksInventory.MAINNET.name: ( + domains.MAINNET.name: ( 'https://closest-seed.nucypher.network:9151', 'https://seeds.nucypher.network', 'https://mainnet.nucypher.network:9151', ), - NetworksInventory.LYNX.name: ("https://lynx.nucypher.network:9151",), - NetworksInventory.TAPIR.name: ("https://tapir.nucypher.network:9151",), - NetworksInventory.ORYX.name: ("https://oryx.nucypher.network:9151",), + domains.LYNX.name: ("https://lynx.nucypher.network:9151",), + domains.TAPIR.name: ("https://tapir.nucypher.network:9151",), + domains.ORYX.name: ("https://oryx.nucypher.network:9151",), } @@ -271,7 +271,7 @@ class Learner: self.learning_deferred = Deferred() self.domain = domain - self.taco_domain = NetworksInventory.from_domain_name(self.domain) + self.taco_domain = domains.from_domain_name(self.domain) default_middleware = self.__DEFAULT_MIDDLEWARE_CLASS( registry=self.registry, eth_endpoint=self.eth_endpoint ) diff --git a/nucypher/policy/payment.py b/nucypher/policy/payment.py index 5c9f62a8f..1d1e810ab 100644 --- a/nucypher/policy/payment.py +++ b/nucypher/policy/payment.py @@ -5,8 +5,8 @@ import maya from nucypher_core import ReencryptionRequest from web3.types import ChecksumAddress, Timestamp, TxReceipt, Wei +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ContractAgency, SubscriptionManagerAgent -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.policy import policies @@ -73,7 +73,7 @@ class ContractPayment(PaymentMethod, ABC): ): super().__init__(*args, **kwargs) self.blockchain_endpoint = blockchain_endpoint - self.taco_domain = NetworksInventory.from_domain_name(domain) + self.taco_domain = domains.from_domain_name(domain) if not registry: registry = ContractRegistry.from_latest_publication(domain=domain) self.registry = registry diff --git a/scripts/hooks/nucypher_agents.py b/scripts/hooks/nucypher_agents.py index 285b85acc..065c0fa8b 100644 --- a/scripts/hooks/nucypher_agents.py +++ b/scripts/hooks/nucypher_agents.py @@ -20,6 +20,7 @@ import rlcompleter import click +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ( ContractAgency, CoordinatorAgent, @@ -27,7 +28,6 @@ from nucypher.blockchain.eth.agents import ( TACoApplicationAgent, TACoChildApplicationAgent, ) -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.utilities.emitters import StdoutEmitter from nucypher.utilities.logging import GlobalLoggerSettings @@ -45,7 +45,7 @@ emitter = StdoutEmitter(verbosity=2) "--domain", "domain", help="TACo domain", - type=click.Choice(NetworksInventory.SUPPORTED_DOMAIN_NAMES), + type=click.Choice(domains.SUPPORTED_DOMAIN_NAMES), default="lynx", ) @click.option( diff --git a/scripts/hooks/nucypher_dkg.py b/scripts/hooks/nucypher_dkg.py index b364430ac..6ab82754a 100644 --- a/scripts/hooks/nucypher_dkg.py +++ b/scripts/hooks/nucypher_dkg.py @@ -6,12 +6,12 @@ import maya from nucypher_core.ferveo import DkgPublicKey from web3 import Web3 +from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ( ContractAgency, CoordinatorAgent, TACoApplicationAgent, ) -from nucypher.blockchain.eth.networks import NetworksInventory from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner, Signer from nucypher.characters.lawful import Bob, Enrico @@ -154,7 +154,7 @@ def nucypher_dkg( ), ) - taco_domain = NetworksInventory.from_domain_name(domain) + taco_domain = domains.from_domain_name(domain) registry = ContractRegistry.from_latest_publication( domain=domain ) diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index d1bde7755..496b2c1f2 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -11,13 +11,12 @@ from nucypher.blockchain.eth.agents import ( TACoApplicationAgent, TACoChildApplicationAgent, ) -from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory -from nucypher.blockchain.eth.networks import ( +from nucypher.blockchain.eth.domains import ( EthChain, - NetworksInventory, PolygonChain, TACoDomain, ) +from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.registry import ContractRegistry, RegistrySourceManager from nucypher.blockchain.eth.signers.software import Web3Signer from nucypher.config.constants import TEMPORARY_DOMAIN @@ -304,8 +303,8 @@ def deployed_contracts( @pytest.fixture(scope="module", autouse=True) -def test_registry(deployed_contracts): - with tests.utils.registry.mock_registry_sources(): +def test_registry(deployed_contracts, module_mocker): + with tests.utils.registry.mock_registry_sources(mocker=module_mocker): RegistrySourceManager._FALLBACK_CHAIN = (ApeRegistrySource,) source = ApeRegistrySource(domain=TEMPORARY_DOMAIN) registry = ContractRegistry(source=source) @@ -445,8 +444,8 @@ def mock_condition_blockchains(session_mocker): TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - session_mocker.patch.object( - NetworksInventory, "from_domain_name", return_value=test_domain + session_mocker.patch( + "nucypher.blockchain.eth.domains.from_domain_name", return_value=test_domain ) diff --git a/tests/conftest.py b/tests/conftest.py index 7f822dbbc..2d7879433 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,9 +4,8 @@ import pytest from eth_utils.crypto import keccak from nucypher.blockchain.eth.actors import Operator -from nucypher.blockchain.eth.networks import ( +from nucypher.blockchain.eth.domains import ( EthChain, - NetworksInventory, PolygonChain, TACoDomain, ) @@ -151,8 +150,8 @@ def mock_condition_blockchains(session_mocker): TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - session_mocker.patch.object( - NetworksInventory, "from_domain_name", return_value=test_domain + session_mocker.patch( + "nucypher.blockchain.eth.domains.from_domain_name", return_value=test_domain ) diff --git a/tests/fixtures.py b/tests/fixtures.py index 86f63afa2..b22cc882c 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -304,8 +304,8 @@ def lonely_ursula_maker(ursula_test_config, testerchain): @pytest.fixture(scope="module") -def mock_registry_sources(): - with tests.utils.registry.mock_registry_sources(): +def mock_registry_sources(module_mocker): + with tests.utils.registry.mock_registry_sources(module_mocker): yield diff --git a/tests/integration/cli/actions/test_select_network.py b/tests/integration/cli/actions/test_select_network.py index 09f26b39d..0797d799b 100644 --- a/tests/integration/cli/actions/test_select_network.py +++ b/tests/integration/cli/actions/test_select_network.py @@ -1,9 +1,9 @@ import pytest -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth import domains from nucypher.cli.actions.select import select_domain -__DOMAINS = NetworksInventory.SUPPORTED_DOMAIN_NAMES +__DOMAINS = domains.SUPPORTED_DOMAIN_NAMES @pytest.mark.parametrize("user_input", range(0, len(__DOMAINS) - 1)) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index b430823b9..247f3553e 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -14,16 +14,15 @@ from nucypher.blockchain.eth.agents import ( TACoChildApplicationAgent, ) from nucypher.blockchain.eth.clients import EthereumClient +from nucypher.blockchain.eth.domains import ( + EthChain, + PolygonChain, + TACoDomain, +) from nucypher.blockchain.eth.interfaces import ( BlockchainInterface, BlockchainInterfaceFactory, ) -from nucypher.blockchain.eth.networks import ( - EthChain, - NetworksInventory, - PolygonChain, - TACoDomain, -) from nucypher.blockchain.eth.registry import ( ContractRegistry, ) @@ -137,8 +136,8 @@ def mock_interface(module_mocker): @pytest.fixture(scope='module') -def test_registry(): - with mock_registry_sources(): +def test_registry(module_mocker): + with mock_registry_sources(mocker=module_mocker): mock_source = MockRegistrySource(domain=TEMPORARY_DOMAIN) registry = ContractRegistry(source=mock_source) yield registry @@ -295,8 +294,8 @@ def mock_condition_blockchains(session_mocker): TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - session_mocker.patch.object( - NetworksInventory, "from_domain_name", return_value=test_domain + session_mocker.patch( + "nucypher.blockchain.eth.domains.from_domain_name", return_value=test_domain ) diff --git a/tests/metrics/grant_availability.py b/tests/metrics/grant_availability.py index 7e1bfe2ac..09ec11af5 100755 --- a/tests/metrics/grant_availability.py +++ b/tests/metrics/grant_availability.py @@ -22,7 +22,7 @@ from nucypher_core.umbral import SecretKey from web3 import Web3 from web3.types import Wei -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth.domains import LYNX from nucypher.blockchain.eth.signers import Signer from nucypher.characters.lawful import Alice, Bob, Ursula from nucypher.config.characters import AliceConfiguration @@ -54,7 +54,7 @@ except KeyError: raise RuntimeError(message) # Alice Configuration -TACO_DOMAIN: str = NetworksInventory.LYNX.name # mainnet +TACO_DOMAIN: str = LYNX.name # mainnet DEFAULT_SEEDNODE_URIS: List[str] = [ *TEACHER_NODES[TACO_DOMAIN], ] diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index 93be27e83..9512dd702 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -18,8 +18,8 @@ def pytest_addhooks(pluginmanager): @pytest.fixture(scope='module') -def test_registry(): - with mock_registry_sources(): +def test_registry(module_mocker): + with mock_registry_sources(mocker=module_mocker): source = MockRegistrySource(domain=TEMPORARY_DOMAIN) yield ContractRegistry(source=source) diff --git a/tests/unit/test_teacher_nodes.py b/tests/unit/test_teacher_nodes.py index 5150e6627..38e743d2d 100644 --- a/tests/unit/test_teacher_nodes.py +++ b/tests/unit/test_teacher_nodes.py @@ -1,6 +1,6 @@ import pytest -from nucypher.blockchain.eth.networks import NetworksInventory +from nucypher.blockchain.eth import domains from nucypher.network.nodes import TEACHER_NODES @@ -11,6 +11,6 @@ def mock_teacher_nodes(mocker): def test_default_teacher_seednodes_defined(): - for domain in NetworksInventory.SUPPORTED_DOMAIN_NAMES: + for domain in domains.SUPPORTED_DOMAIN_NAMES: teacher_nodes = TEACHER_NODES[domain] assert len(teacher_nodes) > 0 diff --git a/tests/utils/registry.py b/tests/utils/registry.py index 90d776336..bc07192cc 100644 --- a/tests/utils/registry.py +++ b/tests/utils/registry.py @@ -5,9 +5,9 @@ from typing import List from ape.contracts import ContractInstance from eth_utils import to_checksum_address -from nucypher.blockchain.eth.networks import ( +from nucypher.blockchain.eth import domains +from nucypher.blockchain.eth.domains import ( EthChain, - NetworksInventory, PolygonChain, TACoDomain, ) @@ -20,26 +20,15 @@ from nucypher.config.constants import TEMPORARY_DOMAIN @contextmanager -def mock_registry_sources(): - # capture the real values - real_domains = NetworksInventory.SUPPORTED_DOMAINS - real_domain_names = NetworksInventory.SUPPORTED_DOMAIN_NAMES - real_registry_sources = RegistrySourceManager._FALLBACK_CHAIN - - # set the mock values - NetworksInventory.SUPPORTED_DOMAIN_NAMES = [TEMPORARY_DOMAIN] +def mock_registry_sources(mocker): test_domain = TACoDomain( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - NetworksInventory.SUPPORTED_DOMAINS = [test_domain] - RegistrySourceManager._FALLBACK_CHAIN = (MockRegistrySource,) - yield # run the test + mocker.patch.object(domains, "SUPPORTED_DOMAINS", [test_domain]) + mocker.patch.object(domains, "SUPPORTED_DOMAIN_NAMES", [TEMPORARY_DOMAIN]) - # restore the real values - NetworksInventory.SUPPORTED_DOMAINS = real_domains - NetworksInventory.SUPPORTED_DOMAIN_NAMES = real_domain_names - RegistrySourceManager._FALLBACK_CHAIN = real_registry_sources + mocker.patch.object(RegistrySourceManager, "_FALLBACK_CHAIN", (MockRegistrySource,)) class MockRegistrySource(RegistrySource): From a5b8b805da78a257b25026839546c2c8bb610e4a Mon Sep 17 00:00:00 2001 From: derekpierre Date: Tue, 3 Oct 2023 16:39:46 -0400 Subject: [PATCH 41/63] The use of the `blockchain_` prefix for blockchain providers and interfaces is redundant; so remove the prefix from those usages. --- nucypher/blockchain/eth/agents.py | 4 +- nucypher/blockchain/eth/interfaces.py | 102 +++++++++--------- nucypher/blockchain/eth/providers.py | 22 ++-- nucypher/blockchain/eth/signers/software.py | 2 +- nucypher/characters/lawful.py | 8 +- nucypher/characters/unlawful.py | 8 +- nucypher/cli/actions/select.py | 8 +- nucypher/cli/painting/transactions.py | 2 +- nucypher/cli/utils.py | 6 +- nucypher/config/base.py | 4 +- nucypher/utilities/ethereum.py | 10 +- nucypher/utilities/prometheus/collector.py | 2 +- tests/acceptance/conftest.py | 2 +- tests/acceptance/test_testerchain.py | 2 +- ...ursula_local_keystore_cli_functionality.py | 4 +- tests/unit/test_web3_clients.py | 40 ++++--- tests/utils/blockchain.py | 2 +- 17 files changed, 104 insertions(+), 124 deletions(-) diff --git a/nucypher/blockchain/eth/agents.py b/nucypher/blockchain/eth/agents.py index ebdab8d4a..953f1a734 100644 --- a/nucypher/blockchain/eth/agents.py +++ b/nucypher/blockchain/eth/agents.py @@ -91,7 +91,7 @@ class EthereumContractAgent: self.registry = registry self.blockchain = BlockchainInterfaceFactory.get_or_create_interface( - blockchain_endpoint=blockchain_endpoint + endpoint=blockchain_endpoint ) if not contract: # Fetch the contract @@ -110,7 +110,7 @@ class EthereumContractAgent: "Initialized new {} for {} with {} and {}".format( self.__class__.__name__, self.contract.address, - self.blockchain.blockchain_endpoint, + self.blockchain.endpoint, str(self.registry), ) ) diff --git a/nucypher/blockchain/eth/interfaces.py b/nucypher/blockchain/eth/interfaces.py index 5875469a7..7691e846c 100644 --- a/nucypher/blockchain/eth/interfaces.py +++ b/nucypher/blockchain/eth/interfaces.py @@ -137,8 +137,8 @@ class BlockchainInterface: emitter=None, # TODO # 1754 poa: bool = None, light: bool = False, - blockchain_endpoint: str = NO_BLOCKCHAIN_CONNECTION, - blockchain_provider: BaseProvider = NO_BLOCKCHAIN_CONNECTION, + endpoint: str = NO_BLOCKCHAIN_CONNECTION, + provider: BaseProvider = NO_BLOCKCHAIN_CONNECTION, gas_strategy: Optional[Union[str, Callable]] = None, max_gas_price: Optional[int] = None, ): @@ -207,8 +207,8 @@ class BlockchainInterface: self.log = Logger('Blockchain') self.poa = poa - self.blockchain_endpoint = blockchain_endpoint - self._blockchain_provider = blockchain_provider + self.endpoint = endpoint + self._provider = provider self.w3 = NO_BLOCKCHAIN_CONNECTION self.client = NO_BLOCKCHAIN_CONNECTION self.is_light = light @@ -220,9 +220,7 @@ class BlockchainInterface: self.max_gas_price = max_gas_price def __repr__(self): - r = "{name}({uri})".format( - name=self.__class__.__name__, uri=self.blockchain_endpoint - ) + r = "{name}({uri})".format(name=self.__class__.__name__, uri=self.endpoint) return r def get_blocktime(self): @@ -295,29 +293,29 @@ class BlockchainInterface: def connect(self): - blockchain_endpoint = self.blockchain_endpoint - self.log.info(f"Using external Web3 Provider '{self.blockchain_endpoint}'") + endpoint = self.endpoint + self.log.info(f"Using external Web3 Provider '{self.endpoint}'") # Attach Provider self._attach_blockchain_provider( - blockchain_provider=self._blockchain_provider, - blockchain_endpoint=blockchain_endpoint, + provider=self._provider, + endpoint=endpoint, ) - self.log.info("Connecting to {}".format(self.blockchain_endpoint)) - if self._blockchain_provider is NO_BLOCKCHAIN_CONNECTION: + self.log.info("Connecting to {}".format(self.endpoint)) + if self._provider is NO_BLOCKCHAIN_CONNECTION: raise self.NoProvider("There are no configured blockchain providers") # Connect if not connected try: - self.w3 = self.Web3(provider=self._blockchain_provider) + self.w3 = self.Web3(provider=self._provider) self.client = EthereumClient.from_w3(w3=self.w3) except requests.ConnectionError: # RPC raise self.ConnectionFailed( - f"Connection Failed - {str(self.blockchain_endpoint)} - is RPC enabled?" + f"Connection Failed - {str(self.endpoint)} - is RPC enabled?" ) except FileNotFoundError: # IPC File Protocol raise self.ConnectionFailed( - f"Connection Failed - {str(self.blockchain_endpoint)} - is IPC enabled?" + f"Connection Failed - {str(self.endpoint)} - is IPC enabled?" ) else: self.attach_middleware() @@ -326,22 +324,22 @@ class BlockchainInterface: @property def provider(self) -> BaseProvider: - return self._blockchain_provider + return self._provider def _attach_blockchain_provider( self, - blockchain_provider: Optional[BaseProvider] = None, - blockchain_endpoint: str = None, + provider: Optional[BaseProvider] = None, + endpoint: str = None, ) -> None: """ https://web3py.readthedocs.io/en/latest/providers.html#providers """ - if not blockchain_endpoint and not blockchain_provider: + if not endpoint and not provider: raise self.NoProvider("No URI or provider instances supplied.") - if blockchain_endpoint and not blockchain_provider: - uri_breakdown = urlparse(blockchain_endpoint) + if endpoint and not provider: + uri_breakdown = urlparse(endpoint) if uri_breakdown.scheme == 'tester': providers = { @@ -364,27 +362,23 @@ class BlockchainInterface: # auto-detect for file based ipc if not provider_scheme: - if Path(blockchain_endpoint).is_file(): + if Path(endpoint).is_file(): # file is available - assume ipc/file scheme provider_scheme = "file" self.log.info( - f"Auto-detected provider scheme as 'file://' for provider {blockchain_endpoint}" + f"Auto-detected provider scheme as 'file://' for provider {endpoint}" ) try: - self._blockchain_provider = providers[provider_scheme]( - blockchain_endpoint - ) + self._provider = providers[provider_scheme](endpoint) except KeyError: raise self.UnsupportedProvider( - f"{blockchain_endpoint} is an invalid or unsupported blockchain provider URI" + f"{endpoint} is an invalid or unsupported blockchain provider URI" ) else: - self.blockchain_endpoint = ( - blockchain_endpoint or NO_BLOCKCHAIN_CONNECTION - ) + self.endpoint = endpoint or NO_BLOCKCHAIN_CONNECTION else: - self._blockchain_provider = blockchain_provider + self._provider = provider @classmethod def _handle_failed_transaction(cls, @@ -709,11 +703,11 @@ class BlockchainInterfaceFactory: return cls._instance @classmethod - def is_interface_initialized(cls, blockchain_endpoint: str) -> bool: + def is_interface_initialized(cls, endpoint: str) -> bool: """ - Returns True if there is an existing connection with an equal blockchain_endpoint. + Returns True if there is an existing connection with an equal endpoint. """ - return bool(cls._interfaces.get(blockchain_endpoint, False)) + return bool(cls._interfaces.get(endpoint, False)) @classmethod def register_interface(cls, @@ -722,33 +716,33 @@ class BlockchainInterfaceFactory: force: bool = False ) -> None: - blockchain_endpoint = interface.blockchain_endpoint - if (blockchain_endpoint in cls._interfaces) and not force: + endpoint = interface.endpoint + if (endpoint in cls._interfaces) and not force: raise cls.InterfaceAlreadyInitialized( - f"A connection already exists for {blockchain_endpoint}. " + f"A connection already exists for {endpoint}. " "Use .get_interface instead." ) cached = cls.CachedInterface(interface=interface, emitter=emitter) - cls._interfaces[blockchain_endpoint] = cached + cls._interfaces[endpoint] = cached @classmethod def initialize_interface( cls, - blockchain_endpoint: str, + endpoint: str, emitter=None, interface_class: Interfaces = None, *interface_args, **interface_kwargs, ) -> None: - if not blockchain_endpoint: + if not endpoint: # Prevent empty strings and Falsy raise BlockchainInterface.UnsupportedProvider( - f"'{blockchain_endpoint}' is not a valid provider URI" + f"'{endpoint}' is not a valid provider URI" ) - if blockchain_endpoint in cls._interfaces: + if endpoint in cls._interfaces: raise cls.InterfaceAlreadyInitialized( - f"A connection already exists for {blockchain_endpoint}. " + f"A connection already exists for {endpoint}. " f"Use .get_interface instead." ) @@ -756,23 +750,23 @@ class BlockchainInterfaceFactory: if not interface_class: interface_class = cls._default_interface_class interface = interface_class( - blockchain_endpoint=blockchain_endpoint, *interface_args, **interface_kwargs + endpoint=endpoint, *interface_args, **interface_kwargs ) interface.connect() - cls._interfaces[blockchain_endpoint] = cls.CachedInterface( + cls._interfaces[endpoint] = cls.CachedInterface( interface=interface, emitter=emitter ) @classmethod - def get_interface(cls, blockchain_endpoint: str = None) -> Interfaces: + def get_interface(cls, endpoint: str = None) -> Interfaces: # Try to get an existing cached interface. - if blockchain_endpoint: + if endpoint: try: - cached_interface = cls._interfaces[blockchain_endpoint] + cached_interface = cls._interfaces[endpoint] except KeyError: raise cls.InterfaceNotInitialized( - f"There is no connection for {blockchain_endpoint}. " + f"There is no connection for {endpoint}. " f"Call .initialize_connection, then try again." ) @@ -793,15 +787,15 @@ class BlockchainInterfaceFactory: @classmethod def get_or_create_interface( - cls, blockchain_endpoint: str, *interface_args, **interface_kwargs + cls, endpoint: str, *interface_args, **interface_kwargs ) -> BlockchainInterface: try: - interface = cls.get_interface(blockchain_endpoint=blockchain_endpoint) + interface = cls.get_interface(endpoint=endpoint) except (cls.InterfaceNotInitialized, cls.NoRegisteredInterfaces): cls.initialize_interface( - blockchain_endpoint=blockchain_endpoint, + endpoint=endpoint, *interface_args, **interface_kwargs, ) - interface = cls.get_interface(blockchain_endpoint=blockchain_endpoint) + interface = cls.get_interface(endpoint=endpoint) return interface diff --git a/nucypher/blockchain/eth/providers.py b/nucypher/blockchain/eth/providers.py index 2df935a39..6ad8de7e0 100644 --- a/nucypher/blockchain/eth/providers.py +++ b/nucypher/blockchain/eth/providers.py @@ -14,33 +14,33 @@ class ProviderError(Exception): pass -def _get_IPC_provider(blockchain_endpoint) -> BaseProvider: - uri_breakdown = urlparse(blockchain_endpoint) +def _get_IPC_provider(endpoint) -> BaseProvider: + uri_breakdown = urlparse(endpoint) from nucypher.blockchain.eth.interfaces import BlockchainInterface return IPCProvider(ipc_path=uri_breakdown.path, timeout=BlockchainInterface.TIMEOUT, request_kwargs={'timeout': BlockchainInterface.TIMEOUT}) -def _get_HTTP_provider(blockchain_endpoint) -> BaseProvider: +def _get_HTTP_provider(endpoint) -> BaseProvider: from nucypher.blockchain.eth.interfaces import BlockchainInterface return HTTPProvider( - endpoint_uri=blockchain_endpoint, + endpoint_uri=endpoint, request_kwargs={"timeout": BlockchainInterface.TIMEOUT}, ) -def _get_websocket_provider(blockchain_endpoint) -> BaseProvider: +def _get_websocket_provider(endpoint) -> BaseProvider: from nucypher.blockchain.eth.interfaces import BlockchainInterface return WebsocketProvider( - endpoint_uri=blockchain_endpoint, + endpoint_uri=endpoint, websocket_kwargs={"timeout": BlockchainInterface.TIMEOUT}, ) -def _get_auto_provider(blockchain_endpoint) -> BaseProvider: +def _get_auto_provider(endpoint) -> BaseProvider: from web3.auto import w3 # how-automated-detection-works: https://web3py.readthedocs.io/en/latest/providers.html connected = w3.isConnected() @@ -69,7 +69,7 @@ def _get_ethereum_tester(test_backend: Union[PyEVMBackend, MockBackend]) -> Ethe return provider -def _get_pyevm_test_provider(blockchain_endpoint) -> BaseProvider: +def _get_pyevm_test_provider(endpoint) -> BaseProvider: """ Test provider entry-point""" # https://github.com/ethereum/eth-tester#pyevm-experimental pyevm_eth_tester = _get_pyevm_test_backend() @@ -77,13 +77,13 @@ def _get_pyevm_test_provider(blockchain_endpoint) -> BaseProvider: return provider -def _get_mock_test_provider(blockchain_endpoint) -> BaseProvider: +def _get_mock_test_provider(endpoint) -> BaseProvider: # https://github.com/ethereum/eth-tester#mockbackend mock_backend = MockBackend() provider = _get_ethereum_tester(test_backend=mock_backend) return provider -def _get_tester_ganache(blockchain_endpoint=None) -> BaseProvider: - endpoint_uri = blockchain_endpoint or "http://localhost:7545" +def _get_tester_ganache(endpoint=None) -> BaseProvider: + endpoint_uri = endpoint or "http://localhost:7545" return HTTPProvider(endpoint_uri=endpoint_uri) diff --git a/nucypher/blockchain/eth/signers/software.py b/nucypher/blockchain/eth/signers/software.py index f878dda2c..554b98f3d 100644 --- a/nucypher/blockchain/eth/signers/software.py +++ b/nucypher/blockchain/eth/signers/software.py @@ -35,7 +35,7 @@ class Web3Signer(Signer): ) try: blockchain = BlockchainInterfaceFactory.get_or_create_interface( - blockchain_endpoint=uri + endpoint=uri ) except BlockchainInterface.UnsupportedProvider: raise cls.InvalidSignerURI(uri) diff --git a/nucypher/characters/lawful.py b/nucypher/characters/lawful.py index a664fe946..d00f23218 100644 --- a/nucypher/characters/lawful.py +++ b/nucypher/characters/lawful.py @@ -179,7 +179,7 @@ class Alice(Character, actors.PolicyAuthor): if is_me: # TODO: #289 blockchain = BlockchainInterfaceFactory.get_interface( - blockchain_endpoint=self.eth_endpoint + endpoint=self.eth_endpoint ) signer = signer or Web3Signer( blockchain.client @@ -991,11 +991,9 @@ class Ursula(Teacher, Character, Operator): # Connect to Provider if not BlockchainInterfaceFactory.is_interface_initialized( - blockchain_endpoint=self.eth_endpoint + endpoint=self.eth_endpoint ): - BlockchainInterfaceFactory.initialize_interface( - blockchain_endpoint=self.eth_endpoint - ) + BlockchainInterfaceFactory.initialize_interface(endpoint=self.eth_endpoint) if preflight: self.__preflight() diff --git a/nucypher/characters/unlawful.py b/nucypher/characters/unlawful.py index cb73cb388..b4c97ca8c 100644 --- a/nucypher/characters/unlawful.py +++ b/nucypher/characters/unlawful.py @@ -43,9 +43,7 @@ class Vladimir(Ursula): importable_name="tests.utils.middleware.EvilMiddleWare" ) eth_blockchain = target_ursula.application_agent.blockchain - cls.network_middleware = EvilMiddleWare( - eth_endpoint=eth_blockchain.blockchain_endpoint - ) + cls.network_middleware = EvilMiddleWare(eth_endpoint=eth_blockchain.endpoint) polygon_blockchain = target_ursula.child_application_agent.blockchain @@ -76,8 +74,8 @@ class Vladimir(Ursula): checksum_address=cls.fraud_address, operator_address=cls.fraud_address, signer=Web3Signer(eth_blockchain.client), - eth_endpoint=eth_blockchain.blockchain_endpoint, - polygon_endpoint=polygon_blockchain.blockchain_endpoint, + eth_endpoint=eth_blockchain.endpoint, + polygon_endpoint=polygon_blockchain.endpoint, pre_payment_method=bogus_pre_payment_method, ) diff --git a/nucypher/cli/actions/select.py b/nucypher/cli/actions/select.py index c06fae5d0..8bbb77500 100644 --- a/nucypher/cli/actions/select.py +++ b/nucypher/cli/actions/select.py @@ -58,17 +58,15 @@ def select_client_account( if polygon_endpoint: # Connect to the blockchain in order to select an account if not BlockchainInterfaceFactory.is_interface_initialized( - blockchain_endpoint=polygon_endpoint + endpoint=polygon_endpoint ): BlockchainInterfaceFactory.initialize_interface( - blockchain_endpoint=polygon_endpoint, poa=poa, emitter=emitter + endpoint=polygon_endpoint, poa=poa, emitter=emitter ) if not signer_uri: signer_uri = polygon_endpoint - blockchain = BlockchainInterfaceFactory.get_interface( - blockchain_endpoint=polygon_endpoint - ) + blockchain = BlockchainInterfaceFactory.get_interface(endpoint=polygon_endpoint) if signer_uri and not signer: testnet = domain != domains.MAINNET.name diff --git a/nucypher/cli/painting/transactions.py b/nucypher/cli/painting/transactions.py index 3ad272e51..e65615e48 100644 --- a/nucypher/cli/painting/transactions.py +++ b/nucypher/cli/painting/transactions.py @@ -23,7 +23,7 @@ def paint_receipt_summary( if not chain_name: blockchain = BlockchainInterfaceFactory.get_interface( - blockchain_endpoint=blockchain_endpoint + endpoint=blockchain_endpoint ) chain_name = blockchain.client.chain_name try: diff --git a/nucypher/cli/utils.py b/nucypher/cli/utils.py index 305e95ae3..e41642a96 100644 --- a/nucypher/cli/utils.py +++ b/nucypher/cli/utils.py @@ -120,14 +120,14 @@ def connect_to_blockchain( try: # Note: Conditional for test compatibility. if not BlockchainInterfaceFactory.is_interface_initialized( - blockchain_endpoint=blockchain_endpoint + endpoint=blockchain_endpoint ): BlockchainInterfaceFactory.initialize_interface( - blockchain_endpoint=blockchain_endpoint, light=light, emitter=emitter + endpoint=blockchain_endpoint, light=light, emitter=emitter ) emitter.echo(message=CONNECTING_TO_BLOCKCHAIN) blockchain = BlockchainInterfaceFactory.get_interface( - blockchain_endpoint=blockchain_endpoint + endpoint=blockchain_endpoint ) return blockchain except Exception as e: diff --git a/nucypher/config/base.py b/nucypher/config/base.py index 4520fddad..2029759c7 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -511,12 +511,12 @@ class CharacterConfiguration(BaseConfiguration): for endpoint in endpoints: if endpoint and endpoint != NO_BLOCKCHAIN_CONNECTION: is_initialized = BlockchainInterfaceFactory.is_interface_initialized( - blockchain_endpoint=endpoint + endpoint=endpoint ) if not is_initialized: BlockchainInterfaceFactory.initialize_interface( - blockchain_endpoint=endpoint, + endpoint=endpoint, poa=self.poa, light=self.is_light, emitter=emitter, diff --git a/nucypher/utilities/ethereum.py b/nucypher/utilities/ethereum.py index ecf81fb3c..11b283ab6 100644 --- a/nucypher/utilities/ethereum.py +++ b/nucypher/utilities/ethereum.py @@ -31,12 +31,8 @@ def connect_web3_provider(blockchain_endpoint: str) -> None: from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory if not BlockchainInterfaceFactory.is_interface_initialized( - blockchain_endpoint=blockchain_endpoint + endpoint=blockchain_endpoint ): - BlockchainInterfaceFactory.initialize_interface( - blockchain_endpoint=blockchain_endpoint - ) - interface = BlockchainInterfaceFactory.get_interface( - blockchain_endpoint=blockchain_endpoint - ) + BlockchainInterfaceFactory.initialize_interface(endpoint=blockchain_endpoint) + interface = BlockchainInterfaceFactory.get_interface(endpoint=blockchain_endpoint) interface.connect() diff --git a/nucypher/utilities/prometheus/collector.py b/nucypher/utilities/prometheus/collector.py index 63484b317..3e08b4432 100644 --- a/nucypher/utilities/prometheus/collector.py +++ b/nucypher/utilities/prometheus/collector.py @@ -140,7 +140,7 @@ class BlockchainMetricsCollector(BaseMetricsCollector): def _collect_internal(self) -> None: blockchain = BlockchainInterfaceFactory.get_or_create_interface( - blockchain_endpoint=self.eth_endpoint + endpoint=self.eth_endpoint ) self.metrics["eth_chain_id"].set(blockchain.client.chain_id) self.metrics["eth_current_block_number"].set(blockchain.client.block_number) diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index 496b2c1f2..e45aac720 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -316,7 +316,7 @@ def test_registry(deployed_contracts, module_mocker): def testerchain(project) -> TesterBlockchain: # Extract the web3 provider containing EthereumTester from the ape project's chain manager provider = project.chain_manager.provider.web3.provider - testerchain = TesterBlockchain(blockchain_provider=provider) + testerchain = TesterBlockchain(provider=provider) BlockchainInterfaceFactory.register_interface(interface=testerchain, force=True) yield testerchain diff --git a/tests/acceptance/test_testerchain.py b/tests/acceptance/test_testerchain.py index 51078efcc..81e5e7190 100644 --- a/tests/acceptance/test_testerchain.py +++ b/tests/acceptance/test_testerchain.py @@ -26,7 +26,7 @@ def test_testerchain_creation(testerchain, another_testerchain): for chain in chains: # Ensure we are testing on the correct network... - assert "tester" in chain.blockchain_endpoint + assert "tester" in chain.endpoint # ... and that there are already some blocks mined chain.w3.eth.w3.testing.mine(1) diff --git a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py index 680428c2c..4846e2fb8 100644 --- a/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py +++ b/tests/integration/cli/test_ursula_local_keystore_cli_functionality.py @@ -51,10 +51,10 @@ def test_ursula_init_with_local_keystore_signer( "--domain", TEMPORARY_DOMAIN, "--eth-endpoint", - testerchain.blockchain_endpoint, + testerchain.endpoint, # Layer 2 "--polygon-endpoint", - testerchain.blockchain_endpoint, + testerchain.endpoint, "--rest-host", MOCK_IP_ADDRESS, "--rest-port", diff --git a/tests/unit/test_web3_clients.py b/tests/unit/test_web3_clients.py index 6a1f1c717..a3e9a2ff6 100644 --- a/tests/unit/test_web3_clients.py +++ b/tests/unit/test_web3_clients.py @@ -150,39 +150,37 @@ class ProviderTypeTestClient(BlockchainInterfaceTestBase): # check type assert isinstance(self.provider, self.expected_provider_class) - super()._attach_blockchain_provider( - blockchain_provider=self.test_provider_to_attach - ) + super()._attach_blockchain_provider(provider=self.test_provider_to_attach) class InfuraTestClient(BlockchainInterfaceTestBase): def _attach_blockchain_provider(self, *args, **kwargs) -> None: - super()._attach_blockchain_provider(blockchain_provider=MockInfuraProvider()) + super()._attach_blockchain_provider(provider=MockInfuraProvider()) class AlchemyTestClient(BlockchainInterfaceTestBase): def _attach_blockchain_provider(self, *args, **kwargs) -> None: - super()._attach_blockchain_provider(blockchain_provider=MockAlchemyProvider()) + super()._attach_blockchain_provider(provider=MockAlchemyProvider()) class GethClientTestBlockchain(BlockchainInterfaceTestBase): def _attach_blockchain_provider(self, *args, **kwargs) -> None: - super()._attach_blockchain_provider(blockchain_provider=MockGethProvider()) + super()._attach_blockchain_provider(provider=MockGethProvider()) class ParityClientTestInterface(BlockchainInterfaceTestBase): def _attach_blockchain_provider(self, *args, **kwargs) -> None: - super()._attach_blockchain_provider(blockchain_provider=MockParityProvider()) + super()._attach_blockchain_provider(provider=MockParityProvider()) class GanacheClientTestInterface(BlockchainInterfaceTestBase): def _attach_blockchain_provider(self, *args, **kwargs) -> None: - super()._attach_blockchain_provider(blockchain_provider=MockGanacheProvider()) + super()._attach_blockchain_provider(provider=MockGanacheProvider()) def test_client_no_provider(): @@ -192,7 +190,7 @@ def test_client_no_provider(): def test_geth_web3_client(): - interface = GethClientTestBlockchain(blockchain_endpoint="file:///ipc.geth") + interface = GethClientTestBlockchain(endpoint="file:///ipc.geth") interface.connect() assert isinstance(interface.client, GethClient) @@ -207,7 +205,7 @@ def test_geth_web3_client(): def test_autodetect_provider_type_file(tempfile_path): interface = ProviderTypeTestClient( - blockchain_endpoint=str(tempfile_path), # existing file for test + endpoint=str(tempfile_path), # existing file for test expected_provider_class=IPCProvider, actual_provider_to_attach=MockGethProvider(), ) @@ -217,15 +215,13 @@ def test_autodetect_provider_type_file(tempfile_path): def test_autodetect_provider_type_file_none_existent(): with pytest.raises(BlockchainInterface.UnsupportedProvider): - interface = BlockchainInterfaceTestBase( - blockchain_endpoint="/none_existent.ipc.geth" - ) + interface = BlockchainInterfaceTestBase(endpoint="/none_existent.ipc.geth") interface.connect() def test_detect_provider_type_file(): interface = ProviderTypeTestClient( - blockchain_endpoint="file:///ipc.geth", + endpoint="file:///ipc.geth", expected_provider_class=IPCProvider, actual_provider_to_attach=MockGethProvider(), ) @@ -235,7 +231,7 @@ def test_detect_provider_type_file(): def test_detect_provider_type_ipc(): interface = ProviderTypeTestClient( - blockchain_endpoint="ipc:///ipc.geth", + endpoint="ipc:///ipc.geth", expected_provider_class=IPCProvider, actual_provider_to_attach=MockGethProvider(), ) @@ -245,7 +241,7 @@ def test_detect_provider_type_ipc(): def test_detect_provider_type_http(): interface = ProviderTypeTestClient( - blockchain_endpoint="http://ganache:8445", + endpoint="http://ganache:8445", expected_provider_class=HTTPProvider, actual_provider_to_attach=MockGanacheProvider(), ) @@ -255,7 +251,7 @@ def test_detect_provider_type_http(): def test_detect_provider_type_https(): interface = ProviderTypeTestClient( - blockchain_endpoint="https://ganache:8445", + endpoint="https://ganache:8445", expected_provider_class=HTTPProvider, actual_provider_to_attach=MockGanacheProvider(), ) @@ -265,7 +261,7 @@ def test_detect_provider_type_https(): def test_detect_provider_type_ws(): interface = ProviderTypeTestClient( - blockchain_endpoint=f"ws://{LOOPBACK_ADDRESS}:8546", + endpoint=f"ws://{LOOPBACK_ADDRESS}:8546", expected_provider_class=WebsocketProvider, actual_provider_to_attach=MockWebSocketProvider(), ) @@ -275,7 +271,7 @@ def test_detect_provider_type_ws(): def test_infura_web3_client(): interface = InfuraTestClient( - blockchain_endpoint="wss://:@goerli.infura.io/ws/v3/1234567890987654321abcdef" + endpoint="wss://:@goerli.infura.io/ws/v3/1234567890987654321abcdef" ) interface.connect() @@ -293,7 +289,7 @@ def test_infura_web3_client(): def test_alchemy_web3_client(): interface = AlchemyTestClient( - blockchain_endpoint="https://eth-rinkeby.alchemyapi.io/v2/1234567890987654321abcdef" + endpoint="https://eth-rinkeby.alchemyapi.io/v2/1234567890987654321abcdef" ) interface.connect() @@ -306,7 +302,7 @@ def test_alchemy_web3_client(): def test_parity_web3_client(): - interface = ParityClientTestInterface(blockchain_endpoint="file:///ipc.parity") + interface = ParityClientTestInterface(endpoint="file:///ipc.parity") interface.connect() assert isinstance(interface.client, ParityClient) @@ -317,7 +313,7 @@ def test_parity_web3_client(): def test_ganache_web3_client(): - interface = GanacheClientTestInterface(blockchain_endpoint="http://ganache:8445") + interface = GanacheClientTestInterface(endpoint="http://ganache:8445") interface.connect() assert isinstance(interface.client, GanacheClient) diff --git a/tests/utils/blockchain.py b/tests/utils/blockchain.py index 8fe25a9a9..0cf4d807d 100644 --- a/tests/utils/blockchain.py +++ b/tests/utils/blockchain.py @@ -84,7 +84,7 @@ class TesterBlockchain(BlockchainInterface): ): EXPECTED_CONFIRMATION_TIME_IN_SECONDS["free"] = 5 # Just some upper-limit super().__init__( - blockchain_endpoint=self.ETH_PROVIDER_URI, + endpoint=self.ETH_PROVIDER_URI, poa=poa, light=light, *args, From 6a508e6aed830c1118760d9332e244f9a80035de Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 11:15:59 -0400 Subject: [PATCH 42/63] Yield after patching allowed domains. --- tests/utils/registry.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/utils/registry.py b/tests/utils/registry.py index bc07192cc..a232d8847 100644 --- a/tests/utils/registry.py +++ b/tests/utils/registry.py @@ -30,6 +30,8 @@ def mock_registry_sources(mocker): mocker.patch.object(RegistrySourceManager, "_FALLBACK_CHAIN", (MockRegistrySource,)) + yield # run the test + class MockRegistrySource(RegistrySource): name = "Mock Registry Source" From 51ceff7035d795babe6571e686b614f85ece1927 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 11:19:27 -0400 Subject: [PATCH 43/63] Update TEMPORARY_DOMAIN tester chains to use "eth-tester" as chain name instead. --- nucypher/blockchain/eth/domains.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/nucypher/blockchain/eth/domains.py b/nucypher/blockchain/eth/domains.py index 0000b16fc..a466dd808 100644 --- a/nucypher/blockchain/eth/domains.py +++ b/nucypher/blockchain/eth/domains.py @@ -1,8 +1,6 @@ from enum import Enum from typing import NamedTuple -from nucypher.config.constants import TEMPORARY_DOMAIN - class ChainInfo(NamedTuple): id: int @@ -13,13 +11,13 @@ class EthChain(ChainInfo, Enum): MAINNET = ChainInfo(1, "mainnet") GOERLI = ChainInfo(5, "goerli") SEPOLIA = ChainInfo(11155111, "sepolia") - TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) + TESTERCHAIN = ChainInfo(131277322940537, "eth-tester") class PolygonChain(ChainInfo, Enum): POLYGON = ChainInfo(137, "polygon") MUMBAI = ChainInfo(80001, "mumbai") - TESTERCHAIN = ChainInfo(131277322940537, TEMPORARY_DOMAIN) + TESTERCHAIN = ChainInfo(131277322940537, "eth-tester") class TACoDomain(NamedTuple): @@ -55,9 +53,6 @@ SUPPORTED_DOMAINS = [ SUPPORTED_DOMAIN_NAMES = [domain.name for domain in SUPPORTED_DOMAINS] -# TODO not needed once merged with registry changes -POLYGON_CHAINS = [domain.polygon_chain.name for domain in SUPPORTED_DOMAINS] - def from_domain_name(domain: str) -> TACoDomain: for taco_domain in SUPPORTED_DOMAINS: From cbb776f68b898166ce0fa47b188d5ee82a2a8348 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 11:20:41 -0400 Subject: [PATCH 44/63] Fix failing test (after rebase). --- tests/unit/test_teacher_nodes.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_teacher_nodes.py b/tests/unit/test_teacher_nodes.py index 38e743d2d..ac8b9f8a3 100644 --- a/tests/unit/test_teacher_nodes.py +++ b/tests/unit/test_teacher_nodes.py @@ -6,7 +6,13 @@ from nucypher.network.nodes import TEACHER_NODES @pytest.fixture(autouse=True) def mock_teacher_nodes(mocker): - # override fixture + # override fixture which mocks TEACHER_NODES + yield + + +@pytest.fixture(scope="module") +def test_registry(module_mocker): + # override fixture which mocks SUPPORTED_DOMAIN_NAMES yield From 9708efb0ba55e562632dcc99b8afbddf4a5a5fb4 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 11:21:29 -0400 Subject: [PATCH 45/63] Fix bug where filepath should be used with LocalRegistrySource and not with ContractRegistry directly. Use domain as parameter instead of network when calling get_registry(...) in utils. --- nucypher/cli/commands/taco.py | 2 +- nucypher/cli/utils.py | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/nucypher/cli/commands/taco.py b/nucypher/cli/commands/taco.py index 5467bcae0..0d35e5477 100644 --- a/nucypher/cli/commands/taco.py +++ b/nucypher/cli/commands/taco.py @@ -60,7 +60,7 @@ class RegistryOptions: def setup(self, general_config) -> tuple: emitter = setup_emitter(general_config) registry = get_registry( - network=self.domain, registry_filepath=self.registry_filepath + domain=self.domain, registry_filepath=self.registry_filepath ) return emitter, registry, self.blockchain_endpoint diff --git a/nucypher/cli/utils.py b/nucypher/cli/utils.py index e41642a96..cc2d8ca28 100644 --- a/nucypher/cli/utils.py +++ b/nucypher/cli/utils.py @@ -16,6 +16,7 @@ from nucypher.blockchain.eth.interfaces import ( ) from nucypher.blockchain.eth.registry import ( ContractRegistry, + LocalRegistrySource, ) from nucypher.characters.base import Character from nucypher.cli.actions.auth import ( @@ -102,12 +103,13 @@ def make_cli_character( def get_registry( - network: str, registry_filepath: Optional[Path] = None + domain: str, registry_filepath: Optional[Path] = None ) -> ContractRegistry: if registry_filepath: - registry = ContractRegistry(filepath=registry_filepath) + source = LocalRegistrySource(filepath=registry_filepath) + registry = ContractRegistry(source=source) else: - registry = ContractRegistry.from_latest_publication(domain=network) + registry = ContractRegistry.from_latest_publication(domain=domain) return registry From 568270d36c8bbff843835f68f422449b600b8ef3 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 13:12:30 -0400 Subject: [PATCH 46/63] Allow MockRegistrySource to take any domain value while allowing the accepted values to be specified. Update various tests that used random domain values to either use the mock, or just use TEMPORARY_DOMAIN if applicable. --- .../characters/test_ursula_startup.py | 6 +- tests/integration/learning/test_domains.py | 134 +++++++++++++----- .../learning/test_firstula_circumstances.py | 7 +- tests/utils/registry.py | 27 ++-- 4 files changed, 130 insertions(+), 44 deletions(-) diff --git a/tests/integration/characters/test_ursula_startup.py b/tests/integration/characters/test_ursula_startup.py index 1ae13479c..0ce1a8635 100644 --- a/tests/integration/characters/test_ursula_startup.py +++ b/tests/integration/characters/test_ursula_startup.py @@ -1,9 +1,11 @@ import pytest +from nucypher.config.constants import TEMPORARY_DOMAIN + def test_new_ursula_announces_herself(lonely_ursula_maker): ursula_in_a_house, ursula_with_a_mouse = lonely_ursula_maker( - quantity=2, domain="useless_domain" + quantity=2, domain=TEMPORARY_DOMAIN ) # Neither Ursula knows about the other. @@ -36,7 +38,7 @@ def test_goerli_and_mumbai_as_conditions_providers(lonely_ursula_maker): with pytest.raises(NotImplementedError): _ursula_who_tries_to_connect_to_an_invalid_chain = lonely_ursula_maker( quantity=1, - domain="useless_domain", + domain=TEMPORARY_DOMAIN, condition_blockchain_endpoints={ INVALID_CHAIN_ID: "this is a provider URI, but it doesn't matter what we pass here because the chain_id is invalid." }, diff --git a/tests/integration/learning/test_domains.py b/tests/integration/learning/test_domains.py index e7a9a9e50..2a6fe0359 100644 --- a/tests/integration/learning/test_domains.py +++ b/tests/integration/learning/test_domains.py @@ -2,22 +2,62 @@ from pathlib import Path import pytest +import tests from nucypher.acumen.perception import FleetSensor +from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.characters.lawful import Ursula from nucypher.config.storages import LocalFileBasedNodeStorage from nucypher.network.nodes import TEACHER_NODES +from tests.utils.registry import MockRegistrySource from tests.utils.ursula import make_ursulas -@pytest.mark.usefixtures("test_registry_source_manager") -def test_learner_learns_about_domains_separately(lonely_ursula_maker, caplog): +@pytest.fixture(scope="module") +def domain_1(): + return "domain_uno" + + +@pytest.fixture(scope="module") +def domain_2(): + return "domain_dos" + + +@pytest.fixture(scope="module") +def test_registry(module_mocker, domain_1, domain_2): + with tests.utils.registry.mock_registry_sources( + mocker=module_mocker, domain_names=[domain_1, domain_2] + ): + # doesn't really matter what domain is used here + registry = ContractRegistry(MockRegistrySource(domain=domain_1)) + yield registry + + +@pytest.fixture(scope="module") +def registry_1(domain_1, test_registry): + return ContractRegistry(MockRegistrySource(domain=domain_1)) + + +@pytest.fixture(scope="module") +def registry_2(domain_2, test_registry): + return ContractRegistry(MockRegistrySource(domain=domain_2)) + + +def test_learner_learns_about_domains_separately( + lonely_ursula_maker, domain_1, domain_2, registry_1, registry_2, caplog +): hero_learner, other_first_domain_learner = lonely_ursula_maker( - domain="nucypher1.test_suite", quantity=2 + domain=domain_1, + registry=registry_1, + quantity=2, ) - _nobody = lonely_ursula_maker(domain="nucypher1.test_suite", quantity=1).pop() + _nobody = lonely_ursula_maker( + domain=domain_1, registry=registry_1, quantity=1 + ).pop() other_first_domain_learner.remember_node(_nobody) - second_domain_learners = lonely_ursula_maker(domain="nucypher2.test_suite", know_each_other=True, quantity=3) + second_domain_learners = lonely_ursula_maker( + domain=domain_2, registry=registry_2, know_each_other=True, quantity=3 + ) assert len(hero_learner.known_nodes) == 0 @@ -36,8 +76,12 @@ def test_learner_learns_about_domains_separately(lonely_ursula_maker, caplog): # All domain 1 nodes assert len(hero_learner.known_nodes) == 2 - new_first_domain_learner = lonely_ursula_maker(domain="nucypher1.test_suite", quantity=1).pop() - _new_second_domain_learner = lonely_ursula_maker(domain="nucypher2.test_suite", quantity=1).pop() + new_first_domain_learner = lonely_ursula_maker( + domain=domain_1, registry=registry_1, quantity=1 + ).pop() + _new_second_domain_learner = lonely_ursula_maker( + domain=domain_2, registry=registry_2, quantity=1 + ).pop() new_first_domain_learner.remember_node(hero_learner) @@ -52,7 +96,9 @@ def test_learner_learns_about_domains_separately(lonely_ursula_maker, caplog): assert _nobody in new_first_domain_learner.known_nodes -def test_learner_restores_metadata_from_storage(lonely_ursula_maker, tmpdir): +def test_learner_restores_metadata_from_storage( + lonely_ursula_maker, tmpdir, domain_1, domain_2 +): # Create a local file-based node storage root = tmpdir.mkdir("known_nodes") metadata = root.mkdir("metadata") @@ -62,20 +108,24 @@ def test_learner_restores_metadata_from_storage(lonely_ursula_maker, tmpdir): storage_root=Path(root)) # Use the ursula maker with this storage so it's populated with nodes from one domain - _some_ursulas = lonely_ursula_maker(domain="fistro", - node_storage=old_storage, - know_each_other=True, - quantity=3, - save_metadata=True) + _some_ursulas = lonely_ursula_maker( + domain=domain_1, + node_storage=old_storage, + know_each_other=True, + quantity=3, + save_metadata=True, + ) # Create a pair of new learners in a different domain, using the previous storage, and learn from it - new_learners = lonely_ursula_maker(domain="duodenal", - node_storage=old_storage, - quantity=2, - know_each_other=True, - save_metadata=False) + new_learners = lonely_ursula_maker( + domain=domain_2, + node_storage=old_storage, + quantity=2, + know_each_other=True, + save_metadata=False, + ) learner, buddy = new_learners - buddy._Learner__known_nodes = FleetSensor(domain="fistro") + buddy._Learner__known_nodes = FleetSensor(domain=domain_1) # The learner shouldn't learn about any node from the first domain, since it's different. learner.learn_from_teacher_node() @@ -88,11 +138,19 @@ def test_learner_restores_metadata_from_storage(lonely_ursula_maker, tmpdir): def test_learner_ignores_stored_nodes_from_other_domains( - lonely_ursula_maker, tmpdir, testerchain, ursula_test_config + lonely_ursula_maker, + domain_1, + domain_2, + registry_1, + registry_2, + tmpdir, + testerchain, + ursula_test_config, ): learner, other_staker = make_ursulas( ursula_test_config, - domain="call-it-mainnet", + domain=domain_1, + registry=registry_1, quantity=2, know_each_other=True, staking_provider_addresses=testerchain.stake_providers_accounts[:2], @@ -101,7 +159,8 @@ def test_learner_ignores_stored_nodes_from_other_domains( pest, *other_ursulas_from_the_wrong_side_of_the_tracks = make_ursulas( ursula_test_config, - domain="i-dunno-testt-maybe", + domain=domain_2, + registry=registry_2, quantity=5, know_each_other=True, staking_provider_addresses=testerchain.stake_providers_accounts[2:], @@ -129,13 +188,16 @@ def test_learner_ignores_stored_nodes_from_other_domains( assert pest not in other_staker.known_nodes # But not anymore. -def test_learner_with_empty_storage_uses_fallback_nodes(lonely_ursula_maker, mocker): - domain = "learner-domain" - mocker.patch.dict(TEACHER_NODES, {domain: ("teacher-uri",)}, clear=True) +def test_learner_with_empty_storage_uses_fallback_nodes( + lonely_ursula_maker, domain_1, mocker +): + mocker.patch.dict(TEACHER_NODES, {domain_1: ("teacher-uri",)}, clear=True) # Create a learner and a teacher - learner, teacher = lonely_ursula_maker(domain=domain, quantity=2, save_metadata=False) - mocker.patch.object(Ursula, 'from_teacher_uri', return_value=teacher) + learner, teacher = lonely_ursula_maker( + domain=domain_1, quantity=2, save_metadata=False + ) + mocker.patch.object(Ursula, "from_teacher_uri", return_value=teacher) # Since there are no nodes in local node storage, the learner should only learn about the teacher learner.learn_from_teacher_node() @@ -143,10 +205,16 @@ def test_learner_with_empty_storage_uses_fallback_nodes(lonely_ursula_maker, moc def test_learner_uses_both_nodes_from_storage_and_fallback_nodes( - lonely_ursula_maker, tmpdir, mocker, test_registry, ursula_test_config, testerchain + lonely_ursula_maker, + domain_1, + registry_1, + tmpdir, + mocker, + test_registry, + ursula_test_config, + testerchain, ): - domain = "learner-domain" - mocker.patch.dict(TEACHER_NODES, {domain: ("teacher-uri",)}, clear=True) + mocker.patch.dict(TEACHER_NODES, {domain_1: ("teacher-uri",)}, clear=True) # Create a local file-based node storage root = tmpdir.mkdir("known_nodes") @@ -159,7 +227,8 @@ def test_learner_uses_both_nodes_from_storage_and_fallback_nodes( # Create some nodes and persist them to local storage other_nodes = make_ursulas( ursula_test_config, - domain=domain, + domain=domain_1, + registry=registry_1, node_storage=node_storage, know_each_other=True, quantity=3, @@ -170,7 +239,8 @@ def test_learner_uses_both_nodes_from_storage_and_fallback_nodes( # Create a teacher and a learner using existing node storage learner, teacher = lonely_ursula_maker( - domain=domain, + domain=domain_1, + registry=registry_1, node_storage=node_storage, quantity=2, know_each_other=True, diff --git a/tests/integration/learning/test_firstula_circumstances.py b/tests/integration/learning/test_firstula_circumstances.py index 31f6eb92a..a0de34de2 100644 --- a/tests/integration/learning/test_firstula_circumstances.py +++ b/tests/integration/learning/test_firstula_circumstances.py @@ -3,15 +3,18 @@ from functools import partial import pytest_twisted as pt from twisted.internet.threads import deferToThread +from nucypher.config.constants import TEMPORARY_DOMAIN from nucypher.network.middleware import RestMiddleware from tests.constants import MOCK_ETH_PROVIDER_URI def test_proper_seed_node_instantiation(lonely_ursula_maker): _lonely_ursula_maker = partial(lonely_ursula_maker, quantity=1) - firstula = _lonely_ursula_maker(domain="this-is-meaningful-now").pop() + firstula = _lonely_ursula_maker(domain=TEMPORARY_DOMAIN).pop() firstula_as_seed_node = firstula.seed_node_metadata() - any_other_ursula = _lonely_ursula_maker(seed_nodes=[firstula_as_seed_node], domain="this-is-meaningful-now").pop() + any_other_ursula = _lonely_ursula_maker( + seed_nodes=[firstula_as_seed_node], domain=TEMPORARY_DOMAIN + ).pop() assert not any_other_ursula.known_nodes any_other_ursula.start_learning_loop(now=True) diff --git a/tests/utils/registry.py b/tests/utils/registry.py index a232d8847..c288b2409 100644 --- a/tests/utils/registry.py +++ b/tests/utils/registry.py @@ -20,13 +20,22 @@ from nucypher.config.constants import TEMPORARY_DOMAIN @contextmanager -def mock_registry_sources(mocker): - test_domain = TACoDomain( - TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN - ) +def mock_registry_sources(mocker, domain_names: List[str] = None): + if not domain_names: + domain_names = [TEMPORARY_DOMAIN] - mocker.patch.object(domains, "SUPPORTED_DOMAINS", [test_domain]) - mocker.patch.object(domains, "SUPPORTED_DOMAIN_NAMES", [TEMPORARY_DOMAIN]) + supported_domains = [] + supported_domain_names = [] + for domain_name in domain_names: + test_domain = TACoDomain( + domain_name, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN + ) + supported_domains.append(test_domain) + supported_domain_names.append(domain_name) + + mocker.patch.object(domains, "SUPPORTED_DOMAINS", supported_domains) + mocker.patch.object(domains, "SUPPORTED_DOMAIN_NAMES", supported_domain_names) + mocker.patch.object(MockRegistrySource, "ALLOWED_DOMAINS", domain_names) mocker.patch.object(RegistrySourceManager, "_FALLBACK_CHAIN", (MockRegistrySource,)) @@ -34,15 +43,17 @@ def mock_registry_sources(mocker): class MockRegistrySource(RegistrySource): + ALLOWED_DOMAINS = [TEMPORARY_DOMAIN] + name = "Mock Registry Source" is_primary = False def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - if self.domain != TEMPORARY_DOMAIN: + if self.domain not in self.ALLOWED_DOMAINS: raise ValueError( f"Somehow, MockRegistrySource is trying to get a registry for '{self.domain}'. " - f"Only '{TEMPORARY_DOMAIN}' is supported.'" + f"Only '{','.join(self.ALLOWED_DOMAINS)}' are supported.'" ) @property From f79ad31ee23700b9d525348a87d0f031895d8f44 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 13:14:56 -0400 Subject: [PATCH 47/63] Don't use TACoDomain object in examples since not really needed. --- examples/testnet_compound_multichain_taco.py | 7 +++---- examples/testnet_simple_taco.py | 7 +++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/examples/testnet_compound_multichain_taco.py b/examples/testnet_compound_multichain_taco.py index 001840387..2f1ba23b8 100644 --- a/examples/testnet_compound_multichain_taco.py +++ b/examples/testnet_compound_multichain_taco.py @@ -2,7 +2,6 @@ import os from nucypher_core.ferveo import DkgPublicKey -from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import CoordinatorAgent from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner @@ -20,7 +19,7 @@ GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] -taco_domain = domains.from_domain_name("lynx") +domain = "lynx" polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] @@ -31,7 +30,7 @@ polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] print("--------- Threshold Encryption ---------") registry = ContractRegistry.from_latest_publication( - domain=taco_domain.name, + domain=domain, ) coordinator_agent = CoordinatorAgent( @@ -100,7 +99,7 @@ print(f"\nEncrypted message:\n{bytes(threshold_message_kit).hex()}") print("--------- Threshold Decryption ---------") bob = Bob( - domain=taco_domain.name, + domain=domain, eth_endpoint=eth_endpoint, polygon_endpoint=polygon_endpoint, registry=registry, diff --git a/examples/testnet_simple_taco.py b/examples/testnet_simple_taco.py index 34bafdf97..2665afe3f 100644 --- a/examples/testnet_simple_taco.py +++ b/examples/testnet_simple_taco.py @@ -2,7 +2,6 @@ import os from nucypher_core.ferveo import DkgPublicKey -from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import CoordinatorAgent from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner @@ -20,7 +19,7 @@ GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] -taco_domain = domains.from_domain_name("lynx") +domain = "lynx" polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] @@ -31,7 +30,7 @@ polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] print("--------- Threshold Encryption ---------") registry = ContractRegistry.from_latest_publication( - domain=taco_domain.name, + domain=domain, ) coordinator_agent = CoordinatorAgent( @@ -77,7 +76,7 @@ print(f"\nEncrypted message:\n{bytes(threshold_message_kit).hex()}") print("--------- Threshold Decryption ---------") bob = Bob( - domain=taco_domain.name, + domain=domain, eth_endpoint=eth_endpoint, polygon_endpoint=polygon_endpoint, registry=registry, From 35681e9bd9a4a80c0fc3af850d342247b5dd8afc Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 13:15:31 -0400 Subject: [PATCH 48/63] Don't create new TACoDomain object when one is already available via the superclass (Character). --- nucypher/config/characters.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index 781e3a0bf..1206d8cfb 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -5,7 +5,6 @@ from typing import Dict, List, Optional from cryptography.x509 import Certificate from eth_utils import is_checksum_address -from nucypher.blockchain.eth import domains from nucypher.config.base import CharacterConfiguration from nucypher.config.constants import ( NUCYPHER_ENVVAR_ALICE_ETH_PASSWORD, @@ -70,10 +69,8 @@ class UrsulaConfiguration(CharacterConfiguration): def configure_condition_blockchain_endpoints(self) -> None: """Configure default condition provider URIs for eth and polygon network.""" - taco_domain = domains.from_domain_name(self.domain) - # Polygon - polygon_chain_id = taco_domain.polygon_chain.id + polygon_chain_id = self.taco_domain.polygon_chain.id polygon_endpoints = self.condition_blockchain_endpoints.get( polygon_chain_id, [] ) @@ -84,7 +81,7 @@ class UrsulaConfiguration(CharacterConfiguration): polygon_endpoints.append(self.polygon_endpoint) # Ethereum - staking_chain_id = taco_domain.eth_chain.id + staking_chain_id = self.taco_domain.eth_chain.id staking_chain_endpoints = self.condition_blockchain_endpoints.get( staking_chain_id, [] ) From 9ee7b9e7efc809667f1036bb6c3181d54c86a3fd Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 15:11:59 -0400 Subject: [PATCH 49/63] Rename test class to prevent pytest warning about it starting with "Test". --- tests/integration/utilities/test_integration_concurrency.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/integration/utilities/test_integration_concurrency.py b/tests/integration/utilities/test_integration_concurrency.py index 30bdea6d5..3eea06dbe 100644 --- a/tests/integration/utilities/test_integration_concurrency.py +++ b/tests/integration/utilities/test_integration_concurrency.py @@ -232,7 +232,7 @@ def test_join(join_worker_pool): assert t_end - t_start < 3 -class TestBatchValueFactory(BatchValueFactory): +class BatchTrackingBatchValueFactory(BatchValueFactory): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.batch_sizes = [] @@ -258,7 +258,9 @@ def test_batched_value_generation(join_worker_pool): seed=123, ) - factory = TestBatchValueFactory(values=list(outcomes), required_successes=10) + factory = BatchTrackingBatchValueFactory( + values=list(outcomes), required_successes=10 + ) pool = WorkerPool( worker, factory, From 7c4c43b1c8fe4dd7d2965e69a49d11224d463c4c Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 15:15:06 -0400 Subject: [PATCH 50/63] Fix darker linting issues. --- nucypher/blockchain/eth/actors.py | 5 +---- nucypher/characters/base.py | 7 +++---- scripts/hooks/nucypher_dkg.py | 4 +--- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index 7056b2da3..c85cc0b32 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -207,10 +207,7 @@ class Operator(BaseActor): registry=self.registry, ) - # TODO: registry usage (and subsequently "network") is inconsistent here - registry = ContractRegistry.from_latest_publication( - domain=self.network - ) + registry = ContractRegistry.from_latest_publication(domain=self.network) self.child_application_agent = ContractAgency.get_agent( TACoChildApplicationAgent, registry=registry, diff --git a/nucypher/characters/base.py b/nucypher/characters/base.py index 529aed9c2..aca564d67 100644 --- a/nucypher/characters/base.py +++ b/nucypher/characters/base.py @@ -117,10 +117,9 @@ class Character(Learner): self.eth_endpoint = eth_endpoint self.polygon_endpoint = polygon_endpoint - self.registry = ( - registry - or ContractRegistry.from_latest_publication(domain=domain) - ) # See #1580 + self.registry = registry or ContractRegistry.from_latest_publication( + domain=domain + ) # REST self.network_middleware = network_middleware or RestMiddleware( diff --git a/scripts/hooks/nucypher_dkg.py b/scripts/hooks/nucypher_dkg.py index 6ab82754a..89cc631d6 100644 --- a/scripts/hooks/nucypher_dkg.py +++ b/scripts/hooks/nucypher_dkg.py @@ -155,9 +155,7 @@ def nucypher_dkg( ) taco_domain = domains.from_domain_name(domain) - registry = ContractRegistry.from_latest_publication( - domain=domain - ) + registry = ContractRegistry.from_latest_publication(domain=domain) coordinator_agent = ContractAgency.get_agent( agent_class=CoordinatorAgent, registry=registry, From 5b7a56a804f9127da057a1c57989a8305304867d Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 15:18:46 -0400 Subject: [PATCH 51/63] Update test to eagerly learn about nodes. --- tests/integration/learning/test_domains.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/integration/learning/test_domains.py b/tests/integration/learning/test_domains.py index 2a6fe0359..16ed03713 100644 --- a/tests/integration/learning/test_domains.py +++ b/tests/integration/learning/test_domains.py @@ -64,14 +64,14 @@ def test_learner_learns_about_domains_separately( # Learn from a teacher in our domain. hero_learner.remember_node(other_first_domain_learner) hero_learner.start_learning_loop(now=True) - hero_learner.learn_from_teacher_node() + hero_learner.learn_from_teacher_node(eager=True) # All domain 1 nodes assert len(hero_learner.known_nodes) == 2 # Learn about the second domain. hero_learner._current_teacher_node = second_domain_learners.pop() - hero_learner.learn_from_teacher_node() + hero_learner.learn_from_teacher_node(eager=True) # All domain 1 nodes assert len(hero_learner.known_nodes) == 2 @@ -85,7 +85,7 @@ def test_learner_learns_about_domains_separately( new_first_domain_learner.remember_node(hero_learner) - new_first_domain_learner.learn_from_teacher_node() + new_first_domain_learner.learn_from_teacher_node(eager=True) # This node, in the first domain, didn't learn about the second domain. assert not set(second_domain_learners).intersection(new_first_domain_learner.known_nodes) From 681bc3e299b69dcbb174307a6109f1768ae33e1f Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 15:19:57 -0400 Subject: [PATCH 52/63] Remove unused/commented functions from NuCypherTokenActor. --- nucypher/blockchain/eth/actors.py | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index c85cc0b32..5a4076a88 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -130,24 +130,6 @@ class NucypherTokenActor(BaseActor): super().__init__(registry=registry, **kwargs) self.__token_agent = None - # @property - # def token_agent(self): - # if self.__token_agent: - # return self.__token_agent - # self.__token_agent = ContractAgency.get_agent( - # NucypherTokenAgent, - # blockchain_endpoint=self.eth_provider_uri, # TODO this is fishy - and doesn't seem needed? - # registry=self.registry, - # ) - # return self.__token_agent - # - # @property - # def token_balance(self) -> NU: - # """Return this actor's current token balance""" - # balance = int(self.token_agent.get_balance(address=self.checksum_address)) - # nu_balance = NU(balance, 'NuNit') - # return nu_balance - class Operator(BaseActor): READY_TIMEOUT = None # (None or 0) == indefinite From ee6a48070f91e70dd283de97fd061ecebb2e85ec Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 15:41:56 -0400 Subject: [PATCH 53/63] Remove policy_registry/policy_registry_filepath which are unused and unnecessary parameters. --- nucypher/cli/commands/ursula.py | 8 ------- nucypher/cli/options.py | 5 ---- nucypher/config/base.py | 23 +------------------ .../config/test_character_configuration.py | 2 -- tests/utils/config.py | 2 -- 5 files changed, 1 insertion(+), 39 deletions(-) diff --git a/nucypher/cli/commands/ursula.py b/nucypher/cli/commands/ursula.py index fe1053274..37d11d849 100644 --- a/nucypher/cli/commands/ursula.py +++ b/nucypher/cli/commands/ursula.py @@ -44,7 +44,6 @@ from nucypher.cli.options import ( option_max_gas_price, option_min_stake, option_poa, - option_policy_registry_filepath, option_polygon_endpoint, option_pre_payment_method, option_registry_filepath, @@ -79,7 +78,6 @@ class UrsulaConfigOptions: rest_port: int, domain: str, registry_filepath: Path, - policy_registry_filepath: Path, dev: bool, poa: bool, light: bool, @@ -98,7 +96,6 @@ class UrsulaConfigOptions: self.rest_port = rest_port # FIXME: not used in generate() self.domain = domain self.registry_filepath = registry_filepath - self.policy_registry_filepath = policy_registry_filepath self.dev = dev self.poa = poa self.light = light @@ -117,7 +114,6 @@ class UrsulaConfigOptions: poa=self.poa, light=self.light, registry_filepath=self.registry_filepath, - policy_registry_filepath=self.policy_registry_filepath, eth_endpoint=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, @@ -139,7 +135,6 @@ class UrsulaConfigOptions: filepath=config_file, domain=self.domain, registry_filepath=self.registry_filepath, - policy_registry_filepath=self.policy_registry_filepath, eth_endpoint=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, @@ -192,7 +187,6 @@ class UrsulaConfigOptions: domain=self.domain, operator_address=self.operator_address, registry_filepath=self.registry_filepath, - policy_registry_filepath=self.policy_registry_filepath, eth_endpoint=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, @@ -210,7 +204,6 @@ class UrsulaConfigOptions: domain=self.domain, operator_address=self.operator_address, registry_filepath=self.registry_filepath, - policy_registry_filepath=self.policy_registry_filepath, eth_endpoint=self.eth_endpoint, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, @@ -249,7 +242,6 @@ group_config_options = group_options( ), domain=option_domain(), registry_filepath=option_registry_filepath, - policy_registry_filepath=option_policy_registry_filepath, poa=option_poa, light=option_light, dev=option_dev, diff --git a/nucypher/cli/options.py b/nucypher/cli/options.py index a32ad4edf..ff7a0a43e 100644 --- a/nucypher/cli/options.py +++ b/nucypher/cli/options.py @@ -100,11 +100,6 @@ option_registry_filepath = click.option( help="Custom contract registry filepath", type=EXISTING_READABLE_FILE, ) -option_policy_registry_filepath = click.option( - "--policy-registry-filepath", - help="Custom contract registry filepath for policies", - type=EXISTING_READABLE_FILE, -) option_signer_uri = click.option("--signer", "signer_uri", "-S", default=None, type=str) option_staking_provider = click.option( "--staking-provider", diff --git a/nucypher/config/base.py b/nucypher/config/base.py index 2029759c7..aeed5db98 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -376,8 +376,6 @@ class CharacterConfiguration(BaseConfiguration): # Registries registry: Optional[ContractRegistry] = None, registry_filepath: Optional[Path] = None, - policy_registry: Optional[ContractRegistry] = None, - policy_registry_filepath: Optional[Path] = None, ): self.log = Logger(self.__class__.__name__) @@ -408,9 +406,6 @@ class CharacterConfiguration(BaseConfiguration): self.registry = registry or NO_BLOCKCHAIN_CONNECTION.bool_value(False) self.registry_filepath = registry_filepath or UNINITIALIZED_CONFIGURATION - self.policy_registry = policy_registry or NO_BLOCKCHAIN_CONNECTION.bool_value(False) - self.policy_registry_filepath = policy_registry_filepath or UNINITIALIZED_CONFIGURATION - # Blockchain self.poa = poa self.is_light = light @@ -474,22 +469,6 @@ class CharacterConfiguration(BaseConfiguration): pre_payment_method or self.DEFAULT_PRE_PAYMENT_METHOD ) - # TODO: Dedupe - if not self.policy_registry: - if not self.policy_registry_filepath: - self.log.info("Fetching latest policy registry from source.") - self.policy_registry = ContractRegistry.from_latest_publication( - domain=self.taco_domain.name - ) - else: - source = LocalRegistrySource( - domain=self.domain, filepath=self.policy_registry_filepath - ) - self.policy_registry = ContractRegistry(source=source) - self.log.info( - f"Using local policy registry ({self.policy_registry})." - ) - if dev_mode: self.__temp_dir = UNINITIALIZED_CONFIGURATION self._setup_node_storage() @@ -857,7 +836,7 @@ class CharacterConfiguration(BaseConfiguration): pre_payment_strategy = pre_payment_class( domain=self.taco_domain.name, blockchain_endpoint=self.polygon_endpoint, - registry=self.policy_registry, + registry=self.registry, ) else: pre_payment_strategy = pre_payment_class() diff --git a/tests/integration/config/test_character_configuration.py b/tests/integration/config/test_character_configuration.py index 3ff7c2ce6..7df840d54 100644 --- a/tests/integration/config/test_character_configuration.py +++ b/tests/integration/config/test_character_configuration.py @@ -127,7 +127,6 @@ def test_default_character_configuration_preservation( domain=domain, rest_host=MOCK_IP_ADDRESS, polygon_endpoint=MOCK_ETH_PROVIDER_URI, - policy_registry=test_registry, keystore=keystore, ) @@ -136,7 +135,6 @@ def test_default_character_configuration_preservation( checksum_address=fake_address, eth_endpoint=MOCK_ETH_PROVIDER_URI, domain=domain, - policy_registry=test_registry, ) generated_filepath = character_config.generate_filepath() diff --git a/tests/utils/config.py b/tests/utils/config.py index c864930c2..7ce773337 100644 --- a/tests/utils/config.py +++ b/tests/utils/config.py @@ -56,7 +56,6 @@ def make_ursula_test_configuration( rest_port=rest_port, polygon_endpoint=polygon_endpoint, operator_address=operator_address, - policy_registry=test_params["registry"] ) return ursula_config @@ -68,7 +67,6 @@ def make_alice_test_configuration( config = AliceConfiguration( **test_params, polygon_endpoint=polygon_endpoint, - policy_registry=test_params["registry"] ) return config From d8b9180921b805bbb9e30bacb72c889604c1d815 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Wed, 4 Oct 2023 22:09:40 -0400 Subject: [PATCH 54/63] Update domains/TACoDomain structure. Added magic methods. --- examples/local_simple_taco.py | 3 +- .../finnegans-wake-demo-l2.py | 5 +- examples/pre/heartbeat_demo/alicia.py | 3 +- examples/pre/heartbeat_demo/doctor.py | 3 +- examples/testnet_compound_multichain_taco.py | 3 +- examples/testnet_simple_taco.py | 3 +- nucypher/blockchain/eth/actors.py | 4 +- nucypher/blockchain/eth/domains.py | 73 ++++++++++--------- nucypher/blockchain/eth/registry.py | 6 +- nucypher/cli/actions/select.py | 6 +- nucypher/cli/commands/taco.py | 4 +- nucypher/cli/types.py | 6 +- nucypher/config/base.py | 10 +-- nucypher/config/characters.py | 4 +- .../migrations/configuration_v5_to_v6.py | 8 +- nucypher/network/nodes.py | 12 +-- nucypher/policy/payment.py | 4 +- scripts/hooks/nucypher_agents.py | 6 +- scripts/hooks/nucypher_dkg.py | 10 +-- tests/acceptance/conftest.py | 7 +- tests/conftest.py | 7 +- .../characters/test_dkg_and_testnet_bypass.py | 3 +- .../cli/actions/test_select_network.py | 4 +- tests/integration/conftest.py | 7 +- tests/unit/test_teacher_nodes.py | 4 +- tests/utils/registry.py | 8 +- 26 files changed, 115 insertions(+), 98 deletions(-) diff --git a/examples/local_simple_taco.py b/examples/local_simple_taco.py index d0c7038a5..8bd115e1d 100644 --- a/examples/local_simple_taco.py +++ b/examples/local_simple_taco.py @@ -1,3 +1,4 @@ +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.signers import InMemorySigner from nucypher.characters.chaotic import NiceGuyEddie as _Enrico from nucypher.characters.chaotic import ThisBobAlwaysDecrypts @@ -8,7 +9,7 @@ THIS_IS_NOT_A_TRINKET = 55 # sometimes called "public key" signer = InMemorySigner() enrico = _Enrico(encrypting_key=THIS_IS_NOT_A_TRINKET, signer=signer) -bob = ThisBobAlwaysDecrypts(domain="lynx", eth_endpoint="Nowhere") +bob = ThisBobAlwaysDecrypts(domain=TACoDomain.LYNX.name, eth_endpoint="Nowhere") ANYTHING_CAN_BE_PASSED_AS_RITUAL_ID = 55 diff --git a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py index dd81aa17f..2d65255c8 100644 --- a/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py +++ b/examples/pre/finnegans_wake_demo/finnegans-wake-demo-l2.py @@ -5,6 +5,7 @@ from pathlib import Path import maya +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.signers.base import Signer from nucypher.characters.lawful import Alice, Bob from nucypher.characters.lawful import Enrico as Enrico @@ -41,10 +42,10 @@ except KeyError: print("\n************** Setup **************\n") ########## -# DOMAIN # +# Domain # ########## -TACO_DOMAIN = "lynx" +TACO_DOMAIN = TACoDomain.LYNX.name ##################### # Bob the BUIDLer ## diff --git a/examples/pre/heartbeat_demo/alicia.py b/examples/pre/heartbeat_demo/alicia.py index 0cbfb1fa4..f043263ca 100644 --- a/examples/pre/heartbeat_demo/alicia.py +++ b/examples/pre/heartbeat_demo/alicia.py @@ -24,6 +24,7 @@ from pathlib import Path import maya +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.signers import Signer from nucypher.characters.lawful import Alice, Bob from nucypher.policy.payment import SubscriptionManagerPayment @@ -57,7 +58,7 @@ try: except KeyError: raise RuntimeError("Missing environment variables to run demo.") -TACO_DOMAIN = "lynx" +TACO_DOMAIN = TACoDomain.LYNX.name ####################################### diff --git a/examples/pre/heartbeat_demo/doctor.py b/examples/pre/heartbeat_demo/doctor.py index 21b1cd286..63c2e6fb6 100644 --- a/examples/pre/heartbeat_demo/doctor.py +++ b/examples/pre/heartbeat_demo/doctor.py @@ -9,6 +9,7 @@ import msgpack from nucypher_core import EncryptedTreasureMap, MessageKit from nucypher_core.umbral import PublicKey +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.characters.lawful import Bob from nucypher.crypto.keypairs import DecryptingKeypair, SigningKeypair from nucypher.crypto.powers import DecryptingPower, SigningPower @@ -27,7 +28,7 @@ except KeyError: raise RuntimeError("Missing environment variables to run demo.") -TACO_DOMAIN = "lynx" +TACO_DOMAIN = TACoDomain.LYNX.name # To create a Bob, we need the doctor's private keys previously generated. from doctor_keys import get_doctor_privkeys # noqa: E402 diff --git a/examples/testnet_compound_multichain_taco.py b/examples/testnet_compound_multichain_taco.py index 2f1ba23b8..5a2514939 100644 --- a/examples/testnet_compound_multichain_taco.py +++ b/examples/testnet_compound_multichain_taco.py @@ -3,6 +3,7 @@ import os from nucypher_core.ferveo import DkgPublicKey from nucypher.blockchain.eth.agents import CoordinatorAgent +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner from nucypher.characters.lawful import Bob, Enrico @@ -19,7 +20,7 @@ GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] -domain = "lynx" +domain = TACoDomain.LYNX.name polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] diff --git a/examples/testnet_simple_taco.py b/examples/testnet_simple_taco.py index 2665afe3f..93a079621 100644 --- a/examples/testnet_simple_taco.py +++ b/examples/testnet_simple_taco.py @@ -3,6 +3,7 @@ import os from nucypher_core.ferveo import DkgPublicKey from nucypher.blockchain.eth.agents import CoordinatorAgent +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner from nucypher.characters.lawful import Bob, Enrico @@ -19,7 +20,7 @@ GlobalLoggerSettings.set_log_level(log_level_name=LOG_LEVEL) GlobalLoggerSettings.start_console_logging() eth_endpoint = os.environ["DEMO_L1_PROVIDER_URI"] -domain = "lynx" +domain = TACoDomain.LYNX.name polygon_endpoint = os.environ["DEMO_L2_PROVIDER_URI"] diff --git a/nucypher/blockchain/eth/actors.py b/nucypher/blockchain/eth/actors.py index 5a4076a88..ced806495 100644 --- a/nucypher/blockchain/eth/actors.py +++ b/nucypher/blockchain/eth/actors.py @@ -27,7 +27,6 @@ from web3 import HTTPProvider, Web3 from web3.types import TxReceipt from nucypher.acumen.nicknames import Nickname -from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ( ContractAgency, CoordinatorAgent, @@ -37,6 +36,7 @@ from nucypher.blockchain.eth.agents import ( from nucypher.blockchain.eth.clients import PUBLIC_CHAINS from nucypher.blockchain.eth.constants import NULL_ADDRESS from nucypher.blockchain.eth.decorators import validate_checksum_address +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.registry import ( ContractRegistry, @@ -93,7 +93,7 @@ class BaseActor: self.transacting_power = transacting_power self.registry = registry self.network = domain - self.taco_domain = domains.from_domain_name(self.network) + self.taco_domain_info = TACoDomain.get_domain_info(self.network) self._saved_receipts = list() # track receipts of transmitted transactions def __repr__(self): diff --git a/nucypher/blockchain/eth/domains.py b/nucypher/blockchain/eth/domains.py index a466dd808..abf3b5366 100644 --- a/nucypher/blockchain/eth/domains.py +++ b/nucypher/blockchain/eth/domains.py @@ -8,55 +8,62 @@ class ChainInfo(NamedTuple): class EthChain(ChainInfo, Enum): - MAINNET = ChainInfo(1, "mainnet") - GOERLI = ChainInfo(5, "goerli") - SEPOLIA = ChainInfo(11155111, "sepolia") - TESTERCHAIN = ChainInfo(131277322940537, "eth-tester") + MAINNET = (1, "mainnet") + GOERLI = (5, "goerli") + SEPOLIA = (11155111, "sepolia") + TESTERCHAIN = (131277322940537, "eth-tester") class PolygonChain(ChainInfo, Enum): - POLYGON = ChainInfo(137, "polygon") - MUMBAI = ChainInfo(80001, "mumbai") - TESTERCHAIN = ChainInfo(131277322940537, "eth-tester") + POLYGON = (137, "polygon") + MUMBAI = (80001, "mumbai") + TESTERCHAIN = (131277322940537, "eth-tester") -class TACoDomain(NamedTuple): +class DomainInfo(NamedTuple): name: str eth_chain: EthChain polygon_chain: PolygonChain + def __str__(self) -> str: + return self.name + + def __bytes__(self) -> bytes: + return self.name.encode() + + @property def is_testnet(self) -> bool: return self.eth_chain != EthChain.MAINNET -class UnrecognizedDomain(RuntimeError): - """Raised when a provided domain name is not recognized.""" +class TACoDomain: + class Unrecognized(RuntimeError): + """Raised when a provided domain name is not recognized.""" + MAINNET = DomainInfo("mainnet", EthChain.MAINNET, PolygonChain.POLYGON) + # Testnets + ORYX = DomainInfo("oryx", EthChain.GOERLI, PolygonChain.POLYGON) + LYNX = DomainInfo("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) + TAPIR = DomainInfo("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) + IBEX = DomainInfo( + "ibex", EthChain.GOERLI, None + ) # this is required for configuration file migrations (backwards compatibility) -MAINNET = TACoDomain("mainnet", EthChain.MAINNET, PolygonChain.POLYGON) -# Testnets -ORYX = TACoDomain("oryx", EthChain.GOERLI, PolygonChain.POLYGON) -LYNX = TACoDomain("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) -TAPIR = TACoDomain("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) -IBEX = TACoDomain( - "ibex", EthChain.GOERLI, None -) # this is required for configuration file migrations (backwards compatibility) + DEFAULT_DOMAIN_NAME: str = MAINNET.name -DEFAULT_DOMAIN_NAME: str = MAINNET.name + SUPPORTED_DOMAINS = [ + MAINNET, + ORYX, + LYNX, + TAPIR, + ] -SUPPORTED_DOMAINS = [ - MAINNET, - ORYX, - LYNX, - TAPIR, -] + SUPPORTED_DOMAIN_NAMES = [domain.name for domain in SUPPORTED_DOMAINS] -SUPPORTED_DOMAIN_NAMES = [domain.name for domain in SUPPORTED_DOMAINS] + @classmethod + def get_domain_info(cls, domain: str) -> DomainInfo: + for taco_domain in cls.SUPPORTED_DOMAINS: + if taco_domain.name == domain: + return taco_domain - -def from_domain_name(domain: str) -> TACoDomain: - for taco_domain in SUPPORTED_DOMAINS: - if taco_domain.name == domain: - return taco_domain - - raise UnrecognizedDomain(f"{domain} is not a recognized domain.") + raise cls.Unrecognized(f"{domain} is not a recognized domain.") diff --git a/nucypher/blockchain/eth/registry.py b/nucypher/blockchain/eth/registry.py index 79b3e6ec1..86638a4d3 100644 --- a/nucypher/blockchain/eth/registry.py +++ b/nucypher/blockchain/eth/registry.py @@ -9,7 +9,7 @@ import requests from requests import Response from web3.types import ABI -from nucypher.blockchain.eth import domains +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.utilities.logging import Logger RegistryArtifact = Dict[str, Union[str, ABI]] @@ -34,10 +34,10 @@ class RegistrySource(ABC): """Raised when there are no available registry sources""" def __init__(self, domain: str, *args, **kwargs): - if domain not in domains.SUPPORTED_DOMAIN_NAMES: + if domain not in TACoDomain.SUPPORTED_DOMAIN_NAMES: raise ValueError( f"{self.__class__.__name__} not available for domain '{domain}'. " - f"Valid options are: {', '.join(list(domains.SUPPORTED_DOMAIN_NAMES))}" + f"Valid options are: {', '.join(list(TACoDomain.SUPPORTED_DOMAIN_NAMES))}" ) self.domain = domain self.data = self.get() diff --git a/nucypher/cli/actions/select.py b/nucypher/cli/actions/select.py index 8bbb77500..199696ae0 100644 --- a/nucypher/cli/actions/select.py +++ b/nucypher/cli/actions/select.py @@ -6,7 +6,7 @@ import click from tabulate import tabulate from web3.main import Web3 -from nucypher.blockchain.eth import domains +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.registry import ( ContractRegistry, @@ -69,7 +69,7 @@ def select_client_account( blockchain = BlockchainInterfaceFactory.get_interface(endpoint=polygon_endpoint) if signer_uri and not signer: - testnet = domain != domains.MAINNET.name + testnet = domain != TACoDomain.MAINNET.name signer = Signer.from_signer_uri(signer_uri, testnet=testnet) # Display accounts info @@ -116,7 +116,7 @@ def select_client_account( def select_domain(emitter: StdoutEmitter, message: Optional[str] = None) -> str: """Interactively select a domain from TACo domain inventory list""" emitter.message(message=message or str(), color="yellow") - domain_list = domains.SUPPORTED_DOMAIN_NAMES + domain_list = TACoDomain.SUPPORTED_DOMAIN_NAMES rows = [[n] for n in domain_list] emitter.echo(tabulate(rows, showindex="always")) choice = click.prompt( diff --git a/nucypher/cli/commands/taco.py b/nucypher/cli/commands/taco.py index 0d35e5477..b1c9dbf62 100644 --- a/nucypher/cli/commands/taco.py +++ b/nucypher/cli/commands/taco.py @@ -3,7 +3,6 @@ from pathlib import Path import click from web3 import Web3 -from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ( ContractAgency, TACoApplicationAgent, @@ -12,6 +11,7 @@ from nucypher.blockchain.eth.constants import ( AVERAGE_BLOCK_TIME_IN_SECONDS, TACO_CONTRACT_NAMES, ) +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.cli.config import group_general_config from nucypher.cli.options import ( group_options, @@ -42,7 +42,7 @@ option_domain = click.option( "--domain", help="TACo Domain", type=click.STRING, - default=click.Choice(domains.SUPPORTED_DOMAIN_NAMES), + default=click.Choice(TACoDomain.SUPPORTED_DOMAIN_NAMES), required=True, ) diff --git a/nucypher/cli/types.py b/nucypher/cli/types.py index cfe11f280..c8193be0f 100644 --- a/nucypher/cli/types.py +++ b/nucypher/cli/types.py @@ -10,7 +10,7 @@ from cryptography.exceptions import InternalError from eth_utils import to_checksum_address from nucypher_core.umbral import PublicKey -from nucypher.blockchain.eth import domains +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.token import TToken from nucypher.policy.payment import PRE_PAYMENT_METHODS from nucypher.utilities.networking import InvalidOperatorIP, validate_operator_ip @@ -97,9 +97,9 @@ class NuCypherDomainName(click.ParamType): def convert(self, value, param, ctx): if self.validate: domain = str(value).lower() - if domain not in domains.SUPPORTED_DOMAIN_NAMES: + if domain not in TACoDomain.SUPPORTED_DOMAIN_NAMES: self.fail( - f"'{value}' is not a recognized domain. Valid options are: {list(domains.SUPPORTED_DOMAIN_NAMES)}" + f"'{value}' is not a recognized domain. Valid options are: {list(TACoDomain.SUPPORTED_DOMAIN_NAMES)}" ) else: return domain diff --git a/nucypher/config/base.py b/nucypher/config/base.py index aeed5db98..dfffe2685 100644 --- a/nucypher/config/base.py +++ b/nucypher/config/base.py @@ -16,7 +16,7 @@ from constant_sorrow.constants import ( ) from eth_utils.address import is_checksum_address -from nucypher.blockchain.eth import domains +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory from nucypher.blockchain.eth.registry import ( ContractRegistry, @@ -307,7 +307,7 @@ class CharacterConfiguration(BaseConfiguration): CHARACTER_CLASS = NotImplemented MNEMONIC_KEYSTORE = False - DEFAULT_DOMAIN = domains.DEFAULT_DOMAIN_NAME + DEFAULT_DOMAIN = TACoDomain.DEFAULT_DOMAIN_NAME DEFAULT_NETWORK_MIDDLEWARE = RestMiddleware TEMP_CONFIGURATION_DIR_PREFIX = 'tmp-nucypher' SIGNER_ENVVAR = None @@ -415,7 +415,7 @@ class CharacterConfiguration(BaseConfiguration): # Learner self.domain = domain - self.taco_domain = domains.from_domain_name(self.domain) + self.taco_domain_info = TACoDomain.get_domain_info(self.domain) self.learn_on_same_thread = learn_on_same_thread self.abort_on_learning_error = abort_on_learning_error self.start_learning_now = start_learning_now @@ -454,7 +454,7 @@ class CharacterConfiguration(BaseConfiguration): self.log.info(f"Using local registry ({self.registry}).") self.signer = Signer.from_signer_uri( - self.signer_uri, testnet=self.taco_domain.is_testnet() + self.signer_uri, testnet=self.taco_domain_info.is_testnet ) # @@ -834,7 +834,7 @@ class CharacterConfiguration(BaseConfiguration): if pre_payment_class.ONCHAIN: # on-chain payment strategies require a blockchain connection pre_payment_strategy = pre_payment_class( - domain=self.taco_domain.name, + domain=self.taco_domain_info.name, blockchain_endpoint=self.polygon_endpoint, registry=self.registry, ) diff --git a/nucypher/config/characters.py b/nucypher/config/characters.py index 1206d8cfb..bd7abe7a8 100644 --- a/nucypher/config/characters.py +++ b/nucypher/config/characters.py @@ -70,7 +70,7 @@ class UrsulaConfiguration(CharacterConfiguration): def configure_condition_blockchain_endpoints(self) -> None: """Configure default condition provider URIs for eth and polygon network.""" # Polygon - polygon_chain_id = self.taco_domain.polygon_chain.id + polygon_chain_id = self.taco_domain_info.polygon_chain.id polygon_endpoints = self.condition_blockchain_endpoints.get( polygon_chain_id, [] ) @@ -81,7 +81,7 @@ class UrsulaConfiguration(CharacterConfiguration): polygon_endpoints.append(self.polygon_endpoint) # Ethereum - staking_chain_id = self.taco_domain.eth_chain.id + staking_chain_id = self.taco_domain_info.eth_chain.id staking_chain_endpoints = self.condition_blockchain_endpoints.get( staking_chain_id, [] ) diff --git a/nucypher/config/migrations/configuration_v5_to_v6.py b/nucypher/config/migrations/configuration_v5_to_v6.py index 0417ef39e..0c1813ec0 100644 --- a/nucypher/config/migrations/configuration_v5_to_v6.py +++ b/nucypher/config/migrations/configuration_v5_to_v6.py @@ -1,15 +1,15 @@ from typing import Dict -from nucypher.blockchain.eth import domains +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.config.migrations.common import perform_migration def __migration(config: Dict) -> Dict: - taco_domain = domains.from_domain_name(config["domain"]) + taco_domain_info = TACoDomain.get_domain_info(config["domain"]) eth_provider = config["eth_provider_uri"] - eth_chain_id = taco_domain.eth_chain.id + eth_chain_id = taco_domain_info.eth_chain.id polygon_provider = config["payment_provider"] - polygon_chain_id = taco_domain.polygon_chain.id + polygon_chain_id = taco_domain_info.polygon_chain.id if "condition_provider_uris" in config: return config config["condition_provider_uris"] = { diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index 403d0b1eb..108d61072 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -26,9 +26,9 @@ from twisted.internet.defer import Deferred from nucypher import characters from nucypher.acumen.nicknames import Nickname from nucypher.acumen.perception import FleetSensor -from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ContractAgency, TACoApplicationAgent from nucypher.blockchain.eth.constants import NULL_ADDRESS +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.config.constants import SeednodeMetadata from nucypher.config.storages import ForgetfulNodeStorage @@ -46,14 +46,14 @@ from nucypher.network.protocols import InterfaceInfo, SuspiciousActivity from nucypher.utilities.logging import Logger TEACHER_NODES = { - domains.MAINNET.name: ( + TACoDomain.MAINNET.name: ( 'https://closest-seed.nucypher.network:9151', 'https://seeds.nucypher.network', 'https://mainnet.nucypher.network:9151', ), - domains.LYNX.name: ("https://lynx.nucypher.network:9151",), - domains.TAPIR.name: ("https://tapir.nucypher.network:9151",), - domains.ORYX.name: ("https://oryx.nucypher.network:9151",), + TACoDomain.LYNX.name: ("https://lynx.nucypher.network:9151",), + TACoDomain.TAPIR.name: ("https://tapir.nucypher.network:9151",), + TACoDomain.ORYX.name: ("https://oryx.nucypher.network:9151",), } @@ -271,7 +271,7 @@ class Learner: self.learning_deferred = Deferred() self.domain = domain - self.taco_domain = domains.from_domain_name(self.domain) + self.taco_domain_info = TACoDomain.get_domain_info(self.domain) default_middleware = self.__DEFAULT_MIDDLEWARE_CLASS( registry=self.registry, eth_endpoint=self.eth_endpoint ) diff --git a/nucypher/policy/payment.py b/nucypher/policy/payment.py index 1d1e810ab..8a443f637 100644 --- a/nucypher/policy/payment.py +++ b/nucypher/policy/payment.py @@ -5,8 +5,8 @@ import maya from nucypher_core import ReencryptionRequest from web3.types import ChecksumAddress, Timestamp, TxReceipt, Wei -from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ContractAgency, SubscriptionManagerAgent +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.policy import policies @@ -73,7 +73,7 @@ class ContractPayment(PaymentMethod, ABC): ): super().__init__(*args, **kwargs) self.blockchain_endpoint = blockchain_endpoint - self.taco_domain = domains.from_domain_name(domain) + self.taco_domain_info = TACoDomain.get_domain_info(domain) if not registry: registry = ContractRegistry.from_latest_publication(domain=domain) self.registry = registry diff --git a/scripts/hooks/nucypher_agents.py b/scripts/hooks/nucypher_agents.py index 065c0fa8b..6a82046af 100644 --- a/scripts/hooks/nucypher_agents.py +++ b/scripts/hooks/nucypher_agents.py @@ -20,7 +20,6 @@ import rlcompleter import click -from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ( ContractAgency, CoordinatorAgent, @@ -28,6 +27,7 @@ from nucypher.blockchain.eth.agents import ( TACoApplicationAgent, TACoChildApplicationAgent, ) +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.utilities.emitters import StdoutEmitter from nucypher.utilities.logging import GlobalLoggerSettings @@ -45,8 +45,8 @@ emitter = StdoutEmitter(verbosity=2) "--domain", "domain", help="TACo domain", - type=click.Choice(domains.SUPPORTED_DOMAIN_NAMES), - default="lynx", + type=click.Choice(TACoDomain.SUPPORTED_DOMAIN_NAMES), + default=TACoDomain.LYNX.name, ) @click.option( "--eth-endpoint", diff --git a/scripts/hooks/nucypher_dkg.py b/scripts/hooks/nucypher_dkg.py index 89cc631d6..8d5dedde4 100644 --- a/scripts/hooks/nucypher_dkg.py +++ b/scripts/hooks/nucypher_dkg.py @@ -6,12 +6,12 @@ import maya from nucypher_core.ferveo import DkgPublicKey from web3 import Web3 -from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.agents import ( ContractAgency, CoordinatorAgent, TACoApplicationAgent, ) +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.registry import ContractRegistry from nucypher.blockchain.eth.signers import InMemorySigner, Signer from nucypher.characters.lawful import Bob, Enrico @@ -47,8 +47,8 @@ def get_transacting_power(signer: Signer): "--domain", "domain", help="TACo Domain", - type=click.Choice(["tapir", "lynx"]), - default="lynx", + type=click.Choice([TACoDomain.TAPIR.name, TACoDomain.LYNX.name]), + default=TACoDomain.LYNX.name, ) @click.option( "--eth-endpoint", @@ -154,7 +154,7 @@ def nucypher_dkg( ), ) - taco_domain = domains.from_domain_name(domain) + taco_domain_info = TACoDomain.get_domain_info(domain) registry = ContractRegistry.from_latest_publication(domain=domain) coordinator_agent = ContractAgency.get_agent( agent_class=CoordinatorAgent, @@ -191,7 +191,7 @@ def nucypher_dkg( emitter.echo("--------- Initiating Ritual ---------", color="yellow") emitter.echo( - f"Commencing DKG Ritual(s) on {taco_domain.polygon_chain.name} using {account_address}", + f"Commencing DKG Ritual(s) on {taco_domain_info.polygon_chain.name} using {account_address}", color="green", ) diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index e45aac720..bc6096dc3 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -12,6 +12,7 @@ from nucypher.blockchain.eth.agents import ( TACoChildApplicationAgent, ) from nucypher.blockchain.eth.domains import ( + DomainInfo, EthChain, PolygonChain, TACoDomain, @@ -440,12 +441,12 @@ def mock_condition_blockchains(session_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - test_domain = TACoDomain( + test_domain_info = DomainInfo( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - session_mocker.patch( - "nucypher.blockchain.eth.domains.from_domain_name", return_value=test_domain + session_mocker.patch.object( + TACoDomain, "get_domain_info", return_value=test_domain_info ) diff --git a/tests/conftest.py b/tests/conftest.py index 2d7879433..700ac6284 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,6 +5,7 @@ from eth_utils.crypto import keccak from nucypher.blockchain.eth.actors import Operator from nucypher.blockchain.eth.domains import ( + DomainInfo, EthChain, PolygonChain, TACoDomain, @@ -146,12 +147,12 @@ def mock_condition_blockchains(session_mocker): "nucypher.policy.conditions.evm._CONDITION_CHAINS", {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - test_domain = TACoDomain( + test_domain_info = DomainInfo( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - session_mocker.patch( - "nucypher.blockchain.eth.domains.from_domain_name", return_value=test_domain + session_mocker.patch.object( + TACoDomain, "get_domain_info", return_value=test_domain_info ) diff --git a/tests/integration/characters/test_dkg_and_testnet_bypass.py b/tests/integration/characters/test_dkg_and_testnet_bypass.py index 3e6014660..4314f0acf 100644 --- a/tests/integration/characters/test_dkg_and_testnet_bypass.py +++ b/tests/integration/characters/test_dkg_and_testnet_bypass.py @@ -1,5 +1,6 @@ import pytest +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.blockchain.eth.signers.software import Web3Signer from nucypher.characters.chaotic import ( NiceGuyEddie, @@ -22,7 +23,7 @@ def _attempt_decryption(BobClass, plaintext, testerchain): enrico = NiceGuyEddie(encrypting_key=trinket, signer=signer) bob = BobClass( registry=MOCK_REGISTRY_FILEPATH, - domain="lynx", + domain=TACoDomain.LYNX.name, eth_endpoint=MOCK_ETH_PROVIDER_URI, ) diff --git a/tests/integration/cli/actions/test_select_network.py b/tests/integration/cli/actions/test_select_network.py index 0797d799b..1fd0b6741 100644 --- a/tests/integration/cli/actions/test_select_network.py +++ b/tests/integration/cli/actions/test_select_network.py @@ -1,9 +1,9 @@ import pytest -from nucypher.blockchain.eth import domains +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.cli.actions.select import select_domain -__DOMAINS = domains.SUPPORTED_DOMAIN_NAMES +__DOMAINS = TACoDomain.SUPPORTED_DOMAIN_NAMES @pytest.mark.parametrize("user_input", range(0, len(__DOMAINS) - 1)) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 247f3553e..b7356d08a 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -15,6 +15,7 @@ from nucypher.blockchain.eth.agents import ( ) from nucypher.blockchain.eth.clients import EthereumClient from nucypher.blockchain.eth.domains import ( + DomainInfo, EthChain, PolygonChain, TACoDomain, @@ -290,12 +291,12 @@ def mock_condition_blockchains(session_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) - test_domain = TACoDomain( + test_domain_info = DomainInfo( TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - session_mocker.patch( - "nucypher.blockchain.eth.domains.from_domain_name", return_value=test_domain + session_mocker.patch.object( + TACoDomain, "get_domain_info", return_value=test_domain_info ) diff --git a/tests/unit/test_teacher_nodes.py b/tests/unit/test_teacher_nodes.py index ac8b9f8a3..ff532d5ae 100644 --- a/tests/unit/test_teacher_nodes.py +++ b/tests/unit/test_teacher_nodes.py @@ -1,6 +1,6 @@ import pytest -from nucypher.blockchain.eth import domains +from nucypher.blockchain.eth.domains import TACoDomain from nucypher.network.nodes import TEACHER_NODES @@ -17,6 +17,6 @@ def test_registry(module_mocker): def test_default_teacher_seednodes_defined(): - for domain in domains.SUPPORTED_DOMAIN_NAMES: + for domain in TACoDomain.SUPPORTED_DOMAIN_NAMES: teacher_nodes = TEACHER_NODES[domain] assert len(teacher_nodes) > 0 diff --git a/tests/utils/registry.py b/tests/utils/registry.py index c288b2409..db7eee346 100644 --- a/tests/utils/registry.py +++ b/tests/utils/registry.py @@ -5,8 +5,8 @@ from typing import List from ape.contracts import ContractInstance from eth_utils import to_checksum_address -from nucypher.blockchain.eth import domains from nucypher.blockchain.eth.domains import ( + DomainInfo, EthChain, PolygonChain, TACoDomain, @@ -27,14 +27,14 @@ def mock_registry_sources(mocker, domain_names: List[str] = None): supported_domains = [] supported_domain_names = [] for domain_name in domain_names: - test_domain = TACoDomain( + test_domain = DomainInfo( domain_name, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) supported_domains.append(test_domain) supported_domain_names.append(domain_name) - mocker.patch.object(domains, "SUPPORTED_DOMAINS", supported_domains) - mocker.patch.object(domains, "SUPPORTED_DOMAIN_NAMES", supported_domain_names) + mocker.patch.object(TACoDomain, "SUPPORTED_DOMAINS", supported_domains) + mocker.patch.object(TACoDomain, "SUPPORTED_DOMAIN_NAMES", supported_domain_names) mocker.patch.object(MockRegistrySource, "ALLOWED_DOMAINS", domain_names) mocker.patch.object(RegistrySourceManager, "_FALLBACK_CHAIN", (MockRegistrySource,)) From 247b93859e0b6751bae7b2654049afa24ec50f3d Mon Sep 17 00:00:00 2001 From: derekpierre Date: Thu, 5 Oct 2023 06:21:34 -0400 Subject: [PATCH 55/63] Add unit test for structures in domains.py. --- nucypher/blockchain/eth/domains.py | 3 +- tests/unit/test_domains.py | 60 ++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 tests/unit/test_domains.py diff --git a/nucypher/blockchain/eth/domains.py b/nucypher/blockchain/eth/domains.py index abf3b5366..127f47102 100644 --- a/nucypher/blockchain/eth/domains.py +++ b/nucypher/blockchain/eth/domains.py @@ -42,9 +42,10 @@ class TACoDomain: MAINNET = DomainInfo("mainnet", EthChain.MAINNET, PolygonChain.POLYGON) # Testnets - ORYX = DomainInfo("oryx", EthChain.GOERLI, PolygonChain.POLYGON) LYNX = DomainInfo("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) TAPIR = DomainInfo("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) + # TODO remove these (oryx, ibex) when appropriate + ORYX = DomainInfo("oryx", EthChain.GOERLI, PolygonChain.POLYGON) IBEX = DomainInfo( "ibex", EthChain.GOERLI, None ) # this is required for configuration file migrations (backwards compatibility) diff --git a/tests/unit/test_domains.py b/tests/unit/test_domains.py new file mode 100644 index 000000000..46a9cf706 --- /dev/null +++ b/tests/unit/test_domains.py @@ -0,0 +1,60 @@ +import pytest + +from nucypher.blockchain.eth.domains import ( + EthChain, + PolygonChain, + TACoDomain, +) + + +@pytest.mark.parametrize( + "eth_chain_test", + ( + (EthChain.MAINNET, "mainnet", 1), + (EthChain.GOERLI, "goerli", 5), + (EthChain.SEPOLIA, "sepolia", 11155111), + ), +) +def test_eth_chains(eth_chain_test): + eth_chain, expected_name, expected_id = eth_chain_test + assert eth_chain.name == expected_name + assert eth_chain.id == expected_id + + +@pytest.mark.parametrize( + "poly_chain_test", + ( + (PolygonChain.POLYGON, "polygon", 137), + (PolygonChain.MUMBAI, "mumbai", 80001), + ), +) +def test_polygon_chains(poly_chain_test): + eth_chain, expected_name, expected_id = poly_chain_test + assert eth_chain.name == expected_name + assert eth_chain.id == expected_id + + +@pytest.mark.parametrize( + "taco_domain_test", + ( + (TACoDomain.MAINNET, "mainnet", EthChain.MAINNET, PolygonChain.POLYGON), + (TACoDomain.LYNX, "lynx", EthChain.GOERLI, PolygonChain.MUMBAI), + (TACoDomain.TAPIR, "tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI), + ), +) +def test_taco_domain_info(taco_domain_test): + ( + domain_info, + expected_name, + expected_eth_chain, + expected_polygon_chain, + ) = taco_domain_test + assert domain_info.name == expected_name + assert domain_info.eth_chain == expected_eth_chain + assert domain_info.polygon_chain == expected_polygon_chain + + assert domain_info.is_testnet == (expected_name != "mainnet") + + # magic methods + assert str(domain_info) == expected_name + assert bytes(domain_info) == expected_name.encode() From dc547249aec697c46d0c08983080beaba4f3e956 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Thu, 5 Oct 2023 06:55:32 -0400 Subject: [PATCH 56/63] Reduce scope of fixture froms session to module, so that its effects can be overridden by test modules. Added unit tests for get_domain_info. --- tests/acceptance/conftest.py | 8 ++++---- tests/conftest.py | 8 ++++---- tests/integration/conftest.py | 8 ++++---- tests/unit/test_domains.py | 30 ++++++++++++++++++++++++++++++ 4 files changed, 42 insertions(+), 12 deletions(-) diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index bc6096dc3..c60f80199 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -433,10 +433,10 @@ def multichain_ursulas(ursulas, multichain_ids, mock_rpc_condition): return ursulas -@pytest.fixture(scope="session", autouse=True) -def mock_condition_blockchains(session_mocker): +@pytest.fixture(scope="module", autouse=True) +def mock_condition_blockchains(module_mocker): """adds testerchain's chain ID to permitted conditional chains""" - session_mocker.patch.dict( + module_mocker.patch.dict( "nucypher.policy.conditions.evm._CONDITION_CHAINS", {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) @@ -445,7 +445,7 @@ def mock_condition_blockchains(session_mocker): TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - session_mocker.patch.object( + module_mocker.patch.object( TACoDomain, "get_domain_info", return_value=test_domain_info ) diff --git a/tests/conftest.py b/tests/conftest.py index 700ac6284..eddd29cb3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -140,10 +140,10 @@ def disable_check_grant_requirements(session_mocker): session_mocker.patch(target, return_value=MOCK_IP_ADDRESS) -@pytest.fixture(scope="session", autouse=True) -def mock_condition_blockchains(session_mocker): +@pytest.fixture(scope="module", autouse=True) +def mock_condition_blockchains(module_mocker): """adds testerchain's chain ID to permitted conditional chains""" - session_mocker.patch.dict( + module_mocker.patch.dict( "nucypher.policy.conditions.evm._CONDITION_CHAINS", {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) @@ -151,7 +151,7 @@ def mock_condition_blockchains(session_mocker): TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - session_mocker.patch.object( + module_mocker.patch.object( TACoDomain, "get_domain_info", return_value=test_domain_info ) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index b7356d08a..c7663d885 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -283,10 +283,10 @@ def monkeypatch_get_staking_provider_from_operator(monkeymodule): ) -@pytest.fixture(scope="session", autouse=True) -def mock_condition_blockchains(session_mocker): +@pytest.fixture(scope="module", autouse=True) +def mock_condition_blockchains(module_mocker): """adds testerchain's chain ID to permitted conditional chains""" - session_mocker.patch.dict( + module_mocker.patch.dict( "nucypher.policy.conditions.evm._CONDITION_CHAINS", {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) @@ -295,7 +295,7 @@ def mock_condition_blockchains(session_mocker): TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN ) - session_mocker.patch.object( + module_mocker.patch.object( TACoDomain, "get_domain_info", return_value=test_domain_info ) diff --git a/tests/unit/test_domains.py b/tests/unit/test_domains.py index 46a9cf706..b97b47a9b 100644 --- a/tests/unit/test_domains.py +++ b/tests/unit/test_domains.py @@ -7,6 +7,18 @@ from nucypher.blockchain.eth.domains import ( ) +@pytest.fixture(scope="module") +def test_registry(module_mocker): + # override fixture which mocks SUPPORTED_DOMAIN_NAMES + yield + + +@pytest.fixture(scope="module", autouse=True) +def mock_condition_blockchains(module_mocker): + # override fixture which mocks get_domain_info + yield + + @pytest.mark.parametrize( "eth_chain_test", ( @@ -58,3 +70,21 @@ def test_taco_domain_info(taco_domain_test): # magic methods assert str(domain_info) == expected_name assert bytes(domain_info) == expected_name.encode() + + +@pytest.mark.parametrize( + "domain_name_test", + ( + ("mainnet", TACoDomain.MAINNET), + ("lynx", TACoDomain.LYNX), + ("tapir", TACoDomain.TAPIR), + ), +) +def test_get_domain_info(domain_name_test): + domain_name, expected_domain_info = domain_name_test + assert TACoDomain.get_domain_info(domain_name) == expected_domain_info + + +def test_get_domain_info_unrecognized_domain_name(): + with pytest.raises(TACoDomain.Unrecognized): + TACoDomain.get_domain_info(domain="5am_In_Toronto") From 4ed74fc0f273dfbd68afbad01be1e2de6e883cd2 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Thu, 5 Oct 2023 08:25:58 -0400 Subject: [PATCH 57/63] Rename PolygonChain.POLYGON to PolygonChain.MAINNET. Remove ORYX, IBEX domains. --- nucypher/blockchain/eth/domains.py | 10 ++-------- nucypher/network/nodes.py | 1 - tests/unit/test_domains.py | 4 ++-- 3 files changed, 4 insertions(+), 11 deletions(-) diff --git a/nucypher/blockchain/eth/domains.py b/nucypher/blockchain/eth/domains.py index 127f47102..8f092b811 100644 --- a/nucypher/blockchain/eth/domains.py +++ b/nucypher/blockchain/eth/domains.py @@ -15,7 +15,7 @@ class EthChain(ChainInfo, Enum): class PolygonChain(ChainInfo, Enum): - POLYGON = (137, "polygon") + MAINNET = (137, "polygon") MUMBAI = (80001, "mumbai") TESTERCHAIN = (131277322940537, "eth-tester") @@ -40,21 +40,15 @@ class TACoDomain: class Unrecognized(RuntimeError): """Raised when a provided domain name is not recognized.""" - MAINNET = DomainInfo("mainnet", EthChain.MAINNET, PolygonChain.POLYGON) + MAINNET = DomainInfo("mainnet", EthChain.MAINNET, PolygonChain.MAINNET) # Testnets LYNX = DomainInfo("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) TAPIR = DomainInfo("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) - # TODO remove these (oryx, ibex) when appropriate - ORYX = DomainInfo("oryx", EthChain.GOERLI, PolygonChain.POLYGON) - IBEX = DomainInfo( - "ibex", EthChain.GOERLI, None - ) # this is required for configuration file migrations (backwards compatibility) DEFAULT_DOMAIN_NAME: str = MAINNET.name SUPPORTED_DOMAINS = [ MAINNET, - ORYX, LYNX, TAPIR, ] diff --git a/nucypher/network/nodes.py b/nucypher/network/nodes.py index 108d61072..a1577bfbf 100644 --- a/nucypher/network/nodes.py +++ b/nucypher/network/nodes.py @@ -53,7 +53,6 @@ TEACHER_NODES = { ), TACoDomain.LYNX.name: ("https://lynx.nucypher.network:9151",), TACoDomain.TAPIR.name: ("https://tapir.nucypher.network:9151",), - TACoDomain.ORYX.name: ("https://oryx.nucypher.network:9151",), } diff --git a/tests/unit/test_domains.py b/tests/unit/test_domains.py index b97b47a9b..79c96b7f5 100644 --- a/tests/unit/test_domains.py +++ b/tests/unit/test_domains.py @@ -36,7 +36,7 @@ def test_eth_chains(eth_chain_test): @pytest.mark.parametrize( "poly_chain_test", ( - (PolygonChain.POLYGON, "polygon", 137), + (PolygonChain.MAINNET, "polygon", 137), (PolygonChain.MUMBAI, "mumbai", 80001), ), ) @@ -49,7 +49,7 @@ def test_polygon_chains(poly_chain_test): @pytest.mark.parametrize( "taco_domain_test", ( - (TACoDomain.MAINNET, "mainnet", EthChain.MAINNET, PolygonChain.POLYGON), + (TACoDomain.MAINNET, "mainnet", EthChain.MAINNET, PolygonChain.MAINNET), (TACoDomain.LYNX, "lynx", EthChain.GOERLI, PolygonChain.MUMBAI), (TACoDomain.TAPIR, "tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI), ), From 2a0bd02203b810019112ae2d97a383968149c9dd Mon Sep 17 00:00:00 2001 From: derekpierre Date: Thu, 5 Oct 2023 08:27:44 -0400 Subject: [PATCH 58/63] Move TESTERCHAIN chain information out of domains and into testing constants. --- nucypher/blockchain/eth/domains.py | 8 -------- tests/acceptance/conftest.py | 5 ++--- tests/conftest.py | 10 ++++++---- tests/constants.py | 3 +++ tests/integration/conftest.py | 5 ++--- tests/utils/registry.py | 5 ++--- 6 files changed, 15 insertions(+), 21 deletions(-) diff --git a/nucypher/blockchain/eth/domains.py b/nucypher/blockchain/eth/domains.py index 8f092b811..65015799c 100644 --- a/nucypher/blockchain/eth/domains.py +++ b/nucypher/blockchain/eth/domains.py @@ -11,13 +11,11 @@ class EthChain(ChainInfo, Enum): MAINNET = (1, "mainnet") GOERLI = (5, "goerli") SEPOLIA = (11155111, "sepolia") - TESTERCHAIN = (131277322940537, "eth-tester") class PolygonChain(ChainInfo, Enum): MAINNET = (137, "polygon") MUMBAI = (80001, "mumbai") - TESTERCHAIN = (131277322940537, "eth-tester") class DomainInfo(NamedTuple): @@ -25,12 +23,6 @@ class DomainInfo(NamedTuple): eth_chain: EthChain polygon_chain: PolygonChain - def __str__(self) -> str: - return self.name - - def __bytes__(self) -> bytes: - return self.name.encode() - @property def is_testnet(self) -> bool: return self.eth_chain != EthChain.MAINNET diff --git a/tests/acceptance/conftest.py b/tests/acceptance/conftest.py index c60f80199..de32d8102 100644 --- a/tests/acceptance/conftest.py +++ b/tests/acceptance/conftest.py @@ -13,8 +13,6 @@ from nucypher.blockchain.eth.agents import ( ) from nucypher.blockchain.eth.domains import ( DomainInfo, - EthChain, - PolygonChain, TACoDomain, ) from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory @@ -30,6 +28,7 @@ from tests.constants import ( MIN_OPERATOR_SECONDS, TEST_ETH_PROVIDER_URI, TESTERCHAIN_CHAIN_ID, + TESTERCHAIN_CHAIN_INFO, ) from tests.utils.blockchain import TesterBlockchain from tests.utils.registry import ApeRegistrySource @@ -442,7 +441,7 @@ def mock_condition_blockchains(module_mocker): ) test_domain_info = DomainInfo( - TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN + TEMPORARY_DOMAIN, TESTERCHAIN_CHAIN_INFO, TESTERCHAIN_CHAIN_INFO ) module_mocker.patch.object( diff --git a/tests/conftest.py b/tests/conftest.py index eddd29cb3..2698c2a30 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,15 +6,17 @@ from eth_utils.crypto import keccak from nucypher.blockchain.eth.actors import Operator from nucypher.blockchain.eth.domains import ( DomainInfo, - EthChain, - PolygonChain, TACoDomain, ) from nucypher.config.constants import TEMPORARY_DOMAIN from nucypher.crypto.powers import TransactingPower from nucypher.network.nodes import Learner from nucypher.utilities.logging import GlobalLoggerSettings -from tests.constants import MOCK_IP_ADDRESS, TESTERCHAIN_CHAIN_ID +from tests.constants import ( + MOCK_IP_ADDRESS, + TESTERCHAIN_CHAIN_ID, + TESTERCHAIN_CHAIN_INFO, +) # Don't re-lock accounts in the background while making commitments LOCK_FUNCTION = TransactingPower.lock_account @@ -148,7 +150,7 @@ def mock_condition_blockchains(module_mocker): {TESTERCHAIN_CHAIN_ID: "eth-tester/pyevm"}, ) test_domain_info = DomainInfo( - TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN + TEMPORARY_DOMAIN, TESTERCHAIN_CHAIN_INFO, TESTERCHAIN_CHAIN_INFO ) module_mocker.patch.object( diff --git a/tests/constants.py b/tests/constants.py index ce9bcdb0c..aee733162 100644 --- a/tests/constants.py +++ b/tests/constants.py @@ -7,6 +7,7 @@ from random import SystemRandom from hexbytes import HexBytes from web3 import Web3 +from nucypher.blockchain.eth.domains import ChainInfo from nucypher.blockchain.eth.token import NU from nucypher.config.constants import ( NUCYPHER_ENVVAR_KEYSTORE_PASSWORD, @@ -71,6 +72,8 @@ NUMBER_OF_ALLOCATIONS_IN_TESTS = 50 # TODO: Move to constants TESTERCHAIN_CHAIN_ID = 131277322940537 +TESTERCHAIN_CHAIN_INFO = ChainInfo(131277322940537, "eth-tester") + # # Insecure Secrets diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index c7663d885..36c3fd0c9 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -16,8 +16,6 @@ from nucypher.blockchain.eth.agents import ( from nucypher.blockchain.eth.clients import EthereumClient from nucypher.blockchain.eth.domains import ( DomainInfo, - EthChain, - PolygonChain, TACoDomain, ) from nucypher.blockchain.eth.interfaces import ( @@ -40,6 +38,7 @@ from tests.constants import ( MOCK_KEYSTORE_PATH, NUMBER_OF_MOCK_KEYSTORE_ACCOUNTS, TESTERCHAIN_CHAIN_ID, + TESTERCHAIN_CHAIN_INFO, ) from tests.mock.interfaces import MockBlockchain from tests.mock.io import MockStdinWrapper @@ -292,7 +291,7 @@ def mock_condition_blockchains(module_mocker): ) test_domain_info = DomainInfo( - TEMPORARY_DOMAIN, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN + TEMPORARY_DOMAIN, TESTERCHAIN_CHAIN_INFO, TESTERCHAIN_CHAIN_INFO ) module_mocker.patch.object( diff --git a/tests/utils/registry.py b/tests/utils/registry.py index db7eee346..477b5c115 100644 --- a/tests/utils/registry.py +++ b/tests/utils/registry.py @@ -7,8 +7,6 @@ from eth_utils import to_checksum_address from nucypher.blockchain.eth.domains import ( DomainInfo, - EthChain, - PolygonChain, TACoDomain, ) from nucypher.blockchain.eth.registry import ( @@ -17,6 +15,7 @@ from nucypher.blockchain.eth.registry import ( RegistrySourceManager, ) from nucypher.config.constants import TEMPORARY_DOMAIN +from tests.constants import TESTERCHAIN_CHAIN_INFO @contextmanager @@ -28,7 +27,7 @@ def mock_registry_sources(mocker, domain_names: List[str] = None): supported_domain_names = [] for domain_name in domain_names: test_domain = DomainInfo( - domain_name, EthChain.TESTERCHAIN, PolygonChain.TESTERCHAIN + domain_name, TESTERCHAIN_CHAIN_INFO, TESTERCHAIN_CHAIN_INFO ) supported_domains.append(test_domain) supported_domain_names.append(domain_name) From 6e4563013b1e2c4338a1f5cb7ffb7eaa55a18e29 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Thu, 5 Oct 2023 08:42:35 -0400 Subject: [PATCH 59/63] Respond to RFC in #3262. --- nucypher/blockchain/eth/domains.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nucypher/blockchain/eth/domains.py b/nucypher/blockchain/eth/domains.py index 65015799c..5603f3642 100644 --- a/nucypher/blockchain/eth/domains.py +++ b/nucypher/blockchain/eth/domains.py @@ -33,7 +33,6 @@ class TACoDomain: """Raised when a provided domain name is not recognized.""" MAINNET = DomainInfo("mainnet", EthChain.MAINNET, PolygonChain.MAINNET) - # Testnets LYNX = DomainInfo("lynx", EthChain.GOERLI, PolygonChain.MUMBAI) TAPIR = DomainInfo("tapir", EthChain.SEPOLIA, PolygonChain.MUMBAI) From 4865053f8ca48907b386f87c0b37970a85c65747 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Thu, 5 Oct 2023 08:46:55 -0400 Subject: [PATCH 60/63] Fix failing unit test. --- tests/unit/test_domains.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/unit/test_domains.py b/tests/unit/test_domains.py index 79c96b7f5..ffcde6f02 100644 --- a/tests/unit/test_domains.py +++ b/tests/unit/test_domains.py @@ -67,10 +67,6 @@ def test_taco_domain_info(taco_domain_test): assert domain_info.is_testnet == (expected_name != "mainnet") - # magic methods - assert str(domain_info) == expected_name - assert bytes(domain_info) == expected_name.encode() - @pytest.mark.parametrize( "domain_name_test", From 7c884d239264fbe5a87102bf6551d09d9ae6597a Mon Sep 17 00:00:00 2001 From: derekpierre Date: Thu, 5 Oct 2023 10:42:22 -0400 Subject: [PATCH 61/63] Rename unit test so no naming conflict with integration test. --- tests/unit/{test_domains.py => test_taco_domains.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/unit/{test_domains.py => test_taco_domains.py} (100%) diff --git a/tests/unit/test_domains.py b/tests/unit/test_taco_domains.py similarity index 100% rename from tests/unit/test_domains.py rename to tests/unit/test_taco_domains.py From 04e085d02a0d297caf52b953eb2a41edc48f4648 Mon Sep 17 00:00:00 2001 From: derekpierre Date: Thu, 5 Oct 2023 10:42:45 -0400 Subject: [PATCH 62/63] Attempt to address failing integration test. --- tests/integration/learning/test_domains.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/integration/learning/test_domains.py b/tests/integration/learning/test_domains.py index 16ed03713..f68a27e6a 100644 --- a/tests/integration/learning/test_domains.py +++ b/tests/integration/learning/test_domains.py @@ -53,7 +53,7 @@ def test_learner_learns_about_domains_separately( _nobody = lonely_ursula_maker( domain=domain_1, registry=registry_1, quantity=1 ).pop() - other_first_domain_learner.remember_node(_nobody) + other_first_domain_learner.remember_node(_nobody, eager=True) second_domain_learners = lonely_ursula_maker( domain=domain_2, registry=registry_2, know_each_other=True, quantity=3 @@ -62,7 +62,7 @@ def test_learner_learns_about_domains_separately( assert len(hero_learner.known_nodes) == 0 # Learn from a teacher in our domain. - hero_learner.remember_node(other_first_domain_learner) + hero_learner.remember_node(other_first_domain_learner, eager=True) hero_learner.start_learning_loop(now=True) hero_learner.learn_from_teacher_node(eager=True) @@ -83,7 +83,7 @@ def test_learner_learns_about_domains_separately( domain=domain_2, registry=registry_2, quantity=1 ).pop() - new_first_domain_learner.remember_node(hero_learner) + new_first_domain_learner.remember_node(hero_learner, eager=True) new_first_domain_learner.learn_from_teacher_node(eager=True) From 62d8dc6bb3fbc08e144f7ac93e0ba9b0defe1e03 Mon Sep 17 00:00:00 2001 From: Kieran Prasch Date: Fri, 6 Oct 2023 11:39:21 +0200 Subject: [PATCH 63/63] renames newsfragment .txt -> .rst --- newsfragments/{3262.misc.txt => 3262.misc.rst} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename newsfragments/{3262.misc.txt => 3262.misc.rst} (100%) diff --git a/newsfragments/3262.misc.txt b/newsfragments/3262.misc.rst similarity index 100% rename from newsfragments/3262.misc.txt rename to newsfragments/3262.misc.rst