@ethereumjs/块 v10
| 执行与Ethereum区块有关的计划和功能. |
|---|
- 所有块特性直到 大阪( 大阪)
- *
- 受控制依赖的一组(4个外部+)
@noble密码) - 🔮
EIP-4844硬块 Txs - 🔮
EIP-7594PerDAS 集团交易 - 💸
EIP-4895灯塔链退出 - 📨
EIP-7685协商一致层请求 - 📋
EIP-7928区块级访问列表 Hash(阿姆斯特丹,实验性) - 🕐
EIP-7843Slot 编号页眉字段( Amsterdam, 实验) - QQ324KB 捆绑大小( 81KB gziped)
- QQ 无 WASM 默认 + 完整浏览器已准备好
可运行的示例 examples/。 。 。 .
目录
- 安装
- 开始
- 创建块
- EIP-1559 基费
- EIP-4895 退出
- EIP-4844 块块
- EIP-7685 CL 请求
- EIP-7928 屏蔽出入列表 Hash
- EIP-7843 槽数
- 协商一致类型
- 浏览器
- API 密码
- 测试
- 爱丽丝
- 许可证
安装
npm install @ethereumjs/block
说明: 对于 EIP-4844 需要设置 KZG 块 Common 看到了吗 @ethereumjs/tx KZG 设置。 。 。 .
开始
Block 财务报告和审定财务报表 BlockHeader 对象通过独立的工厂函数创建( 不) new Block()) (中文(简体) ). 属性默认被冻结( E)freeze: false 页:1.
// ./examples/createBlockHeader.ts
import { createBlockHeader } from '@ethereumjs/block'
import { bytesToHex } from '@ethereumjs/util'
import type { HeaderData } from '@ethereumjs/block'
const headerData: HeaderData = {
number: 15,
parentHash: '0x6bfee7294bf44572b7266358e627f3c35105e1c3851f3de09e6d646f955725a7',
gasLimit: 8000000,
timestamp: 1562422144,
}
const header = createBlockHeader(headerData)
console.log(`Created block header with hash=${bytesToHex(header.hash())}`)
主构造器 :
| 工厂 | 目的 |
|---|---|
createBlock() | 完整块从 BlockData |
createEmptyBlock() | 仅用页眉块块 |
createBlockFromRLP() | 解码序列化块字节 |
createBlockFromRPC() 编号 : createBlockFromJSONRPCProvider() | 从 JSON- RPC 块对象 |
createBlockFromExecutionPayload() 编号 : createBlockFromBeaconPayloadJSON() | 从 CL 执行有效载荷 |
createBlockHeader() | 以上仅标头的变体 |
三次帮助 : genTransactionsTrieRoot(), (中文(简体) ), genWithdrawalsTrieRoot(), (中文(简体) ), genRequestsRoot()。 。 。 .
创建块
与交易
// ./examples/createBlockWithTxs.ts
import { createBlock, genTransactionsTrieRoot } from '@ethereumjs/block'
import { Common, Mainnet } from '@ethereumjs/common'
import { createFeeMarket1559Tx } from '@ethereumjs/tx'
import { bytesToHex, createAddressFromString, hexToBytes } from '@ethereumjs/util'
const main = async () => {
const common = new Common({ chain: Mainnet })
const privateKey = hexToBytes('0xe331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109')
const tx = createFeeMarket1559Tx(
{
type: 2,
nonce: 0n,
gasLimit: 21_000n,
maxFeePerGas: 100n,
maxPriorityFeePerGas: 1n,
to: createAddressFromString('0xcccccccccccccccccccccccccccccccccccccccc'),
value: 1n,
},
{ common },
).sign(privateKey)
const block = createBlock({ transactions: [tx] }, { common, skipConsensusFormatValidation: true })
const transactionsRoot = await genTransactionsTrieRoot(block.transactions)
console.log(`Block with ${block.transactions.length} transaction(s)`)
console.log(`Transactions root: ${bytesToHex(transactionsRoot)}`)
}
void main()
RLP 往返
// ./examples/blockFromRLP.ts
import { createBlock, createBlockFromRLP } from '@ethereumjs/block'
import { Common, Mainnet } from '@ethereumjs/common'
import { bytesToHex } from '@ethereumjs/util'
const common = new Common({ chain: Mainnet })
const block = createBlock(
{
header: {
number: 1n,
gasLimit: 30_000_000n,
},
},
{ common, skipConsensusFormatValidation: true },
)
const serialized = block.serialize()
const decoded = createBlockFromRLP(serialized, { common })
console.log(`Serialized ${serialized.length} bytes`)
console.log(`Round-trip hash match: ${bytesToHex(decoded.hash()) === bytesToHex(block.hash())}`)
打电话 await block.validateData() 进行协商一致和交易核对。 使用 skipConsensusFormatValidation: true 当标题字段故意不完整时,在示例和测试中.
EIP-1559 基费
用默认主网创建块 Common 为: EIP-1559 (中文(简体) ) 兼容. BlockHeader.calcNextBaseFee() 计算儿童区的基本费用.
// ./examples/1559.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Mainnet } from '@ethereumjs/common'
import { createTx } from '@ethereumjs/tx'
const common = new Common({ chain: Mainnet })
const block = createBlock(
{
header: {
baseFeePerGas: BigInt(10),
gasLimit: BigInt(100),
gasUsed: BigInt(60),
},
},
{ common },
)
// Base fee will increase for next block since the
// gas used is greater than half the gas limit
console.log(Number(block.header.calcNextBaseFee())) // 11
// So for creating a block with a matching base fee in a certain
// chain context you can do:
const blockWithMatchingBaseFee = createBlock(
{
header: {
baseFeePerGas: block.header.calcNextBaseFee(),
gasLimit: BigInt(100),
gasUsed: BigInt(60),
},
},
{ common },
)
console.log(Number(blockWithMatchingBaseFee.header.baseFeePerGas)) // 11
// successful validation does not throw error
await blockWithMatchingBaseFee.validateData()
// failed validation throws error
const tx = createTx(
{ type: 2, maxFeePerGas: BigInt(20) },
{ common: new Common({ chain: Mainnet }) },
)
blockWithMatchingBaseFee.transactions.push(tx)
console.log(blockWithMatchingBaseFee.getTransactionsValidationErrors()) // invalid transaction added to block
try {
await blockWithMatchingBaseFee.validateData()
} catch (err) {
console.log(`Expected validation failure: ${(err as Error).message.split('\n')[0]}`)
}
EIP-4895 退出
上海+区块携带信标链退出. 提供 withdrawals 和一个匹配 withdrawalsRoot数字 :
// ./examples/withdrawals.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Mainnet } from '@ethereumjs/common'
import { Address, hexToBytes } from '@ethereumjs/util'
import type { WithdrawalData } from '@ethereumjs/util'
const common = new Common({ chain: Mainnet })
const withdrawal: WithdrawalData = {
index: BigInt(0),
validatorIndex: BigInt(0),
address: new Address(hexToBytes(`0x${'20'.repeat(20)}`)),
amount: BigInt(1000),
}
const block = createBlock(
{
header: {
withdrawalsRoot: hexToBytes(
'0x69f28913c562b0d38f8dc81e72eb0d99052444d301bf8158dc1f3f94a4526357',
),
},
withdrawals: [withdrawal],
},
{
common,
},
)
console.log(`Block with ${block.withdrawals!.length} withdrawal(s) created`)
验证提取程序 await block.withdrawalsTrieIsValid()。 。 。 .
EIP-4844 块块
坎昆+区块包括: excessBlobGas 财务报告和审定财务报表 blobGasUsedBlob txs 需要 KZG 打开 Common数字 :
// ./examples/eip4844Block.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { createBlob4844Tx } from '@ethereumjs/tx'
import { createAddressFromPrivateKey } from '@ethereumjs/util'
import { randomBytes } from '@noble/hashes/utils.js'
import { trustedSetup } from '@paulmillr/trusted-setups/fast-peerdas.js'
import { KZG as microEthKZG } from 'micro-eth-signer/kzg.js'
const main = async () => {
const kzg = new microEthKZG(trustedSetup)
const common = new Common({
chain: Mainnet,
customCrypto: {
kzg,
},
hardfork: Hardfork.Cancun,
})
const blobTx = createBlob4844Tx(
{ blobsData: ['myFirstBlob'], to: createAddressFromPrivateKey(randomBytes(32)) },
{ common },
)
const block = createBlock(
{
header: {
excessBlobGas: 0n,
},
transactions: [blobTx],
},
{
common,
skipConsensusFormatValidation: true,
},
)
console.log(
`4844 block header with excessBlobGas=${block.header.excessBlobGas} created and ${
block.transactions.filter((tx) => tx.type === 3).length
} blob transactions`,
)
}
void main()
标题中的 blob 气体定价 :
// ./examples/blobGasPrice.ts
import { createBlockHeader } from '@ethereumjs/block'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Cancun })
const header = createBlockHeader({ excessBlobGas: 1_000_000n }, { common })
console.log(`Blob gas price at excessBlobGas=1_000_000: ${header.getBlobGasPrice()}`)
EIP-7685 CL 请求
布拉格+区块 requestsHash 超度排序的共识层请求。 使用 genRequestsRoot() 财务报告和审定财务报表 @ethereumjs/util 请求类型 :
// ./examples/clrequests.ts
import { createBlock, genRequestsRoot } from '@ethereumjs/block'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { bytesToHex, createCLRequest, hexToBytes } from '@ethereumjs/util'
import { sha256 } from '@noble/hashes/sha2.js'
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Prague })
const depositData = hexToBytes(
'0x00ac842878bb70009552a4cfcad801d6e659c50bd50d7d03306790cb455ce7363c5b6972f0159d170f625a99b2064dbefc010000000000000000000000818ccb1c4eda80270b04d6df822b1e72dd83c3030040597307000000a747f75c72d0cf0d2b52504c7385b516f0523e2f0842416399f42b4aee5c6384a5674f6426b1cc3d0827886fa9b909e616f5c9f61f986013ed2b9bf37071cbae951136265b549f44e3c8e26233c0433e9124b7fd0dc86e82f9fedfc0a179d7690000000000000000',
)
const withdrawalData = hexToBytes(
'0x01000000000000000000000000000000000000000001000000000000000000000de0b6b3a7640000',
)
const consolidationData = hexToBytes('0x020000000100000000000000000000000000000000000001')
// Requests must be sorted by type (Deposit=0, Withdrawal=1, Consolidation=2)
const requests = [
createCLRequest(depositData),
createCLRequest(withdrawalData),
createCLRequest(consolidationData),
]
const requestsHash = genRequestsRoot(requests, sha256)
const block = createBlock({ header: { requestsHash } }, { common })
console.log(`Created ${requests.length} CL requests`)
console.log(`requestsHash: ${bytesToHex(requestsHash)}`)
console.log(`Block hash: ${bytesToHex(block.hash())}`)
EIP-7928 屏蔽出入列表 Hash
见 阿姆斯特丹州概况 内 @ethereumjs/vm 用于发布qq光谱跟踪.
何时 EIP-7928 (中文(简体) ) 活动( e)Hardfork.Amsterdam,实验性),区块携带a blockAccessListHash 头字段. 用这个计算 @ethereumjs/util 或从 runBlock({ generate: true }) 在越战中.
// ./examples/blockAccessListHash.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
import { bytesToHex, createBlockLevelAccessListFromJSON } from '@ethereumjs/util'
const main = () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Amsterdam })
const balJson = [
{
address: '0x0000000000000000000000000000000000000001',
storageChanges: [],
storageReads: [],
balanceChanges: [{ blockAccessIndex: '0x01', postBalance: '0x03e8' }],
nonceChanges: [],
codeChanges: [],
},
]
const bal = createBlockLevelAccessListFromJSON(balJson)
const block = createBlock(
{
header: {
blockAccessListHash: bal.hash(),
},
},
{ common, skipConsensusFormatValidation: true },
)
console.log(`blockAccessListHash: ${bytesToHex(block.header.blockAccessListHash!)}`)
console.log(`matches BAL hash: ${bytesToHex(bal.hash())}`)
console.log(`hash length: ${block.header.blockAccessListHash!.length} bytes`)
}
void main()
EIP-7843 槽数
何时 EIP-7843 活动( e)Hardfork.Amsterdam,实验性),区块携带a slotNumber 头字段. 明确设定,当构建块,或让 buildBlock() 默认从 parent.slotNumber + 1。 。 。 . runBlock({ generate: true }) 不创造协商一致的时间档。 欧洲议会 SLOTNUM 操作码( o)0x4b阅读这个字段——见 @ethereumjs/evm 斯洛文尼亚。 。 。 .
// ./examples/blockSlotNumber.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
const main = () => {
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Amsterdam })
const block = createBlock(
{
header: {
slotNumber: 42n,
},
},
{ common, skipConsensusFormatValidation: true },
)
console.log(`slotNumber: ${block.header.slotNumber}`)
}
void main()
协商一致类型
证据( 默认)
发生后区块(Hardfork.Paris ) 使用 PoS 页眉规则——困难 0,无微粒,以及相关 EIP-3675 (单位:千美元) 变化 :
// ./examples/pos.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Mainnet } from '@ethereumjs/common'
const common = new Common({ chain: Mainnet })
const block = createBlock(
{
// Provide your block data here or use default values
},
{ common },
)
console.log(`Proof-of-Stake (default) block created with hardfork=${block.common.hardfork()}`)
埃塔什/波瓦
预先出现或专用的扑克链:
// ./examples/pow.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
const common = new Common({ chain: Mainnet, hardfork: Hardfork.Chainstart })
console.log(common.consensusType()) // 'pow'
console.log(common.consensusAlgorithm()) // 'ethash'
createBlock({}, { common })
console.log(`Old Proof-of-Work block created`)
过 calcDifficultyFromHeader 与父标题一起自动计算难度.
Clique / 行动纲领
为历史PoA测试网块(如:Goerli). 使用 createSealedCliqueBlock() 带有 cliqueSigner 即时封存的密钥 :
// ./examples/clique.ts
import { createBlock } from '@ethereumjs/block'
import { Common, Hardfork } from '@ethereumjs/common'
import { goerliChainConfig } from '@ethereumjs/testdata'
const common = new Common({ chain: goerliChainConfig, hardfork: Hardfork.Chainstart })
console.log(common.consensusType()) // 'poa'
console.log(common.consensusAlgorithm()) // 'clique'
createBlock({ header: { extraData: new Uint8Array(97) } }, { common })
console.log(`Old Clique Proof-of-Authority block created`)
Clique 公用功能( E)cliqueSigner, (中文(简体) ), cliqueVerifySignature,.)在《行动纲领》背景之外抛出.
浏览器
我们为所有图书馆提供混合的无害环境管理/CJS。 随着从2025年春季开始的v10断开发行回合,所有的库都是默认的"纯-JS",我们已经取消了所有硬接通的WASM代码. 此外,我们还大幅度地降低了捆绑大小,减少了依赖性的数量,并切除了Node.js特定原始物的所有用法(如Node.js事件发射器).
在现代浏览器内使用所提供的无害环境管理架构运行一个EthereumJS图书馆的浏览器是很容易的。 关于设置的例子,见 ./例/浏览器.html。 。 。 .
API 密码
生成类型文件 文档。 。 。 .
每个 Block 编号 : BlockHeader 以 Common 实例,可决定活动硬叉、EIP集和验证规则。 见 @ethereumjs/常见 用于链式配置.
WASM 加密后端可以通过 Common.customCrypto ——见: 普通读取器。 。 。 .
测试
测试 tests 目录部分过时;主要报道来自 BlockchainTests 内 @ ethereumjs/vm (英语)。 。 。 .
包装 乙醇/测试 当地JSON装置,使用 包装测试。 。 。 .
爱丽丝
这个 EthereumJS GitHub组织及其寄存器由原Ethereum基金会JavaScript团队和更广泛的Ethereum社区的成员管理. 如果您想参加工作或改进图书馆,请查看 开发者文件 * 概述现行标准和工具,并审查 行为守则。 。 。 .