Esempio n. 1
0
 def __init__(self,
              shard_id=0,
              expected_period_number=0,
              period_start_prevhash=utils.sha3rlp([]),
              parent_collation_hash=utils.sha3rlp([]),
              tx_list_root=trie.BLANK_ROOT,
              coinbase=sharding_config['GENESIS_COINBASE'],
              post_state_root=trie.BLANK_ROOT,
              receipts_root=trie.BLANK_ROOT,
              sig=''):
     fields = {k: v for k, v in locals().items() if k != 'self'}
     if len(fields['coinbase']) == 40:
         fields['coinbase'] = decode_hex(fields['coinbase'])
     assert len(fields['coinbase']) == 20
     super(CollationHeader, self).__init__(**fields)
Esempio n. 2
0
 def __init__(self,
              prevhash=default_config['GENESIS_PREVHASH'],
              uncles_hash=utils.sha3rlp([]),
              coinbase=default_config['GENESIS_COINBASE'],
              state_root=trie.BLANK_ROOT,
              tx_list_root=trie.BLANK_ROOT,
              receipts_root=trie.BLANK_ROOT,
              bloom=0,
              difficulty=default_config['GENESIS_DIFFICULTY'],
              number=0,
              gas_limit=default_config['GENESIS_GAS_LIMIT'],
              gas_used=0,
              timestamp=0,
              extra_data=b'',
              mixhash=default_config['GENESIS_MIXHASH'],
              nonce=b''):
     # at the beginning of a method, locals() is a dict of all arguments
     fields = {
         k: v
         for k, v in locals().items() if k not in ['self', '__class__']
     }
     if len(fields['coinbase']) == 40:
         fields['coinbase'] = decode_hex(fields['coinbase'])
     assert len(fields['coinbase']) == 20
     self.block = None
     super(BlockHeader, self).__init__(**fields)
Esempio n. 3
0
 def __init__(self,
              shard_id=int_to_big_endian(0),
              prev_state_root=trie.BLANK_ROOT,
              tx_list_root=trie.BLANK_ROOT,
              coinbase=sharding_config['GENESIS_COINBASE'],
              post_state_root=trie.BLANK_ROOT,
              receipt_root=trie.BLANK_ROOT,
              children=[],
              state_branch_node=utils.sha3rlp([]),
              signatures=[],
              mixhash='',
              nonce='',
              source_block_numeber=int_to_big_endian(0),
              source_block_hash=utils.sha3rlp([])):
     fields = {k: v for k, v in locals().items() if k != 'self'}
     if len(fields['coinbase']) == 40:
         fields['coinbase'] = decode_hex(fields['coinbase'])
     assert len(fields['coinbase']) == 20
     super(CollationHeader, self).__init__(**fields)
Esempio n. 4
0
 def __init__(self,
              shard_id=int_to_big_endian(0),
              prev_state_root=trie.BLANK_ROOT,
              tx_list_root=trie.BLANK_ROOT,
              coinbase=sharding_config['GENESIS_COINBASE'],
              post_state_root=trie.BLANK_ROOT,
              receipt_root=trie.BLANK_ROOT,
              children=[],
              state_branch_node=utils.sha3rlp([]),
              signatures=[],
              mixhash='',
              nonce='',
              source_block_numeber=int_to_big_endian(0),
              source_block_hash=utils.sha3rlp([])):
     fields = {k: v for k, v in locals().items() if k != 'self'}
     if len(fields['coinbase']) == 40:
         fields['coinbase'] = decode_hex(fields['coinbase'])
     assert len(fields['coinbase']) == 20
     super(CollationHeader, self).__init__(**fields)
Esempio n. 5
0
def generate_transaction_hash() -> str:
    (private_key, public_key, sender) = generate_eth_account()
    recipient = generate_eth_account(only_address=True)

    transaction = {
        'to': '0x%s' % recipient,
        'value': 0,
        'gas': 1000000,
        'gasPrice': 1000000000,
        'nonce': 0,
        'chainId': 1
    }

    signature = utils.ecdsa_raw_sign(utils.sha3(transaction), private_key)
    return utils.sha3rlp(signature).hex()
Esempio n. 6
0
def run_block_test(params):
    b = blocks.genesis(env, start_alloc=params["pre"])
    gbh = params["genesisBlockHeader"]
    b.bloom = utils.scanners['int256b'](gbh["bloom"])
    b.timestamp = utils.scanners['int'](gbh["timestamp"])
    b.nonce = utils.scanners['bin'](gbh["nonce"])
    b.extra_data = utils.scanners['bin'](gbh["extraData"])
    b.gas_limit = utils.scanners['int'](gbh["gasLimit"])
    b.gas_used = utils.scanners['int'](gbh["gasUsed"])
    b.coinbase = utils.scanners['addr'](decode_hex(gbh["coinbase"]))
    b.difficulty = utils.parse_int_or_hex(gbh["difficulty"])
    b.prevhash = utils.scanners['bin'](gbh["parentHash"])
    b.mixhash = utils.scanners['bin'](gbh["mixHash"])
    assert b.receipts.root_hash == \
        utils.scanners['bin'](gbh["receiptTrie"])
    assert b.transactions.root_hash == \
        utils.scanners['bin'](gbh["transactionsTrie"])
    assert utils.sha3rlp(b.uncles) == \
        utils.scanners['bin'](gbh["uncleHash"])
    h = encode_hex(b.state.root_hash)
    if h != str_to_bytes(gbh["stateRoot"]):
        raise Exception("state root mismatch")
    if b.hash != utils.scanners['bin'](gbh["hash"]):
        raise Exception("header hash mismatch")
    assert b.header.check_pow()
    blockmap = {b.hash: b}
    env.db.put(b.hash, rlp.encode(b))
    for blk in params["blocks"]:
        if 'blockHeader' not in blk:
            try:
                rlpdata = decode_hex(blk["rlp"][2:])
                blkparent = rlp.decode(
                    rlp.encode(rlp.decode(rlpdata)[0]), blocks.BlockHeader).prevhash
                b2 = rlp.decode(rlpdata, blocks.Block, parent=blockmap[blkparent], env=env)
                success = b2.validate_uncles()
            except (ValueError, TypeError, AttributeError, VerificationFailed,
                    DecodingError, DeserializationError, InvalidTransaction, KeyError):
                success = False
            assert not success
        else:
            rlpdata = decode_hex(blk["rlp"][2:])
            blkparent = rlp.decode(rlp.encode(rlp.decode(rlpdata)[0]), blocks.BlockHeader).prevhash
            b2 = rlp.decode(rlpdata, blocks.Block, parent=blockmap[blkparent], env=env)
            assert b2.validate_uncles()
            blockmap[b2.hash] = b2
            env.db.put(b2.hash, rlp.encode(b2))
Esempio n. 7
0
 def __init__(self,
              prevhash=GENESIS_PREVHASH,
              uncles_hash=utils.sha3rlp([]),
              coinbase=GENESIS_COINBASE,
              state_root=trie.BLANK_ROOT,
              tx_list_root=trie.BLANK_ROOT,
              receipts_root=trie.BLANK_ROOT,
              bloom=0,
              difficulty=GENESIS_DIFFICULTY,
              number=0,
              gas_limit=GENESIS_GAS_LIMIT,
              gas_used=0,
              timestamp=0,
              extra_data='',
              mixhash=GENESIS_MIXHASH,
              nonce=''):
     # at the beginning of a method, locals() is a dict of all arguments
     fields = {k: v for k, v in locals().items() if k != 'self'}
     if len(fields['coinbase']) == 40:
         fields['coinbase'] = decode_hex(fields['coinbase'])
     assert len(fields['coinbase']) == 20
     self.block = None
     super(BlockHeader, self).__init__(**fields)
Esempio n. 8
0
import logging
import warnings

import numpy as np
import pandas as pd
import rlp
from eth_utils import (encode_hex, to_canonical_address, decode_hex)
from ethereum import utils
from ethereum.trie import Trie

BLANK_ROOT = encode_hex(utils.sha3rlp(b''))
BLANK_CODE = encode_hex(utils.sha3(b''))
BLANK_RLP = rlp.encode(b'')
ACCOUNT_LENGTH = 42


class Account:
    def __init__(self, address, nonce=0, balance=0, storage_root=BLANK_ROOT, contract_code=BLANK_CODE,
                 is_in_db=False, is_address_in_db=False):
        """
        :type nonce: int
        :type address: str
        :type balance: int
        :type storage_root: str
        :type contract_code: str
        :type is_in_db: bool
        """
        self.address = address
        self.nonce = nonce
        self.balance = balance
        self.storage_root = storage_root
Esempio n. 9
0
from ethereum.trie import Trie
from ethereum.securetrie import SecureTrie
from ethereum.config import default_config, Env
from ethereum.block import FakeHeader
from ethereum.db import BaseDB, EphemDB, OverlayDB, RefcountDB
from ethereum.specials import specials as default_specials
import copy
import sys
if sys.version_info.major == 2:
    from repoze.lru import lru_cache
else:
    from functools import lru_cache


BLANK_HASH = utils.sha3(b'')
BLANK_ROOT = utils.sha3rlp(b'')

THREE = b'\x00' * 19 + b'\x03'


def snapshot_form(val):
    if is_numeric(val):
        return str(val)
    elif is_string(val):
        return '0x' + encode_hex(val)


STATE_DEFAULTS = {
    "txindex": 0,
    "gas_used": 0,
    "gas_limit": 3141592,
Esempio n. 10
0

(
    NODE_TYPE_BLANK,
    NODE_TYPE_LEAF,
    NODE_TYPE_EXTENSION,
    NODE_TYPE_BRANCH
) = tuple(range(4))


def is_key_value_type(node_type):
    return node_type in [NODE_TYPE_LEAF,
                         NODE_TYPE_EXTENSION]

BLANK_NODE = b''
BLANK_ROOT = utils.sha3rlp(b'')


def transient_trie_exception(*args):
    raise Exception("Transient trie")


class Trie(object):

    def __init__(self, db, root_hash=BLANK_ROOT, transient=False):
        '''it also present a dictionary like interface

        :param db key value database
        :root: blank or trie node in form of [key, value] or [v0,v1..v15,v]
        '''
        self.db = db  # Pass in a database object directly
Esempio n. 11
0
def run_block_test(params, config_overrides={}):
    b = blocks.genesis(env, start_alloc=params["pre"])
    gbh = params["genesisBlockHeader"]
    b.bloom = utils.scanners['int256b'](gbh["bloom"])
    b.timestamp = utils.scanners['int'](gbh["timestamp"])
    b.nonce = utils.scanners['bin'](gbh["nonce"])
    b.extra_data = utils.scanners['bin'](gbh["extraData"])
    b.gas_limit = utils.scanners['int'](gbh["gasLimit"])
    b.gas_used = utils.scanners['int'](gbh["gasUsed"])
    b.coinbase = utils.scanners['addr'](decode_hex(gbh["coinbase"]))
    b.difficulty = utils.parse_int_or_hex(gbh["difficulty"])
    b.prevhash = utils.scanners['bin'](gbh["parentHash"])
    b.mixhash = utils.scanners['bin'](gbh["mixHash"])
    assert b.receipts.root_hash == \
        utils.scanners['bin'](gbh["receiptTrie"])
    assert b.transactions.root_hash == \
        utils.scanners['bin'](gbh["transactionsTrie"])
    assert utils.sha3rlp(b.uncles) == \
        utils.scanners['bin'](gbh["uncleHash"])
    h = encode_hex(b.state.root_hash)
    if h != str_to_bytes(gbh["stateRoot"]):
        raise Exception("state root mismatch")
    if b.hash != utils.scanners['bin'](gbh["hash"]):
        raise Exception("header hash mismatch")
    # assert b.header.check_pow()
    blockmap = {b.hash: b}
    env.db.put(b.hash, rlp.encode(b))
    old_config = copy.deepcopy(env.config)
    try:
        for k, v in config_overrides.items():
            env.config[k] = v
        b2 = None
        for blk in params["blocks"]:
            if 'blockHeader' not in blk:
                try:
                    rlpdata = decode_hex(blk["rlp"][2:])
                    blkparent = rlp.decode(rlp.encode(rlp.decode(rlpdata)[0]),
                                           blocks.BlockHeader).prevhash
                    b2 = rlp.decode(rlpdata,
                                    blocks.Block,
                                    parent=blockmap[blkparent],
                                    env=env)
                    success = b2.validate_uncles()
                except (ValueError, TypeError, AttributeError,
                        VerificationFailed, DecodingError,
                        DeserializationError, InvalidTransaction, KeyError):
                    success = False
                assert not success
            else:
                rlpdata = decode_hex(blk["rlp"][2:])
                blkparent = rlp.decode(rlp.encode(rlp.decode(rlpdata)[0]),
                                       blocks.BlockHeader).prevhash
                b2 = rlp.decode(rlpdata,
                                blocks.Block,
                                parent=blockmap[blkparent],
                                env=env)
                assert b2.validate_uncles()
                blockmap[b2.hash] = b2
                env.db.put(b2.hash, rlp.encode(b2))
            if b2:
                print('Block %d with state root %s' %
                      (b2.number, encode_hex(b2.state.root_hash)))
            # blkdict = b.to_dict(False, True, False, True)
            # assert blk["blockHeader"] == \
            #     translate_keys(blkdict["header"], translator_list, lambda y, x: x, [])
            # assert blk["transactions"] == \
            #     [translate_keys(t, translator_list, valueconv, ['hash'])
            #      for t in blkdict["transactions"]]
            # assert blk["uncleHeader"] == \
            #     [translate_keys(u, translator_list, lambda x: x, [])
            #      for u in blkdict["uncles"]]
    finally:
        env.config = old_config
Esempio n. 12
0
def run_block_test(params, config_overrides = {}):
    b = blocks.genesis(env, start_alloc=params["pre"])
    gbh = params["genesisBlockHeader"]
    b.bloom = utils.scanners['int256b'](gbh["bloom"])
    b.timestamp = utils.scanners['int'](gbh["timestamp"])
    b.nonce = utils.scanners['bin'](gbh["nonce"])
    b.extra_data = utils.scanners['bin'](gbh["extraData"])
    b.gas_limit = utils.scanners['int'](gbh["gasLimit"])
    b.gas_used = utils.scanners['int'](gbh["gasUsed"])
    b.coinbase = utils.scanners['addr'](decode_hex(gbh["coinbase"]))
    b.difficulty = utils.parse_int_or_hex(gbh["difficulty"])
    b.prevhash = utils.scanners['bin'](gbh["parentHash"])
    b.mixhash = utils.scanners['bin'](gbh["mixHash"])
    assert b.receipts.root_hash == \
        utils.scanners['bin'](gbh["receiptTrie"])
    assert b.transactions.root_hash == \
        utils.scanners['bin'](gbh["transactionsTrie"])
    assert utils.sha3rlp(b.uncles) == \
        utils.scanners['bin'](gbh["uncleHash"])
    h = encode_hex(b.state.root_hash)
    if h != str_to_bytes(gbh["stateRoot"]):
        raise Exception("state root mismatch")
    if b.hash != utils.scanners['bin'](gbh["hash"]):
        raise Exception("header hash mismatch")
    # assert b.header.check_pow()
    blockmap = {b.hash: b}
    env.db.put(b.hash, rlp.encode(b))
    old_config = copy.deepcopy(env.config)
    for k, v in config_overrides.items():
        env.config[k] = v
    b2 = None
    for blk in params["blocks"]:
        if 'blockHeader' not in blk:
            try:
                rlpdata = decode_hex(blk["rlp"][2:])
                blkparent = rlp.decode(
                    rlp.encode(rlp.decode(rlpdata)[0]), blocks.BlockHeader).prevhash
                b2 = rlp.decode(rlpdata, blocks.Block, parent=blockmap[blkparent], env=env)
                success = b2.validate_uncles()
            except (ValueError, TypeError, AttributeError, VerificationFailed,
                    DecodingError, DeserializationError, InvalidTransaction, KeyError):
                success = False
            assert not success
        else:
            rlpdata = decode_hex(blk["rlp"][2:])
            blkparent = rlp.decode(rlp.encode(rlp.decode(rlpdata)[0]), blocks.BlockHeader).prevhash
            b2 = rlp.decode(rlpdata, blocks.Block, parent=blockmap[blkparent], env=env)
            assert b2.validate_uncles()
            blockmap[b2.hash] = b2
            env.db.put(b2.hash, rlp.encode(b2))
        if b2:
            print('Block %d with state root %s' % (b2.number, encode_hex(b2.state.root_hash)))
        # blkdict = b.to_dict(False, True, False, True)
        # assert blk["blockHeader"] == \
        #     translate_keys(blkdict["header"], translator_list, lambda y, x: x, [])
        # assert blk["transactions"] == \
        #     [translate_keys(t, translator_list, valueconv, ['hash'])
        #      for t in blkdict["transactions"]]
        # assert blk["uncleHeader"] == \
        #     [translate_keys(u, translator_list, lambda x: x, [])
        #      for u in blkdict["uncles"]]
    env.config = old_config
Esempio n. 13
0
 def un_hash(self, key):
     return utils.sha3rlp(rlp.decode(key))