コード例 #1
0
def testerchain(solidity_compiler):
    """
    https: // github.com / ethereum / eth - tester     # available-backends
    """
    memory_registry = InMemoryEthereumContractRegistry()

    # Use the the custom provider and registrar to init an interface

    deployer_interface = BlockchainDeployerInterface(
        compiler=solidity_compiler,  # freshly recompile if not None
        registry=memory_registry,
        provider_uri=TEST_PROVIDER_URI)

    # Create the blockchain
    testerchain = TesterBlockchain(interface=deployer_interface,
                                   eth_airdrop=True,
                                   free_transactions=True,
                                   poa=True)

    # Set the deployer address from a freshly created test account
    deployer_interface.deployer_address = testerchain.etherbase_account

    yield testerchain
    deployer_interface.disconnect()
    testerchain.sever_connection()
コード例 #2
0
def testerchain(solidity_compiler):
    """
    https: // github.com / ethereum / eth - tester     # available-backends
    """
    memory_registry = InMemoryEthereumContractRegistry()

    # Use the the custom provider and registrar to init an interface

    deployer_interface = BlockchainDeployerInterface(
        compiler=solidity_compiler,  # freshly recompile if not None
        registry=memory_registry,
        provider_uri='tester://pyevm')

    # Create the blockchain
    testerchain = TesterBlockchain(
        interface=deployer_interface,
        test_accounts=NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK,
        airdrop=False)

    origin, *everyone = testerchain.interface.w3.eth.accounts
    deployer_interface.deployer_address = origin  # Set the deployer address from a freshly created test account
    testerchain.ether_airdrop(amount=1000000000)  # TODO: Use test constant

    yield testerchain
    testerchain.sever_connection()
コード例 #3
0
def another_testerchain(solidity_compiler):
    memory_registry = InMemoryEthereumContractRegistry()
    deployer_interface = BlockchainDeployerInterface(
        compiler=solidity_compiler,
        registry=memory_registry,
        provider_uri=TEST_PROVIDER_URI)
    testerchain = TesterBlockchain(interface=deployer_interface,
                                   test_accounts=2 *
                                   NUMBER_OF_ETH_TEST_ACCOUNTS,
                                   eth_airdrop=True)
    deployer_interface.deployer_address = testerchain.etherbase_account
    yield testerchain
    testerchain.sever_connection()
コード例 #4
0
ファイル: test_deploy.py プロジェクト: Howlla/nucypher
def make_testerchain(provider_uri, solidity_compiler):

    # Destroy existing blockchain
    BlockchainInterface.disconnect()
    TesterBlockchain.sever_connection()

    registry = EthereumContractRegistry(registry_filepath=MOCK_REGISTRY_FILEPATH)
    deployer_interface = BlockchainDeployerInterface(compiler=solidity_compiler,
                                                     registry=registry,
                                                     provider_uri=provider_uri)

    # Create new blockchain
    testerchain = TesterBlockchain(interface=deployer_interface,
                                   eth_airdrop=True,
                                   free_transactions=False,
                                   poa=True)

    # Set the deployer address from a freshly created test account
    deployer_interface.deployer_address = testerchain.etherbase_account
    return testerchain
コード例 #5
0
ファイル: fixtures.py プロジェクト: lucianstroie/nucypher
def testerchain(solidity_compiler):
    """
    https: // github.com / ethereum / eth - tester     # available-backends
    """

    temp_registrar = TemporaryEthereumContractRegistry()

    # Use the the custom provider and registrar to init an interface

    deployer_interface = BlockchainDeployerInterface(
        compiler=solidity_compiler,  # freshly recompile if not None
        registry=temp_registrar,
        provider_uri='pyevm://tester')

    # Create the blockchain
    testerchain = TesterBlockchain(interface=deployer_interface,
                                   test_accounts=10)
    origin, *everyone = testerchain.interface.w3.eth.accounts
    deployer_interface.deployer_address = origin  # Set the deployer address from a freshly created test account

    yield testerchain

    testerchain.sever_connection()
コード例 #6
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 = BlockchainDeployerInterface(
        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()

    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 = miner_escrow_deployer.make_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()

    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!")
コード例 #7
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)