@feelyourprotocol/blockchain 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 (132) hide show
  1. package/README.md +269 -0
  2. package/dist/cjs/blockchain.d.ts +372 -0
  3. package/dist/cjs/blockchain.d.ts.map +1 -0
  4. package/dist/cjs/blockchain.js +1105 -0
  5. package/dist/cjs/blockchain.js.map +1 -0
  6. package/dist/cjs/consensus/casper.d.ts +16 -0
  7. package/dist/cjs/consensus/casper.d.ts.map +1 -0
  8. package/dist/cjs/consensus/casper.js +28 -0
  9. package/dist/cjs/consensus/casper.js.map +1 -0
  10. package/dist/cjs/consensus/clique.d.ts +164 -0
  11. package/dist/cjs/consensus/clique.d.ts.map +1 -0
  12. package/dist/cjs/consensus/clique.js +520 -0
  13. package/dist/cjs/consensus/clique.js.map +1 -0
  14. package/dist/cjs/consensus/ethash.d.ts +29 -0
  15. package/dist/cjs/consensus/ethash.d.ts.map +1 -0
  16. package/dist/cjs/consensus/ethash.js +48 -0
  17. package/dist/cjs/consensus/ethash.js.map +1 -0
  18. package/dist/cjs/consensus/index.d.ts +5 -0
  19. package/dist/cjs/consensus/index.d.ts.map +1 -0
  20. package/dist/cjs/consensus/index.js +10 -0
  21. package/dist/cjs/consensus/index.js.map +1 -0
  22. package/dist/cjs/constructors.d.ts +13 -0
  23. package/dist/cjs/constructors.d.ts.map +1 -0
  24. package/dist/cjs/constructors.js +80 -0
  25. package/dist/cjs/constructors.js.map +1 -0
  26. package/dist/cjs/db/cache.d.ts +17 -0
  27. package/dist/cjs/db/cache.d.ts.map +1 -0
  28. package/dist/cjs/db/cache.js +38 -0
  29. package/dist/cjs/db/cache.js.map +1 -0
  30. package/dist/cjs/db/constants.d.ts +23 -0
  31. package/dist/cjs/db/constants.d.ts.map +1 -0
  32. package/dist/cjs/db/constants.js +54 -0
  33. package/dist/cjs/db/constants.js.map +1 -0
  34. package/dist/cjs/db/helpers.d.ts +9 -0
  35. package/dist/cjs/db/helpers.d.ts.map +1 -0
  36. package/dist/cjs/db/helpers.js +68 -0
  37. package/dist/cjs/db/helpers.js.map +1 -0
  38. package/dist/cjs/db/manager.d.ts +78 -0
  39. package/dist/cjs/db/manager.d.ts.map +1 -0
  40. package/dist/cjs/db/manager.js +203 -0
  41. package/dist/cjs/db/manager.js.map +1 -0
  42. package/dist/cjs/db/operation.d.ts +45 -0
  43. package/dist/cjs/db/operation.d.ts.map +1 -0
  44. package/dist/cjs/db/operation.js +110 -0
  45. package/dist/cjs/db/operation.js.map +1 -0
  46. package/dist/cjs/helpers.d.ts +19 -0
  47. package/dist/cjs/helpers.d.ts.map +1 -0
  48. package/dist/cjs/helpers.js +34 -0
  49. package/dist/cjs/helpers.js.map +1 -0
  50. package/dist/cjs/index.d.ts +7 -0
  51. package/dist/cjs/index.d.ts.map +1 -0
  52. package/dist/cjs/index.js +33 -0
  53. package/dist/cjs/index.js.map +1 -0
  54. package/dist/cjs/package.json +3 -0
  55. package/dist/cjs/types.d.ts +219 -0
  56. package/dist/cjs/types.d.ts.map +1 -0
  57. package/dist/cjs/types.js +3 -0
  58. package/dist/cjs/types.js.map +1 -0
  59. package/dist/esm/blockchain.d.ts +372 -0
  60. package/dist/esm/blockchain.d.ts.map +1 -0
  61. package/dist/esm/blockchain.js +1101 -0
  62. package/dist/esm/blockchain.js.map +1 -0
  63. package/dist/esm/consensus/casper.d.ts +16 -0
  64. package/dist/esm/consensus/casper.d.ts.map +1 -0
  65. package/dist/esm/consensus/casper.js +24 -0
  66. package/dist/esm/consensus/casper.js.map +1 -0
  67. package/dist/esm/consensus/clique.d.ts +164 -0
  68. package/dist/esm/consensus/clique.d.ts.map +1 -0
  69. package/dist/esm/consensus/clique.js +516 -0
  70. package/dist/esm/consensus/clique.js.map +1 -0
  71. package/dist/esm/consensus/ethash.d.ts +29 -0
  72. package/dist/esm/consensus/ethash.d.ts.map +1 -0
  73. package/dist/esm/consensus/ethash.js +44 -0
  74. package/dist/esm/consensus/ethash.js.map +1 -0
  75. package/dist/esm/consensus/index.d.ts +5 -0
  76. package/dist/esm/consensus/index.d.ts.map +1 -0
  77. package/dist/esm/consensus/index.js +5 -0
  78. package/dist/esm/consensus/index.js.map +1 -0
  79. package/dist/esm/constructors.d.ts +13 -0
  80. package/dist/esm/constructors.d.ts.map +1 -0
  81. package/dist/esm/constructors.js +76 -0
  82. package/dist/esm/constructors.js.map +1 -0
  83. package/dist/esm/db/cache.d.ts +17 -0
  84. package/dist/esm/db/cache.d.ts.map +1 -0
  85. package/dist/esm/db/cache.js +34 -0
  86. package/dist/esm/db/cache.js.map +1 -0
  87. package/dist/esm/db/constants.d.ts +23 -0
  88. package/dist/esm/db/constants.d.ts.map +1 -0
  89. package/dist/esm/db/constants.js +46 -0
  90. package/dist/esm/db/constants.js.map +1 -0
  91. package/dist/esm/db/helpers.d.ts +9 -0
  92. package/dist/esm/db/helpers.d.ts.map +1 -0
  93. package/dist/esm/db/helpers.js +61 -0
  94. package/dist/esm/db/helpers.js.map +1 -0
  95. package/dist/esm/db/manager.d.ts +78 -0
  96. package/dist/esm/db/manager.d.ts.map +1 -0
  97. package/dist/esm/db/manager.js +199 -0
  98. package/dist/esm/db/manager.js.map +1 -0
  99. package/dist/esm/db/operation.d.ts +45 -0
  100. package/dist/esm/db/operation.d.ts.map +1 -0
  101. package/dist/esm/db/operation.js +106 -0
  102. package/dist/esm/db/operation.js.map +1 -0
  103. package/dist/esm/helpers.d.ts +19 -0
  104. package/dist/esm/helpers.d.ts.map +1 -0
  105. package/dist/esm/helpers.js +30 -0
  106. package/dist/esm/helpers.js.map +1 -0
  107. package/dist/esm/index.d.ts +7 -0
  108. package/dist/esm/index.d.ts.map +1 -0
  109. package/dist/esm/index.js +7 -0
  110. package/dist/esm/index.js.map +1 -0
  111. package/dist/esm/package.json +3 -0
  112. package/dist/esm/types.d.ts +219 -0
  113. package/dist/esm/types.d.ts.map +1 -0
  114. package/dist/esm/types.js +2 -0
  115. package/dist/esm/types.js.map +1 -0
  116. package/dist/tsconfig.prod.cjs.tsbuildinfo +1 -0
  117. package/dist/tsconfig.prod.esm.tsbuildinfo +1 -0
  118. package/package.json +75 -0
  119. package/src/blockchain.ts +1353 -0
  120. package/src/consensus/casper.ts +33 -0
  121. package/src/consensus/clique.ts +633 -0
  122. package/src/consensus/ethash.ts +69 -0
  123. package/src/consensus/index.ts +5 -0
  124. package/src/constructors.ts +119 -0
  125. package/src/db/cache.ts +39 -0
  126. package/src/db/constants.ts +73 -0
  127. package/src/db/helpers.ts +81 -0
  128. package/src/db/manager.ts +243 -0
  129. package/src/db/operation.ts +152 -0
  130. package/src/helpers.ts +37 -0
  131. package/src/index.ts +12 -0
  132. package/src/types.ts +256 -0
package/README.md ADDED
@@ -0,0 +1,269 @@
1
+ # @ethereumjs/blockchain `v10`
2
+
3
+ [![NPM Package][blockchain-npm-badge]][blockchain-npm-link]
4
+ [![GitHub Issues][blockchain-issues-badge]][blockchain-issues-link]
5
+ [![Actions Status][blockchain-actions-badge]][blockchain-actions-link]
6
+ [![Code Coverage][blockchain-coverage-badge]][blockchain-coverage-link]
7
+ [![Discord][discord-badge]][discord-link]
8
+
9
+ | A module to store and interact with blocks. |
10
+ | ------------------------------------------- |
11
+
12
+ ## Table of Contents
13
+
14
+ - [Installation](#installation)
15
+ - [Getting Started](#getting-started)
16
+ - [EIP Integrations](#eip-integrations)
17
+ - [Consensus Types](#consensus-types)
18
+ - [Browser](#browser)
19
+ - [API](#api)
20
+ - [Testing](#testing)
21
+ - [EthereumJS](#ethereumjs)
22
+ - [License](#license)
23
+
24
+ ## Installation
25
+
26
+ To obtain the latest version, simply install the project using `npm`:
27
+
28
+ ```shell
29
+ npm install @ethereumjs/blockchain
30
+ ```
31
+
32
+ **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.
33
+
34
+ ## Getting Started
35
+
36
+ ### Introduction
37
+
38
+ The `Blockchain` package represents an Ethereum-compatible blockchain storing a sequential chain of [@ethereumjs/block](../block) blocks and holding information about the current canonical head block as well as the context the chain is operating in (e.g. the hardfork rules the current head block adheres to).
39
+
40
+ New blocks can be added to the blockchain. Validation ensures that the block format adheres to the given chain rules (with the `Blockchain.validateBlock()` function) and consensus rules (`Blockchain.consensus.validateConsensus()`).
41
+
42
+ The library also supports reorg scenarios e.g. by allowing to add a new block with `Blockchain.putBlock()` which follows a different canonical path to the head than given by the current canonical head block.
43
+
44
+ ## Examples
45
+
46
+ The following is an example to instantiate a simple Blockchain object, put blocks into the blockchain and then iterate through the blocks added:
47
+
48
+ ```ts
49
+ // ./examples/simple.ts
50
+
51
+ import { createBlock } from '@ethereumjs/block'
52
+ import { createBlockchain } from '@ethereumjs/blockchain'
53
+ import { Common, Hardfork, Mainnet } from '@ethereumjs/common'
54
+ import { bytesToHex } from '@ethereumjs/util'
55
+
56
+ const main = async () => {
57
+ const common = new Common({ chain: Mainnet, hardfork: Hardfork.London })
58
+ // Use the safe static constructor which awaits the init method
59
+ const blockchain = await createBlockchain({
60
+ validateBlocks: false, // Skipping validation so we can make a simple chain without having to provide complete blocks
61
+ validateConsensus: false,
62
+ common,
63
+ })
64
+
65
+ // We use minimal data to provide a sequence of blocks (increasing number, difficulty, and then setting parent hash to previous block)
66
+ const block = createBlock(
67
+ {
68
+ header: {
69
+ number: 1n,
70
+ parentHash: blockchain.genesisBlock.hash(),
71
+ difficulty: blockchain.genesisBlock.header.difficulty + 1n,
72
+ },
73
+ },
74
+ { common, setHardfork: true },
75
+ )
76
+ const block2 = createBlock(
77
+ {
78
+ header: {
79
+ number: 2n,
80
+ parentHash: block.header.hash(),
81
+ difficulty: block.header.difficulty + 1n,
82
+ },
83
+ },
84
+ { common, setHardfork: true },
85
+ )
86
+ // See @ethereumjs/block for more details on how to create a block
87
+ await blockchain.putBlock(block)
88
+ await blockchain.putBlock(block2)
89
+
90
+ // We iterate over the blocks in the chain to the current head (block 2)
91
+ await blockchain.iterator('i', (block) => {
92
+ const blockNumber = block.header.number.toString()
93
+ const blockHash = bytesToHex(block.hash())
94
+ console.log(`Block ${blockNumber}: ${blockHash}`)
95
+ })
96
+
97
+ // Block 1: 0xa1a061528d74ba81f560e1ebc4f29d6b58171fc13b72b876cdffe6e43b01bdc5
98
+ // Block 2: 0x5583be91cf9fb14f5dbeb03ad56e8cef19d1728f267c35a25ba5a355a528f602
99
+ }
100
+ void main()
101
+ ```
102
+
103
+ More examples can be found in the [examples](./examples/) folder.
104
+
105
+ ## Setup
106
+
107
+ ### Block Storage
108
+
109
+ For storing blocks different backends can be used. The database needs to conform to the [DB](https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/util/src/db.ts) interface provided in the `@ethereumjs/util` package (since this is used in other places as well).
110
+
111
+ By default the blockchain package uses a [MapDB](https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/util/src/mapDB.ts) non-persistent data storage which is also generically provided in the `@ethereumjs/util` package.
112
+
113
+ If you need a persistent data store for your use case you can consider using the wrapper we have written within our [client](https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/client/src/execution/level.ts) library.
114
+
115
+ ### Consensus
116
+
117
+ Starting with v6 there is a dedicated consensus class for each type of supported consensus, `Ethash`, `Clique` and `Casper` (PoS, this one is rather the do-nothing part of `Casper` and letting the respective consensus/beacon client do the hard work! 🙂). Each consensus class adheres to a common interface `Consensus` implementing the following five methods in a consensus-specific way:
118
+
119
+ - `genesisInit(genesisBlock: Block): Promise<void>`
120
+ - `setup(): Promise<void>`
121
+ - `validateConsensus(block: Block): Promise<void>`
122
+ - `validateDifficulty(header: BlockHeader): Promise<void>`
123
+ - `newBlock(block: Block, commonAncestor?: BlockHeader, ancientHeaders?: BlockHeader[]): Promise<void>`
124
+
125
+ #### Custom Consensus Algorithms
126
+
127
+ Also part of V6, you can also create a custom consensus class implementing the above interface and pass it into the `Blockchain` constructor using the `consensus` option at instantiation. See [this test script](https://github.com/ethereumjs/ethereumjs-monorepo/blob/master/packages/blockchain/test/customConsensus.spec.ts) for a complete example of how write and use a custom consensus implementation.
128
+
129
+ Note, if you construct a blockchain with a custom consensus implementation, transition checks for switching from PoW to PoS are disabled so defining a merge hardfork will have no impact on the consensus mechanism defined for the chain.
130
+
131
+ ## Custom Genesis State
132
+
133
+ ### Genesis State
134
+
135
+ Genesis state for the 4 supported networks (mainnet, sepolia, hoodi, holesky) is stored in an auxiliary package [@ethereumjs/genesis](https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/genesis), from which it can be included if needed (for most - especially VM - use cases it is not necessary), see PR [#2844](https://github.com/ethereumjs/ethereumjs-monorepo/pull/2844).
136
+
137
+
138
+ ### Custom genesis from a Geth genesis config
139
+
140
+ For many custom chains we might come across a genesis configuration, which can be used to build both chain config as well the genesis state (and hence the genesis block as well to start off with)
141
+
142
+ ```ts
143
+ // ./examples/gethGenesis.ts
144
+
145
+ import { createBlockchain } from '@ethereumjs/blockchain'
146
+ import { createCommonFromGethGenesis, parseGethGenesisState } from '@ethereumjs/common'
147
+ import { postMergeGethGenesis } from '@ethereumjs/testdata'
148
+ import { bytesToHex } from '@ethereumjs/util'
149
+
150
+ const main = async () => {
151
+ // Load geth genesis file
152
+ const common = createCommonFromGethGenesis(postMergeGethGenesis, { chain: 'customChain' })
153
+ const genesisState = parseGethGenesisState(postMergeGethGenesis)
154
+ const blockchain = await createBlockchain({
155
+ genesisState,
156
+ common,
157
+ })
158
+ const genesisBlockHash = blockchain.genesisBlock.hash()
159
+ common.setForkHashes(genesisBlockHash)
160
+ console.log(
161
+ `Genesis hash from geth genesis parameters - ${bytesToHex(blockchain.genesisBlock.hash())}`,
162
+ )
163
+ }
164
+
165
+ void main()
166
+
167
+ ```
168
+
169
+ The genesis block from the initialized `Blockchain` can be retrieved via the `Blockchain.genesisBlock` getter. For creating a genesis block from the params in `@ethereumjs/common`, the `createGenesisBlock(stateRoot: Buffer): Block` method can be used.
170
+
171
+ ## Supported Blocks and Tx Types
172
+
173
+ ### EIP-1559 Support
174
+
175
+ This library supports the handling of `EIP-1559` blocks and transactions starting with the `v5.3.0` release.
176
+
177
+ ### EIP-4844 Shard Blob Transactions Support
178
+
179
+ This library supports the blob transaction type introduced with [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844).
180
+
181
+ The blockchain library now allows for blob transactions to be validated and included in a chain where EIP-4844 activated either by hardfork or standalone EIP.
182
+
183
+ **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.
184
+
185
+ ### EIP-7685 Requests Support
186
+
187
+ This library supports blocks including the [EIP-7685](https://eips.ethereum.org/EIPS/eip-7685) requests to the consensus layer (like e.g. deposit or withdrawal requests).
188
+
189
+ ## Browser
190
+
191
+ 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).
192
+
193
+ 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).
194
+
195
+ ## API
196
+
197
+ ### Docs
198
+
199
+ Generated TypeDoc API [Documentation](./docs/README.md)
200
+
201
+ ### Hybrid CJS/ESM Builds
202
+
203
+ 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.
204
+
205
+ If you use an ES6-style `import` in your code files from the ESM build will be used:
206
+
207
+ ```ts
208
+ import { EthereumJSClass } from '@ethereumjs/[PACKAGE_NAME]'
209
+ ```
210
+
211
+ If you use Node.js specific `require`, the CJS build will be used:
212
+
213
+ ```ts
214
+ const { EthereumJSClass } = require('@ethereumjs/[PACKAGE_NAME]')
215
+ ```
216
+
217
+ Using ESM will give you additional advantages over CJS beyond browser usage like static code analysis / Tree Shaking which CJS can not provide.
218
+
219
+ ## Events
220
+
221
+ The `Blockchain` class has a public property `events` which contains an `EventEmitter` (using [EventEmitter3](https://github.com/primus/eventemitter3)). Following events are emitted on which you can react within your code:
222
+
223
+ | Event | Description |
224
+ | ------------------------ | ------------------------------------------- |
225
+ | `deletedCanonicalBlocks` | Emitted when blocks are reorged and deleted |
226
+
227
+ ## Debugging
228
+
229
+ This library uses the [debug](https://github.com/visionmedia/debug) debugging utility package.
230
+
231
+ The following initial logger is currently available:
232
+
233
+ | Logger | Description |
234
+ | ------------------- | ------------------------------------------------------------------------ |
235
+ | `blockchain:#` | Core blockchain operations like when a block or header is put or deleted |
236
+ | `blockchain:clique` | Clique consensus operations like updating the vote and/or signer list |
237
+ | `blockchain:ethash` | Ethash consensus operations like PoW block or header validation |
238
+
239
+ The following is an example for a logger run:
240
+
241
+ Run with the clique logger:
242
+
243
+ ```shell
244
+ DEBUG=ethjs,blockchain:clique tsx test.ts
245
+ ```
246
+
247
+ `ethjs` **must** be included in the `DEBUG` environment variables to enable **any** logs.
248
+ Additional log selections can be added with a comma separated list (no spaces). Logs with extensions can be enabled with a colon `:`, and `*` can be used to include all extensions (currently do not apply for blockchain debugging, example taken from another library).
249
+
250
+ `DEBUG=ethjs,statemanager:cache:*,trie,statemanager:merkle npx vitest test/statemanager.spec.ts`
251
+
252
+ ## EthereumJS
253
+
254
+ 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).
255
+
256
+ ## License
257
+
258
+ [MPL-2.0](<https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)>)
259
+
260
+ [discord-badge]: https://img.shields.io/static/v1?logo=discord&label=discord&message=Join&color=blue
261
+ [discord-link]: https://discord.gg/TNwARpR
262
+ [blockchain-npm-badge]: https://img.shields.io/npm/v/@ethereumjs/blockchain.svg
263
+ [blockchain-npm-link]: https://www.npmjs.com/package/@ethereumjs/blockchain
264
+ [blockchain-issues-badge]: https://img.shields.io/github/issues/ethereumjs/ethereumjs-monorepo/package:%20blockchain?label=issues
265
+ [blockchain-issues-link]: https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aopen+is%3Aissue+label%3A"package%3A+blockchain"
266
+ [blockchain-actions-badge]: https://github.com/ethereumjs/ethereumjs-monorepo/workflows/Blockchain/badge.svg
267
+ [blockchain-actions-link]: https://github.com/ethereumjs/ethereumjs-monorepo/actions?query=workflow%3A%22Blockchain%22
268
+ [blockchain-coverage-badge]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/branch/master/graph/badge.svg?flag=blockchain
269
+ [blockchain-coverage-link]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/tree/master/packages/blockchain
@@ -0,0 +1,372 @@
1
+ import { Block, BlockHeader } from '@feelyourprotocol/block';
2
+ import { Common } from '@feelyourprotocol/common';
3
+ import { EventEmitter } from 'eventemitter3';
4
+ import { DBManager } from './db/manager.ts';
5
+ import type { BigIntLike, DB, DBObject } from '@feelyourprotocol/util';
6
+ import type { BlockchainEvent, BlockchainInterface, BlockchainOptions, Consensus, OnBlock } from './types.ts';
7
+ /**
8
+ * Blockchain implementation to create and maintain a valid canonical chain
9
+ * of block headers or blocks with support for reorgs and the ability to provide
10
+ * custom DB backends.
11
+ *
12
+ * By default consensus validation is not provided since with the switch to
13
+ * Proof-of-Stake consensus is validated by the Ethereum consensus layer.
14
+ * If consensus validation is desired for Ethash or Clique blockchains the
15
+ * optional `consensusDict` option can be used to pass in validation objects.
16
+ *
17
+ * A Blockchain object can be created with the constructor method:
18
+ *
19
+ * - {@link createBlockchain}
20
+ */
21
+ export declare class Blockchain implements BlockchainInterface {
22
+ db: DB<Uint8Array | string, Uint8Array | string | DBObject>;
23
+ dbManager: DBManager;
24
+ events: EventEmitter<BlockchainEvent>;
25
+ private _genesisBlock?; /** The genesis block of this blockchain */
26
+ private _customGenesisState?; /** Custom genesis state */
27
+ /**
28
+ * The following two heads and the heads stored within the `_heads` always point
29
+ * to a hash in the canonical chain and never to a stale hash.
30
+ * With the exception of `_headHeaderHash` this does not necessarily need to be
31
+ * the hash with the highest total difficulty.
32
+ */
33
+ /** The hash of the current head block */
34
+ private _headBlockHash?;
35
+ /** The hash of the current head header */
36
+ private _headHeaderHash?;
37
+ /**
38
+ * A Map which stores the head of each key (for instance the "vm" key) which is
39
+ * updated along a {@link Blockchain.iterator} method run and can be used to (re)run
40
+ * non-verified blocks (for instance in the VM).
41
+ */
42
+ private _heads;
43
+ private _lock;
44
+ readonly common: Common;
45
+ private _hardforkByHeadBlockNumber;
46
+ private readonly _validateBlocks;
47
+ private readonly _validateConsensus;
48
+ private _consensusDict;
49
+ /**
50
+ * This is used to track which canonical blocks are deleted. After a method calls
51
+ * `_deleteCanonicalChainReferences`, if this array has any items, the
52
+ * `deletedCanonicalBlocks` event is emitted with the array as argument.
53
+ */
54
+ private _deletedBlocks;
55
+ private DEBUG;
56
+ private _debug;
57
+ /**
58
+ * Creates new Blockchain object.
59
+ *
60
+ * @deprecated The direct usage of this constructor is discouraged since
61
+ * non-finalized async initialization might lead to side effects. Please
62
+ * use the async {@link createBlockchain} constructor instead (same API).
63
+ *
64
+ * @param opts An object with the options that this constructor takes. See
65
+ * {@link BlockchainOptions}.
66
+ */
67
+ constructor(opts?: BlockchainOptions);
68
+ private _consensusCheck;
69
+ /**
70
+ * Returns an eventual consensus object matching the current consensus algorithm from Common
71
+ * or undefined if non available
72
+ */
73
+ get consensus(): Consensus | undefined;
74
+ /**
75
+ * Returns a deep copy of this {@link Blockchain} instance.
76
+ *
77
+ * Note: this does not make a copy of the underlying db
78
+ * since it is unknown if the source is on disk or in memory.
79
+ * This should not be a significant issue in most usage since
80
+ * the queries will only reflect the instance's known data.
81
+ * If you would like this copied blockchain to use another db
82
+ * set the {@link db} of this returned instance to a copy of
83
+ * the original.
84
+ */
85
+ shallowCopy(): Blockchain;
86
+ /**
87
+ * Run a function after acquiring a lock. It is implied that we have already
88
+ * initialized the module (or we are calling this from the init function, like
89
+ * `_setCanonicalGenesisBlock`)
90
+ * @param action - function to run after acquiring a lock
91
+ * @hidden
92
+ */
93
+ private runWithLock;
94
+ /**
95
+ * Returns the specified iterator head.
96
+ *
97
+ * This function replaces the old Blockchain.getHead() method. Note that
98
+ * the function deviates from the old behavior and returns the
99
+ * genesis hash instead of the current head block if an iterator
100
+ * has not been run. This matches the behavior of {@link Blockchain.iterator}.
101
+ *
102
+ * @param name - Optional name of the iterator head (default: 'vm')
103
+ */
104
+ getIteratorHead(name?: string): Promise<Block>;
105
+ /**
106
+ * This method differs from `getIteratorHead`. If the head is not found, it returns `undefined`.
107
+ * @param name - Optional name of the iterator head (default: 'vm')
108
+ * @returns
109
+ */
110
+ getIteratorHeadSafe(name?: string): Promise<Block | undefined>;
111
+ private getHead;
112
+ /**
113
+ * Returns the latest header in the canonical chain.
114
+ */
115
+ getCanonicalHeadHeader(): Promise<BlockHeader>;
116
+ /**
117
+ * Returns the latest full block in the canonical chain.
118
+ */
119
+ getCanonicalHeadBlock(): Promise<Block>;
120
+ /**
121
+ * Adds blocks to the blockchain.
122
+ *
123
+ * If an invalid block is met the function will throw, blocks before will
124
+ * nevertheless remain in the DB. If any of the saved blocks has a higher
125
+ * total difficulty than the current max total difficulty the canonical
126
+ * chain is rebuilt and any stale heads/hashes are overwritten.
127
+ * @param blocks - The blocks to be added to the blockchain
128
+ */
129
+ putBlocks(blocks: Block[]): Promise<void>;
130
+ /**
131
+ * Adds a block to the blockchain.
132
+ *
133
+ * If the block is valid and has a higher total difficulty than the current
134
+ * max total difficulty, the canonical chain is rebuilt and any stale
135
+ * heads/hashes are overwritten.
136
+ * @param block - The block to be added to the blockchain
137
+ */
138
+ putBlock(block: Block): Promise<void>;
139
+ /**
140
+ * Adds many headers to the blockchain.
141
+ *
142
+ * If an invalid header is met the function will throw, headers before will
143
+ * nevertheless remain in the DB. If any of the saved headers has a higher
144
+ * total difficulty than the current max total difficulty the canonical
145
+ * chain is rebuilt and any stale heads/hashes are overwritten.
146
+ * @param headers - The headers to be added to the blockchain
147
+ */
148
+ putHeaders(headers: Array<any>): Promise<void>;
149
+ /**
150
+ * Adds a header to the blockchain.
151
+ *
152
+ * If this header is valid and it has a higher total difficulty than the current
153
+ * max total difficulty, the canonical chain is rebuilt and any stale
154
+ * heads/hashes are overwritten.
155
+ * @param header - The header to be added to the blockchain
156
+ */
157
+ putHeader(header: BlockHeader): Promise<void>;
158
+ /**
159
+ * Resets the canonical chain to canonicalHead number
160
+ *
161
+ * This updates the head hashes (if affected) to the hash corresponding to
162
+ * canonicalHead and cleans up canonical references greater than canonicalHead
163
+ * @param canonicalHead - The number to which chain should be reset to
164
+ */
165
+ resetCanonicalHead(canonicalHead: bigint): Promise<void>;
166
+ /**
167
+ * Entrypoint for putting any block or block header. Verifies this block,
168
+ * checks the total TD: if this TD is higher than the current highest TD, we
169
+ * have thus found a new canonical block and have to rewrite the canonical
170
+ * chain. This also updates the head block hashes. If any of the older known
171
+ * canonical chains just became stale, then we also reset every _heads header
172
+ * which points to a stale header to the last verified header which was in the
173
+ * old canonical chain, but also in the new canonical chain. This thus rolls
174
+ * back these headers so that these can be updated to the "new" canonical
175
+ * header using the iterator method.
176
+ * @hidden
177
+ */
178
+ private _putBlockOrHeader;
179
+ /**
180
+ * Validates a block header, throwing if invalid. It is being validated against the reported `parentHash`.
181
+ * It verifies the current block against the `parentHash`:
182
+ * - The `parentHash` is part of the blockchain (it is a valid header)
183
+ * - Current block number is parent block number + 1
184
+ * - Current block has a strictly higher timestamp
185
+ * - Additional PoW checks ->
186
+ * - Current block has valid difficulty and gas limit
187
+ * - In case that the header is an uncle header, it should not be too old or young in the chain.
188
+ * - Additional PoA clique checks ->
189
+ * - Checks on coinbase and mixHash
190
+ * - Current block has a timestamp diff greater or equal to PERIOD
191
+ * - Current block has difficulty correctly marked as INTURN or NOTURN
192
+ * @param header - header to be validated
193
+ * @param height - If this is an uncle header, this is the height of the block that is including it
194
+ */
195
+ validateHeader(header: BlockHeader, height?: bigint): Promise<void>;
196
+ /**
197
+ * Validates a block, by validating the header against the current chain, any uncle headers, and then
198
+ * whether the block is internally consistent
199
+ * @param block block to be validated
200
+ */
201
+ validateBlock(block: Block): Promise<void>;
202
+ /**
203
+ * The following rules are checked in this method:
204
+ * Uncle Header is a valid header.
205
+ * Uncle Header is an orphan, i.e. it is not one of the headers of the canonical chain.
206
+ * Uncle Header has a parentHash which points to the canonical chain. This parentHash is within the last 7 blocks.
207
+ * Uncle Header is not already included as uncle in another block.
208
+ * @param block - block for which uncles are being validated
209
+ */
210
+ private _validateUncleHeaders;
211
+ /**
212
+ * Gets a block by its hash or number. If a number is provided, the returned
213
+ * block will be the canonical block at that number in the chain
214
+ *
215
+ * @param blockId - The block's hash or number. If a hash is provided, then
216
+ * this will be immediately looked up, otherwise it will wait until we have
217
+ * unlocked the DB
218
+ */
219
+ getBlock(blockId: Uint8Array | number | bigint): Promise<Block>;
220
+ /**
221
+ * Gets total difficulty for a block specified by hash and number
222
+ */
223
+ getTotalDifficulty(hash: Uint8Array, number?: bigint): Promise<bigint>;
224
+ /**
225
+ * Gets total difficulty for a header's parent, helpful for determining terminal block
226
+ * @param header - Block header whose parent td is desired
227
+ */
228
+ getParentTD(header: BlockHeader): Promise<bigint>;
229
+ /**
230
+ * Looks up many blocks relative to blockId Note: due to `GetBlockHeaders
231
+ * (0x03)` (ETH wire protocol) we have to support skip/reverse as well.
232
+ * @param blockId - The block's hash or number
233
+ * @param maxBlocks - Max number of blocks to return
234
+ * @param skip - Number of blocks to skip apart
235
+ * @param reverse - Fetch blocks in reverse
236
+ */
237
+ getBlocks(blockId: Uint8Array | bigint | number, maxBlocks: number, skip: number, reverse: boolean): Promise<Block[]>;
238
+ /**
239
+ * Given an ordered array, returns an array of hashes that are not in the
240
+ * blockchain yet. Uses binary search to find out what hashes are missing.
241
+ * Therefore, the array needs to be ordered upon number.
242
+ * @param hashes - Ordered array of hashes (ordered on `number`).
243
+ */
244
+ selectNeededHashes(hashes: Array<Uint8Array>): Promise<Uint8Array[]>;
245
+ /**
246
+ * Completely deletes a block from the blockchain including any references to
247
+ * this block. If this block was in the canonical chain, then also each child
248
+ * block of this block is deleted Also, if this was a canonical block, each
249
+ * head header which is part of this now stale chain will be set to the
250
+ * parentHeader of this block An example reason to execute is when running the
251
+ * block in the VM invalidates this block: this will then reset the canonical
252
+ * head to the past block (which has been validated in the past by the VM, so
253
+ * we can be sure it is correct).
254
+ * @param blockHash - The hash of the block to be deleted
255
+ */
256
+ delBlock(blockHash: Uint8Array): Promise<void>;
257
+ /**
258
+ * @hidden
259
+ */
260
+ private _delBlock;
261
+ /**
262
+ * Updates the `DatabaseOperation` list to delete a block from the DB,
263
+ * identified by `blockHash` and `blockNumber`. Deletes fields from `Header`,
264
+ * `Body`, `HashToNumber` and `TotalDifficulty` tables. If child blocks of
265
+ * this current block are in the canonical chain, delete these as well. Does
266
+ * not actually commit these changes to the DB. Sets `_headHeaderHash` and
267
+ * `_headBlockHash` to `headHash` if any of these matches the current child to
268
+ * be deleted.
269
+ * @param blockHash - the block hash to delete
270
+ * @param blockNumber - the number corresponding to the block hash
271
+ * @param headHash - the current head of the chain (if null, do not update
272
+ * `_headHeaderHash` and `_headBlockHash`)
273
+ * @param ops - the `DatabaseOperation` list to add the delete operations to
274
+ * @hidden
275
+ */
276
+ private _delChild;
277
+ /**
278
+ * Iterates through blocks starting at the specified iterator head and calls
279
+ * the onBlock function on each block. The current location of an iterator
280
+ * head can be retrieved using {@link Blockchain.getIteratorHead}.
281
+ *
282
+ * @param name - Name of the state root head
283
+ * @param onBlock - Function called on each block with params (block, reorg)
284
+ * @param maxBlocks - How many blocks to run. By default, run all unprocessed blocks in the canonical chain.
285
+ * @param releaseLockOnCallback - Do not lock the blockchain for running the callback (default: `false`)
286
+ * @returns number of blocks actually iterated
287
+ */
288
+ iterator(name: string, onBlock: OnBlock, maxBlocks?: number, releaseLockOnCallback?: boolean): Promise<number>;
289
+ /**
290
+ * Set header hash of a certain `tag`.
291
+ * When calling the iterator, the iterator will start running the first child block after the header hash currently stored.
292
+ * @param tag - The tag to save the headHash to
293
+ * @param headHash - The head hash to save
294
+ */
295
+ setIteratorHead(tag: string, headHash: Uint8Array): Promise<void>;
296
+ /**
297
+ * Find the common ancestor of the new block and the old block.
298
+ * @param newHeader - the new block header
299
+ */
300
+ private findCommonAncestor;
301
+ /**
302
+ * Pushes DB operations to delete canonical number assignments for specified
303
+ * block number and above. This only deletes `NumberToHash` references and not
304
+ * the blocks themselves. Note: this does not write to the DB but only pushes
305
+ * to a DB operations list.
306
+ * @param blockNumber - the block number from which we start deleting
307
+ * canonical chain assignments (including this block)
308
+ * @param headHash - the hash of the current canonical chain head. The _heads
309
+ * reference matching any hash of any of the deleted blocks will be set to
310
+ * this
311
+ * @param ops - the DatabaseOperation list to write DatabaseOperations to
312
+ * @hidden
313
+ */
314
+ private _deleteCanonicalChainReferences;
315
+ /**
316
+ * Given a `header`, put all operations to change the canonical chain directly
317
+ * into `ops`. This walks the supplied `header` backwards. It is thus assumed
318
+ * that this header should be canonical header. For each header the
319
+ * corresponding hash corresponding to the current canonical chain in the DB
320
+ * is checked. If the number => hash reference does not correspond to the
321
+ * reference in the DB, we overwrite this reference with the implied number =>
322
+ * hash reference Also, each `_heads` member is checked; if these point to a
323
+ * stale hash, then the hash which we terminate the loop (i.e. the first hash
324
+ * which matches the number => hash of the implied chain) is put as this stale
325
+ * head hash. The same happens to _headBlockHash.
326
+ * @param header - The canonical header.
327
+ * @param ops - The database operations list.
328
+ * @hidden
329
+ */
330
+ private _rebuildCanonical;
331
+ /**
332
+ * Builds the `DatabaseOperation[]` list which describes the DB operations to
333
+ * write the heads, head header hash and the head header block to the DB
334
+ * @hidden
335
+ */
336
+ private _saveHeadOps;
337
+ /**
338
+ * Gets the `DatabaseOperation[]` list to save `_heads`, `_headHeaderHash` and
339
+ * `_headBlockHash` and writes these to the DB
340
+ * @hidden
341
+ */
342
+ private _saveHeads;
343
+ /**
344
+ * Gets a header by hash and number. Header can exist outside the canonical
345
+ * chain
346
+ *
347
+ * @hidden
348
+ */
349
+ private _getHeader;
350
+ checkAndTransitionHardForkByNumber(number: BigIntLike, timestamp?: BigIntLike): Promise<void>;
351
+ /**
352
+ * Gets a header by number. Header must be in the canonical chain
353
+ */
354
+ getCanonicalHeader(number: bigint): Promise<BlockHeader>;
355
+ /**
356
+ * This method either returns a Uint8Array if there exists one in the DB or if it
357
+ * does not exist then return false If DB throws
358
+ * any other error, this function throws.
359
+ * @param number
360
+ */
361
+ safeNumberToHash(number: bigint): Promise<Uint8Array | false>;
362
+ /**
363
+ * The genesis {@link Block} for the blockchain.
364
+ */
365
+ get genesisBlock(): Block;
366
+ /**
367
+ * Creates a genesis {@link Block} for the blockchain with params from {@link Common.genesis}
368
+ * @param stateRoot The genesis stateRoot
369
+ */
370
+ createGenesisBlock(stateRoot: Uint8Array): Block;
371
+ }
372
+ //# sourceMappingURL=blockchain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"blockchain.d.ts","sourceRoot":"","sources":["../../src/blockchain.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,WAAW,EAAe,MAAM,mBAAmB,CAAA;AACnE,OAAO,EAAE,MAAM,EAAwD,MAAM,oBAAoB,CAAA;AAkBjG,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAU5C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAK3C,OAAO,KAAK,EAAE,UAAU,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAEhE,OAAO,KAAK,EACV,eAAe,EACf,mBAAmB,EACnB,iBAAiB,EACjB,SAAS,EAET,OAAO,EACR,MAAM,YAAY,CAAA;AAEnB;;;;;;;;;;;;;GAaG;AACH,qBAAa,UAAW,YAAW,mBAAmB;IACpD,EAAE,EAAE,EAAE,CAAC,UAAU,GAAG,MAAM,EAAE,UAAU,GAAG,M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