コード例 #1
0
def three_agents(testerchain):
    """
    Musketeers, if you will.
    Launch the big three contracts on provided chain,
    make agents for each and return them.
    """

    """Launch all Nucypher ethereum contracts"""
    origin, *everybody_else = testerchain.interface.w3.eth.accounts

    token_deployer = NucypherTokenDeployer(blockchain=testerchain, deployer_address=origin)

    token_deployer.deploy()

    token_agent = token_deployer.make_agent()  # 1: Token

    miners_escrow_secret = os.urandom(DISPATCHER_SECRET_LENGTH)
    miner_escrow_deployer = MinerEscrowDeployer(
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.keccak(miners_escrow_secret))

    miner_escrow_deployer.deploy()

    miner_agent = miner_escrow_deployer.make_agent()  # 2 Miner Escrow

    policy_manager_secret = os.urandom(DISPATCHER_SECRET_LENGTH)
    policy_manager_deployer = PolicyManagerDeployer(
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.keccak(policy_manager_secret))

    policy_manager_deployer.deploy()

    policy_agent = policy_manager_deployer.make_agent()  # 3 Policy Agent

    return token_agent, miner_agent, policy_agent
コード例 #2
0
def test_token_deployer_and_agent(testerchain):
    origin = testerchain.etherbase_account

    # Trying to get token from blockchain before it's been published fails
    with pytest.raises(EthereumContractRegistry.UnknownContract):
        NucypherTokenAgent(blockchain=testerchain)

    # The big day...
    deployer = NucypherTokenDeployer(blockchain=testerchain, deployer_address=origin)

    deployment_txhashes = deployer.deploy()

    for title, txhash in deployment_txhashes.items():
        receipt = testerchain.wait_for_receipt(txhash=txhash)
        assert receipt['status'] == 1, "Transaction Rejected {}:{}".format(title, txhash)

    # Create a token instance
    token_agent = deployer.make_agent()
    token_contract = token_agent.contract

    expected_token_supply = token_contract.functions.totalSupply().call()
    assert expected_token_supply == token_agent.contract.functions.totalSupply().call()

    # Retrieve the token from the blockchain
    same_token_agent = NucypherTokenAgent(blockchain=testerchain)

    # Compare the contract address for equality
    assert token_agent.contract_address == same_token_agent.contract_address
    assert token_agent == same_token_agent  # __eq__

    testerchain.registry.clear()
コード例 #3
0
ファイル: actors.py プロジェクト: mallek/nucypher
    def deploy_token_contract(self):

        token_deployer = NucypherTokenDeployer(blockchain=self.blockchain, deployer_address=self.deployer_address)

        txhashes = token_deployer.deploy()
        self.token_agent = token_deployer.make_agent()
        return txhashes
コード例 #4
0
def three_agents(testerchain):
    """
    Musketeers, if you will.
    Launch the big three contracts on provided chain,
    make agents for each and return them.
    """
    """Launch all Nucypher ethereum contracts"""
    origin = testerchain.etherbase_account

    token_deployer = NucypherTokenDeployer(blockchain=testerchain,
                                           deployer_address=origin)
    token_deployer.deploy()

    miner_escrow_deployer = MinerEscrowDeployer(deployer_address=origin)
    miner_escrow_deployer.deploy(
        secret_hash=os.urandom(DispatcherDeployer.DISPATCHER_SECRET_LENGTH))

    policy_manager_deployer = PolicyManagerDeployer(deployer_address=origin)
    policy_manager_deployer.deploy(
        secret_hash=os.urandom(DispatcherDeployer.DISPATCHER_SECRET_LENGTH))

    token_agent = token_deployer.make_agent()  # 1: Token
    miner_agent = miner_escrow_deployer.make_agent()  # 2 Miner Escrow
    policy_agent = policy_manager_deployer.make_agent()  # 3 Policy Agent

    adjudicator_deployer = MiningAdjudicatorDeployer(deployer_address=origin)
    adjudicator_deployer.deploy(
        secret_hash=os.urandom(DispatcherDeployer.DISPATCHER_SECRET_LENGTH))

    yield token_agent, miner_agent, policy_agent
    Agency.clear()
コード例 #5
0
def agent(testerchain, test_registry):
    origin, *everybody_else = testerchain.client.accounts
    token_deployer = NucypherTokenDeployer(registry=test_registry, deployer_address=origin)

    token_deployer.deploy()
    token_agent = token_deployer.make_agent()
    return token_agent
コード例 #6
0
def agent(testerchain):
    origin, *everybody_else = testerchain.interface.w3.eth.accounts
    token_deployer = NucypherTokenDeployer(blockchain=testerchain, deployer_address=origin)

    token_deployer.deploy()
    token_agent = token_deployer.make_agent()
    return token_agent
コード例 #7
0
ファイル: test_deployers.py プロジェクト: ngocson2vn/nucypher
def test_token_deployer_and_agent(testerchain):
    origin, *everybody_else = testerchain.interface.w3.eth.accounts

    # Trying to get token from blockchain before it's been published fails
    with pytest.raises(EthereumContractRegistry.UnknownContract):
        NucypherTokenAgent(blockchain=testerchain)

    # The big day...
    deployer = NucypherTokenDeployer(blockchain=testerchain,
                                     deployer_address=origin)

    # It's not armed
    with pytest.raises(NucypherTokenDeployer.ContractDeploymentError):
        deployer.deploy()

    # Token must be armed before deploying to the blockchain
    deployer.arm()
    deployer.deploy()

    # Create a token instance
    token_agent = deployer.make_agent()
    token_contract = testerchain.get_contract(token_agent.contract_name)

    expected_token_supply = token_contract.functions.totalSupply().call()
    assert expected_token_supply == token_agent.contract.functions.totalSupply(
    ).call()

    # Retrieve the token from the blockchain
    same_token_agent = NucypherTokenAgent(blockchain=testerchain)

    # Compare the contract address for equality
    assert token_agent.contract_address == same_token_agent.contract_address
    assert token_agent == same_token_agent  # __eq__

    testerchain.interface._registry.clear()
コード例 #8
0
ファイル: fixtures.py プロジェクト: raccoonrat/nucypher
def three_agents(testerchain):
    """
    Musketeers, if you will.
    Launch the big three contracts on provided chain,
    make agents for each and return them.
    """
    """Launch all Nucypher ethereum contracts"""
    origin, *everybody_else = testerchain.interface.w3.eth.accounts

    token_deployer = NucypherTokenDeployer(blockchain=testerchain,
                                           deployer_address=origin)
    token_deployer.arm()
    token_deployer.deploy()

    token_agent = token_deployer.make_agent()

    miner_escrow_deployer = MinerEscrowDeployer(token_agent=token_agent,
                                                deployer_address=origin)
    miner_escrow_deployer.arm()
    miner_escrow_deployer.deploy()

    miner_agent = miner_escrow_deployer.make_agent()

    policy_manager_deployer = PolicyManagerDeployer(miner_agent=miner_agent,
                                                    deployer_address=origin)
    policy_manager_deployer.arm()
    policy_manager_deployer.deploy()

    policy_agent = policy_manager_deployer.make_agent()

    return token_agent, miner_agent, policy_agent
コード例 #9
0
def test_token_deployer_and_agent(testerchain, deployment_progress,
                                  test_registry):
    testerchain = testerchain
    origin = testerchain.etherbase_account

    # Trying to get token from blockchain before it's been published fails
    with pytest.raises(BaseContractRegistry.UnknownContract):
        NucypherTokenAgent(registry=test_registry)

    # The big day...
    deployer = NucypherTokenDeployer(registry=test_registry,
                                     deployer_address=origin)

    deployment_receipts = deployer.deploy(progress=deployment_progress)

    for title, receipt in deployment_receipts.items():
        assert receipt['status'] == 1

    # deployment steps must match expected number of steps
    assert deployment_progress.num_steps == len(deployer.deployment_steps) == 1

    # Create a token instance
    token_agent = deployer.make_agent()
    token_contract = token_agent.contract

    expected_token_supply = token_contract.functions.totalSupply().call()
    assert expected_token_supply == token_agent.contract.functions.totalSupply(
    ).call()

    # Retrieve the token from the blockchain
    same_token_agent = NucypherTokenAgent(registry=test_registry)

    # Compare the contract address for equality
    assert token_agent.contract_address == same_token_agent.contract_address
    assert token_agent == same_token_agent  # __eq__
コード例 #10
0
ファイル: test_token_agent.py プロジェクト: KPrasch/nucypher
def agent(testerchain, test_registry) -> NucypherTokenAgent:
    origin, *everybody_else = testerchain.client.accounts
    token_deployer = NucypherTokenDeployer(registry=test_registry)
    tpower = TransactingPower(account=origin, signer=Web3Signer(testerchain.client))

    token_deployer.deploy(transacting_power=tpower)
    token_agent = token_deployer.make_agent()
    return token_agent
コード例 #11
0
ファイル: fixtures.py プロジェクト: gs455/nucypher
def _make_agency(testerchain, test_registry):
    """
    Launch the big three contracts on provided chain,
    make agents for each and return them.
    """

    # Mock TransactingPower Consumption (Deployer)
    testerchain.transacting_power = TransactingPower(
        password=INSECURE_DEVELOPMENT_PASSWORD,
        account=testerchain.etherbase_account)
    testerchain.transacting_power.activate()

    origin = testerchain.etherbase_account

    token_deployer = NucypherTokenDeployer(deployer_address=origin,
                                           registry=test_registry)
    token_deployer.deploy()

    staking_escrow_deployer = StakingEscrowDeployer(deployer_address=origin,
                                                    registry=test_registry,
                                                    test_mode=True)
    staking_escrow_deployer.deploy(secret_hash=INSECURE_DEPLOYMENT_SECRET_HASH)

    policy_manager_deployer = PolicyManagerDeployer(deployer_address=origin,
                                                    registry=test_registry)
    policy_manager_deployer.deploy(secret_hash=INSECURE_DEPLOYMENT_SECRET_HASH)

    adjudicator_deployer = AdjudicatorDeployer(deployer_address=origin,
                                               registry=test_registry)
    adjudicator_deployer.deploy(secret_hash=INSECURE_DEPLOYMENT_SECRET_HASH)

    staking_interface_deployer = StakingInterfaceDeployer(
        deployer_address=origin, registry=test_registry)
    staking_interface_deployer.deploy(
        secret_hash=INSECURE_DEPLOYMENT_SECRET_HASH)

    token_agent = token_deployer.make_agent()  # 1 Token
    staking_agent = staking_escrow_deployer.make_agent()  # 2 Staking Escrow
    policy_agent = policy_manager_deployer.make_agent()  # 3 Policy Agent
    _adjudicator_agent = adjudicator_deployer.make_agent()  # 4 Adjudicator

    # TODO: Get rid of returning these agents here.
    # What's important is deploying and creating the first agent for each contract,
    # and since agents are singletons, in tests it's only necessary to call the agent
    # constructor again to receive the existing agent.
    #
    # For example:
    #     staking_agent = StakingEscrowAgent()
    #
    # This is more clear than how we currently obtain an agent instance in tests:
    #     _, staking_agent, _ = agency
    #
    # Other advantages is that it's closer to how agents should be use (i.e., there
    # are no fixtures IRL) and it's more extensible (e.g., AdjudicatorAgent)

    return token_agent, staking_agent, policy_agent
コード例 #12
0
def _make_agency(testerchain):
    """
    Launch the big three contracts on provided chain,
    make agents for each and return them.
    """
    origin = testerchain.etherbase_account

    token_deployer = NucypherTokenDeployer(blockchain=testerchain,
                                           deployer_address=origin)
    token_deployer.deploy()

    staking_escrow_deployer = StakingEscrowDeployer(deployer_address=origin,
                                                    blockchain=testerchain)
    staking_escrow_deployer.deploy(
        secret_hash=os.urandom(DispatcherDeployer.DISPATCHER_SECRET_LENGTH))

    policy_manager_deployer = PolicyManagerDeployer(deployer_address=origin,
                                                    blockchain=testerchain)
    policy_manager_deployer.deploy(
        secret_hash=os.urandom(DispatcherDeployer.DISPATCHER_SECRET_LENGTH))

    adjudicator_deployer = AdjudicatorDeployer(deployer_address=origin,
                                               blockchain=testerchain)
    adjudicator_deployer.deploy(
        secret_hash=os.urandom(DispatcherDeployer.DISPATCHER_SECRET_LENGTH))

    token_agent = token_deployer.make_agent()  # 1 Token
    staking_agent = staking_escrow_deployer.make_agent()  # 2 Miner Escrow
    policy_agent = policy_manager_deployer.make_agent()  # 3 Policy Agent
    _adjudicator_agent = adjudicator_deployer.make_agent()  # 4 Adjudicator

    # TODO: Perhaps we should get rid of returning these agents here.
    # What's important is deploying and creating the first agent for each contract,
    # and since agents are singletons, in tests it's only necessary to call the agent
    # constructor again to receive the existing agent.
    #
    # For example:
    #     staking_agent = StakingEscrowAgent()
    #
    # This is more clear than how we currently obtain an agent instance in tests:
    #     _, staking_agent, _ = agency
    #
    # Other advantages is that it's closer to how agents should be use (i.e., there
    # are no fixtures IRL) and it's more extensible (e.g., AdjudicatorAgent)

    return token_agent, staking_agent, policy_agent
コード例 #13
0
def test_policy_manager_deployer(testerchain):
    origin, *everybody_else = testerchain.interface.w3.eth.accounts

    token_deployer = NucypherTokenDeployer(blockchain=testerchain,
                                           deployer_address=origin)

    token_deployer.deploy()

    token_agent = token_deployer.make_agent()  # 1: Token

    miners_escrow_secret = os.urandom(DISPATCHER_SECRET_LENGTH)
    miner_escrow_deployer = MinerEscrowDeployer(
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.keccak(miners_escrow_secret))

    miner_escrow_deployer.deploy()

    miner_agent = miner_escrow_deployer.make_agent()  # 2 Miner Escrow

    policy_manager_secret = os.urandom(DISPATCHER_SECRET_LENGTH)
    deployer = PolicyManagerDeployer(
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.keccak(policy_manager_secret))

    deployment_txhashes = deployer.deploy()
    assert len(deployment_txhashes) == 3

    for title, txhash in deployment_txhashes.items():
        receipt = testerchain.wait_for_receipt(txhash=txhash)
        assert receipt['status'] == 1, "Transaction Rejected {}:{}".format(
            title, txhash)

    # Create a token instance
    policy_agent = deployer.make_agent()
    policy_manager_contract = policy_agent.contract

    # Retrieve the token from the blockchain
    some_policy_agent = PolicyAgent()
    assert some_policy_agent.contract.address == policy_manager_contract.address

    # Compare the contract address for equality
    assert policy_agent.contract_address == some_policy_agent.contract_address
    assert policy_agent == some_policy_agent  # __eq__
コード例 #14
0
def test_deploy_ethereum_contracts(testerchain, deployment_progress,
                                   test_registry):
    testerchain = testerchain

    origin, *everybody_else = testerchain.client.accounts

    #
    # Nucypher Token
    #
    token_deployer = NucypherTokenDeployer(registry=test_registry,
                                           deployer_address=origin)
    assert token_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert token_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not token_deployer.is_deployed

    token_deployer.deploy(progress=deployment_progress)
    assert token_deployer.is_deployed
    assert len(token_deployer.contract_address) == 42

    token_agent = NucypherTokenAgent(registry=test_registry)
    assert len(token_agent.contract_address) == 42
    assert token_agent.contract_address == token_deployer.contract_address

    another_token_agent = token_deployer.make_agent()
    assert len(another_token_agent.contract_address) == 42
    assert another_token_agent.contract_address == token_deployer.contract_address == token_agent.contract_address

    #
    # StakingEscrow
    #
    stakers_escrow_secret = os.urandom(
        DispatcherDeployer.DISPATCHER_SECRET_LENGTH)
    staking_escrow_deployer = StakingEscrowDeployer(registry=test_registry,
                                                    deployer_address=origin)
    assert staking_escrow_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert staking_escrow_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not staking_escrow_deployer.is_deployed

    staking_escrow_deployer.deploy(secret_hash=keccak(stakers_escrow_secret),
                                   progress=deployment_progress)
    assert staking_escrow_deployer.is_deployed
    assert len(staking_escrow_deployer.contract_address) == 42

    staking_agent = ContractAgency.get_agent(StakingEscrowAgent,
                                             registry=test_registry)
    assert len(staking_agent.contract_address) == 42
    assert staking_agent.contract_address == staking_escrow_deployer.contract_address

    another_staking_agent = staking_escrow_deployer.make_agent()
    assert len(another_staking_agent.contract_address) == 42
    assert another_staking_agent.contract_address == staking_escrow_deployer.contract_address == staking_agent.contract_address

    #
    # Policy Manager
    #
    policy_manager_secret = os.urandom(
        DispatcherDeployer.DISPATCHER_SECRET_LENGTH)
    policy_manager_deployer = PolicyManagerDeployer(registry=test_registry,
                                                    deployer_address=origin)

    assert policy_manager_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert policy_manager_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not policy_manager_deployer.is_deployed

    policy_manager_deployer.deploy(secret_hash=keccak(policy_manager_secret),
                                   progress=deployment_progress)
    assert policy_manager_deployer.is_deployed
    assert len(policy_manager_deployer.contract_address) == 42

    policy_agent = policy_manager_deployer.make_agent()
    assert len(policy_agent.contract_address) == 42
    assert policy_agent.contract_address == policy_manager_deployer.contract_address

    another_policy_agent = policy_manager_deployer.make_agent()
    assert len(another_policy_agent.contract_address) == 42
    assert another_policy_agent.contract_address == policy_manager_deployer.contract_address == policy_agent.contract_address

    #
    # Adjudicator
    #
    adjudicator_secret = os.urandom(
        DispatcherDeployer.DISPATCHER_SECRET_LENGTH)
    adjudicator_deployer = AdjudicatorDeployer(registry=test_registry,
                                               deployer_address=origin)

    assert adjudicator_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert adjudicator_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not adjudicator_deployer.is_deployed

    adjudicator_deployer.deploy(secret_hash=keccak(adjudicator_secret),
                                progress=deployment_progress)
    assert adjudicator_deployer.is_deployed
    assert len(adjudicator_deployer.contract_address) == 42

    adjudicator_agent = adjudicator_deployer.make_agent()
    assert len(adjudicator_agent.contract_address) == 42
    assert adjudicator_agent.contract_address == adjudicator_deployer.contract_address

    another_adjudicator_agent = AdjudicatorAgent(registry=test_registry)
    assert len(another_adjudicator_agent.contract_address) == 42
    assert another_adjudicator_agent.contract_address == adjudicator_deployer.contract_address == adjudicator_agent.contract_address

    # overall deployment steps must match aggregated individual expected number of steps
    all_deployment_transactions = token_deployer.deployment_steps + staking_escrow_deployer.deployment_steps + \
                                  policy_manager_deployer.deployment_steps + adjudicator_deployer.deployment_steps
    assert deployment_progress.num_steps == len(all_deployment_transactions)
コード例 #15
0
def estimate_gas():
    solidity_compiler = SolidityCompiler(test_contract_dir=CONTRACTS_DIR)

    # create a temporary registrar for the tester blockchain
    temporary_registry = TemporaryEthereumContractRegistry()

    # Configure a custom provider
    overrides = {'gas_limit': 4626271}
    pyevm_backend = OverridablePyEVMBackend(genesis_overrides=overrides)

    eth_tester = EthereumTester(backend=pyevm_backend,
                                auto_mine_transactions=True)
    pyevm_provider = EthereumTesterProvider(ethereum_tester=eth_tester)

    # Use the the custom provider and registrar to init an interface
    circumflex = DeployerCircumflex(
        compiler=solidity_compiler,  # freshly recompile
        registry=temporary_registry,  # use temporary registrar
        providers=(pyevm_provider, ))  # use custom test provider

    # Create the blockchain
    testerchain = TesterBlockchain(interface=circumflex, test_accounts=10)
    origin, ursula1, ursula2, ursula3, alice1, *everyone_else = testerchain.interface.w3.eth.accounts
    circumflex.deployer_address = origin  # Set the deployer address from a freshly created test account

    token_deployer = NucypherTokenDeployer(blockchain=testerchain,
                                           deployer_address=origin)
    token_deployer.arm()
    token_deployer.deploy()
    token_agent = token_deployer.make_agent()

    miner_escrow_deployer = MinerEscrowDeployer(token_agent=token_agent,
                                                deployer_address=origin)
    miner_escrow_deployer.arm()
    miner_escrow_deployer.deploy()
    miner_agent = miner_escrow_deployer.make_agent()

    policy_manager_deployer = PolicyManagerDeployer(miner_agent=miner_agent,
                                                    deployer_address=origin)
    policy_manager_deployer.arm()
    policy_manager_deployer.deploy()
    policy_agent = policy_manager_deployer.make_agent()

    web3 = testerchain.interface.w3

    print("Estimate gas:")
    # Pre deposit tokens
    tx = token_agent.contract.functions.approve(miner_agent.contract_address, constants.MIN_ALLOWED_LOCKED * 5)\
        .transact({'from': origin})
    testerchain.wait_for_receipt(tx)
    print("Pre-deposit tokens for 5 owners = " + str(
        miner_agent.contract.functions.preDeposit(
            everyone_else[0:5], [int(constants.MIN_ALLOWED_LOCKED)] *
            5, [int(constants.MIN_LOCKED_PERIODS)] *
            5).estimateGas({'from': origin})))

    # Give Ursula and Alice some coins
    print("Transfer tokens = " + str(
        token_agent.contract.functions.transfer(
            ursula1, constants.MIN_ALLOWED_LOCKED *
            10).estimateGas({'from': origin})))
    tx = token_agent.contract.functions.transfer(
        ursula1, constants.MIN_ALLOWED_LOCKED * 10).transact({'from': origin})
    testerchain.wait_for_receipt(tx)
    tx = token_agent.contract.functions.transfer(
        ursula2, constants.MIN_ALLOWED_LOCKED * 10).transact({'from': origin})
    testerchain.wait_for_receipt(tx)
    tx = token_agent.contract.functions.transfer(
        ursula3, constants.MIN_ALLOWED_LOCKED * 10).transact({'from': origin})
    testerchain.wait_for_receipt(tx)

    # Ursula and Alice give Escrow rights to transfer
    print("Approving transfer = " + str(
        token_agent.contract.functions.approve(
            miner_agent.contract_address, constants.MIN_ALLOWED_LOCKED *
            6).estimateGas({'from': ursula1})))
    tx = token_agent.contract.functions.approve(miner_agent.contract_address, constants.MIN_ALLOWED_LOCKED * 6)\
        .transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    tx = token_agent.contract.functions.approve(miner_agent.contract_address, constants.MIN_ALLOWED_LOCKED * 6)\
        .transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    tx = token_agent.contract.functions.approve(miner_agent.contract_address, constants.MIN_ALLOWED_LOCKED * 6)\
        .transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Ursula and Alice transfer some tokens to the escrow and lock them
    print("First initial deposit tokens = " + str(
        miner_agent.contract.functions.deposit(
            constants.MIN_ALLOWED_LOCKED * 3, int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula1})))
    tx = miner_agent.contract.functions.deposit(constants.MIN_ALLOWED_LOCKED * 3, int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second initial deposit tokens = " + str(
        miner_agent.contract.functions.deposit(
            constants.MIN_ALLOWED_LOCKED * 3, int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula2})))
    tx = miner_agent.contract.functions.deposit(constants.MIN_ALLOWED_LOCKED * 3, int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third initial deposit tokens = " + str(
        miner_agent.contract.functions.deposit(
            constants.MIN_ALLOWED_LOCKED * 3, int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula3})))
    tx = miner_agent.contract.functions.deposit(constants.MIN_ALLOWED_LOCKED * 3, int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Wait 1 period and confirm activity
    testerchain.time_travel(periods=1)
    print("First confirm activity = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula1})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second confirm activity = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula2})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third confirm activity = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula3})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Wait 1 period and mint tokens
    testerchain.time_travel(periods=1)
    print("First mining (1 stake) = " + str(
        miner_agent.contract.functions.mint().estimateGas({'from': ursula1})))
    tx = miner_agent.contract.functions.mint().transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second mining (1 stake) = " + str(
        miner_agent.contract.functions.mint().estimateGas({'from': ursula2})))
    tx = miner_agent.contract.functions.mint().transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third/last mining (1 stake) = " + str(
        miner_agent.contract.functions.mint().estimateGas({'from': ursula3})))
    tx = miner_agent.contract.functions.mint().transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    print("First confirm activity again = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula1})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second confirm activity again = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula2})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third confirm activity again = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula3})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Confirm again
    testerchain.time_travel(periods=1)
    print("First confirm activity + mint = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula1})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second confirm activity + mint = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula2})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third confirm activity + mint = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula3})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Get locked tokens
    print("Getting locked tokens = " + str(
        miner_agent.contract.functions.getLockedTokens(ursula1).estimateGas()))

    # Wait 1 period and withdraw tokens
    testerchain.time_travel(periods=1)
    print("First withdraw = " + str(
        miner_agent.contract.functions.withdraw(1).estimateGas(
            {'from': ursula1})))
    tx = miner_agent.contract.functions.withdraw(1).transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second withdraw = " + str(
        miner_agent.contract.functions.withdraw(1).estimateGas(
            {'from': ursula2})))
    tx = miner_agent.contract.functions.withdraw(1).transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third withdraw = " + str(
        miner_agent.contract.functions.withdraw(1).estimateGas(
            {'from': ursula3})))
    tx = miner_agent.contract.functions.withdraw(1).transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Wait 1 period and confirm activity
    testerchain.time_travel(periods=1)
    print("First confirm activity after downtime = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula1})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second confirm activity after downtime  = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula2})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third confirm activity after downtime  = " +
          str(miner_agent.contract.functions.confirmActivity().estimateGas(
              {'from': ursula3})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Ursula and Alice deposit some tokens to the escrow again
    print("First deposit tokens again = " + str(
        miner_agent.contract.functions.deposit(
            constants.MIN_ALLOWED_LOCKED * 2, int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula1})))
    tx = miner_agent.contract.functions.deposit(constants.MIN_ALLOWED_LOCKED * 2, int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second deposit tokens again = " + str(
        miner_agent.contract.functions.deposit(
            constants.MIN_ALLOWED_LOCKED * 2, int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula2})))
    tx = miner_agent.contract.functions.deposit(constants.MIN_ALLOWED_LOCKED * 2, int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third deposit tokens again = " + str(
        miner_agent.contract.functions.deposit(
            constants.MIN_ALLOWED_LOCKED * 2, int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula3})))
    tx = miner_agent.contract.functions.deposit(constants.MIN_ALLOWED_LOCKED * 2, int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Wait 1 period and mint tokens
    testerchain.time_travel(periods=1)
    print("First mining again = " + str(
        miner_agent.contract.functions.mint().estimateGas({'from': ursula1})))
    tx = miner_agent.contract.functions.mint().transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second mining again = " + str(
        miner_agent.contract.functions.mint().estimateGas({'from': ursula2})))
    tx = miner_agent.contract.functions.mint().transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third/last mining again = " + str(
        miner_agent.contract.functions.mint().estimateGas({'from': ursula3})))
    tx = miner_agent.contract.functions.mint().transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Create policy
    policy_id_1 = os.urandom(int(constants.POLICY_ID_LENGTH))
    policy_id_2 = os.urandom(int(constants.POLICY_ID_LENGTH))
    number_of_periods = 10
    print("First creating policy (1 node, 10 periods) = " + str(
        policy_agent.contract.functions.createPolicy(
            policy_id_1, number_of_periods, 0, [ursula1]).estimateGas(
                {
                    'from': alice1,
                    'value': 10000
                })))
    tx = policy_agent.contract.functions.createPolicy(policy_id_1, number_of_periods, 0, [ursula1])\
        .transact({'from': alice1, 'value': 10000})
    testerchain.wait_for_receipt(tx)
    print("Second creating policy (1 node, 10 periods) = " + str(
        policy_agent.contract.functions.createPolicy(
            policy_id_2, number_of_periods, 0, [ursula1]).estimateGas(
                {
                    'from': alice1,
                    'value': 10000
                })))
    tx = policy_agent.contract.functions.createPolicy(policy_id_2, number_of_periods, 0, [ursula1])\
        .transact({'from': alice1, 'value': 10000})
    testerchain.wait_for_receipt(tx)

    # Revoke policy
    print("Revoking policy = " + str(
        policy_agent.contract.functions.revokePolicy(policy_id_1).estimateGas(
            {'from': alice1})))
    tx = policy_agent.contract.functions.revokePolicy(policy_id_1).transact(
        {'from': alice1})
    testerchain.wait_for_receipt(tx)
    tx = policy_agent.contract.functions.revokePolicy(policy_id_2).transact(
        {'from': alice1})
    testerchain.wait_for_receipt(tx)

    # Create policy with more periods
    policy_id_1 = os.urandom(int(constants.POLICY_ID_LENGTH))
    policy_id_2 = os.urandom(int(constants.POLICY_ID_LENGTH))
    policy_id_3 = os.urandom(int(constants.POLICY_ID_LENGTH))
    number_of_periods = 100
    print("First creating policy (1 node, " + str(number_of_periods) +
          " periods, first reward) = " + str(
              policy_agent.contract.functions.createPolicy(
                  policy_id_1, number_of_periods, 50, [ursula2]).estimateGas(
                      {
                          'from': alice1,
                          'value': 10050
                      })))
    tx = policy_agent.contract.functions.createPolicy(policy_id_1, number_of_periods, 50, [ursula2])\
        .transact({'from': alice1, 'value': 10050})
    testerchain.wait_for_receipt(tx)
    testerchain.time_travel(periods=1)
    print("Second creating policy (1 node, " + str(number_of_periods) +
          " periods, first reward) = " + str(
              policy_agent.contract.functions.createPolicy(
                  policy_id_2, number_of_periods, 50, [ursula2]).estimateGas(
                      {
                          'from': alice1,
                          'value': 10050
                      })))
    tx = policy_agent.contract.functions.createPolicy(policy_id_2, number_of_periods, 50, [ursula2])\
        .transact({'from': alice1, 'value': 10050})
    testerchain.wait_for_receipt(tx)
    print("Third creating policy (1 node, " + str(number_of_periods) +
          " periods, first reward) = " + str(
              policy_agent.contract.functions.createPolicy(
                  policy_id_3, number_of_periods, 50, [ursula1]).estimateGas(
                      {
                          'from': alice1,
                          'value': 10050
                      })))
    tx = policy_agent.contract.functions.createPolicy(policy_id_3, number_of_periods, 50, [ursula1])\
        .transact({'from': alice1, 'value': 10050})
    testerchain.wait_for_receipt(tx)

    # Mine and revoke policy
    testerchain.time_travel(periods=10)
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula2})
    testerchain.wait_for_receipt(tx)
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula1})
    testerchain.wait_for_receipt(tx)

    testerchain.time_travel(periods=1)
    print("First mining after downtime = " + str(
        miner_agent.contract.functions.mint().estimateGas({'from': ursula1})))
    tx = miner_agent.contract.functions.mint().transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second mining after downtime = " + str(
        miner_agent.contract.functions.mint().estimateGas({'from': ursula2})))
    tx = miner_agent.contract.functions.mint().transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)

    testerchain.time_travel(periods=10)
    print("First revoking policy after downtime = " + str(
        policy_agent.contract.functions.revokePolicy(policy_id_1).estimateGas(
            {'from': alice1})))
    tx = policy_agent.contract.functions.revokePolicy(policy_id_1).transact(
        {'from': alice1})
    testerchain.wait_for_receipt(tx)
    print("Second revoking policy after downtime = " + str(
        policy_agent.contract.functions.revokePolicy(policy_id_2).estimateGas(
            {'from': alice1})))
    tx = policy_agent.contract.functions.revokePolicy(policy_id_2).transact(
        {'from': alice1})
    testerchain.wait_for_receipt(tx)
    print("Second revoking policy after downtime = " + str(
        policy_agent.contract.functions.revokePolicy(policy_id_3).estimateGas(
            {'from': alice1})))
    tx = policy_agent.contract.functions.revokePolicy(policy_id_3).transact(
        {'from': alice1})
    testerchain.wait_for_receipt(tx)

    # Create policy with multiple nodes
    policy_id_1 = os.urandom(int(constants.POLICY_ID_LENGTH))
    policy_id_2 = os.urandom(int(constants.POLICY_ID_LENGTH))
    policy_id_3 = os.urandom(int(constants.POLICY_ID_LENGTH))
    number_of_periods = 100
    print("First creating policy (3 nodes, 100 periods, first reward) = " +
          str(
              policy_agent.contract.functions.createPolicy(
                  policy_id_1, number_of_periods, 50,
                  [ursula1, ursula2, ursula3]).estimateGas({
                      'from': alice1,
                      'value': 30150
                  })))
    tx = policy_agent.contract.functions.createPolicy(policy_id_1, number_of_periods, 50, [ursula1, ursula2, ursula3])\
        .transact({'from': alice1, 'value': 30150})
    testerchain.wait_for_receipt(tx)
    print("Second creating policy (3 nodes, 100 periods, first reward) = " +
          str(
              policy_agent.contract.functions.createPolicy(
                  policy_id_2, number_of_periods, 50,
                  [ursula1, ursula2, ursula3]).estimateGas({
                      'from': alice1,
                      'value': 30150
                  })))
    tx = policy_agent.contract.functions.createPolicy(policy_id_2, number_of_periods, 50, [ursula1, ursula2, ursula3])\
        .transact({'from': alice1, 'value': 30150})
    testerchain.wait_for_receipt(tx)
    print("Third creating policy (2 nodes, 100 periods, first reward) = " +
          str(
              policy_agent.contract.functions.createPolicy(
                  policy_id_3, number_of_periods, 50,
                  [ursula1, ursula2]).estimateGas({
                      'from': alice1,
                      'value': 20100
                  })))
    tx = policy_agent.contract.functions.createPolicy(policy_id_3, number_of_periods, 50, [ursula1, ursula2])\
        .transact({'from': alice1, 'value': 20100})
    testerchain.wait_for_receipt(tx)

    for index in range(5):
        tx = miner_agent.contract.functions.confirmActivity().transact(
            {'from': ursula1})
        testerchain.wait_for_receipt(tx)
        tx = miner_agent.contract.functions.confirmActivity().transact(
            {'from': ursula2})
        testerchain.wait_for_receipt(tx)
        tx = miner_agent.contract.functions.confirmActivity().transact(
            {'from': ursula3})
        testerchain.wait_for_receipt(tx)
        testerchain.time_travel(periods=1)

    tx = miner_agent.contract.functions.mint().transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    tx = miner_agent.contract.functions.mint().transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    tx = miner_agent.contract.functions.mint().transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Check regular deposit
    print("First deposit tokens = " + str(
        miner_agent.contract.functions.deposit(
            int(constants.MIN_ALLOWED_LOCKED), int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula1})))
    tx = miner_agent.contract.functions.deposit(int(constants.MIN_ALLOWED_LOCKED), int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second deposit tokens = " + str(
        miner_agent.contract.functions.deposit(
            int(constants.MIN_ALLOWED_LOCKED), int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula2})))
    tx = miner_agent.contract.functions.deposit(int(constants.MIN_ALLOWED_LOCKED), int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third deposit tokens = " + str(
        miner_agent.contract.functions.deposit(
            int(constants.MIN_ALLOWED_LOCKED), int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula3})))
    tx = miner_agent.contract.functions.deposit(int(constants.MIN_ALLOWED_LOCKED), int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # ApproveAndCall
    testerchain.time_travel(periods=1)

    tx = miner_agent.contract.functions.mint().transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    tx = miner_agent.contract.functions.mint().transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    tx = miner_agent.contract.functions.mint().transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    print("First approveAndCall = " + str(
        token_agent.contract.functions.approveAndCall(
            miner_agent.contract_address,
            int(constants.MIN_ALLOWED_LOCKED) *
            2, web3.toBytes(int(constants.MIN_LOCKED_PERIODS))).estimateGas(
                {'from': ursula1})))
    tx = token_agent.contract.functions.approveAndCall(miner_agent.contract_address,
                                                       int(constants.MIN_ALLOWED_LOCKED) * 2,
                                                       web3.toBytes(int(constants.MIN_LOCKED_PERIODS)))\
        .transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second approveAndCall = " + str(
        token_agent.contract.functions.approveAndCall(
            miner_agent.contract_address,
            int(constants.MIN_ALLOWED_LOCKED) *
            2, web3.toBytes(int(constants.MIN_LOCKED_PERIODS))).estimateGas(
                {'from': ursula2})))
    tx = token_agent.contract.functions.approveAndCall(miner_agent.contract_address,
                                                       int(constants.MIN_ALLOWED_LOCKED) * 2,
                                                       web3.toBytes(int(constants.MIN_LOCKED_PERIODS)))\
        .transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third approveAndCall = " + str(
        token_agent.contract.functions.approveAndCall(
            miner_agent.contract_address,
            int(constants.MIN_ALLOWED_LOCKED) *
            2, web3.toBytes(int(constants.MIN_LOCKED_PERIODS))).estimateGas(
                {'from': ursula3})))
    tx = token_agent.contract.functions.approveAndCall(miner_agent.contract_address,
                                                       int(constants.MIN_ALLOWED_LOCKED) * 2,
                                                       web3.toBytes(int(constants.MIN_LOCKED_PERIODS)))\
        .transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Locking tokens
    testerchain.time_travel(periods=1)

    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula1})
    testerchain.wait_for_receipt(tx)
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula2})
    testerchain.wait_for_receipt(tx)
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula3})
    testerchain.wait_for_receipt(tx)

    print("First locking tokens = " + str(
        miner_agent.contract.functions.lock(int(
            constants.MIN_ALLOWED_LOCKED), int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula1})))
    tx = miner_agent.contract.functions.lock(int(constants.MIN_ALLOWED_LOCKED),
                                             int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second locking tokens = " + str(
        miner_agent.contract.functions.lock(int(
            constants.MIN_ALLOWED_LOCKED), int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula2})))
    tx = miner_agent.contract.functions.lock(int(constants.MIN_ALLOWED_LOCKED),
                                             int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula2})
    testerchain.wait_for_receipt(tx)
    print("Third locking tokens = " + str(
        miner_agent.contract.functions.lock(int(
            constants.MIN_ALLOWED_LOCKED), int(
                constants.MIN_LOCKED_PERIODS)).estimateGas({'from': ursula3})))
    tx = miner_agent.contract.functions.lock(int(constants.MIN_ALLOWED_LOCKED),
                                             int(constants.MIN_LOCKED_PERIODS))\
        .transact({'from': ursula3})
    testerchain.wait_for_receipt(tx)

    # Divide stake
    print("First divide stake = " + str(
        miner_agent.contract.functions.divideStake(
            1, int(constants.MIN_ALLOWED_LOCKED), 2).estimateGas(
                {'from': ursula1})))
    tx = miner_agent.contract.functions.divideStake(
        1, int(constants.MIN_ALLOWED_LOCKED), 2).transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Second divide stake = " + str(
        miner_agent.contract.functions.divideStake(
            3, int(constants.MIN_ALLOWED_LOCKED), 2).estimateGas(
                {'from': ursula1})))
    tx = miner_agent.contract.functions.divideStake(
        3, int(constants.MIN_ALLOWED_LOCKED), 2).transact({'from': ursula1})
    testerchain.wait_for_receipt(tx)

    # Divide almost finished stake
    testerchain.time_travel(periods=1)
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula1})
    testerchain.wait_for_receipt(tx)
    testerchain.time_travel(periods=1)
    print("Divide stake (next period is not confirmed) = " + str(
        miner_agent.contract.functions.divideStake(
            0, int(constants.MIN_ALLOWED_LOCKED), 2).estimateGas(
                {'from': ursula1})))
    tx = miner_agent.contract.functions.confirmActivity().transact(
        {'from': ursula1})
    testerchain.wait_for_receipt(tx)
    print("Divide stake (next period is confirmed) = " + str(
        miner_agent.contract.functions.divideStake(
            0, int(constants.MIN_ALLOWED_LOCKED), 2).estimateGas(
                {'from': ursula1})))

    print("All done!")
コード例 #16
0
def test_deploy_idle_network(testerchain, deployment_progress, test_registry):
    origin, *everybody_else = testerchain.client.accounts

    #
    # Nucypher Token
    #
    token_deployer = NucypherTokenDeployer(registry=test_registry,
                                           deployer_address=origin)
    assert token_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert token_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not token_deployer.is_deployed()

    token_deployer.deploy(progress=deployment_progress)
    assert token_deployer.is_deployed()

    token_agent = NucypherTokenAgent(registry=test_registry)
    assert token_agent.contract_address == token_deployer.contract_address

    another_token_agent = token_deployer.make_agent()
    assert another_token_agent.contract_address == token_deployer.contract_address == token_agent.contract_address

    #
    # StakingEscrow - in INIT mode, i.e. stub for StakingEscrow
    #
    staking_escrow_deployer = StakingEscrowDeployer(registry=test_registry,
                                                    deployer_address=origin)
    assert staking_escrow_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert staking_escrow_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not staking_escrow_deployer.is_deployed()

    staking_escrow_deployer.deploy(progress=deployment_progress,
                                   deployment_mode=constants.INIT)
    assert not staking_escrow_deployer.is_deployed()

    #
    # Policy Manager
    #
    policy_manager_deployer = PolicyManagerDeployer(registry=test_registry,
                                                    deployer_address=origin)

    assert policy_manager_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert policy_manager_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not policy_manager_deployer.is_deployed()

    policy_manager_deployer.deploy(progress=deployment_progress)
    assert policy_manager_deployer.is_deployed()

    policy_agent = policy_manager_deployer.make_agent()
    assert policy_agent.contract_address == policy_manager_deployer.contract_address

    #
    # Adjudicator
    #
    adjudicator_deployer = AdjudicatorDeployer(registry=test_registry,
                                               deployer_address=origin)

    assert adjudicator_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert adjudicator_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not adjudicator_deployer.is_deployed()

    adjudicator_deployer.deploy(progress=deployment_progress)
    assert adjudicator_deployer.is_deployed()

    adjudicator_agent = adjudicator_deployer.make_agent()
    assert adjudicator_agent.contract_address == adjudicator_deployer.contract_address

    #
    # StakingEscrow - in IDLE mode, i.e. without activation steps (approve_funding and initialize)
    #
    staking_escrow_deployer = StakingEscrowDeployer(registry=test_registry,
                                                    deployer_address=origin)
    assert staking_escrow_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert staking_escrow_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not staking_escrow_deployer.is_deployed()

    staking_escrow_deployer.deploy(progress=deployment_progress,
                                   deployment_mode=constants.IDLE)
    assert staking_escrow_deployer.is_deployed()

    staking_agent = ContractAgency.get_agent(StakingEscrowAgent,
                                             registry=test_registry)
    assert staking_agent.contract_address == staking_escrow_deployer.contract_address

    # The contract has no tokens yet
    assert token_agent.get_balance(staking_agent.contract_address) == 0
コード例 #17
0
ファイル: main.py プロジェクト: lucianstroie/nucypher
def simulate(config, action, nodes, federated_only):
    """
    Simulate the nucypher blockchain network

    Arguments
    ==========

    action - Which action to perform; The choices are:
           - start: Start a multi-process nucypher network simulation
           - stop: Stop a running simulation gracefully

    Options
    ========

    --nodes - The quantity of nodes (processes) to execute during the simulation
    --duration = The number of periods to run the simulation before termination

    """

    if action == 'init':

        # OK, Try connecting to the blockchain
        click.echo("Connecting to provider endpoint")
        config.connect_to_blockchain()

        # Actual simulation setup logic
        one_million_eth = 10**6 * 10**18
        click.echo("Airdropping {} ETH to {} test accounts".format(
            one_million_eth, len(config.accounts)))
        config.blockchain.ether_airdrop(
            amount=one_million_eth)  # wei -> ether | 1 Million ETH

        # Fin
        click.echo("Blockchain initialized")

    if action == 'deploy':

        if config.simulation_running is True:
            raise RuntimeError("Network simulation already running")

        if not federated_only:
            config.connect_to_blockchain()

            click.confirm("Deploy all nucypher contracts to blockchain?",
                          abort=True)
            click.echo("Bootstrapping simulated blockchain network")

            blockchain = TesterBlockchain.from_config()

            # TODO: Enforce Saftey - ensure this is "fake" #
            conditions = ()
            assert True

            # Parse addresses
            etherbase, *everybody_else = blockchain.interface.w3.eth.accounts

            # Deploy contracts
            token_deployer = NucypherTokenDeployer(blockchain=blockchain,
                                                   deployer_address=etherbase)
            token_deployer.arm()
            token_deployer.deploy()
            token_agent = token_deployer.make_agent()
            click.echo("Deployed {}:{}".format(token_agent.contract_name,
                                               token_agent.contract_address))

            miner_escrow_deployer = MinerEscrowDeployer(
                token_agent=token_agent, deployer_address=etherbase)
            miner_escrow_deployer.arm()
            miner_escrow_deployer.deploy()
            miner_agent = miner_escrow_deployer.make_agent()
            click.echo("Deployed {}:{}".format(miner_agent.contract_name,
                                               miner_agent.contract_address))

            policy_manager_deployer = PolicyManagerDeployer(
                miner_agent=miner_agent, deployer_address=etherbase)
            policy_manager_deployer.arm()
            policy_manager_deployer.deploy()
            policy_agent = policy_manager_deployer.make_agent()
            click.echo("Deployed {}:{}".format(policy_agent.contract_name,
                                               policy_agent.contract_address))

            airdrop_amount = 1000000 * int(constants.M)
            click.echo("Airdropping tokens {} to {} addresses".format(
                airdrop_amount, len(everybody_else)))
            _receipts = token_airdrop(token_agent=token_agent,
                                      origin=etherbase,
                                      addresses=everybody_else,
                                      amount=airdrop_amount)

            click.echo("Connecting to deployed contracts")
            config.connect_to_contracts()

            # Commit the current state of deployment to a registry file.
            click.echo("Writing filesystem registry")
            _sim_registry_name = config.blockchain.interface._registry.commit(
                filepath=DEFAULT_SIMULATION_REGISTRY_FILEPATH)

            # Fin
            click.echo("Ready to simulate decentralized swarm.")

        else:
            click.echo("Ready to run federated swarm.")

    elif action == 'swarm':

        if not federated_only:
            config.connect_to_blockchain()
            config.connect_to_contracts(simulation=True)

        localhost = 'localhost'

        # Select a port range to use on localhost for sim servers
        start_port, stop_port = DEFAULT_SIMULATION_PORT, DEFAULT_SIMULATION_PORT + int(
            nodes)
        port_range = range(start_port, stop_port)
        click.echo("Selected local ports {}-{}".format(start_port, stop_port))

        for index, sim_port_number in enumerate(port_range):

            #
            # Parse ursula parameters
            #

            rest_port, dht_port = sim_port_number, sim_port_number + 100
            db_name = 'sim-{}'.format(rest_port)

            proc_params = '''
            run_ursula --host {} --rest-port {} --dht-port {} --db-name {}
            '''.format(localhost, rest_port, dht_port, db_name).split()

            if federated_only:
                click.echo("Setting federated operating mode")
                proc_params.append('--federated-only')
            else:
                sim_address = config.accounts[index + 1]
                miner = Miner(miner_agent=config.miner_agent,
                              checksum_address=sim_address)

                # stake a random amount
                min_stake, balance = constants.MIN_ALLOWED_LOCKED, miner.token_balance
                value = random.randint(min_stake, balance)

                # for a random lock duration
                min_locktime, max_locktime = constants.MIN_LOCKED_PERIODS, constants.MAX_MINTING_PERIODS
                periods = random.randint(min_locktime, max_locktime)

                miner.initialize_stake(amount=value, lock_periods=periods)
                click.echo(
                    "{} Initialized new stake: {} tokens for {} periods".
                    format(sim_address, value, periods))

                proc_params.extend(
                    '--checksum-address {}'.format(sim_address).split())

            # Spawn
            click.echo("Spawning node #{}".format(index + 1))
            processProtocol = UrsulaProcessProtocol(command=proc_params)
            ursula_proc = reactor.spawnProcess(processProtocol, "nucypher-cli",
                                               proc_params)
            config.sim_processes.append(ursula_proc)

            #
            # post-spawnProcess
            #

            # Start with some basic status data, then build on it

            rest_uri = "http://{}:{}".format(localhost, rest_port)
            dht_uri = "http://{}:{}".format(localhost, dht_port)

            sim_data = "Started simulated Ursula | ReST {} | DHT {} ".format(
                rest_uri, dht_uri)
            rest_uri = "{host}:{port}".format(host=localhost,
                                              port=str(sim_port_number))
            dht_uri = '{host}:{port}'.format(host=localhost, port=dht_port)
            sim_data.format(rest_uri, dht_uri)

            if not federated_only:
                stake_infos = tuple(
                    config.miner_agent.get_all_stakes(
                        miner_address=sim_address))
                sim_data += '| ETH address {}'.format(sim_address)
                sim_data += '| {} Active stakes '.format(len(stake_infos))

            click.echo(sim_data)
            config.simulation_running = True

        click.echo("Starting the reactor")
        try:
            reactor.run()

        finally:

            if config.operating_mode == 'decentralized':
                click.echo("Removing simulation registry")
                os.remove(config.sim_registry_filepath)

            click.echo("Stopping simulated Ursula processes")
            for process in config.sim_processes:
                os.kill(process.pid, 9)
                click.echo("Killed {}".format(process))
            config.simulation_running = False
            click.echo("Simulation stopped")

    elif action == 'stop':
        # Kill the simulated ursulas TODO: read PIDs from storage?
        if config.simulation_running is not True:
            raise RuntimeError("Network simulation is not running")

        for process in config.ursula_processes:
            process.transport.signalProcess('KILL')
        else:
            # TODO: Confirm they are dead
            config.simulation_running = False

    elif action == 'status':

        if not config.simulation_running:
            status_message = "Simulation not running."
        else:

            ursula_processes = len(config.ursula_processes)

            status_message = """
            
            | Node Swarm Simulation Status |
            
            Simulation processes .............. {}
            
            """.format(ursula_processes)

        click.echo(status_message)

    elif action == 'demo':
        """Run the finnegans wake demo"""
        demo_exec = os.path.join(BASE_DIR, 'nucypher_cli', 'demos',
                                 'finnegans-wake-demo.py')
        subprocess.run([sys.executable, demo_exec], stdout=subprocess.PIPE)
コード例 #18
0
ファイル: fixtures.py プロジェクト: arjunhassard/nucypher
def _make_agency(
    testerchain, test_registry, token_economics
) -> Tuple[NucypherTokenAgent, StakingEscrowAgent, PolicyManagerAgent]:
    """
    Launch the big three contracts on provided chain,
    make agents for each and return them.
    """

    # Mock TransactingPower Consumption (Deployer)
    testerchain.transacting_power = TransactingPower(
        password=INSECURE_DEVELOPMENT_PASSWORD,
        signer=Web3Signer(client=testerchain.client),
        account=testerchain.etherbase_account)
    testerchain.transacting_power.activate()

    origin = testerchain.etherbase_account

    token_deployer = NucypherTokenDeployer(deployer_address=origin,
                                           economics=token_economics,
                                           registry=test_registry)
    token_deployer.deploy()

    staking_escrow_deployer = StakingEscrowDeployer(deployer_address=origin,
                                                    economics=token_economics,
                                                    registry=test_registry,
                                                    test_mode=True)
    staking_escrow_deployer.deploy()

    policy_manager_deployer = PolicyManagerDeployer(deployer_address=origin,
                                                    economics=token_economics,
                                                    registry=test_registry)
    policy_manager_deployer.deploy()

    adjudicator_deployer = AdjudicatorDeployer(deployer_address=origin,
                                               economics=token_economics,
                                               registry=test_registry)
    adjudicator_deployer.deploy()

    staking_interface_deployer = StakingInterfaceDeployer(
        deployer_address=origin,
        economics=token_economics,
        registry=test_registry)
    staking_interface_deployer.deploy()

    worklock_deployer = WorklockDeployer(deployer_address=origin,
                                         economics=token_economics,
                                         registry=test_registry)
    worklock_deployer.deploy()

    token_agent = token_deployer.make_agent()  # 1 Token
    staking_agent = staking_escrow_deployer.make_agent()  # 2 Staking Escrow
    policy_agent = policy_manager_deployer.make_agent()  # 3 Policy Agent
    _adjudicator_agent = adjudicator_deployer.make_agent()  # 4 Adjudicator
    _worklock_agent = worklock_deployer.make_agent()  # 5 Worklock

    # Set additional parameters
    minimum, default, maximum = FEE_RATE_RANGE
    txhash = policy_agent.contract.functions.setFeeRateRange(
        minimum, default, maximum).transact()
    _receipt = testerchain.wait_for_receipt(txhash)

    # TODO: Get rid of returning these agents here.
    # What's important is deploying and creating the first agent for each contract,
    # and since agents are singletons, in tests it's only necessary to call the agent
    # constructor again to receive the existing agent.
    #
    # For example:
    #     staking_agent = StakingEscrowAgent()
    #
    # This is more clear than how we currently obtain an agent instance in tests:
    #     _, staking_agent, _ = agency
    #
    # Other advantages is that it's closer to how agents should be use (i.e., there
    # are no fixtures IRL) and it's more extensible (e.g., AdjudicatorAgent)

    return token_agent, staking_agent, policy_agent
コード例 #19
0
def test_deploy_ethereum_contracts(testerchain):

    origin, *everybody_else = testerchain.client.accounts

    #
    # Nucypher Token
    #
    token_deployer = NucypherTokenDeployer(blockchain=testerchain,
                                           deployer_address=origin)
    assert token_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert token_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not token_deployer.is_deployed

    token_deployer.deploy()
    assert token_deployer.is_deployed
    assert len(token_deployer.contract_address) == 42

    token_agent = NucypherTokenAgent(blockchain=testerchain)
    assert len(token_agent.contract_address) == 42
    assert token_agent.contract_address == token_deployer.contract_address

    another_token_agent = token_deployer.make_agent()
    assert len(another_token_agent.contract_address) == 42
    assert another_token_agent.contract_address == token_deployer.contract_address == token_agent.contract_address

    #
    # StakingEscrow
    #
    stakers_escrow_secret = os.urandom(
        DispatcherDeployer.DISPATCHER_SECRET_LENGTH)
    staking_escrow_deployer = StakingEscrowDeployer(blockchain=testerchain,
                                                    deployer_address=origin)
    assert staking_escrow_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert staking_escrow_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not staking_escrow_deployer.is_deployed

    staking_escrow_deployer.deploy(secret_hash=keccak(stakers_escrow_secret))
    assert staking_escrow_deployer.is_deployed
    assert len(staking_escrow_deployer.contract_address) == 42

    staking_agent = StakingEscrowAgent(blockchain=testerchain)
    assert len(staking_agent.contract_address) == 42
    assert staking_agent.contract_address == staking_escrow_deployer.contract_address

    another_staking_agent = staking_escrow_deployer.make_agent()
    assert len(another_staking_agent.contract_address) == 42
    assert another_staking_agent.contract_address == staking_escrow_deployer.contract_address == staking_agent.contract_address

    #
    # Policy Manager
    #
    policy_manager_secret = os.urandom(
        DispatcherDeployer.DISPATCHER_SECRET_LENGTH)
    policy_manager_deployer = PolicyManagerDeployer(blockchain=testerchain,
                                                    deployer_address=origin)

    assert policy_manager_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert policy_manager_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not policy_manager_deployer.is_deployed

    policy_manager_deployer.deploy(secret_hash=keccak(policy_manager_secret))
    assert policy_manager_deployer.is_deployed
    assert len(policy_manager_deployer.contract_address) == 42

    policy_agent = policy_manager_deployer.make_agent()
    assert len(policy_agent.contract_address) == 42
    assert policy_agent.contract_address == policy_manager_deployer.contract_address

    another_policy_agent = policy_manager_deployer.make_agent()
    assert len(another_policy_agent.contract_address) == 42
    assert another_policy_agent.contract_address == policy_manager_deployer.contract_address == policy_agent.contract_address

    #
    # Adjudicator
    #
    adjudicator_secret = os.urandom(
        DispatcherDeployer.DISPATCHER_SECRET_LENGTH)
    adjudicator_deployer = AdjudicatorDeployer(blockchain=testerchain,
                                               deployer_address=origin)

    assert adjudicator_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert adjudicator_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not adjudicator_deployer.is_deployed

    adjudicator_deployer.deploy(secret_hash=keccak(adjudicator_secret))
    assert adjudicator_deployer.is_deployed
    assert len(adjudicator_deployer.contract_address) == 42

    adjudicator_agent = adjudicator_deployer.make_agent()
    assert len(adjudicator_agent.contract_address) == 42
    assert adjudicator_agent.contract_address == adjudicator_deployer.contract_address

    another_adjudicator_agent = adjudicator_deployer.make_agent()
    assert len(another_adjudicator_agent.contract_address) == 42
    assert another_adjudicator_agent.contract_address == adjudicator_deployer.contract_address == adjudicator_agent.contract_address
コード例 #20
0
def test_deploy_ethereum_contracts(testerchain, deployment_progress,
                                   test_registry):

    origin, *everybody_else = testerchain.client.accounts
    tpower = TransactingPower(account=origin,
                              signer=Web3Signer(testerchain.client))

    #
    # Nucypher Token
    #
    token_deployer = NucypherTokenDeployer(registry=test_registry)

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert token_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not token_deployer.is_deployed()

    token_deployer.deploy(progress=deployment_progress,
                          transacting_power=tpower)
    assert token_deployer.is_deployed()
    assert len(token_deployer.contract_address) == 42

    token_agent = NucypherTokenAgent(registry=test_registry)
    assert len(token_agent.contract_address) == 42
    assert token_agent.contract_address == token_deployer.contract_address

    another_token_agent = token_deployer.make_agent()
    assert len(another_token_agent.contract_address) == 42
    assert another_token_agent.contract_address == token_deployer.contract_address == token_agent.contract_address

    #
    # StakingEscrowStub
    #
    staking_escrow_deployer = StakingEscrowDeployer(registry=test_registry)

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert staking_escrow_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not staking_escrow_deployer.is_deployed()

    staking_escrow_deployer.deploy(progress=deployment_progress,
                                   transacting_power=tpower)
    assert not staking_escrow_deployer.is_deployed()
    assert len(staking_escrow_deployer.contract_address) == 42

    # StakingEscrow
    staking_escrow_deployer = StakingEscrowDeployer(registry=test_registry)

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert staking_escrow_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not staking_escrow_deployer.is_deployed()

    staking_escrow_deployer.deploy(progress=deployment_progress,
                                   deployment_mode=constants.FULL,
                                   transacting_power=tpower)
    assert staking_escrow_deployer.is_deployed()
    assert len(staking_escrow_deployer.contract_address) == 42

    staking_agent = ContractAgency.get_agent(StakingEscrowAgent,
                                             registry=test_registry)
    assert len(staking_agent.contract_address) == 42
    assert staking_agent.contract_address == staking_escrow_deployer.contract_address

    another_staking_agent = staking_escrow_deployer.make_agent()
    assert len(another_staking_agent.contract_address) == 42
    assert another_staking_agent.contract_address == staking_escrow_deployer.contract_address == staking_agent.contract_address

    # overall deployment steps must match aggregated individual expected number of steps
    all_deployment_transactions = token_deployer.deployment_steps + staking_escrow_deployer.init_steps + \
                                  staking_escrow_deployer.deployment_steps
    assert deployment_progress.num_steps == len(all_deployment_transactions)
コード例 #21
0
ファイル: main.py プロジェクト: OnGridSystems/nucypher
def simulate(config, action, nodes, federated_only, geth):
    """
    Simulate the nucypher blockchain network

    Arguments
    ==========

    action - Which action to perform; The choices are:
           - start: Start a multi-process nucypher network simulation
           - stop: Stop a running simulation gracefully

    Options
    ========

    --nodes - The quantity of nodes (processes) to execute during the simulation
    --duration = The number of periods to run the simulation before termination

    """
    if action == 'start':

        #
        # Blockchain Connection
        #
        if not federated_only:
            if geth:
                test_provider_uri = "ipc:///tmp/geth.ipc"
            else:
                test_provider_uri = "pyevm://tester"

            simulation_registry = TemporaryEthereumContractRegistry()
            simulation_interface = BlockchainDeployerInterface(provider_uri=test_provider_uri,
                                                               registry=simulation_registry,
                                                               compiler=SolidityCompiler())

            blockchain = TesterBlockchain(interface=simulation_interface, test_accounts=nodes, airdrop=False)

            accounts = blockchain.interface.w3.eth.accounts
            origin, *everyone_else = accounts

            # Set the deployer address from the freshly created test account
            simulation_interface.deployer_address = origin

            #
            # Blockchain Action
            #
            blockchain.ether_airdrop(amount=DEVELOPMENT_ETH_AIRDROP_AMOUNT)

            click.confirm("Deploy all nucypher contracts to {}?".format(test_provider_uri), abort=True)
            click.echo("Bootstrapping simulated blockchain network")

            # Deploy contracts
            token_deployer = NucypherTokenDeployer(blockchain=blockchain, deployer_address=origin)
            token_deployer.arm()
            token_deployer.deploy()
            token_agent = token_deployer.make_agent()

            miners_escrow_secret = os.urandom(DISPATCHER_SECRET_LENGTH)
            miner_escrow_deployer = MinerEscrowDeployer(token_agent=token_agent,
                                                        deployer_address=origin,
                                                        secret_hash=miners_escrow_secret)
            miner_escrow_deployer.arm()
            miner_escrow_deployer.deploy()
            miner_agent = miner_escrow_deployer.make_agent()

            policy_manager_secret = os.urandom(DISPATCHER_SECRET_LENGTH)
            policy_manager_deployer = PolicyManagerDeployer(miner_agent=miner_agent,
                                                            deployer_address=origin,
                                                            secret_hash=policy_manager_secret)
            policy_manager_deployer.arm()
            policy_manager_deployer.deploy()
            policy_agent = policy_manager_deployer.make_agent()

            airdrop_amount = DEVELOPMENT_TOKEN_AIRDROP_AMOUNT
            click.echo("Airdropping tokens {} to {} addresses".format(airdrop_amount, len(everyone_else)))
            _receipts = token_airdrop(token_agent=token_agent,
                                      origin=origin,
                                      addresses=everyone_else,
                                      amount=airdrop_amount)

            # Commit the current state of deployment to a registry file.
            click.echo("Writing filesystem registry")
            _sim_registry_name = blockchain.interface.registry.commit(filepath=DEFAULT_SIMULATION_REGISTRY_FILEPATH)

        click.echo("Ready to run swarm.")

        #
        # Swarm
        #

        # Select a port range to use on localhost for sim servers

        if not federated_only:
            sim_addresses = everyone_else
        else:
            sim_addresses = NotImplemented

        start_port = 8787
        counter = 0
        for sim_port_number, sim_address in enumerate(sim_addresses, start=start_port):

            #
            # Parse ursula parameters
            #

            rest_port = sim_port_number
            db_name = 'sim-{}'.format(rest_port)

            cli_exec = os.path.join(BASE_DIR, 'cli', 'main.py')
            python_exec = 'python'

            proc_params = '''
            python3 {} run_ursula --rest-port {} --db-name {}
            '''.format(python_exec, cli_exec, rest_port, db_name).split()

            if federated_only:
                proc_params.append('--federated-only')

            else:
                token_agent = NucypherTokenAgent(blockchain=blockchain)
                miner_agent = MinerAgent(token_agent=token_agent)
                miner = Miner(miner_agent=miner_agent, checksum_address=sim_address)

                # stake a random amount
                min_stake, balance = MIN_ALLOWED_LOCKED, miner.token_balance
                value = random.randint(min_stake, balance)

                # for a random lock duration
                min_locktime, max_locktime = MIN_LOCKED_PERIODS, MAX_MINTING_PERIODS
                periods = random.randint(min_locktime, max_locktime)

                miner.initialize_stake(amount=value, lock_periods=periods)
                click.echo("{} Initialized new stake: {} tokens for {} periods".format(sim_address, value, periods))

                proc_params.extend('--checksum-address {}'.format(sim_address).split())

            # Spawn
            click.echo("Spawning node #{}".format(counter+1))
            processProtocol = UrsulaProcessProtocol(command=proc_params)
            cli_exec = os.path.join(BASE_DIR, 'cli', 'main.py')
            ursula_proc = reactor.spawnProcess(processProtocol, cli_exec, proc_params)

            #
            # post-spawnProcess
            #

            # Start with some basic status data, then build on it

            rest_uri = "http://{}:{}".format('localhost', rest_port)

            sim_data = "Started simulated Ursula | ReST {}".format(rest_uri)
            rest_uri = "{host}:{port}".format(host='localhost', port=str(sim_port_number))
            sim_data.format(rest_uri)

            # if not federated_only:
            #     stake_infos = tuple(config.miner_agent.get_all_stakes(miner_address=sim_address))
            #     sim_data += '| ETH address {}'.format(sim_address)
            #     sim_data += '| {} Active stakes '.format(len(stake_infos))

            click.echo(sim_data)
            counter += 1

        click.echo("Starting the reactor")
        click.confirm("Start the reactor?", abort=True)
        try:
            reactor.run()
        finally:

            if not federated_only:
                click.echo("Removing simulation registry")
                os.remove(DEFAULT_SIMULATION_REGISTRY_FILEPATH)

            click.echo("Stopping simulated Ursula processes")
            for process in config.sim_processes:
                os.kill(process.pid, 9)
                click.echo("Killed {}".format(process))

            click.echo("Simulation completed")

    elif action == 'stop':
        # Kill the simulated ursulas
        for process in config.ursula_processes:
            process.transport.signalProcess('KILL')

    elif action == 'status':

        if not config.simulation_running:
            status_message = "Simulation not running."
        else:

            ursula_processes = len(config.ursula_processes)

            status_message = """
            
            | Node Swarm Simulation Status |
            
            Simulation processes .............. {}
            
            """.format(ursula_processes)

        click.echo(status_message)

    elif action == 'demo':
        """Run the finnegans wake demo"""
        demo_exec = os.path.join(BASE_DIR, 'cli', 'demos', 'finnegans-wake-demo.py')
        process_args = [sys.executable, demo_exec]

        if federated_only:
            process_args.append('--federated-only')

        subprocess.run(process_args, stdout=subprocess.PIPE)
コード例 #22
0
def test_deploy_ethereum_contracts(testerchain):

    origin, *everybody_else = testerchain.interface.w3.eth.accounts

    #
    # Nucypher Token
    #
    token_deployer = NucypherTokenDeployer(blockchain=testerchain,
                                           deployer_address=origin)
    assert token_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert token_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not token_deployer.is_deployed

    token_deployer.deploy()
    assert token_deployer.is_deployed
    assert len(token_deployer.contract_address) == 42

    token_agent = NucypherTokenAgent(blockchain=testerchain)
    assert len(token_agent.contract_address) == 42
    assert token_agent.contract_address == token_deployer.contract_address

    another_token_agent = token_deployer.make_agent()
    assert len(another_token_agent.contract_address) == 42
    assert another_token_agent.contract_address == token_deployer.contract_address == token_agent.contract_address

    #
    # Miner Escrow
    #
    miners_escrow_secret = os.urandom(DISPATCHER_SECRET_LENGTH)
    miner_escrow_deployer = MinerEscrowDeployer(
        blockchain=testerchain,
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.keccak(miners_escrow_secret))
    assert miner_escrow_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert miner_escrow_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not miner_escrow_deployer.is_deployed

    miner_escrow_deployer.deploy()
    assert miner_escrow_deployer.is_deployed
    assert len(miner_escrow_deployer.contract_address) == 42

    miner_agent = MinerAgent(blockchain=testerchain)
    assert len(miner_agent.contract_address) == 42
    assert miner_agent.contract_address == miner_escrow_deployer.contract_address

    another_miner_agent = miner_escrow_deployer.make_agent()
    assert len(another_miner_agent.contract_address) == 42
    assert another_miner_agent.contract_address == miner_escrow_deployer.contract_address == miner_agent.contract_address

    #
    # Policy Manager
    #
    policy_manager_secret = os.urandom(DISPATCHER_SECRET_LENGTH)
    policy_manager_deployer = PolicyManagerDeployer(
        blockchain=testerchain,
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.keccak(policy_manager_secret))
    assert policy_manager_deployer.deployer_address == origin

    with pytest.raises(ContractDeployer.ContractDeploymentError):
        assert policy_manager_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not policy_manager_deployer.is_deployed

    policy_manager_deployer.deploy()
    assert policy_manager_deployer.is_deployed
    assert len(policy_manager_deployer.contract_address) == 42

    policy_agent = policy_manager_deployer.make_agent()
    assert len(policy_agent.contract_address) == 42
    assert policy_agent.contract_address == policy_manager_deployer.contract_address

    another_policy_agent = policy_manager_deployer.make_agent()
    assert len(another_policy_agent.contract_address) == 42
    assert another_policy_agent.contract_address == policy_manager_deployer.contract_address == policy_agent.contract_address
コード例 #23
0
def test_deploy_ethereum_contracts(testerchain, deployment_progress,
                                   test_registry):

    origin, *everybody_else = testerchain.client.accounts

    #
    # Nucypher Token
    #
    token_deployer = NucypherTokenDeployer(registry=test_registry,
                                           deployer_address=origin)
    assert token_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert token_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not token_deployer.is_deployed()

    token_deployer.deploy(progress=deployment_progress)
    assert token_deployer.is_deployed()
    assert len(token_deployer.contract_address) == 42

    token_agent = NucypherTokenAgent(registry=test_registry)
    assert len(token_agent.contract_address) == 42
    assert token_agent.contract_address == token_deployer.contract_address

    another_token_agent = token_deployer.make_agent()
    assert len(another_token_agent.contract_address) == 42
    assert another_token_agent.contract_address == token_deployer.contract_address == token_agent.contract_address

    #
    # StakingEscrowStub
    #
    staking_escrow_deployer = StakingEscrowDeployer(registry=test_registry,
                                                    deployer_address=origin)
    assert staking_escrow_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert staking_escrow_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not staking_escrow_deployer.is_deployed()

    staking_escrow_deployer.deploy(progress=deployment_progress)
    assert not staking_escrow_deployer.is_deployed()
    assert len(staking_escrow_deployer.contract_address) == 42

    #
    # Policy Manager
    #
    policy_manager_deployer = PolicyManagerDeployer(registry=test_registry,
                                                    deployer_address=origin)

    assert policy_manager_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert policy_manager_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not policy_manager_deployer.is_deployed()

    policy_manager_deployer.deploy(progress=deployment_progress)
    assert policy_manager_deployer.is_deployed()
    assert len(policy_manager_deployer.contract_address) == 42

    policy_agent = policy_manager_deployer.make_agent()
    assert len(policy_agent.contract_address) == 42
    assert policy_agent.contract_address == policy_manager_deployer.contract_address

    another_policy_agent = policy_manager_deployer.make_agent()
    assert len(another_policy_agent.contract_address) == 42
    assert another_policy_agent.contract_address == policy_manager_deployer.contract_address == policy_agent.contract_address

    #
    # Adjudicator
    #
    adjudicator_deployer = AdjudicatorDeployer(registry=test_registry,
                                               deployer_address=origin)

    assert adjudicator_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert adjudicator_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not adjudicator_deployer.is_deployed()

    adjudicator_deployer.deploy(progress=deployment_progress)
    assert adjudicator_deployer.is_deployed()
    assert len(adjudicator_deployer.contract_address) == 42

    adjudicator_agent = adjudicator_deployer.make_agent()
    assert len(adjudicator_agent.contract_address) == 42
    assert adjudicator_agent.contract_address == adjudicator_deployer.contract_address

    another_adjudicator_agent = AdjudicatorAgent(registry=test_registry)
    assert len(another_adjudicator_agent.contract_address) == 42
    assert another_adjudicator_agent.contract_address == adjudicator_deployer.contract_address == adjudicator_agent.contract_address

    # StakingEscrow
    #
    staking_escrow_deployer = StakingEscrowDeployer(registry=test_registry,
                                                    deployer_address=origin)
    assert staking_escrow_deployer.deployer_address == origin

    with pytest.raises(BaseContractDeployer.ContractDeploymentError):
        assert staking_escrow_deployer.contract_address is constants.CONTRACT_NOT_DEPLOYED
    assert not staking_escrow_deployer.is_deployed()

    staking_escrow_deployer.deploy(progress=deployment_progress,
                                   deployment_mode=constants.FULL)
    assert staking_escrow_deployer.is_deployed()
    assert len(staking_escrow_deployer.contract_address) == 42

    staking_agent = ContractAgency.get_agent(StakingEscrowAgent,
                                             registry=test_registry)
    assert len(staking_agent.contract_address) == 42
    assert staking_agent.contract_address == staking_escrow_deployer.contract_address

    another_staking_agent = staking_escrow_deployer.make_agent()
    assert len(another_staking_agent.contract_address) == 42
    assert another_staking_agent.contract_address == staking_escrow_deployer.contract_address == staking_agent.contract_address

    # overall deployment steps must match aggregated individual expected number of steps
    all_deployment_transactions = token_deployer.deployment_steps + staking_escrow_deployer.init_steps + \
                                  staking_escrow_deployer.deployment_steps + \
                                  policy_manager_deployer.deployment_steps + adjudicator_deployer.deployment_steps
    assert deployment_progress.num_steps == len(all_deployment_transactions)