首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ethereumjs计算事务从BlockBodies消息中运行根哈希

使用ethereumjs计算事务从BlockBodies消息中运行根哈希
EN

Ethereum用户
提问于 2020-03-18 05:28:26
回答 1查看 262关注 0票数 1

给定已解码的BlockBodies消息,我希望计算事务trie的根散列,以便将其与我的节点下载的块头进行匹配。

在回顾了云母事务树是如何形成的并扫描了围棋OpenEthereum (nee奇偶)空想块的源代码之后,我觉得自己已经接近了--但我仍然没有得到正确的结果。

下面是我代码中的重要部分:

代码语言:javascript
复制
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')}`)

下面是我运行代码时得到的信息:

代码语言:javascript
复制
Expected tx root: 0xcee16501e007fe5240aa50faa96cce60c7de8ae56f34044d850e378b98e04537
Actual   tx root: 0x8147ebbcffc667ee12746a2154299728a46435f4078d2f6f8b113e34f2758c6b

我已经验证了transactionsRaw包含正确的数据,方法是取消对每个事务的序列化,并将它们的散列与恩弗拉进行比较。

我觉得我只是把错误的键/值放进trie,但我找不到任何例子,而比较散列并不能提供很多反馈

我在这里做错什么了?

EN

回答 1

Ethereum用户

回答已采纳

发布于 2020-03-18 22:37:32

在回顾了ethereumjs-block:Block.genTxTrie()是如何做到的之后,我设法弄明白了:

代码语言:javascript
复制
const trie = new Trie()
await Promise.all(transactionsRaw.map((t, i) =>
  new Promise(resolve => {
    trie.put(
      rlp.encode(i),
      new Transaction(t).serialize(),
      resolve
    )
  })
))

代码语言:javascript
复制
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())
))

而且起作用了

代码语言:javascript
复制
Expected tx root: 0xcee16501e007fe5240aa50faa96cce60c7de8ae56f34044d850e378b98e04537
Actual   tx root: 0xcee16501e007fe5240aa50faa96cce60c7de8ae56f34044d850e378b98e04537

merkle-patricia-tree:BaseTrie.batch()得到错误结果的原因是,该方法只对底层的LevelDB实例进行操作,而不是实际的patricia!

票数 2
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/80661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档