nucypher.blockchain.eth

Subpackages

Submodules

class BaseActor(domain: Optional[str], registry: nucypher.blockchain.eth.registry.BaseContractRegistry, transacting_power: Optional[nucypher.crypto.powers.TransactingPower] = None, checksum_address: Optional[NewType.<locals>.new_type] = None, economics: Optional[nucypher.blockchain.economics.Economics] = None)

Bases: object

Concrete base class for any actor that will interface with NuCypher’s ethereum smart contracts.

exception ActorError

Bases: Exception

property eth_balance

Return this actor’s current ETH balance

property wallet_address
class NucypherTokenActor(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, **kwargs)

Bases: nucypher.blockchain.eth.actors.BaseActor

Actor to interface with the NuCypherToken contract

property token_agent
property token_balance

Return this actor’s current token balance

class ContractAdministrator(*args, **kwargs)

Bases: nucypher.blockchain.eth.actors.BaseActor

The administrator of network contracts.

standard_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.NucypherTokenDeployer'>, <class 'nucypher.blockchain.eth.deployers.PREApplicationDeployer'>, <class 'nucypher.blockchain.eth.deployers.SubscriptionManagerDeployer'>)
dispatched_upgradeable_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>,)
upgradeable_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>,)
aux_deployer_classes = ()
ownable_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>,)
primary_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.NucypherTokenDeployer'>, <class 'nucypher.blockchain.eth.deployers.PREApplicationDeployer'>, <class 'nucypher.blockchain.eth.deployers.SubscriptionManagerDeployer'>, <class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>)
all_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.NucypherTokenDeployer'>, <class 'nucypher.blockchain.eth.deployers.PREApplicationDeployer'>, <class 'nucypher.blockchain.eth.deployers.SubscriptionManagerDeployer'>, <class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>, <class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>)
exception UnknownContract

Bases: ValueError

deploy_contract(contract_name: str, gas_limit: int = None, deployment_mode=FULL, ignore_deployed: bool = False, progress=None, confirmations: int = 0, deployment_parameters: dict = None, emitter=None, *args, **kwargs) → Tuple[dict, nucypher.blockchain.eth.deployers.BaseContractDeployer]
upgrade_contract(contract_name: str, confirmations: int, ignore_deployed: bool = False)dict
retarget_proxy(confirmations: int, contract_name: str, target_address: str, just_build_transaction: bool = False)
rollback_contract(contract_name: str)
save_deployment_receipts(receipts: dict, filename_prefix: str = 'deployment')str
class Operator(is_me: bool, work_tracker: nucypher.blockchain.eth.token.WorkTracker = None, operator_address: NewType.<locals>.new_type = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.actors.BaseActor

READY_TIMEOUT = None
READY_POLL_RATE = 10
exception OperatorError

Bases: nucypher.blockchain.eth.actors.BaseActor.ActorError

property wallet_address
property staking_provider_address
get_staking_provider_address()
property is_confirmed
confirm_address(fire_and_forget: bool = True) → Union[web3.types.TxReceipt, hexbytes.main.HexBytes]
block_until_ready(poll_rate: int = None, timeout: int = None)
get_work_is_needed_check()
class BlockchainPolicyAuthor(eth_provider_uri: str, *args, **kwargs)

Bases: nucypher.blockchain.eth.actors.NucypherTokenActor

Alice base class for blockchain operations, mocking up new policies!

create_policy(*args, **kwargs)

Hence the name, a BlockchainPolicyAuthor can create a BlockchainPolicy with themself as the author.

class Investigator(*args, **kwargs)

Bases: nucypher.blockchain.eth.actors.NucypherTokenActor

Actor that reports incorrect CFrags to the Adjudicator contract. In most cases, Bob will act as investigator, but the actor is generic enough than anyone can report CFrags.

request_evaluation(evidence)dict
was_this_evidence_evaluated(evidence)bool
class EthereumContractAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, eth_provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None, contract_version: Optional[str] = None)

Bases: object

Base class for ethereum contract wrapper types that interact with blockchain contract instances

contract_name: str = NotImplemented
DEFAULT_TRANSACTION_GAS_LIMITS: Dict[str, Optional[NewType.<locals>.new_type]] = {'default': None}
exception ContractNotDeployed

Bases: Exception

Raised when attempting to access a contract that is not deployed on the current network.

exception RequirementError

Bases: Exception

Raised when an agent discovers a failed requirement in an invocation to a contract function, usually, a failed require().

property contract
property contract_address
property owner
class NucypherTokenAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, eth_provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None, contract_version: Optional[str] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'NuCypherToken'
get_balance(address: NewType.<locals>.new_type) → NewType.<locals>.new_type

Get the NU balance (in NuNits) of a token holder address, or of this contract address

get_allowance(owner: NewType.<locals>.new_type, spender: NewType.<locals>.new_type) → NewType.<locals>.new_type

Check the amount of tokens that an owner allowed to a spender

increase_allowance(transacting_power: nucypher.crypto.powers.TransactingPower, spender_address: NewType.<locals>.new_type, increase: NewType.<locals>.new_type) → web3.types.TxReceipt

Increase the allowance of a spender address funded by a sender address

decrease_allowance(transacting_power: nucypher.crypto.powers.TransactingPower, spender_address: NewType.<locals>.new_type, decrease: NewType.<locals>.new_type) → web3.types.TxReceipt

Decrease the allowance of a spender address funded by a sender address

approve_transfer(amount: NewType.<locals>.new_type, spender_address: NewType.<locals>.new_type, transacting_power: nucypher.crypto.powers.TransactingPower) → web3.types.TxReceipt

Approve the spender address to transfer an amount of tokens on behalf of the sender address

transfer(amount: NewType.<locals>.new_type, target_address: NewType.<locals>.new_type, transacting_power: nucypher.crypto.powers.TransactingPower) → web3.types.TxReceipt

Transfer an amount of tokens from the sender address to the target address.

approve_and_call(amount: NewType.<locals>.new_type, target_address: NewType.<locals>.new_type, transacting_power: nucypher.crypto.powers.TransactingPower, call_data: bytes = b'', gas_limit: Optional[NewType.<locals>.new_type] = None) → web3.types.TxReceipt
class SubscriptionManagerAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, eth_provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None, contract_version: Optional[str] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'SubscriptionManager'
class PolicyInfo(sponsor, owner, start_timestamp, end_timestamp)

Bases: tuple

property sponsor

Alias for field number 0

property owner

Alias for field number 1

property start_timestamp

Alias for field number 2

property end_timestamp

Alias for field number 3

fee_rate() → NewType.<locals>.new_type
is_policy_active(policy_id: bytes)bool
fetch_policy(policy_id: bytes)nucypher.blockchain.eth.agents.SubscriptionManagerAgent.PolicyInfo
create_policy(policy_id: bytes, transacting_power: nucypher.crypto.powers.TransactingPower, size: int, start_timestamp: NewType.<locals>.new_type, end_timestamp: NewType.<locals>.new_type, value: NewType.<locals>.new_type, owner_address: Optional[NewType.<locals>.new_type] = None) → web3.types.TxReceipt
class AdjudicatorAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, eth_provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None, contract_version: Optional[str] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'Adjudicator'
evaluate_cfrag(evidence, transacting_power: nucypher.crypto.powers.TransactingPower) → web3.types.TxReceipt

Submits proof that a worker created wrong CFrag

was_this_evidence_evaluated(evidence)bool
property staking_escrow_contract
property hash_algorithm
property base_penalty
property penalty_history_coefficient
property percentage_penalty_coefficient
property reward_coefficient
penalty_history(staker_address: str)int
slashing_parameters() → Tuple[int, …]
class PREApplicationAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, eth_provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None, contract_version: Optional[str] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'SimplePREApplication'
DEFAULT_PROVIDERS_PAGINATION_SIZE_LIGHT_NODE = 30
DEFAULT_PROVIDERS_PAGINATION_SIZE = 1000
exception NotEnoughStakingProviders

Bases: Exception

class OperatorInfo(address, confirmed, start_timestamp)

Bases: tuple

property address

Alias for field number 0

property confirmed

Alias for field number 1

property start_timestamp

Alias for field number 2

get_min_authorization()int
get_min_operator_seconds()int
get_staking_provider_from_operator(operator_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_operator_from_staking_provider(staking_provider: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_beneficiary(staking_provider: NewType.<locals>.new_type) → NewType.<locals>.new_type
is_operator_confirmed(address: NewType.<locals>.new_type)bool
get_staking_provider_info(staking_provider: NewType.<locals>.new_type)nucypher.types.StakingProviderInfo
get_authorized_stake(staking_provider: NewType.<locals>.new_type)int
is_authorized(staking_provider: NewType.<locals>.new_type)bool
get_staking_providers_population()int
get_staking_providers() → List[NewType.<locals>.new_type]

Returns a list of staking provider addresses

get_active_staking_providers(start_index: int, max_results: int) → Iterable
swarm() → Iterable[NewType.<locals>.new_type]
get_all_active_staking_providers(pagination_size: Optional[int] = None) → Tuple[NewType.<locals>.new_type, Dict[NewType.<locals>.new_type, NewType.<locals>.new_type]]
get_staking_provider_reservoir(without: Iterable[NewType.<locals>.new_type] = None, pagination_size: Optional[int] = None)nucypher.blockchain.eth.agents.StakingProvidersReservoir
confirm_operator_address(transacting_power: nucypher.crypto.powers.TransactingPower, fire_and_forget: bool = True) → web3.types.TxReceipt

Confirm the sender’s account as a operator

bond_operator(staking_provider: NewType.<locals>.new_type, operator: NewType.<locals>.new_type, transacting_power: nucypher.crypto.powers.TransactingPower) → web3.types.TxReceipt

For use by threshold operator accounts only.

class ContractAgency

Bases: object

Where agents live and die.

classmethod get_agent(agent_class: Type[Agent], registry: Optional[nucypher.blockchain.eth.registry.BaseContractRegistry] = None, eth_provider_uri: Optional[str] = None, contract_version: Optional[str] = None) → Agent
classmethod get_agent_by_contract_name(contract_name: str, registry: nucypher.blockchain.eth.registry.BaseContractRegistry, eth_provider_uri: Optional[str] = None, contract_version: Optional[str] = None)nucypher.blockchain.eth.agents.EthereumContractAgent
class WeightedSampler(weighted_elements: Dict[Any, int])

Bases: object

Samples random elements with probabilities proportional to given weights.

sample_no_replacement(rng, quantity: int)list

Samples quantity of elements from the internal array. The probability of an element to appear is proportional to the weight provided to the constructor.

The elements will not repeat; every time an element is sampled its weight is set to 0. (does not mutate the object and only applies to the current invocation of the method).

class StakingProvidersReservoir(staking_provider_map: Dict[NewType.<locals>.new_type, int])

Bases: object

draw(quantity)
draw_at_most(quantity)
exception Web3ClientError

Bases: Exception

exception Web3ClientConnectionFailed

Bases: nucypher.blockchain.eth.clients.Web3ClientError

exception Web3ClientUnexpectedVersionString

Bases: nucypher.blockchain.eth.clients.Web3ClientError

class EthereumClient(w3, node_technology: str, version: str, platform: str, backend: str)

Bases: object

is_local = False
GETH = 'Geth'
BOR = 'bor'
PARITY = 'Parity'
ALT_PARITY = 'Parity-Ethereum'
GANACHE = 'EthereumJS TestRPC'
ETHEREUM_TESTER = 'EthereumTester'
CLEF = 'Clef'
BLOCK_CONFIRMATIONS_POLLING_TIME = 3
TRANSACTION_POLLING_TIME = 0.5
COOLING_TIME = 5
STALECHECK_ALLOWABLE_DELAY = 30
exception ConnectionNotEstablished

Bases: RuntimeError

exception SyncTimeout

Bases: RuntimeError

exception UnknownAccount

Bases: ValueError

exception TransactionBroadcastError

Bases: RuntimeError

exception NotEnoughConfirmations

Bases: nucypher.blockchain.eth.clients.EthereumClient.TransactionBroadcastError

exception TransactionTimeout

Bases: nucypher.blockchain.eth.clients.EthereumClient.TransactionBroadcastError

exception ChainReorganizationDetected(receipt)

Bases: nucypher.blockchain.eth.clients.EthereumClient.TransactionBroadcastError

Raised when block confirmations logic detects that a TX was lost due to a chain reorganization

error_message = "Chain re-organization detected: Transaction {transaction_hash} was reported to be in block {block_hash}, but it's not there anymore"
classmethod from_w3(w3: web3.main.Web3)nucypher.blockchain.eth.clients.EthereumClient

Client version strings:

Geth -> ‘Geth/v1.4.11-stable-fed692f6/darwin/go1.7’ Parity -> ‘Parity-Ethereum/v2.5.1-beta-e0141f8-20190510/x86_64-linux-gnu/rustc1.34.1’ Ganache -> ‘EthereumJS TestRPC/v2.1.5/ethereum-js’ PyEVM -> ‘EthereumTester/0.1.0b39/linux/python3.6.7’ Bor -> ‘bor/v0.2.13-beta2-c227a072/linux-amd64/go1.17.5’

property peers
property chain_name
lock_account(account)bool
unlock_account(account, password, duration=None)bool
property is_connected
property etherbase
property accounts
get_balance(account)
inject_middleware(middleware, **kwargs)
add_middleware(middleware)
set_gas_strategy(gas_strategy)
property chain_id
property net_version
get_contract(**kwargs)web3.contract.Contract
property gas_price

Returns client’s gas price. Underneath, it uses the eth_gasPrice JSON-RPC method

gas_price_for_transaction(transaction=None) → NewType.<locals>.new_type

Obtains a gas price via the current gas strategy, if any; otherwise, it resorts to the client’s gas price. This method mirrors the behavior of web3._utils.transactions when building transactions.

property block_number
property coinbase
wait_for_receipt(transaction_hash: str, timeout: float, confirmations: int = 0) → web3.types.TxReceipt
block_until_enough_confirmations(transaction_hash: str, timeout: float, confirmations: int)dict
check_transaction_is_on_chain(receipt: web3.types.TxReceipt)bool
sign_transaction(transaction_dict: dict)bytes
get_transaction(transaction_hash)dict
get_transaction_receipt(transaction_hash) → Optional[dict]
get_transaction_count(account: str, pending: bool)int
send_transaction(transaction_dict: dict)str
send_raw_transaction(transaction_bytes: bytes)str
sign_message(account: str, message: bytes)str

Calls the appropriate signing function for the specified account on the backend. If the backend is based on eth-tester, then it uses the eth-tester signing interface to do so.

get_blocktime()
get_block(block_identifier)
parse_transaction_data(transaction)
class GethClient(w3, node_technology: str, version: str, platform: str, backend: str)

Bases: nucypher.blockchain.eth.clients.EthereumClient

property is_local

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

property peers
new_account(password: str)str
unlock_account(account: str, password: str, duration: int = None)
lock_account(account)
sign_transaction(transaction_dict: dict)bytes
property wallets
class BorClient(w3, node_technology: str, version: str, platform: str, backend: str)

Bases: nucypher.blockchain.eth.clients.GethClient

Geth to Bor adapter

class ParityClient(w3, node_technology: str, version: str, platform: str, backend: str)

Bases: nucypher.blockchain.eth.clients.EthereumClient

property peers

Look for web3.py support for Parity Peers endpoint

Type

TODO

new_account(password: str)str
unlock_account(account, password, duration: int = None)bool
lock_account(account)
class GanacheClient(w3, node_technology: str, version: str, platform: str, backend: str)

Bases: nucypher.blockchain.eth.clients.EthereumClient

is_local = True
unlock_account(*args, **kwargs)bool
class InfuraClient(w3, node_technology: str, version: str, platform: str, backend: str)

Bases: nucypher.blockchain.eth.clients.EthereumClient

is_local = False
TRANSACTION_POLLING_TIME = 2
unlock_account(*args, **kwargs)bool
class AlchemyClient(w3, node_technology: str, version: str, platform: str, backend: str)

Bases: nucypher.blockchain.eth.clients.EthereumClient

class EthereumTesterClient(w3, node_technology: str, version: str, platform: str, backend: str)

Bases: nucypher.blockchain.eth.clients.EthereumClient

is_local = True
unlock_account(account, password, duration: int = None)bool

Returns True if the testing backend keystore has control of the given address.

lock_account(account)bool

Returns True if the testing backend keystore has control of the given address.

new_account(password: str)str
sign_transaction(transaction_dict: dict)bytes
sign_message(account: str, message: bytes)str

Sign, EIP-191 (Geth) Style

parse_transaction_data(transaction)
exception InvalidChecksumAddress

Bases: eth_utils.exceptions.ValidationError

validate_checksum_address(func: Callable) → Callable

EIP-55 Checksum address validation decorator.

Inspects the decorated function for input parameters ending with “_address”, then uses eth_utils to validate the addresses’ EIP-55 checksum, verifying the input type on failure; Raises TypeError or InvalidChecksumAddress if validation fails, respectively.

EIP-55 Specification: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md ETH Utils Implementation: https://github.com/ethereum/eth-utils

only_me(func: Callable) → Callable

Decorator to enforce invocation of permissioned actor methods

save_receipt(actor_method) → Callable

Decorator to save the result of a function with a timestamp

contract_api(interface: Union[CONTRACT_CALL(b’\xf3\x17\t`\x10\xee\x02\xf8’), TRANSACTION(b’\xbb\x13Q!*a,L’), CONTRACT_ATTRIBUTE(b’;\x03\x8eh\xa52\x96\xe7’), UNKNOWN_CONTRACT_INTERFACE(b’e\xeb%X6$\xdb\x9f’), None] = UNKNOWN_CONTRACT_INTERFACE(b'e\xeb%X6$\xdb\x9f')) → Callable

Decorator factory for contract API markers

class BaseContractDeployer(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, economics: nucypher.blockchain.economics.Economics = None)

Bases: object

agency = NotImplemented
contract_name = NotImplemented
deployment_steps = NotImplemented
can_be_idle = False
exception ContractDeploymentError

Bases: Exception

exception ContractNotDeployed

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer.ContractDeploymentError

property economics

Read-only access for economics instance.

property contract_address
property contract
property dispatcher
is_deployed(contract_version: str = None)bool
check_deployment_readiness(deployer_address: NewType.<locals>.new_type, contract_version: str = None, ignore_deployed=False, fail=True, additional_rules: List[Tuple[bool, str]] = None) → Tuple[bool, list]

Iterates through a set of rules required for an ethereum contract deployer to be eligible for deployment returning a tuple or raising an exception if <fail> is True.

Returns a tuple containing the boolean readiness result and a list of reasons (if any) why the deployer is not ready.

If fail is set to True, raise a configuration error, instead of returning.

deploy(transacting_power: nucypher.crypto.powers.TransactingPower, deployment_mode=FULL, gas_limit: int = None, progress: int = None, emitter=None, **overrides)dict

Provides for the setup, deployment, and initialization of ethereum smart contracts. Emits the configured blockchain network transactions for single contract instance publication.

make_agent()nucypher.blockchain.eth.agents.EthereumContractAgent
get_latest_enrollment()nucypher.blockchain.eth.interfaces.VersionedContract

Get the latest enrolled, bare version of the contract from the registry.

class OwnableContractMixin

Bases: object

exception ContractNotOwnable

Bases: RuntimeError

property owner
transfer_ownership(transacting_power: nucypher.crypto.powers.TransactingPower, new_owner: str, transaction_gas_limit: int = None)dict
class UpgradeableContractMixin

Bases: object

exception ContractNotUpgradeable

Bases: RuntimeError

deploy(deployment_mode=FULL, gas_limit: int = None, progress=None, contract_version: str = 'latest', ignore_deployed: bool = False)dict

Provides for the setup, deployment, and initialization of ethereum smart contracts. Emits the configured blockchain network transactions for single contract instance publication.

get_principal_contract()nucypher.blockchain.eth.interfaces.VersionedContract

Get the on-chain targeted version of the principal contract directly without assembling it with its proxy.

get_proxy_contract()nucypher.blockchain.eth.interfaces.VersionedContract
get_proxy_deployer()nucypher.blockchain.eth.deployers.BaseContractDeployer
retarget(transacting_power: nucypher.crypto.powers.TransactingPower, target_address: str, confirmations: int, gas_limit: int = None, just_build_transaction: bool = False)

Directly engage a proxy contract for an existing deployment, executing the proxy’s upgrade interfaces to verify upgradeability and modify the on-chain contract target.

upgrade(transacting_power: nucypher.crypto.powers.TransactingPower, confirmations: int, gas_limit: int = None, contract_version: str = 'latest', ignore_deployed: bool = False, **overrides)

Deploy a new version of a contract, then engage the proxy contract’s upgrade interfaces.

rollback(transacting_power: nucypher.crypto.powers.TransactingPower, gas_limit: int = None)

Execute an existing deployment’s proxy contract, engaging the upgrade rollback interfaces, modifying the proxy’s on-chain contract target to the most recent previous target.

class NucypherTokenDeployer(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, economics: nucypher.blockchain.economics.Economics = None)

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer

agency

alias of nucypher.blockchain.eth.agents.NucypherTokenAgent

contract_name = 'NuCypherToken'
deployment_steps = ('contract_deployment',)
TOTAL_SUPPLY = 1000000000000000000000000000
deploy(transacting_power: nucypher.crypto.powers.TransactingPower, gas_limit: int = None, progress=None, confirmations: int = 0, deployment_mode=FULL, ignore_deployed: bool = False, emitter=None, **overrides)dict

Deploy and publish the NuCypher Token contract to the blockchain network specified in self.blockchain.network.

Deployment can only ever be executed exactly once!

class ProxyContractDeployer(target_contract: web3.contract.Contract, bare: bool = False, *args, **kwargs)

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer

contract_name = NotImplemented
deployment_steps = ('contract_deployment',)
deploy(transacting_power: nucypher.crypto.powers.TransactingPower, gas_limit: int = None, progress=None, confirmations: int = 0)dict

Provides for the setup, deployment, and initialization of ethereum smart contracts. Emits the configured blockchain network transactions for single contract instance publication.

retarget(transacting_power: nucypher.crypto.powers.TransactingPower, new_target: str, confirmations: int, gas_limit: int = None)dict
build_retarget_transaction(sender_address: NewType.<locals>.new_type, new_target: str, gas_limit: int = None)dict
rollback(transacting_power: nucypher.crypto.powers.TransactingPower, gas_limit: int = None)dict
class DispatcherDeployer(target_contract: web3.contract.Contract, bare: bool = False, *args, **kwargs)

Bases: nucypher.blockchain.eth.deployers.OwnableContractMixin, nucypher.blockchain.eth.deployers.ProxyContractDeployer

Ethereum smart contract that acts as a proxy to another ethereum contract, used as a means of “dispatching” the correct version of the contract to the client

contract_name = 'Dispatcher'
class StakingEscrowDeployer(staking_interface: NewType.<locals>.new_type = None, worklock_address: NewType.<locals>.new_type = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer, nucypher.blockchain.eth.deployers.UpgradeableContractMixin, nucypher.blockchain.eth.deployers.OwnableContractMixin

Deploys the StakingEscrow ethereum contract to the blockchain. Depends on NucypherTokenAgent

agency = NotImplemented
contract_name = 'StakingEscrow'
contract_name_stub = 'StakingEscrowStub'
can_be_idle = True
init_steps = ('stub_deployment', 'dispatcher_deployment')
preparation_steps = ('contract_deployment', 'dispatcher_retarget')
deployment_steps = ('contract_deployment', 'dispatcher_retarget')
STUB_MIN_ALLOWED_TOKENS = 15000000000000000000000
STUB_MAX_ALLOWED_TOKENS = 30000000000000000000000000
deploy(transacting_power: nucypher.crypto.powers.TransactingPower, deployment_mode=INIT, gas_limit: int = None, progress=None, contract_version: str = 'latest', ignore_deployed: bool = False, confirmations: int = 0, emitter=None, **overrides)dict

Deploy and publish the StakingEscrow contract to the blockchain network specified in self.blockchain.network.

Emits the following blockchain network transactions:
  • StakingEscrow contract deployment

  • StakingEscrow dispatcher deployment

  • Transfer reward tokens origin to StakingEscrow contract

  • StakingEscrow contract initialization

Returns transaction receipts in a dict.

class SubscriptionManagerDeployer(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, economics: nucypher.blockchain.economics.Economics = None)

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer, nucypher.blockchain.eth.deployers.OwnableContractMixin

agency

alias of nucypher.blockchain.eth.agents.SubscriptionManagerAgent

contract_name = 'SubscriptionManager'
deployment_steps = ('contract_deployment', 'initialize')
deploy(transacting_power: nucypher.crypto.powers.TransactingPower, gas_limit: int = None, progress=None, confirmations: int = 0, emitter=None, ignore_deployed: bool = False, deployment_mode=FULL, **overrides)dict

Provides for the setup, deployment, and initialization of ethereum smart contracts. Emits the configured blockchain network transactions for single contract instance publication.

class AdjudicatorDeployer(*args, **kwargs)

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer, nucypher.blockchain.eth.deployers.UpgradeableContractMixin, nucypher.blockchain.eth.deployers.OwnableContractMixin

agency

alias of nucypher.blockchain.eth.agents.AdjudicatorAgent

contract_name = 'Adjudicator'
deployment_steps = ('contract_deployment', 'dispatcher_deployment')
check_deployment_readiness(deployer_address: NewType.<locals>.new_type, *args, **kwargs) → Tuple[bool, list]

Iterates through a set of rules required for an ethereum contract deployer to be eligible for deployment returning a tuple or raising an exception if <fail> is True.

Returns a tuple containing the boolean readiness result and a list of reasons (if any) why the deployer is not ready.

If fail is set to True, raise a configuration error, instead of returning.

deploy(transacting_power: nucypher.crypto.powers.TransactingPower, deployment_mode=FULL, gas_limit: int = None, progress=None, contract_version: str = 'latest', ignore_deployed: bool = False, emitter=None, confirmations: int = 0, **overrides) → Dict[str, str]

Provides for the setup, deployment, and initialization of ethereum smart contracts. Emits the configured blockchain network transactions for single contract instance publication.

class PREApplicationDeployer(staking_interface: NewType.<locals>.new_type = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer

agency

alias of nucypher.blockchain.eth.agents.PREApplicationAgent

contract_name = 'SimplePREApplication'
deployment_steps = ('contract_deployment',)
deploy(transacting_power: nucypher.crypto.powers.TransactingPower, gas_limit: int = None, confirmations: int = 0, deployment_mode=FULL, ignore_deployed: bool = False, progress=None, emitter=None, **overrides)

Provides for the setup, deployment, and initialization of ethereum smart contracts. Emits the configured blockchain network transactions for single contract instance publication.

class EventRecord(event: dict)

Bases: object

class ContractEvents(contract: web3.contract.Contract)

Bases: object

class ContractEventsThrottler(agent: EthereumContractAgent, event_name: str, from_block: int, to_block: int = None, max_blocks_per_call: int = 1000, **argument_filters)

Bases: object

Enables Contract events to be retrieved in batches.

DEFAULT_MAX_BLOCKS_PER_CALL = 1000
class VersionedContract(address: Optional[NewType.<locals>.new_type] = None)

Bases: web3.contract.Contract

version = None
class BlockchainInterface(emitter=None, poa: bool = None, light: bool = False, eth_provider_uri: str = NO_BLOCKCHAIN_CONNECTION, eth_provider: web3.providers.base.BaseProvider = NO_BLOCKCHAIN_CONNECTION, gas_strategy: Union[str, Callable, None] = None, max_gas_price: Optional[int] = None)

Bases: object

Interacts with a solidity compiler and a registry in order to instantiate compiled ethereum contracts with the given web3 provider backend.

TIMEOUT = 600
DEFAULT_GAS_STRATEGY = 'fast'
GAS_STRATEGIES = {'fast': <function web3_gas_strategy_wrapper.<locals>._wrapper>, 'medium': <function web3_gas_strategy_wrapper.<locals>._wrapper>, 'slow': <function web3_gas_strategy_wrapper.<locals>._wrapper>}
class Web3(provider: Optional[web3.providers.base.BaseProvider] = None, middlewares: Optional[Sequence[Any]] = None, modules: Optional[Dict[str, Union[Type[web3.module.Module], Sequence[Any]]]] = None, external_modules: Optional[Dict[str, Union[Type[web3.module.Module], Sequence[Any]]]] = None, ens: ens.main.ENS = <web3._utils.empty.Empty object>)

Bases: object

class AsyncHTTPProvider(endpoint_uri: Union[NewType.<locals>.new_type, str, None] = None, request_kwargs: Optional[Any] = None)

Bases: web3.providers.async_base.AsyncJSONBaseProvider

async cache_async_session(session: aiohttp.client.ClientSession)None
endpoint_uri = None
get_request_headers() → Dict[str, str]
get_request_kwargs() → Iterable[Tuple[str, Any]]
logger = <Logger web3.providers.HTTPProvider (WARNING)>
async make_request(method: NewType.<locals>.new_type, params: Any) → web3.types.RPCResponse
class EthereumTesterProvider(ethereum_tester: Union[EthereumTester, BaseChainBackend, None] = None, api_endpoints: Optional[Dict[str, Dict[str, Callable[[…], web3.types.RPCResponse]]]] = None)

Bases: web3.providers.base.BaseProvider

api_endpoints = None
ethereum_tester = None
isConnected() → typing_extensions.Literal[True][True]
make_request(method: NewType.<locals>.new_type, params: Any) → web3.types.RPCResponse
middlewares = (<function default_transaction_fields_middleware>, <function construct_web3_formatting_middleware.<locals>.formatter_middleware>)
class HTTPProvider(endpoint_uri: Union[NewType.<locals>.new_type, str, None] = None, request_kwargs: Optional[Any] = None, session: Optional[Any] = None)

Bases: web3.providers.base.JSONBaseProvider

endpoint_uri = None
get_request_headers() → Dict[str, str]
get_request_kwargs() → Iterable[Tuple[str, Any]]
logger = <Logger web3.providers.HTTPProvider (WARNING)>
make_request(method: NewType.<locals>.new_type, params: Any) → web3.types.RPCResponse
class IPCProvider(ipc_path: Union[str, pathlib.Path] = None, timeout: int = 10, *args: Any, **kwargs: Any)

Bases: web3.providers.base.JSONBaseProvider

logger = <Logger web3.providers.IPCProvider (WARNING)>
make_request(method: NewType.<locals>.new_type, params: Any) → web3.types.RPCResponse
class Iban(iban: str)

Bases: object

address() → Union[str, NewType.<locals>.new_type]

Should be called to get client direct address

@method address @returns {String} client direct address

checksum()str

Should be called to get iban checksum Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003)

@method checksum @returns {String} checksum

client()str

Should be called to get client identifier within institution eg. GAVOFYORK

@method client @returns {String} client identifier

static createIndirect(options: web3.iban.IbanOptions) → web3.iban.Iban

Should be used to create IBAN object for given institution and identifier

@method createIndirect @param {Object} options, required options are “institution” and “identifier” @return {Iban} the IBAN object

static fromAddress(address: Union[NewType.<locals>.new_type, NewType.<locals>.new_type]) → web3.iban.Iban

This method should be used to create an iban object from ethereum address

@method fromAddress @param {String} address @return {Iban} the IBAN object

static fromBban(bban: str) → web3.iban.Iban

Convert the passed BBAN to an IBAN for this country specification. Please note that <i>”generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account”</i>. This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits

@method fromBban @param {String} bban the BBAN to convert to IBAN @returns {Iban} the IBAN object

institution()str

Should be called to get institution identifier eg. XREG

@method institution @returns {String} institution identifier

isDirect()bool

Should be called to check if iban number is direct

@method isDirect @returns {Boolean} true if it is, otherwise false

isIndirect()bool

Should be called to check if iban number if indirect

@method isIndirect @returns {Boolean} true if it is, otherwise false

isValid()bool
toString()str
class RequestManager(web3: Web3, provider: Optional[web3.providers.base.BaseProvider] = None, middlewares: Optional[Sequence[Tuple[Callable[[Callable[[NewType.<locals>.new_type, Any], web3.types.RPCResponse], Web3], Any], str]]] = None)

Bases: object

async coro_request(method: Union[NewType.<locals>.new_type, Callable[[...], NewType.<locals>.new_type]], params: Any, error_formatters: Optional[Callable[[...], Any]] = None, null_result_formatters: Optional[Callable[[...], Any]] = None) → Any

Couroutine for making a request using the provider

static default_middlewares(web3: Web3) → List[Tuple[Callable[[Callable[[NewType.<locals>.new_type, Any], web3.types.RPCResponse], Web3], Any], str]]

List the default middlewares for the request manager. Leaving ens unspecified will prevent the middleware from resolving names.

static formatted_response(response: web3.types.RPCResponse, params: Any, error_formatters: Optional[Callable[[…], Any]] = None, null_result_formatters: Optional[Callable[[…], Any]] = None) → Any
logger = <Logger web3.RequestManager (WARNING)>
property provider
receive_async(request_id: uuid.UUID, *args: Any, **kwargs: Any) → NoReturn
receive_blocking(request_id: uuid.UUID, timeout: Optional[float] = None) → Any
request_async(raw_method: str, raw_params: Any)uuid.UUID
request_blocking(method: Union[NewType.<locals>.new_type, Callable[[...], NewType.<locals>.new_type]], params: Any, error_formatters: Optional[Callable[[...], Any]] = None, null_result_formatters: Optional[Callable[[...], Any]] = None) → Any

Make a synchronous request using the provider

web3: Web3 = None
class WebsocketProvider(endpoint_uri: Union[NewType.<locals>.new_type, str, None] = None, websocket_kwargs: Optional[Any] = None, websocket_timeout: int = 10)

Bases: web3.providers.base.JSONBaseProvider

async coro_make_request(request_data: bytes) → web3.types.RPCResponse
logger = <Logger web3.providers.WebsocketProvider (WARNING)>
make_request(method: NewType.<locals>.new_type, params: Any) → web3.types.RPCResponse
property api
async_net = None
attach_modules(modules: Optional[Dict[str, Union[Type[web3.module.Module], Sequence[Any]]]])None

Attach modules to the Web3 instance.

property clientVersion
enable_strict_bytes_type_checking()None
enable_unstable_package_management_api()None
property ens
eth = None
static fromWei(number: int, unit: str) → Union[int, decimal.Decimal]

Takes a number of wei and converts it to any other ether unit.

geth = None
static isAddress(value: Any)bool

Is the given string an address in any of the known formats?

static isChecksumAddress(value: Any)bool
isConnected()bool
is_encodable(_type: str, value: Any)bool
static keccak(primitive: Union[bytes, int, bool, None] = None, text: Optional[str] = None, hexstr: Optional[NewType.<locals>.new_type] = None)bytes
property middleware_onion
net = None
parity = None
property pm
property provider
static sha3(primitive: Union[bytes, int, bool, None] = None, text: Optional[str] = None, hexstr: Optional[NewType.<locals>.new_type] = None)bytes
solidityKeccak(abi_types: List[str], values: List[Any])bytes

Executes keccak256 exactly as Solidity does. Takes list of abi_types as inputs – [uint24, int8[], bool] and list of corresponding values – [20, [-1, 5, 0], True]

soliditySha3(abi_types: List[str], values: List[Any])bytes
static toBytes(primitive: Union[bytes, int, bool] = None, hexstr: NewType.<locals>.new_type = None, text: str = None)bytes
static toChecksumAddress(value: Union[AnyAddress, str, bytes]) → NewType.<locals>.new_type

Makes a checksum address given a supported format.

static toHex(primitive: Union[bytes, int, bool] = None, hexstr: NewType.<locals>.new_type = None, text: str = None) → NewType.<locals>.new_type

Auto converts any supported value into its hex representation. Trims leading zeros, as defined in: https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding

static toInt(primitive: Union[bytes, int, bool] = None, hexstr: NewType.<locals>.new_type = None, text: str = None)int

Converts value to its integer representation. Values are converted this way:

  • primitive:

    • bytes, bytearrays: big-endian integer

    • bool: True => 1, False => 0

  • hexstr: interpret hex as integer

  • text: interpret as string of digits, like ‘12’ => 12

static toJSON(obj: Dict[Any, Any])str

Convert a complex object (like a transaction object) to a JSON string

static toText(primitive: Union[bytes, int, bool] = None, hexstr: NewType.<locals>.new_type = None, text: str = None)str
static toWei(number: Union[int, float, str, decimal.Decimal], unit: str)int

Takes a number of a unit and converts it to wei.

exception InterfaceError

Bases: Exception

exception NoProvider

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterface.InterfaceError

exception UnsupportedProvider

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterface.InterfaceError

exception ConnectionFailed

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterface.InterfaceError

exception UnknownContract

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterface.InterfaceError

REASONS = {INSUFFICIENT_ETH: 'insufficient funds for gas * price + value'}
exception TransactionFailed(message: str, transaction_dict: dict, contract_function: Union[web3.contract.ContractFunction, web3.contract.ContractConstructor], *args)

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterface.InterfaceError

IPC_CODE = -32000
property default
get_balance()
property insufficient_eth
get_blocktime()
property is_connected

//web3py.readthedocs.io/en/stable/__provider.html#examples-using-automated-detection

Type

https

classmethod get_gas_strategy(gas_strategy: Union[str, Callable] = None) → Callable
attach_middleware()
configure_gas_strategy(gas_strategy: Optional[Callable] = None)None
connect()
property provider
build_payload(sender_address: str, payload: dict = None, transaction_gas_limit: int = None, use_pending_nonce: bool = True)dict
build_contract_transaction(contract_function: web3.contract.ContractFunction, sender_address: str, payload: dict = None, transaction_gas_limit: Optional[int] = None, gas_estimation_multiplier: Optional[float] = None, use_pending_nonce: Optional[bool] = None)dict
sign_and_broadcast_transaction(transacting_power: nucypher.crypto.powers.TransactingPower, transaction_dict: eth.typing.TransactionDict, transaction_name: str = '', confirmations: int = 0, fire_and_forget: bool = False) → Union[web3.types.TxReceipt, hexbytes.main.HexBytes]

Takes a transaction dictionary, signs it with the configured signer, then broadcasts the signed transaction using the ethereum provider’s eth_sendRawTransaction RPC endpoint. Optionally blocks for receipt and confirmation with ‘confirmations’, and ‘fire_and_forget’ flags.

If ‘fire and forget’ is True this method returns the transaction hash only, without waiting for a receipt - otherwise return the transaction receipt.

send_transaction(contract_function: Union[web3.contract.ContractFunction, web3.contract.ContractConstructor], transacting_power: nucypher.crypto.powers.TransactingPower, payload: dict = None, transaction_gas_limit: Optional[int] = None, gas_estimation_multiplier: Optional[float] = 1.15, confirmations: int = 0, fire_and_forget: bool = False, replace: bool = False) → Union[web3.types.TxReceipt, hexbytes.main.HexBytes]
get_contract_by_name(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, contract_name: str, contract_version: str = None, enrollment_version: Union[int, str] = None, proxy_name: str = None, use_proxy_address: bool = True)nucypher.blockchain.eth.interfaces.VersionedContract

Instantiate a deployed contract from registry data, and assimilate it with its proxy if it is upgradeable.

class BlockchainDeployerInterface(emitter=None, poa: bool = None, light: bool = False, eth_provider_uri: str = NO_BLOCKCHAIN_CONNECTION, eth_provider: web3.providers.base.BaseProvider = NO_BLOCKCHAIN_CONNECTION, gas_strategy: Union[str, Callable, None] = None, max_gas_price: Optional[int] = None)

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterface

TIMEOUT = 600
SOURCES: List[nucypher.blockchain.eth.sol.compile.types.SourceBundle] = [SourceBundle(base_path=PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/nucypher/envs/latest/lib/python3.7/site-packages/nucypher/blockchain/eth/sol/source'), other_paths=())]
exception NoDeployerAddress

Bases: RuntimeError

exception DeploymentFailed

Bases: RuntimeError

connect(compile_now: bool = True, ignore_solidity_check: bool = False)bool
deploy_contract(transacting_power: nucypher.crypto.powers.TransactingPower, registry: nucypher.blockchain.eth.registry.BaseContractRegistry, contract_name: str, *constructor_args, enroll: bool = True, gas_limit: int = None, confirmations: int = 0, contract_version: str = 'latest', **constructor_kwargs) → Tuple[nucypher.blockchain.eth.interfaces.VersionedContract, web3.types.TxReceipt]

Retrieve compiled interface data from the cache and return an instantiated deployed contract

find_raw_contract_data(contract_name: str, requested_version: str = 'latest') → Tuple[str, dict]
get_contract_instance(address: NewType.<locals>.new_type, contract_name: str, version: str = 'latest')nucypher.blockchain.eth.interfaces.VersionedContract

Retrieve compiled contract data from the cache and return web3 contract instantiated for some address

get_contract_factory(contract_name: str, version: str = 'latest')nucypher.blockchain.eth.interfaces.VersionedContract

Retrieve compiled contract data from the cache and return web3 contract factory

get_proxy_contract(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, target_address: str, proxy_name: str)nucypher.blockchain.eth.interfaces.VersionedContract
class BlockchainInterfaceFactory

Bases: object

Canonical source of bound blockchain interfaces.

class CachedInterface(interface, emitter)

Bases: tuple

property interface

Alias for field number 0

property emitter

Alias for field number 1

exception FactoryError

Bases: Exception

exception NoRegisteredInterfaces

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterfaceFactory.FactoryError

exception InterfaceNotInitialized

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterfaceFactory.FactoryError

exception InterfaceAlreadyInitialized

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterfaceFactory.FactoryError

classmethod is_interface_initialized(eth_provider_uri: str)bool

Returns True if there is an existing connection with an equal eth_provider_uri.

classmethod register_interface(interface: nucypher.blockchain.eth.interfaces.BlockchainInterface, emitter=None, force: bool = False)None
classmethod initialize_interface(eth_provider_uri: str, emitter=None, interface_class: Union[nucypher.blockchain.eth.interfaces.BlockchainInterface, nucypher.blockchain.eth.interfaces.BlockchainDeployerInterface] = None, *interface_args, **interface_kwargs)None
classmethod get_interface(eth_provider_uri: str = None) → Union[nucypher.blockchain.eth.interfaces.BlockchainInterface, nucypher.blockchain.eth.interfaces.BlockchainDeployerInterface]
classmethod get_or_create_interface(eth_provider_uri: str, *interface_args, **interface_kwargs)nucypher.blockchain.eth.interfaces.BlockchainInterface
class NetworksInventory

Bases: object

MAINNET = 'mainnet'
IBEX = 'ibex'
LYNX = 'lynx'
ORYX = 'oryx'
ETH = 'ethereum'
POLYGON = 'polygon'
MUMBAI = 'mumbai'
UNKNOWN = 'unknown'
DEFAULT = 'mainnet'
ETH_NETWORKS = ('mainnet', 'oryx', 'ibex', 'lynx')
POLY_NETWORKS = ('polygon', 'mumbai')
NETWORKS = ('mainnet', 'oryx', 'ibex', 'lynx', 'polygon', 'mumbai')
exception UnrecognizedNetwork

Bases: RuntimeError

classmethod get_ethereum_chain_id(network)
classmethod validate_network_name(network_name: str)
exception ProviderError

Bases: Exception

class CanonicalRegistrySource(network: str, registry_name: str, *args, **kwargs)

Bases: abc.ABC

logger

Drop-in replacement of Twisted’s Logger, patching the emit() method to tolerate inputs with curly braces, i.e., not compliant with PEP 3101.

See Issue #724 and, particularly, https://github.com/nucypher/nucypher/issues/724#issuecomment-600190455

name

alias of builtins.NotImplementedError

is_primary

alias of builtins.NotImplementedError

exception RegistrySourceError

Bases: Exception

exception RegistrySourceUnavailable

Bases: nucypher.blockchain.eth.registry.CanonicalRegistrySource.RegistrySourceError

abstract get_publication_endpoint()str
abstract fetch_latest_publication() → Union[str, bytes]
class GithubRegistrySource(network: str, registry_name: str, *args, **kwargs)

Bases: nucypher.blockchain.eth.registry.CanonicalRegistrySource

name = 'GitHub Registry Source'
is_primary = True
get_publication_endpoint()str
fetch_latest_publication() → Union[str, bytes]
class EmbeddedRegistrySource(network: str, registry_name: str, *args, **kwargs)

Bases: nucypher.blockchain.eth.registry.CanonicalRegistrySource

name = 'Embedded Registry Source'
is_primary = False
get_publication_endpoint()pathlib.Path
fetch_latest_publication() → Union[str, bytes]
class RegistrySourceManager(sources=None, only_primary: bool = False)

Bases: object

logger

Drop-in replacement of Twisted’s Logger, patching the emit() method to tolerate inputs with curly braces, i.e., not compliant with PEP 3101.

See Issue #724 and, particularly, https://github.com/nucypher/nucypher/issues/724#issuecomment-600190455

exception NoSourcesAvailable

Bases: Exception

classmethod get_primary_sources()
fetch_latest_publication(registry_class, network: str)

Get the latest contract registry data available from a registry source chain.

class BaseContractRegistry(source=None, *args, **kwargs)

Bases: abc.ABC

Records known contracts on the disk for future access and utility. This lazily writes to the filesystem during contract enrollment.

WARNING: Unless you are developing NuCypher, you most likely won’t ever need to use this.

logger

Drop-in replacement of Twisted’s Logger, patching the emit() method to tolerate inputs with curly braces, i.e., not compliant with PEP 3101.

See Issue #724 and, particularly, https://github.com/nucypher/nucypher/issues/724#issuecomment-600190455

REGISTRY_NAME = 'contract_registry.json'
DEVELOPMENT_REGISTRY_NAME = 'dev_contract_registry.json'
exception RegistryError

Bases: Exception

exception EmptyRegistry

Bases: nucypher.blockchain.eth.registry.BaseContractRegistry.RegistryError

exception NoRegistry

Bases: nucypher.blockchain.eth.registry.BaseContractRegistry.RegistryError

exception UnknownContract

Bases: nucypher.blockchain.eth.registry.BaseContractRegistry.RegistryError

exception InvalidRegistry

Bases: nucypher.blockchain.eth.registry.BaseContractRegistry.RegistryError

Raised when invalid data is encountered in the registry

exception CantOverwriteRegistry

Bases: nucypher.blockchain.eth.registry.BaseContractRegistry.RegistryError

property id

Returns a hexstr of the registry contents.

abstract write(registry_data: list)None
abstract read() → Union[list, dict]
classmethod from_latest_publication(*args, source_manager=None, network: str = 'mainnet', **kwargs)nucypher.blockchain.eth.registry.BaseContractRegistry

Get the latest contract registry available from a registry source chain.

property source
property enrolled_names
property enrolled_addresses
enroll(contract_name, contract_address, contract_abi, contract_version)None

Enrolls a contract to the chain registry by writing the name, version, address, and abi information to the filesystem as JSON.

Note: Unless you are developing NuCypher, you most likely won’t ever need to use this.

search(contract_name: str = None, contract_version: str = None, contract_address: str = None)tuple

Searches the registry for a contract with the provided name or address and returns the contracts component data.

class LocalContractRegistry(filepath: pathlib.Path, *args, **kwargs)

Bases: nucypher.blockchain.eth.registry.BaseContractRegistry

REGISTRY_TYPE = 'contract'
property filepath
read() → Union[list, dict]

Reads the registry file and parses the JSON and returns a list. If the file is empty it will return an empty list. If you are modifying or updating the registry file, you _must_ call this function first to get the current state to append to the dict or modify it because _write_registry_file overwrites the file.

write(registry_data: Union[List, Dict])None

Writes the registry data list as JSON to the registry file. If no file exists, it will create it and write the data. If a file does exist it will _overwrite_ everything in it.

classmethod from_dict(payload: dict, **overrides)nucypher.blockchain.eth.registry.LocalContractRegistry
to_dict()dict
class TemporaryContractRegistry(*args, **kwargs)

Bases: nucypher.blockchain.eth.registry.LocalContractRegistry

clear()
commit(filepath)pathlib.Path

writes the current state of the registry to a file

class InMemoryContractRegistry(*args, **kwargs)

Bases: nucypher.blockchain.eth.registry.BaseContractRegistry

clear()
write(registry_data: list)None
read()list
commit(filepath: Optional[pathlib.Path] = None, overwrite: bool = False)pathlib.Path

writes the current state of the registry to a file

class ERC20(value: Union[int, decimal.Decimal, str], denomination: str)

Bases: object

An amount of ERC20 tokens that doesn’t hurt your eyes. Wraps the eth_utils currency conversion methods.

The easiest way to use ERC20, is to pass an int, Decimal, or str, and denomination string:

Int: t = T(100, ‘T’) Int: t = T(15000000000000000000000, ‘TuNits’)

Decimal: t = T(Decimal(‘15042.445’), ‘T’) String: t = T(‘10002.302’, ‘T’)

…or alternately…

Decimal: t = T.from_tokens(Decimal(‘100.50’)) Int: t = T.from_units(15000000000000000000000)

Token quantity is stored internally as an int in the smallest denomination, and all arithmetic operations use this value.

Using float inputs to this class to represent amounts of NU is supported but not recommended, as floats don’t have enough precision to represent some quantities.

exception InvalidAmount

Bases: ValueError

Raised when an invalid input amount is provided

exception InvalidDenomination

Bases: ValueError

Raised when an unknown denomination string is passed into __init__

classmethod ZERO()nucypher.blockchain.eth.token.ERC20
classmethod from_units(value: int)nucypher.blockchain.eth.token.ERC20
classmethod from_tokens(value: Union[int, decimal.Decimal, str])nucypher.blockchain.eth.token.ERC20
to_tokens()decimal.Decimal

Returns a decimal value of NU

to_units() → NewType.<locals>.new_type

Returns an int value in the Unit class for this token

class NU(value: Union[int, decimal.Decimal, str], denomination: str)

Bases: nucypher.blockchain.eth.token.ERC20

class TToken(value: Union[int, decimal.Decimal, str], denomination: str)

Bases: nucypher.blockchain.eth.token.ERC20

class WorkTrackerBase(worker, *args, **kwargs)

Bases: object

Baseclass for handling automated transaction tracking…

CLOCK = <twisted.internet.epollreactor.EPollReactor object>
INTERVAL_FLOOR = 900
INTERVAL_CEIL = 10800
ALLOWED_DEVIATION = 0.5
classmethod random_interval(fails=None)int
max_confirmation_time()int
stop()None
start(commit_now: bool = True, requirement_func: Callable = None, force: bool = False)None

High-level stake tracking initialization, this function aims to be safely called at any time - For example, it is okay to call this function multiple times within the same period.

handle_working_errors(*args, **kwargs)None
property pending
class WorkTracker(worker, *args, **kwargs)

Bases: nucypher.blockchain.eth.token.WorkTrackerBase

INTERVAL_FLOOR = 1
INTERVAL_CEIL = 2
epoch_to_period(epoch: int, seconds_per_period: int)int
datetime_to_period(datetime: maya.core.MayaDT, seconds_per_period: int)int

Converts a MayaDT instance to a period number.

period_to_epoch(period: int, seconds_per_period: int)int
get_current_period(seconds_per_period: int)int
datetime_at_period(period: int, seconds_per_period: int, start_of_period: bool = False) → maya.core.MayaDT

Returns the datetime object at a given period, future, or past. If start_of_period, the datetime object represents the first second of said period.

calculate_period_duration(future_time: maya.core.MayaDT, seconds_per_period: int, now: maya.core.MayaDT = None)int

Takes a future MayaDT instance and calculates the duration from now, returning in periods

estimate_block_number_for_period(period: int, seconds_per_period: int, latest_block: NewType.<locals>.new_type) → NewType.<locals>.new_type

Logic for getting the approximate block height of the start of the specified period.

etherscan_url(item, network: str, is_token=False)str
prettify_eth_amount(amount, original_denomination: str = 'wei')str

Converts any ether amount in original_denomination and finds a suitable representation based on its length. The options in consideration are representing the amount in wei, gwei or ETH. :param amount: Input amount to prettify :param original_denomination: Denomination used by amount (by default, wei is assumed) :return: Shortest representation for amount, considering wei, gwei and ETH.

get_transaction_name(contract_function: Union[web3.contract.ContractFunction, web3.contract.ContractConstructor])str