[Ethereum] How to generate a raw transaction with data using Pyethereum

pyethereumraw-transactionweb3.py

How do you use Pyethereum to generate a raw tx to send to the blockchain? I can do it successfully with a transaction with no data, but when I am attempting to use data, it does not function properly.

To expand on this, I have pinpointed the problem to the data encoding. I can send a 1 ETH transaction with no data perfectly. I can send that same transaction with a string of data, say '0xabcdef' and it will go through the same, except the 'data' section on etherscan.io does not read '0xabcdef'. I believe this is the issue, but I do not know how to fix it.

To show an example, I am using this to create the transaction, and the following code works:

nonce = 100
gas_price = 10000000000
gas_limit = 22000
value = 1000000000000000000
data = ""
privkey = private_key_here

unencoded_tx = rlp.encode(transactions.Transaction(nonce, gas_price, gas_limit, to_address, value, data).sign(privkey))
signedtx = '0x' + codecs.encode(unencoded_tx, 'hex').decode('utf-8')

The following code, which is the same, but with data, also goes through, but the data is not what I expect:

nonce = 100
gas_price = 10000000000
gas_limit = 22000
value = 1000000000000000000
data = "0xabcdef"
privkey = private_key_here

unencoded_tx = rlp.encode(transactions.Transaction(nonce, gas_price, gas_limit, to_address, value, data).sign(privkey))
signedtx = '0x' + codecs.encode(unencoded_tx, 'hex').decode('utf-8')

Data output (according to etherscan.io): 0x3078616263646566

Obviously that is not the data I wanted to see. How can I pass in the same data I see on etherscan.io?

Best Answer

0x3078616263646566 is the hex representation of the UTF-8 encoding of the string "0xabcdef". "0" is hex 30, "x" is hex 78, and so on. Try passing in b'\xab\xcd\xef' as the data, instead.

You can generate this byte string from hex with:

import codecs
raw_bytes = codecs.decode('abcdef', 'hex')
assert raw_bytes == b'\xab\xcd\xef'

It's also worth checking out the package ethereum-utils for eth_utils.decode_hex() and other useful tools.

Related Topic