@feelyourprotocol/block 8141.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +466 -0
  3. package/dist/cjs/block/block.d.ts +147 -0
  4. package/dist/cjs/block/block.d.ts.map +1 -0
  5. package/dist/cjs/block/block.js +415 -0
  6. package/dist/cjs/block/block.js.map +1 -0
  7. package/dist/cjs/block/constructors.d.ts +77 -0
  8. package/dist/cjs/block/constructors.d.ts.map +1 -0
  9. package/dist/cjs/block/constructors.js +298 -0
  10. package/dist/cjs/block/constructors.js.map +1 -0
  11. package/dist/cjs/block/index.d.ts +3 -0
  12. package/dist/cjs/block/index.d.ts.map +1 -0
  13. package/dist/cjs/block/index.js +19 -0
  14. package/dist/cjs/block/index.js.map +1 -0
  15. package/dist/cjs/consensus/clique.d.ts +52 -0
  16. package/dist/cjs/consensus/clique.d.ts.map +1 -0
  17. package/dist/cjs/consensus/clique.js +144 -0
  18. package/dist/cjs/consensus/clique.js.map +1 -0
  19. package/dist/cjs/consensus/ethash.d.ts +9 -0
  20. package/dist/cjs/consensus/ethash.d.ts.map +1 -0
  21. package/dist/cjs/consensus/ethash.js +13 -0
  22. package/dist/cjs/consensus/ethash.js.map +1 -0
  23. package/dist/cjs/consensus/index.d.ts +3 -0
  24. package/dist/cjs/consensus/index.d.ts.map +1 -0
  25. package/dist/cjs/consensus/index.js +29 -0
  26. package/dist/cjs/consensus/index.js.map +1 -0
  27. package/dist/cjs/from-beacon-payload.d.ts +36 -0
  28. package/dist/cjs/from-beacon-payload.d.ts.map +1 -0
  29. package/dist/cjs/from-beacon-payload.js +48 -0
  30. package/dist/cjs/from-beacon-payload.js.map +1 -0
  31. package/dist/cjs/header/constructors.d.ts +39 -0
  32. package/dist/cjs/header/constructors.d.ts.map +1 -0
  33. package/dist/cjs/header/constructors.js +127 -0
  34. package/dist/cjs/header/constructors.js.map +1 -0
  35. package/dist/cjs/header/header.d.ts +134 -0
  36. package/dist/cjs/header/header.d.ts.map +1 -0
  37. package/dist/cjs/header/header.js +699 -0
  38. package/dist/cjs/header/header.js.map +1 -0
  39. package/dist/cjs/header/index.d.ts +3 -0
  40. package/dist/cjs/header/index.d.ts.map +1 -0
  41. package/dist/cjs/header/index.js +19 -0
  42. package/dist/cjs/header/index.js.map +1 -0
  43. package/dist/cjs/helpers.d.ts +59 -0
  44. package/dist/cjs/helpers.d.ts.map +1 -0
  45. package/dist/cjs/helpers.js +172 -0
  46. package/dist/cjs/helpers.js.map +1 -0
  47. package/dist/cjs/index.d.ts +8 -0
  48. package/dist/cjs/index.d.ts.map +1 -0
  49. package/dist/cjs/index.js +31 -0
  50. package/dist/cjs/index.js.map +1 -0
  51. package/dist/cjs/package.json +3 -0
  52. package/dist/cjs/params.d.ts +3 -0
  53. package/dist/cjs/params.d.ts.map +1 -0
  54. package/dist/cjs/params.js +97 -0
  55. package/dist/cjs/params.js.map +1 -0
  56. package/dist/cjs/types.d.ts +228 -0
  57. package/dist/cjs/types.d.ts.map +1 -0
  58. package/dist/cjs/types.js +3 -0
  59. package/dist/cjs/types.js.map +1 -0
  60. package/dist/esm/block/block.d.ts +147 -0
  61. package/dist/esm/block/block.d.ts.map +1 -0
  62. package/dist/esm/block/block.js +411 -0
  63. package/dist/esm/block/block.js.map +1 -0
  64. package/dist/esm/block/constructors.d.ts +77 -0
  65. package/dist/esm/block/constructors.d.ts.map +1 -0
  66. package/dist/esm/block/constructors.js +286 -0
  67. package/dist/esm/block/constructors.js.map +1 -0
  68. package/dist/esm/block/index.d.ts +3 -0
  69. package/dist/esm/block/index.d.ts.map +1 -0
  70. package/dist/esm/block/index.js +3 -0
  71. package/dist/esm/block/index.js.map +1 -0
  72. package/dist/esm/consensus/clique.d.ts +52 -0
  73. package/dist/esm/consensus/clique.d.ts.map +1 -0
  74. package/dist/esm/consensus/clique.js +132 -0
  75. package/dist/esm/consensus/clique.js.map +1 -0
  76. package/dist/esm/consensus/ethash.d.ts +9 -0
  77. package/dist/esm/consensus/ethash.d.ts.map +1 -0
  78. package/dist/esm/consensus/ethash.js +10 -0
  79. package/dist/esm/consensus/ethash.js.map +1 -0
  80. package/dist/esm/consensus/index.d.ts +3 -0
  81. package/dist/esm/consensus/index.d.ts.map +1 -0
  82. package/dist/esm/consensus/index.js +3 -0
  83. package/dist/esm/consensus/index.js.map +1 -0
  84. package/dist/esm/from-beacon-payload.d.ts +36 -0
  85. package/dist/esm/from-beacon-payload.d.ts.map +1 -0
  86. package/dist/esm/from-beacon-payload.js +45 -0
  87. package/dist/esm/from-beacon-payload.js.map +1 -0
  88. package/dist/esm/header/constructors.d.ts +39 -0
  89. package/dist/esm/header/constructors.d.ts.map +1 -0
  90. package/dist/esm/header/constructors.js +120 -0
  91. package/dist/esm/header/constructors.js.map +1 -0
  92. package/dist/esm/header/header.d.ts +134 -0
  93. package/dist/esm/header/header.d.ts.map +1 -0
  94. package/dist/esm/header/header.js +695 -0
  95. package/dist/esm/header/header.js.map +1 -0
  96. package/dist/esm/header/index.d.ts +3 -0
  97. package/dist/esm/header/index.d.ts.map +1 -0
  98. package/dist/esm/header/index.js +3 -0
  99. package/dist/esm/header/index.js.map +1 -0
  100. package/dist/esm/helpers.d.ts +59 -0
  101. package/dist/esm/helpers.d.ts.map +1 -0
  102. package/dist/esm/helpers.js +161 -0
  103. package/dist/esm/helpers.js.map +1 -0
  104. package/dist/esm/index.d.ts +8 -0
  105. package/dist/esm/index.d.ts.map +1 -0
  106. package/dist/esm/index.js +8 -0
  107. package/dist/esm/index.js.map +1 -0
  108. package/dist/esm/package.json +3 -0
  109. package/dist/esm/params.d.ts +3 -0
  110. package/dist/esm/params.d.ts.map +1 -0
  111. package/dist/esm/params.js +94 -0
  112. package/dist/esm/params.js.map +1 -0
  113. package/dist/esm/types.d.ts +228 -0
  114. package/dist/esm/types.d.ts.map +1 -0
  115. package/dist/esm/types.js +2 -0
  116. package/dist/esm/types.js.map +1 -0
  117. package/dist/tsconfig.prod.cjs.tsbuildinfo +1 -0
  118. package/dist/tsconfig.prod.esm.tsbuildinfo +1 -0
  119. package/package.json +75 -0
  120. package/src/block/block.ts +526 -0
  121. package/src/block/constructors.ts +407 -0
  122. package/src/block/index.ts +2 -0
  123. package/src/consensus/clique.ts +171 -0
  124. package/src/consensus/ethash.ts +11 -0
  125. package/src/consensus/index.ts +12 -0
  126. package/src/from-beacon-payload.ts +82 -0
  127. package/src/header/constructors.ts +169 -0
  128. package/src/header/header.ts +890 -0
  129. package/src/header/index.ts +2 -0
  130. package/src/helpers.ts +223 -0
  131. package/src/index.ts +13 -0
  132. package/src/params.ts +95 -0
  133. package/src/types.ts +254 -0
package/README.md ADDED
@@ -0,0 +1,466 @@
1
+ # @ethereumjs/block `v10`
2
+
3
+ [![NPM Package][block-npm-badge]][block-npm-link]
4
+ [![GitHub Issues][block-issues-badge]][block-issues-link]
5
+ [![Actions Status][block-actions-badge]][block-actions-link]
6
+ [![Code Coverage][block-coverage-badge]][block-coverage-link]
7
+ [![Discord][discord-badge]][discord-link]
8
+
9
+ | Implements schema and functions related to Ethereum blocks. |
10
+ | ----------------------------------------------------------- |
11
+
12
+ - 🦄 All block features till **Osaka**
13
+ - 🌴 Tree-shakeable API
14
+ - 👷🏼 Controlled dependency set (4 external + `@noble` crypto)
15
+ - 🔮 `EIP-4844` Shard Blob Txs
16
+ - 🔮 `EIP-7594` PeerDAS Blob Transactions
17
+ - 💸 `EIP-4895` Beacon Chain Withdrawals
18
+ - 📨 `EIP-7685` Consensus Layer Requests
19
+ - 🛵 324KB bundle size (81KB gzipped)
20
+ - 🏄🏾‍♂️ WASM-free default + Fully browser ready
21
+
22
+ ## Table of Contents
23
+
24
+ - [Installation](#installation)
25
+ - [Getting Started](#getting-started)
26
+ - [EIP Integrations](#eip-integrations)
27
+ - [Consensus Types](#consensus-types)
28
+ - [Browser](#browser)
29
+ - [API](#api)
30
+ - [Testing](#testing)
31
+ - [EthereumJS](#ethereumjs)
32
+ - [License](#license)
33
+
34
+ ## Installation
35
+
36
+ To obtain the latest version, simply install the project using `npm`:
37
+
38
+ ```shell
39
+ npm install @ethereumjs/block
40
+ ```
41
+
42
+ **Note:** If you want to work with `EIP-4844` related functionality, you will have additional initialization steps for the **KZG setup**, see related section below.
43
+
44
+ ## Getting Started
45
+
46
+ ### Instantiation
47
+
48
+ There are several standalone functions to instantiate a `Block`:
49
+
50
+ - `createBlock(blockData: BlockData = {}, opts?: BlockOptions)`
51
+ - `createEmptyBlock(headerData: HeaderData, opts?: BlockOptions)`
52
+ - `createBlockFromBytesArray(values: BlockBytes, opts?: BlockOptions)`
53
+ - `createBlockFromRLP(serialized: Uint8Array, opts?: BlockOptions)`
54
+ - `createBlockFromRPC(blockParams: JSONRPCBlock, uncles?: any[], opts?: BlockOptions)`
55
+ - `createBlockFromJSONRPCProvider(provider: string | EthersProvider, blockTag: string | bigint, opts: BlockOptions)`
56
+ - `createBlockFromExecutionPayload(payload: ExecutionPayload, opts?: BlockOptions)`
57
+ - `createBlockFromBeaconPayloadJSON(payload: BeaconPayloadJSON, opts?: BlockOptions)`
58
+ - `createSealedCliqueBlock(blockData: BlockData = {}, cliqueSigner: Uint8Array, opts?: BlockOptions)`
59
+
60
+ For `BlockHeader` instantiation, there are similar standalone functions:
61
+
62
+ - `createBlockHeader(headerData: HeaderData = {}, opts?: BlockOptions)`
63
+ - `createBlockHeaderFromBytesArray(values: BlockHeaderBytes, opts?: BlockOptions)`
64
+ - `createBlockHeaderFromRLP(serializedHeaderData: Uint8Array, opts?: BlockOptions)`
65
+ - `createBlockHeaderFromRPC(blockParams: JSONRPCBlock, options?: BlockOptions)`
66
+ - `createSealedCliqueBlockHeader(headerData: HeaderData = {}, cliqueSigner: Uint8Array, opts?: BlockOptions)`
67
+
68
+ Instantiation Example:
69
+
70
+ ```ts
71
+ // ./examples/simple.ts
72
+
73
+ import { createBlockHeader } from '@ethereumjs/block'
74
+ import { bytesToHex } from '@ethereumjs/util'
75
+
76
+ import type { HeaderData } from '@ethereumjs/block'
77
+
78
+ const headerData: HeaderData = {
79
+ number: 15,
80
+ parentHash: '0x6bfee7294bf44572b7266358e627f3c35105e1c3851f3de09e6d646f955725a7',
81
+ gasLimit: 8000000,
82
+ timestamp: 1562422144,
83
+ }
84
+ const header = createBlockHeader(headerData)
85
+ console.log(`Created block header with hash=${bytesToHex(header.hash())}`)
86
+ ```
87
+
88
+ Properties of a `Block` or `BlockHeader` object are frozen with `Object.freeze()` which gives you enhanced security and consistency properties when working with the instantiated object. This behavior can be modified using the `freeze` option in the constructor if needed.
89
+
90
+ API Usage Example:
91
+
92
+ ```ts
93
+ // ./examples/1559.ts#L46-L50
94
+
95
+ try {
96
+ await blockWithMatchingBaseFee.validateData()
97
+ } catch (err) {
98
+ console.log(err) // block validation fails
99
+ }
100
+ ```
101
+
102
+ ### WASM Crypto Support
103
+
104
+ This library by default uses JavaScript implementations for the basic standard crypto primitives like hashing or signature verification (for included txs). See `@ethereumjs/common` [README](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/common) for instructions on how to replace with e.g. a more performant WASM implementation by using a shared `common` instance.
105
+
106
+ ## EIP Integrations
107
+
108
+ ### Blocks with an EIP-1559 Fee Market
109
+
110
+ By default (since `Hardfork.London`) blocks created with this library are [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) compatible.
111
+
112
+ ```ts
113
+ // ./examples/1559.ts
114
+
115
+ import { createBlock } from '@ethereumjs/block'
116
+ import { Common, Mainnet } from '@ethereumjs/common'
117
+ import { createTx } from '@ethereumjs/tx'
118
+ const common = new Common({ chain: Mainnet })
119
+
120
+ const block = createBlock(
121
+ {
122
+ header: {
123
+ baseFeePerGas: BigInt(10),
124
+ gasLimit: BigInt(100),
125
+ gasUsed: BigInt(60),
126
+ },
127
+ },
128
+ { common },
129
+ )
130
+
131
+ // Base fee will increase for next block since the
132
+ // gas used is greater than half the gas limit
133
+ console.log(Number(block.header.calcNextBaseFee())) // 11
134
+
135
+ // So for creating a block with a matching base fee in a certain
136
+ // chain context you can do:
137
+ const blockWithMatchingBaseFee = createBlock(
138
+ {
139
+ header: {
140
+ baseFeePerGas: block.header.calcNextBaseFee(),
141
+ gasLimit: BigInt(100),
142
+ gasUsed: BigInt(60),
143
+ },
144
+ },
145
+ { common },
146
+ )
147
+
148
+ console.log(Number(blockWithMatchingBaseFee.header.baseFeePerGas)) // 11
149
+
150
+ // successful validation does not throw error
151
+ await blockWithMatchingBaseFee.validateData()
152
+
153
+ // failed validation throws error
154
+ const tx = createTx(
155
+ { type: 2, maxFeePerGas: BigInt(20) },
156
+ { common: new Common({ chain: Mainnet }) },
157
+ )
158
+ blockWithMatchingBaseFee.transactions.push(tx)
159
+ console.log(blockWithMatchingBaseFee.getTransactionsValidationErrors()) // invalid transaction added to block
160
+ try {
161
+ await blockWithMatchingBaseFee.validateData()
162
+ } catch (err) {
163
+ console.log(err) // block validation fails
164
+ }
165
+
166
+ ```
167
+
168
+ ### Blocks with EIP-4895 Beacon Chain Withdrawals
169
+
170
+ Starting with the `v4.1.0` release there is support for [EIP-4895](https://eips.ethereum.org/EIPS/eip-4895) beacon chain withdrawals (`Hardfork.Shanghai` or higher). To create a block containing system-level withdrawals, the `withdrawals` data option together with a matching `withdrawalsRoot` can be used:
171
+
172
+ ```ts
173
+ // ./examples/withdrawals.ts
174
+
175
+ import { createBlock } from '@ethereumjs/block'
176
+ import { Common, Mainnet } from '@ethereumjs/common'
177
+ import { Address, hexToBytes } from '@ethereumjs/util'
178
+
179
+ import type { WithdrawalData } from '@ethereumjs/util'
180
+
181
+ const common = new Common({ chain: Mainnet })
182
+
183
+ const withdrawal: WithdrawalData = {
184
+ index: BigInt(0),
185
+ validatorIndex: BigInt(0),
186
+ address: new Address(hexToBytes(`0x${'20'.repeat(20)}`)),
187
+ amount: BigInt(1000),
188
+ }
189
+
190
+ const block = createBlock(
191
+ {
192
+ header: {
193
+ withdrawalsRoot: hexToBytes(
194
+ '0x69f28913c562b0d38f8dc81e72eb0d99052444d301bf8158dc1f3f94a4526357',
195
+ ),
196
+ },
197
+ withdrawals: [withdrawal],
198
+ },
199
+ {
200
+ common,
201
+ },
202
+ )
203
+
204
+ console.log(`Block with ${block.withdrawals!.length} withdrawal(s) created`)
205
+
206
+ ```
207
+
208
+ Validation of the withdrawals trie can be manually triggered with the newly introduced async `Block.withdrawalsTrieIsValid()` method.
209
+
210
+ ### Blocks with EIP-4844 Shard Blob Transactions
211
+
212
+ This library supports the blob transaction type introduced with [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) (`Hardfork.Cancun` or higher), see the following example:
213
+
214
+ ```ts
215
+ // ./examples/4844.ts
216
+
217
+ import { createBlock } from '@ethereumjs/block'
218
+ import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
219
+ import { createBlob4844Tx } from '@ethereumjs/tx'
220
+ import { createAddressFromPrivateKey } from '@ethereumjs/util'
221
+ import { randomBytes } from '@noble/hashes/utils.js'
222
+ import { trustedSetup } from '@paulmillr/trusted-setups/fast-peerdas.js'
223
+ import { KZG as microEthKZG } from 'micro-eth-signer/kzg.js'
224
+
225
+ const main = async () => {
226
+ const kzg = new microEthKZG(trustedSetup)
227
+
228
+ const common = new Common({
229
+ chain: Mainnet,
230
+ customCrypto: {
231
+ kzg,
232
+ },
233
+ hardfork: Hardfork.Cancun,
234
+ })
235
+ const blobTx = createBlob4844Tx(
236
+ { blobsData: ['myFirstBlob'], to: createAddressFromPrivateKey(randomBytes(32)) },
237
+ { common },
238
+ )
239
+
240
+ const block = createBlock(
241
+ {
242
+ header: {
243
+ excessBlobGas: 0n,
244
+ },
245
+ transactions: [blobTx],
246
+ },
247
+ {
248
+ common,
249
+ skipConsensusFormatValidation: true,
250
+ },
251
+ )
252
+
253
+ console.log(
254
+ `4844 block header with excessBlobGas=${block.header.excessBlobGas} created and ${
255
+ block.transactions.filter((tx) => tx.type === 3).length
256
+ } blob transactions`,
257
+ )
258
+ }
259
+
260
+ void main()
261
+
262
+ ```
263
+
264
+ **Note:** Working with blob transactions needs a manual KZG library installation and global initialization, see [KZG Setup](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/tx/README.md#kzg-setup) for instructions.
265
+
266
+ ### Blocks with EIP-7685 Consensus Layer Requests
267
+
268
+ Starting with v10 this library supports requests to the consensus layer which have been introduced with [EIP-7685](https://eips.ethereum.org/EIPS/eip-7685) (`Hardfork.Prague` or higher). See the `@ethereumjs/util` [Request](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/util#module-request) README section for an overview of current request types.
269
+
270
+ ```ts
271
+ // ./examples/clrequests.ts
272
+
273
+ import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
274
+ import { CLRequestType, bytesToHex, createCLRequest, hexToBytes } from '@ethereumjs/util'
275
+ import { sha256 } from '@noble/hashes/sha2.js'
276
+
277
+ import { createBlock, genRequestsRoot } from '../src'
278
+
279
+ // Enable EIP-7685 to support CLRequests
280
+ const common = new Common({ chain: Mainnet, hardfork: Hardfork.Cancun, eips: [7685] })
281
+
282
+ // Create examples of the three CLRequest types
283
+ const createExampleRequests = () => {
284
+ // Create a deposit request (type 0)
285
+ const depositData = hexToBytes(
286
+ '0x00ac842878bb70009552a4cfcad801d6e659c50bd50d7d03306790cb455ce7363c5b6972f0159d170f625a99b2064dbefc010000000000000000000000818ccb1c4eda80270b04d6df822b1e72dd83c3030040597307000000a747f75c72d0cf0d2b52504c7385b516f0523e2f0842416399f42b4aee5c6384a5674f6426b1cc3d0827886fa9b909e616f5c9f61f986013ed2b9bf37071cbae951136265b549f44e3c8e26233c0433e9124b7fd0dc86e82f9fedfc0a179d7690000000000000000',
287
+ )
288
+ const depositRequest = createCLRequest(depositData)
289
+
290
+ // Create a withdrawal request (type 1)
291
+ const withdrawalData = hexToBytes(
292
+ '0x01000000000000000000000000000000000000000001000000000000000000000de0b6b3a7640000',
293
+ )
294
+ const withdrawalRequest = createCLRequest(withdrawalData)
295
+
296
+ // Create a consolidation request (type 2)
297
+ const consolidationData = hexToBytes('0x020000000100000000000000000000000000000000000001')
298
+ const consolidationRequest = createCLRequest(consolidationData)
299
+
300
+ // CLRequests must be sorted by type (Deposit=0, Withdrawal=1, Consolidation=2)
301
+ return [depositRequest, withdrawalRequest, consolidationRequest]
302
+ }
303
+
304
+ // Generate a block with CLRequests
305
+ function createBlockWithCLRequests() {
306
+ const requests = createExampleRequests()
307
+ console.log(`Created ${requests.length} CLRequests:`)
308
+
309
+ for (const req of requests) {
310
+ console.log(
311
+ `- Type: ${req.type} (${Object.keys(CLRequestType).find(
312
+ (k) => CLRequestType[k as keyof typeof CLRequestType] === req.type,
313
+ )})`,
314
+ )
315
+ }
316
+
317
+ // Generate the requestsHash by hashing all the CLRequests
318
+ const requestsHash = genRequestsRoot(requests, sha256)
319
+ console.log(`Generated requestsHash: 0x${bytesToHex(requestsHash)}`)
320
+
321
+ // Create a block with the CLRequests hash
322
+ const block = createBlock({ header: { requestsHash } }, { common })
323
+ console.log(`Created block hash: 0x${bytesToHex(block.hash())}`)
324
+
325
+ return block
326
+ }
327
+
328
+ // Execute
329
+ createBlockWithCLRequests()
330
+
331
+ ```
332
+
333
+ ### Consensus Types
334
+
335
+ ### Proof-of-Stake
336
+
337
+ By default (`Hardfork.Paris` (aka: Merge) and higher) blocks are created as Proof-of-Stake blocks. These blocks come with their own set of header field simplifications and associated validation rules. The difficulty is set to `0` since not relevant anymore, just to name an example. For a full list of changes see [EIP-3675](https://eips.ethereum.org/EIPS/eip-3675).
338
+
339
+ You can instantiate a Merge/PoS block like this:
340
+
341
+ ```ts
342
+ // ./examples/pos.ts
343
+
344
+ import { createBlock } from '@ethereumjs/block'
345
+ import { Common, Mainnet } from '@ethereumjs/common'
346
+
347
+ const common = new Common({ chain: Mainnet })
348
+
349
+ const block = createBlock(
350
+ {
351
+ // Provide your block data here or use default values
352
+ },
353
+ { common },
354
+ )
355
+
356
+ console.log(`Proof-of-Stake (default) block created with hardfork=${block.common.hardfork()}`)
357
+ ```
358
+
359
+ ### Ethash/PoW
360
+
361
+ Blocks before the Merge or blocks on dedicated PoW chains are created as Proof-of-work blocks. An Ethash/PoW block can be instantiated as follows:
362
+
363
+ ```ts
364
+ // ./examples/pow.ts
365
+
366
+ import { createBlock } from '@ethereumjs/block'
367
+ import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
368
+
369
+ const common = new Common({ chain: Mainnet, hardfork: Hardfork.Chainstart })
370
+
371
+ console.log(common.consensusType()) // 'pow'
372
+ console.log(common.consensusAlgorithm()) // 'ethash'
373
+
374
+ createBlock({}, { common })
375
+ console.log(`Old Proof-of-Work block created`)
376
+ ```
377
+
378
+ To calculate the difficulty when creating the block pass in the block option `calcDifficultyFromHeader` with the preceding (parent) `BlockHeader`.
379
+
380
+ ### Clique/PoA
381
+
382
+ Clique is a standalone Proof-of-Authority protocol which had been in use for older Ethereum testnets (like e.g. the `Goerli` testnet). This library still supports Clique/PoA so that blocks from those testnets can still be read.
383
+
384
+ A clique block can be instantiated as follows:
385
+
386
+ ```ts
387
+ // ./examples/clique.ts
388
+
389
+ import { createBlock } from '@ethereumjs/block'
390
+ import { Common, Hardfork } from '@ethereumjs/common'
391
+ import { goerliChainConfig } from '@ethereumjs/testdata'
392
+
393
+ const common = new Common({ chain: goerliChainConfig, hardfork: Hardfork.Chainstart })
394
+
395
+ console.log(common.consensusType()) // 'poa'
396
+ console.log(common.consensusAlgorithm()) // 'clique'
397
+
398
+ createBlock({ header: { extraData: new Uint8Array(97) } }, { common })
399
+ console.log(`Old Clique Proof-of-Authority block created`)
400
+
401
+ ```
402
+
403
+ For sealing a block on instantiation you can use the `cliqueSigner` constructor option:
404
+
405
+ ```ts
406
+ const cliqueSigner = hexToBytes('PRIVATE_KEY_HEX_STRING')
407
+ const block = createSealedCliqueBlock(blockData, cliqueSigner)
408
+ ```
409
+
410
+ See the API docs for detailed documentation on Clique/PoA related utility methods. Note that these methods will throw if called in a non-Clique/PoA context.
411
+
412
+ ## Browser
413
+
414
+ We provide hybrid ESM/CJS builds for all our libraries. With the v10 breaking release round from Spring 2025, all libraries are "pure-JS" by default and we have eliminated all hard-wired WASM code. Additionally we have substantially lowered the bundle sizes, reduced the number of dependencies, and cut out all usages of Node.js-specific primitives (like the Node.js event emitter).
415
+
416
+ It is easily possible to run a browser build of one of the EthereumJS libraries within a modern browser using the provided ESM build. For a setup example see [./examples/browser.html](./examples/browser.html).
417
+
418
+ ## API
419
+
420
+ ### Docs
421
+
422
+ Generated TypeDoc API [Documentation](./docs/README.md)
423
+
424
+ ### Hybrid CJS/ESM Builds
425
+
426
+ With the breaking releases from Summer 2023 we have started to ship our libraries with both CommonJS (`cjs` folder) and ESM builds (`esm` folder), see `package.json` for the detailed setup.
427
+
428
+ If you use an ES6-style `import` in your code, the ESM build will be used:
429
+
430
+ ```ts
431
+ import { EthereumJSClass } from '@ethereumjs/[PACKAGE_NAME]'
432
+ ```
433
+
434
+ If you use Node.js specific `require`, the CJS build will be used:
435
+
436
+ ```ts
437
+ const { EthereumJSClass } = require('@ethereumjs/[PACKAGE_NAME]')
438
+ ```
439
+
440
+ Using ESM will give you additional advantages over CJS beyond browser usage like static code analysis / Tree Shaking which CJS cannot provide.
441
+
442
+
443
+ ## Testing
444
+
445
+ Tests in the `tests` directory are partly outdated and testing is primarily done by running the `BlockchainTests` from within the [@ethereumjs/vm](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/vm) package.
446
+
447
+ To avoid bloating this repository with [ethereum/tests](https://github.com/ethereum/tests) JSON files, we usually copy specific JSON files and wrap them with some metadata (source, date, commit hash). There's a helper to aid in that process and can be found at [wrap-ethereum-test.sh](https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/block/scripts/wrap-ethereum-test.sh).
448
+
449
+ ## EthereumJS
450
+
451
+ 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](../../DEVELOPER.md) for an overview of current standards and tools and review our [code of conduct](../../CODE_OF_CONDUCT.md).
452
+
453
+ ## License
454
+
455
+ [MPL-2.0](<https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)>)
456
+
457
+ [discord-badge]: https://img.shields.io/static/v1?logo=discord&label=discord&message=Join&color=blue
458
+ [discord-link]: https://discord.gg/TNwARpR
459
+ [block-npm-badge]: https://img.shields.io/npm/v/@ethereumjs/block.svg
460
+ [block-npm-link]: https://www.npmjs.com/package/@ethereumjs/block
461
+ [block-issues-badge]: https://img.shields.io/github/issues/ethereumjs/ethereumjs-monorepo/package:%20block?label=issues
462
+ [block-issues-link]: https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aopen+is%3Aissue+label%3A"package%3A+block"
463
+ [block-actions-badge]: https://github.com/ethereumjs/ethereumjs-monorepo/workflows/Block/badge.svg
464
+ [block-actions-link]: https://github.com/ethereumjs/ethereumjs-monorepo/actions?query=workflow%3A%22Block%22
465
+ [block-coverage-badge]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/branch/master/graph/badge.svg?flag=block
466
+ [block-coverage-link]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/tree/master/packages/block
@@ -0,0 +1,147 @@
1
+ import type { Common } from '@feelyourprotocol/common';
2
+ import type { TypedTransaction } from '@feelyourprotocol/tx';
3
+ import type { Withdrawal } from '@feelyourprotocol/util';
4
+ import { BlockHeader } from '../index.ts';
5
+ import type { BlockBytes, BlockOptions, ExecutionPayload, JSONBlock } from '../types.ts';
6
+ /**
7
+ * Class representing a block in the Ethereum network. The {@link BlockHeader} has its own
8
+ * class and can be used independently, for a block it is included in the form of the
9
+ * {@link Block.header} property.
10
+ *
11
+ * A block object can be created with one of the following constructor methods
12
+ * (separate from the Block class to allow for tree shaking):
13
+ *
14
+ * - {@link createBlock }
15
+ * - {@link createBlockFromBytesArray }
16
+ * - {@link createBlockFromRLP }
17
+ * - {@link createBlockFromRPC }
18
+ * - {@link createBlockFromJSONRPCProvider }
19
+ * - {@link createBlockFromExecutionPayload }
20
+ * - {@link createBlockFromBeaconPayloadJSON }
21
+ */
22
+ export declare class Block {
23
+ readonly header: BlockHeader;
24
+ readonly transactions: TypedTransaction[];
25
+ readonly uncleHeaders: BlockHeader[];
26
+ readonly withdrawals?: Withdrawal[];
27
+ readonly common: Common;
28
+ protected keccakFunction: (msg: Uint8Array) => Uint8Array;
29
+ protected sha256Function: (msg: Uint8Array) => Uint8Array;
30
+ protected cache: {
31
+ txTrieRoot?: Uint8Array;
32
+ withdrawalsTrieRoot?: Uint8Array;
33
+ };
34
+ /**
35
+ * This constructor takes the values, validates them, assigns them and freezes the object.
36
+ *
37
+ * @deprecated Use the static factory methods (see {@link Block} for an overview) to assist in creating
38
+ * a Block object from varying data types and options.
39
+ */
40
+ constructor(header?: BlockHeader, transactions?: TypedTransaction[], uncleHeaders?: BlockHeader[], withdrawals?: Withdrawal[], opts?: BlockOptions);
41
+ /**
42
+ * Returns an array of the raw byte arrays for this block, in order.
43
+ */
44
+ raw(): BlockBytes;
45
+ /**
46
+ * Returns the hash of the block.
47
+ */
48
+ hash(): Uint8Array;
49
+ /**
50
+ * Determines if this block is the genesis block.
51
+ */
52
+ isGenesis(): boolean;
53
+ /**
54
+ * Returns the rlp encoding of the block.
55
+ */
56
+ serialize(): Uint8Array;
57
+ /**
58
+ * Generates transaction trie for validation.
59
+ */
60
+ genTxTrie(): Promise<Uint8Array>;
61
+ /**
62
+ * Validates the transaction trie by generating a trie
63
+ * and do a check on the root hash.
64
+ * @returns True if the transaction trie is valid, false otherwise
65
+ */
66
+ transactionsTrieIsValid(): Promise<boolean>;
67
+ /**
68
+ * Validates transaction signatures and minimum gas requirements.
69
+ * @returns {string[]} an array of error strings
70
+ */
71
+ getTransactionsValidationErrors(): string[];
72
+ /**
73
+ * Validates transaction signatures and minimum gas requirements.
74
+ * @returns True if all transactions are valid, false otherwise
75
+ */
76
+ transactionsAreValid(): boolean;
77
+ /**
78
+ * Validates the block data, throwing if invalid.
79
+ * This can be checked on the Block itself without needing access to any parent block
80
+ * It checks:
81
+ * - All transactions are valid
82
+ * - The transactions trie is valid
83
+ * - The uncle hash is valid
84
+ * - Block size limit (EIP-7934)
85
+ * @param onlyHeader if only passed the header, skip validating txTrie and unclesHash (default: false)
86
+ * @param verifyTxs if set to `false`, will not check for transaction validation errors (default: true)
87
+ * @param validateBlockSize if set to `true`, will check for block size limit (EIP-7934) (default: false)
88
+ */
89
+ validateData(onlyHeader?: boolean, verifyTxs?: boolean, validateBlockSize?: boolean): Promise<void>;
90
+ /**
91
+ * Validates that blob gas fee for each transaction is greater than or equal to the
92
+ * blobGasPrice for the block and that total blob gas in block is less than maximum
93
+ * blob gas per block
94
+ * @param parentHeader header of parent block
95
+ */
96
+ validateBlobTransactions(parentHeader: BlockHeader): void;
97
+ /**
98
+ * Validates the uncle's hash.
99
+ * @returns true if the uncle's hash is valid, false otherwise.
100
+ */
101
+ uncleHashIsValid(): boolean;
102
+ /**
103
+ * Validates the withdrawal root
104
+ * @returns true if the withdrawals trie root is valid, false otherwise
105
+ */
106
+ withdrawalsTrieIsValid(): Promise<boolean>;
107
+ /**
108
+ * Consistency checks for uncles included in the block, if any.
109
+ *
110
+ * Throws if invalid.
111
+ *
112
+ * The rules for uncles checked are the following:
113
+ * Header has at most 2 uncles.
114
+ * Header does not count an uncle twice.
115
+ */
116
+ validateUncles(): void;
117
+ /**
118
+ * Validates if the block gasLimit remains in the boundaries set by the protocol.
119
+ * Throws if invalid
120
+ *
121
+ * @param parentBlock - the parent of this `Block`
122
+ */
123
+ validateGasLimit(parentBlock: Block): void;
124
+ /**
125
+ * Returns the block in JSON format.
126
+ */
127
+ toJSON(): JSONBlock;
128
+ /**
129
+ * Maps the block properties to the execution payload structure from the beacon chain,
130
+ * see https://github.com/ethereum/consensus-specs/blob/dev/specs/bellatrix/beacon-chain.md#ExecutionPayload
131
+ *
132
+ * @returns dict with the execution payload parameters with camel case naming
133
+ */
134
+ toExecutionPayload(): ExecutionPayload;
135
+ /**
136
+ * Return a compact error string representation of the object
137
+ */
138
+ errorStr(): string;
139
+ /**
140
+ * Internal helper function to create an annotated error message
141
+ *
142
+ * @param msg Base error message
143
+ * @hidden
144
+ */
145
+ protected _errorMsg(msg: string): string;
146
+ }
147
+ //# sourceMappingURL=block.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block.d.ts","sourceRoot":"","sources":["../../../src/block/block.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAChD,OAAO,KAAK,EAA6B,gBAAgB,EAAE,MAAM,gBAAgB,CAAA;AACjF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAOlD,OAAO,EACL,WAAW,EAUZ,MAAM,aAAa,CAAA;AAEpB,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAExF;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,KAAK;IAChB,SAAgB,MAAM,EAAE,WAAW,CAAA;IACnC,SAAgB,YAAY,EAAE,gBAAgB,EAAE,CAAK;IACrD,SAAgB,YAAY,EAAE,WAAW,EAAE,CAAK;IAChD,SAAgB,WAAW,CAAC,EAAE,UAAU,EAAE,CAAA;IAC1C,SAAgB,MAAM,EAAE,MAAM,CAAA;IAC9B,SAAS,CAAC,cAAc,EAAE,CAAC,GAAG,EAAE,UAAU,KAAK,UAAU,CAAA;IACzD,SAAS,CAAC,cAAc,EAAE,CAAC,GAAG,EAAE,UAAU,KAAK,UAAU,CAAA;IAEzD,SAAS,CAAC,KAAK,EAAE;QACf,UAAU,CAAC,EAAE,UAAU,CAAA;QACvB,mBAAmB,CAAC,EAAE,UAAU,CAAA;KACjC,CAAK;IAEN;;;;;OAKG;gBAED,MAAM,CAAC,EAAE,WAAW,EACpB,YAAY,GAAE,gBAAgB,EAAO,EACrC,YAAY,GAAE,WAAW,EAAO,EAChC,WAAW,CAAC,EAAE,UAAU,EAAE,EAC1B,IAAI,GAAE,YAAiB;IAqCzB;;OAEG;IACH,GAAG,IAAI,UAAU;IAgBjB;;OAEG;IACH,IAAI,IAAI,UAAU;IAIlB;;OAEG;IACH,SAAS,IAAI,OAAO;IAIpB;;OAEG;IACH,SAAS,IAAI,UAAU;IAIvB;;OAEG;IACG,SAAS,IAAI,OAAO,CAAC,UAAU,CAAC;IAOtC;;;;OAIG;IACG,uBAAuB,IAAI,OAAO,CAAC,OAAO,CAAC;IAcjD;;;OAGG;IACH,+BAA+B,IAAI,MAAM,EAAE;IA8C3C;;;OAGG;IACH,oBAAoB,IAAI,OAAO;IAM/B;;;;;;;;;;;OAWG;IACG,YAAY,CAChB,UAAU,GAAE,OAAe,EAC3B,SAAS,GAAE,OAAc,EACzB,iBAAiB,GAAE,OAAe,GACjC,OAAO,CAAC,IAAI,CAAC;IAoDhB;;;;;OAKG;IACH,wBAAwB,CAAC,YAAY,EAAE,WAAW;IA4ClD;;;OAGG;IACH,gBAAgB,IAAI,OAAO;IAS3B;;;OAGG;IACG,sBAAsB,IAAI,OAAO,CAAC,OAAO,CAAC;IAqBhD;;;;;;;;OAQG;IACH,cAAc;IAmBd;;;;;OAKG;IACH,gBAAgB,CAAC,WAAW,EAAE,KAAK;IAInC;;OAEG;IACH,MAAM,IAAI,SAAS;IAcnB;;;;;OAKG;IACH,kBAAkB,IAAI,gBAAgB;IA+BtC;;OAEG;IACI,QAAQ;IAmBf;;;;;OAKG;IACH,SAAS,CAAC,SAAS,CAAC,GAAG,EAAE,MAAM;CAGhC"}