@ethereumjs/mpt

中文文档
10.1.3发布于 2026/08/21MPL-2.0TypeScriptESM + CJS近 30 天下载 25.6万

Implementation of the modified merkle patricia tree as specified in Ethereum's yellow paper.

原始使用文档
文档目录17 节
  1. Table of Contents
  2. Installation
  3. Getting Started
  4. Checkpoints
  5. Walking a Trie
  6. Merkle Proofs
  7. Trie from Proof
  8. Value Map
  9. Storage Backends
  10. Root Persistence and Pruning
  11. Browser
  12. API
  13. Benchmarking
  14. Debugging
  15. References
  16. EthereumJS
  17. License

@ethereumjs/mpt v10

NPM Package GitHub Issues Actions Status Code Coverage Discord

Implementation of the Modified Merkle Patricia Trie as specified in the Ethereum Yellow Paper
  • 🔭 Highly scalable
  • 🌴 Tree-shakeable API
  • 👷🏼 Controlled dependency set (3 external + @Noble crypto)
  • ⏳ Checkpoint Functionality
  • 🛢️ Flexible storage backends
  • ⚖️ EIP-1186 Proofs
  • 🛵 176KB bundle size (48KB gzipped)
  • 🏄🏾‍♂️ WASM-free default + Fully browser ready

Runnable examples live in examples/. Additional walk-throughs: examples/README.md.

Table of Contents

Installation

npm install @ethereumjs/mpt

Getting Started

Use createMPT() for the async factory (recommended) or new MerklePatriciaTrie() directly. With useKeyHashing: true (Ethereum production default), keys are hashed with keccak256 before lookup.

// ./examples/basicUsage.ts

import { createMPT } from '@ethereumjs/mpt'
import { MapDB, bytesToUtf8, utf8ToBytes } from '@ethereumjs/util'

async function test() {
  const trie = await createMPT({ db: new MapDB() })
  await trie.put(utf8ToBytes('test'), utf8ToBytes('one'))
  const value = await trie.get(utf8ToBytes('test'))
  console.log(value ? bytesToUtf8(value) : 'not found') // 'one'
}

void test()

Main constructors: createMPT(), createMPTFromProof(), new MerklePatriciaTrie(opts).

Properties are frozen by default on returned nodes where applicable. Pass a Common with customCrypto for WASM hashing backends — see @ethereumjs/common.

Checkpoints

Nested checkpoint() / commit() / revert() stack for speculative writes (used by @ethereumjs/statemanager and @ethereumjs/vm):

// ./examples/checkpoint.ts

import { createMPT } from '@ethereumjs/mpt'
import { bytesToHex, hexToBytes } from '@ethereumjs/util'

const main = async () => {
  const trie = await createMPT()
  const key = hexToBytes('0x11')

  await trie.put(key, hexToBytes('0xaa'))
  trie.checkpoint()
  await trie.put(key, hexToBytes('0xbb'))
  console.log(`In checkpoint: ${bytesToHex((await trie.get(key))!)}`)

  await trie.revert()
  console.log(`After revert: ${bytesToHex((await trie.get(key))!)}`)

  trie.checkpoint()
  await trie.put(key, hexToBytes('0xcc'))
  await trie.commit()
  console.log(`After commit: ${bytesToHex((await trie.get(key))!)}`)
}

void main()

Walking a Trie

walkTrieIterable() yields { node, currentKey } pairs for for await loops. Use walkTrie() with WalkController when you need concurrent DB reads or per-node traversal control (see API docs).

// ./examples/trieWalking.ts

import { createMPT } from '@ethereumjs/mpt'
import { utf8ToBytes } from '@ethereumjs/util'

async function main() {
  const trie = await createMPT()
  await trie.put(utf8ToBytes('key'), utf8ToBytes('val'))
  const walk = trie.walkTrieIterable(trie.root())

  for await (const { node, currentKey } of walk) {
    console.log({ node, currentKey })
  }
}
void main()

Merkle Proofs

EIP-1186 proof creation and verification:

// ./examples/proofs.ts

import { MerklePatriciaTrie, createMerkleProof, verifyMPTWithMerkleProof } from '@ethereumjs/mpt'
import { bytesToUtf8, utf8ToBytes } from '@ethereumjs/util'

const trie = new MerklePatriciaTrie()

async function main() {
  const k1 = utf8ToBytes('key1')
  const k2 = utf8ToBytes('key2')
  const v1 = utf8ToBytes('one')
  const v2 = utf8ToBytes('two')

  // proof-of-inclusion
  await trie.put(k1, v1)
  let proof = await createMerkleProof(trie, k1)
  let value = await verifyMPTWithMerkleProof(trie, trie.root(), k1, proof)
  console.log(value ? bytesToUtf8(value) : 'not found') // 'one'

  // proof-of-exclusion
  await trie.put(k1, v1)
  await trie.put(k2, v2)
  proof = await createMerkleProof(trie, utf8ToBytes('key3'))
  value = await verifyMPTWithMerkleProof(trie, trie.root(), utf8ToBytes('key3'), proof)
  console.log(value ? bytesToUtf8(value) : 'null') // null

  // invalid proof
  await trie.put(k1, v1)
  await trie.put(k2, v2)
  proof = await createMerkleProof(trie, k2)
  proof[0].reverse()
  try {
    const _value = await verifyMPTWithMerkleProof(trie, trie.root(), k2, proof)
  } catch (err) {
    console.log(`Invalid proof rejected: ${(err as Error).message.split('\n')[0]}`)
  }
}

void main()

Range proofs: verifyMPTRangeProof() for snap-sync style leaf ranges.

Trie from Proof

Build a partial trie from existing proofs — useful for light clients and @ethereumjs/statemanager:

// ./examples/createFromProof.ts

import {
  MerklePatriciaTrie,
  createMPTFromProof,
  createMerkleProof,
  updateMPTFromMerkleProof,
} from '@ethereumjs/mpt'
import { bytesToUtf8, utf8ToBytes } from '@ethereumjs/util'

async function main() {
  const k1 = utf8ToBytes('keyOne')
  const k2 = utf8ToBytes('keyTwo')

  const someOtherTrie = new MerklePatriciaTrie({ useKeyHashing: true })
  await someOtherTrie.put(k1, utf8ToBytes('valueOne'))
  await someOtherTrie.put(k2, utf8ToBytes('valueTwo'))

  const proof = await createMerkleProof(someOtherTrie, k1)
  const trie = await createMPTFromProof(proof, { useKeyHashing: true })
  const otherProof = await createMerkleProof(someOtherTrie, k2)

  await updateMPTFromMerkleProof(trie, otherProof)

  const value = await trie.get(k1)
  console.log(bytesToUtf8(value!)) // valueOne
  const otherValue = await trie.get(k2)
  console.log(bytesToUtf8(otherValue!)) // valueTwo
}

void main()

Value Map

Dump leaf key/value pairs with getValueMap():

// ./examples/getValueMap.ts

import { createMPT } from '@ethereumjs/mpt'
import { bigIntToBytes, hexToBytes } from '@ethereumjs/util'

const main = async () => {
  const trie = await createMPT({})
  const entries: [Uint8Array, string][] = [
    [bigIntToBytes(1n), '0x' + '0a'.repeat(32)],
    [bigIntToBytes(2n), '0x' + '0b'.repeat(32)],
    [bigIntToBytes(3n), '0x' + '0c'.repeat(32)],
  ]

  for (const entry of entries) {
    await trie.put(entry[0], hexToBytes(entry[1]))
  }

  const dump = await trie.getValueMap()
  console.log(`All leaf values: ${Object.keys(dump.values).length} entries`)

  const selectiveDump = await trie.getValueMap(1n, 2)
  console.log(`Selective dump: ${Object.keys(selectiveDump.values).length} entries`)
}

void main()

Storage Backends

Pass any @ethereumjs/util DB implementation via opts.db. Default is in-memory MapDB.

ExampleBackend
examples/level.jsLevelDB (used by @ethereumjs/client)
examples/lmdb.jsLMDB
recipes/level.tsTypeScript LevelDB wrapper recipe
// ./examples/customLevelDB.ts (excerpt)

// const trie = new MerklePatriciaTrie({ db: new LevelDB(new Level('MY_TRIE_DB_LOCATION')) })

Implement the DB interface for custom backends.

Root Persistence and Pruning

Persist the trie root across restarts:

// ./examples/rootPersistence.ts

import { createMPT } from '@ethereumjs/mpt'
import { bytesToHex } from '@ethereumjs/util'

async function main() {
  const trie = await createMPT({
    useRootPersistence: true,
  })

  console.log(bytesToHex(trie.root())) // 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421
}
void main()

Enable useNodePruning: true to delete superseded nodes from the DB (saves disk space; only safe when you do not need historical trie states).

Browser

Hybrid ESM/CJS builds are provided. See ./examples/browser.html.

API

Generated TypeDoc documentation.

Benchmarking

npm run benchmarks   # random PUT + checkpointing benchmarks
npm run profiling    # flamegraph via 0x

Debugging

Uses the debug package. Enable with DEBUG=ethjs,mpt (see full logger table in previous docs or run DEBUG=ethjs,mpt:* npm test).

References

EthereumJS

The EthereumJS GitHub organization and its repositories are managed by members of the former Ethereum Foundation JavaScript team and the broader Ethereum community. If you want to join for work or carry out improvements on the libraries see the developer docs for an overview of current standards and tools and review our code of conduct.

License

MPL-2.0

版本与发布记录

@ethereumjs/mpt 共发布 9 个版本,首次发布于 2024/10/17;过去 12 个月发布了 5 个版本。

版本发布日期距今
10.1.3latest2026/08/212 个月前
10.1.22026/05/295 个月前
10.1.12026/01/289 个月前
10.1.1-nightly.2nightly2026/01/199 个月前
10.1.1-nightly.12025/12/0411 个月前
10.1.02025/11/071 年前

其他发布通道:alpha → 7.0.0-alpha.1,rc → 10.0.0-rc.1,nightly → 10.1.1-nightly.2。

关于 @ethereumjs/mpt 的常见问题

@ethereumjs/mpt 是什么?

Implementation of the modified merkle patricia tree as specified in Ethereum's yellow paper.

如何安装 @ethereumjs/mpt?

在项目目录运行 npm install @ethereumjs/mpt,或使用 pnpm add / yarn add / bun add。

@ethereumjs/mpt 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ethereumjs/mpt 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ethereumjs/mpt 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@ethereumjs/mpt 可以商用吗?

@ethereumjs/mpt 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@ethereumjs/mpt 的下载量有多少?

根据 npm 官方下载统计,@ethereumjs/mpt 在 2026/10/14 – 2026/11/12 这 30 天内被下载 255,882 次,日均约 8,529 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ethereumjs/mpt 还在维护吗?

最新版本 10.1.3 发布于 2026/08/21(2 个月前);至今共发布 9 个版本,其中过去 12 个月发布了 5 个;首次发布于 2024/10/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。