Beispiel #1
0
 def configure(self, config):
     self.config = config
     logger.info('Opening chain @ %s', utils.get_db_path())
     self.blockchain = DB(utils.get_db_path())
     logger.debug('Chain @ #%d %s', self.head.number, self.head.hex_hash())
     self.log_chain()
     self.new_miner()
Beispiel #2
0
 def configure(self, config):
     self.config = config
     logger.info('Opening chain @ %s', utils.get_db_path())
     self.blockchain = DB(utils.get_db_path())
     logger.debug('Chain @ #%d %s', self.head.number, self.head.hex_hash())
     self.log_chain()
     self.new_miner()
     self.init_dcp_list()
Beispiel #3
0
 def configure(self, config, genesis=None):
     self.config = config
     logger.info('Opening chain @ %s', utils.get_db_path())
     db = self.blockchain = DB(utils.get_db_path())
     self.index = Index(db)
     if genesis:
         self._initialize_blockchain(genesis)
     logger.debug('Chain @ #%d %s', self.head.number, self.head.hex_hash())
     self.new_miner()
Beispiel #4
0
 def configure(self, config, genesis=None):
     self.config = config
     logger.info('Opening chain @ %s', utils.get_db_path())
     db = self.blockchain = DB(utils.get_db_path())
     self.index = Index(db)
     if genesis:
         self._initialize_blockchain(genesis)
     logger.debug('Chain @ #%d %s', self.head.number, self.head.hex_hash())
     self.new_miner()
Beispiel #5
0
    def __init__(self,
                 prevhash='',
                 uncles_hash=block_structure_rev['uncles_hash'][2],
                 coinbase=block_structure_rev['coinbase'][2],
                 state_root='',
                 tx_list_root='',
                 difficulty=block_structure_rev['difficulty'][2],
                 number=0,
                 min_gas_price=block_structure_rev['min_gas_price'][2],
                 gas_limit=block_structure_rev['gas_limit'][2],
                 gas_used=0, timestamp=0, extra_data='', nonce='',
                 transaction_list=[],
                 uncles=[]):

        self.prevhash = prevhash
        self.uncles_hash = uncles_hash
        self.coinbase = coinbase
        self.state_root = state_root
        self.tx_list_root = tx_list_root
        self.difficulty = difficulty
        self.number = number
        self.min_gas_price = min_gas_price
        self.gas_limit = gas_limit
        self.gas_used = gas_used
        self.timestamp = timestamp
        self.extra_data = extra_data
        self.nonce = nonce
        self.transaction_list = transaction_list
        self.uncles = uncles

        self.transactions = Trie(get_db_path())
        self.transaction_count = 0

        # Fill in nodes for transaction trie
        for tx in transaction_list:
            self.add_transaction_to_list(tx)

        self.state = Trie(get_db_path(), self.state_root)

        # Basic consistency verifications
        if self.state.root != '' and self.state.db.get(self.state.root) == '':
            raise Exception("State Merkle root not found in database!")
        if self.tx_list_root != self.transactions.root:
            raise Exception("Transaction list root hash does not match!")
        if sha3(rlp.encode(self.uncles)) != self.uncles_hash:
            raise Exception("Uncle root hash does not match!")
        if len(self.extra_data) > 1024:
            raise Exception("Extra data cannot exceed 1024 bytes")
        if self.coinbase == '':
            raise Exception("Coinbase cannot be empty address")
Beispiel #6
0
 def account_to_dict(self, address, with_storage_root=False):
     if with_storage_root:
         assert len(self.journal) == 0
     med_dict = {}
     for i, val in enumerate(self.get_acct(address)):
         name, typ, default = acct_structure[i]
         key = acct_structure[i][0]
         if name == 'storage':
             strie = trie.Trie(utils.get_db_path(), val)
             if with_storage_root:
                 med_dict['storage_root'] = strie.get_root_hash().encode('hex')
         else:
             med_dict[key] = self.caches[key].get(address, utils.printers[typ](val))
     med_dict['storage'] = {}
     d = strie.to_dict()
     for k in d.keys() + self.caches['all'].keys():
         v = d.get(k, None)
         subcache = self.caches.get('storage:'+address, {})
         v2 = subcache.get(utils.big_endian_to_int(k), None)
         hexkey = '0x'+k.encode('hex')
         if v2 is not None:
             if v2 != 0:
                 med_dict['storage'][hexkey] = '0x'+utils.int_to_big_endian(v2).encode('hex')
         elif v is not None:
             med_dict['storage'][hexkey] = '0x'+rlp.decode(v).encode('hex')
     return med_dict
Beispiel #7
0
 def commit_state(self):
     if not len(self.journal):
         return
     for address in self.caches['all']:
         acct = rlp.decode(self.state.get(address.decode('hex'))) \
             or self.mk_blank_acct()
         for i, (key, typ, default) in enumerate(acct_structure):
             if key == 'storage':
                 t = trie.Trie(utils.get_db_path(), acct[i])
                 t.proof_mode = self.proof_mode
                 t.proof_nodes = self.proof_nodes
                 for k, v in self.caches.get('storage:'+address, {}).iteritems():
                     enckey = utils.zpad(utils.coerce_to_bytes(k), 32)
                     val = rlp.encode(utils.int_to_big_endian(v))
                     if v:
                         t.update(enckey, val)
                     else:
                         t.delete(enckey)
                 acct[i] = t.root_hash
                 if self.proof_mode == RECORDING:
                     self.proof_nodes.extend(t.proof_nodes)
             else:
                 if address in self.caches[key]:
                     v = self.caches[key].get(address, default)
                     acct[i] = utils.encoders[acct_structure[i][1]](v)
         self.state.update(address.decode('hex'), rlp.encode(acct))
     if self.proof_mode == RECORDING:
         self.proof_nodes.extend(self.state.proof_nodes)
         self.state.proof_nodes = []
     self.reset_cache()
Beispiel #8
0
 def account_to_dict(self, address, with_storage_root=False):
     if with_storage_root:
         assert len(self.journal) == 0
     med_dict = {}
     for i, val in enumerate(self.get_acct(address)):
         name, typ, default = acct_structure[i]
         key = acct_structure[i][0]
         if name == 'storage':
             strie = trie.Trie(utils.get_db_path(), val)
             if with_storage_root:
                 med_dict['storage_root'] = strie.get_root_hash().encode(
                     'hex')
         else:
             med_dict[key] = self.caches[key].get(address,
                                                  utils.printers[typ](val))
     med_dict['storage'] = {}
     d = strie.to_dict()
     for k in d.keys() + self.caches['all'].keys():
         v = d.get(k, None)
         subcache = self.caches.get('storage:' + address, {})
         v2 = subcache.get(utils.big_endian_to_int(k), None)
         hexkey = '0x' + k.encode('hex')
         if v2 is not None:
             if v2 != 0:
                 med_dict['storage'][
                     hexkey] = '0x' + utils.int_to_big_endian(v2).encode(
                         'hex')
         elif v is not None:
             med_dict['storage'][hexkey] = '0x' + rlp.decode(v).encode(
                 'hex')
     return med_dict
Beispiel #9
0
 def commit_state(self):
     if not len(self.journal):
         return
     for address in self.caches['all']:
         acct = rlp.decode(self.state.get(address.decode('hex'))) \
             or self.mk_blank_acct()
         for i, (key, typ, default) in enumerate(acct_structure):
             if key == 'storage':
                 t = trie.Trie(utils.get_db_path(), acct[i])
                 t.proof_mode = self.proof_mode
                 t.proof_nodes = self.proof_nodes
                 for k, v in self.caches.get('storage:' + address,
                                             {}).iteritems():
                     enckey = utils.zpad(utils.coerce_to_bytes(k), 32)
                     val = rlp.encode(utils.int_to_big_endian(v))
                     if v:
                         t.update(enckey, val)
                     else:
                         t.delete(enckey)
                 acct[i] = t.root_hash
                 if self.proof_mode == RECORDING:
                     self.proof_nodes.extend(t.proof_nodes)
             else:
                 if address in self.caches[key]:
                     v = self.caches[key].get(address, default)
                     acct[i] = utils.encoders[acct_structure[i][1]](v)
         self.state.update(address.decode('hex'), rlp.encode(acct))
     if self.proof_mode == RECORDING:
         self.proof_nodes.extend(self.state.proof_nodes)
         self.state.proof_nodes = []
     self.reset_cache()
Beispiel #10
0
 def _initialize_blockchain(self, genesis=None):
     logger.info('Initializing new chain @ %s', utils.get_db_path())
     if not genesis:
         genesis = blocks.genesis()
         self.index.add_block(genesis)
     self._store_block(genesis)
     self._update_head(genesis)
Beispiel #11
0
 def _initialize_blockchain(self, genesis=None):
     logger.info('Initializing new chain @ %s', utils.get_db_path())
     if not genesis:
         genesis = blocks.genesis()
         self.index.add_block(genesis)
     self._store_block(genesis)
     self._update_head(genesis)
Beispiel #12
0
def get_block(blockhash):
    """
    Assumtion: blocks loaded from the db are not manipulated
                -> can be cached including hash
    """
    return CachedBlock.create_cached(
        Block.deserialize(db.DB(utils.get_db_path()).get(blockhash)))
Beispiel #13
0
    def POST(self):
        # todo add ping event response

        data = web.data()
        try:
            data_dict = json.loads(data)
        except:
            print 'Invalid json received'
            traceback.print_exc()
            raise web.webapi.BadRequest()

        if data_dict.get('forced') is not True:
            # only save force pushes, so ignore other push events
            raise web.webapi.ok()

        simple_response_validation(data_dict)

        conn = sqlite3.connect(get_db_path())
        ref = str(data_dict.get('ref'))
        repo_name = str(
            data_dict.get('repository', {}).get('full_name'), '<name_missing>')
        conn.execute('INSERT INTO data(repo_name,ref,event) VALUES (?,?,?)',
                     (repo_name, ref, data))
        conn.commit()
        conn.close()
        return web.webapi.Accepted()
Beispiel #14
0
 def account_to_dict(self, address):
     med_dict = {}
     for i, val in enumerate(self.get_acct(address)):
         med_dict[acct_structure[i][0]] = val
     strie = trie.Trie(utils.get_db_path(), med_dict['storage']).to_dict()
     med_dict['storage'] = {utils.decode_int(k): utils.decode_int(v)
                            for k, v in strie.iteritems()}
     return med_dict
Beispiel #15
0
 def account_to_dict(self, address):
     med_dict = {}
     for i, val in enumerate(self.get_acct(address)):
         med_dict[acct_structure[i][0]] = val
     strie = trie.Trie(utils.get_db_path(), med_dict['storage']).to_dict()
     med_dict['storage'] = {
         utils.decode_int(k): utils.decode_int(v)
         for k, v in strie.iteritems()
     }
     return med_dict
Beispiel #16
0
 def account_to_dict(self, address):
     med_dict = {}
     for i, val in enumerate(self.get_acct(address)):
         med_dict[acct_structure[i][0]] = val
     med_dict['code_hash'] = utils.sha3(med_dict['code']).encode('hex')
     med_dict['code'] = med_dict['code'].encode('hex')
     strie = trie.Trie(utils.get_db_path(), med_dict['storage'])
     med_dict['storage'] = {k.encode('hex'): v.encode('hex')
                            for k, v in strie.to_dict().iteritems()}
     med_dict['storage_root'] = strie.root_hash.encode('hex')
     return med_dict
Beispiel #17
0
 def account_to_dict(self, address):
     self.commit_state()
     med_dict = {}
     for i, val in enumerate(self.get_acct(address)):
         name, typ, default = acct_structure[i]
         med_dict[acct_structure[i][0]] = utils.printers[typ](val)
         if name == 'storage':
             strie = trie.Trie(utils.get_db_path(), val)
     med_dict['storage'] = {'0x'+k.encode('hex'):
                            '0x'+rlp.decode(v).encode('hex')
                            for k, v in strie.to_dict().iteritems()}
     return med_dict
Beispiel #18
0
 def _account_to_dict(self, acct):
     med_dict = {}
     for i, (name, typ, default) in enumerate(acct_structure):
         med_dict[name] = utils.decoders[typ](acct[i])
     chash = med_dict['code']
     strie = trie.Trie(utils.get_db_path(), med_dict['storage']).to_dict()
     med_dict['code'] = \
         self.state.db.get(chash).encode('hex') if chash else ''
     med_dict['storage'] = {
         utils.decode_int(k): utils.decode_int(strie[k]) for k in strie
     }
     return med_dict
Beispiel #19
0
 def _account_to_dict(self, acct):
     med_dict = {}
     for i, (name, typ, default) in enumerate(acct_structure):
         med_dict[name] = utils.decoders[typ](acct[i])
     chash = med_dict['code']
     strie = trie.Trie(utils.get_db_path(), med_dict['storage']).to_dict()
     med_dict['code'] = \
         self.state.db.get(chash).encode('hex') if chash else ''
     med_dict['storage'] = {
         utils.decode_int(k): utils.decode_int(strie[k])
         for k in strie
     }
     return med_dict
Beispiel #20
0
 def account_to_dict(self, address):
     self.commit_state()
     med_dict = {}
     for i, val in enumerate(self.get_acct(address)):
         name, typ, default = acct_structure[i]
         med_dict[acct_structure[i][0]] = utils.printers[typ](val)
         if name == 'storage':
             strie = trie.Trie(utils.get_db_path(), val)
             med_dict['storage_root'] = strie.get_root_hash().encode('hex')
     med_dict['storage'] = {
         '0x' + k.encode('hex'): '0x' + rlp.decode(v).encode('hex')
         for k, v in strie.to_dict().iteritems()
     }
     return med_dict
Beispiel #21
0
    def deserialize(cls, rlpdata):
        header_args, transaction_list, uncles = rlp.decode(rlpdata)
        kargs = cls.deserialize_header(header_args)
        kargs['transaction_list'] = transaction_list
        kargs['uncles'] = uncles

        # if we don't have the state we need to replay transactions
        _db = db.DB(utils.get_db_path())
        if len(kargs['state_root']) == 32 and kargs['state_root'] in _db:
            return Block(**kargs)
        elif kargs['prevhash'] == GENESIS_PREVHASH:
            return Block(**kargs)
        else:  # no state, need to replay
            try:
                parent = get_block(kargs['prevhash'])
            except KeyError:
                raise UnknownParentException(kargs['prevhash'].encode('hex'))
            return parent.deserialize_child(rlpdata)
Beispiel #22
0
    def deserialize(cls, rlpdata):
        header_args, transaction_list, uncles = rlp.decode(rlpdata)
        kargs = cls.deserialize_header(header_args)
        kargs['transaction_list'] = transaction_list
        kargs['uncles'] = uncles

        # if we don't have the state we need to replay transactions
        _db = db.DB(utils.get_db_path())
        if len(kargs['state_root']) == 32 and kargs['state_root'] in _db:
            return Block(**kargs)
        elif kargs['prevhash'] == GENESIS_PREVHASH:
            return Block(**kargs)
        else:  # no state, need to replay
            try:
                parent = get_block(kargs['prevhash'])
            except KeyError:
                raise UnknownParentException(kargs['prevhash'].encode('hex'))
            return parent.deserialize_child(rlpdata)
Beispiel #23
0
    def __init__(self, data=None):

        self.reward = 10 ** 18
        self.gas_consumed = 0
        self.gaslimit = 1000000  # for now

        if not data:
            self.number = 0
            self.prevhash = ''
            self.uncles_root = ''
            self.coinbase = '0' * 40
            self.state = Trie(get_db_path())
            self.transactions_root = ''
            self.transactions = []
            self.uncles = []
            self.difficulty = 2 ** 23
            self.timestamp = 0
            self.extradata = ''
            self.nonce = 0
            return

        if re.match('^[0-9a-fA-F]*$', data):
            data = data.decode('hex')

        header,  transaction_list, self.uncles = rlp.decode(data)
        self.number = decode_int(header[0])
        self.prevhash = header[1]
        self.uncles_root = header[2]
        self.coinbase = header[3].encode('hex')
        self.state = Trie(STATEDB_DIR, header[4])
        self.transactions_root = header[5]
        self.difficulty = decode_int(header[6])
        self.timestamp = decode_int(header[7])
        self.extradata = header[8]
        self.nonce = decode_int(header[9])
        self.transactions = [Transaction(x) for x in transaction_list]

        # Verifications
        if self.state.root != '' and self.state.db.get(self.state.root) == '':
            raise Exception("State Merkle root not found in database!")
        if sha3(rlp.encode(transaction_list)) != self.transactions_root:
            raise Exception("Transaction list root hash does not match!")
        if sha3(rlp.encode(self.uncles)) != self.uncles_root:
            raise Exception("Uncle root hash does not match!")
Beispiel #24
0
    def deserialize(cls, rlpdata):
        header_args, transaction_list, uncles = rlp.decode(rlpdata)
        assert len(header_args) == len(block_structure)
        kargs = dict(transaction_list=transaction_list, uncles=uncles)
        # Deserialize all properties
        for i, (name, typ, default) in enumerate(block_structure):
            kargs[name] = utils.decoders[typ](header_args[i])

        # if we don't have the state we need to replay transactions
        _db = db.DB(utils.get_db_path())
        if len(kargs['state_root']) == 32 and kargs['state_root'] in _db:
            return Block(**kargs)
        elif kargs['prevhash'] == GENESIS_PREVHASH:
            return Block(**kargs)
        else:  # no state, need to replay
            try:
                parent = get_block(kargs['prevhash'])
            except KeyError:
                raise UnknownParentException(kargs['prevhash'].encode('hex'))
            return parent.deserialize_child(rlpdata)
Beispiel #25
0
    def deserialize(cls, rlpdata):
        header_args, transaction_list, uncles = rlp.decode(rlpdata)
        assert len(header_args) == len(block_structure)
        kargs = dict(transaction_list=transaction_list, uncles=uncles)
        # Deserialize all properties
        for i, (name, typ, default) in enumerate(block_structure):
            kargs[name] = utils.decoders[typ](header_args[i])

        # if we don't have the state we need to replay transactions
        _db = db.DB(utils.get_db_path())
        if len(kargs['state_root']) == 32 and kargs['state_root'] in _db:
            return Block(**kargs)
        elif kargs['prevhash'] == GENESIS_PREVHASH:
            return Block(**kargs)
        else:  # no state, need to replay
            try:
                parent = get_block(kargs['prevhash'])
            except KeyError:
                raise UnknownParentException(kargs['prevhash'].encode('hex'))
            return parent.deserialize_child(rlpdata)
Beispiel #26
0
 def commit_state(self):
     for address in self.caches['all']:
         acct = rlp.decode(self.state.get(address.decode('hex'))) \
             or self.mk_blank_acct()
         for i, (key, typ, default) in enumerate(acct_structure):
             if key == 'storage':
                 t = trie.Trie(utils.get_db_path(), acct[i])
                 for k, v in self.caches[key].get(address, {}).iteritems():
                     enckey = utils.zpad(utils.coerce_to_bytes(k), 32)
                     val = rlp.encode(utils.int_to_big_endian(v))
                     if v:
                         t.update(enckey, val)
                     else:
                         t.delete(enckey)
                 acct[i] = t.root_hash
             else:
                 if address in self.caches[key]:
                     v = self.caches[key].get(address, default)
                     acct[i] = utils.encoders[acct_structure[i][1]](v)
         self.state.update(address.decode('hex'), rlp.encode(acct))
     self.reset_cache()
Beispiel #27
0
 def commit_state(self):
     for address in self.caches['all']:
         acct = rlp.decode(self.state.get(address.decode('hex'))) \
             or self.mk_blank_acct()
         for i, (key, typ, default) in enumerate(acct_structure):
             if key == 'storage':
                 t = trie.Trie(utils.get_db_path(), acct[i])
                 for k, v in self.caches[key].get(address, {}).iteritems():
                     enckey = utils.zpad(utils.coerce_to_bytes(k), 32)
                     val = rlp.encode(utils.int_to_big_endian(v))
                     if v:
                         t.update(enckey, val)
                     else:
                         t.delete(enckey)
                 acct[i] = t.root_hash
             else:
                 if address in self.caches[key]:
                     v = self.caches[key].get(address, default)
                     acct[i] = utils.encoders[acct_structure[i][1]](v)
         self.state.update(address.decode('hex'), rlp.encode(acct))
     self.reset_cache()
Beispiel #28
0
 def account_to_dict(self, address, with_storage_root=False):
     if with_storage_root:
         assert len(self.journal) == 0
     med_dict = {}
     for i, val in enumerate(self.get_acct(address)):
         name, typ, default = acct_structure[i]
         key = acct_structure[i][0]
         if name == "storage":
             strie = trie.Trie(utils.get_db_path(), val)
             if with_storage_root:
                 med_dict["storage_root"] = strie.get_root_hash().encode("hex")
         else:
             med_dict[key] = self.caches[key].get(address, utils.printers[typ](val))
     med_dict["storage"] = {}
     for k, v in strie.to_dict().iteritems():
         subcache = self.caches.get("storage:" + address, {})
         v2 = subcache.get(utils.big_endian_to_int(k), None)
         hexkey = "0x" + k.encode("hex")
         if v2 is not None:
             med_dict["storage"][hexkey] = "0x" + utils.int_to_big_endian(v2).encode("hex")
         else:
             med_dict["storage"][hexkey] = "0x" + v.encode("hex")
     return med_dict
Beispiel #29
0
    def __init__(self,
                 prevhash='\00' * 32,
                 uncles_hash=block_structure_rev['uncles_hash'][2],
                 coinbase=block_structure_rev['coinbase'][2],
                 state_root=trie.BLANK_ROOT,
                 tx_list_root=trie.BLANK_ROOT,
                 difficulty=block_structure_rev['difficulty'][2],
                 number=0,
                 min_gas_price=block_structure_rev['min_gas_price'][2],
                 gas_limit=block_structure_rev['gas_limit'][2],
                 gas_used=0,
                 timestamp=0,
                 extra_data='',
                 nonce='',
                 transaction_list=[],
                 uncles=[]):

        self.prevhash = prevhash
        self.uncles_hash = uncles_hash
        self.coinbase = coinbase
        self.difficulty = difficulty
        self.number = number
        self.min_gas_price = min_gas_price
        self.gas_limit = gas_limit
        self.gas_used = gas_used
        self.timestamp = timestamp
        self.extra_data = extra_data
        self.nonce = nonce
        self.uncles = uncles

        self.transactions = trie.Trie(utils.get_db_path(), tx_list_root)
        self.transaction_count = 0

        self.state = trie.Trie(utils.get_db_path(), state_root)

        if transaction_list:
            # support init with transactions only if state is known
            assert self.state.root_hash_valid()
            for tx_lst_serialized, state_root, gas_used_encoded \
                    in transaction_list:
                self._add_transaction_to_list(tx_lst_serialized, state_root,
                                              gas_used_encoded)

        # make sure we are all on the same db
        assert self.state.db.db == self.transactions.db.db

        # use de/encoders to check type and validity
        for name, typ, d in block_structure:
            v = getattr(self, name)
            assert utils.decoders[typ](utils.encoders[typ](v)) == v

        # Basic consistency verifications
        if not self.state.root_hash_valid():
            raise Exception("State Merkle root not found in database! %r" %
                            self)
        if tx_list_root != self.transactions.root_hash:
            raise Exception("Transaction list root hash does not match!")
        if not self.transactions.root_hash_valid():
            raise Exception("Transactions root not found in database! %r" %
                            self)
        if utils.sha3(rlp.encode(self.uncles)) != self.uncles_hash:
            raise Exception("Uncle root hash does not match!")
        if len(self.uncles) != len(set(self.uncles)):
            raise Exception("Uncle hash not uniqe in uncles list")
        if len(self.extra_data) > 1024:
            raise Exception("Extra data cannot exceed 1024 bytes")
        if self.coinbase == '':
            raise Exception("Coinbase cannot be empty address")
        if not self.is_genesis() and self.nonce and\
                not self.check_proof_of_work(self.nonce):
            raise Exception("PoW check failed")
Beispiel #30
0
def has_block(blockhash):
    return db.DB(utils.get_db_path()).has_key(blockhash)
Beispiel #31
0
def dbget(x):
    db = trie.DB(utils.get_db_path())
    print db.get(x.decode('hex'))
Beispiel #32
0
def has_block(blockhash):
    return blockhash in db.DB(utils.get_db_path())
Beispiel #33
0
    def __init__(
        self,
        prevhash="\00" * 32,
        uncles_hash=block_structure_rev["uncles_hash"][2],
        coinbase=block_structure_rev["coinbase"][2],
        state_root=trie.BLANK_ROOT,
        tx_list_root=trie.BLANK_ROOT,
        difficulty=block_structure_rev["difficulty"][2],
        number=0,
        min_gas_price=block_structure_rev["min_gas_price"][2],
        gas_limit=block_structure_rev["gas_limit"][2],
        gas_used=0,
        timestamp=0,
        extra_data="",
        nonce="",
        transaction_list=[],
        uncles=[],
        header=None,
    ):

        self.prevhash = prevhash
        self.uncles_hash = uncles_hash
        self.coinbase = coinbase
        self.difficulty = difficulty
        self.number = number
        self.min_gas_price = min_gas_price
        self.gas_limit = gas_limit
        self.gas_used = gas_used
        self.timestamp = timestamp
        self.extra_data = extra_data
        self.nonce = nonce
        self.uncles = uncles
        self.suicides = []
        self.postqueue = []
        self.caches = {"balance": {}, "nonce": {}, "code": {}, "all": {}}
        self.journal = []

        self.transactions = trie.Trie(utils.get_db_path(), tx_list_root)
        self.transaction_count = 0

        self.state = trie.Trie(utils.get_db_path(), state_root)

        if transaction_list:
            # support init with transactions only if state is known
            assert self.state.root_hash_valid()
            for tx_lst_serialized, state_root, gas_used_encoded in transaction_list:
                self._add_transaction_to_list(tx_lst_serialized, state_root, gas_used_encoded)

        # make sure we are all on the same db
        assert self.state.db.db == self.transactions.db.db

        # use de/encoders to check type and validity
        for name, typ, d in block_structure:
            v = getattr(self, name)
            assert utils.decoders[typ](utils.encoders[typ](v)) == v

        # Basic consistency verifications
        if not self.state.root_hash_valid():
            raise Exception("State Merkle root not found in database! %r" % self)
        if tx_list_root != self.transactions.root_hash:
            raise Exception("Transaction list root hash does not match!")
        if not self.transactions.root_hash_valid():
            raise Exception("Transactions root not found in database! %r" % self)
        if len(self.extra_data) > 1024:
            raise Exception("Extra data cannot exceed 1024 bytes")
        if self.coinbase == "":
            raise Exception("Coinbase cannot be empty address")
        if not self.is_genesis() and self.nonce and not check_header_pow(header or self.list_header()):
            raise Exception("PoW check failed")
Beispiel #34
0
 def __init__(self):
     super(ChainManager, self).__init__()
     self.transactions = set()
     self.blockchain = DB(utils.get_db_path())
     self.head = None
Beispiel #35
0
def has_block(blockhash):
    return blockhash in db.DB(utils.get_db_path())
Beispiel #36
0
 def set_state_root(self, state_root_hash):
     self.state = trie.Trie(utils.get_db_path(), state_root_hash)
     self.reset_cache()
Beispiel #37
0
 def _initialize_blockchain(self):
     logger.info('Initializing new chain @ %s', utils.get_db_path())
     genesis = blocks.genesis({self_addr: 10**18})
     self._store_block(genesis)
     self._update_head(genesis)
     self.blockchain.commit()
Beispiel #38
0
 def get_storage(self, address):
     storage_root = self._get_acct_item(address, 'storage')
     return trie.Trie(utils.get_db_path(), storage_root)
Beispiel #39
0
 def set_state_root(self, state_root_hash):
     self.state = trie.Trie(utils.get_db_path(), state_root_hash)
     self.reset_cache()
Beispiel #40
0
def get_block(blockhash):
    return Block.deserialize(db.DB(utils.get_db_path()).get(blockhash))
Beispiel #41
0
def has_block(blockhash):
    return db.DB(utils.get_db_path()).has_key(blockhash)
Beispiel #42
0
    def __init__(self,
                 prevhash='\00' * 32,
                 uncles_hash=block_structure_rev['uncles_hash'][2],
                 coinbase=block_structure_rev['coinbase'][2],
                 state_root=trie.BLANK_ROOT,
                 tx_list_root=trie.BLANK_ROOT,
                 difficulty=block_structure_rev['difficulty'][2],
                 number=0,
                 min_gas_price=block_structure_rev['min_gas_price'][2],
                 gas_limit=block_structure_rev['gas_limit'][2],
                 gas_used=0, timestamp=0, extra_data='', nonce='',
                 transaction_list=[],
                 uncles=[]):

        self.prevhash = prevhash
        self.uncles_hash = uncles_hash
        self.coinbase = coinbase
        self.difficulty = difficulty
        self.number = number
        self.min_gas_price = min_gas_price
        self.gas_limit = gas_limit
        self.gas_used = gas_used
        self.timestamp = timestamp
        self.extra_data = extra_data
        self.nonce = nonce
        self.uncles = uncles
        self.suicides = []

        self.transactions = trie.Trie(utils.get_db_path(), tx_list_root)
        self.transaction_count = 0

        self.state = trie.Trie(utils.get_db_path(), state_root)

        if transaction_list:
            # support init with transactions only if state is known
            assert self.state.root_hash_valid()
            for tx_lst_serialized, state_root, gas_used_encoded \
                    in transaction_list:
                self._add_transaction_to_list(
                    tx_lst_serialized, state_root, gas_used_encoded)

        # make sure we are all on the same db
        assert self.state.db.db == self.transactions.db.db

        # use de/encoders to check type and validity
        for name, typ, d in block_structure:
            v = getattr(self, name)
            assert utils.decoders[typ](utils.encoders[typ](v)) == v

        # Basic consistency verifications
        if not self.state.root_hash_valid():
            raise Exception(
                "State Merkle root not found in database! %r" % self)
        if tx_list_root != self.transactions.root_hash:
            raise Exception("Transaction list root hash does not match!")
        if not self.transactions.root_hash_valid():
            raise Exception(
                "Transactions root not found in database! %r" % self)
        if utils.sha3(rlp.encode(self.uncles)) != self.uncles_hash:
            raise Exception("Uncle root hash does not match!")
        if len(self.uncles) != len(set(self.uncles)):
            raise Exception("Uncle hash not uniqe in uncles list")
        if len(self.extra_data) > 1024:
            raise Exception("Extra data cannot exceed 1024 bytes")
        if self.coinbase == '':
            raise Exception("Coinbase cannot be empty address")
        if not self.is_genesis() and self.nonce and\
                not self.check_proof_of_work(self.nonce):
            raise Exception("PoW check failed")
Beispiel #43
0
    def __init__(self,
                 prevhash='\00' * 32,
                 uncles_hash=block_structure_rev['uncles_hash'][2],
                 coinbase=block_structure_rev['coinbase'][2],
                 state_root=trie.BLANK_ROOT,
                 tx_list_root=trie.BLANK_ROOT,
                 difficulty=block_structure_rev['difficulty'][2],
                 number=0,
                 min_gas_price=block_structure_rev['min_gas_price'][2],
                 gas_limit=block_structure_rev['gas_limit'][2],
                 gas_used=0,
                 timestamp=0,
                 extra_data='',
                 nonce='',
                 transaction_list=[],
                 uncles=[],
                 header=None):

        self.prevhash = prevhash
        self.uncles_hash = uncles_hash
        self.coinbase = coinbase
        self.difficulty = difficulty
        self.number = number
        self.min_gas_price = min_gas_price
        self.gas_limit = gas_limit
        self.gas_used = gas_used
        self.timestamp = timestamp
        self.extra_data = extra_data
        self.nonce = nonce
        self.uncles = uncles
        self.suicides = []
        self.postqueue = []
        self.caches = {'balance': {}, 'nonce': {}, 'code': {}, 'all': {}}
        self.journal = []

        self.transactions = trie.Trie(utils.get_db_path(), tx_list_root)
        self.transaction_count = 0

        self.state = trie.Trie(utils.get_db_path(), state_root)
        self.proof_mode = None
        self.proof_nodes = []

        # If transaction_list is None, then it's a block header imported for
        # SPV purposes
        if transaction_list is not None:
            # support init with transactions only if state is known
            assert self.state.root_hash_valid()
            for tx_lst_serialized, state_root, gas_used_encoded \
                    in transaction_list:
                self._add_transaction_to_list(tx_lst_serialized, state_root,
                                              gas_used_encoded)
            if tx_list_root != self.transactions.root_hash:
                raise Exception("Transaction list root hash does not match!")
            if not self.is_genesis() and self.nonce and\
                    not check_header_pow(header or self.list_header()):
                raise Exception("PoW check failed")

        # make sure we are all on the same db
        assert self.state.db.db == self.transactions.db.db

        # use de/encoders to check type and validity
        for name, typ, d in block_structure:
            v = getattr(self, name)
            assert utils.decoders[typ](utils.encoders[typ](v)) == v

        # Basic consistency verifications
        if not self.state.root_hash_valid():
            raise Exception("State Merkle root not found in database! %r" %
                            self)
        if not self.transactions.root_hash_valid():
            raise Exception("Transactions root not found in database! %r" %
                            self)
        if len(self.extra_data) > 1024:
            raise Exception("Extra data cannot exceed 1024 bytes")
        if self.coinbase == '':
            raise Exception("Coinbase cannot be empty address")
Beispiel #44
0
 def get_storage(self, address):
     storage_root = self._get_acct_item(address, 'storage')
     return trie.Trie(utils.get_db_path(), storage_root)
Beispiel #45
0
 def _initialize_blockchain(self):
     logger.info('Initializing new chain @ %s', utils.get_db_path())
     genesis = blocks.genesis()
     self._store_block(genesis)
     self._update_head(genesis)
     self.blockchain.commit()
Beispiel #46
0
def get_block(blockhash):
    return Block.deserialize(db.DB(utils.get_db_path()).get(blockhash))
def dbget(x):
    db = trie.DB(utils.get_db_path())
    return db.get(x.decode('hex'))
Beispiel #48
0
 def __init__(self):
     self.db = db.DB(utils.get_db_path())
     self.pagenation = 1000
Beispiel #49
0
def get_block(blockhash):
    """
    Assumtion: blocks loaded from the db are not manipulated
                -> can be cached including hash
    """
    return CachedBlock.create_cached(Block.deserialize(db.DB(utils.get_db_path()).get(blockhash)))