给定已解码的BlockBodies消息,我希望计算事务trie的根散列,以便将其与我的节点下载的块头进行匹配。
在回顾了云母事务树是如何形成的并扫描了围棋、OpenEthereum (nee奇偶)和空想块的源代码之后,我觉得自己已经接近了--但我仍然没有得到正确的结果。
下面是我代码中的重要部分:
const { Transaction } = require('ethereumjs-tx')
const { rlp, toBuffer } = require('ethereumjs-util')
const Trie = require('merkle-patricia-tree')
// Construct a Patricia trie, using each transaction's index as the key, and the
// raw transaction body as the value.
const tree = new Trie()
tree.batch(transactionsRaw.map((t, i) => ({
type: 'put',
key: rlp.encode(toBuffer(i)),
value: new Transaction(t).serialize()
})))
// According to Infura, the transactions trie root for block 9069000 is...
console.log('Expected tx root: 0xcee16501e007fe5240aa50faa96cce60c7de8ae56f34044d850e378b98e04537')
// And this is what my code generates...
console.log(`Actual tx root: 0x${tree.root.toString('hex')}`)下面是我运行代码时得到的信息:
Expected tx root: 0xcee16501e007fe5240aa50faa96cce60c7de8ae56f34044d850e378b98e04537
Actual tx root: 0x8147ebbcffc667ee12746a2154299728a46435f4078d2f6f8b113e34f2758c6b我已经验证了transactionsRaw包含正确的数据,方法是取消对每个事务的序列化,并将它们的散列与恩弗拉进行比较。
我觉得我只是把错误的键/值放进trie,但我找不到任何例子,而比较散列并不能提供很多反馈
我在这里做错什么了?
发布于 2020-03-18 22:37:32
在回顾了ethereumjs-block:Block.genTxTrie()是如何做到的之后,我设法弄明白了:
const trie = new Trie()
await Promise.all(transactionsRaw.map((t, i) =>
new Promise(resolve => {
trie.put(
rlp.encode(i),
new Transaction(t).serialize(),
resolve
)
})
))或
const trie = new Trie()
const put = util.promisify(trie.put.bind(trie))
await Promise.all(transactionsRaw.map((t, i) =>
put(rlp.encode(i), new Transaction(t).serialize())
))而且起作用了
Expected tx root: 0xcee16501e007fe5240aa50faa96cce60c7de8ae56f34044d850e378b98e04537
Actual tx root: 0xcee16501e007fe5240aa50faa96cce60c7de8ae56f34044d850e378b98e04537merkle-patricia-tree:BaseTrie.batch()得到错误结果的原因是,该方法只对底层的LevelDB实例进行操作,而不是实际的patricia!
https://ethereum.stackexchange.com/questions/80661
复制相似问题