chainlib-eth

Ethereum implementation of the chainlib interface
Info | Log | Files | Refs | README | LICENSE

transaction.py (2208B)


      1 # standard imports
      2 import os
      3 
      4 # external imports
      5 from crypto_dev_signer.keystore.dict import DictKeystore
      6 from crypto_dev_signer.eth.signer import ReferenceSigner as EIP155Signer
      7 from hexathon import (
      8         add_0x,
      9         strip_0x,
     10         )
     11 
     12 # local imports
     13 from chainlib.chain import ChainSpec
     14 from chainlib.eth.nonce import OverrideNonceOracle
     15 from chainlib.eth.gas import OverrideGasOracle
     16 from chainlib.eth.tx import (
     17         TxFactory,
     18         TxFormat,
     19         unpack,
     20         pack,
     21         raw,
     22         )
     23 
     24 # eth transactions need an explicit chain parameter as part of their signature
     25 chain_spec = ChainSpec.from_chain_str('evm:ethereum:1')
     26 
     27 # create keystore and signer
     28 keystore = DictKeystore()
     29 signer = EIP155Signer(keystore)
     30 sender_address = keystore.new()
     31 recipient_address = keystore.new()
     32 
     33 # explicitly set nonce and gas parameters on this transaction
     34 nonce_oracle = OverrideNonceOracle(sender_address, 0)
     35 gas_oracle = OverrideGasOracle(price=1000000000, limit=21000)
     36 
     37 # create a new transaction
     38 tx_factory = TxFactory(chain_spec, signer=signer, nonce_oracle=nonce_oracle, gas_oracle=gas_oracle)
     39 tx = tx_factory.template(sender_address, recipient_address, use_nonce=True)
     40 tx['value'] = 1024
     41 (tx_hash, tx_rpc) = tx_factory.finalize(tx)
     42 
     43 print('transaction hash: ' + tx_hash)
     44 print('jsonrpc payload: ' + str(tx_rpc))
     45 
     46 # create a new transaction, but output in raw rlp format 
     47 tx = tx_factory.template(sender_address, recipient_address, use_nonce=True) # will now have increased nonce by 1
     48 tx['value'] = 1024
     49 (tx_hash, tx_signed_raw) = tx_factory.finalize(tx, tx_format=TxFormat.RLP_SIGNED) 
     50 print('transaction hash: ' + tx_hash)
     51 print('raw rlp payload: ' + tx_signed_raw)
     52 
     53 # convert tx from raw RLP 
     54 tx_signed_raw_bytes = bytes.fromhex(strip_0x(tx_signed_raw))
     55 tx_src = unpack(tx_signed_raw_bytes, chain_spec)
     56 print('tx parsed from rlp payload: ' + str(tx_src))
     57 
     58 # .. and back
     59 tx_signed_raw_bytes_recovered = pack(tx_src, chain_spec)
     60 tx_signed_raw_recovered = add_0x(tx_signed_raw_bytes_recovered.hex())
     61 print('raw rlp payload re-parsed: ' + tx_signed_raw_recovered)
     62 
     63 # create a raw send jsonrpc payload from the raw RLP
     64 o = raw(tx_signed_raw_recovered)
     65 print('jsonrpc payload: ' + str(o))