def run_test(name, pairs): logger.debug('testing %s' % name) #print('testing %s' % name) def _dec(x): if is_string(x) and x.startswith(b'0x'): return decode_hex(x[2:]) return x pairs['in'] = [(_dec(k), _dec(v)) for k, v in pairs['in']] deletes = [(k, v) for k, v in pairs['in'] if v is None] N_PERMUTATIONS = 1000 for i, permut in enumerate(itertools.permutations(pairs['in'])): print(i, permut) if i > N_PERMUTATIONS: break t = trie.Trie(db.EphemDB()) for k, v in permut: #logger.debug('updating with (%s, %s)' %(k, v)) #print('updating with (%s, %s)' %(k, v)) if v is not None: t.update(k, v) else: t.delete(k) # make sure we have deletes at the end for k, v in deletes: t.delete(k) #print('pairs["root"] should be equal with %s' % (b'0x' + encode_hex(t.root_hash))) if pairs['root'] != b'0x' + encode_hex(t.root_hash): raise Exception( "Mismatch: %r %r %r %r" % (name, pairs['root'], b'0x' + encode_hex(t.root_hash), (i, list(permut) + deletes)))
def run(): st = time.time() x = trie.Trie(db.EphemDB()) for i in range(10000): x.update(to_string(i), to_string(i**3)) print('elapsed', time.time() - st) return x.root_hash
def run_test(name): logger.debug('testing %s' % name) pairs = load_tests()[name] def _dec(x): if is_string(x) and x.startswith(b'0x'): return decode_hex(x[2:]) return x pairs['in'] = [(_dec(k), _dec(v)) for k, v in pairs['in']] deletes = [(k, v) for k, v in pairs['in'] if v is None] N_PERMUTATIONS = 1000 for i, permut in enumerate(itertools.permutations(pairs['in'])): if i > N_PERMUTATIONS: break t = trie.Trie(db.EphemDB()) for k, v in permut: #logger.debug('updating with (%s, %s)' %(k, v)) if v is not None: t.update(k, v) else: t.delete(k) # make sure we have deletes at the end for k, v in deletes: t.delete(k) assert pairs['root'] == b'0x' + encode_hex(t.root_hash), (i, list(permut) + deletes)
def run_block_test(params, config_overrides=None): if config_overrides is None: config_overrides = {} env = Env(db.EphemDB()) genesis_decl = {} for param in ("bloom", "timestamp", "nonce", "extraData", "gasLimit", "coinbase", "difficulty", "parentHash", "mixHash", "gasUsed"): genesis_decl[param] = params["genesisBlockHeader"][param] genesis_decl["alloc"] = params["pre"] old_config = copy.deepcopy(env.config) for k, v in config_overrides.items(): env.config[k] = v # print('overrides', config_overrides) s = state_from_genesis_declaration(genesis_decl, env, allow_empties=True) initialize_genesis_keys(s, Block(s.prev_headers[0], [], [])) c = chain.Chain(genesis=s, localtime=2**99) # print('h', encode_hex(c.state.prev_headers[0].state_root)) # print(c.state.to_dict()) # print(params["pre"]) assert c.state.env == env assert c.state.prev_headers[0].state_root == safe_decode( params["genesisBlockHeader"]["stateRoot"]), ( encode_hex(c.state.prev_headers[0].state_root), params["genesisBlockHeader"]["stateRoot"]) assert c.state.trie.root_hash == safe_decode( params["genesisBlockHeader"]["stateRoot"]) assert c.state.prev_headers[0].hash == safe_decode( params["genesisBlockHeader"]["hash"]) #print('std', c.state.to_dict()) for blk in params["blocks"]: if 'blockHeader' not in blk: success = True try: rlpdata = safe_decode(blk["rlp"][2:]) success = c.add_block(rlp.decode(rlpdata, Block)) except (ValueError, TypeError, AttributeError, VerificationFailed, DecodingError, DeserializationError, InvalidTransaction, InvalidNonce, KeyError) as e: success = False assert not success else: rlpdata = safe_decode(blk["rlp"][2:]) assert c.add_block(rlp.decode(rlpdata, Block)) env.config = old_config
def benchmark(size): t = trie.Trie(db.EphemDB()) for i in range(size): t.update(utils.sha3('k' + str(i)), utils.sha3('v' + str(i))) sz = sum([len(v) for k, v in t.db.db.items()]) nsz = [] ldb = db.ListeningDB(t.db.db) for i in range(min(size, 100)): ldb2 = db.ListeningDB(ldb) odb = t.db t.db = ldb2 t.get(utils.sha3('k' + str(i))) nsz.append(sum([len(v) for k, v in ldb2.kv.items()])) t.db = odb ldbsz = sum([len(v) for k, v in ldb.kv.items()]) print sz, sum(nsz) // len(nsz), ldbsz
def __init__(self, num_accounts=len(keys)): global serpent if not serpent: serpent = __import__('serpent') self.temp_data_dir = tempfile.mkdtemp() self.db = db.EphemDB() o = {} for i in range(num_accounts): o[accounts[i]] = {"wei": 10**24} for i in range(1, 5): o[u.int_to_addr(i)] = {"wei": 1} self.block = b.genesis(self.db, o) self.blocks = [self.block] self.block.timestamp = 1410973349 self.block.coinbase = a0 self.block.gas_limit = 10**9
def __init__(self, num_accounts=len(keys)): self.temp_data_dir = tempfile.mkdtemp() self.db = db.EphemDB() self.env = Env(self.db) self.last_tx = None initial_balances = {} for i in range(num_accounts): account = accounts[i] initial_balances[account] = {'wei': 10**24} for i in range(1, 5): address = int_to_addr(i) initial_balances[address] = {'wei': 1} self.block = blocks.genesis( self.env, start_alloc=initial_balances, ) self.blocks = [self.block] self.block.timestamp = 1410973349 self.block.coinbase = DEFAULT_ACCOUNT self.block.gas_limit = 10**9
import rlp from codecs import encode, decode from ethereum import trie, utils, db ## EX1 print('Exercice 1 ... \n') #initialize trie state = trie.Trie(db.EphemDB()) key = utils.to_string('\x01\x01\x02') state.update(key, rlp.encode(['hello'])) print('Root hash: ', encode(state.root_hash, 'hex')) k, v = state.root_node print('Root node: ', [k, v]) print('HP encoded key, in hex:', encode(k, 'hex')) primaryRoot = encode(state.root_hash, 'hex') ## EX2 - A input('\n\nExercice 2 - A... \n') #initialize trie from previous hash; add new entry with same key. state = trie.Trie(state.db, decode(primaryRoot, 'hex')) print('Root hash: ', encode(state.root_hash, 'hex')) print('Root node: ', state.root_node) print('\n') state.update(key, rlp.encode(['hellothere']))