nucypher.blockchain.eth

Submodules

class BaseActor(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, domains=None, checksum_address: NewType.<locals>.new_type = 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 actors’s current ETH balance

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

Bases: nucypher.blockchain.eth.actors.BaseActor

Actor to interface with the NuCypherToken contract

property token_balance

Return this actors’s current token balance

class ContractAdministrator(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, deployer_address: str = None, client_password: str = None, signer: nucypher.blockchain.eth.signers.base.Signer = None, staking_escrow_test_mode: bool = False, is_transacting: bool = True, economics: nucypher.blockchain.economics.BaseEconomics = None)

Bases: nucypher.blockchain.eth.actors.NucypherTokenActor

The administrator of network contracts.

standard_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.NucypherTokenDeployer'>,)
dispatched_upgradeable_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.StakingEscrowDeployer'>, <class 'nucypher.blockchain.eth.deployers.PolicyManagerDeployer'>, <class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>)
upgradeable_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.StakingEscrowDeployer'>, <class 'nucypher.blockchain.eth.deployers.PolicyManagerDeployer'>, <class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>, <class 'nucypher.blockchain.eth.deployers.StakingInterfaceDeployer'>)
aux_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.WorklockDeployer'>, <class 'nucypher.blockchain.eth.deployers.MultiSigDeployer'>)
ownable_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.StakingEscrowDeployer'>, <class 'nucypher.blockchain.eth.deployers.PolicyManagerDeployer'>, <class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>, <class 'nucypher.blockchain.eth.deployers.StakingInterfaceRouterDeployer'>)
primary_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.NucypherTokenDeployer'>, <class 'nucypher.blockchain.eth.deployers.StakingEscrowDeployer'>, <class 'nucypher.blockchain.eth.deployers.PolicyManagerDeployer'>, <class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>, <class 'nucypher.blockchain.eth.deployers.StakingInterfaceDeployer'>)
all_deployer_classes = (<class 'nucypher.blockchain.eth.deployers.NucypherTokenDeployer'>, <class 'nucypher.blockchain.eth.deployers.StakingEscrowDeployer'>, <class 'nucypher.blockchain.eth.deployers.PolicyManagerDeployer'>, <class 'nucypher.blockchain.eth.deployers.AdjudicatorDeployer'>, <class 'nucypher.blockchain.eth.deployers.StakingInterfaceDeployer'>, <class 'nucypher.blockchain.eth.deployers.WorklockDeployer'>, <class 'nucypher.blockchain.eth.deployers.MultiSigDeployer'>)
exception UnknownContract

Bases: ValueError

recruit_sidekick(sidekick_address: str, sidekick_password: str)
activate_deployer(refresh: bool = True)
activate_sidekick(refresh: bool = True)
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, ignore_deployed: bool = False)dict
retarget_proxy(contract_name: str, target_address: str, just_build_transaction: bool = False)
rollback_contract(contract_name: str)
deploy_network_contracts(interactive: bool = True, emitter: nucypher.characters.control.emitters.StdoutEmitter = None, etherscan: bool = False, ignore_deployed: bool = False)dict
Parameters
  • interactive – If True, wait for keypress after each contract deployment

  • emitter – A console output emitter instance. If emitter is None, no output will be echoed to the console.

  • etherscan – Open deployed contracts in Etherscan

  • ignore_deployed – Ignore already deployed contracts if exist

Returns

Returns a dictionary of deployment receipts keyed by contract name

batch_deposits(allocation_data_filepath: str, interactive: bool = True, emitter: nucypher.characters.control.emitters.StdoutEmitter = None, gas_limit: int = None) → Dict[str, dict]

The allocations file is a JSON or CSV file containing a list of substakes. Each substake is comprised of a staker address, an amount of tokens locked (in NuNits), and a lock duration (in periods).

It accepts both CSV and JSON formats. Example allocation file in CSV format:

“checksum_address”,”amount”,”lock_periods” “0xFABADA”,123456,30 “0xFABADA”,789,45

Example allocation file in JSON format:

[ {“checksum_address”: “0xFABADA”, “amount”: 123456, “lock_periods”: 30},

{“checksum_address”: “0xFABADA”, “amount”: 789, “lock_periods”: 45}]

save_deployment_receipts(receipts: dict, filename_prefix: str = 'deployment')str
set_fee_rate_range(minimum: int, default: int, maximum: int, transaction_gas_limit: int = None) → web3.types.TxReceipt
class Allocator(filepath: str, registry, deployer_address)

Bases: object

exception AllocationInputError

Bases: Exception

Raised when the allocation data file doesn’t have the correct format

OCCUPATION_RATIO = 0.9
deposit_next_batch(sender_address: str, gas_limit: int = None) → Tuple[List[str], dict]
property pending_deposits
class MultiSigActor(*args, **kwargs)

Bases: nucypher.blockchain.eth.actors.BaseActor

exception UnknownExecutive

Bases: Exception

Raised when Executive is not listed as a owner of the MultiSig.

class Trustee(checksum_address: str, client_password: str = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.actors.MultiSigActor

A member of a MultiSigBoard given the power and obligation to execute an authorized transaction on behalf of the board of executives.

exception NoAuthorizations

Bases: RuntimeError

Raised when there are zero authorizations.

add_authorization(authorization, proposal: nucypher.blockchain.eth.multisig.Proposal)str
execute(proposal: nucypher.blockchain.eth.multisig.Proposal)dict
create_transaction_proposal(transaction)
propose_adding_owner(new_owner_address: str, evidence: str)nucypher.blockchain.eth.multisig.Proposal
propose_removing_owner(owner_address: str)nucypher.blockchain.eth.multisig.Proposal
propose_changing_threshold(new_threshold: int)nucypher.blockchain.eth.multisig.Proposal
class Executive(checksum_address: str, signer: nucypher.blockchain.eth.signers.base.Signer = None, client_password: str = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.actors.MultiSigActor

An actor having the power to authorize transaction executions to a delegated trustee.

authorize_proposal(proposal)nucypher.blockchain.eth.multisig.Authorization
class Staker(is_me: bool, individual_allocation: nucypher.blockchain.eth.registry.IndividualAllocationRegistry = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.actors.NucypherTokenActor

Baseclass for staking-related operations on the blockchain.

exception StakerError

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

exception InsufficientTokens

Bases: nucypher.blockchain.eth.actors.Staker.StakerError

refresh_stakes()
property is_contract
to_dict()dict
property is_staking

Checks if this Staker currently has active stakes / locked tokens.

owned_tokens()nucypher.blockchain.eth.token.NU

Returns all tokens that belong to the staker, including locked, unlocked and rewards.

locked_tokens(periods: int = 0)nucypher.blockchain.eth.token.NU

Returns the amount of tokens this staker has locked for a given duration in periods.

property current_stake

The total number of staked tokens, i.e., tokens locked in the current period.

filtered_stakes(parent_status: nucypher.blockchain.eth.token.Stake.Status = None, filter_function: Callable[[nucypher.blockchain.eth.token.Stake], bool] = None) → Iterable[nucypher.blockchain.eth.token.Stake]

Returns stakes for this staker which filtered by status or by a provided function.

sorted_stakes(parent_status: nucypher.blockchain.eth.token.Stake.Status = None, filter_function: Callable[[nucypher.blockchain.eth.token.Stake], bool] = None) → List[nucypher.blockchain.eth.token.Stake]

Returns a list of filtered stakes sorted by account wallet index.

initialize_stake(amount: nucypher.blockchain.eth.token.NU = None, lock_periods: int = None, expiration: maya.core.MayaDT = None, entire_balance: bool = False, only_lock: bool = False) → web3.types.TxReceipt

Create a new stake.

divide_stake(stake: nucypher.blockchain.eth.token.Stake, target_value: nucypher.blockchain.eth.token.NU, additional_periods: int = None, expiration: maya.core.MayaDT = None) → web3.types.TxReceipt
increase_stake(stake: nucypher.blockchain.eth.token.Stake, amount: nucypher.blockchain.eth.token.NU = None, entire_balance: bool = False, only_lock: bool = False) → web3.types.TxReceipt

Add tokens to existing stake.

prolong_stake(stake: nucypher.blockchain.eth.token.Stake, additional_periods: int = None, expiration: maya.core.MayaDT = None) → web3.types.TxReceipt
merge_stakes(stake_1: nucypher.blockchain.eth.token.Stake, stake_2: nucypher.blockchain.eth.token.Stake) → web3.types.TxReceipt
property is_restaking
enable_restaking() → web3.types.TxReceipt
enable_restaking_lock(release_period: int) → web3.types.TxReceipt
property restaking_lock_enabled
property restake_unlock_period
disable_restaking() → web3.types.TxReceipt
property is_winding_down
enable_winding_down() → web3.types.TxReceipt
disable_winding_down() → web3.types.TxReceipt
property is_taking_snapshots
enable_snapshots() → web3.types.TxReceipt
disable_snapshots() → web3.types.TxReceipt
non_withdrawable_stake()nucypher.blockchain.eth.token.NU
property last_committed_period
mintable_periods()int

Returns number of periods that can be rewarded in the current period. Value in range [0, 2]

bond_worker(worker_address: str) → web3.types.TxReceipt
property worker_address
unbond_worker() → web3.types.TxReceipt
mint() → web3.types.TxReceipt

Computes and transfers tokens to the staker’s account

calculate_staking_reward()nucypher.blockchain.eth.token.NU
calculate_policy_fee()int
collect_policy_fee(collector_address=None) → web3.types.TxReceipt

Collect fees (ETH) earned since last withdrawal

collect_staking_reward() → web3.types.TxReceipt

Withdraw tokens rewarded for staking

withdraw(amount: nucypher.blockchain.eth.token.NU) → web3.types.TxReceipt

Withdraw tokens from StakingEscrow (assuming they’re unlocked)

withdraw_preallocation_tokens(amount: nucypher.blockchain.eth.token.NU) → web3.types.TxReceipt

Withdraw tokens from PreallocationEscrow (assuming they’re unlocked)

withdraw_preallocation_eth() → web3.types.TxReceipt

Withdraw ETH from PreallocationEscrow

property missing_commitments
set_min_fee_rate(min_rate: int) → web3.types.TxReceipt

Public facing method for staker to set the minimum acceptable fee rate for their associated worker

property min_fee_rate

Minimum fee rate that staker accepts

property raw_min_fee_rate

Minimum acceptable fee rate set by staker for their associated worker. This fee rate is only used if it falls within the global fee range. If it doesn’t a default fee rate is used instead of the raw value (see min_fee_rate)

class Worker(is_me: bool, work_tracker: nucypher.blockchain.eth.token.WorkTracker = None, worker_address: str = None, start_working_now: bool = True, block_until_ready: bool = True, *args, **kwargs)

Bases: nucypher.blockchain.eth.actors.NucypherTokenActor

Ursula baseclass for blockchain operations, practically carrying a pickaxe.

READY_TIMEOUT = None
READY_POLL_RATE = 10
READY_CLI_FEEDBACK_RATE = 60
exception WorkerError

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

exception UnbondedWorker

Bases: nucypher.blockchain.eth.actors.Worker.WorkerError

Raised when the Worker is not bonded to a Staker in the StakingEscrow contract.

crash_right_now = True
block_until_ready(poll_rate: int = None, timeout: int = None, feedback_rate: int = None)

Polls the staking_agent and blocks until the staking address is not a null address for the given worker_address. Once the worker is bonded, it returns the staker address.

property eth_balance

Return this workers’s current ETH balance

property token_balance

Return this worker’s current token balance. Note: Workers typically do not control any tokens.

property last_committed_period
commit_to_next_period(fire_and_forget: bool = True) → web3.types.TxReceipt

For each period that the worker makes a commitment, the staker is rewarded

property missing_commitments
class BlockchainPolicyAuthor(checksum_address: str, rate: int = None, duration_periods: int = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.actors.NucypherTokenActor

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

property default_rate
generate_policy_parameters(number_of_ursulas: int = None, duration_periods: int = None, expiration: maya.core.MayaDT = None, value: int = None, rate: int = None)dict

Construct policy creation from parameters or overrides.

get_stakers_reservoir(**options)nucypher.blockchain.eth.agents.StakersReservoir

Get a sampler object containing the currently registered stakers.

create_policy(*args, **kwargs)

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

Returns

Returns a newly authored BlockchainPolicy with n proposed arrangements.

class Investigator(checksum_address: str, *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)dict
class Wallet(client_addresses: set = None, provider_uri: str = None, signer=None)

Bases: object

Account management abstraction on top of blockchain providers and external signers

exception UnknownAccount

Bases: KeyError

property active_account
property accounts
activate_account(checksum_address: str, signer: Optional[nucypher.blockchain.eth.signers.base.Signer] = None, password: Optional[str] = None)None
eth_balance(account: str)int
token_balance(account: str, registry: nucypher.blockchain.eth.registry.BaseContractRegistry)int
class StakeHolder(is_me: bool = True, initial_address: str = None, checksum_addresses: set = None, signer: nucypher.blockchain.eth.signers.base.Signer = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.actors.Staker

banner = "\n ____ __ __ \n/\\ _`\\ /\\ \\__ /\\ \\ \n\\ \\,\\L\\_\\ \\ ,_\\ __ \\ \\ \\/'\\ __ _ __ \n \\/_\\__ \\\\ \\ \\/ /'__`\\\\ \\ , < /'__`\\/\\`'__\\\n /\\ \\L\\ \\ \\ \\_/\\ \\L\\.\\\\ \\ \\\\`\\ /\\ __/\\ \\ \\/ \n \\ `\\____\\ \\__\\ \\__/.\\_\\ \\_\\ \\_\\ \\____\\\\ \\_\\ \n \\/_____/\\/__/\\/__/\\/_/\\/_/\\/_/\\/____/ \\/_/ \n \nThe Holder of Stakes. \n"
set_staker(checksum_address: str)None
assimilate(checksum_address: str = None, password: str = None)None
get_staker(checksum_address: str)
get_stakers() → List[nucypher.blockchain.eth.actors.Staker]
property total_stake

The total number of staked tokens, either locked or unlocked in the current period.

class Bidder(checksum_address: str, transacting: bool = True, signer: nucypher.blockchain.eth.signers.base.Signer = None, client_password: str = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.actors.NucypherTokenActor

WorkLock participant

exception BidderError

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

exception BiddingIsOpen

Bases: nucypher.blockchain.eth.actors.Bidder.BidderError

exception BiddingIsClosed

Bases: nucypher.blockchain.eth.actors.Bidder.BidderError

exception CancellationWindowIsOpen

Bases: nucypher.blockchain.eth.actors.Bidder.BidderError

exception CancellationWindowIsClosed

Bases: nucypher.blockchain.eth.actors.Bidder.BidderError

exception ClaimError

Bases: nucypher.blockchain.eth.actors.Bidder.BidderError

exception WhaleError

Bases: nucypher.blockchain.eth.actors.Bidder.BidderError

ensure_bidding_is_open(message: str = None)None
place_bid(value: int) → web3.types.TxReceipt
claim() → web3.types.TxReceipt
cancel_bid() → web3.types.TxReceipt
get_whales(force_read: bool = False) → Dict[str, int]

Returns all worklock bidders over the whale threshold as a dictionary of addresses and bonus bid values.

force_refund() → web3.types.TxReceipt
verify_bidding_correctness(gas_limit: int)dict
refund_deposit()dict

Refund ethers for completed work

withdraw_compensation() → web3.types.TxReceipt

Withdraw compensation after force refund

property get_deposited_eth
property has_claimed
property completed_work
property remaining_work
property refunded_work
property available_refund
property available_compensation
property available_claim
class DaoActor(network: str, checksum_address: NewType.<locals>.new_type, registry=None, signer: nucypher.blockchain.eth.signers.base.Signer = None, client_password: str = None, transacting: bool = True)

Bases: nucypher.blockchain.eth.actors.BaseActor

Base class for actors that interact with the NuCypher DAO

class EmergencyResponseManager(**kwargs)

Bases: nucypher.blockchain.eth.actors.DaoActor

rotate_emergency_response_team(members_out: Iterable[NewType.<locals>.new_type], members_in: Iterable[NewType.<locals>.new_type])
class EthereumContractAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = 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, provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'NuCypherToken'
get_balance(address: Optional[NewType.<locals>.new_type] = None) → 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(sender_address: NewType.<locals>.new_type, 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

approve_transfer(amount: NewType.<locals>.new_type, spender_address: NewType.<locals>.new_type, sender_address: NewType.<locals>.new_type) → 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, sender_address: NewType.<locals>.new_type) → 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, sender_address: NewType.<locals>.new_type, call_data: bytes = b'', gas_limit: Optional[NewType.<locals>.new_type] = None) → web3.types.TxReceipt
class StakingEscrowAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'StakingEscrow'
DEFAULT_PAGINATION_SIZE: int = 30
exception NotEnoughStakers

Bases: Exception

Raised when the are not enough stakers available to complete an operation

get_staker_population()int

Returns the number of stakers on the blockchain

get_current_period() → NewType.<locals>.new_type

Returns the current period

get_stakers() → List[NewType.<locals>.new_type]

Returns a list of stakers

partition_stakers_by_activity() → Tuple[List[NewType.<locals>.new_type], List[NewType.<locals>.new_type], List[NewType.<locals>.new_type]]

Returns three lists of stakers depending on their commitments: The first list contains stakers that already committed to next period. The second, stakers that committed to current period but haven’t committed to next yet. The third contains stakers that have missed commitments before current period

get_all_active_stakers(periods: int, pagination_size: Optional[int] = None) → Tuple[NewType.<locals>.new_type, Dict[NewType.<locals>.new_type, NewType.<locals>.new_type]]

Only stakers which committed to the current period (in the previous period) are used.

get_all_locked_tokens(periods: int, pagination_size: Optional[int] = None) → NewType.<locals>.new_type
get_global_locked_tokens(at_period: Optional[NewType.<locals>.new_type] = None) → NewType.<locals>.new_type

Gets the number of locked tokens for all stakers that have made a commitment to the specified period.

at_period values can be any valid period number past, present, or future:

PAST - Calling this function with an at_period value in the past will return the number of locked tokens whose worker commitment was made to that past period.

PRESENT - This is the default value, when no at_period value is provided.

FUTURE - Calling this function with an at_period value greater than the current period + 1 (next period), will result in a zero return value because commitment cannot be made beyond the next period.

Returns an amount of NuNits.

get_staker_info(staker_address: NewType.<locals>.new_type) → nucypher.types.StakerInfo
get_locked_tokens(staker_address: NewType.<locals>.new_type, periods: int = 0) → NewType.<locals>.new_type

Returns the amount of tokens this staker has locked for a given duration in periods measured from the current period forwards.

owned_tokens(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type

Returns all tokens that belong to staker_address, including locked, unlocked and rewards.

get_substake_info(staker_address: NewType.<locals>.new_type, stake_index: int) → nucypher.types.SubStakeInfo
get_raw_substake_info(staker_address: NewType.<locals>.new_type, stake_index: int) → nucypher.types.RawSubStakeInfo
get_all_stakes(staker_address: NewType.<locals>.new_type) → Iterable[nucypher.types.SubStakeInfo]
deposit_tokens(staker_address: NewType.<locals>.new_type, amount: NewType.<locals>.new_type, lock_periods: NewType.<locals>.new_type, sender_address: Optional[NewType.<locals>.new_type] = None) → web3.types.TxReceipt

Send tokens to the escrow from the sender’s address to be locked on behalf of the staker address. If the sender address is not provided, the stakers address is used. Note that this resolved to two separate contract function signatures.

deposit_and_increase(staker_address: NewType.<locals>.new_type, amount: NewType.<locals>.new_type, stake_index: int) → web3.types.TxReceipt

Send tokens to the escrow from the sender’s address to be locked on behalf of the staker address. This method will add tokens to the selected sub-stake. Note that this resolved to two separate contract function signatures.

lock_and_create(staker_address: NewType.<locals>.new_type, amount: NewType.<locals>.new_type, lock_periods: NewType.<locals>.new_type) → web3.types.TxReceipt

Locks tokens amount and creates new sub-stake

lock_and_increase(staker_address: NewType.<locals>.new_type, amount: NewType.<locals>.new_type, stake_index: int) → web3.types.TxReceipt

Locks tokens amount and add them to selected sub-stake

construct_batch_deposit_parameters(deposits: Dict[NewType.<locals>.new_type, List[Tuple[int, int]]]) → Tuple[list, list, list, list]
batch_deposit(stakers: List[NewType.<locals>.new_type], number_of_substakes: List[int], amounts: List[NewType.<locals>.new_type], lock_periods: List[NewType.<locals>.new_type], sender_address: NewType.<locals>.new_type, dry_run: bool = False, gas_limit: Optional[NewType.<locals>.new_type] = None) → Union[web3.types.TxReceipt, NewType.<locals>.new_type]
divide_stake(staker_address: NewType.<locals>.new_type, stake_index: int, target_value: NewType.<locals>.new_type, periods: NewType.<locals>.new_type) → web3.types.TxReceipt
prolong_stake(staker_address: NewType.<locals>.new_type, stake_index: int, periods: NewType.<locals>.new_type) → web3.types.TxReceipt
merge_stakes(staker_address: NewType.<locals>.new_type, stake_index_1: int, stake_index_2: int) → web3.types.TxReceipt
get_current_committed_period(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_next_committed_period(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_last_committed_period(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_worker_from_staker(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_staker_from_worker(worker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
bond_worker(staker_address: NewType.<locals>.new_type, worker_address: NewType.<locals>.new_type) → web3.types.TxReceipt
release_worker(staker_address: NewType.<locals>.new_type) → web3.types.TxReceipt
commit_to_next_period(worker_address: NewType.<locals>.new_type, fire_and_forget: bool = True) → web3.types.TxReceipt

For each period that the worker makes a commitment, the staker is rewarded.

mint(staker_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Computes reward tokens for the staker’s account; This is only used to calculate the reward for the final period of a stake, when you intend to withdraw 100% of tokens.

non_withdrawable_stake(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type

Returns token amount that can not be withdrawn. Opposite method for calculate_staking_reward. Uses maximum of locked tokens in the current and next periods.

calculate_staking_reward(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
collect_staking_reward(staker_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Withdraw tokens rewarded for staking.

withdraw(staker_address: NewType.<locals>.new_type, amount: NewType.<locals>.new_type) → web3.types.TxReceipt

Withdraw tokens

get_flags(staker_address: NewType.<locals>.new_type) → nucypher.types.StakerFlags
is_restaking(staker_address: NewType.<locals>.new_type)bool
is_restaking_locked(staker_address: NewType.<locals>.new_type)bool
set_restaking(staker_address: NewType.<locals>.new_type, value: bool) → web3.types.TxReceipt

Enable automatic restaking for a fixed duration of lock periods. If set to True, then all staking rewards will be automatically added to locked stake.

lock_restaking(staker_address: NewType.<locals>.new_type, release_period: NewType.<locals>.new_type) → web3.types.TxReceipt
get_restake_unlock_period(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
is_winding_down(staker_address: NewType.<locals>.new_type)bool
set_winding_down(staker_address: NewType.<locals>.new_type, value: bool) → web3.types.TxReceipt

Enable wind down for stake. If set to True, then stakes duration will decrease in each period with commitToNextPeriod().

is_taking_snapshots(staker_address: NewType.<locals>.new_type)bool
set_snapshots(staker_address: NewType.<locals>.new_type, activate: bool) → web3.types.TxReceipt

Activate/deactivate taking balance snapshots. If set to True, then each time the balance changes, a snapshot associated to current block number is stored.

staking_parameters() → nucypher.types.StakingEscrowParameters
swarm() → Iterable[NewType.<locals>.new_type]

Returns an iterator of all staker addresses via cumulative sum, on-network. Staker addresses are returned in the order in which they registered with the StakingEscrow contract’s ledger

get_stakers_reservoir(duration: int, without: Iterable[NewType.<locals>.new_type] = [], pagination_size: Optional[int] = None)nucypher.blockchain.eth.agents.StakersReservoir
get_completed_work(bidder_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_missing_commitments(checksum_address: NewType.<locals>.new_type)int
property is_test_contract
property worklock
property adjudicator
property policy_manager
class PolicyManagerAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'PolicyManager'
create_policy(policy_id: str, author_address: NewType.<locals>.new_type, value: NewType.<locals>.new_type, end_timestamp: NewType.<locals>.new_type, node_addresses: List[NewType.<locals>.new_type], owner_address: Optional[NewType.<locals>.new_type] = None) → web3.types.TxReceipt
fetch_policy(policy_id: str)list

Fetch raw stored blockchain data regarding the policy with the given policy ID

fetch_arrangement_addresses_from_policy_txid(txhash: Union[str, bytes], timeout: int = 600) → Iterable
revoke_policy(policy_id: bytes, author_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Revoke by arrangement ID; Only the policy’s author_address can revoke the policy.

collect_policy_fee(collector_address: NewType.<locals>.new_type, staker_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Collect fees (ETH) earned since last withdrawal

fetch_policy_arrangements(policy_id: str) → Iterable[Tuple[NewType.<locals>.new_type, int, int]]
revoke_arrangement(policy_id: str, node_address: NewType.<locals>.new_type, author_address: NewType.<locals>.new_type) → web3.types.TxReceipt
calculate_refund(policy_id: str, author_address: NewType.<locals>.new_type) → web3.types.TxReceipt
collect_refund(policy_id: str, author_address: NewType.<locals>.new_type) → web3.types.TxReceipt
get_fee_amount(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_fee_rate_range() → Tuple[NewType.<locals>.new_type, NewType.<locals>.new_type, NewType.<locals>.new_type]

Check minimum, default & maximum fee rate for all policies (‘global fee range’)

get_min_fee_rate(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type

Check minimum fee rate that staker accepts

get_raw_min_fee_rate(staker_address: NewType.<locals>.new_type) → NewType.<locals>.new_type

Check minimum acceptable fee rate set by staker for their associated worker

set_min_fee_rate(staker_address: NewType.<locals>.new_type, min_rate: NewType.<locals>.new_type) → web3.types.TxReceipt
class PreallocationEscrowAgent(beneficiary: NewType.<locals>.new_type, registry: nucypher.blockchain.eth.registry.BaseContractRegistry, allocation_registry: Optional[nucypher.blockchain.eth.registry.AllocationRegistry] = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'PreallocationEscrow'
class StakingInterfaceAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'StakingInterface'
property owner
property beneficiary
property interface_contract
property principal_contract

Directly reference the beneficiary’s deployed contract instead of the interface contracts’s ABI

property initial_locked_amount
property available_balance
property unvested_tokens
property end_timestamp
lock(amount: NewType.<locals>.new_type, periods: NewType.<locals>.new_type) → web3.types.TxReceipt
withdraw_tokens(value: NewType.<locals>.new_type) → web3.types.TxReceipt
withdraw_eth() → web3.types.TxReceipt
deposit_as_staker(amount: NewType.<locals>.new_type, lock_periods: NewType.<locals>.new_type) → web3.types.TxReceipt
withdraw_as_staker(value: NewType.<locals>.new_type) → web3.types.TxReceipt
bond_worker(worker_address: NewType.<locals>.new_type) → web3.types.TxReceipt
release_worker() → web3.types.TxReceipt
mint() → web3.types.TxReceipt
collect_policy_fee() → web3.types.TxReceipt
set_min_fee_rate(min_rate: NewType.<locals>.new_type) → web3.types.TxReceipt
set_restaking(value: bool) → web3.types.TxReceipt

Enable automatic restaking for a fixed duration of lock periods. If set to True, then all staking rewards will be automatically added to locked stake.

lock_restaking(release_period: NewType.<locals>.new_type) → web3.types.TxReceipt
set_winding_down(value: bool) → web3.types.TxReceipt

Enable wind down for stake. If set to True, then the stake’s duration will decrease each period with commitToNextPeriod().

class AdjudicatorAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'Adjudicator'
evaluate_cfrag(evidence: Evidence, sender_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Submits proof that a worker created wrong CFrag

was_this_evidence_evaluated(evidence: 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 WorkLockAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'WorkLock'
bid(value: NewType.<locals>.new_type, checksum_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Bid for NU tokens with ETH.

cancel_bid(checksum_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Cancel bid and refund deposited ETH.

force_refund(checksum_address: NewType.<locals>.new_type, addresses: List[NewType.<locals>.new_type]) → web3.types.TxReceipt

Force refund to bidders who can get tokens more than maximum allowed.

verify_bidding_correctness(checksum_address: NewType.<locals>.new_type, gas_limit: NewType.<locals>.new_type, gas_to_save_state: NewType.<locals>.new_type = 30000) → web3.types.TxReceipt

Verify all bids are less than max allowed bid

claim(checksum_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Claim tokens - will be deposited and locked as stake in the StakingEscrow contract.

refund(checksum_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Refund ETH for completed work.

withdraw_compensation(checksum_address: NewType.<locals>.new_type) → web3.types.TxReceipt

Withdraw compensation after force refund.

check_claim(checksum_address: NewType.<locals>.new_type)bool
get_refunded_work(checksum_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_available_refund(checksum_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_available_compensation(checksum_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_deposited_eth(checksum_address: NewType.<locals>.new_type) → NewType.<locals>.new_type
property lot_value

Total number of tokens than can be bid for and awarded in or the number of NU tokens deposited before the bidding windows begins via tokenDeposit().

get_bonus_lot_value() → NewType.<locals>.new_type

Total number of tokens than can be awarded for bonus part of bid.

get_remaining_work(checksum_address: str) → NewType.<locals>.new_type

Get remaining work periods until full refund for the target address.

get_bonus_eth_supply() → NewType.<locals>.new_type
get_eth_supply() → NewType.<locals>.new_type
property boosting_refund
property slowing_refund
get_bonus_refund_rate()float
get_base_refund_rate()int
get_base_deposit_rate()int
get_bonus_deposit_rate()int
eth_to_tokens(value: NewType.<locals>.new_type) → NewType.<locals>.new_type
eth_to_work(value: NewType.<locals>.new_type) → NewType.<locals>.new_type
work_to_eth(value: NewType.<locals>.new_type) → NewType.<locals>.new_type
get_bidders_population()int

Returns the number of bidders on the blockchain

get_bidders() → List[NewType.<locals>.new_type]

Returns a list of bidders

is_claiming_available()bool

Returns True if claiming is available

estimate_verifying_correctness(gas_limit: NewType.<locals>.new_type, gas_to_save_state: NewType.<locals>.new_type = 30000)int

Returns how many bidders will be verified using specified gas limit

next_bidder_to_check()int

Returns the index of the next bidder to check as part of the bids verification process

bidders_checked()bool

Returns True if bidders have been checked

property minimum_allowed_bid
property start_bidding_date
property end_bidding_date
property end_cancellation_date
worklock_parameters() → nucypher.types.WorklockParameters
class MultiSigAgent(registry: nucypher.blockchain.eth.registry.BaseContractRegistry = None, provider_uri: Optional[str] = None, contract: Optional[web3.contract.Contract] = None, transaction_gas: Optional[NewType.<locals>.new_type] = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

contract_name: str = 'MultiSig'
property nonce
get_owner(index: int) → NewType.<locals>.new_type
property number_of_owners
property owners
property threshold
is_owner(checksum_address: NewType.<locals>.new_type)bool
build_add_owner_tx(new_owner_address: NewType.<locals>.new_type) → web3.types.TxParams
build_remove_owner_tx(owner_address: NewType.<locals>.new_type) → web3.types.TxParams
build_change_threshold_tx(threshold: int) → web3.types.TxParams
get_unsigned_transaction_hash(trustee_address: NewType.<locals>.new_type, target_address: NewType.<locals>.new_type, value: NewType.<locals>.new_type, data: bytes, nonce: NewType.<locals>.new_type) → hexbytes.main.HexBytes
execute(v: List[str], r: List[str], s: List[str], destination: NewType.<locals>.new_type, value: NewType.<locals>.new_type, data: Union[bytes, NewType.<locals>.new_type], sender_address: NewType.<locals>.new_type) → web3.types.TxReceipt
class InstanceAgent(address: str, abi: List[Dict] = None, provider_uri: str = None)

Bases: nucypher.blockchain.eth.agents.EthereumContractAgent

Base class for agents that interact with contracts instantiated by address

class AragonAgent(address: str, provider_uri: str = None)

Bases: nucypher.blockchain.eth.agents.InstanceAgent

Base agent for Aragon contracts that uses ABIs from artifact.json files

class ForwarderAgent(address: str, provider_uri: str = None)

Bases: nucypher.blockchain.eth.agents.AragonAgent

Agent for Aragon apps that implement the Forwarder interface

contract_name: str = 'IForwarder'
forward(callscript: bytes, sender_address: NewType.<locals>.new_type) → web3.types.TxReceipt
class VotingAgent(address: str, provider_uri: str = None)

Bases: nucypher.blockchain.eth.agents.ForwarderAgent

Agent to interact with Aragon’s Voting apps

contract_name: str = 'Voting'
new_vote(callscript: bytes, metadata: str, sender_address: NewType.<locals>.new_type, cast_vote: bool = None, execute_if_decided: bool = None) → web3.types.TxReceipt
vote(vote_id: int, support_proposal: bool, execute_if_decided: bool, sender_address: NewType.<locals>.new_type)
class VotingAggregatorAgent(address: str, provider_uri: str = None)

Bases: nucypher.blockchain.eth.agents.ForwarderAgent

Agent to interact with Aragon’s Voting Aggregator app

contract_name: str = 'VotingAggregator'
class TokenManagerAgent(address: str, provider_uri: str = None)

Bases: nucypher.blockchain.eth.agents.ForwarderAgent

contract_name: str = 'TokenManager'
class ContractAgency

Bases: object

Where agents live and die.

classmethod get_agent(agent_class: Type[Agent], registry: Optional[nucypher.blockchain.eth.registry.BaseContractRegistry] = None, provider_uri: Optional[str] = None) → Agent
classmethod get_agent_by_contract_name(contract_name: str, registry: nucypher.blockchain.eth.registry.BaseContractRegistry, provider_uri: 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 probablity 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 StakersReservoir(stakers_map: Dict[NewType.<locals>.new_type, int])

Bases: object

draw(quantity)
draw_at_most(quantity)
class Action

Bases: tuple

An action is the conjunction of a smart contract address and a call to one of its methods

property target

Alias for field number 0

property data

Alias for field number 1

class CallScriptCodec

Bases: object

Utility class to facilitate encoding ‘actions’ (i.e, calls to smart contracts) as per the CallScript format used by Aragon contracts.

CALLSCRIPT_ID = b'\x00\x00\x00\x01'
classmethod encode_actions(actions: Iterable[nucypher.blockchain.eth.aragon.Action])bytes
class Artifact(name: str)

Bases: object

A helper class to extract data from Aragon’s Artifacts, which contain metadata about Aragon’s apps.

ARTIFACTS_DIRECTORY = PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/nucypher/envs/latest/lib/python3.7/site-packages/nucypher/blockchain/eth/aragon_artifacts')
property abi
class DAORegistry(network: str)

Bases: object

A simple registry to store the addresses and types of NuCypher DAO instances. An instance is a particular specimen of an Aragon App. An Aragon App may have several instances in the NuCypher DAO (e.g., there are two instances of the Voting app)

class Instance(name, app_name, address)

Bases: tuple

property address

Alias for field number 2

property app_name

Alias for field number 1

property name

Alias for field number 0

exception InstanceNotInRegistry

Bases: RuntimeError

Raised when a instance is not found in the NuCypher DAO registry

classmethod get_filepath(network: str)
get_instance(instance_name: str)
get_address_of(instance_name: str) → NewType.<locals>.new_type
get_app_name_of(instance_name: str)str
get_instance_name_by_address(address: NewType.<locals>.new_type)str
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'
PARITY = 'Parity'
ALT_PARITY = 'Parity-Ethereum'
GANACHE = 'EthereumJS TestRPC'
ETHEREUM_TESTER = 'EthereumTester'
CLEF = 'Clef'
PEERING_TIMEOUT = 30
SYNC_TIMEOUT_DURATION = 60
SYNC_SLEEP_DURATION = 5
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’

property peers
property chain_name
property syncing
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
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()
sync(timeout: int = 120, quiet: bool = False)
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 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
sync(*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
sync(*args, **kwargs)bool
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 keyring has control of the given address.

lock_account(account)bool

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

sync(*args, **kwargs)
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)
class NuCypherGethProcess(geth_kwargs: dict, stdout_logfile_path: str = "/home/docs/.cache/nucypher/log/<Logger 'nucypher-geth'>.log", stderr_logfile_path: str = "/home/docs/.cache/nucypher/log/<Logger 'nucypher-geth'>.log", *args, **kwargs)

Bases: geth.mixins.LoggingMixin, geth.process.BaseGethProcess

IPC_PROTOCOL = 'http'
IPC_FILENAME = 'geth.ipc'
VERBOSITY = 5
CHAIN_ID = NotImplemented
LOG

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

LOG_PATH = "/home/docs/.cache/nucypher/log/<Logger 'nucypher-geth'>.log"
provider_uri(scheme: str = None)str
start(timeout: int = 30, extra_delay: int = 1)
ensure_account_exists(password: str)str
class NuCypherGethDevProcess(config_root: str = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.clients.NuCypherGethProcess

start(timeout: int = 30, extra_delay: int = 1)
class NuCypherGethDevnetProcess(config_root: str = None, overrides: dict = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.clients.NuCypherGethProcess

IPC_PROTOCOL = 'file'
GENESIS_FILENAME = 'testnet_genesis.json'
GENESIS_SOURCE_FILEPATH = '/home/docs/checkouts/readthedocs.org/user_builds/nucypher/envs/latest/lib/python3.7/site-packages/deploy/testnet_genesis.json'
P2P_PORT = 30303
initialize_blockchain(overwrite: bool = True)None
class NuCypherGethGoerliProcess(config_root: str = None, overrides: dict = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.clients.NuCypherGethProcess

IPC_PROTOCOL = 'file'
GENESIS_FILENAME = 'testnet_genesis.json'
GENESIS_SOURCE_FILEPATH = '/home/docs/checkouts/readthedocs.org/user_builds/nucypher/envs/latest/lib/python3.7/site-packages/deploy/testnet_genesis.json'
P2P_PORT = 30303
CHAIN_ID = 5
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.BaseEconomics = None, deployer_address: str = 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 deployer_address
property contract
property dispatcher
is_deployed(contract_version: str = None)bool
check_deployment_readiness(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(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

transfer_ownership(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(target_address: str, 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(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(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.BaseEconomics = None, deployer_address: str = None)

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer

agency

alias of nucypher.blockchain.eth.agents.NucypherTokenAgent

contract_name = 'NuCypherToken'
deployment_steps = ('contract_deployment',)
deploy(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(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(new_target: str, gas_limit: int = None)dict
build_retarget_transaction(new_target: str, gas_limit: int = None)dict
rollback(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(test_mode: bool = False, *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

alias of nucypher.blockchain.eth.agents.StakingEscrowAgent

contract_name = 'StakingEscrow'
can_be_idle = True
preparation_steps = ('contract_deployment', 'dispatcher_deployment')
activation_steps = ('approve_reward_transfer', 'initialize')
deployment_steps = ('contract_deployment', 'dispatcher_deployment', 'approve_reward_transfer', 'initialize')
deploy(deployment_mode=FULL, 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.

activate(gas_limit: int = None, progress=None, emitter=None, confirmations: int = 0)
property ready_to_activate
property is_active
class PolicyManagerDeployer(*args, **kwargs)

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

Depends on StakingEscrow and NucypherTokenAgent

agency

alias of nucypher.blockchain.eth.agents.PolicyManagerAgent

contract_name = 'PolicyManager'
deployment_steps = ('deployment', 'dispatcher_deployment', 'set_policy_manager')
check_deployment_readiness(*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(deployment_mode=FULL, gas_limit: int = None, progress=None, contract_version: str = 'latest', ignore_deployed: bool = False, confirmations: int = 0, emitter=None) → Dict[str, dict]

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

set_fee_rate_range(minimum: int, default: int, maximum: int, gas_limit: int = None, confirmations: int = 0)dict
class StakingInterfaceRouterDeployer(target_contract: web3.contract.Contract, bare: bool = False, *args, **kwargs)

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

contract_name = 'StakingInterfaceRouter'
rollback(gas_limit: int = None)dict
class StakingInterfaceDeployer(*args, **kwargs)

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

contract_name = 'StakingInterface'
deployment_steps = ('contract_deployment', 'router_deployment')
number_of_deployment_transactions = 2
deploy(deployment_mode=FULL, gas_limit: int = None, progress=None, contract_version: str = 'latest', ignore_deployed: bool = False, confirmations: int = 0, emitter=None)dict

Deploys a new StakingInterface contract, and a new StakingInterfaceRouter, targeting the former. This is meant to be called only once per general deployment.

class PreallocationEscrowDeployer(allocation_registry: nucypher.blockchain.eth.registry.AllocationRegistry = None, sidekick_address: str = None, *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.PreallocationEscrowAgent

contract_name = 'PreallocationEscrow'
deployment_steps = ('contract_deployment', 'transfer_ownership', 'initial_deposit')
make_agent()nucypher.blockchain.eth.agents.PreallocationEscrowAgent
property allocation_registry
assign_beneficiary(checksum_address: str, use_sidekick: bool = False, progress=None)dict

Relinquish ownership of a PreallocationEscrow deployment to the beneficiary

initial_deposit(value: int, duration_seconds: int, progress=None)

Allocate an amount of tokens with lock time in seconds

enroll_principal_contract()
deploy(gas_limit: int = None, use_sidekick: bool = False, progress=None, ignore_deployed: bool = False, emitter=None)dict

Deploy a new instance of PreallocationEscrow to the blockchain.

get_contract_abi()
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', 'set_adjudicator')
check_deployment_readiness(*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(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 WorklockDeployer(*args, **kwargs)

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer

agency

alias of nucypher.blockchain.eth.agents.WorkLockAgent

contract_name = 'WorkLock'
deployment_steps = ('contract_deployment', 'bond_escrow', 'approve_funding', 'fund_worklock')
deploy(gas_limit: int = None, progress=None, confirmations: int = 0, deployment_mode=FULL, ignore_deployed: bool = False, emitter=None) → Dict[str, dict]

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

fund(sender_address: str, progress=None, confirmations: int = 0, emitter=None) → Tuple[dict, dict]

Convenience method for funding the contract and establishing the total worklock lot value to be auctioned.

class MultiSigDeployer(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, economics: nucypher.blockchain.economics.BaseEconomics = None, deployer_address: str = None)

Bases: nucypher.blockchain.eth.deployers.BaseContractDeployer

agency

alias of nucypher.blockchain.eth.agents.MultiSigAgent

contract_name = 'MultiSig'
deployment_steps = ('contract_deployment',)
MAX_OWNER_COUNT = 50
deploy(deployment_mode=FULL, gas_limit: int = None, progress=None, ignore_deployed: bool = False, emitter=None, *args, **kwargs)dict

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, provider_process=NO_PROVIDER_PROCESS, provider_uri: str = NO_BLOCKCHAIN_CONNECTION, provider: Union[web3.providers.ipc.IPCProvider, web3.providers.websocket.WebsocketProvider, web3.providers.rpc.HTTPProvider, eth_tester.main.EthereumTester] = NO_BLOCKCHAIN_CONNECTION, gas_strategy: Union[str, Callable] = 'fast')

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 construct_time_based_gas_price_strategy.<locals>.time_based_gas_price_strategy>, 'glacial': <function construct_time_based_gas_price_strategy.<locals>.time_based_gas_price_strategy>, 'medium': <function construct_time_based_gas_price_strategy.<locals>.time_based_gas_price_strategy>, 'slow': <function construct_time_based_gas_price_strategy.<locals>.time_based_gas_price_strategy>}
process = NO_PROVIDER_PROCESS (b'I\x14b\x8c\xff\t\xb8\xa1')
class Web3(provider: Optional[web3.providers.base.BaseProvider] = None, middlewares: Optional[Sequence[Any]] = None, modules: Optional[Dict[str, Sequence[Any]]] = None, ens: ens.main.ENS = <web3._utils.empty.Empty object>)

Bases: object

class EthereumTesterProvider(ethereum_tester: Optional[EthereumTester] = 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) → 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.

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) → 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
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

Checks if the given string in a supported value is 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: AnyStr) → 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
classmethod from_dict(payload: dict, **overrides)nucypher.blockchain.eth.interfaces.BlockchainInterface
to_dict()dict
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()
connect()
sync(emitter=None)None
property provider
build_payload(sender_address: str, payload: dict = None, transaction_gas_limit: int = None)dict
build_contract_transaction(contract_function: web3.contract.ContractFunction, sender_address: str, payload: dict = None, transaction_gas_limit: int = None)dict
sign_and_broadcast_transaction(transaction_dict, 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.

get_blocktime()
send_transaction(contract_function: Union[web3.contract.ContractFunction, web3.contract.ContractConstructor], sender_address: str, payload: dict = None, transaction_gas_limit: int = None, confirmations: int = 0, fire_and_forget: bool = False)dict
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(compiler: nucypher.blockchain.eth.sol.compile.SolidityCompiler = None, ignore_solidity_check: bool = False, dry_run: bool = False, *args, **kwargs)

Bases: nucypher.blockchain.eth.interfaces.BlockchainInterface

TIMEOUT = 600
exception NoDeployerAddress

Bases: RuntimeError

exception DeploymentFailed

Bases: RuntimeError

connect()
deploy_contract(deployer_address: str, 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, sync, emitter)

Bases: tuple

property interface

Alias for field number 0

property sync

Alias for field number 1

property emitter

Alias for field number 2

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(provider_uri: str)bool

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

classmethod register_interface(interface: nucypher.blockchain.eth.interfaces.BlockchainInterface, sync: bool = False, emitter=None, force: bool = False)None
classmethod initialize_interface(provider_uri: str, sync: bool = False, emitter=None, interface_class: Union[nucypher.blockchain.eth.interfaces.BlockchainInterface, nucypher.blockchain.eth.interfaces.BlockchainDeployerInterface] = None, *interface_args, **interface_kwargs)None
classmethod get_interface(provider_uri: str = None) → Union[nucypher.blockchain.eth.interfaces.BlockchainInterface, nucypher.blockchain.eth.interfaces.BlockchainDeployerInterface]
classmethod get_or_create_interface(provider_uri: str, *interface_args, **interface_kwargs)nucypher.blockchain.eth.interfaces.BlockchainInterface
class Proposal(trustee_address, target_address, value, data, nonce, digest)

Bases: object

classmethod from_transaction(transaction, multisig_agent, trustee_address: str)
property application_specific_data

In EIP191 version 0 signatures, data to be signed follows the following format:

0x19 + 0x00 + validator_address + application_specific_data

In the context of our MultiSig (which is the “validator”), the application specific data is the concatenation of:
  • Trustee address (actual sender of the TX)

  • Target address

  • Value included in the transaction (in wei)

  • Transaction data (e.g., an encoded call to a contract function)

  • MultiSig nonce

decode_transaction_data(contract: web3.contract.Contract = None, registry=None) → Tuple[web3.contract.ContractFunction, Dict[str, Any]]
write(filepath: str = None)str
classmethod from_file(filepath: str = None)nucypher.blockchain.eth.multisig.Proposal
class Authorization(r, s, v)

Bases: object

An edict issued by an Executive authorizing the execution of a multisig transaction by the delegated trustee.

class SignatureComponents(r, s, v)

Bases: tuple

property r

Alias for field number 0

property s

Alias for field number 1

property v

Alias for field number 2

splitter = <bytestring_splitter.BytestringSplitter object>
recover_executive_address(proposal: nucypher.blockchain.eth.multisig.Proposal)str
serialize()bytes
classmethod deserialize(data: bytes)nucypher.blockchain.eth.multisig.Authorization
classmethod from_hex(hexstr: str)nucypher.blockchain.eth.multisig.Authorization
classmethod from_file(filepath: str)nucypher.blockchain.eth.multisig.Authorization
class NetworksInventory

Bases: object

MAINNET = 'mainnet'
IBEX = 'ibex'
UNKNOWN = 'unknown'
DEFAULT = 'mainnet'
NETWORKS = ('mainnet', 'ibex')
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()str
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 = 'mainnet')

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: str, *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)str

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: str = None, overwrite: bool = False)str

writes the current state of the registry to a file

class AllocationRegistry(filepath: str = None, *args, **kwargs)

Bases: nucypher.blockchain.eth.registry.LocalContractRegistry

REGISTRY_TYPE = 'allocation'
REGISTRY_NAME = 'allocation_registry.json'
exception NoAllocationRegistry

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

exception AllocationEnrollmentError

Bases: RuntimeError

exception UnknownBeneficiary

Bases: ValueError

search(beneficiary_address: str = None, contract_address: str = None)

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

is_beneficiary_enrolled(beneficiary_address: str)bool
enroll(beneficiary_address, contract_address, contract_abi)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.

class InMemoryAllocationRegistry(*args, **kwargs)

Bases: nucypher.blockchain.eth.registry.AllocationRegistry

clear()
write(registry_data: 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.

read()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.

class IndividualAllocationRegistry(beneficiary_address: str, contract_address: str, contract_abi=None, network: str = 'mainnet', *args, **kwargs)

Bases: nucypher.blockchain.eth.registry.InMemoryAllocationRegistry

REGISTRY_NAME = 'individual_allocation_ABI.json'
classmethod from_allocation_file(filepath: str, **kwargs)nucypher.blockchain.eth.registry.IndividualAllocationRegistry
class NU(value: Union[int, float, str], denomination: str)

Bases: object

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

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

Int: nu = NU(100, ‘NU’) Int: nu_wei = NU(15000000000000000000000, ‘NuNit’)

Float: nu = NU(15042.445, ‘NU’) String: nu = NU(‘10002.302’, ‘NU’)

…or alternately…

Float: nu = NU.from_tokens(100.50) Int: nu_wei = NU.from_nu_wei(15000000000000000000000)

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

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.NU
classmethod from_nunits(value: int)nucypher.blockchain.eth.token.NU
classmethod from_tokens(value: Union[int, float, str])nucypher.blockchain.eth.token.NU
to_tokens()decimal.Decimal

Returns a decimal value of NU

to_nunits() → NewType.<locals>.new_type

Returns an int value in NuNit

class Stake(staking_agent: nucypher.blockchain.eth.agents.StakingEscrowAgent, checksum_address: str, value: nucypher.blockchain.eth.token.NU, first_locked_period: int, final_locked_period: int, index: int, economics)

Bases: object

A quantity of tokens and staking duration in periods for one stake for one staker.

exception StakingError

Bases: Exception

Raised when a staking operation cannot be executed due to failure.

class Status

Bases: enum.Enum

Sub-stake status.

INACTIVE = 1
UNLOCKED = 2
LOCKED = 3
EDITABLE = 4
DIVISIBLE = 5
is_child(other: Status)bool
property address_index_ordering_key

To be used as a lexicographical order key for Stakes based on the tuple (staker_address, index).

status(staker_info: nucypher.types.StakerInfo = None, current_period: NewType.<locals>.new_type = None)nucypher.blockchain.eth.token.Stake.Status

Returns status of sub-stake: UNLOCKED - final period in the past INACTIVE - UNLOCKED and sub-stake will not be included in any future calculations LOCKED - sub-stake is still locked and final period is current period EDITABLE - LOCKED and final period greater than current DIVISIBLE - EDITABLE and locked value is greater than two times the minimum allowed locked

classmethod from_stake_info(checksum_address: str, index: int, stake_info: nucypher.types.SubStakeInfo, economics, *args, **kwargs)nucypher.blockchain.eth.token.Stake

Reads staking values as they exist on the blockchain

to_stake_info() → nucypher.types.SubStakeInfo

Returns a tuple representing the blockchain record of a stake

property duration

Return stake duration in periods

property periods_remaining

Returns the number of periods remaining in the stake from now.

time_remaining(slang: bool = False) → Union[int, str]

Returns the time delta remaining in the stake from now. This method is designed for UI usage.

describe() → Dict[str, str]
sync()None

Update this stakes attributes with on-chain values.

classmethod initialize_stake(staking_agent, economics, checksum_address: str, amount: nucypher.blockchain.eth.token.NU, lock_periods: int)nucypher.blockchain.eth.token.Stake
validate_value(stake: nucypher.blockchain.eth.token.Stake)None

Validate a single staking value against pre-defined requirements

validate_duration(stake: nucypher.blockchain.eth.token.Stake)None

Validate a single staking lock-time against pre-defined requirements

validate_divide(stake: nucypher.blockchain.eth.token.Stake, target_value: nucypher.blockchain.eth.token.NU, additional_periods: int = None)None

Validates possibility to divide specified stake into two stakes using provided parameters.

validate_max_value(stake: nucypher.blockchain.eth.token.Stake, amount: nucypher.blockchain.eth.token.NU = None)None
validate_prolong(stake: nucypher.blockchain.eth.token.Stake, additional_periods: int)None
validate_merge(stake_1: nucypher.blockchain.eth.token.Stake, stake_2: nucypher.blockchain.eth.token.Stake)None
validate_increase(stake: nucypher.blockchain.eth.token.Stake, amount: nucypher.blockchain.eth.token.NU)None
class WorkTracker(worker, refresh_rate: int = None, *args, **kwargs)

Bases: object

CLOCK = <twisted.internet.epollreactor.EPollReactor object>
REFRESH_RATE = 900
property current_period
stop()None
start(act_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
class StakeList(registry: nucypher.blockchain.eth.registry.BaseContractRegistry, checksum_address: str = None, *args, **kwargs)

Bases: collections.UserList

property updated
property initial_period
property terminal_period
refresh()None

Public staking cache invalidation method

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
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