@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
@@ -0,0 +1,1101 @@
1
+ import { Block, BlockHeader, createBlock } from '@feelyourprotocol/block';
2
+ import { Common, ConsensusAlgorithm, ConsensusType, Hardfork, Mainnet } from '@feelyourprotocol/common';
3
+ import { BIGINT_0, BIGINT_1, BIGINT_8, EthereumJSErrorWithoutCode, KECCAK256_RLP, Lock, MapDB, SHA256_NULL, bigIntToHex, bytesToHex, bytesToUnprefixedHex, concatBytes, equalsBytes, isDebugEnabled, } from '@feelyourprotocol/util';
4
+ import debugDefault from 'debug';
5
+ import { EventEmitter } from 'eventemitter3';
6
+ import { CasperConsensus } from "./consensus/casper.js";
7
+ import { DBOp, DBSaveLookups, DBSetBlockOrHeader, DBSetHashToNumber, DBSetTD, } from "./db/helpers.js";
8
+ import { DBManager } from "./db/manager.js";
9
+ import { DBTarget } from "./db/operation.js";
10
+ /**
11
+ * Blockchain implementation to create and maintain a valid canonical chain
12
+ * of block headers or blocks with support for reorgs and the ability to provide
13
+ * custom DB backends.
14
+ *
15
+ * By default consensus validation is not provided since with the switch to
16
+ * Proof-of-Stake consensus is validated by the Ethereum consensus layer.
17
+ * If consensus validation is desired for Ethash or Clique blockchains the
18
+ * optional `consensusDict` option can be used to pass in validation objects.
19
+ *
20
+ * A Blockchain object can be created with the constructor method:
21
+ *
22
+ * - {@link createBlockchain}
23
+ */
24
+ export class Blockchain {
25
+ /**
26
+ * Creates new Blockchain object.
27
+ *
28
+ * @deprecated The direct usage of this constructor is discouraged since
29
+ * non-finalized async initialization might lead to side effects. Please
30
+ * use the async {@link createBlockchain} constructor instead (same API).
31
+ *
32
+ * @param opts An object with the options that this constructor takes. See
33
+ * {@link BlockchainOptions}.
34
+ */
35
+ constructor(opts = {}) {
36
+ /**
37
+ * This is used to track which canonical blocks are deleted. After a method calls
38
+ * `_deleteCanonicalChainReferences`, if this array has any items, the
39
+ * `deletedCanonicalBlocks` event is emitted with the array as argument.
40
+ */
41
+ this._deletedBlocks = [];
42
+ this.DEBUG = isDebugEnabled('ethjs');
43
+ this._debug = debugDefault('blockchain:#');
44
+ if (opts.common) {
45
+ this.common = opts.common;
46
+ }
47
+ else {
48
+ const DEFAULT_CHAIN = Mainnet;
49
+ const DEFAULT_HARDFORK = Hardfork.Chainstart;
50
+ this.common = new Common({
51
+ chain: DEFAULT_CHAIN,
52
+ hardfork: DEFAULT_HARDFORK,
53
+ });
54
+ }
55
+ this._hardforkByHeadBlockNumber = opts.hardforkByHeadBlockNumber ?? false;
56
+ this._validateBlocks = opts.validateBlocks ?? true;
57
+ this._validateConsensus = opts.validateConsensus ?? false;
58
+ this._customGenesisState = opts.genesisState;
59
+ this.db = opts.db ?? new MapDB();
60
+ this.dbManager = new DBManager(this.db, this.common);
61
+ this.events = new EventEmitter();
62
+ this._consensusDict = {};
63
+ this._consensusDict[ConsensusAlgorithm.Casper] = new CasperConsensus();
64
+ if (opts.consensusDict !== undefined) {
65
+ this._consensusDict = { ...this._consensusDict, ...opts.consensusDict };
66
+ }
67
+ this._consensusCheck();
68
+ this._heads = {};
69
+ this._lock = new Lock();
70
+ if (opts.genesisBlock && !opts.genesisBlock.isGenesis()) {
71
+ throw 'supplied block is not a genesis block';
72
+ }
73
+ }
74
+ _consensusCheck() {
75
+ if (this._validateConsensus && this.consensus === undefined) {
76
+ throw EthereumJSErrorWithoutCode(`Consensus object for ${this.common.consensusAlgorithm()} must be passed (see consensusDict option) if consensus validation is activated`);
77
+ }
78
+ }
79
+ /**
80
+ * Returns an eventual consensus object matching the current consensus algorithm from Common
81
+ * or undefined if non available
82
+ */
83
+ get consensus() {
84
+ return this._consensusDict[this.common.consensusAlgorithm()];
85
+ }
86
+ /**
87
+ * Returns a deep copy of this {@link Blockchain} instance.
88
+ *
89
+ * Note: this does not make a copy of the underlying db
90
+ * since it is unknown if the source is on disk or in memory.
91
+ * This should not be a significant issue in most usage since
92
+ * the queries will only reflect the instance's known data.
93
+ * If you would like this copied blockchain to use another db
94
+ * set the {@link db} of this returned instance to a copy of
95
+ * the original.
96
+ */
97
+ shallowCopy() {
98
+ const copiedBlockchain = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
99
+ copiedBlockchain.common = this.common.copy();
100
+ return copiedBlockchain;
101
+ }
102
+ /**
103
+ * Run a function after acquiring a lock. It is implied that we have already
104
+ * initialized the module (or we are calling this from the init function, like
105
+ * `_setCanonicalGenesisBlock`)
106
+ * @param action - function to run after acquiring a lock
107
+ * @hidden
108
+ */
109
+ async runWithLock(action) {
110
+ try {
111
+ await this._lock.acquire();
112
+ const value = await action();
113
+ return value;
114
+ }
115
+ finally {
116
+ this._lock.release();
117
+ }
118
+ }
119
+ /**
120
+ * Returns the specified iterator head.
121
+ *
122
+ * This function replaces the old Blockchain.getHead() method. Note that
123
+ * the function deviates from the old behavior and returns the
124
+ * genesis hash instead of the current head block if an iterator
125
+ * has not been run. This matches the behavior of {@link Blockchain.iterator}.
126
+ *
127
+ * @param name - Optional name of the iterator head (default: 'vm')
128
+ */
129
+ async getIteratorHead(name = 'vm') {
130
+ return this.runWithLock(async () => {
131
+ return (await this.getHead(name, false));
132
+ });
133
+ }
134
+ /**
135
+ * This method differs from `getIteratorHead`. If the head is not found, it returns `undefined`.
136
+ * @param name - Optional name of the iterator head (default: 'vm')
137
+ * @returns
138
+ */
139
+ async getIteratorHeadSafe(name = 'vm') {
140
+ return this.runWithLock(async () => {
141
+ return this.getHead(name, true);
142
+ });
143
+ }
144
+ async getHead(name, returnUndefinedIfNotSet = false) {
145
+ const headHash = this._heads[name];
146
+ if (headHash === undefined && returnUndefinedIfNotSet) {
147
+ return undefined;
148
+ }
149
+ const hash = this._heads[name] ?? this.genesisBlock.hash();
150
+ const block = await this.getBlock(hash);
151
+ return block;
152
+ }
153
+ /**
154
+ * Returns the latest header in the canonical chain.
155
+ */
156
+ async getCanonicalHeadHeader() {
157
+ return this.runWithLock(async () => {
158
+ if (!this._headHeaderHash)
159
+ throw EthereumJSErrorWithoutCode('No head header set');
160
+ const header = await this._getHeader(this._headHeaderHash);
161
+ return header;
162
+ });
163
+ }
164
+ /**
165
+ * Returns the latest full block in the canonical chain.
166
+ */
167
+ async getCanonicalHeadBlock() {
168
+ return this.runWithLock(async () => {
169
+ if (!this._headBlockHash)
170
+ throw EthereumJSErrorWithoutCode('No head block set');
171
+ return this.getBlock(this._headBlockHash);
172
+ });
173
+ }
174
+ /**
175
+ * Adds blocks to the blockchain.
176
+ *
177
+ * If an invalid block is met the function will throw, blocks before will
178
+ * nevertheless remain in the DB. If any of the saved blocks has a higher
179
+ * total difficulty than the current max total difficulty the canonical
180
+ * chain is rebuilt and any stale heads/hashes are overwritten.
181
+ * @param blocks - The blocks to be added to the blockchain
182
+ */
183
+ async putBlocks(blocks) {
184
+ for (let i = 0; i < blocks.length; i++) {
185
+ await this.putBlock(blocks[i]);
186
+ }
187
+ this.DEBUG && this._debug(`put ${blocks.length} blocks`);
188
+ }
189
+ /**
190
+ * Adds a block to the blockchain.
191
+ *
192
+ * If the block is valid and has a higher total difficulty than the current
193
+ * max total difficulty, the canonical chain is rebuilt and any stale
194
+ * heads/hashes are overwritten.
195
+ * @param block - The block to be added to the blockchain
196
+ */
197
+ async putBlock(block) {
198
+ await this._putBlockOrHeader(block);
199
+ }
200
+ /**
201
+ * Adds many headers to the blockchain.
202
+ *
203
+ * If an invalid header is met the function will throw, headers before will
204
+ * nevertheless remain in the DB. If any of the saved headers has a higher
205
+ * total difficulty than the current max total difficulty the canonical
206
+ * chain is rebuilt and any stale heads/hashes are overwritten.
207
+ * @param headers - The headers to be added to the blockchain
208
+ */
209
+ async putHeaders(headers) {
210
+ for (let i = 0; i < headers.length; i++) {
211
+ await this.putHeader(headers[i]);
212
+ }
213
+ this.DEBUG && this._debug(`put ${headers.length} headers`);
214
+ }
215
+ /**
216
+ * Adds a header to the blockchain.
217
+ *
218
+ * If this header is valid and it has a higher total difficulty than the current
219
+ * max total difficulty, the canonical chain is rebuilt and any stale
220
+ * heads/hashes are overwritten.
221
+ * @param header - The header to be added to the blockchain
222
+ */
223
+ async putHeader(header) {
224
+ await this._putBlockOrHeader(header);
225
+ }
226
+ /**
227
+ * Resets the canonical chain to canonicalHead number
228
+ *
229
+ * This updates the head hashes (if affected) to the hash corresponding to
230
+ * canonicalHead and cleans up canonical references greater than canonicalHead
231
+ * @param canonicalHead - The number to which chain should be reset to
232
+ */
233
+ async resetCanonicalHead(canonicalHead) {
234
+ let hash;
235
+ let canonicalHeadHash;
236
+ if (this.DEBUG) {
237
+ canonicalHeadHash = (await this.getCanonicalHeadHeader()).hash();
238
+ }
239
+ await this.runWithLock(async () => {
240
+ hash = await this.dbManager.numberToHash(canonicalHead);
241
+ if (hash === undefined) {
242
+ throw EthereumJSErrorWithoutCode(`no block for ${canonicalHead} found in DB`);
243
+ }
244
+ const header = await this._getHeader(hash, canonicalHead);
245
+ const dbOps = [];
246
+ await this._deleteCanonicalChainReferences(canonicalHead + BIGINT_1, hash, dbOps);
247
+ const ops = dbOps.concat(this._saveHeadOps());
248
+ await this.dbManager.batch(ops);
249
+ await this.checkAndTransitionHardForkByNumber(canonicalHead, header.timestamp);
250
+ });
251
+ if (this._deletedBlocks.length > 0) {
252
+ this.events.emit('deletedCanonicalBlocks', this._deletedBlocks);
253
+ for (const block of this._deletedBlocks)
254
+ this.DEBUG &&
255
+ this._debug(`deleted block along head reset: number ${block.header.number} hash ${bytesToHex(block.hash())}`);
256
+ this.DEBUG &&
257
+ this._debug(`Canonical head set from ${bytesToHex(canonicalHeadHash)} to ${bytesToHex(hash)} (number ${bigIntToHex(canonicalHead)})`);
258
+ this._deletedBlocks = [];
259
+ }
260
+ }
261
+ /**
262
+ * Entrypoint for putting any block or block header. Verifies this block,
263
+ * checks the total TD: if this TD is higher than the current highest TD, we
264
+ * have thus found a new canonical block and have to rewrite the canonical
265
+ * chain. This also updates the head block hashes. If any of the older known
266
+ * canonical chains just became stale, then we also reset every _heads header
267
+ * which points to a stale header to the last verified header which was in the
268
+ * old canonical chain, but also in the new canonical chain. This thus rolls
269
+ * back these headers so that these can be updated to the "new" canonical
270
+ * header using the iterator method.
271
+ * @hidden
272
+ */
273
+ async _putBlockOrHeader(item) {
274
+ await this.runWithLock(async () => {
275
+ // Save the current sane state in case _putBlockOrHeader midway with some
276
+ // dirty changes in head trackers
277
+ const oldHeads = Object.assign({}, this._heads);
278
+ const oldHeadHeaderHash = this._headHeaderHash;
279
+ const oldHeadBlockHash = this._headBlockHash;
280
+ try {
281
+ const block = item instanceof BlockHeader
282
+ ? new Block(item, undefined, undefined, undefined, { common: item.common })
283
+ : item;
284
+ const isGenesis = block.isGenesis();
285
+ // we cannot overwrite the Genesis block after initializing the Blockchain
286
+ if (isGenesis) {
287
+ if (equalsBytes(this.genesisBlock.hash(), block.hash())) {
288
+ // Try to re-put the existing genesis block, accept this
289
+ return;
290
+ }
291
+ throw EthereumJSErrorWithoutCode('Cannot put a different genesis block than current blockchain genesis: create a new Blockchain');
292
+ }
293
+ const { header } = block;
294
+ const blockHash = header.hash();
295
+ const blockNumber = header.number;
296
+ let td = header.difficulty;
297
+ const currentTd = { header: BIGINT_0, block: BIGINT_0 };
298
+ let dbOps = [];
299
+ if (block.common.chainId() !== this.common.chainId()) {
300
+ throw EthereumJSErrorWithoutCode(`Chain mismatch while trying to put block or header. Chain ID of block: ${block.common.chainId}, chain ID of blockchain : ${this.common.chainId}`);
301
+ }
302
+ if (this._validateBlocks && !isGenesis && item instanceof Block) {
303
+ // this calls into `getBlock`, which is why we cannot lock yet
304
+ await this.validateBlock(block);
305
+ }
306
+ if (this._validateConsensus) {
307
+ await this.consensus.validateConsensus(block);
308
+ }
309
+ // set total difficulty in the current context scope
310
+ if (this._headHeaderHash) {
311
+ currentTd.header = await this.getTotalDifficulty(this._headHeaderHash);
312
+ }
313
+ if (this._headBlockHash) {
314
+ currentTd.block = await this.getTotalDifficulty(this._headBlockHash);
315
+ }
316
+ // calculate the total difficulty of the new block
317
+ const parentTd = await this.getParentTD(header);
318
+ if (!block.isGenesis()) {
319
+ td += parentTd;
320
+ }
321
+ // save total difficulty to the database
322
+ dbOps = dbOps.concat(DBSetTD(td, blockNumber, blockHash));
323
+ // save header/block to the database, but save the input not our wrapper block
324
+ dbOps = dbOps.concat(DBSetBlockOrHeader(item));
325
+ let commonAncestor;
326
+ let ancestorHeaders;
327
+ // if total difficulty is higher than current, add it to canonical chain
328
+ if (block.isGenesis() ||
329
+ td > currentTd.header ||
330
+ block.common.consensusType() === ConsensusType.ProofOfStake) {
331
+ const foundCommon = await this.findCommonAncestor(header);
332
+ commonAncestor = foundCommon.commonAncestor;
333
+ ancestorHeaders = foundCommon.ancestorHeaders;
334
+ this._headHeaderHash = blockHash;
335
+ if (item instanceof Block) {
336
+ this._headBlockHash = blockHash;
337
+ }
338
+ if (this._hardforkByHeadBlockNumber) {
339
+ await this.checkAndTransitionHardForkByNumber(blockNumber, header.timestamp);
340
+ }
341
+ // delete higher number assignments and overwrite stale canonical chain
342
+ await this._deleteCanonicalChainReferences(blockNumber + BIGINT_1, blockHash, dbOps);
343
+ // from the current header block, check the blockchain in reverse (i.e.
344
+ // traverse `parentHash`) until `numberToHash` matches the current
345
+ // number/hash in the canonical chain also: overwrite any heads if these
346
+ // heads are stale in `_heads` and `_headBlockHash`
347
+ await this._rebuildCanonical(header, dbOps);
348
+ }
349
+ else {
350
+ // the TD is lower than the current highest TD so we will add the block
351
+ // to the DB, but will not mark it as the canonical chain.
352
+ if (td > currentTd.block && item instanceof Block) {
353
+ this._headBlockHash = blockHash;
354
+ }
355
+ // save hash to number lookup info even if rebuild not needed
356
+ dbOps.push(DBSetHashToNumber(blockHash, blockNumber));
357
+ }
358
+ const ops = dbOps.concat(this._saveHeadOps());
359
+ await this.dbManager.batch(ops);
360
+ await this.consensus?.newBlock(block, commonAncestor, ancestorHeaders);
361
+ this.DEBUG &&
362
+ this._debug(`put block number=${block.header.number} hash=${bytesToHex(blockHash)}`);
363
+ }
364
+ catch (e) {
365
+ // restore head to the previously sane state
366
+ this._heads = oldHeads;
367
+ this._headHeaderHash = oldHeadHeaderHash;
368
+ this._headBlockHash = oldHeadBlockHash;
369
+ throw e;
370
+ }
371
+ });
372
+ if (this._deletedBlocks.length > 0) {
373
+ this.events.emit('deletedCanonicalBlocks', this._deletedBlocks);
374
+ for (const block of this._deletedBlocks)
375
+ this.DEBUG &&
376
+ this._debug(`delete stale canonical block number=${block.header.number} hash=${bytesToHex(block.hash())}`);
377
+ this._deletedBlocks = [];
378
+ }
379
+ }
380
+ /**
381
+ * Validates a block header, throwing if invalid. It is being validated against the reported `parentHash`.
382
+ * It verifies the current block against the `parentHash`:
383
+ * - The `parentHash` is part of the blockchain (it is a valid header)
384
+ * - Current block number is parent block number + 1
385
+ * - Current block has a strictly higher timestamp
386
+ * - Additional PoW checks ->
387
+ * - Current block has valid difficulty and gas limit
388
+ * - In case that the header is an uncle header, it should not be too old or young in the chain.
389
+ * - Additional PoA clique checks ->
390
+ * - Checks on coinbase and mixHash
391
+ * - Current block has a timestamp diff greater or equal to PERIOD
392
+ * - Current block has difficulty correctly marked as INTURN or NOTURN
393
+ * @param header - header to be validated
394
+ * @param height - If this is an uncle header, this is the height of the block that is including it
395
+ */
396
+ async validateHeader(header, height) {
397
+ if (header.isGenesis()) {
398
+ return;
399
+ }
400
+ const parentHeader = await this._getHeader(header.parentHash);
401
+ const { number } = header;
402
+ if (number !== parentHeader.number + BIGINT_1) {
403
+ throw EthereumJSErrorWithoutCode(`invalid number ${header.errorStr()}`);
404
+ }
405
+ if (header.timestamp <= parentHeader.timestamp) {
406
+ throw EthereumJSErrorWithoutCode(`invalid timestamp ${header.errorStr()}`);
407
+ }
408
+ if (!(header.common.consensusType() === 'pos'))
409
+ await this.consensus?.validateDifficulty(header);
410
+ if (this.common.consensusAlgorithm() === ConsensusAlgorithm.Clique) {
411
+ const period = this.common.consensusConfig().period;
412
+ // Timestamp diff between blocks is lower than PERIOD (clique)
413
+ if (parentHeader.timestamp + BigInt(period) > header.timestamp) {
414
+ throw EthereumJSErrorWithoutCode(`invalid timestamp diff (lower than period) ${header.errorStr()}`);
415
+ }
416
+ }
417
+ header.validateGasLimit(parentHeader);
418
+ if (height !== undefined) {
419
+ const dif = height - parentHeader.number;
420
+ if (!(dif < BIGINT_8 && dif > BIGINT_1)) {
421
+ throw EthereumJSErrorWithoutCode(`uncle block has a parent that is too old or too young ${header.errorStr()}`);
422
+ }
423
+ }
424
+ // check blockchain dependent EIP1559 values
425
+ if (header.common.isActivatedEIP(1559)) {
426
+ // check if the base fee is correct
427
+ let expectedBaseFee;
428
+ const londonHfBlock = this.common.hardforkBlock(Hardfork.London);
429
+ const isInitialEIP1559Block = number === londonHfBlock;
430
+ if (isInitialEIP1559Block) {
431
+ expectedBaseFee = header.common.param('initialBaseFee');
432
+ }
433
+ else {
434
+ expectedBaseFee = parentHeader.calcNextBaseFee();
435
+ }
436
+ if (header.baseFeePerGas !== expectedBaseFee) {
437
+ throw EthereumJSErrorWithoutCode(`Invalid block: base fee not correct ${header.errorStr()}`);
438
+ }
439
+ }
440
+ if (header.common.isActivatedEIP(4844)) {
441
+ const expectedExcessBlobGas = parentHeader.calcNextExcessBlobGas(header.common);
442
+ if (header.excessBlobGas !== expectedExcessBlobGas) {
443
+ throw EthereumJSErrorWithoutCode(`expected blob gas: ${expectedExcessBlobGas}, got: ${header.excessBlobGas}`);
444
+ }
445
+ }
446
+ if (header.common.isActivatedEIP(7685)) {
447
+ if (header.requestsHash === undefined) {
448
+ throw EthereumJSErrorWithoutCode(`requestsHash must be provided when EIP-7685 is active`);
449
+ }
450
+ }
451
+ }
452
+ /**
453
+ * Validates a block, by validating the header against the current chain, any uncle headers, and then
454
+ * whether the block is internally consistent
455
+ * @param block block to be validated
456
+ */
457
+ async validateBlock(block) {
458
+ await this.validateHeader(block.header);
459
+ await this._validateUncleHeaders(block);
460
+ await block.validateData(false);
461
+ // TODO: Rethink how validateHeader vs validateBlobTransactions works since the parentHeader is retrieved multiple times
462
+ // (one for each uncle header and then for validateBlobTxs).
463
+ const parentBlock = await this.getBlock(block.header.parentHash);
464
+ block.validateBlobTransactions(parentBlock.header);
465
+ }
466
+ /**
467
+ * The following rules are checked in this method:
468
+ * Uncle Header is a valid header.
469
+ * Uncle Header is an orphan, i.e. it is not one of the headers of the canonical chain.
470
+ * Uncle Header has a parentHash which points to the canonical chain. This parentHash is within the last 7 blocks.
471
+ * Uncle Header is not already included as uncle in another block.
472
+ * @param block - block for which uncles are being validated
473
+ */
474
+ async _validateUncleHeaders(block) {
475
+ const uncleHeaders = block.uncleHeaders;
476
+ if (uncleHeaders.length === 0) {
477
+ return;
478
+ }
479
+ // Each Uncle Header is a valid header
480
+ await Promise.all(uncleHeaders.map((uh) => this.validateHeader(uh, block.header.number)));
481
+ // Check how many blocks we should get in order to validate the uncle.
482
+ // In the worst case, we get 8 blocks, in the best case, we only get 1 block.
483
+ const canonicalBlockMap = [];
484
+ let lowestUncleNumber = block.header.number;
485
+ uncleHeaders.map((header) => {
486
+ if (header.number < lowestUncleNumber) {
487
+ lowestUncleNumber = header.number;
488
+ }
489
+ });
490
+ // Helper variable: set hash to `true` if hash is part of the canonical chain
491
+ const canonicalChainHashes = {};
492
+ // Helper variable: set hash to `true` if uncle hash is included in any canonical block
493
+ const includedUncles = {};
494
+ // Due to the header validation check above, we know that `getBlocks` is between 1 and 8 inclusive.
495
+ const getBlocks = Number(block.header.number - lowestUncleNumber + BIGINT_1);
496
+ // See Geth: https://github.com/ethereum/go-ethereum/blob/b63bffe8202d46ea10ac8c4f441c582642193ac8/consensus/ethash/consensus.go#L207
497
+ // Here we get the necessary blocks from the chain.
498
+ let parentHash = block.header.parentHash;
499
+ for (let i = 0; i < getBlocks; i++) {
500
+ const parentBlock = await this.getBlock(parentHash);
501
+ canonicalBlockMap.push(parentBlock);
502
+ // mark block hash as part of the canonical chain
503
+ // Using deprecated bytesToUnprefixedHex for performance: used as object keys for hash lookups.
504
+ canonicalChainHashes[bytesToUnprefixedHex(parentBlock.hash())] = true;
505
+ // for each of the uncles, mark the uncle as included
506
+ parentBlock.uncleHeaders.map((uh) => {
507
+ includedUncles[bytesToUnprefixedHex(uh.hash())] = true;
508
+ });
509
+ parentHash = parentBlock.header.parentHash;
510
+ }
511
+ // Here we check:
512
+ // Uncle Header is an orphan, i.e. it is not one of the headers of the canonical chain.
513
+ // Uncle Header is not already included as uncle in another block.
514
+ // Uncle Header has a parentHash which points to the canonical chain.
515
+ uncleHeaders.map((uh) => {
516
+ // Using deprecated bytesToUnprefixedHex for performance: used as object keys for hash lookups.
517
+ const uncleHash = bytesToUnprefixedHex(uh.hash());
518
+ const parentHash = bytesToUnprefixedHex(uh.parentHash);
519
+ if (!canonicalChainHashes[parentHash]) {
520
+ throw EthereumJSErrorWithoutCode(`The parent hash of the uncle header is not part of the canonical chain ${block.errorStr()}`);
521
+ }
522
+ if (includedUncles[uncleHash]) {
523
+ throw EthereumJSErrorWithoutCode(`The uncle is already included in the canonical chain ${block.errorStr()}`);
524
+ }
525
+ if (canonicalChainHashes[uncleHash]) {
526
+ throw EthereumJSErrorWithoutCode(`The uncle is a canonical block ${block.errorStr()}`);
527
+ }
528
+ });
529
+ }
530
+ /**
531
+ * Gets a block by its hash or number. If a number is provided, the returned
532
+ * block will be the canonical block at that number in the chain
533
+ *
534
+ * @param blockId - The block's hash or number. If a hash is provided, then
535
+ * this will be immediately looked up, otherwise it will wait until we have
536
+ * unlocked the DB
537
+ */
538
+ async getBlock(blockId) {
539
+ // cannot wait for a lock here: it is used both in `validate` of `Block`
540
+ // (calls `getBlock` to get `parentHash`) it is also called from `runBlock`
541
+ // in the `VM` if we encounter a `BLOCKHASH` opcode: then a bigint is used we
542
+ // need to then read the block from the canonical chain Q: is this safe? We
543
+ // know it is OK if we call it from the iterator... (runBlock)
544
+ const block = await this.dbManager.getBlock(blockId);
545
+ if (block === undefined) {
546
+ if (typeof blockId === 'object') {
547
+ throw EthereumJSErrorWithoutCode(`Block with hash ${bytesToHex(blockId)} not found in DB`);
548
+ }
549
+ else {
550
+ throw EthereumJSErrorWithoutCode(`Block number ${blockId} not found in DB`);
551
+ }
552
+ }
553
+ return block;
554
+ }
555
+ /**
556
+ * Gets total difficulty for a block specified by hash and number
557
+ */
558
+ async getTotalDifficulty(hash, number) {
559
+ if (number === undefined) {
560
+ number = await this.dbManager.hashToNumber(hash);
561
+ if (number === undefined) {
562
+ throw EthereumJSErrorWithoutCode(`Block with hash ${bytesToHex(hash)} not found in DB`);
563
+ }
564
+ }
565
+ return this.dbManager.getTotalDifficulty(hash, number);
566
+ }
567
+ /**
568
+ * Gets total difficulty for a header's parent, helpful for determining terminal block
569
+ * @param header - Block header whose parent td is desired
570
+ */
571
+ async getParentTD(header) {
572
+ return header.number === BIGINT_0
573
+ ? header.difficulty
574
+ : this.getTotalDifficulty(header.parentHash, header.number - BIGINT_1);
575
+ }
576
+ /**
577
+ * Looks up many blocks relative to blockId Note: due to `GetBlockHeaders
578
+ * (0x03)` (ETH wire protocol) we have to support skip/reverse as well.
579
+ * @param blockId - The block's hash or number
580
+ * @param maxBlocks - Max number of blocks to return
581
+ * @param skip - Number of blocks to skip apart
582
+ * @param reverse - Fetch blocks in reverse
583
+ */
584
+ async getBlocks(blockId, maxBlocks, skip, reverse) {
585
+ return this.runWithLock(async () => {
586
+ const blocks = [];
587
+ let i = -1;
588
+ const nextBlock = async (blockId) => {
589
+ let block;
590
+ try {
591
+ block = await this.getBlock(blockId);
592
+ }
593
+ catch (err) {
594
+ if (err.message.includes('not found in DB') === true) {
595
+ return;
596
+ }
597
+ else
598
+ throw err;
599
+ }
600
+ i++;
601
+ const nextBlockNumber = block.header.number + BigInt(reverse ? -1 : 1);
602
+ if (i !== 0 && skip && i % (skip + 1) !== 0) {
603
+ return nextBlock(nextBlockNumber);
604
+ }
605
+ blocks.push(block);
606
+ if (blocks.length < maxBlocks) {
607
+ await nextBlock(nextBlockNumber);
608
+ }
609
+ };
610
+ await nextBlock(blockId);
611
+ return blocks;
612
+ });
613
+ }
614
+ /**
615
+ * Given an ordered array, returns an array of hashes that are not in the
616
+ * blockchain yet. Uses binary search to find out what hashes are missing.
617
+ * Therefore, the array needs to be ordered upon number.
618
+ * @param hashes - Ordered array of hashes (ordered on `number`).
619
+ */
620
+ async selectNeededHashes(hashes) {
621
+ return this.runWithLock(async () => {
622
+ let max;
623
+ let mid;
624
+ let min;
625
+ max = hashes.length - 1;
626
+ mid = min = 0;
627
+ while (max >= min) {
628
+ let number;
629
+ try {
630
+ number = await this.dbManager.hashToNumber(hashes[mid]);
631
+ }
632
+ catch (err) {
633
+ if (err.message.includes('not found in DB') === true) {
634
+ number = undefined;
635
+ }
636
+ else
637
+ throw err;
638
+ }
639
+ if (number !== undefined) {
640
+ min = mid + 1;
641
+ }
642
+ else {
643
+ max = mid - 1;
644
+ }
645
+ mid = Math.floor((min + max) / 2);
646
+ }
647
+ return hashes.slice(min);
648
+ });
649
+ }
650
+ /**
651
+ * Completely deletes a block from the blockchain including any references to
652
+ * this block. If this block was in the canonical chain, then also each child
653
+ * block of this block is deleted Also, if this was a canonical block, each
654
+ * head header which is part of this now stale chain will be set to the
655
+ * parentHeader of this block An example reason to execute is when running the
656
+ * block in the VM invalidates this block: this will then reset the canonical
657
+ * head to the past block (which has been validated in the past by the VM, so
658
+ * we can be sure it is correct).
659
+ * @param blockHash - The hash of the block to be deleted
660
+ */
661
+ async delBlock(blockHash) {
662
+ // Q: is it safe to make this not wait for a lock? this is called from
663
+ // `BlockchainTestsRunner` in case `runBlock` throws (i.e. the block is invalid).
664
+ // But is this the way to go? If we know this is called from the
665
+ // iterator we are safe, but if this is called from anywhere
666
+ // else then this might lead to a concurrency problem?
667
+ await this._delBlock(blockHash);
668
+ }
669
+ /**
670
+ * @hidden
671
+ */
672
+ async _delBlock(blockHash) {
673
+ const dbOps = [];
674
+ // get header
675
+ const header = await this._getHeader(blockHash);
676
+ const blockHeader = header;
677
+ const blockNumber = blockHeader.number;
678
+ const parentHash = blockHeader.parentHash;
679
+ // check if block is in the canonical chain
680
+ const canonicalHash = await this.safeNumberToHash(blockNumber);
681
+ const inCanonical = canonicalHash !== false && equalsBytes(canonicalHash, blockHash);
682
+ // delete the block, and if block is in the canonical chain, delete all
683
+ // children as well
684
+ await this._delChild(blockHash, blockNumber, inCanonical ? parentHash : null, dbOps);
685
+ // delete all number to hash mappings for deleted block number and above
686
+ if (inCanonical) {
687
+ await this._deleteCanonicalChainReferences(blockNumber, parentHash, dbOps);
688
+ }
689
+ await this.dbManager.batch(dbOps);
690
+ if (this._deletedBlocks.length > 0) {
691
+ this.events.emit('deletedCanonicalBlocks', this._deletedBlocks);
692
+ for (const block of this._deletedBlocks)
693
+ this.DEBUG &&
694
+ this._debug(`delete stale canonical block number=${block.header.number} hash=${blockHash})}`);
695
+ this._deletedBlocks = [];
696
+ }
697
+ }
698
+ /**
699
+ * Updates the `DatabaseOperation` list to delete a block from the DB,
700
+ * identified by `blockHash` and `blockNumber`. Deletes fields from `Header`,
701
+ * `Body`, `HashToNumber` and `TotalDifficulty` tables. If child blocks of
702
+ * this current block are in the canonical chain, delete these as well. Does
703
+ * not actually commit these changes to the DB. Sets `_headHeaderHash` and
704
+ * `_headBlockHash` to `headHash` if any of these matches the current child to
705
+ * be deleted.
706
+ * @param blockHash - the block hash to delete
707
+ * @param blockNumber - the number corresponding to the block hash
708
+ * @param headHash - the current head of the chain (if null, do not update
709
+ * `_headHeaderHash` and `_headBlockHash`)
710
+ * @param ops - the `DatabaseOperation` list to add the delete operations to
711
+ * @hidden
712
+ */
713
+ async _delChild(blockHash, blockNumber, headHash, ops) {
714
+ // delete header, body, hash to number mapping and td
715
+ ops.push(DBOp.del(DBTarget.Header, { blockHash, blockNumber }));
716
+ ops.push(DBOp.del(DBTarget.Body, { blockHash, blockNumber }));
717
+ ops.push(DBOp.del(DBTarget.HashToNumber, { blockHash }));
718
+ ops.push(DBOp.del(DBTarget.TotalDifficulty, { blockHash, blockNumber }));
719
+ if (!headHash) {
720
+ return;
721
+ }
722
+ if (this._headHeaderHash !== undefined &&
723
+ equalsBytes(this._headHeaderHash, blockHash) === true) {
724
+ this._headHeaderHash = headHash;
725
+ }
726
+ if (this._headBlockHash !== undefined && equalsBytes(this._headBlockHash, blockHash)) {
727
+ this._headBlockHash = headHash;
728
+ }
729
+ try {
730
+ const childHeader = await this.getCanonicalHeader(blockNumber + BIGINT_1);
731
+ await this._delChild(childHeader.hash(), childHeader.number, headHash, ops);
732
+ }
733
+ catch (err) {
734
+ if (err.message.includes('not found in canonical chain') !== true) {
735
+ throw err;
736
+ }
737
+ }
738
+ }
739
+ /**
740
+ * Iterates through blocks starting at the specified iterator head and calls
741
+ * the onBlock function on each block. The current location of an iterator
742
+ * head can be retrieved using {@link Blockchain.getIteratorHead}.
743
+ *
744
+ * @param name - Name of the state root head
745
+ * @param onBlock - Function called on each block with params (block, reorg)
746
+ * @param maxBlocks - How many blocks to run. By default, run all unprocessed blocks in the canonical chain.
747
+ * @param releaseLockOnCallback - Do not lock the blockchain for running the callback (default: `false`)
748
+ * @returns number of blocks actually iterated
749
+ */
750
+ async iterator(name, onBlock, maxBlocks, releaseLockOnCallback) {
751
+ return this.runWithLock(async () => {
752
+ let headHash = this._heads[name] ?? this.genesisBlock.hash();
753
+ if (typeof maxBlocks === 'number' && maxBlocks < 0) {
754
+ throw 'If maxBlocks is provided, it has to be a non-negative number';
755
+ }
756
+ let headBlockNumber = await this.dbManager.hashToNumber(headHash);
757
+ // `headBlockNumber` should always exist since it defaults to the genesis block
758
+ let nextBlockNumber = headBlockNumber + BIGINT_1;
759
+ let blocksRanCounter = 0;
760
+ let lastBlock;
761
+ try {
762
+ while (maxBlocks !== blocksRanCounter) {
763
+ try {
764
+ let nextBlock = await this.getBlock(nextBlockNumber);
765
+ const reorg = lastBlock
766
+ ? !equalsBytes(lastBlock.hash(), nextBlock.header.parentHash)
767
+ : false;
768
+ if (reorg) {
769
+ // If reorg has happened, the _heads must have been updated so lets reload the counters
770
+ headHash = this._heads[name] ?? this.genesisBlock.hash();
771
+ headBlockNumber = await this.dbManager.hashToNumber(headHash);
772
+ nextBlockNumber = headBlockNumber + BIGINT_1;
773
+ nextBlock = await this.getBlock(nextBlockNumber);
774
+ }
775
+ // While running onBlock with released lock, reorgs can happen via putBlocks
776
+ let reorgWhileOnBlock = false;
777
+ if (releaseLockOnCallback === true) {
778
+ this._lock.release();
779
+ }
780
+ try {
781
+ await onBlock(nextBlock, reorg);
782
+ }
783
+ finally {
784
+ if (releaseLockOnCallback === true) {
785
+ await this._lock.acquire();
786
+ // If lock was released check if reorg occurred
787
+ const nextBlockMayBeReorged = await this.getBlock(nextBlockNumber).catch((_e) => null);
788
+ reorgWhileOnBlock = nextBlockMayBeReorged
789
+ ? !equalsBytes(nextBlockMayBeReorged.hash(), nextBlock.hash())
790
+ : true;
791
+ }
792
+ }
793
+ // if there was no reorg, update head
794
+ if (!reorgWhileOnBlock) {
795
+ this._heads[name] = nextBlock.hash();
796
+ lastBlock = nextBlock;
797
+ nextBlockNumber++;
798
+ }
799
+ // Successful execution of onBlock, move the head pointer
800
+ blocksRanCounter++;
801
+ }
802
+ catch (error) {
803
+ if (error.message.includes('not found in DB')) {
804
+ break;
805
+ }
806
+ else {
807
+ throw error;
808
+ }
809
+ }
810
+ }
811
+ return blocksRanCounter;
812
+ }
813
+ finally {
814
+ await this._saveHeads();
815
+ }
816
+ });
817
+ }
818
+ /**
819
+ * Set header hash of a certain `tag`.
820
+ * When calling the iterator, the iterator will start running the first child block after the header hash currently stored.
821
+ * @param tag - The tag to save the headHash to
822
+ * @param headHash - The head hash to save
823
+ */
824
+ async setIteratorHead(tag, headHash) {
825
+ await this.runWithLock(async () => {
826
+ this._heads[tag] = headHash;
827
+ await this._saveHeads();
828
+ });
829
+ }
830
+ /* Methods regarding reorg operations */
831
+ /**
832
+ * Find the common ancestor of the new block and the old block.
833
+ * @param newHeader - the new block header
834
+ */
835
+ async findCommonAncestor(newHeader) {
836
+ if (!this._headHeaderHash)
837
+ throw EthereumJSErrorWithoutCode('No head header set');
838
+ const ancestorHeaders = new Set();
839
+ let header = await this._getHeader(this._headHeaderHash);
840
+ if (header.number > newHeader.number) {
841
+ header = await this.getCanonicalHeader(newHeader.number);
842
+ ancestorHeaders.add(header);
843
+ }
844
+ else {
845
+ while (header.number !== newHeader.number && newHeader.number > BIGINT_0) {
846
+ newHeader = await this._getHeader(newHeader.parentHash, newHeader.number - BIGINT_1);
847
+ ancestorHeaders.add(newHeader);
848
+ }
849
+ }
850
+ if (header.number !== newHeader.number) {
851
+ throw EthereumJSErrorWithoutCode('Failed to find ancient header');
852
+ }
853
+ while (!equalsBytes(header.hash(), newHeader.hash()) && header.number > BIGINT_0) {
854
+ header = await this.getCanonicalHeader(header.number - BIGINT_1);
855
+ ancestorHeaders.add(header);
856
+ newHeader = await this._getHeader(newHeader.parentHash, newHeader.number - BIGINT_1);
857
+ ancestorHeaders.add(newHeader);
858
+ }
859
+ if (!equalsBytes(header.hash(), newHeader.hash())) {
860
+ throw EthereumJSErrorWithoutCode('Failed to find ancient header');
861
+ }
862
+ this.DEBUG && this._debug(`found common ancestor with hash=${bytesToHex(header.hash())}`);
863
+ this.DEBUG && this._debug(`total ancestor headers num=${ancestorHeaders.size}`);
864
+ return {
865
+ commonAncestor: header,
866
+ ancestorHeaders: Array.from(ancestorHeaders),
867
+ };
868
+ }
869
+ /**
870
+ * Pushes DB operations to delete canonical number assignments for specified
871
+ * block number and above. This only deletes `NumberToHash` references and not
872
+ * the blocks themselves. Note: this does not write to the DB but only pushes
873
+ * to a DB operations list.
874
+ * @param blockNumber - the block number from which we start deleting
875
+ * canonical chain assignments (including this block)
876
+ * @param headHash - the hash of the current canonical chain head. The _heads
877
+ * reference matching any hash of any of the deleted blocks will be set to
878
+ * this
879
+ * @param ops - the DatabaseOperation list to write DatabaseOperations to
880
+ * @hidden
881
+ */
882
+ async _deleteCanonicalChainReferences(blockNumber, headHash, ops) {
883
+ try {
884
+ let hash;
885
+ hash = await this.safeNumberToHash(blockNumber);
886
+ while (hash !== false) {
887
+ ops.push(DBOp.del(DBTarget.NumberToHash, { blockNumber }));
888
+ if (this.events.listenerCount('deletedCanonicalBlocks') > 0) {
889
+ const block = await this.getBlock(blockNumber);
890
+ this._deletedBlocks.push(block);
891
+ }
892
+ // reset stale iterator heads to current canonical head this can, for
893
+ // instance, make the VM run "older" (i.e. lower number blocks than last
894
+ // executed block) blocks to verify the chain up to the current, actual,
895
+ // head.
896
+ for (const name of Object.keys(this._heads)) {
897
+ if (equalsBytes(this._heads[name], hash)) {
898
+ this._heads[name] = headHash;
899
+ }
900
+ }
901
+ // reset stale headHeader to current canonical
902
+ if (this._headHeaderHash !== undefined &&
903
+ equalsBytes(this._headHeaderHash, hash) === true) {
904
+ this._headHeaderHash = headHash;
905
+ }
906
+ // reset stale headBlock to current canonical
907
+ if (this._headBlockHash !== undefined && equalsBytes(this._headBlockHash, hash) === true) {
908
+ this._headBlockHash = headHash;
909
+ }
910
+ blockNumber++;
911
+ hash = await this.safeNumberToHash(blockNumber);
912
+ }
913
+ this.DEBUG &&
914
+ this._deletedBlocks.length > 0 &&
915
+ this._debug(`deleted ${this._deletedBlocks.length} stale canonical blocks in total`);
916
+ }
917
+ catch (e) {
918
+ // Ensure that if this method throws, `_deletedBlocks` is reset to the empty array
919
+ this._deletedBlocks = [];
920
+ throw e;
921
+ }
922
+ }
923
+ /**
924
+ * Given a `header`, put all operations to change the canonical chain directly
925
+ * into `ops`. This walks the supplied `header` backwards. It is thus assumed
926
+ * that this header should be canonical header. For each header the
927
+ * corresponding hash corresponding to the current canonical chain in the DB
928
+ * is checked. If the number => hash reference does not correspond to the
929
+ * reference in the DB, we overwrite this reference with the implied number =>
930
+ * hash reference Also, each `_heads` member is checked; if these point to a
931
+ * stale hash, then the hash which we terminate the loop (i.e. the first hash
932
+ * which matches the number => hash of the implied chain) is put as this stale
933
+ * head hash. The same happens to _headBlockHash.
934
+ * @param header - The canonical header.
935
+ * @param ops - The database operations list.
936
+ * @hidden
937
+ */
938
+ async _rebuildCanonical(header, ops) {
939
+ let currentNumber = header.number;
940
+ let currentCanonicalHash = header.hash();
941
+ // track the staleHash: this is the hash currently in the DB which matches
942
+ // the block number of the provided header.
943
+ let staleHash = false;
944
+ let staleHeads = [];
945
+ let staleHeadBlock = false;
946
+ const loopCondition = async () => {
947
+ staleHash = await this.safeNumberToHash(currentNumber);
948
+ currentCanonicalHash = header.hash();
949
+ return staleHash === false || !equalsBytes(currentCanonicalHash, staleHash);
950
+ };
951
+ while (await loopCondition()) {
952
+ // handle genesis block
953
+ const blockHash = header.hash();
954
+ const blockNumber = header.number;
955
+ if (blockNumber === BIGINT_0) {
956
+ break;
957
+ }
958
+ DBSaveLookups(blockHash, blockNumber).map((op) => {
959
+ ops.push(op);
960
+ });
961
+ // mark each key `_heads` which is currently set to the hash in the DB as
962
+ // stale to overwrite later in `_deleteCanonicalChainReferences`.
963
+ for (const name of Object.keys(this._heads)) {
964
+ if (staleHash && equalsBytes(this._heads[name], staleHash)) {
965
+ staleHeads.push(name);
966
+ }
967
+ }
968
+ // flag stale headBlock for reset
969
+ if (staleHash &&
970
+ this._headBlockHash !== undefined &&
971
+ equalsBytes(this._headBlockHash, staleHash) === true) {
972
+ staleHeadBlock = true;
973
+ }
974
+ header = await this._getHeader(header.parentHash, --currentNumber);
975
+ if (header === undefined) {
976
+ staleHeads = [];
977
+ break;
978
+ }
979
+ }
980
+ // When the stale hash is equal to the blockHash of the provided header,
981
+ // set stale heads to last previously valid canonical block
982
+ for (const name of staleHeads) {
983
+ this._heads[name] = currentCanonicalHash;
984
+ }
985
+ // set stale headBlock to last previously valid canonical block
986
+ if (staleHeadBlock) {
987
+ this._headBlockHash = currentCanonicalHash;
988
+ }
989
+ this.DEBUG && this._debug(`stale heads found num=${staleHeads.length}`);
990
+ }
991
+ /* Helper functions */
992
+ /**
993
+ * Builds the `DatabaseOperation[]` list which describes the DB operations to
994
+ * write the heads, head header hash and the head header block to the DB
995
+ * @hidden
996
+ */
997
+ _saveHeadOps() {
998
+ // Convert DB heads to hex strings for efficient storage in DB
999
+ // LevelDB doesn't handle Uint8Arrays properly when they are part
1000
+ // of a JSON object being stored as a value in the DB
1001
+ // Using deprecated bytesToUnprefixedHex for performance: used for JSON serialization where unprefixed hex is needed.
1002
+ const hexHeads = Object.fromEntries(Object.entries(this._heads).map((entry) => [entry[0], bytesToUnprefixedHex(entry[1])]));
1003
+ return [
1004
+ DBOp.set(DBTarget.Heads, hexHeads),
1005
+ DBOp.set(DBTarget.HeadHeader, this._headHeaderHash),
1006
+ DBOp.set(DBTarget.HeadBlock, this._headBlockHash),
1007
+ ];
1008
+ }
1009
+ /**
1010
+ * Gets the `DatabaseOperation[]` list to save `_heads`, `_headHeaderHash` and
1011
+ * `_headBlockHash` and writes these to the DB
1012
+ * @hidden
1013
+ */
1014
+ async _saveHeads() {
1015
+ return this.dbManager.batch(this._saveHeadOps());
1016
+ }
1017
+ /**
1018
+ * Gets a header by hash and number. Header can exist outside the canonical
1019
+ * chain
1020
+ *
1021
+ * @hidden
1022
+ */
1023
+ async _getHeader(hash, number) {
1024
+ if (number === undefined) {
1025
+ number = await this.dbManager.hashToNumber(hash);
1026
+ if (number === undefined)
1027
+ throw EthereumJSErrorWithoutCode(`no header for ${bytesToHex(hash)} found in DB`);
1028
+ }
1029
+ return this.dbManager.getHeader(hash, number);
1030
+ }
1031
+ async checkAndTransitionHardForkByNumber(number, timestamp) {
1032
+ this.common.setHardforkBy({
1033
+ blockNumber: number,
1034
+ timestamp,
1035
+ });
1036
+ this._consensusCheck();
1037
+ await this.consensus?.setup({ blockchain: this });
1038
+ await this.consensus?.genesisInit(this.genesisBlock);
1039
+ }
1040
+ /**
1041
+ * Gets a header by number. Header must be in the canonical chain
1042
+ */
1043
+ async getCanonicalHeader(number) {
1044
+ const hash = await this.dbManager.numberToHash(number);
1045
+ if (hash === undefined) {
1046
+ throw EthereumJSErrorWithoutCode(`header with number ${number} not found in canonical chain`);
1047
+ }
1048
+ return this._getHeader(hash, number);
1049
+ }
1050
+ /**
1051
+ * This method either returns a Uint8Array if there exists one in the DB or if it
1052
+ * does not exist then return false If DB throws
1053
+ * any other error, this function throws.
1054
+ * @param number
1055
+ */
1056
+ async safeNumberToHash(number) {
1057
+ const hash = await this.dbManager.numberToHash(number);
1058
+ return hash ?? false;
1059
+ }
1060
+ /**
1061
+ * The genesis {@link Block} for the blockchain.
1062
+ */
1063
+ get genesisBlock() {
1064
+ if (!this._genesisBlock)
1065
+ throw EthereumJSErrorWithoutCode('genesis block not set (init may not be finished)');
1066
+ return this._genesisBlock;
1067
+ }
1068
+ /**
1069
+ * Creates a genesis {@link Block} for the blockchain with params from {@link Common.genesis}
1070
+ * @param stateRoot The genesis stateRoot
1071
+ */
1072
+ createGenesisBlock(stateRoot) {
1073
+ const common = this.common.copy();
1074
+ common.setHardforkBy({
1075
+ blockNumber: 0,
1076
+ timestamp: common.genesis().timestamp,
1077
+ });
1078
+ const header = {
1079
+ ...common.genesis(),
1080
+ number: 0,
1081
+ stateRoot,
1082
+ withdrawalsRoot: common.isActivatedEIP(4895) ? KECCAK256_RLP : undefined,
1083
+ requestsHash: common.isActivatedEIP(7685) ? SHA256_NULL : undefined,
1084
+ };
1085
+ if (common.consensusType() === 'poa') {
1086
+ if (common.genesis().extraData) {
1087
+ // Ensure extra data is populated from genesis data if provided
1088
+ header.extraData = common.genesis().extraData;
1089
+ }
1090
+ else {
1091
+ // Add required extraData (32 bytes vanity + 65 bytes filled with zeroes
1092
+ header.extraData = concatBytes(new Uint8Array(32), new Uint8Array(65));
1093
+ }
1094
+ }
1095
+ return createBlock({
1096
+ header,
1097
+ withdrawals: common.isActivatedEIP(4895) ? [] : undefined,
1098
+ }, { common });
1099
+ }
1100
+ }
1101
+ //# sourceMappingURL=blockchain.js.map