def trace(txhash): """ /trace/<hexhash> return trace for transaction """ logger.debug('GET trace/%s', txhash) try: # index test_blk, tx = _get_block_before_tx(txhash) except (KeyError, TypeError): return bottle.abort(404, 'Unknown Transaction %s' % txhash) # collect debug output log = [] def log_receiver(name, data): log.append({name:data}) processblock.pblogger.listeners.append(log_receiver) # apply tx (thread? we don't want logs from other invocations) processblock.apply_transaction(test_blk, tx) # stop collecting debug output processblock.pblogger.listeners.remove(log_receiver) # format return dict(tx=txhash, trace=log)
def test_namecoin(): k, v, k2, v2 = accounts() blk = b.genesis({v: u.denoms.ether * 1}) code1 = serpent.compile(namecoin_code) tx1 = t.contract(0, gasprice, startgas, 0, code1).sign(k) s, addr = pb.apply_transaction(blk, tx1) snapshot = blk.snapshot() # tx2 tx2 = t.Transaction(1, gasprice, startgas, addr, 0, serpent.encode_datalist(['george', 45])) tx2.sign(k) s, o = pb.apply_transaction(blk, tx2) assert serpent.decode_datalist(o) == [1] # tx3 tx3 = t.Transaction(2, gasprice, startgas, addr, 0, serpent.encode_datalist(['george', 20])).sign(k) s, o = pb.apply_transaction(blk, tx3) assert serpent.decode_datalist(o) == [0] # tx4 tx4 = t.Transaction(3, gasprice, startgas, addr, 0, serpent.encode_datalist(['harry', 60])).sign(k) s, o = pb.apply_transaction(blk, tx4) assert serpent.decode_datalist(o) == [1] blk.revert(snapshot) assert blk.to_dict() assert blk.to_dict()['state'][addr]['code']
def test_data_feeds(): k, v, k2, v2 = accounts() scode3 = ''' if !contract.storage[1000]: contract.storage[1000] = 1 contract.storage[1001] = msg.sender return(0) elif msg.sender == contract.storage[1001] and msg.datasize == 2: contract.storage[msg.data[0]] = msg.data[1] return(1) else: return(contract.storage[msg.data[0]]) ''' code3 = serpent.compile(scode3) logger.debug("AST", serpent.rewrite(serpent.parse(scode3))) blk = b.genesis({v: 10 ** 18, v2: 10 ** 18}) tx10 = t.contract(0, gasprice, startgas, 0, code3).sign(k) s, addr = pb.apply_transaction(blk, tx10) tx11 = t.Transaction(1, gasprice, startgas, addr, 0, '').sign(k) s, o = pb.apply_transaction(blk, tx11) tx12 = t.Transaction(2, gasprice, startgas, addr, 0, serpent.encode_datalist([500])).sign(k) s, o = pb.apply_transaction(blk, tx12) assert serpent.decode_datalist(o) == [0] tx13 = t.Transaction(3, gasprice, startgas, addr, 0, serpent.encode_datalist([500, 726])).sign(k) s, o = pb.apply_transaction(blk, tx13) assert serpent.decode_datalist(o) == [1] tx14 = t.Transaction(4, gasprice, startgas, addr, 0, serpent.encode_datalist([500])).sign(k) s, o = pb.apply_transaction(blk, tx14) assert serpent.decode_datalist(o) == [726] return blk, addr
def trace(txhash): """ /trace/<hexhash> return trace for transaction """ logger.debug('GET trace/ %s', txhash) try: # index test_blk, tx = _get_block_before_tx(txhash) except (KeyError, TypeError): return bottle.abort(404, 'Unknown Transaction %s' % txhash) # collect debug output log = [] def log_receiver(name, data): log.append({name: data}) processblock.pblogger.listeners.append(log_receiver) # apply tx (thread? we don't want logs from other invocations) processblock.apply_transaction(test_blk, tx) # stop collecting debug output processblock.pblogger.listeners.remove(log_receiver) # format return dict(tx=txhash, trace=log)
def get_trace(txhash): try: # index test_blk, tx, i = _get_block_before_tx(txhash) except (KeyError, TypeError): return bottle.abort(404, 'Unknown Transaction %s' % txhash) # collect debug output recorder = LogRecorder() # apply tx (thread? we don't want logs from other invocations) processblock.apply_transaction(test_blk, tx) return dict(tx=txhash, trace=recorder.pop_records())
def dump(txblkhash): """ /dump/<hash> return state dump after transaction or block """ try: blk = chain_manager.get(txblkhash.decode('hex')) except: try: # index test_blk, tx, i = _get_block_before_tx(txblkhash) except (KeyError, TypeError): return bottle.abort(404, 'Unknown Transaction %s' % txblkhash) processblock.apply_transaction(test_blk, tx) blk = test_blk # format return blk.to_dict(with_state=True, with_uncles=True)
def dump(txblkhash): """ /dump/<hash> return state dump after transaction or block """ try: blk = chain_manager.get(txblkhash.decode('hex')) except: try: # index test_blk, tx = _get_block_before_tx(txblkhash) except (KeyError, TypeError): return bottle.abort(404, 'Unknown Transaction %s' % txblkhash) processblock.apply_transaction(test_blk, tx) blk = test_blk # format return blk.to_dict(with_state=True)
def test_gas_price_calculation(): code = [ 'CALLER', 'PUSH1', 69, 'SSTORE', 'PUSH1', 42, 'DUP', 'PUSH1', 16, 'PUSH1', 0, 'CODECOPY', 'PUSH1', 0, 'RETURN', 'STOP', 'PUSH1', 69, 'SLOAD', 'CALLER', 'EQ', 'NOT', 'PUSH1', 42, 'JUMPI', 'CALLDATASIZE', 'PUSH1', 0, 'MLOAD', 'LT', 'NOT', 'PUSH1', 42, 'JUMPI', 'PUSH1', 32, 'PUSH1', 0, 'MLOAD', 'ADD', 'CALLDATALOAD', 'PUSH1', 0, 'MLOAD', 'CALLDATALOAD', 'SSTORE', 'PUSH1', 64, 'PUSH1', 0, 'MLOAD', 'ADD', 'PUSH1', 0, 'MSTORE', 'PUSH1', 9, 'JUMP' ] tx_dict = { 'nonce': 0L, 'startgas': 10000L, 'value': 0L, 'to': '0000000000000000000000000000000000000000', 's': 9504411864285061276187941232604806802531640604671611347567260576513458657555L, 'r': 23362574597211079051662254624411036839077618676481166419446762923566339937125L, 'v': 28L, 'data': '3`EW`*Q`\x10`\x009`\x00\xf2\x00`EV3\x0e\x0f`*Y6`\x00S\n\x0f`*Y` `\x00S\x015`\x00S5W`@`\x00S\x01`\x00T`\tX', 'gasprice': 10000000000000L } assert serpent.compiler.serialize(code) == tx_dict['data'] set_db() block = genesis = blocks.genesis() tx = transactions.Transaction(**tx_dict) assert block.gas_used == 0 success, output = processblock.apply_transaction(block, tx) GAS_USED_CPP = 1001 # as seen for tx0 in block1 in protocol 17 cpp chain assert block.gas_used == GAS_USED_CPP
def step_impl(context): word = 'a5b2cc1f54' msg = context.msg = '\x00' * (32 - len(word)) + word tx = transactions.Transaction(1, 100, 10**40, context.contract, 0, msg).sign(context.key) success, context.ans = processblock.apply_transaction(context.gen, tx) assert (success)
def load_contract(self, frm, code, endowment=0, gas=STARTGAS): _tx = transactions.contract(nonce=self.nonce[frm], gasprice=self.GASPRICE, startgas=gas, endowment=endowment, code=code).sign(frm.key) result, contract = processblock.apply_transaction(self.genesis, _tx) assert result self.nonce[frm] += 1 return contract
def test_deserialize_cpp_block_42(): # 54.204.10.41 / NEthereum(++)/ZeroGox/v0.5.9/ncurses/Linux/g++ V:17L # E TypeError: ord() expected a character, but string of length 0 found # 00bab55f2e230d4d56c7a2c11e7f3132663cc6734a5d4406f2e4359f4ab56593 """ RomanJ dumped the block BlockData [ hash=00bab55f2e230d4d56c7a2c11e7f3132663cc6734a5d4406f2e4359f4ab56593 parentHash=0df28c56b0cc32ceb55299934fca74ff63956ede0ffd430367ebcb1bb94d42fe unclesHash=1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347 coinbase=a70abb9ed4b5d82ed1d82194943349bcde036812 stateHash=203838e6ea7b03bce4b806ab4e5c069d5cd98ca2ba27a2d343d809cc6365e1ce txTrieHash=78aaa0f3b726f8d9273ba145e0efd4a6b21183412582449cc9457f713422b5ae difficulty=4142bd number=48 minGasPrice=10000000000000 gasLimit=954162 gasUsed=500 timestamp=1400678342 extraData=null nonce=0000000000000000000000000000000000000000000000007d117303138a74e0 TransactionData [ hash=9003d7211c4b0d123778707fbdcabd93a6184be210390de4f73f89eae847556d nonce=null, gasPrice=09184e72a000, gas=01f4, receiveAddress=e559de5527492bcb42ec68d07df0742a98ec3f1e, value=8ac7230489e80000, data=null, signatureV=27, signatureR=18d646b8c4f7a804fdf7ba8da4d5dd049983e7d2b652ab902f7d4eaebee3e33b, signatureS=229ad485ef078d6e5f252db58dd2cce99e18af02028949896248aa01baf48b77] ] """ genesis = mkgenesis( {'a70abb9ed4b5d82ed1d82194943349bcde036812': 100000000000000000000L}) hex_rlp_data = \ """f9016df8d3a00df28c56b0cc32ceb55299934fca74ff63956ede0ffd430367ebcb1bb94d42fea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794a70abb9ed4b5d82ed1d82194943349bcde036812a0203838e6ea7b03bce4b806ab4e5c069d5cd98ca2ba27a2d343d809cc6365e1cea078aaa0f3b726f8d9273ba145e0efd4a6b21183412582449cc9457f713422b5ae834142bd308609184e72a000830e8f328201f484537ca7c680a00000000000000000000000000000000000000000000000007d117303138a74e0f895f893f86d808609184e72a0008201f494e559de5527492bcb42ec68d07df0742a98ec3f1e888ac7230489e80000801ba018d646b8c4f7a804fdf7ba8da4d5dd049983e7d2b652ab902f7d4eaebee3e33ba0229ad485ef078d6e5f252db58dd2cce99e18af02028949896248aa01baf48b77a06e957f0f99502ad60a66a016f72957eff0f3a5bf791ad4a0606a44f35a6e09288201f4c0""" header_args, transaction_list, uncles = rlp.decode( hex_rlp_data.decode('hex')) for tx_data, _state_root, _gas_used_encoded in transaction_list: tx = transactions.Transaction.create(tx_data) logger.debug('Block #48 failing tx %r' % tx.to_dict()) processblock.apply_transaction(genesis, tx)
def test_deserialize_cpp_block_42(): # 54.204.10.41 / NEthereum(++)/ZeroGox/v0.5.9/ncurses/Linux/g++ V:17L # E TypeError: ord() expected a character, but string of length 0 found # 00bab55f2e230d4d56c7a2c11e7f3132663cc6734a5d4406f2e4359f4ab56593 """ RomanJ dumped the block BlockData [ hash=00bab55f2e230d4d56c7a2c11e7f3132663cc6734a5d4406f2e4359f4ab56593 parentHash=0df28c56b0cc32ceb55299934fca74ff63956ede0ffd430367ebcb1bb94d42fe unclesHash=1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347 coinbase=a70abb9ed4b5d82ed1d82194943349bcde036812 stateHash=203838e6ea7b03bce4b806ab4e5c069d5cd98ca2ba27a2d343d809cc6365e1ce txTrieHash=78aaa0f3b726f8d9273ba145e0efd4a6b21183412582449cc9457f713422b5ae difficulty=4142bd number=48 minGasPrice=10000000000000 gasLimit=954162 gasUsed=500 timestamp=1400678342 extraData=null nonce=0000000000000000000000000000000000000000000000007d117303138a74e0 TransactionData [ hash=9003d7211c4b0d123778707fbdcabd93a6184be210390de4f73f89eae847556d nonce=null, gasPrice=09184e72a000, gas=01f4, receiveAddress=e559de5527492bcb42ec68d07df0742a98ec3f1e, value=8ac7230489e80000, data=null, signatureV=27, signatureR=18d646b8c4f7a804fdf7ba8da4d5dd049983e7d2b652ab902f7d4eaebee3e33b, signatureS=229ad485ef078d6e5f252db58dd2cce99e18af02028949896248aa01baf48b77] ] """ genesis = mkgenesis( {'a70abb9ed4b5d82ed1d82194943349bcde036812': 100000000000000000000L}) hex_rlp_data = \ """f9016df8d3a00df28c56b0cc32ceb55299934fca74ff63956ede0ffd430367ebcb1bb94d42fea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794a70abb9ed4b5d82ed1d82194943349bcde036812a0203838e6ea7b03bce4b806ab4e5c069d5cd98ca2ba27a2d343d809cc6365e1cea078aaa0f3b726f8d9273ba145e0efd4a6b21183412582449cc9457f713422b5ae834142bd308609184e72a000830e8f328201f484537ca7c680a00000000000000000000000000000000000000000000000007d117303138a74e0f895f893f86d808609184e72a0008201f494e559de5527492bcb42ec68d07df0742a98ec3f1e888ac7230489e80000801ba018d646b8c4f7a804fdf7ba8da4d5dd049983e7d2b652ab902f7d4eaebee3e33ba0229ad485ef078d6e5f252db58dd2cce99e18af02028949896248aa01baf48b77a06e957f0f99502ad60a66a016f72957eff0f3a5bf791ad4a0606a44f35a6e09288201f4c0""" header_args, transaction_list, uncles = rlp.decode( hex_rlp_data.decode('hex')) for tx_data, _state_root, _gas_used_encoded in transaction_list: tx = transactions.Transaction.create(tx_data) logger.debug('Block #48 failing tx %r', tx.to_dict()) processblock.apply_transaction(genesis, tx)
def step_impl(context): word = 342156 word = hex(word)[2:] if len(word)%2 != 0: word = '0' + word msg = context.msg = '\x00'*(32-len(word)/2)+word.decode('hex') tx = transactions.Transaction(1, 100, 10**40, context.contract, 0, msg).sign(context.key) success, context.ans = processblock.apply_transaction(context.gen, tx) assert(success)
def tx(self, frm, to, value, data, gas=STARTGAS): _tx = transactions.Transaction(nonce=self.nonce[frm], gasprice=self.GASPRICE, startgas=gas, to=to, value=value, data=serpent.encode_datalist(data)).sign(frm.key) result, ans = processblock.apply_transaction(self.genesis, _tx) assert result self.nonce[frm] += 1 return serpent.decode_datalist(ans)
def step_impl(context): word = 342156 word = hex(word)[2:] if len(word) % 2 != 0: word = '0' + word msg = context.msg = '\x00' * (32 - len(word) / 2) + word.decode('hex') tx = transactions.Transaction(1, 100, 10**40, context.contract, 0, msg).sign(context.key) success, context.ans = processblock.apply_transaction(context.gen, tx) assert (success)
def step_impl(context): ''' serpent: 'return(sha3(msg.data[0]))' assembly: ['$begincode_0.endcode_0', 'DUP', 'MSIZE', 'SWAP', 'MSIZE', '$begincode_0', 'CALLDATACOPY', 'RETURN', '~begincode_0', '#CODE_BEGIN', 32, 'MSIZE', 0L, 'CALLDATALOAD', 'MSIZE', 'MSTORE', 'SHA3', 'MSIZE', 'SWAP', 'MSIZE', 'MSTORE', 32, 'SWAP', 'RETURN', '#CODE_END', '~endcode_0'] byte code: 6011515b525b600a37f260205b6000355b54205b525b54602052f2 ''' code = '6011515b525b600a37f260205b6000355b54205b525b54602052f2'.decode('hex') tx_contract = transactions.contract(0,10,10**30, 10**30, code).sign(context.key) success, context.contract = processblock.apply_transaction(context.gen, tx_contract) assert(success)
def __init__(self, root_user): self.user = root_user self.code = serpent.compile(open('./crowdfund.se').read()) tx = transactions.contract(NonceSingleton.inc(root_user), Message.DEFAULT_GASPRICE, Message.DEFAULT_STARTGAS, 0, self.code).sign(root_user.private_key) print "Made crowdfund tx: {}".format(tx) self.contract = self._wrap_contract_response( processblock.apply_transaction(root_user.genesis, tx))
def test_transaction(): k, v, k2, v2 = accounts() set_db() blk = mkquickgenesis({v: utils.denoms.ether * 1}) db_store(blk) blk = mine_next_block(blk) tx = get_transaction() assert tx not in blk.get_transactions() success, res = processblock.apply_transaction(blk, tx) assert tx in blk.get_transactions() assert blk.get_balance(v) == utils.denoms.finney * 990 assert blk.get_balance(v2) == utils.denoms.finney * 10
def tx(self, frm, to, value, data, gas=STARTGAS): _tx = transactions.Transaction(nonce=self.nonce[frm], gasprice=self.GASPRICE, startgas=gas, to=to, value=value, data=encode_datalist(data)).sign( frm.key) result, ans = processblock.apply_transaction(self.genesis, _tx) assert result self.nonce[frm] += 1 return decode_datalist(ans)
def deserialize_child(parent, rlpdata): """ deserialization w/ replaying transactions """ header_args, transaction_list, uncles = rlp.decode(rlpdata) assert len(header_args) == len(blocks.block_structure) kargs = dict(transaction_list=transaction_list, uncles=uncles) # Deserialize all properties for i, (name, typ, default) in enumerate(blocks.block_structure): kargs[name] = utils.decoders[typ](header_args[i]) block = blocks.Block.init_from_parent(parent, kargs['coinbase'], extra_data=kargs['extra_data'], timestamp=kargs['timestamp']) block.finalize() # this is the first potential state change # replay transactions for tx_lst_serialized, _state_root, _gas_used_encoded in transaction_list: tx = transactions.Transaction.create(tx_lst_serialized) logger.debug("data %r", tx.data) logger.debug('applying %r', tx) logger.debug('applying %r', tx.to_dict()) logger.debug('block.gas_used before: %r', block.gas_used) success, output = processblock.apply_transaction(block, tx) logger.debug('block.gas_used after: %r', block.gas_used) logger.debug('success: %r', success) diff = utils.decode_int(_gas_used_encoded) - block.gas_used logger.debug("GAS_USED DIFF %r", diff) assert utils.decode_int(_gas_used_encoded) == block.gas_used assert _state_root.encode('hex') == block.state.root_hash.encode('hex') # checks assert block.prevhash == parent.hash assert block.tx_list_root == kargs['tx_list_root'] assert block.gas_used == kargs['gas_used'] assert block.gas_limit == kargs['gas_limit'] assert block.timestamp == kargs['timestamp'] assert block.difficulty == kargs['difficulty'] assert block.number == kargs['number'] assert block.extra_data == kargs['extra_data'] assert utils.sha3(rlp.encode(block.uncles)) == kargs['uncles_hash'] assert block.state.root_hash.encode('hex') == kargs['state_root'].encode( 'hex') block.uncles_hash = kargs['uncles_hash'] block.nonce = kargs['nonce'] block.min_gas_price = kargs['min_gas_price'] return block
def step_impl(context): ''' serpent: 'return(sha3(msg.data[0]))' assembly: ['$begincode_0.endcode_0', 'DUP', 'MSIZE', 'SWAP', 'MSIZE', '$begincode_0', 'CALLDATACOPY', 'RETURN', '~begincode_0', '#CODE_BEGIN', 32, 'MSIZE', 0L, 'CALLDATALOAD', 'MSIZE', 'MSTORE', 'SHA3', 'MSIZE', 'SWAP', 'MSIZE', 'MSTORE', 32, 'SWAP', 'RETURN', '#CODE_END', '~endcode_0'] byte code: 6011515b525b600a37f260205b6000355b54205b525b54602052f2 ''' code = '6011515b525b600a37f260205b6000355b54205b525b54602052f2'.decode( 'hex') tx_contract = transactions.contract(0, 10, 10**30, 10**30, code).sign(context.key) success, context.contract = processblock.apply_transaction( context.gen, tx_contract) assert (success)
def deserialize_child(parent, rlpdata): """ deserialization w/ replaying transactions """ header_args, transaction_list, uncles = rlp.decode(rlpdata) assert len(header_args) == len(blocks.block_structure) kargs = dict(transaction_list=transaction_list, uncles=uncles) # Deserialize all properties for i, (name, typ, default) in enumerate(blocks.block_structure): kargs[name] = utils.decoders[typ](header_args[i]) block = blocks.Block.init_from_parent(parent, kargs['coinbase'], extra_data=kargs['extra_data'], timestamp=kargs['timestamp']) block.finalize() # this is the first potential state change # replay transactions for tx_lst_serialized, _state_root, _gas_used_encoded in transaction_list: tx = transactions.Transaction.create(tx_lst_serialized) logger.debug("data %r", tx.data) logger.debug('applying %r', tx) logger.debug('applying %r', tx.to_dict()) logger.debug('block.gas_used before: %r', block.gas_used) success, output = processblock.apply_transaction(block, tx) logger.debug('block.gas_used after: %r', block.gas_used) logger.debug('success: %r', success) diff = utils.decode_int(_gas_used_encoded) - block.gas_used logger.debug("GAS_USED DIFF %r", diff) assert utils.decode_int(_gas_used_encoded) == block.gas_used assert _state_root.encode('hex') == block.state.root_hash.encode('hex') # checks assert block.prevhash == parent.hash assert block.tx_list_root == kargs['tx_list_root'] assert block.gas_used == kargs['gas_used'] assert block.gas_limit == kargs['gas_limit'] assert block.timestamp == kargs['timestamp'] assert block.difficulty == kargs['difficulty'] assert block.number == kargs['number'] assert block.extra_data == kargs['extra_data'] assert utils.sha3(rlp.encode(block.uncles)) == kargs['uncles_hash'] assert block.state.root_hash.encode( 'hex') == kargs['state_root'].encode('hex') block.uncles_hash = kargs['uncles_hash'] block.nonce = kargs['nonce'] block.min_gas_price = kargs['min_gas_price'] return block
def test_gas_deduction(): k, v, k2, v2 = accounts() blk = blocks.genesis({v: utils.denoms.ether * 1}) v_old_balance = blk.get_balance(v) assert blk.get_balance(blk.coinbase) == 0 gasprice = 1 startgas = 10000 code1 = serpent.compile(namecoin_code) tx1 = transactions.contract(0, gasprice, startgas, 0, code1).sign(k) success, addr = processblock.apply_transaction(blk, tx1) assert success assert blk.coinbase != v assert v_old_balance > blk.get_balance(v) assert v_old_balance == blk.get_balance(v) + blk.get_balance(blk.coinbase) intrinsic_gas_used = processblock.GTXCOST + \ processblock.GTXDATA * len(tx1.data) assert v_old_balance - blk.get_balance(v) >= intrinsic_gas_used * gasprice
def test_gas_price_calculation(): code = [ 'CALLER', 'PUSH1', 69, 'SSTORE', 'PUSH1', 42, 'DUP', 'PUSH1', 16, 'PUSH1', 0, 'CODECOPY', 'PUSH1', 0, 'RETURN', 'STOP', 'PUSH1', 69, 'SLOAD', 'CALLER', 'EQ', 'NOT', 'PUSH1', 42, 'JUMPI', 'CALLDATASIZE', 'PUSH1', 0, 'MLOAD', 'LT', 'NOT', 'PUSH1', 42, 'JUMPI', 'PUSH1', 32, 'PUSH1', 0, 'MLOAD', 'ADD', 'CALLDATALOAD', 'PUSH1', 0, 'MLOAD', 'CALLDATALOAD', 'SSTORE', 'PUSH1', 64, 'PUSH1', 0, 'MLOAD', 'ADD', 'PUSH1', 0, 'MSTORE', 'PUSH1', 9, 'JUMP'] tx_dict = {'nonce': 0L, 'startgas': 10000L, 'value': 0L, 'to': '0000000000000000000000000000000000000000', 's': 9504411864285061276187941232604806802531640604671611347567260576513458657555L, 'r': 23362574597211079051662254624411036839077618676481166419446762923566339937125L, 'v': 28L, 'data': '3`EW`*Q`\x10`\x009`\x00\xf2\x00`EV3\x0e\x0f`*Y6`\x00S\n\x0f`*Y` `\x00S\x015`\x00S5W`@`\x00S\x01`\x00T`\tX', 'gasprice': 10000000000000L} assert serpent.compiler.serialize(code) == tx_dict['data'] set_db() block = genesis = blocks.genesis() tx = transactions.Transaction(**tx_dict) assert block.gas_used == 0 success, output = processblock.apply_transaction(block, tx) GAS_USED_CPP = 1001 # as seen for tx0 in block1 in protocol 17 cpp chain assert block.gas_used == GAS_USED_CPP
def test_currency(): k, v, k2, v2 = accounts() scode2 = ''' if !contract.storage[1000]: contract.storage[1000] = 1 contract.storage[0x%s] = 1000 return(1) elif msg.datasize == 1: addr = msg.data[0] return(contract.storage[addr]) else: from = msg.sender fromvalue = contract.storage[from] to = msg.data[0] value = msg.data[1] if fromvalue >= value: contract.storage[from] = fromvalue - value contract.storage[to] = contract.storage[to] + value return(1) else: return(0) ''' % v code2 = serpent.compile(scode2) blk = b.genesis({v: 10 ** 18}) tx4 = t.contract(0, gasprice, startgas, 0, code2).sign(k) s, addr = pb.apply_transaction(blk, tx4) tx5 = t.Transaction(1, gasprice, startgas, addr, 0, '').sign(k) s, o = pb.apply_transaction(blk, tx5) assert serpent.decode_datalist(o) == [1] tx6 = t.Transaction(2, gasprice, startgas, addr, 0, serpent.encode_datalist([v2, 200])).sign(k) s, o = pb.apply_transaction(blk, tx6) assert serpent.decode_datalist(o) == [1] tx7 = t.Transaction(3, gasprice, startgas, addr, 0, serpent.encode_datalist([v2, 900])).sign(k) s, o = pb.apply_transaction(blk, tx7) assert serpent.decode_datalist(o) == [0] tx8 = t.Transaction(4, gasprice, startgas, addr, 0, serpent.encode_datalist([v])).sign(k) s, o = pb.apply_transaction(blk, tx8) assert serpent.decode_datalist(o) == [800] tx9 = t.Transaction(5, gasprice, startgas, addr, 0, serpent.encode_datalist([v2])).sign(k) s, o = pb.apply_transaction(blk, tx9) assert serpent.decode_datalist(o) == [200]
sys.exit(1) code = serpent.compile(escrow) sender_key = utils.sha3('sender') sender_addr = utils.privtoaddr(sender_key) recipient_key = utils.sha3('recipient') recipient_addr = utils.privtoaddr(recipient_key) host_key = utils.sha3('host') host_addr = utils.privtoaddr(host_key) #initialize the block genesis = blocks.genesis({sender_addr: 10**18, recipient_addr: 10**18, host_addr: 10**18}) #initialize the contract tx1 = transactions.contract(0, 10**12, 10000, 0, code).sign(host_key) result, contract = processblock.apply_transaction(genesis, tx1) #execute escrow transaction #nonce, gasprice, startgas, to, value, data price = int(sys.argv[1]) #user supplied price tx2 = transactions.Transaction(0, 10**12, 10000, contract, price, serpent.encode_datalist([1,recipient_addr])).sign(sender_key) result, ans = processblock.apply_transaction(genesis, tx2) tx3 = transactions.Transaction(0, 10**12, 10000, contract, 0, serpent.encode_datalist([int(sys.argv[2])])).sign(recipient_key) result, ans = processblock.apply_transaction(genesis, tx3) tx4 = transactions.Transaction(1, 10**12, 10000, contract, 0, serpent.encode_datalist([int(sys.argv[3])])).sign(sender_key) result, ans = processblock.apply_transaction(genesis, tx4) print('Service address: %s ' %str(hex(genesis.get_storage_data(contract, 0)))) print('Sender address: %s' %str(hex(genesis.get_storage_data(contract, 1)))) print('Reciever address: %s\n' %str(hex(genesis.get_storage_data(contract, 3)))) print('Price: %s' %str(genesis.get_storage_data(contract, 2)))
def do_test_vm(filename, testname=None, limit=99999999): if testname is None: for testname in vm_tests_fixtures()[filename].keys()[:limit]: do_test_vm(filename, testname) return if testname in faulty: logger.debug('skipping test:%r in %r' % (testname, filename)) return logger.debug('running test:%r in %r' % (testname, filename)) params = vm_tests_fixtures()[filename][testname] pre = params['pre'] exek = params['transaction'] env = params['env'] post = params['post'] check_testdata(env.keys(), [ 'currentGasLimit', 'currentTimestamp', 'previousHash', 'currentCoinbase', 'currentDifficulty', 'currentNumber' ]) # setup env blk = blocks.Block(new_db(), prevhash=env['previousHash'].decode('hex'), number=int(env['currentNumber']), coinbase=env['currentCoinbase'], difficulty=int(env['currentDifficulty']), gas_limit=int(env['currentGasLimit']), timestamp=int(env['currentTimestamp'])) # code FIXME WHAT TO DO WITH THIS CODE??? # if isinstance(env['code'], str): # continue # else: # addr = 0 # FIXME # blk.set_code(addr, ''.join(map(chr, env['code']))) # setup state for address, h in pre.items(): check_testdata(h.keys(), ['code', 'nonce', 'balance', 'storage']) blk.set_nonce(address, int(h['nonce'])) blk.set_balance(address, int(h['balance'])) blk.set_code(address, h['code'][2:].decode('hex')) for k, v in h['storage'].iteritems(): blk.set_storage_data(address, u.big_endian_to_int(k[2:].decode('hex')), u.big_endian_to_int(v[2:].decode('hex'))) # execute transactions tx = transactions.Transaction(nonce=int(exek['nonce'] or "0"), gasprice=int(exek['gasPrice'] or "0"), startgas=int(exek['gasLimit'] or "0"), to=exek['to'], value=int(exek['value'] or "0"), data=exek['data'][2:].decode('hex')).sign( exek['secretKey']) orig_apply_msg = pb.apply_msg def apply_msg_wrapper(ext, msg, code): def blkhash(n): if n >= blk.number or n < blk.number - 256: return '' else: return u.sha3(str(n)) ext.block_hash = blkhash return orig_apply_msg(ext, msg, code) pb.apply_msg = apply_msg_wrapper try: success, output = pb.apply_transaction(blk, tx) blk.commit_state() except pb.InvalidTransaction: output = '' logger.debug('Transaction not valid') pass if tx.to == '': output = blk.get_code(output) pb.apply_msg = orig_apply_msg assert '0x' + output.encode('hex') == params['out'] # check state for address, data in post.items(): state = blk.account_to_dict(address, for_vmtest=True) state.pop('storage_root', None) assert state == data
def do_test_vm(filename, testname=None, limit=99999999): if testname is None: for testname in vm_tests_fixtures()[filename].keys()[:limit]: do_test_vm(filename, testname) return if testname in faulty: logger.debug('skipping test:%r in %r' % (testname, filename)) return logger.debug('running test:%r in %r' % (testname, filename)) params = vm_tests_fixtures()[filename][testname] pre = params['pre'] exek = params['transaction'] env = params['env'] post = params['post'] check_testdata(env.keys(), ['currentGasLimit', 'currentTimestamp', 'previousHash', 'currentCoinbase', 'currentDifficulty', 'currentNumber']) # setup env blk = blocks.Block(new_db(), prevhash=env['previousHash'].decode('hex'), number=int(env['currentNumber']), coinbase=env['currentCoinbase'], difficulty=int(env['currentDifficulty']), gas_limit=int(env['currentGasLimit']), timestamp=int(env['currentTimestamp'])) # code FIXME WHAT TO DO WITH THIS CODE??? # if isinstance(env['code'], str): # continue # else: # addr = 0 # FIXME # blk.set_code(addr, ''.join(map(chr, env['code']))) # setup state for address, h in pre.items(): check_testdata(h.keys(), ['code', 'nonce', 'balance', 'storage']) blk.set_nonce(address, int(h['nonce'])) blk.set_balance(address, int(h['balance'])) blk.set_code(address, h['code'][2:].decode('hex')) for k, v in h['storage'].iteritems(): blk.set_storage_data(address, u.big_endian_to_int(k[2:].decode('hex')), u.big_endian_to_int(v[2:].decode('hex'))) # execute transactions tx = transactions.Transaction( nonce=int(exek['nonce'] or "0"), gasprice=int(exek['gasPrice'] or "0"), startgas=int(exek['gasLimit'] or "0"), to=exek['to'], value=int(exek['value'] or "0"), data=exek['data'][2:].decode('hex')).sign(exek['secretKey']) orig_apply_msg = pb.apply_msg def apply_msg_wrapper(ext, msg, code): def blkhash(n): if n >= blk.number or n < blk.number - 256: return '' else: return u.sha3(str(n)) ext.block_hash = blkhash return orig_apply_msg(ext, msg, code) pb.apply_msg = apply_msg_wrapper try: success, output = pb.apply_transaction(blk, tx) blk.commit_state() except pb.InvalidTransaction: output = '' logger.debug('Transaction not valid') pass if tx.to == '': output = blk.get_code(output) pb.apply_msg = orig_apply_msg assert '0x' + output.encode('hex') == params['out'] # check state for address, data in post.items(): state = blk.account_to_dict(address, for_vmtest=True) state.pop('storage_root', None) assert state == data
def execute(self, from_): signed_tx = self.tx(from_).sign(from_.private_key) return processblock.apply_transaction(from_.genesis, signed_tx)
def test_hedge(): k, v, k2, v2 = accounts() blk, addr = test_data_feeds() scode4 = ''' if !contract.storage[1000]: contract.storage[1000] = msg.sender contract.storage[1002] = msg.value contract.storage[1003] = msg.data[0] return(1) elif !contract.storage[1001]: ethvalue = contract.storage[1002] if msg.value >= ethvalue: contract.storage[1001] = msg.sender othervalue = ethvalue * call(0x%s,[contract.storage[1003]],1) contract.storage[1004] = othervalue contract.storage[1005] = block.timestamp + 86400 return([2,othervalue],2) else: othervalue = contract.storage[1004] ethvalue = othervalue / call(0x%s,contract.storage[1003]) if ethvalue >= contract.balance: send(contract.storage[1000],contract.balance) return(3) elif block.timestamp > contract.storage[1005]: send(contract.storage[1001],contract.balance - ethvalue) send(contract.storage[1000],ethvalue) return(4) else: return(5) ''' % (addr, addr) code4 = serpent.compile(scode4) logger.debug("AST", serpent.rewrite(serpent.parse(scode4))) # important: no new genesis block tx15 = t.contract(5, gasprice, startgas, 0, code4).sign(k) s, addr2 = pb.apply_transaction(blk, tx15) tx16 = t.Transaction(6, gasprice, startgas, addr2, 10 ** 17, serpent.encode_datalist([500])).sign(k) s, o = pb.apply_transaction(blk, tx16) assert serpent.decode_datalist(o) == [1] tx17 = t.Transaction(0, gasprice, startgas, addr2, 10 ** 17, serpent.encode_datalist([500])).sign(k2) s, o = pb.apply_transaction(blk, tx17) assert serpent.decode_datalist(o) == [2, 72600000000000000000L] snapshot = blk.snapshot() tx18 = t.Transaction(7, gasprice, startgas, addr2, 0, '').sign(k) s, o = pb.apply_transaction(blk, tx18) assert serpent.decode_datalist(o) == [5] tx19 = t.Transaction(8, gasprice, startgas, addr, 0, serpent.encode_datalist([500, 300])).sign(k) s, o = pb.apply_transaction(blk, tx19) assert serpent.decode_datalist(o) == [1] tx20 = t.Transaction(9, gasprice, startgas, addr2, 0, '').sign(k) s, o = pb.apply_transaction(blk, tx20) assert serpent.decode_datalist(o) == [3] blk.revert(snapshot) blk.timestamp += 200000 tx21 = t.Transaction(7, gasprice, startgas, addr, 0, serpent.encode_datalist([500, 1452])).sign(k) s, o = pb.apply_transaction(blk, tx21) assert serpent.decode_datalist(o) == [1] tx22 = t.Transaction(8, gasprice, 2000, addr2, 0, '').sign(k) s, o = pb.apply_transaction(blk, tx22) assert serpent.decode_datalist(o) == [4]
def do_test_vm(name): tempdir = tempfile.mktemp() logger.debug('running test:%r', name) params = vm_tests_fixtures()[name] # HOTFIFX # params['pre']['0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6']['balance'] *= 100 pre = params['pre'] execs = params['exec'] callcreates = params['callcreates'] env = params['env'] post = params['post'] check_testdata(env.keys(), [ 'code', 'currentGasLimit', 'currentTimestamp', 'previousHash', 'currentCoinbase', 'currentDifficulty', 'currentNumber' ]) # setup env blk = blocks.Block(prevhash=env['previousHash'].decode('hex'), number=int(env['currentNumber']), coinbase=env['currentCoinbase'], difficulty=int(env['currentDifficulty']), gas_limit=int(env['currentGasLimit']), timestamp=env['currentTimestamp']) # code FIXME WHAT TO DO WITH THIS CODE??? # if isinstance(env['code'], str): # continue # else: # addr = 0 # FIXME # blk.set_code(addr, ''.join(map(chr, env['code']))) # setup state for address, h in pre.items(): check_testdata(h.keys(), ['code', 'nonce', 'balance', 'storage']) blk.set_balance(address, h['balance']) logger.debug('PRE Balance: %r: %r', address, h['balance']) blk._set_acct_item(address, 'nonce', h['nonce']) blk.set_code(address, ''.join(map(chr, h['code']))) assert h['storage'] == { } # FOR NOW test contracts don't seem to persist anything # execute transactions for i, exek in enumerate(execs): sender = exek['address'] # a party that originates a call recvaddr = exek['caller'] tx = transactions.Transaction(nonce=blk._get_acct_item( exek['caller'], 'nonce'), gasprice=int(exek['gasPrice']), startgas=int(exek['gas']), to=recvaddr, value=int(exek['value']), data=exek['data']) tx.sender = sender logger.debug('TX %r > %r v:%r gas:%s @price:%s', sender, recvaddr, tx.value, tx.startgas, tx.gasprice) # capture apply_message calls apply_message_calls = [] orig_apply_msg = processblock.apply_msg def apply_msg_wrapper(_block, _tx, msg): result, gas_remained, data = orig_apply_msg(_block, _tx, msg) apply_message_calls.append( dict(msg=msg, result=result, gas_remained=gas_remained, data=data)) return result, gas_remained, data processblock.apply_msg = apply_msg_wrapper success, output = processblock.apply_transaction(blk, tx) processblock.apply_msg = orig_apply_msg assert success assert len(callcreates) == len(apply_message_calls) # check against callcreates for i, callcreate in enumerate(callcreates): amc = apply_message_calls[i] assert callcreate['data'] == amc['data'] assert callcreate['gasLimit'] == amc['gas_remained'] assert callcreate['value'] == amc['msg'].value # data and out not set in tests yet assert output == params['out'] assert not params['out'] assert not callcreates['data'] # check state for address, h in post.items(): check_testdata(h.keys(), ['code', 'nonce', 'balance', 'storage']) logger.debug('POST: %r %r', address, h['balance']) blk.get_balance(address) == h['balance'] blk._get_acct_item(address, 'nonce') == h['nonce'] map(ord, blk.get_code(recvaddr)) == h['code'] assert storage == { } # FOR NOW test contracts don't seem to persist anything
def step_impl(context): word = 'a5b2cc1f54' msg = context.msg = '\x00'*(32-len(word))+word tx = transactions.Transaction(1, 100, 10**40, context.contract, 0, msg).sign(context.key) success, context.ans = processblock.apply_transaction(context.gen, tx) assert(success)
### From here is pasted together from earlier version of pyetherem import serpent from pyethereum import transactions, blocks, processblock, utils #processblock.print_debug = 1 from pyethereum import slogging slogging.set_level('eth.tx', "DEBUG") code = serpent.compile(namecoin_code) key = utils.sha3('cow') addr = utils.privtoaddr(key) genesis = blocks.genesis(new_db(), {addr: 10**18}) tx1 = transactions.contract(nonce=0, gasprice=10**12, startgas=10000, endowment=0, code=code).sign(key) result, contract = processblock.apply_transaction(genesis, tx1) print genesis.to_dict() tx2 = transactions.Transaction(nonce=1, gasprice=10**12, startgas=10000, to=contract, value=0, data=serpent.encode_abi(0, 1, 45)).sign(key) result, ans = processblock.apply_transaction(genesis, tx2) serpent.decode_datalist(ans) #print genesis.to_dict()
def do_test_vm(name): tempdir = tempfile.mktemp() logger.debug('running test:%r', name) params = vm_tests_fixtures()[name] # HOTFIFX # params['pre']['0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6']['balance'] *= 100 pre = params['pre'] execs = params['exec'] callcreates = params['callcreates'] env = params['env'] post = params['post'] check_testdata(env.keys(), ['code', 'currentGasLimit', 'currentTimestamp','previousHash', 'currentCoinbase', 'currentDifficulty', 'currentNumber']) # setup env blk = blocks.Block( prevhash=env['previousHash'].decode('hex'), number=int(env['currentNumber']), coinbase=env['currentCoinbase'], difficulty=int(env['currentDifficulty']), gas_limit=int(env['currentGasLimit']), timestamp=env['currentTimestamp']) # code FIXME WHAT TO DO WITH THIS CODE??? # if isinstance(env['code'], str): # continue # else: # addr = 0 # FIXME # blk.set_code(addr, ''.join(map(chr, env['code']))) # setup state for address, h in pre.items(): check_testdata(h.keys(), ['code', 'nonce', 'balance', 'storage']) blk.set_balance(address, h['balance']) logger.debug('PRE Balance: %r: %r', address, h['balance']) blk._set_acct_item(address,'nonce', h['nonce']) blk.set_code(address, ''.join(map(chr, h['code']))) assert h['storage'] == {} # FOR NOW test contracts don't seem to persist anything # execute transactions for i, exek in enumerate(execs): sender = exek['address'] # a party that originates a call recvaddr = exek['caller'] tx = transactions.Transaction(nonce=blk._get_acct_item(exek['caller'], 'nonce'), gasprice=int(exek['gasPrice']), startgas=int(exek['gas']), to=recvaddr, value=int(exek['value']), data=exek['data']) tx.sender = sender logger.debug('TX %r > %r v:%r gas:%s @price:%s', sender, recvaddr, tx.value, tx.startgas, tx.gasprice) # capture apply_message calls apply_message_calls = [] orig_apply_msg = processblock.apply_msg def apply_msg_wrapper(_block, _tx, msg): result, gas_remained, data = orig_apply_msg(_block, _tx, msg) apply_message_calls.append(dict(msg=msg, result=result, gas_remained=gas_remained, data=data)) return result, gas_remained, data processblock.apply_msg = apply_msg_wrapper success, output = processblock.apply_transaction(blk, tx) processblock.apply_msg = orig_apply_msg assert success assert len(callcreates) == len(apply_message_calls) # check against callcreates for i, callcreate in enumerate(callcreates): amc = apply_message_calls[i] assert callcreate['data'] == amc['data'] assert callcreate['gasLimit'] == amc['gas_remained'] assert callcreate['value'] == amc['msg'].value # data and out not set in tests yet assert output == params['out'] assert not params['out'] assert not callcreates['data'] # check state for address, h in post.items(): check_testdata(h.keys(), ['code', 'nonce', 'balance', 'storage']) logger.debug('POST: %r %r', address, h['balance']) blk.get_balance(address) == h['balance'] blk._get_acct_item(address,'nonce') == h['nonce'] map(ord, blk.get_code(recvaddr)) ==h['code'] assert storage == {} # FOR NOW test contracts don't seem to persist anything
def prepare_state_test(params): pre = params['pre'] exek = params['transaction'] env = params['env'] # setup env blk = blocks.Block(db, prevhash=env['previousHash'].decode('hex'), number=int(env['currentNumber']), coinbase=env['currentCoinbase'], difficulty=int(env['currentDifficulty']), gas_limit=int(env['currentGasLimit']), timestamp=int(env['currentTimestamp'])) for address, h in pre.items(): blk.set_nonce(address, int(h['nonce'])) blk.set_balance(address, int(h['balance'])) blk.set_code(address, h['code'][2:].decode('hex')) for k, v in h['storage'].iteritems(): blk.set_storage_data(address, u.big_endian_to_int(k[2:].decode('hex')), u.big_endian_to_int(v[2:].decode('hex'))) # execute transactions tx = transactions.Transaction(nonce=int(exek['nonce'] or "0"), gasprice=int(exek['gasPrice'] or "0"), startgas=int(exek['gasLimit'] or "0"), to=exek['to'], value=int(exek['value'] or "0"), data=exek['data'][2:].decode('hex')).sign( exek['secretKey']) orig_apply_msg = pb.apply_msg def apply_msg_wrapper(ext, msg, code): def blkhash(n): if n >= blk.number or n < blk.number - 256: return '' else: return u.sha3(str(n)) ext.block_hash = blkhash return orig_apply_msg(ext, msg, code) pb.apply_msg = apply_msg_wrapper blk2 = blocks.Block.deserialize(db, blk.serialize()) t1 = time.time() try: pb.apply_transaction(blk, tx) except: print 'exception' pass t2 = time.time() recorder = LogRecorder() try: pb.apply_transaction(blk2, tx) except: print 'exception' pass trace = recorder.pop_records() ops = [x['op'] for x in trace if x['event'] == 'vm'] opdict = {} for op in ops: opdict[op] = opdict.get(op, 0) + 1 return {"ops": opdict, "time": t2 - t1}