示例#1
0
def test_deploy_ethereum_contracts(chain):
    """
    Launch all ethereum contracts:
    - NuCypherToken
    - PolicyManager
    - MinersEscrow
    - UserEscrow
    - Issuer
    """

    token_deployer = NucypherTokenDeployer(blockchain=chain)
    token_deployer.arm()
    token_deployer.deploy()

    token_agent = NucypherTokenAgent(blockchain=chain)

    miner_escrow_deployer = MinerEscrowDeployer(token_agent=token_agent)
    miner_escrow_deployer.arm()
    miner_escrow_deployer.deploy()

    miner_agent = MinerAgent(token_agent=token_agent)

    policy_manager_contract = PolicyManagerDeployer(miner_agent=miner_agent)
    policy_manager_contract.arm()
    policy_manager_contract.deploy()
示例#2
0
def test_deploy_ethereum_contracts(testerchain):
    """
    Launch all ethereum contracts:
    - NuCypherToken
    - PolicyManager
    - MinersEscrow
    - UserEscrow
    - Issuer
    """
    origin, *everybody_else = testerchain.interface.w3.eth.accounts

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

    token_agent = NucypherTokenAgent(blockchain=testerchain)

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

    miner_agent = MinerAgent(token_agent=token_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()
示例#3
0
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()
示例#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, *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
示例#5
0
def test_deploy_ethereum_contracts(testerchain):
    """
    A bare minimum nucypher deployment fixture.
    """
    origin, *everybody_else = testerchain.interface.w3.eth.accounts

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

    token_agent = NucypherTokenAgent(blockchain=testerchain)

    miners_escrow_secret = os.urandom(constants.DISPATCHER_SECRET_LENGTH)
    miner_escrow_deployer = MinerEscrowDeployer(
        token_agent=token_agent,
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.sha3(miners_escrow_secret))
    miner_escrow_deployer.arm()
    miner_escrow_deployer.deploy()

    miner_agent = MinerAgent(token_agent=token_agent)

    policy_manager_secret = os.urandom(constants.DISPATCHER_SECRET_LENGTH)
    policy_manager_deployer = PolicyManagerDeployer(
        miner_agent=miner_agent,
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.sha3(policy_manager_secret))
    policy_manager_deployer.arm()
    policy_manager_deployer.deploy()

    policy_agent = policy_manager_deployer.make_agent()
示例#6
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.arm()
    token_deployer.deploy()

    token_agent = token_deployer.make_agent()              # 1: Token

    miners_escrow_secret = os.urandom(DISPATCHER_SECRET_LENGTH)
    miner_escrow_deployer = MinerEscrowDeployer(
        token_agent=token_agent,
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.sha3(miners_escrow_secret))
    miner_escrow_deployer.arm()
    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(
        miner_agent=miner_agent,
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.sha3(policy_manager_secret))
    policy_manager_deployer.arm()
    policy_manager_deployer.deploy()

    policy_agent = policy_manager_deployer.make_agent()    # 3 Policy Agent

    return token_agent, miner_agent, policy_agent
示例#7
0
def test_token_deployer_and_agent(chain):

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

    # The big day...
    deployer = NucypherTokenDeployer(blockchain=chain)

    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 = NucypherTokenAgent(blockchain=chain)

    # Make sure we got the name right
    deployer_contract_identifier = NucypherTokenDeployer._contract_name
    assert 'NuCypherToken' == deployer_contract_identifier

    # Ensure the contract is deployed and has a valid blockchain address
    assert len(token_agent.contract_address) == 42

    # Check that the token contract has tokens
    assert token_agent.contract.functions.totalSupply().call() != 0
    # assert token().totalSupply() == int(1e9) * _M     # TODO

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

    # Compare the contract address for equality
    assert token_agent.contract_address == same_token_agent.contract_address
    assert token_agent == same_token_agent  # __eq__
示例#8
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!")
示例#9
0
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)
示例#10
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_armed
    assert not token_deployer.is_deployed

    token_deployer.arm()
    assert token_deployer.is_armed

    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(
        token_agent=token_agent,
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.sha3(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_armed
    assert not miner_escrow_deployer.is_deployed

    miner_escrow_deployer.arm()
    assert miner_escrow_deployer.is_armed

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

    miner_agent = MinerAgent(token_agent=token_agent)
    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(
        miner_agent=miner_agent,
        deployer_address=origin,
        secret_hash=testerchain.interface.w3.sha3(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_armed
    assert not policy_manager_deployer.is_deployed

    policy_manager_deployer.arm()
    assert policy_manager_deployer.is_armed

    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
示例#11
0
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)