mirror of https://github.com/nucypher/nucypher.git
More renames of instances of eth_provider_uri to either blockchain_endpoint or eth_endpoint.
parent
8fcf422728
commit
941b21f34f
|
@ -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.
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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,
|
||||
)
|
||||
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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,
|
||||
)
|
||||
)
|
||||
|
||||
|
|
|
@ -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):
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
||||
#
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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,
|
||||
)
|
||||
|
|
|
@ -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",
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
|
@ -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]
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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"
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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()
|
||||
|
||||
|
|
|
@ -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,
|
||||
)
|
||||
|
|
|
@ -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):
|
||||
|
|
Loading…
Reference in New Issue