@ethereumjs/blockchain

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

A module to store and interact with blocks

原始使用文档
文档目录15 节
  1. Table of Contents
  2. Installation
  3. Getting Started
  4. Block Lookup
  5. Chain Iteration
  6. Hardfork by Head
  7. Custom Genesis
  8. Consensus Types
  9. Storage
  10. Supported Block Features
  11. Events and Debugging
  12. Browser
  13. API
  14. EthereumJS
  15. License

@ethereumjs/blockchain v10

NPM Package GitHub Issues Actions Status Code Coverage Discord

A module to store and interact with blocks.

Stores a sequential chain of @ethereumjs/block blocks, tracks the canonical head, and supports reorgs via putBlock(). Used by @ethereumjs/client and @ethereumjs/vm.

Runnable examples live in examples/.

Table of Contents

Installation

npm install @ethereumjs/blockchain

Getting Started

Use createBlockchain() — it awaits async initialization (genesis setup, consensus wiring):

import { createBlockchain } from '@ethereumjs/blockchain'
import { Common, Mainnet } from '@ethereumjs/common'

const common = new Common({ chain: Mainnet })
const blockchain = await createBlockchain({ common })
console.log(`Genesis hash: ${blockchain.genesisBlock.hash()}`)

Main constructors: createBlockchain(), createBlockchainFromBlocksData().

Pass validateBlocks: false / validateConsensus: false in examples and tests when blocks are intentionally incomplete.

Block Lookup

Retrieve blocks by number or hash after adding them with putBlock():

// ./examples/getBlock.ts

import { createBlock } from '@ethereumjs/block'
import { createBlockchain } from '@ethereumjs/blockchain'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { bytesToHex } from '@ethereumjs/util'

const main = async () => {
  const common = new Common({ chain: Mainnet, hardfork: Hardfork.Prague })
  const blockchain = await createBlockchain({
    validateBlocks: false,
    validateConsensus: false,
    common,
  })

  const block1 = createBlock(
    {
      header: {
        number: 1n,
        parentHash: blockchain.genesisBlock.hash(),
        difficulty: blockchain.genesisBlock.header.difficulty + 1n,
      },
    },
    { common, setHardfork: true },
  )
  const block2 = createBlock(
    {
      header: {
        number: 2n,
        parentHash: block1.header.hash(),
        difficulty: block1.header.difficulty + 1n,
      },
    },
    { common, setHardfork: true },
  )
  await blockchain.putBlock(block1)
  await blockchain.putBlock(block2)

  const byNumber = await blockchain.getBlock(2n)
  const byHash = await blockchain.getBlock(block2.hash())

  console.log(`Block ${byNumber.header.number} hash: ${bytesToHex(byNumber.hash())}`)
  console.log(`Lookup by hash matches: ${bytesToHex(byHash.hash()) === bytesToHex(block2.hash())}`)
}

void main()

Also: getBlocks(), getIteratorHead(), getLatestHeader().

Chain Iteration

Walk the canonical chain with iterator():

// ./examples/iterateChain.ts

import { createBlock } from '@ethereumjs/block'
import { createBlockchain } from '@ethereumjs/blockchain'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { bytesToHex } from '@ethereumjs/util'

const main = async () => {
  const common = new Common({ chain: Mainnet, hardfork: Hardfork.Prague })
  const blockchain = await createBlockchain({
    validateBlocks: false,
    validateConsensus: false,
    common,
  })

  const block = createBlock(
    {
      header: {
        number: 1n,
        parentHash: blockchain.genesisBlock.hash(),
        difficulty: blockchain.genesisBlock.header.difficulty + 1n,
      },
    },
    { common, setHardfork: true },
  )
  const block2 = createBlock(
    {
      header: {
        number: 2n,
        parentHash: block.header.hash(),
        difficulty: block.header.difficulty + 1n,
      },
    },
    { common, setHardfork: true },
  )
  await blockchain.putBlock(block)
  await blockchain.putBlock(block2)

  await blockchain.iterator('i', (block) => {
    const blockNumber = block.header.number.toString()
    const blockHash = bytesToHex(block.hash())
    console.log(`Block ${blockNumber}: ${blockHash}`)
  })
}
void main()

Hardfork by Head

Pin Common hardfork to the current head block number on init:

// ./examples/hardforkByHead.ts

import { createBlockchain } from '@ethereumjs/blockchain'
import { Common, Mainnet } from '@ethereumjs/common'

const main = async () => {
  const common = new Common({ chain: Mainnet })
  await createBlockchain({ common, hardforkByHeadBlockNumber: true })
  console.log(`Hardfork at genesis head: ${common.hardfork()}`)
}

void main()

Custom Genesis

Build a chain from a Geth genesis JSON file:

// ./examples/gethGenesis.ts

import { createBlockchain } from '@ethereumjs/blockchain'
import { createCommonFromGethGenesis, parseGethGenesisState } from '@ethereumjs/common'
import { postMergeGethGenesis } from '@ethereumjs/testdata'
import { bytesToHex } from '@ethereumjs/util'

const main = async () => {
  const common = createCommonFromGethGenesis(postMergeGethGenesis, { chain: 'customChain' })
  const genesisState = parseGethGenesisState(postMergeGethGenesis)
  const blockchain = await createBlockchain({
    genesisState,
    common,
  })
  const genesisBlockHash = blockchain.genesisBlock.hash()
  common.setForkHashes(genesisBlockHash)
  console.log(
    `Genesis hash from geth genesis parameters - ${bytesToHex(blockchain.genesisBlock.hash())}`,
  )
}

void main()

Built-in network genesis state lives in @ethereumjs/genesis. Access the genesis block via blockchain.genesisBlock.

Consensus Types

AlgorithmClassNotes
PoS (default post-merge)CasperConsensusDifficulty 0, beacon client does validation
PoW (pre-merge)EthashConsensusEthash difficulty rules
PoA (historical testnets)CliqueConsensusGoerli-style signer voting

Clique example:

// ./examples/clique.ts

import { CliqueConsensus, createBlockchain } from '@ethereumjs/blockchain'
import { Common, ConsensusAlgorithm, Hardfork } from '@ethereumjs/common'
import { goerliChainConfig } from '@ethereumjs/testdata'

import type { ConsensusDict } from '@ethereumjs/blockchain'

const main = async () => {
  const common = new Common({ chain: goerliChainConfig, hardfork: Hardfork.London })

  const consensusDict: ConsensusDict = {}
  consensusDict[ConsensusAlgorithm.Clique] = new CliqueConsensus()
  const blockchain = await createBlockchain({
    consensusDict,
    common,
  })
  console.log(`Created blockchain with ${blockchain.consensus!.algorithm} consensus algorithm`)
}

void main()

Custom consensus: implement the Consensus interface and pass via consensusDict or consensus option. See customConsensus.spec.ts.

Storage

Default DB is in-memory MapDB. For persistence, pass a DB-conforming backend (see @ethereumjs/client level wrapper).

Supported Block Features

  • EIP-1559 — base fee blocks (default post-London)
  • EIP-4844 — blob txs (requires KZG on Common, see @ethereumjs/tx)
  • EIP-7685 — CL requests in block headers
  • EIP-4895 — withdrawals

Events and Debugging

blockchain.events emits deletedCanonicalBlocks on reorgs.

Debug loggers: blockchain:#, blockchain:clique, blockchain:ethash. Enable with DEBUG=ethjs,blockchain:clique.

Browser

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

API

Generated TypeDoc documentation.

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/blockchain 共发布 77 个版本,首次发布于 2020/10/22;过去 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 年前

其他发布通道:beta → 6.0.0-beta.3,alpha → 8.0.0-alpha.1,rc → 10.0.0-rc.1,nightly → 10.1.1-nightly.2。

关于 @ethereumjs/blockchain 的常见问题

@ethereumjs/blockchain 是什么?

A module to store and interact with blocks

如何安装 @ethereumjs/blockchain?

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

@ethereumjs/blockchain 支持 TypeScript 吗?

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

@ethereumjs/blockchain 支持 ESM 还是 CommonJS?

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

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

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

@ethereumjs/blockchain 可以商用吗?

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

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

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

@ethereumjs/blockchain 还在维护吗?

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