Transactions

使用 Python trie 建構 transactionsTrie。為什麼我的 Transactionsroot 錯誤?

  • October 10, 2018

我正在嘗試用 python 建構一個 TransactionsTrie。我正在使用這個

$$ trie $$$$ 1 $$-圖書館。我按照說明進行操作。 編輯:刪除了原始問題,因為它很愚蠢。

@carver 非常感謝。你的回復真的很有幫助。所以我正在嘗試使用您從 py-evm 引用的方法。

這是我的完整程式碼:

import requests
import json
import ethereum.utils as utils
from eth.db.trie import make_trie_root_and_nodes as make_trie
from eth.rlp.transactions import BaseTransactionFields
from eth.rlp.transactions import BaseTransaction

url = 'https://ropsten.infura.io/1234'

headers = {
   "Content-Type": "application/json"
}
data = {}
data['jsonrpc'] = '2.0'
data['id'] = 1
data['method'] = 'eth_getBlockByHash'
data['params'] = ["0xd993562b847a2b61f858ee2baa2351f05e22d755d3657444f06a8c51f88a11f8", True]
data = json.dumps(data)

response = requests.post(url, headers=headers, data=str(data) )
print(response.text)
block = json.loads(response.text)
result = block['result']
raw_transactions = result['transactions']

transactions = tuple()
for tx in raw_transactions:
   nonce = tx['nonce']
   nonce = utils.int_to_big_endian(int(nonce[2:], 16))
   gas_price = tx['gasPrice']
   gas_price = utils.int_to_big_endian(int(gas_price[2:], 16))
   gas = tx['gas']
   gas = utils.int_to_big_endian(int(gas[2:], 16))
   to = tx['to']
   to = bin(int(to[2:], 16))
   value = tx['value']
   value = utils.int_to_big_endian(int(value[2:], 16))
   data = tx['input']
   print(data)
   if data != '0x':
       data = bin(int(data[2:], 16))
   else:
       data = bin(0)
   print(data)
   v = tx['v']
   v = utils.int_to_big_endian(int(v[2:], 16))
   r = tx['r']
   r = utils.int_to_big_endian(int(r[2:], 16))
   s = tx['s']
   s = utils.int_to_big_endian(int(s[2:], 16))
   f = BaseTransactionFields(nonce = nonce, gas_price = gas_price, gas = gas, to = to, value = value, data = data, v = v, r = r, s = s)
   transactions += tuple(f)

tx_root, _ = make_trie(transactions)
print(tx_root.hex())

我的 txRoot 仍然與 Block 中的不同。我究竟做錯了什麼?

在乙太坊中建構事務樹時,鍵和值都是 rlp 編碼的。關鍵是從零開始的包含順序,值是完整的交易(不是散列)。

您可以看到trinity 用於生成事務 trie的範例實用程序(為清晰起見進行了編輯):

items = tuple(rlp.encode(object) for object in rlp_objects)

kv_store = {}  # type: Dict[Hash32, bytes]
trie = HexaryTrie(kv_store, BLANK_ROOT_HASH)

for index, item in enumerate(items):
   index_key = rlp.encode(index, sedes=rlp.sedes.big_endian_int)
   trie[index_key] = item

transaction_root = trie.root_hash

引用自:https://ethereum.stackexchange.com/questions/59653