示例#1
0
def test_invalid_proofs_no_proofs():

    testdb = create_reward_test_blockchain_database()

    chain = TestnetChain(testdb,
                         private_keys[0].public_key.to_canonical_address(),
                         private_keys[0])
    min_time_between_blocks = chain.get_vm(
        timestamp=Timestamp(int(time.time()))).min_time_between_blocks
    tx_list = [[
        private_keys[1], private_keys[0],
        to_wei(1, 'ether'),
        int(int(time.time()) - min_time_between_blocks * 10)
    ]]

    add_transactions_to_blockchain_db(testdb, tx_list)

    chain = TestnetChain(testdb,
                         private_keys[0].public_key.to_canonical_address(),
                         private_keys[0])

    required_number_of_proofs_for_reward_type_2_proof = chain.get_consensus_db(
        timestamp=Timestamp(int(
            time.time()))).required_number_of_proofs_for_reward_type_2_proof

    # Now we try to import the reward block with instance 0
    reward_chain = TestnetChain(
        testdb, private_keys[0].public_key.to_canonical_address(),
        private_keys[0])

    with pytest.raises(RewardAmountRoundsToZero):
        imported_block = reward_chain.import_current_queue_block_with_reward(
            [])
示例#2
0
def test_invalid_proofs_not_enough_proofs():

    testdb = create_reward_test_blockchain_database()

    chain = TestnetChain(testdb,
                         private_keys[0].public_key.to_canonical_address(),
                         private_keys[0])
    min_time_between_blocks = chain.get_vm(
        timestamp=Timestamp(int(time.time()))).min_time_between_blocks
    tx_list = [[
        private_keys[1], private_keys[0],
        to_wei(1, 'ether'),
        int(int(time.time()) - min_time_between_blocks * 10)
    ]]

    add_transactions_to_blockchain_db(testdb, tx_list)

    chain = TestnetChain(testdb,
                         private_keys[0].public_key.to_canonical_address(),
                         private_keys[0])

    required_number_of_proofs_for_reward_type_2_proof = chain.get_consensus_db(
        timestamp=Timestamp(int(
            time.time()))).required_number_of_proofs_for_reward_type_2_proof

    node_staking_scores = []

    # First score/proof with timestamp far in future
    current_private_key = private_keys[1]
    node_staking_score = NodeStakingScore(
        recipient_node_wallet_address=private_keys[0].public_key.
        to_canonical_address(),
        score=int(1000000),
        since_block_number=0,
        timestamp=int(time.time()) - 60 * 10,
        head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash(
            current_private_key.public_key.to_canonical_address()),
        v=0,
        r=0,
        s=0,
    )
    signed_node_staking_score = node_staking_score.get_signed(
        current_private_key, TESTNET_NETWORK_ID)
    node_staking_scores.append(signed_node_staking_score)

    # Now we try to import the reward block with instance 0
    reward_chain = TestnetChain(
        testdb, private_keys[0].public_key.to_canonical_address(),
        private_keys[0])

    with pytest.raises(NotEnoughProofsOrStakeForRewardType2Proof):
        reward_chain.import_current_queue_block_with_reward(
            node_staking_scores)
 def current_window(self) -> Timestamp:
     # Returns the current historical root hash window
     last_finished_window = int(
         time.time() /
         TIME_BETWEEN_HEAD_HASH_SAVE) * TIME_BETWEEN_HEAD_HASH_SAVE
     current_window = last_finished_window + TIME_BETWEEN_HEAD_HASH_SAVE
     return Timestamp(int(current_window))
示例#4
0
def test_invalid_proofs_score_too_large():

    testdb = create_reward_test_blockchain_database()

    chain = TestnetChain(testdb,
                         private_keys[0].public_key.to_canonical_address(),
                         private_keys[0])

    required_number_of_proofs_for_reward_type_2_proof = chain.get_consensus_db(
        timestamp=Timestamp(int(
            time.time()))).required_number_of_proofs_for_reward_type_2_proof

    node_staking_scores = []

    # First score/proof has a score too large
    current_private_key = private_keys[1]
    node_staking_score = NodeStakingScore(
        recipient_node_wallet_address=private_keys[0].public_key.
        to_canonical_address(),
        score=int(1000001),
        since_block_number=0,
        timestamp=int(time.time()),
        head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash(
            current_private_key.public_key.to_canonical_address()),
        v=0,
        r=0,
        s=0,
    )
    signed_node_staking_score = node_staking_score.get_signed(
        current_private_key, TESTNET_NETWORK_ID)
    node_staking_scores.append(signed_node_staking_score)

    score = 1000000
    for i in range(2, 10):
        # Second score/proof is from instance 1
        current_private_key = private_keys[i]
        node_staking_score = NodeStakingScore(
            recipient_node_wallet_address=private_keys[0].public_key.
            to_canonical_address(),
            score=int(score - i),
            since_block_number=0,
            timestamp=int(time.time()),
            head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash(
                current_private_key.public_key.to_canonical_address()),
            v=0,
            r=0,
            s=0,
        )
        signed_node_staking_score = node_staking_score.get_signed(
            current_private_key, TESTNET_NETWORK_ID)
        node_staking_scores.append(signed_node_staking_score)

    # Now we try to import the reward block with instance 0
    reward_chain = TestnetChain(
        testdb, private_keys[0].public_key.to_canonical_address(),
        private_keys[0])

    with pytest.raises(ValidationError):
        reward_chain.import_current_queue_block_with_reward(
            node_staking_scores)
def create_reward_test_blockchain_database():
    testdb = MemoryDB()

    chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY)
    coin_mature_time = chain.get_vm(timestamp=Timestamp(int(time.time()))).consensus_db.coin_mature_time_for_staking
    min_time_between_blocks = chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks
    required_stake_for_reward_type_2_proof = chain.get_consensus_db(timestamp=Timestamp(int(time.time()))).required_stake_for_reward_type_2_proof


    now = int(time.time())
    start = now - max((coin_mature_time * 2), (min_time_between_blocks * 20))
    key_balance_dict = {}
    for i in range(10):
        key_balance_dict[private_keys[i]] = (
        required_stake_for_reward_type_2_proof, start + min_time_between_blocks * i)

    create_dev_fixed_blockchain_database(testdb, key_balance_dict)
    return testdb
def test_invalid_proofs_previous_reward_block_incorrect():

    testdb = create_reward_test_blockchain_database()

    chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0])
    min_time_between_blocks = chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks
    tx_list = [[private_keys[1], private_keys[0], to_wei(1, 'ether'), int(int(time.time())-min_time_between_blocks*10)]]

    add_transactions_to_blockchain_db(testdb, tx_list)

    chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0])

    required_number_of_proofs_for_reward_type_2_proof = chain.get_consensus_db(timestamp=Timestamp(int(time.time()))).required_number_of_proofs_for_reward_type_2_proof

    node_staking_scores = []

    # First score/proof with the incorrect head hash
    current_private_key = private_keys[1]
    node_staking_score = NodeStakingScore(
        recipient_node_wallet_address=private_keys[0].public_key.to_canonical_address(),
        score=int(1000000),
        since_block_number=1,
        timestamp=int(time.time()),
        head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash(
            current_private_key.public_key.to_canonical_address()),
        v=0,
        r=0,
        s=0,
    )
    signed_node_staking_score = node_staking_score.get_signed(current_private_key, MAINNET_NETWORK_ID)
    node_staking_scores.append(signed_node_staking_score)

    score = 100000
    for i in range(2, 10):
        # Second score/proof is from instance 1
        current_private_key = private_keys[i]
        node_staking_score = NodeStakingScore(
            recipient_node_wallet_address=private_keys[0].public_key.to_canonical_address(),
            score=int(score-i),
            since_block_number=1,
            timestamp=int(time.time()),
            head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash(
                current_private_key.public_key.to_canonical_address()),
            v=0,
            r=0,
            s=0,
            )
        signed_node_staking_score = node_staking_score.get_signed(current_private_key, MAINNET_NETWORK_ID)
        node_staking_scores.append(signed_node_staking_score)

    # Now we try to import the reward block with instance 0
    reward_chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0])

    with pytest.raises(ValidationError):
        reward_chain.import_current_queue_block_with_reward(node_staking_scores)
def create_dev_test_random_blockchain_database(base_db = None, num_iterations = None, timestamp = None):
    logger.debug("generating test blockchain db")
    if base_db == None:
        base_db = MemoryDB()

    if num_iterations == None:
        num_iterations = 5

    #initialize db
    sender_chain = import_genesis_block(base_db)
    # sender_chain.chaindb.initialize_historical_minimum_gas_price_at_genesis(min_gas_price = 1, net_tpc_cap=5)\
    MIN_TIME_BETWEEN_BLOCKS = sender_chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks

    if timestamp == None:
        timestamp = int(time.time()) - num_iterations*MIN_TIME_BETWEEN_BLOCKS
    elif timestamp == "genesis":
        timestamp = MAINNET_GENESIS_PARAMS['timestamp'] + TIME_BETWEEN_HEAD_HASH_SAVE

    tx_list = []
    for i in range (num_iterations):
        if i == 0:
            numbers = [x for x in range(0, len(random_private_keys) - 1)]
            random_int = random.choice(numbers)
            privkey = GENESIS_PRIVATE_KEY
            receiver_privkey = keys.PrivateKey(random_private_keys[random_int])
        else:
            numbers = [x for x in range(0, len(random_private_keys) - 1) if x != random_int]
            random_int = random.choice(numbers)
            privkey = receiver_privkey
            receiver_privkey = keys.PrivateKey(random_private_keys[random_int])

        # random.shuffle(random_private_keys)
        # if i == 0:
        #     privkey = GENESIS_PRIVATE_KEY
        #     receiver_privkey = keys.PrivateKey(random_private_keys[0])
        # else:
        #     privkey = receiver_privkey
        #     receiver_privkey = keys.PrivateKey(random_private_keys[0])

        tx_timestamp = timestamp+i*MIN_TIME_BETWEEN_BLOCKS
        tx_list.append([privkey, receiver_privkey, 10000000 * 10 ** 18 - i * 100000 * 10 ** 18 - random.randint(0, 1000), tx_timestamp])

    print('ZZZZZZZZZZZ')
    pprint(tx_list)
    add_transactions_to_blockchain_db(base_db, tx_list)

    return base_db
示例#8
0
    async def getNewestBlocks(self,
                              num_to_return=10,
                              start_idx=0,
                              after_hash=b'',
                              chain_address=b'',
                              include_transactions: bool = False):
        '''
        Returns list of block dicts
        :param start_idx:
        :param end_idx:
        :param chain_address:
        :return:
        '''
        # block = chain.get_block_by_hash(block_hash)
        # return block_to_dict(block, include_transactions, chain)
        if num_to_return is None:
            num_to_return = 10
        if start_idx is None:
            start_idx = 0
        num_to_return = min([10, num_to_return])
        block_dicts_to_return = []

        if chain_address != b'' and chain_address is not None:
            chain = self.get_new_chain(chain_address)
            try:
                canonical_header = chain.chaindb.get_canonical_head(
                    chain_address)
                start = canonical_header.block_number - start_idx
                if start >= 0:
                    end = max([-1, start - num_to_return])
                    for i in range(start, end, -1):
                        block = chain.get_block_by_number(i, chain_address)
                        if block.hash == after_hash:
                            break
                        block_dicts_to_return.append(
                            block_to_dict(block, include_transactions, chain))

            except CanonicalHeadNotFound:
                return []
        else:
            chain = self.get_new_chain()
            at_block_index = -1
            current_window = int(
                time.time() /
                TIME_BETWEEN_HEAD_HASH_SAVE) * TIME_BETWEEN_HEAD_HASH_SAVE
            for timestamp in range(
                    current_window, current_window -
                (NUMBER_OF_HEAD_HASH_TO_SAVE * TIME_BETWEEN_HEAD_HASH_SAVE),
                    -1 * TIME_BETWEEN_HEAD_HASH_SAVE):
                chronological_blocks = chain.chain_head_db.load_chronological_block_window(
                    Timestamp(timestamp))
                if chronological_blocks is None:
                    continue
                chronological_blocks.reverse()

                for block_timestamp_block_hash in chronological_blocks:
                    at_block_index += 1
                    if at_block_index < start_idx:
                        continue

                    block = chain.get_block_by_hash(
                        block_timestamp_block_hash[1])
                    if block.hash == after_hash:
                        return block_dicts_to_return

                    block_dicts_to_return.append(
                        block_to_dict(block, include_transactions, chain))

                    if len(block_dicts_to_return) >= num_to_return:
                        return block_dicts_to_return

        return block_dicts_to_return
示例#9
0
def create_dev_test_random_blockchain_db_with_reward_blocks(base_db = None, num_iterations = 5):
    # initialize db
    if base_db == None:
        base_db = MemoryDB()


    create_dev_test_random_blockchain_database(base_db, timestamp = 'genesis')

    node_1 = TestnetChain(base_db, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), TESTNET_GENESIS_PRIVATE_KEY)

    MIN_TIME_BETWEEN_BLOCKS = node_1.get_vm(timestamp = Timestamp(int(time.time()))).min_time_between_blocks
    chain_head_hashes = node_1.chain_head_db.get_head_block_hashes_list()

    last_block_timestamp = 0
    for head_hash in chain_head_hashes:
        header = node_1.chaindb.get_block_header_by_hash(head_hash)
        if header.timestamp > last_block_timestamp:
            last_block_timestamp = header.timestamp

    private_keys_dict = {}
    for random_private_key in random_private_keys:
        priv_key = keys.PrivateKey(random_private_key)
        private_keys_dict[priv_key.public_key.to_address()] = priv_key

    private_keys_dict[TESTNET_GENESIS_PRIVATE_KEY.public_key.to_address()] = TESTNET_GENESIS_PRIVATE_KEY

    for i in range(num_iterations):

        # random_int = random.randint(0,len(private_keys_dict)-1)
        # numbers = [x in range(0, len(private_keys_dict)-1) if x != random_int]
        # random_int = random.choice(numbers)

        if i == 0:
            numbers = [x for x in range(0, len(private_keys_dict) - 1)]
            random_int = random.choice(numbers)
            privkey = TESTNET_GENESIS_PRIVATE_KEY
            receiver_privkey = private_keys_dict[list(private_keys_dict.keys())[random_int]]
        else:
            numbers = [x for x in range(0, len(private_keys_dict) - 1) if x != random_int]
            random_int = random.choice(numbers)
            privkey = receiver_privkey
            receiver_privkey = private_keys_dict[list(private_keys_dict.keys())[random_int]]


        tx_timestamp = last_block_timestamp + MIN_TIME_BETWEEN_BLOCKS+2
        tx_list = [[privkey, receiver_privkey, 10000000*10**18-i*100000*10**18-random.randint(0,1000), tx_timestamp]]


        add_transactions_to_blockchain_db(base_db, tx_list)

        node_1 = TestnetChain(base_db, privkey.public_key.to_canonical_address(), privkey)


        chain_head_hashes = node_1.chain_head_db.get_head_block_hashes_list()

        reward_block_time = tx_timestamp + node_1.get_vm(timestamp = tx_timestamp).consensus_db.min_time_between_reward_blocks+ MIN_TIME_BETWEEN_BLOCKS+2+node_1.get_vm(timestamp = tx_timestamp).consensus_db.coin_mature_time_for_staking

        # print('BBBBBBB')
        # print(node_1.get_vm(timestamp=tx_timestamp).state.account_db.get_balance(receiver_privkey.public_key.to_canonical_address()))
        # print(node_1.chaindb.get_mature_stake(receiver_privkey.public_key.to_canonical_address(), node_1.get_consensus_db(timestamp=tx_timestamp).coin_mature_time_for_staking, reward_block_time))

        node_staking_scores = []
        for head_hash in chain_head_hashes:
            address = node_1.chaindb.get_chain_wallet_address_for_block_hash(head_hash)
            if not (address == privkey.public_key.to_canonical_address()):
                after_block_number = node_1.chaindb.get_latest_reward_block_number(privkey.public_key.to_canonical_address())

                node_staking_score = NodeStakingScore(privkey.public_key.to_canonical_address(),
                                                      1,
                                                      after_block_number,
                                                      reward_block_time,
                                                      head_hash,
                                                      v=0,
                                                      r=0,
                                                      s=0)

                signed_node_staking_score = node_staking_score.get_signed(private_keys_dict[encode_hex(address)], node_1.network_id)

                node_staking_scores.append(signed_node_staking_score)

        if len(node_staking_scores) >= node_1.get_consensus_db(timestamp = tx_timestamp).required_number_of_proofs_for_reward_type_2_proof:
            # print('AAAAAAAAAAAA')
            # print(len(node_staking_scores))
            # print(node_1.get_consensus_db(timestamp = tx_timestamp).required_number_of_proofs_for_reward_type_2_proof)
            reward_bundle = node_1.get_consensus_db(timestamp=tx_timestamp).create_reward_bundle_for_block(privkey.public_key.to_canonical_address(),
                                                                   node_staking_scores,
                                                                   reward_block_time)


            valid_block = create_valid_block_at_timestamp(base_db, privkey, reward_bundle = reward_bundle, timestamp = reward_block_time)

            assert(valid_block.header.timestamp == reward_block_time)
            node_1.import_block(valid_block)

        last_block_timestamp = reward_block_time


    return base_db
示例#10
0
 def earliest_window(self) -> Timestamp:
     # Returns the earliest historical root hash window
     earliest_window = self.current_window - TIME_BETWEEN_HEAD_HASH_SAVE * NUMBER_OF_HEAD_HASH_TO_SAVE
     return Timestamp(int(earliest_window))
def _test_airdrop_calling_erc_20():

    # testdb = LevelDB('/home/tommy/.local/share/helios/instance_test/mainnet/chain/full/')
    # testdb = JournalDB(testdb)
    testdb = MemoryDB()
    chain = TestnetChain(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        TESTNET_GENESIS_PRIVATE_KEY)
    coin_mature_time = chain.get_vm(timestamp=Timestamp(int(
        time.time()))).consensus_db.coin_mature_time_for_staking

    genesis_params, genesis_state = create_new_genesis_params_and_state(
        TESTNET_GENESIS_PRIVATE_KEY, 1000000 * 10**18,
        int(time.time()) - coin_mature_time * 10000)

    # import genesis block
    chain = TestnetChain.from_genesis(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        genesis_params, genesis_state, TESTNET_GENESIS_PRIVATE_KEY)

    #
    # erc20 contract deploy
    #

    compiled_erc20_sol = load_compiled_sol_dict(
        'contract_data/erc20_compiled.pkl')

    EXPECTED_TOTAL_SUPPLY = 10000000000000000000000

    erc20_contract_interface = compiled_erc20_sol[
        'contract_data/erc20.sol:SimpleToken']

    w3 = Web3()

    SimpleToken = w3.eth.contract(abi=erc20_contract_interface['abi'],
                                  bytecode=erc20_contract_interface['bin'])

    # Build transaction to deploy the contract
    w3_erc20_tx = SimpleToken.constructor().buildTransaction(W3_TX_DEFAULTS)

    max_gas = 20000000

    chain.create_and_sign_transaction_for_queue_block(
        gas_price=0x01,
        gas=max_gas,
        to=CREATE_CONTRACT_ADDRESS,
        value=0,
        data=decode_hex(w3_erc20_tx['data']),
        v=0,
        r=0,
        s=0)

    #time.sleep(1)
    print("deploying erc20 smart contract")
    imported_block = chain.import_current_queue_block()

    #now we need to add the block to the smart contract
    list_of_smart_contracts = chain.get_vm(
    ).state.account_db.get_smart_contracts_with_pending_transactions()
    erc20_contract_address = list_of_smart_contracts[0]

    chain = TestnetChain(testdb, erc20_contract_address, private_keys[0])

    chain.populate_queue_block_with_receive_tx()
    imported_block = chain.import_current_queue_block()

    #
    # airdrop contract deploy
    #
    compiled_airdrop_sol = load_compiled_sol_dict(
        'contract_data/airdrop_compiled.pkl')

    EXPECTED_TOTAL_SUPPLY = 10000000000000000000000

    airdrop_contract_interface = compiled_airdrop_sol[
        'contract_data/airdrop.sol:Airdrop']

    Airdrop = w3.eth.contract(abi=airdrop_contract_interface['abi'],
                              bytecode=airdrop_contract_interface['bin'])

    # Build transaction to deploy the contract
    w3_airdrop_tx = Airdrop.constructor().buildTransaction(W3_TX_DEFAULTS)

    chain = TestnetChain(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        TESTNET_GENESIS_PRIVATE_KEY)

    chain.create_and_sign_transaction_for_queue_block(
        gas_price=0x01,
        gas=max_gas,
        to=CREATE_CONTRACT_ADDRESS,
        value=0,
        data=decode_hex(w3_airdrop_tx['data']),
        v=0,
        r=0,
        s=0)

    print("deploying airdrop smart contract")
    imported_block = chain.import_current_queue_block()

    # now we need to add the block to the smart contract
    list_of_smart_contracts = chain.get_vm(
    ).state.account_db.get_smart_contracts_with_pending_transactions()
    airdrop_contract_address = list_of_smart_contracts[0]

    chain = TestnetChain(testdb, airdrop_contract_address, private_keys[0])

    chain.populate_queue_block_with_receive_tx()
    imported_block = chain.import_current_queue_block()

    #
    # Interacting with deployed smart contract step 1) add send transaction
    #
    chain = TestnetChain(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        TESTNET_GENESIS_PRIVATE_KEY)

    print(erc20_contract_interface['abi'])
    simple_token = w3.eth.contract(
        address=Web3.toChecksumAddress(erc20_contract_address),
        abi=erc20_contract_interface['abi'],
    )

    airdrop_token_balance = 1000

    w3_erc20_send = simple_token.functions.transfer(
        Web3.toChecksumAddress(airdrop_contract_address),
        airdrop_token_balance).buildTransaction(W3_TX_DEFAULTS)

    chain.create_and_sign_transaction_for_queue_block(
        gas_price=0x01,
        gas=max_gas,
        to=erc20_contract_address,
        value=0,
        data=decode_hex(w3_erc20_send['data']),
        v=0,
        r=0,
        s=0)
    imported_block = chain.import_current_queue_block()

    chain = TestnetChain(testdb, erc20_contract_address, private_keys[0])
    chain.populate_queue_block_with_receive_tx()
    imported_block = chain.import_current_queue_block()

    from pprint import pprint
    receipt = chain.chaindb.get_receipts(imported_block.header, Receipt)[0]

    receipt_dict = format_receipt_for_web3_to_extract_events(
        receipt, imported_block.receive_transactions[0].hash, chain)

    rich_logs = simple_token.events.Transfer().processReceipt(receipt_dict)
    print(rich_logs)
    print(rich_logs[0]['args'])
    print('a')

    assert (to_int(
        chain.chaindb.get_receipts(
            imported_block.header,
            Receipt)[0].logs[0].data) == airdrop_token_balance)

    chain = TestnetChain(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        TESTNET_GENESIS_PRIVATE_KEY)

    w3_erc20_balance = simple_token.functions.balanceOf(
        Web3.toChecksumAddress(airdrop_contract_address)).buildTransaction(
            W3_TX_DEFAULTS)

    chain.create_and_sign_transaction_for_queue_block(
        gas_price=0x01,
        gas=max_gas,
        to=erc20_contract_address,
        value=0,
        data=decode_hex(w3_erc20_balance['data']),
        v=0,
        r=0,
        s=0)
    imported_block = chain.import_current_queue_block()

    chain = TestnetChain(testdb, erc20_contract_address, private_keys[0])
    chain.populate_queue_block_with_receive_tx()
    imported_block = chain.import_current_queue_block()

    print(chain.chaindb.get_receipts(imported_block.header, Receipt)[0].logs)

    exit()
    #now lets look at the reciept to see the result
    assert (to_int(
        chain.chaindb.get_receipts(
            imported_block.header,
            Receipt)[0].logs[0].data) == EXPECTED_TOTAL_SUPPLY)
    print("Total supply call gave expected result!")
    gas_used = to_int(
        chain.chaindb.get_receipts(imported_block.header, Receipt)[0].gas_used)

    #
    # Interacting with deployed smart contract step 3) Receiving refund of extra gas that wasn't used in the computation
    #
    initial_balance = chain.get_vm().state.account_db.get_balance(
        TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    chain = TestnetChain(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        TESTNET_GENESIS_PRIVATE_KEY)
    chain.populate_queue_block_with_receive_tx()
    imported_block = chain.import_current_queue_block()
    final_balance = chain.get_vm().state.account_db.get_balance(
        TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    assert ((final_balance - initial_balance) == (max_gas - gas_used))
    print("Refunded gas is the expected amount.")


# test_airdrop_calling_erc_20()
def test_talamus_contract():
    absolute_dir = os.path.dirname(os.path.realpath(__file__))
    testdb = LevelDB(absolute_dir + "/predefined_databases/talamus_test")

    testdb = ReadOnlyDB(testdb)
    talamus_contract_address = decode_hex(
        '0x81bdf63b9a6e871f560dca1d55e8732b5ccdc2f9')

    print(private_keys[0].public_key.to_checksum_address())
    chain = TestnetChain(testdb,
                         private_keys[0].public_key.to_canonical_address(),
                         private_keys[0])

    min_time_between_blocks = chain.get_vm(
        timestamp=Timestamp(int(time.time()))).min_time_between_blocks

    COMPILED_SOLIDITY_FILE = load_compiled_sol_dict(
        'contract_data/talamus_compiled.pkl')
    SOLIDITY_SRC_FILE = 'contract/talamus.sol'

    contract_interface = COMPILED_SOLIDITY_FILE['{}:TalamusHealth'.format(
        SOLIDITY_SRC_FILE)]

    w3 = Web3()

    talamus_contract = w3.eth.contract(abi=contract_interface['abi'],
                                       bytecode=contract_interface['bin'])

    max_gas = 2000000
    w3_tx_params = {
        'gas': max_gas,
        'gasPrice': to_wei(2, 'gwei'),
        'chainId': 2,
        'to': talamus_contract_address,
        'value': 0,
        'nonce': 1
    }

    # from rpc
    # {'gasPrice': 2000000000, 'chainId': 2, 'gas': 2000000, 'to': b'\x81\xbd\xf6;\x9an\x87\x1fV\r\xca\x1dU\xe8s+\\\xcd\xc2\xf9', 'value': 0, 'data': '0x010f836e0000000000000000000000000000000000000000000000000000000000000000', 'nonce': 1}
    # us
    # {'gas': 2000000, 'gasPrice': 2000000000, 'chainId': 2, 'to': b'\x81\xbd\xf6;\x9an\x87\x1fV\r\xca\x1dU\xe8s+\\\xcd\xc2\xf9', 'value': 0, 'data': '0x010f836e0000000000000000000000000000000000000000000000000000000000000000'}

    hash_to_save = Hash32(32 * b'\x00')

    w3_tx = talamus_contract.functions.saveHash(hash_to_save).buildTransaction(
        w3_tx_params)

    print(w3_tx)

    # tx = chain.create_and_sign_transaction_for_queue_block(
    #     gas_price=w3_tx['gasPrice'],
    #     gas=w3_tx['gas'],
    #     to=w3_tx['to'],
    #     value=w3_tx['value'],
    #     data=decode_hex(w3_tx['data']),
    #     nonce=1,
    #     v=0,
    #     r=0,
    #     s=0
    # )

    tx = chain.create_and_sign_transaction_for_queue_block(
        gas_price=w3_tx['gasPrice'],
        gas=w3_tx['gas'],
        to=w3_tx['to'],
        value=w3_tx['value'],
        data=
        b'0x010f836e0000000000000000000000000000000000000000000000000000000000000000',
        nonce=1,
        v=0,
        r=0,
        s=0)

    print('ZZZZZZZZZZZZZZZZZZZZZZZZZZZ')
    print(tx.as_dict())

    # from rpc
    # {'nonce': 1, 'gas_price': 2000000000, 'gas': 2000000, 'to': b'\x81\xbd\xf6;\x9an\x87\x1fV\r\xca\x1dU\xe8s+\\\xcd\xc2\xf9', 'value': 0, 'data': b'0x010f836e0000000000000000000000000000000000000000000000000000000000000000', 'v': 38, 'r': 77546672203976404837758472880488256719656950035867254665717724200250517648493, 's': 2580236846734574215375389852957773325366136635134534812926657997746477469836}
    # from us
    # {'nonce': 1, 'gas_price': 2000000000, 'gas': 2000000, 'to': b'\x81\xbd\xf6;\x9an\x87\x1fV\r\xca\x1dU\xe8s+\\\xcd\xc2\xf9', 'value': 0, 'data': b'\x01\x0f\x83n\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 'v': 39, 'r': 39349908228946674104603389597151977495442914775500474614266302539829498168651, 's': 23552581665426625568029915589486661695498739587988697017071052606525926751079}

    chain.import_current_queue_block()

    contract_chain = TestnetChain(ReadOnlyDB(testdb), talamus_contract_address,
                                  private_keys[0])

    receivable_transactions = contract_chain.get_vm(
    ).state.account_db.get_receivable_transactions(talamus_contract_address)
    print('receivable_transactions before imported into contract chain')
    print(receivable_transactions)

    contract_chain.populate_queue_block_with_receive_tx()
    contract_block = contract_chain.import_current_queue_block()

    contract_chain = TestnetChain(testdb, talamus_contract_address,
                                  private_keys[0])
    contract_chain.import_block(contract_block)

    contract_chain = TestnetChain(testdb, talamus_contract_address,
                                  private_keys[0])

    receivable_transactions = contract_chain.get_vm(
    ).state.account_db.get_receivable_transactions(talamus_contract_address)
    print('receivable_transactions after imported into contract chain')
    print(receivable_transactions)
def test_invalid_proofs_not_enough_stake():
    testdb = MemoryDB()

    chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY)
    coin_mature_time = chain.get_vm(timestamp=Timestamp(int(time.time()))).consensus_db.coin_mature_time_for_staking
    min_time_between_blocks = chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks
    now = int(time.time())
    start = now - max((coin_mature_time * 2), (min_time_between_blocks * 20))
    key_balance_dict = {
        private_keys[0]: (to_wei(1, 'ether'), start),
        private_keys[1]: (to_wei(1, 'ether'), start + min_time_between_blocks * 1),
        private_keys[2]: (to_wei(1, 'ether'), start + min_time_between_blocks * 2),
        private_keys[3]: (to_wei(1, 'ether'), start + min_time_between_blocks * 3),
        private_keys[4]: (to_wei(1, 'ether'), start + min_time_between_blocks * 4),
        private_keys[5]: (to_wei(1, 'ether'), start + min_time_between_blocks * 5),
        private_keys[6]: (to_wei(1, 'ether'), start + min_time_between_blocks * 6),
        private_keys[7]: (to_wei(1, 'ether'), start + min_time_between_blocks * 7),
        private_keys[8]: (to_wei(1, 'ether'), start + min_time_between_blocks * 8),
        private_keys[9]: (to_wei(1, 'ether'), now - coin_mature_time + 1),  # immature
    }
    create_dev_fixed_blockchain_database(testdb, key_balance_dict)

    chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0])

    node_staking_scores = []

    # First score/proof with timestamp far in future
    current_private_key = private_keys[1]
    node_staking_score = NodeStakingScore(
        recipient_node_wallet_address=private_keys[0].public_key.to_canonical_address(),
        score=int(1000000),
        since_block_number=0,
        timestamp=int(time.time())-60*10,
        head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash(
            current_private_key.public_key.to_canonical_address()),
        v=0,
        r=0,
        s=0,
    )
    signed_node_staking_score = node_staking_score.get_signed(current_private_key, MAINNET_NETWORK_ID)
    node_staking_scores.append(signed_node_staking_score)

    score = 100000
    for i in range(2, 10):
        # Second score/proof is from instance 1
        current_private_key = private_keys[i]
        node_staking_score = NodeStakingScore(
            recipient_node_wallet_address=private_keys[0].public_key.to_canonical_address(),
            score=int(score-i),
            since_block_number=1,
            timestamp=int(time.time()),
            head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash(
                current_private_key.public_key.to_canonical_address()),
            v=0,
            r=0,
            s=0,
            )
        signed_node_staking_score = node_staking_score.get_signed(current_private_key, MAINNET_NETWORK_ID)
        node_staking_scores.append(signed_node_staking_score)

    # Now we try to import the reward block with instance 0
    reward_chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0])

    with pytest.raises(NotEnoughProofsOrStakeForRewardType2Proof):
        reward_chain.import_current_queue_block_with_reward(node_staking_scores)
def _test_block_rewards_system():
    #The genesis chain will be adding a reward block. We need to generate fake NodeStakingScores from a bunch of other
    #nodes

    # testdb = LevelDB('/home/tommy/.local/share/helios/instance_test/mainnet/chain/full/')
    # testdb = JournalDB(testdb)
    testdb = create_reward_test_blockchain_database()

    chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY)
    coin_mature_time = chain.get_vm(timestamp=Timestamp(int(time.time()))).consensus_db.coin_mature_time_for_staking
    min_time_between_blocks = chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks
    # now = int(time.time())
    # start = now - max((coin_mature_time * 2), (min_time_between_blocks*20))
    # key_balance_dict = {
    #     private_keys[0]: (to_wei(10, 'ether'), start),
    #     private_keys[1]: (to_wei(200, 'ether'), start + min_time_between_blocks * 1),
    #     private_keys[2]: (to_wei(340, 'ether'), start + min_time_between_blocks * 2),
    #     private_keys[3]: (to_wei(1000, 'ether'), start + min_time_between_blocks * 3),
    #     private_keys[4]: (to_wei(1400, 'ether'), start + min_time_between_blocks * 4),
    #     private_keys[5]: (to_wei(2400, 'ether'), start + min_time_between_blocks * 5),
    #     private_keys[6]: (to_wei(3000, 'ether'), start + min_time_between_blocks * 6),
    #     private_keys[7]: (to_wei(4000, 'ether'), start + min_time_between_blocks * 7),
    #     private_keys[8]: (to_wei(1000, 'ether'), start + min_time_between_blocks * 8),
    #     private_keys[9]: (to_wei(10000, 'ether'), now-coin_mature_time+1),# immature
    # }
    # create_dev_fixed_blockchain_database(testdb, key_balance_dict)

    chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY)

    # class NodeStakingScore(rlp.Serializable, metaclass=ABCMeta):
    #     fields = [
    #         ('recipient_node_wallet_address', address),
    #         ('score', f_big_endian_int),
    #         ('since_block_number', f_big_endian_int),
    #         ('timestamp', f_big_endian_int),
    #         ('v', big_endian_int),
    #         ('r', big_endian_int),
    #         ('s', big_endian_int),
    #     ]

    node_staking_scores = []

    score = 1000000
    for private_key in private_keys:
        node_staking_score = NodeStakingScore(recipient_node_wallet_address = GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
                                              score = int(score),
                                              since_block_number = 0,
                                              timestamp = int(time.time()),
                                              head_hash_of_sender_chain = chain.chaindb.get_canonical_head_hash(private_key.public_key.to_canonical_address()),
                                              v = 0,
                                              r = 0,
                                              s = 0,
                                              )
        signed_node_staking_score = node_staking_score.get_signed(private_key,MAINNET_NETWORK_ID)
        node_staking_scores.append(signed_node_staking_score)
        score = score/5

    chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY)

    node_staking_scores.sort(key=lambda x: -1* x.score)
    for node_staking_score in node_staking_scores:
        node_staking_score.validate()
        print(node_staking_score.is_signature_valid)
        print(node_staking_score.sender)
        print(node_staking_score.score, chain.get_mature_stake(node_staking_score.sender, node_staking_score.timestamp))


    reward_bundle = chain.get_consensus_db().create_reward_bundle_for_block(GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), node_staking_scores, at_timestamp = int(time.time()))


    chain.get_consensus_db().validate_reward_bundle(reward_bundle, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), int(time.time()))

    print('AAAAAAAAAAA')
    print(reward_bundle.reward_type_1.amount)
    print(reward_bundle.reward_type_2.amount)
    print(reward_bundle.reward_type_2.proof[0].score)


    initial_balance = chain.get_vm().state.account_db.get_balance(GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    print("balance before reward = ", initial_balance)

    chain.import_current_queue_block_with_reward(reward_bundle.reward_type_2.proof)

    final_balance = chain.get_vm().state.account_db.get_balance(GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    print("balance after reward = ",final_balance)
    assert((reward_bundle.reward_type_1.amount + reward_bundle.reward_type_2.amount) == (final_balance- initial_balance))

    print("waiting {} seconds before importing the next block".format(min_time_between_blocks))
    time.sleep(min_time_between_blocks)

    proof_chain = MainnetChain(testdb, private_keys[1].public_key.to_canonical_address(), private_keys[1])
    mature_stake = proof_chain.get_mature_stake()
    print("proof chain mature stake")
    print(mature_stake)

    staking_score = proof_chain.get_signed_peer_score_string_private_key(private_keys[1].to_bytes(), private_keys[0].public_key.to_canonical_address())
    staking_score = staking_score.copy(score=1532)
    staking_score = staking_score.get_signed(private_keys[1], proof_chain.network_id)
    print('staking score')
    print(staking_score.score)

    # fields = [
    #     ('recipient_node_wallet_address', address),
    #     ('score', f_big_endian_int),  # a score out of 1,000,000
    #     ('since_block_number', f_big_endian_int),
    #     ('timestamp', f_big_endian_int),
    #     ('head_hash_of_sender_chain', hash32),
    #     ('v', big_endian_int),
    #     ('r', big_endian_int),
    #     ('s', big_endian_int),
    # ]
    #
    reward_chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0])
    reward_bundle = reward_chain.get_consensus_db().create_reward_bundle_for_block(private_keys[0].public_key.to_canonical_address(), [staking_score],at_timestamp=Timestamp(int(time.time())))
    print("reward type 2 amount")
    print(reward_bundle.reward_type_2.amount)
    print("reward type 2 proof")
    print(reward_bundle.reward_type_2.proof)
    reward_chain.import_current_queue_block_with_reward([staking_score])

    # todo: this will fail if the reward block time is too long. Need to manually set it to a small number for the test... or manually make the blocks older?
    print("waiting {} seconds before importing the next block".format(min_time_between_blocks))
    time.sleep(min_time_between_blocks)

    proof_chain = MainnetChain(testdb, private_keys[1].public_key.to_canonical_address(), private_keys[1])
    mature_stake = proof_chain.get_mature_stake()
    print("proof chain mature stake")
    print(mature_stake)

    staking_score = proof_chain.get_signed_peer_score_string_private_key(private_keys[1].to_bytes(), private_keys[
        0].public_key.to_canonical_address())
    staking_score = staking_score.copy(score=1000000)
    staking_score = staking_score.get_signed(private_keys[1], proof_chain.network_id)
    print('staking score')
    print(staking_score.score)

    # fields = [
    #     ('recipient_node_wallet_address', address),
    #     ('score', f_big_endian_int),  # a score out of 1,000,000
    #     ('since_block_number', f_big_endian_int),
    #     ('timestamp', f_big_endian_int),
    #     ('head_hash_of_sender_chain', hash32),
    #     ('v', big_endian_int),
    #     ('r', big_endian_int),
    #     ('s', big_endian_int),
    # ]
    #
    reward_chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0])
    reward_bundle = reward_chain.get_consensus_db().create_reward_bundle_for_block(
        private_keys[0].public_key.to_canonical_address(), [staking_score], at_timestamp=Timestamp(int(time.time())))
    print("reward type 2 amount")
    print(reward_bundle.reward_type_2.amount)
    print("reward type 2 proof")
    print(reward_bundle.reward_type_2.proof)
    reward_chain.import_current_queue_block_with_reward([staking_score])
示例#15
0
 def current_window(self) -> Timestamp:
     last_finished_window = int(time.time() / TIME_BETWEEN_HEAD_HASH_SAVE) * TIME_BETWEEN_HEAD_HASH_SAVE
     current_window = last_finished_window + TIME_BETWEEN_HEAD_HASH_SAVE
     return Timestamp(int(current_window))
def test_erc_20_smart_contract_deploy_system():

    # testdb = LevelDB('/home/tommy/.local/share/helios/instance_test/mainnet/chain/full/')
    # testdb = JournalDB(testdb)
    testdb = MemoryDB()
    chain = TestnetChain(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        TESTNET_GENESIS_PRIVATE_KEY)
    coin_mature_time = chain.get_vm(timestamp=Timestamp(int(
        time.time()))).consensus_db.coin_mature_time_for_staking

    now = int(time.time())
    key_balance_dict = {
        private_keys[0]: (1000000000000, now - coin_mature_time * 10 - 100)
    }
    create_dev_fixed_blockchain_database(testdb, key_balance_dict)

    chain = TestnetChain(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        TESTNET_GENESIS_PRIVATE_KEY)

    min_time_between_blocks = chain.get_vm(
        timestamp=Timestamp(int(time.time()))).min_time_between_blocks
    for private_key, balance_time in key_balance_dict.items():
        assert (chain.get_vm().state.account_db.get_balance(
            private_key.public_key.to_canonical_address()) == balance_time[0])

    SOLIDITY_SRC_FILE = 'contract_data/erc20.sol'
    EXPECTED_TOTAL_SUPPLY = 10000000000000000000000

    #compiled_sol = compile_files([SOLIDITY_SRC_FILE])

    compiled_sol = load_compiled_sol_dict('contract_data/erc20_compiled.pkl')

    contract_interface = compiled_sol['{}:SimpleToken'.format(
        SOLIDITY_SRC_FILE)]

    w3 = Web3()

    SimpleToken = w3.eth.contract(abi=contract_interface['abi'],
                                  bytecode=contract_interface['bin'])

    # Build transaction to deploy the contract
    w3_tx1 = SimpleToken.constructor().buildTransaction(W3_TX_DEFAULTS)

    max_gas = 20000000

    chain.create_and_sign_transaction_for_queue_block(
        gas_price=0x01,
        gas=max_gas,
        to=CREATE_CONTRACT_ADDRESS,
        value=0,
        data=decode_hex(w3_tx1['data']),
        v=0,
        r=0,
        s=0)

    #time.sleep(1)
    print("deploying smart contract")

    initial_balance = chain.get_vm().state.account_db.get_balance(
        TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    imported_block = chain.import_current_queue_block()
    final_balance = chain.get_vm().state.account_db.get_balance(
        TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    gas_used = to_int(
        chain.chaindb.get_receipts(imported_block.header, Receipt)[0].gas_used)
    assert ((initial_balance - final_balance) == gas_used)

    print(TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    print(
        generate_contract_address(
            TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
            imported_block.transactions[0].nonce))
    print(
        chain.chaindb.get_receipts(imported_block.header,
                                   Receipt)[0].logs[0].address)

    #contractAddress

    print("Used the correct amount of gas.")

    #now we need to add the block to the smart contract
    list_of_smart_contracts = chain.get_vm(
    ).state.account_db.get_smart_contracts_with_pending_transactions()
    deployed_contract_address = list_of_smart_contracts[0]
    print(list_of_smart_contracts)

    chain = TestnetChain(testdb, deployed_contract_address, private_keys[0])

    chain.populate_queue_block_with_receive_tx()
    imported_block = chain.import_current_queue_block()

    list_of_smart_contracts = chain.get_vm(
    ).state.account_db.get_smart_contracts_with_pending_transactions()
    print(list_of_smart_contracts)

    #lets make sure it didn't create a refund transaction for the initial sender.
    print(chain.get_vm().state.account_db.has_receivable_transactions(
        TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address()))

    # print('ASDASD')
    # print(chain.chaindb.get_receipts(imported_block.header, Receipt)[0].logs[0].data)

    #
    # Interacting with deployed smart contract step 1) add send transaction
    #
    chain = TestnetChain(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        TESTNET_GENESIS_PRIVATE_KEY)

    simple_token = w3.eth.contract(
        address=Web3.toChecksumAddress(deployed_contract_address),
        abi=contract_interface['abi'],
    )

    w3_tx2 = simple_token.functions.totalSupply().buildTransaction(
        W3_TX_DEFAULTS)

    chain.create_and_sign_transaction_for_queue_block(
        gas_price=0x01,
        gas=max_gas,
        to=deployed_contract_address,
        value=0,
        data=decode_hex(w3_tx2['data']),
        v=0,
        r=0,
        s=0)

    #lets make sure it subtracts the entire max gas
    initial_balance = chain.get_vm().state.account_db.get_balance(
        TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address())

    print("waiting {} seconds before importing next block".format(
        min_time_between_blocks))
    time.sleep(min_time_between_blocks)
    chain.import_current_queue_block()
    final_balance = chain.get_vm().state.account_db.get_balance(
        TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    assert ((initial_balance - final_balance) == max_gas)

    #
    # Interacting with deployed smart contract step 2) add receive transaction to smart contract chain
    #

    chain = TestnetChain(testdb, deployed_contract_address, private_keys[0])
    chain.populate_queue_block_with_receive_tx()

    receivable_transactions = chain.get_vm(
    ).state.account_db.get_receivable_transactions(deployed_contract_address)
    print('receivable_transactions before imported into contract chain')
    print(receivable_transactions)

    print("waiting {} seconds before importing next block".format(
        min_time_between_blocks))
    time.sleep(min_time_between_blocks)
    imported_block = chain.import_current_queue_block()

    receipt = chain.chaindb.get_receipts(imported_block.header, Receipt)[0]
    receipt_dict = format_receipt_for_web3_to_extract_events(
        receipt, imported_block.receive_transactions[0].hash, chain)

    rich_logs = simple_token.events.Print().processReceipt(receipt_dict)
    print(rich_logs[0]['args'])
    print('a')

    #now lets look at the reciept to see the result
    assert (to_int(
        chain.chaindb.get_receipts(
            imported_block.header,
            Receipt)[0].logs[0].data) == EXPECTED_TOTAL_SUPPLY)
    print("Total supply call gave expected result!")
    gas_used = to_int(
        chain.chaindb.get_receipts(imported_block.header, Receipt)[0].gas_used)

    #
    # Interacting with deployed smart contract step 3) Receiving refund of extra gas that wasn't used in the computation
    #
    initial_balance = chain.get_vm().state.account_db.get_balance(
        TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    chain = TestnetChain(
        testdb, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        TESTNET_GENESIS_PRIVATE_KEY)

    #
    # Make sure the receive transaction is no longer in the account receivable
    #
    receivable_transactions = chain.get_vm(
    ).state.account_db.get_receivable_transactions(deployed_contract_address)
    print('receivable_transactions after imported into contract chain')
    print(receivable_transactions)

    chain.populate_queue_block_with_receive_tx()

    print("waiting {} seconds before importing next block".format(
        min_time_between_blocks))
    time.sleep(min_time_between_blocks)
    imported_block = chain.import_current_queue_block()
    final_balance = chain.get_vm().state.account_db.get_balance(
        TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address())
    assert ((final_balance - initial_balance) == (max_gas - gas_used))
    print("Refunded gas is the expected amount.")
示例#17
0
 def earliest_window(self) -> Timestamp:
     earliest_window = self.current_window-TIME_BETWEEN_HEAD_HASH_SAVE*NUMBER_OF_HEAD_HASH_TO_SAVE
     return Timestamp(int(earliest_window))
def test_get_receipts():
    testdb2 = MemoryDB()

    MainnetChain.from_genesis(
        testdb2, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(),
        MAINNET_GENESIS_PARAMS, MAINNET_GENESIS_STATE)
    """
    Create some receive transactions for RECEIVER
    """
    sender_chain = MainnetChain(testdb2,
                                SENDER.public_key.to_canonical_address(),
                                SENDER)

    min_time_between_blocks = sender_chain.get_vm(
        timestamp=Timestamp(int(time.time()))).min_time_between_blocks
    for i in range(6):
        sender_chain.create_and_sign_transaction_for_queue_block(
            gas_price=i + 1,
            gas=0x0c3500,
            to=RECEIVER.public_key.to_canonical_address(),
            value=i + 100000000000,
            data=b"",
            v=0,
            r=0,
            s=0)

    sender_chain.import_current_queue_block()
    receiver_chain = MainnetChain(testdb2,
                                  RECEIVER.public_key.to_canonical_address(),
                                  RECEIVER)
    receiver_chain.populate_queue_block_with_receive_tx()
    imported_block_1 = receiver_chain.import_current_queue_block()
    """
    Create some send transactions for RECEIVER
    """
    receiver_chain = MainnetChain(testdb2,
                                  RECEIVER.public_key.to_canonical_address(),
                                  RECEIVER)
    for i in range(6):
        receiver_chain.create_and_sign_transaction_for_queue_block(
            gas_price=i + 1,
            gas=0x0c3500,
            to=SENDER.public_key.to_canonical_address(),
            value=i,
            data=b"",
            v=0,
            r=0,
            s=0)
    """
    Create a transaction with data in it.
    """
    compiled_sol = load_compiled_sol_dict('contract_data/erc20_compiled.pkl')

    contract_interface = compiled_sol['contract_data/erc20.sol:SimpleToken']

    w3 = Web3()

    SimpleToken = w3.eth.contract(abi=contract_interface['abi'],
                                  bytecode=contract_interface['bin'])

    # Build transaction to deploy the contract
    w3_tx1 = SimpleToken.constructor().buildTransaction(W3_TX_DEFAULTS)

    from hvm.constants import CREATE_CONTRACT_ADDRESS

    receiver_chain.create_and_sign_transaction_for_queue_block(
        gas_price=0x01,
        gas=1375666,
        to=CREATE_CONTRACT_ADDRESS,
        value=0,
        data=decode_hex(w3_tx1['data']),
        v=0,
        r=0,
        s=0)

    receiver_chain.populate_queue_block_with_receive_tx()

    print("waiting {} seconds before importing next block".format(
        min_time_between_blocks))
    time.sleep(min_time_between_blocks)
    imported_block = receiver_chain.import_current_queue_block()

    for i in range(7):
        if i < 6:
            receipt = sender_chain.chaindb.get_transaction_receipt(
                imported_block.transactions[i].hash)
            assert (receipt.status_code == b'\x01')
            assert (receipt.gas_used == GAS_TX)
            assert (receipt.bloom == 0)
            assert (receipt.logs == ())
        if i == 6:
            receipt = sender_chain.chaindb.get_transaction_receipt(
                imported_block.transactions[i].hash)
            assert (receipt.status_code == b'\x01')
            assert (receipt.gas_used == 1375666)
            assert (
                receipt.bloom ==
                243379359099696592952569079439667912256345493617967967903663341910531480774353059570732838085077727505416158987674861080353852392619637689071728561054211502067278701792094127192831079015338935810676425927305370163403783027301927515372719270157454901551766020292792184739669125690737609931485501648741152187826071626833444578979111366057983284511641401113379885201162016756050289195516614302086913696386892161910800529278878068496138240
            )
            assert (len(receipt.logs) == 1)

    for i in range(6):
        receipt = sender_chain.chaindb.get_transaction_receipt(
            imported_block_1.receive_transactions[i].hash)
        assert (receipt.status_code == b'\x01')
        assert (receipt.gas_used == 0)
        assert (receipt.bloom == 0)
        assert (receipt.logs == ())


# test_get_receipts()