# @ethereumjs/mpt 中文文档

规范地址：https://npmcn.com/package/%40ethereumjs/mpt/

版本：10\.1\.3
npm 元数据更新时间：2026-08-21T12:53:56.087Z
中文译文更新时间：2026-11-13T23:39:15.231Z
软件包许可：MPL-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40ethereumjs/mpt
原文对照：https://npmcn.com/package/%40ethereumjs/mpt/?lang=original
项目主页：https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/mpt#readme
源码仓库：https://github.com/ethereumjs/ethereumjs-monorepo

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：667 kB，204 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20
- 运行依赖：5 个
- 首次发布：2024-10-17T09:30:58.075Z
- 最新版本发布：2026-08-21T12:53:55.879Z
- 近 30 天下载量：255882（2026-10-14 至 2026-11-12，npm 官方下载统计）
- 已发布版本数：9（近 12 个月 5 个）

## 中文简介

实施伊特鲁姆"黄纸"所指明的经过改造的"墨克勒活生生树".

## 安装

```sh
npm install @ethereumjs/mpt
```

也可以使用：`pnpm add @ethereumjs/mpt`、`yarn add @ethereumjs/mpt`、`bun add @ethereumjs/mpt`

## README

# @ethereumjs/mpt (英语) `v10`

[![NPM Package](https://img.shields.io/npm/v/@ethereumjs/mpt.svg)](https://www.npmjs.com/package/@ethereumjs/mpt) [![GitHub Issues](https://img.shields.io/github/issues/ethereumjs/ethereumjs-monorepo/package:%20mpt?label=issues)](https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aopen+is%3Aissue+label%3A%22package%3A+mpt%22) [![Actions Status](https://github.com/ethereumjs/ethereumjs-monorepo/workflows/Trie/badge.svg)](https://github.com/ethereumjs/ethereumjs-monorepo/actions?query=workflow%3A%22Trie%22) [![Code Coverage](https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/branch/master/graph/badge.svg?flag=mpt)](https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/tree/master/packages/mpt) [![Discord](https://img.shields.io/static/v1?logo=discord&label=discord&message=Join&color=blue)](https://discord.gg/TNwARpR)

| 执行《公约》 [修改后的梅克勒·帕特里夏·特里](https://ethereum.org/en/developers/docs/data-structures-and-encoding/patricia-merkle-trie/) 一、导 言 [黄纸](http://gavwood.com/Paper.pdf) |
| --- |

-   高度可扩展
-   \*
-   控制下的依赖(3个外部+) `@Noble` 密码)
-   \* 检查站功能
-   软存储后端
-   ⚖️ `EIP-1186` 证据
-   QQ 176KB 捆绑大小( 48KB gziped)
-   QQ 无 WASM 默认 + 完整浏览器已准备好

可运行的示例 [`examples/`](https://npmcn.com/package/%40ethereumjs/mpt/examples/)。额外的走过: [`examples/README.md`](https://npmcn.com/package/%40ethereumjs/mpt/examples/README.md)。 。 。 .

## 目录

-   [安装](https://npmcn.com/package/%40ethereumjs/mpt/#readme-installation)
-   [开始](https://npmcn.com/package/%40ethereumjs/mpt/#readme-getting-started)
-   [检查站](https://npmcn.com/package/%40ethereumjs/mpt/#readme-checkpoints)
-   [走着走着](https://npmcn.com/package/%40ethereumjs/mpt/#readme-walking-a-trie)
-   [默克勒证明](https://npmcn.com/package/%40ethereumjs/mpt/#readme-merkle-proofs)
-   [证明书上的崔](https://npmcn.com/package/%40ethereumjs/mpt/#readme-trie-from-proof)
-   [数值地图](https://npmcn.com/package/%40ethereumjs/mpt/#readme-value-map)
-   [存储后端](https://npmcn.com/package/%40ethereumjs/mpt/#readme-storage-backends)
-   [根持久与奔跑](https://npmcn.com/package/%40ethereumjs/mpt/#readme-root-persistence-and-pruning)
-   [浏览器](https://npmcn.com/package/%40ethereumjs/mpt/#readme-browser)
-   [API 密码](https://npmcn.com/package/%40ethereumjs/mpt/#readme-api)
-   [基准制定](https://npmcn.com/package/%40ethereumjs/mpt/#readme-benchmarking)
-   [调试](https://npmcn.com/package/%40ethereumjs/mpt/#readme-debugging)
-   [参考资料](https://npmcn.com/package/%40ethereumjs/mpt/#readme-references)
-   [爱丽丝](https://npmcn.com/package/%40ethereumjs/mpt/#readme-ethereumjs)
-   [许可证](https://npmcn.com/package/%40ethereumjs/mpt/#readme-license)

## 安装

```shell
npm install @ethereumjs/mpt
```

## 开始

使用 `createMPT()` (建议)或 `new MerklePatriciaTrie()` 直接说 与 `useKeyHashing: true` (Ethreeum Production 默认),键被先用keccak256来散开后再找取.

```ts
// ./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()
```

主构造器 : `createMPT()`, (中文(简体) ), `createMPTFromProof()`, (中文(简体) ), `new MerklePatriciaTrie(opts)`。 。 。 .

酌情在返回的节点上默认冻结财产。 通过 a `Common` 与 `customCrypto` wASM的散列后端——见 [@ethereumjs/常见](https://npmcn.com/package/%40ethereumjs/common#custom-cryptography-wasm--kzg)。 。 。 .

## 检查站

嵌入 `checkpoint()` 编号 : `commit()` 编号 : `revert()` 用于投机性写作的堆栈 `@ethereumjs/statemanager` 财务报告和审定财务报表 `@ethereumjs/vm`:

```ts
// ./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()
```

## 走着走着

`walkTrieIterable()` 产量 `{ node, currentKey }` 用于 `for await` 循环。 使用 `walkTrie()` 与 `WalkController` 当您需要并行的 DB 读取或每个节点的转录控制时(见 API docs).

```ts
// ./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()
```

## 默克勒证明

[EIP-1186 (英语)](https://eips.ethereum.org/EIPS/eip-1186) 建立和核实证据:

```ts
// ./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()
```

范围证明 : `verifyMPTRangeProof()` 用于snap-sync风格的叶片范围.

## 证明书上的崔

从现有证据中构建一个部分的三进制——对轻客户端和 `@ethereumjs/statemanager`数字 :

```ts
// ./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()
```

## 数值地图

倾出叶键/值对 `getValueMap()`数字 :

```ts
// ./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()
```

## 存储后端

传出任何 `@ethereumjs/util` `DB` 执行 `opts.db`默认为记忆 `MapDB`。 。 。 .

| 示例 | 后端 |
| --- | --- |
| [`examples/level.js`](https://npmcn.com/package/%40ethereumjs/mpt/examples/level.js) | LevelDB( 由 `@ethereumjs/client`(中文(简体) ) |
| [`examples/lmdb.js`](https://npmcn.com/package/%40ethereumjs/mpt/examples/lmdb.js) | 语言数据库 |
| [`recipes/level.ts`](https://npmcn.com/package/%40ethereumjs/mpt/recipes/level.ts) | TypeScript LevelDB 包装食谱 |

```ts
// ./examples/customLevelDB.ts (excerpt)

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

执行 [`DB` 接口](https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/util/src/db.ts) 用于自定义后端.

## 根持久与奔跑

坚持三重击根 :

```ts
// ./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()
```

启用 `useNodePruning: true` 以删除 DB 中已替换的节点( 保存磁盘空间; 只有在不需要历史三重状态时才安全).

## 浏览器

提供了混合无害环境管理/CJS大楼。 见 [./例/浏览器.html](https://npmcn.com/package/%40ethereumjs/mpt/examples/browser.html)。 。 。 .

## API 密码

生成类型文件 [文档](https://npmcn.com/package/%40ethereumjs/mpt/docs/README.md)。 。 。 .

## 基准制定

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

## 调试

使用 [调试](https://github.com/visionmedia/debug) 软件包。 启用方式 `DEBUG=ethjs,mpt` (见先前文件中的完整日志表或运行) `DEBUG=ethjs,mpt:* npm test`) (中文(简体) ).

## 参考资料

-   [Ethereum 三重奏规格](https://github.com/ethereum/wiki/wiki/Patricia-Tree)
-   [默克林在伊特鲁姆](https://blog.ethereum.org/2015/11/15/merkling-in-ethereum/)
-   [Trie和Patricia Trie概览(视频)](https://www.youtube.com/watch?v=jXAHLqQthKw&t=26s)

## 爱丽丝

这个 `EthereumJS` GitHub组织及其寄存器由原Ethereum基金会JavaScript团队和更广泛的Ethereum社区的成员管理. 如果您想参加工作或改进图书馆,请查看 [开发者文件](https://npmcn.com/package/DEVELOPER.md) \* 概述现行标准和工具,并审查 [行为守则](https://npmcn.com/package/CODE_OF_CONDUCT.md)。 。 。 .

## 许可证

[MPL - 2.0 导弹](https://tldrlegal.com/license/mozilla-public-license-2.0-\(mpl-2\))

## 常见问题

### @ethereumjs/mpt 是什么？

实施伊特鲁姆"黄纸"所指明的经过改造的"墨克勒活生生树"\.

### 如何安装 @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 和提交记录判断。

