def apply_message(state, msg=None, **kwargs): if msg is None: msg = vm.Message(**kwargs) else: assert not kwargs ext = VMExt(state, transactions.Transaction(0, 0, 21000, b'', 0, b'')) result, gas_remained, data = apply_msg(ext, msg) return bytearray_to_bytestr(data) if result else None
def rawtx_to_ethtx(raw_tx_hex): (nonce, gasprice, gaslimit, to, value, data, v, r, s) = \ map(ethereum.utils.bytes_to_int, rlp.hex_decode(raw_tx_hex)) return transactions.Transaction(nonce=nonce, gasprice=gasprice, startgas=gaslimit, to=ethereum.utils.int_to_bytes(to), value=value, data=ethereum.utils.int_to_bytes(data), v=v, r=r, s=s)
def web3tx_to_ethtx(web3tx): to = '' if web3tx.to is None else \ ethereum.utils.int_to_bytes(int(web3tx.to[2:], 16)) input_data = ethereum.utils.remove_0x_head(web3tx.input) input_data = ethereum.utils.decode_hex(input_data) return transactions.Transaction(nonce=web3tx.nonce, gasprice=web3tx.gasPrice, startgas=web3tx.gas, to=to, value=web3tx.value, data=input_data, v=web3tx.v, r=ethereum.utils.bytes_to_int(web3tx.r), s=ethereum.utils.bytes_to_int(web3tx.s))
def test_encode(self): souvenir = transactions.Transaction() souvenir.type = 'debit' souvenir.post_date = datetime.date(2018, 9, 7) souvenir.description = 'Fairyland Souvenir Shop' souvenir.amount = 12.34 souvenir.tags = {} self.assertEqual( { 'type': 'debit', 'trans_date': None, 'post_date': '2018-09-07', 'description': 'Fairyland Souvenir Shop', 'amount': 12.34, 'tags': {}, }, souvenir.encode())
def _parse_line(key, line): ''' Parse a single `line` of account activity. ''' transaction = transactions.Transaction() tokens = _split_transaction_line(line) if key.type is not None: transaction.type = _parse_transaction_type(tokens[key.type]) if key.trans_date is not None: transaction.trans_date = _parse_transaction_date( tokens[key.trans_date]) if key.post_date is not None: transaction.post_date = _parse_transaction_date(tokens[key.post_date]) if key.description is not None: transaction.description = tokens[key.description] if key.amount is not None: transaction.amount = float(tokens[key.amount]) return transaction
def mktx(nonce, to, value, data): return transactions.Transaction(int(nonce), 10**12, 10000, to, int(value), data.decode('hex')).hex_serialize(False)
import processblock as pb import blocks as b import transactions as t import utils as u import sys k = u.sha3('cow') v = u.privtoaddr(k) k2 = u.sha3('horse') v2 = u.privtoaddr(k2) print "Starting boring transfer test" blk = b.Block.genesis({v: 10**18}) # Give tx2 some money tx = t.Transaction(0, 10**16, 10**12, 1000, v2, '').sign(k) pb.apply_tx(blk, tx) print "New balance of v1: ", blk.get_balance(v) print "New balance of v2: ", blk.get_balance(v2) print "Starting namecoin tests" blk = b.Block.genesis({v: 10**18}) scode1 = ''' if !contract.storage[msg.data[0]]: contract.storage[msg.data[0]] = msg.data[1] return(1) else: return(0) ''' code1 = serpent.compile(scode1) print "AST", serpent.rewrite(serpent.parse(scode1))
from chain_service import ChainService import transactions import db service = ChainService() transact = [] transact.append(transactions.Transaction(1, '', "192.168.9.1/28", 0, 'data', 1, 1, 1)) #to be serializable, address can be empty and transact.append(transactions.Transaction(2, '', "192.170.9.1/28", 0, 'data', 1, 1, 1)) #v, r, s have to be integers transact.append(transactions.Transaction(3, '', "192.172.9.1/28", 0, 'data', 1, 1, 1)) for i in range (0, len(transact)): service.add_transaction(transact[i]) #print('add_block') service.add_block() print('checking if exists block 0') if service.get_block_in_position_i(0) is not None: print ('exists') else: print ('not exists') print('checking if exists block 1') if service.get_block_in_position_i(1) is not None: print ('exists') else: print ('not exists')
def mktx(nonce, gasprice, startgas, to, value, data): return transactions.Transaction( int(nonce), gasprice, startgas, to, int(value), data.decode('hex') ).hex_serialize(False)
async def find_utxos(server: ServerInfo, master_key: BIP32, max_gap: int, max_account: int, address: Optional[str], fee_rate: Optional[int], should_broadcast: bool): """ Connect to an electrum server and find all the UTXOs spendable by a master key. """ print('⏳ Connecting to electrum server, this might take a while') client = StratumClient() await client.connect(server, disable_cert_verify=True) print('🌍 Connected to electrum server successfully') utxos = await scanner.scan_master_key(client, master_key, max_gap, max_account) if len(utxos) == 0: print('😔 Didn\'t find any unspent outputs') client.close() return balance = sum([utxo.amount_in_sat for utxo in utxos]) print(f'💸 Total spendable balance found: {balance} sats') if master_key.master_privkey is None: print('✍️ Re-run with a private key to create a sweep transaction') client.close() return if address is None: print('ℹ️ Re-run with `--address` to create a sweep transaction') client.close() return if fee_rate is None: fee_rate_in_btc_per_kb = await client.RPC('blockchain.estimatefee', 1) if fee_rate_in_btc_per_kb == -1: print( '🔁 Couldn\'t fetch fee rates, try again with manual fee rates using `--fee-rate`' ) client.close() return fee_rate = int(fee_rate_in_btc_per_kb * 10**8 / 1024) print(f'🚌 Fetched next-block fee rate of {fee_rate} sat/vbyte') tx_without_fee = transactions.Transaction(master_key, utxos, address, balance) fee = tx_without_fee.virtual_size() * fee_rate tx = transactions.Transaction(master_key, utxos, address, balance - fee) bin_tx = tx.to_bytes() print('👇 This transaction sweeps all funds to the address provided') print() print(bin_tx.hex()) print() if not should_broadcast: print( '📋 Copy this transaction and broadcast it manually to the network, or re-run with `--broadcast`' ) client.close() return try: print('📣 Broadcasting transaction to the network') txid = await client.RPC('blockchain.transaction.broadcast', bin_tx.hex()) print(f'✅ Transaction {txid} successfully broadcasted') except connectrum.exc.ElectrumErrorResponse as err: print(f'⛔️ Transaction broadcasting failed: {err}') client.close()
k2 = u.sha3('horse') v2 = u.privtoaddr(k2) print("Starting boring transfer test") blk = b.genesis({v: u.denoms.ether * 1}) assert blk.hex_hash() == \ b.Block.deserialize(blk.serialize()).hex_hash() # Give tx2 some money gasprice = 0 startgas = 10000 # nonce,gasprice,startgas,to,value,data,v,r,s tx = t.Transaction(0, gasprice, startgas, v2, u.denoms.finney * 10, '').sign(k) assert blk in set([blk]) assert tx in set([tx]) assert tx.hex_hash() == \ t.Transaction.deserialize(tx.serialize()).hex_hash() assert tx.hex_hash() == \ t.Transaction.hex_deserialize(tx.hex_serialize()).hex_hash() assert tx in set([tx]) assert not tx in blk.get_transactions() print("Balance of v1: ", blk.get_balance(v), v) success, res = pb.apply_tx(blk, tx) assert tx in blk.get_transactions() print("applied transaction", success, res)
def profile_vm_test(params, _): # file = open("Extime.csv", "a") pre = params['pre'] exek = params['exec'] env = params['env'] # setup env blkh = block.BlockHeader(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'])) block.Block(blkh, db=_env) state = State(env=_env, block_number=int(env['currentNumber']), block_coinbase=env['currentCoinbase'], block_difficulty=int(env['currentDifficulty']), gas_limit=int(env['currentGasLimit']), timestamp=int(env['currentTimestamp'])) # setup state for address, h in pre.items(): state.set_nonce(address, int(h['nonce'])) state.set_balance(address, int(h['balance'])) state.set_balance("cd1722f3947def4cf144679da39c4c32bdc35681", int(h['balance'])) state.set_code(address, h['code'][2:].decode('hex')) for k, v in h['storage'].iteritems(): state.set_storage_data(address, u.big_endian_to_int(k[2:].decode('hex')), u.big_endian_to_int(v[2:].decode('hex'))) # execute transactions sender = exek['origin'] # a party that originates a call recvaddr = exek['address'] tx = transactions.Transaction(nonce=state.get_nonce(exek['caller']), gasprice=int(exek['gasPrice']), startgas=int(exek['gas']), to=recvaddr, value=int(exek['value']), data=exek['data'][2:].decode('hex'), r=1, s=2, v=27) tx._sender = sender ext = pb.VMExt(state, tx) def blkhash(n): if n >= ext.block_number or n < ext.block_number - 256: return '' else: return u.sha3(str(n)) ext.block_hash = blkhash exTime = [] _nonce = 0 final_result = [] gasUsed = [] for curr_row in range(0, num_rows, 1): row_data = [] for curr_col in range(0, num_cols, 1): data = worksheet.cell_value( curr_row, curr_col) # Read the data in the current cell # print(data) row_data.append(data) result_data.append(row_data) # ext = pb.VMExt(state, tx) def blkhash(n): if n >= ext.block_number or n < ext.block_number - 256: return '' else: return u.sha3(str(n)) # ext.block_hash = blkhash _nonce1 = _nonce # print _nonce1 exTime = [] gasUsed = [] for i in range(10): tx = transactions.Transaction( nonce=_nonce1, gasprice=int(exek['gasPrice']), startgas=int(exek['gas']), to="", value=int(exek['value']), data=result_data[curr_row][2][2:].decode('hex'), r=1, s=2, v=27) _nonce1 = _nonce1 + 1 tx._sender = sender success, output, ext, gasused = pb.apply_transaction(state, tx) exTime.append(ext) gasUsed.append(gasused) _nonce = _nonce1 # recorder = LogRecorder() # recorder = LogRecorder(log_config=":trace") from messages import ExTime, CreationTime t1 = time.time() # print "Balance before mining is: ", state.get_balance(sender) # tx1 = transactions.Transaction( # nonce=1, # gasprice=int(exek['gasPrice']), # startgas=int(exek['gas']), # to=output, # value=int(exek['value']), # data="".decode('hex'), # r=1, s=2, v=27) # tx1._sender = sender # s2, o2 = pb.apply_transaction(state, tx1) # tx2 = transactions.Transaction( # nonce=2, # gasprice=int(exek['gasPrice']), # startgas=int(exek['gas']), # to=output, # value=int(exek['value']), # data="".decode('hex'), # r=1, s=2, v=27) # tx2._sender = sender # s3, o3 = pb.apply_transaction(state, tx2) # print "Balance after mining is: ", state.get_balance(sender) # print ext.log_storage(output) from _vm import vm_execute, Message, CallData, lisexTime, _list msg = Message(tx.sender, tx.to, tx.value, tx.startgas, CallData([ord(x) for x in tx.data])) # vm_execute(ext, msg, ext.get_code(msg.code_address)) success, gas_remained, comStack = vm_execute( ext, msg, exek['code'][2:].decode('hex')) state.commit() t2 = time.time() trace = recorder.pop_records() _time = [x['Time'] for x in trace if x['event'] == 'vm'] average = [] ops = [x['op'] for x in trace if x['event'] == 'vm'] opdict = {} for op in ops: opdict[op] = opdict.get(op, 0) + 1 for i in _time: for s, (t, ops) in i.iteritems(): if ops == "PUSH1": average.append(t) _average = float(sum(average)) / len(average) return {"ops": opdict, "time": t2 - t1} return { "Ops": exTime.get(0), "totalTime": t2 - t1, "Average": exTime.get(1) } average = [] _average1 = [] Gas = [] print 'most ccommon', Most_Common(_list) print 'least common', least_common(_list) print _list.count("PUSH1") if _[:3] not in ['PUS', 'SWA', 'DUP', 'SHA', 'MST']: opo = filter(lambda c: not c.isdigit(), _) else: opo = _[:-1] for p in lisexTime: if p["opcs"] == opo: _average1.append(p["Time"]) for p in lisexTime: if p["opcs"] == opo: average.append(p["Time"]) Gas.append(p["GasUsed"]) print opo print lisexTime print opo _average = float(sum(average)) / len(average) lisexTime.append({"average": _average}) lower, upper = mean_confidence_interval(_average1, confidence=0.95) stdv = statistics.stdev(_average1) print len(_list) print {"average": _average} print Gas return { 'Opcode': _, 'Occurrence': _list.count(opo), "Mean": _average, "Upper bound": upper, "Lower bound": lower, "95% Confidence Interval": (upper - lower) / 2, "Used Gas": Gas[0], "Standard Deviation": stdv }
import utils import transactions from apiserver import base_url base_url = "http://127.0.0.1:30203" + base_url k = utils.sha3('heiko') v = utils.privtoaddr(k) k2 = utils.sha3('horse') v2 = utils.privtoaddr(k2) # Give tx2 some money # nonce,gasprice,startgas,to,value,data,v,r,s value = 10**16 print value, 'from', v, 'to', v2 nonce = int(sys.argv[1]) tx = transactions.Transaction(nonce, gasprice=10**12, startgas=10000, to=v2, value=10**16, data='').sign(k) data = tx.hex_serialize() url = base_url + '/transactions/' print 'PUT', url, data r = requests.put(url, data) print r.status_code, r.reason, r.url
from random import randint env = Env(LevelDB('./chain')) chain = Chain(genesis=mk_genesis_data(env), env=env) prevhash = chain.head_hash prevnumber = chain.state.block_number for i in range(0, 20): print("iteration " + str(i)) block = Block( BlockHeader(timestamp=int(time.time()), prevhash=prevhash, number=prevnumber + 1)) t = trie.Trie(EphemDB()) for j in range(0, 3): transaction = transactions.Transaction(i * 3 + j, '', "192.172.9.1/28", 0, 'data', 1, 1, 1) block.transactions.append(transaction) t.update(rlp.encode(j), rlp.encode(transaction)) block.header.tx_root = t.root_hash chain.add_block(block) prevhash = block.hash prevnumber = prevnumber + 1 chain.process_time_queue() time.sleep(2) # para que timestamp (padre) != timestamp (hijo) block = chain.get_block_by_number(2) print("nonces for block " + str(2) + ": (" + str(len(block.transactions)) + " transactions in block)") for tx in block.transactions: print(tx.nonce)
def test_trans_date_as_string_realDate(self): x = transactions.Transaction() x.trans_date = datetime.date(2018, 9, 11) self.assertEqual('2018-09-11', x.trans_date_as_string)
def test_trans_date_as_string_None(self): x = transactions.Transaction() x.trans_date = None self.assertIsNone(x.trans_date_as_string)