@aztec/archiver 0.0.1-commit.fce3e4f → 0.0.1-commit.ff7989d6c

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 (209) hide show
  1. package/README.md +156 -22
  2. package/dest/archiver.d.ts +139 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +699 -0
  5. package/dest/config.d.ts +30 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +21 -5
  8. package/dest/errors.d.ts +41 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +62 -0
  11. package/dest/factory.d.ts +9 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +97 -13
  14. package/dest/index.d.ts +11 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +9 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +148 -0
  23. package/dest/l1/calldata_retriever.d.ts +118 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +484 -0
  26. package/dest/l1/data_retrieval.d.ts +89 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +80 -153
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +157 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_trace.d.ts +32 -0
  42. package/dest/l1/validate_trace.d.ts.map +1 -0
  43. package/dest/l1/validate_trace.js +154 -0
  44. package/dest/modules/data_source_base.d.ts +89 -0
  45. package/dest/modules/data_source_base.d.ts.map +1 -0
  46. package/dest/modules/data_source_base.js +216 -0
  47. package/dest/modules/data_store_updater.d.ts +80 -0
  48. package/dest/modules/data_store_updater.d.ts.map +1 -0
  49. package/dest/modules/data_store_updater.js +323 -0
  50. package/dest/modules/instrumentation.d.ts +39 -0
  51. package/dest/modules/instrumentation.d.ts.map +1 -0
  52. package/dest/{archiver → modules}/instrumentation.js +39 -62
  53. package/dest/modules/l1_synchronizer.d.ts +76 -0
  54. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  55. package/dest/modules/l1_synchronizer.js +1112 -0
  56. package/dest/modules/validation.d.ts +17 -0
  57. package/dest/modules/validation.d.ts.map +1 -0
  58. package/dest/{archiver → modules}/validation.js +7 -1
  59. package/dest/store/block_store.d.ts +196 -0
  60. package/dest/store/block_store.d.ts.map +1 -0
  61. package/dest/store/block_store.js +773 -0
  62. package/dest/store/contract_class_store.d.ts +18 -0
  63. package/dest/store/contract_class_store.d.ts.map +1 -0
  64. package/dest/{archiver/kv_archiver_store → store}/contract_class_store.js +13 -9
  65. package/dest/store/contract_instance_store.d.ts +24 -0
  66. package/dest/store/contract_instance_store.d.ts.map +1 -0
  67. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +1 -1
  68. package/dest/store/kv_archiver_store.d.ts +354 -0
  69. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  70. package/dest/store/kv_archiver_store.js +464 -0
  71. package/dest/store/l2_tips_cache.d.ts +19 -0
  72. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  73. package/dest/store/l2_tips_cache.js +89 -0
  74. package/dest/store/log_store.d.ts +54 -0
  75. package/dest/store/log_store.d.ts.map +1 -0
  76. package/dest/store/log_store.js +456 -0
  77. package/dest/store/message_store.d.ts +40 -0
  78. package/dest/store/message_store.d.ts.map +1 -0
  79. package/dest/{archiver/kv_archiver_store → store}/message_store.js +15 -14
  80. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  81. package/dest/structs/data_retrieval.d.ts.map +1 -0
  82. package/dest/structs/inbox_message.d.ts +15 -0
  83. package/dest/structs/inbox_message.d.ts.map +1 -0
  84. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  85. package/dest/structs/published.d.ts +2 -0
  86. package/dest/structs/published.d.ts.map +1 -0
  87. package/dest/test/fake_l1_state.d.ts +193 -0
  88. package/dest/test/fake_l1_state.d.ts.map +1 -0
  89. package/dest/test/fake_l1_state.js +389 -0
  90. package/dest/test/index.d.ts +2 -1
  91. package/dest/test/index.d.ts.map +1 -1
  92. package/dest/test/index.js +4 -1
  93. package/dest/test/mock_archiver.d.ts +16 -8
  94. package/dest/test/mock_archiver.d.ts.map +1 -1
  95. package/dest/test/mock_archiver.js +19 -14
  96. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  97. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  98. package/dest/test/mock_l1_to_l2_message_source.js +21 -11
  99. package/dest/test/mock_l2_block_source.d.ts +51 -18
  100. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  101. package/dest/test/mock_l2_block_source.js +245 -82
  102. package/dest/test/mock_structs.d.ts +80 -4
  103. package/dest/test/mock_structs.d.ts.map +1 -1
  104. package/dest/test/mock_structs.js +145 -11
  105. package/dest/test/noop_l1_archiver.d.ts +23 -0
  106. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  107. package/dest/test/noop_l1_archiver.js +68 -0
  108. package/package.json +20 -20
  109. package/src/archiver.ts +443 -0
  110. package/src/{archiver/config.ts → config.ts} +28 -12
  111. package/src/errors.ts +102 -0
  112. package/src/factory.ts +143 -13
  113. package/src/index.ts +11 -3
  114. package/src/interfaces.ts +9 -0
  115. package/src/l1/README.md +98 -0
  116. package/src/l1/bin/retrieve-calldata.ts +181 -0
  117. package/src/l1/calldata_retriever.ts +663 -0
  118. package/src/{archiver → l1}/data_retrieval.ts +146 -224
  119. package/src/l1/debug_tx.ts +99 -0
  120. package/src/l1/spire_proposer.ts +160 -0
  121. package/src/l1/trace_tx.ts +128 -0
  122. package/src/l1/types.ts +13 -0
  123. package/src/l1/validate_trace.ts +229 -0
  124. package/src/modules/data_source_base.ts +328 -0
  125. package/src/modules/data_store_updater.ts +448 -0
  126. package/src/{archiver → modules}/instrumentation.ts +43 -66
  127. package/src/modules/l1_synchronizer.ts +932 -0
  128. package/src/{archiver → modules}/validation.ts +11 -6
  129. package/src/store/block_store.ts +1015 -0
  130. package/src/{archiver/kv_archiver_store → store}/contract_class_store.ts +13 -9
  131. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +2 -2
  132. package/src/store/kv_archiver_store.ts +671 -0
  133. package/src/store/l2_tips_cache.ts +89 -0
  134. package/src/store/log_store.ts +637 -0
  135. package/src/{archiver/kv_archiver_store → store}/message_store.ts +21 -18
  136. package/src/{archiver/structs → structs}/inbox_message.ts +8 -8
  137. package/src/{archiver/structs → structs}/published.ts +0 -1
  138. package/src/test/fake_l1_state.ts +607 -0
  139. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  140. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  141. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  142. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  143. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  144. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  145. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  146. package/src/test/index.ts +4 -0
  147. package/src/test/mock_archiver.ts +23 -16
  148. package/src/test/mock_l1_to_l2_message_source.ts +18 -11
  149. package/src/test/mock_l2_block_source.ts +296 -90
  150. package/src/test/mock_structs.ts +275 -13
  151. package/src/test/noop_l1_archiver.ts +109 -0
  152. package/dest/archiver/archiver.d.ts +0 -287
  153. package/dest/archiver/archiver.d.ts.map +0 -1
  154. package/dest/archiver/archiver.js +0 -1408
  155. package/dest/archiver/archiver_store.d.ts +0 -255
  156. package/dest/archiver/archiver_store.d.ts.map +0 -1
  157. package/dest/archiver/archiver_store.js +0 -4
  158. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  159. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  160. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  161. package/dest/archiver/config.d.ts +0 -21
  162. package/dest/archiver/config.d.ts.map +0 -1
  163. package/dest/archiver/data_retrieval.d.ts +0 -79
  164. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  165. package/dest/archiver/errors.d.ts +0 -12
  166. package/dest/archiver/errors.d.ts.map +0 -1
  167. package/dest/archiver/errors.js +0 -17
  168. package/dest/archiver/index.d.ts +0 -7
  169. package/dest/archiver/index.d.ts.map +0 -1
  170. package/dest/archiver/index.js +0 -4
  171. package/dest/archiver/instrumentation.d.ts +0 -35
  172. package/dest/archiver/instrumentation.d.ts.map +0 -1
  173. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  174. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  175. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  176. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  177. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  178. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  179. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  180. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  181. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  182. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  183. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  184. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  185. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  186. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  187. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  188. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  189. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  190. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  191. package/dest/archiver/structs/published.d.ts +0 -3
  192. package/dest/archiver/structs/published.d.ts.map +0 -1
  193. package/dest/archiver/validation.d.ts +0 -17
  194. package/dest/archiver/validation.d.ts.map +0 -1
  195. package/dest/rpc/index.d.ts +0 -9
  196. package/dest/rpc/index.d.ts.map +0 -1
  197. package/dest/rpc/index.js +0 -15
  198. package/src/archiver/archiver.ts +0 -1858
  199. package/src/archiver/archiver_store.ts +0 -305
  200. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  201. package/src/archiver/errors.ts +0 -26
  202. package/src/archiver/index.ts +0 -6
  203. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  204. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  205. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  206. package/src/rpc/index.ts +0 -16
  207. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  208. /package/dest/{archiver/structs → structs}/published.js +0 -0
  209. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,773 @@
1
+ import { INITIAL_CHECKPOINT_NUMBER, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
+ import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint } from '@aztec/foundation/branded-types';
3
+ import { Fr } from '@aztec/foundation/curves/bn254';
4
+ import { toArray } from '@aztec/foundation/iterable';
5
+ import { createLogger } from '@aztec/foundation/log';
6
+ import { BufferReader } from '@aztec/foundation/serialize';
7
+ import { bufferToHex } from '@aztec/foundation/string';
8
+ import { isDefined } from '@aztec/foundation/types';
9
+ import { Body, CheckpointedL2Block, CommitteeAttestation, L2Block, deserializeValidateCheckpointResult, serializeValidateCheckpointResult } from '@aztec/stdlib/block';
10
+ import { L1PublishedData } from '@aztec/stdlib/checkpoint';
11
+ import { CheckpointHeader } from '@aztec/stdlib/rollup';
12
+ import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
13
+ import { BlockHeader, TxHash, TxReceipt, TxStatus, deserializeIndexedTxEffect, serializeIndexedTxEffect } from '@aztec/stdlib/tx';
14
+ import { BlockArchiveNotConsistentError, BlockIndexNotSequentialError, BlockNotFoundError, BlockNumberNotSequentialError, CannotOverwriteCheckpointedBlockError, CheckpointNotFoundError, CheckpointNumberNotConsistentError, CheckpointNumberNotSequentialError, InitialBlockNumberNotSequentialError, InitialCheckpointNumberNotSequentialError } from '../errors.js';
15
+ export { TxReceipt } from '@aztec/stdlib/tx';
16
+ /**
17
+ * LMDB-based block storage for the archiver.
18
+ */ export class BlockStore {
19
+ db;
20
+ l1Constants;
21
+ /** Map block number to block data */ #blocks;
22
+ /** Map checkpoint number to checkpoint data */ #checkpoints;
23
+ /** Map slot number to checkpoint number, for looking up checkpoints by slot range. */ #slotToCheckpoint;
24
+ /** Map block hash to list of tx hashes */ #blockTxs;
25
+ /** Tx hash to serialized IndexedTxEffect */ #txEffects;
26
+ /** Stores L1 block number in which the last processed L2 block was included */ #lastSynchedL1Block;
27
+ /** Stores last proven checkpoint */ #lastProvenCheckpoint;
28
+ /** Stores the pending chain validation status */ #pendingChainValidationStatus;
29
+ /** Index mapping a contract's address (as a string) to its location in a block */ #contractIndex;
30
+ /** Index mapping block hash to block number */ #blockHashIndex;
31
+ /** Index mapping block archive to block number */ #blockArchiveIndex;
32
+ #log;
33
+ constructor(db, l1Constants){
34
+ this.db = db;
35
+ this.l1Constants = l1Constants;
36
+ this.#log = createLogger('archiver:block_store');
37
+ this.#blocks = db.openMap('archiver_blocks');
38
+ this.#blockTxs = db.openMap('archiver_block_txs');
39
+ this.#txEffects = db.openMap('archiver_tx_effects');
40
+ this.#contractIndex = db.openMap('archiver_contract_index');
41
+ this.#blockHashIndex = db.openMap('archiver_block_hash_index');
42
+ this.#blockArchiveIndex = db.openMap('archiver_block_archive_index');
43
+ this.#lastSynchedL1Block = db.openSingleton('archiver_last_synched_l1_block');
44
+ this.#lastProvenCheckpoint = db.openSingleton('archiver_last_proven_l2_checkpoint');
45
+ this.#pendingChainValidationStatus = db.openSingleton('archiver_pending_chain_validation_status');
46
+ this.#checkpoints = db.openMap('archiver_checkpoints');
47
+ this.#slotToCheckpoint = db.openMap('archiver_slot_to_checkpoint');
48
+ }
49
+ /**
50
+ * Computes the finalized block number based on the proven block number.
51
+ * A block is considered finalized when it's 2 epochs behind the proven block.
52
+ * TODO(#13569): Compute proper finalized block number based on L1 finalized block.
53
+ * TODO(palla/mbps): Even the provisional computation is wrong, since it should subtract checkpoints, not blocks
54
+ * @returns The finalized block number.
55
+ */ async getFinalizedL2BlockNumber() {
56
+ const provenBlockNumber = await this.getProvenBlockNumber();
57
+ return BlockNumber(Math.max(provenBlockNumber - this.l1Constants.epochDuration * 2, 0));
58
+ }
59
+ /**
60
+ * Append new proposed blocks to the store's list. All blocks must be for the 'current' checkpoint.
61
+ * These are uncheckpointed blocks that have been proposed by the sequencer but not yet included in a checkpoint on L1.
62
+ * For checkpointed blocks (already published to L1), use addCheckpoints() instead.
63
+ * @param blocks - The proposed L2 blocks to be added to the store.
64
+ * @returns True if the operation is successful.
65
+ */ async addProposedBlocks(blocks, opts = {}) {
66
+ if (blocks.length === 0) {
67
+ return true;
68
+ }
69
+ return await this.db.transactionAsync(async ()=>{
70
+ // Check that the block immediately before the first block to be added is present in the store.
71
+ const firstBlockNumber = blocks[0].number;
72
+ const firstBlockCheckpointNumber = blocks[0].checkpointNumber;
73
+ const firstBlockIndex = blocks[0].indexWithinCheckpoint;
74
+ const firstBlockLastArchive = blocks[0].header.lastArchive.root;
75
+ // Extract the latest block and checkpoint numbers
76
+ const previousBlockNumber = await this.getLatestBlockNumber();
77
+ const previousCheckpointNumber = await this.getLatestCheckpointNumber();
78
+ // Verify we're not overwriting checkpointed blocks
79
+ const lastCheckpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
80
+ if (!opts.force && firstBlockNumber <= lastCheckpointedBlockNumber) {
81
+ throw new CannotOverwriteCheckpointedBlockError(firstBlockNumber, lastCheckpointedBlockNumber);
82
+ }
83
+ // Check that the first block number is the expected one
84
+ if (!opts.force && previousBlockNumber !== firstBlockNumber - 1) {
85
+ throw new InitialBlockNumberNotSequentialError(firstBlockNumber, previousBlockNumber);
86
+ }
87
+ // The same check as above but for checkpoints
88
+ if (!opts.force && previousCheckpointNumber !== firstBlockCheckpointNumber - 1) {
89
+ throw new InitialCheckpointNumberNotSequentialError(firstBlockCheckpointNumber, previousCheckpointNumber);
90
+ }
91
+ // Extract the previous block if there is one and see if it is for the same checkpoint or not
92
+ const previousBlockResult = await this.getBlock(previousBlockNumber);
93
+ let expectedFirstblockIndex = 0;
94
+ let previousBlockIndex = undefined;
95
+ if (previousBlockResult !== undefined) {
96
+ if (previousBlockResult.checkpointNumber === firstBlockCheckpointNumber) {
97
+ // The previous block is for the same checkpoint, therefore our index should follow it
98
+ previousBlockIndex = previousBlockResult.indexWithinCheckpoint;
99
+ expectedFirstblockIndex = previousBlockIndex + 1;
100
+ }
101
+ if (!previousBlockResult.archive.root.equals(firstBlockLastArchive)) {
102
+ throw new BlockArchiveNotConsistentError(firstBlockNumber, previousBlockResult.number, firstBlockLastArchive, previousBlockResult.archive.root);
103
+ }
104
+ }
105
+ // Now check that the first block has the expected index value
106
+ if (!opts.force && expectedFirstblockIndex !== firstBlockIndex) {
107
+ throw new BlockIndexNotSequentialError(firstBlockIndex, previousBlockIndex);
108
+ }
109
+ // Iterate over blocks array and insert them, checking that the block numbers and indexes are sequential. Also check they are for the correct checkpoint.
110
+ let previousBlock = undefined;
111
+ for (const block of blocks){
112
+ if (!opts.force && previousBlock) {
113
+ if (previousBlock.number + 1 !== block.number) {
114
+ throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
115
+ }
116
+ if (previousBlock.indexWithinCheckpoint + 1 !== block.indexWithinCheckpoint) {
117
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
118
+ }
119
+ if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
120
+ throw new BlockArchiveNotConsistentError(block.number, previousBlock.number, block.header.lastArchive.root, previousBlock.archive.root);
121
+ }
122
+ }
123
+ if (!opts.force && firstBlockCheckpointNumber !== block.checkpointNumber) {
124
+ throw new CheckpointNumberNotConsistentError(block.checkpointNumber, firstBlockCheckpointNumber);
125
+ }
126
+ previousBlock = block;
127
+ await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
128
+ }
129
+ return true;
130
+ });
131
+ }
132
+ /**
133
+ * Append new cheskpoints to the store's list.
134
+ * @param checkpoints - The L2 checkpoints to be added to the store.
135
+ * @returns True if the operation is successful.
136
+ */ async addCheckpoints(checkpoints, opts = {}) {
137
+ if (checkpoints.length === 0) {
138
+ return true;
139
+ }
140
+ return await this.db.transactionAsync(async ()=>{
141
+ // Check that the checkpoint immediately before the first block to be added is present in the store.
142
+ const firstCheckpointNumber = checkpoints[0].checkpoint.number;
143
+ const previousCheckpointNumber = await this.getLatestCheckpointNumber();
144
+ if (previousCheckpointNumber !== firstCheckpointNumber - 1 && !opts.force) {
145
+ throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
146
+ }
147
+ // Extract the previous checkpoint if there is one
148
+ let previousCheckpointData = undefined;
149
+ if (previousCheckpointNumber !== INITIAL_CHECKPOINT_NUMBER - 1) {
150
+ // There should be a previous checkpoint
151
+ previousCheckpointData = await this.getCheckpointData(previousCheckpointNumber);
152
+ if (previousCheckpointData === undefined) {
153
+ throw new CheckpointNotFoundError(previousCheckpointNumber);
154
+ }
155
+ }
156
+ let previousBlockNumber = undefined;
157
+ let previousBlock = undefined;
158
+ // If we have a previous checkpoint then we need to get the previous block number
159
+ if (previousCheckpointData !== undefined) {
160
+ previousBlockNumber = BlockNumber(previousCheckpointData.startBlock + previousCheckpointData.blockCount - 1);
161
+ previousBlock = await this.getBlock(previousBlockNumber);
162
+ if (previousBlock === undefined) {
163
+ // We should be able to get the required previous block
164
+ throw new BlockNotFoundError(previousBlockNumber);
165
+ }
166
+ }
167
+ // Iterate over checkpoints array and insert them, checking that the block numbers are sequential.
168
+ let previousCheckpoint = undefined;
169
+ for (const checkpoint of checkpoints){
170
+ if (!opts.force && previousCheckpoint && previousCheckpoint.checkpoint.number + 1 !== checkpoint.checkpoint.number) {
171
+ throw new CheckpointNumberNotSequentialError(checkpoint.checkpoint.number, previousCheckpoint.checkpoint.number);
172
+ }
173
+ previousCheckpoint = checkpoint;
174
+ // Store every block in the database. the block may already exist, but this has come from chain and is assumed to be correct.
175
+ for(let i = 0; i < checkpoint.checkpoint.blocks.length; i++){
176
+ const block = checkpoint.checkpoint.blocks[i];
177
+ if (previousBlock) {
178
+ // The blocks should have a sequential block number
179
+ if (previousBlock.number !== block.number - 1) {
180
+ throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
181
+ }
182
+ // If the blocks are for the same checkpoint then they should have sequential indexes
183
+ if (previousBlock.checkpointNumber === block.checkpointNumber && previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1) {
184
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
185
+ }
186
+ if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
187
+ throw new BlockArchiveNotConsistentError(block.number, previousBlock.number, block.header.lastArchive.root, previousBlock.archive.root);
188
+ }
189
+ } else {
190
+ // No previous block, must be block 1 at checkpoint index 0
191
+ if (block.indexWithinCheckpoint !== 0) {
192
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
193
+ }
194
+ if (block.number !== INITIAL_L2_BLOCK_NUM) {
195
+ throw new BlockNumberNotSequentialError(block.number, undefined);
196
+ }
197
+ }
198
+ previousBlock = block;
199
+ await this.addBlockToDatabase(block, checkpoint.checkpoint.number, i);
200
+ }
201
+ // Store the checkpoint in the database
202
+ await this.#checkpoints.set(checkpoint.checkpoint.number, {
203
+ header: checkpoint.checkpoint.header.toBuffer(),
204
+ archive: checkpoint.checkpoint.archive.toBuffer(),
205
+ checkpointOutHash: checkpoint.checkpoint.getCheckpointOutHash().toBuffer(),
206
+ l1: checkpoint.l1.toBuffer(),
207
+ attestations: checkpoint.attestations.map((attestation)=>attestation.toBuffer()),
208
+ checkpointNumber: checkpoint.checkpoint.number,
209
+ startBlock: checkpoint.checkpoint.blocks[0].number,
210
+ blockCount: checkpoint.checkpoint.blocks.length
211
+ });
212
+ // Update slot-to-checkpoint index
213
+ await this.#slotToCheckpoint.set(checkpoint.checkpoint.header.slotNumber, checkpoint.checkpoint.number);
214
+ }
215
+ await this.#lastSynchedL1Block.set(checkpoints[checkpoints.length - 1].l1.blockNumber);
216
+ return true;
217
+ });
218
+ }
219
+ async addBlockToDatabase(block, checkpointNumber, indexWithinCheckpoint) {
220
+ const blockHash = await block.hash();
221
+ await this.#blocks.set(block.number, {
222
+ header: block.header.toBuffer(),
223
+ blockHash: blockHash.toBuffer(),
224
+ archive: block.archive.toBuffer(),
225
+ checkpointNumber,
226
+ indexWithinCheckpoint
227
+ });
228
+ for(let i = 0; i < block.body.txEffects.length; i++){
229
+ const txEffect = {
230
+ data: block.body.txEffects[i],
231
+ l2BlockNumber: block.number,
232
+ l2BlockHash: blockHash,
233
+ txIndexInBlock: i
234
+ };
235
+ await this.#txEffects.set(txEffect.data.txHash.toString(), serializeIndexedTxEffect(txEffect));
236
+ }
237
+ await this.#blockTxs.set(blockHash.toString(), Buffer.concat(block.body.txEffects.map((tx)=>tx.txHash.toBuffer())));
238
+ // Update indices for block hash and archive
239
+ await this.#blockHashIndex.set(blockHash.toString(), block.number);
240
+ await this.#blockArchiveIndex.set(block.archive.root.toString(), block.number);
241
+ }
242
+ /** Deletes a block and all associated data (tx effects, indices). */ async deleteBlock(block) {
243
+ // Delete the block from the main blocks map
244
+ await this.#blocks.delete(block.number);
245
+ // Delete all tx effects for this block
246
+ await Promise.all(block.body.txEffects.map((tx)=>this.#txEffects.delete(tx.txHash.toString())));
247
+ // Delete block txs mapping
248
+ const blockHash = (await block.hash()).toString();
249
+ await this.#blockTxs.delete(blockHash);
250
+ // Clean up indices
251
+ await this.#blockHashIndex.delete(blockHash);
252
+ await this.#blockArchiveIndex.delete(block.archive.root.toString());
253
+ }
254
+ /**
255
+ * Removes all checkpoints with checkpoint number > checkpointNumber.
256
+ * Also removes ALL blocks (both checkpointed and uncheckpointed) after the last block of the given checkpoint.
257
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
258
+ */ async removeCheckpointsAfter(checkpointNumber) {
259
+ return await this.db.transactionAsync(async ()=>{
260
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
261
+ if (checkpointNumber >= latestCheckpointNumber) {
262
+ this.#log.warn(`No checkpoints to remove after ${checkpointNumber} (latest is ${latestCheckpointNumber})`);
263
+ return {
264
+ blocksRemoved: undefined
265
+ };
266
+ }
267
+ // If the proven checkpoint is beyond the target, update it
268
+ const proven = await this.getProvenCheckpointNumber();
269
+ if (proven > checkpointNumber) {
270
+ this.#log.warn(`Updating proven checkpoint ${proven} to last valid checkpoint ${checkpointNumber}`);
271
+ await this.setProvenCheckpointNumber(checkpointNumber);
272
+ }
273
+ // Find the last block number to keep (last block of the given checkpoint, or 0 if no checkpoint)
274
+ let lastBlockToKeep;
275
+ if (checkpointNumber <= 0) {
276
+ lastBlockToKeep = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
277
+ } else {
278
+ const targetCheckpoint = await this.#checkpoints.getAsync(checkpointNumber);
279
+ if (!targetCheckpoint) {
280
+ throw new Error(`Target checkpoint ${checkpointNumber} not found in store`);
281
+ }
282
+ lastBlockToKeep = BlockNumber(targetCheckpoint.startBlock + targetCheckpoint.blockCount - 1);
283
+ }
284
+ // Remove all blocks after lastBlockToKeep (both checkpointed and uncheckpointed)
285
+ const blocksRemoved = await this.removeBlocksAfter(lastBlockToKeep);
286
+ // Remove all checkpoints after the target
287
+ for(let c = latestCheckpointNumber; c > checkpointNumber; c = CheckpointNumber(c - 1)){
288
+ const checkpointStorage = await this.#checkpoints.getAsync(c);
289
+ if (checkpointStorage) {
290
+ const slotNumber = CheckpointHeader.fromBuffer(checkpointStorage.header).slotNumber;
291
+ await this.#slotToCheckpoint.delete(slotNumber);
292
+ }
293
+ await this.#checkpoints.delete(c);
294
+ this.#log.debug(`Removed checkpoint ${c}`);
295
+ }
296
+ return {
297
+ blocksRemoved
298
+ };
299
+ });
300
+ }
301
+ async getCheckpointData(checkpointNumber) {
302
+ const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
303
+ if (!checkpointStorage) {
304
+ return undefined;
305
+ }
306
+ return this.checkpointDataFromCheckpointStorage(checkpointStorage);
307
+ }
308
+ async getRangeOfCheckpoints(from, limit) {
309
+ const checkpoints = [];
310
+ for(let checkpointNumber = from; checkpointNumber < from + limit; checkpointNumber++){
311
+ const checkpoint = await this.#checkpoints.getAsync(checkpointNumber);
312
+ if (!checkpoint) {
313
+ break;
314
+ }
315
+ checkpoints.push(this.checkpointDataFromCheckpointStorage(checkpoint));
316
+ }
317
+ return checkpoints;
318
+ }
319
+ /** Returns checkpoint data for all checkpoints whose slot falls within the given range (inclusive). */ async getCheckpointDataForSlotRange(startSlot, endSlot) {
320
+ const result = [];
321
+ for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync({
322
+ start: startSlot,
323
+ end: endSlot + 1
324
+ })){
325
+ const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
326
+ if (checkpointStorage) {
327
+ result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage));
328
+ }
329
+ }
330
+ return result;
331
+ }
332
+ checkpointDataFromCheckpointStorage(checkpointStorage) {
333
+ return {
334
+ header: CheckpointHeader.fromBuffer(checkpointStorage.header),
335
+ archive: AppendOnlyTreeSnapshot.fromBuffer(checkpointStorage.archive),
336
+ checkpointOutHash: Fr.fromBuffer(checkpointStorage.checkpointOutHash),
337
+ checkpointNumber: CheckpointNumber(checkpointStorage.checkpointNumber),
338
+ startBlock: BlockNumber(checkpointStorage.startBlock),
339
+ blockCount: checkpointStorage.blockCount,
340
+ l1: L1PublishedData.fromBuffer(checkpointStorage.l1),
341
+ attestations: checkpointStorage.attestations.map((buf)=>CommitteeAttestation.fromBuffer(buf))
342
+ };
343
+ }
344
+ async getBlocksForCheckpoint(checkpointNumber) {
345
+ const checkpoint = await this.#checkpoints.getAsync(checkpointNumber);
346
+ if (!checkpoint) {
347
+ return undefined;
348
+ }
349
+ const blocksForCheckpoint = await toArray(this.#blocks.entriesAsync({
350
+ start: checkpoint.startBlock,
351
+ end: checkpoint.startBlock + checkpoint.blockCount
352
+ }));
353
+ const converted = await Promise.all(blocksForCheckpoint.map((x)=>this.getBlockFromBlockStorage(x[0], x[1])));
354
+ return converted.filter(isDefined);
355
+ }
356
+ /**
357
+ * Gets all blocks that have the given slot number.
358
+ * Iterates backwards through blocks for efficiency since we usually query for the last slot.
359
+ * @param slotNumber - The slot number to search for.
360
+ * @returns All blocks with the given slot number, in ascending block number order.
361
+ */ async getBlocksForSlot(slotNumber) {
362
+ const blocks = [];
363
+ // Iterate backwards through all blocks and filter by slot number
364
+ // This is more efficient since we usually query for the most recent slot
365
+ for await (const [blockNumber, blockStorage] of this.#blocks.entriesAsync({
366
+ reverse: true
367
+ })){
368
+ const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
369
+ const blockSlot = block?.header.globalVariables.slotNumber;
370
+ if (block && blockSlot === slotNumber) {
371
+ blocks.push(block);
372
+ } else if (blockSlot && blockSlot < slotNumber) {
373
+ break; // Blocks are stored in slot ascending order, so we can stop searching
374
+ }
375
+ }
376
+ // Reverse to return blocks in ascending order (block number order)
377
+ return blocks.reverse();
378
+ }
379
+ /**
380
+ * Removes all blocks with block number > blockNumber.
381
+ * Does not remove any associated checkpoints.
382
+ * @param blockNumber - The block number to remove after.
383
+ * @returns The removed blocks (for event emission).
384
+ */ async removeBlocksAfter(blockNumber) {
385
+ return await this.db.transactionAsync(async ()=>{
386
+ const removedBlocks = [];
387
+ // Get the latest block number to determine the range
388
+ const latestBlockNumber = await this.getLatestBlockNumber();
389
+ // Iterate from blockNumber + 1 to latestBlockNumber
390
+ for(let bn = blockNumber + 1; bn <= latestBlockNumber; bn++){
391
+ const block = await this.getBlock(BlockNumber(bn));
392
+ if (block === undefined) {
393
+ this.#log.warn(`Cannot remove block ${bn} from the store since we don't have it`);
394
+ continue;
395
+ }
396
+ removedBlocks.push(block);
397
+ await this.deleteBlock(block);
398
+ this.#log.debug(`Removed block ${bn} ${(await block.hash()).toString()}`);
399
+ }
400
+ return removedBlocks;
401
+ });
402
+ }
403
+ async getProvenBlockNumber() {
404
+ const provenCheckpointNumber = await this.getProvenCheckpointNumber();
405
+ if (provenCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
406
+ return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
407
+ }
408
+ const checkpointStorage = await this.#checkpoints.getAsync(provenCheckpointNumber);
409
+ if (!checkpointStorage) {
410
+ throw new CheckpointNotFoundError(provenCheckpointNumber);
411
+ } else {
412
+ return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
413
+ }
414
+ }
415
+ async getLatestBlockNumber() {
416
+ const [latestBlocknumber] = await toArray(this.#blocks.keysAsync({
417
+ reverse: true,
418
+ limit: 1
419
+ }));
420
+ return typeof latestBlocknumber === 'number' ? BlockNumber(latestBlocknumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
421
+ }
422
+ async getLatestCheckpointNumber() {
423
+ const [latestCheckpointNumber] = await toArray(this.#checkpoints.keysAsync({
424
+ reverse: true,
425
+ limit: 1
426
+ }));
427
+ if (latestCheckpointNumber === undefined) {
428
+ return CheckpointNumber(INITIAL_CHECKPOINT_NUMBER - 1);
429
+ }
430
+ return CheckpointNumber(latestCheckpointNumber);
431
+ }
432
+ async getCheckpointedBlock(number) {
433
+ const blockStorage = await this.#blocks.getAsync(number);
434
+ if (!blockStorage) {
435
+ return undefined;
436
+ }
437
+ const checkpoint = await this.#checkpoints.getAsync(blockStorage.checkpointNumber);
438
+ if (!checkpoint) {
439
+ return undefined;
440
+ }
441
+ const block = await this.getBlockFromBlockStorage(number, blockStorage);
442
+ if (!block) {
443
+ return undefined;
444
+ }
445
+ return new CheckpointedL2Block(CheckpointNumber(checkpoint.checkpointNumber), block, L1PublishedData.fromBuffer(checkpoint.l1), checkpoint.attestations.map((buf)=>CommitteeAttestation.fromBuffer(buf)));
446
+ }
447
+ /**
448
+ * Gets up to `limit` amount of Checkpointed L2 blocks starting from `from`.
449
+ * @param start - Number of the first block to return (inclusive).
450
+ * @param limit - The number of blocks to return.
451
+ * @returns The requested L2 blocks
452
+ */ async *getCheckpointedBlocks(start, limit) {
453
+ const checkpointCache = new Map();
454
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)){
455
+ const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
456
+ if (block) {
457
+ const checkpoint = checkpointCache.get(CheckpointNumber(blockStorage.checkpointNumber)) ?? await this.#checkpoints.getAsync(blockStorage.checkpointNumber);
458
+ if (checkpoint) {
459
+ checkpointCache.set(CheckpointNumber(blockStorage.checkpointNumber), checkpoint);
460
+ const checkpointedBlock = new CheckpointedL2Block(CheckpointNumber(checkpoint.checkpointNumber), block, L1PublishedData.fromBuffer(checkpoint.l1), checkpoint.attestations.map((buf)=>CommitteeAttestation.fromBuffer(buf)));
461
+ yield checkpointedBlock;
462
+ }
463
+ }
464
+ }
465
+ }
466
+ async getCheckpointedBlockByHash(blockHash) {
467
+ const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
468
+ if (blockNumber === undefined) {
469
+ return undefined;
470
+ }
471
+ return this.getCheckpointedBlock(BlockNumber(blockNumber));
472
+ }
473
+ async getCheckpointedBlockByArchive(archive) {
474
+ const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
475
+ if (blockNumber === undefined) {
476
+ return undefined;
477
+ }
478
+ return this.getCheckpointedBlock(BlockNumber(blockNumber));
479
+ }
480
+ /**
481
+ * Gets up to `limit` amount of L2 blocks starting from `from`.
482
+ * @param start - Number of the first block to return (inclusive).
483
+ * @param limit - The number of blocks to return.
484
+ * @returns The requested L2 blocks
485
+ */ async *getBlocks(start, limit) {
486
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)){
487
+ const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
488
+ if (block) {
489
+ yield block;
490
+ }
491
+ }
492
+ }
493
+ /**
494
+ * Gets block metadata (without tx data) by block number.
495
+ * @param blockNumber - The number of the block to return.
496
+ * @returns The requested block data.
497
+ */ async getBlockData(blockNumber) {
498
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
499
+ if (!blockStorage || !blockStorage.header) {
500
+ return undefined;
501
+ }
502
+ return this.getBlockDataFromBlockStorage(blockStorage);
503
+ }
504
+ /**
505
+ * Gets block metadata (without tx data) by archive root.
506
+ * @param archive - The archive root of the block to return.
507
+ * @returns The requested block data.
508
+ */ async getBlockDataByArchive(archive) {
509
+ const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
510
+ if (blockNumber === undefined) {
511
+ return undefined;
512
+ }
513
+ return this.getBlockData(BlockNumber(blockNumber));
514
+ }
515
+ /**
516
+ * Gets an L2 block.
517
+ * @param blockNumber - The number of the block to return.
518
+ * @returns The requested L2 block.
519
+ */ async getBlock(blockNumber) {
520
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
521
+ if (!blockStorage || !blockStorage.header) {
522
+ return Promise.resolve(undefined);
523
+ }
524
+ return this.getBlockFromBlockStorage(blockNumber, blockStorage);
525
+ }
526
+ /**
527
+ * Gets an L2 block by its hash.
528
+ * @param blockHash - The hash of the block to return.
529
+ * @returns The requested L2 block.
530
+ */ async getBlockByHash(blockHash) {
531
+ const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
532
+ if (blockNumber === undefined) {
533
+ return undefined;
534
+ }
535
+ return this.getBlock(BlockNumber(blockNumber));
536
+ }
537
+ /**
538
+ * Gets an L2 block by its archive root.
539
+ * @param archive - The archive root of the block to return.
540
+ * @returns The requested L2 block.
541
+ */ async getBlockByArchive(archive) {
542
+ const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
543
+ if (blockNumber === undefined) {
544
+ return undefined;
545
+ }
546
+ return this.getBlock(BlockNumber(blockNumber));
547
+ }
548
+ /**
549
+ * Gets a block header by its hash.
550
+ * @param blockHash - The hash of the block to return.
551
+ * @returns The requested block header.
552
+ */ async getBlockHeaderByHash(blockHash) {
553
+ const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
554
+ if (blockNumber === undefined) {
555
+ return undefined;
556
+ }
557
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
558
+ if (!blockStorage || !blockStorage.header) {
559
+ return undefined;
560
+ }
561
+ return BlockHeader.fromBuffer(blockStorage.header);
562
+ }
563
+ /**
564
+ * Gets a block header by its archive root.
565
+ * @param archive - The archive root of the block to return.
566
+ * @returns The requested block header.
567
+ */ async getBlockHeaderByArchive(archive) {
568
+ const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
569
+ if (blockNumber === undefined) {
570
+ return undefined;
571
+ }
572
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
573
+ if (!blockStorage || !blockStorage.header) {
574
+ return undefined;
575
+ }
576
+ return BlockHeader.fromBuffer(blockStorage.header);
577
+ }
578
+ /**
579
+ * Gets the headers for a sequence of L2 blocks.
580
+ * @param start - Number of the first block to return (inclusive).
581
+ * @param limit - The number of blocks to return.
582
+ * @returns The requested L2 block headers
583
+ */ async *getBlockHeaders(start, limit) {
584
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)){
585
+ const header = BlockHeader.fromBuffer(blockStorage.header);
586
+ if (header.getBlockNumber() !== blockNumber) {
587
+ throw new Error(`Block number mismatch when retrieving block header from archive (expected ${blockNumber} but got ${header.getBlockNumber()})`);
588
+ }
589
+ yield header;
590
+ }
591
+ }
592
+ async *getBlockStorages(start, limit) {
593
+ let expectedBlockNumber = start;
594
+ for await (const [blockNumber, blockStorage] of this.#blocks.entriesAsync(this.#computeBlockRange(start, limit))){
595
+ if (blockNumber !== expectedBlockNumber) {
596
+ throw new Error(`Block number mismatch when iterating blocks from archive (expected ${expectedBlockNumber} but got ${blockNumber})`);
597
+ }
598
+ expectedBlockNumber++;
599
+ yield [
600
+ blockNumber,
601
+ blockStorage
602
+ ];
603
+ }
604
+ }
605
+ getBlockDataFromBlockStorage(blockStorage) {
606
+ return {
607
+ header: BlockHeader.fromBuffer(blockStorage.header),
608
+ archive: AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),
609
+ blockHash: Fr.fromBuffer(blockStorage.blockHash),
610
+ checkpointNumber: CheckpointNumber(blockStorage.checkpointNumber),
611
+ indexWithinCheckpoint: IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint)
612
+ };
613
+ }
614
+ async getBlockFromBlockStorage(blockNumber, blockStorage) {
615
+ const { header, archive, blockHash, checkpointNumber, indexWithinCheckpoint } = this.getBlockDataFromBlockStorage(blockStorage);
616
+ header.setHash(blockHash);
617
+ const blockHashString = bufferToHex(blockStorage.blockHash);
618
+ const blockTxsBuffer = await this.#blockTxs.getAsync(blockHashString);
619
+ if (blockTxsBuffer === undefined) {
620
+ this.#log.warn(`Could not find body for block ${header.globalVariables.blockNumber} ${blockHash}`);
621
+ return undefined;
622
+ }
623
+ const txEffects = [];
624
+ const reader = BufferReader.asReader(blockTxsBuffer);
625
+ while(!reader.isEmpty()){
626
+ const txHash = reader.readObject(TxHash);
627
+ const txEffect = await this.#txEffects.getAsync(txHash.toString());
628
+ if (txEffect === undefined) {
629
+ this.#log.warn(`Could not find tx effect for tx ${txHash} in block ${blockNumber}`);
630
+ return undefined;
631
+ }
632
+ txEffects.push(deserializeIndexedTxEffect(txEffect).data);
633
+ }
634
+ const body = new Body(txEffects);
635
+ const block = new L2Block(archive, header, body, checkpointNumber, indexWithinCheckpoint);
636
+ if (block.number !== blockNumber) {
637
+ throw new Error(`Block number mismatch when retrieving block from archive (expected ${blockNumber} but got ${block.number} with hash ${blockHashString})`);
638
+ }
639
+ return block;
640
+ }
641
+ /**
642
+ * Gets a tx effect.
643
+ * @param txHash - The hash of the tx corresponding to the tx effect.
644
+ * @returns The requested tx effect with block info (or undefined if not found).
645
+ */ async getTxEffect(txHash) {
646
+ const buffer = await this.#txEffects.getAsync(txHash.toString());
647
+ if (!buffer) {
648
+ return undefined;
649
+ }
650
+ return deserializeIndexedTxEffect(buffer);
651
+ }
652
+ /**
653
+ * Gets a receipt of a settled tx.
654
+ * @param txHash - The hash of a tx we try to get the receipt for.
655
+ * @returns The requested tx receipt (or undefined if not found).
656
+ */ async getSettledTxReceipt(txHash) {
657
+ const txEffect = await this.getTxEffect(txHash);
658
+ if (!txEffect) {
659
+ return undefined;
660
+ }
661
+ const blockNumber = BlockNumber(txEffect.l2BlockNumber);
662
+ // Use existing archiver methods to determine finalization level
663
+ const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber] = await Promise.all([
664
+ this.getProvenBlockNumber(),
665
+ this.getCheckpointedL2BlockNumber(),
666
+ this.getFinalizedL2BlockNumber()
667
+ ]);
668
+ let status;
669
+ if (blockNumber <= finalizedBlockNumber) {
670
+ status = TxStatus.FINALIZED;
671
+ } else if (blockNumber <= provenBlockNumber) {
672
+ status = TxStatus.PROVEN;
673
+ } else if (blockNumber <= checkpointedBlockNumber) {
674
+ status = TxStatus.CHECKPOINTED;
675
+ } else {
676
+ status = TxStatus.PROPOSED;
677
+ }
678
+ return new TxReceipt(txHash, status, TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode), undefined, txEffect.data.transactionFee.toBigInt(), txEffect.l2BlockHash, blockNumber);
679
+ }
680
+ /**
681
+ * Looks up which block included the requested tx effect.
682
+ * @param txHash - The txHash of the tx.
683
+ * @returns The block number and index of the tx.
684
+ */ async getTxLocation(txHash) {
685
+ const txEffect = await this.#txEffects.getAsync(txHash.toString());
686
+ if (!txEffect) {
687
+ return undefined;
688
+ }
689
+ const { l2BlockNumber, txIndexInBlock } = deserializeIndexedTxEffect(txEffect);
690
+ return [
691
+ l2BlockNumber,
692
+ txIndexInBlock
693
+ ];
694
+ }
695
+ /**
696
+ * Looks up which block deployed a particular contract.
697
+ * @param contractAddress - The address of the contract to look up.
698
+ * @returns The block number and index of the contract.
699
+ */ getContractLocation(contractAddress) {
700
+ return this.#contractIndex.getAsync(contractAddress.toString());
701
+ }
702
+ /**
703
+ * Gets the number of the latest L2 block checkpointed.
704
+ * @returns The number of the latest L2 block checkpointed.
705
+ */ async getCheckpointedL2BlockNumber() {
706
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
707
+ const checkpoint = await this.getCheckpointData(latestCheckpointNumber);
708
+ if (!checkpoint) {
709
+ return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
710
+ }
711
+ return BlockNumber(checkpoint.startBlock + checkpoint.blockCount - 1);
712
+ }
713
+ async getLatestL2BlockNumber() {
714
+ const [lastBlockNumber] = await toArray(this.#blocks.keysAsync({
715
+ reverse: true,
716
+ limit: 1
717
+ }));
718
+ return typeof lastBlockNumber === 'number' ? BlockNumber(lastBlockNumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
719
+ }
720
+ /**
721
+ * Gets the most recent L1 block processed.
722
+ * @returns The L1 block that published the latest L2 block
723
+ */ getSynchedL1BlockNumber() {
724
+ return this.#lastSynchedL1Block.getAsync();
725
+ }
726
+ setSynchedL1BlockNumber(l1BlockNumber) {
727
+ return this.#lastSynchedL1Block.set(l1BlockNumber);
728
+ }
729
+ async getProvenCheckpointNumber() {
730
+ const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
731
+ this.getLatestCheckpointNumber(),
732
+ this.#lastProvenCheckpoint.getAsync()
733
+ ]);
734
+ return (provenCheckpointNumber ?? 0) > latestCheckpointNumber ? latestCheckpointNumber : CheckpointNumber(provenCheckpointNumber ?? 0);
735
+ }
736
+ async setProvenCheckpointNumber(checkpointNumber) {
737
+ const result = await this.#lastProvenCheckpoint.set(checkpointNumber);
738
+ return result;
739
+ }
740
+ #computeBlockRange(start, limit) {
741
+ if (limit < 1) {
742
+ throw new Error(`Invalid limit: ${limit}`);
743
+ }
744
+ if (start < INITIAL_L2_BLOCK_NUM) {
745
+ throw new Error(`Invalid start: ${start}`);
746
+ }
747
+ return {
748
+ start,
749
+ limit
750
+ };
751
+ }
752
+ /**
753
+ * Gets the pending chain validation status.
754
+ * @returns The validation status or undefined if not set.
755
+ */ async getPendingChainValidationStatus() {
756
+ const buffer = await this.#pendingChainValidationStatus.getAsync();
757
+ if (!buffer) {
758
+ return undefined;
759
+ }
760
+ return deserializeValidateCheckpointResult(buffer);
761
+ }
762
+ /**
763
+ * Sets the pending chain validation status.
764
+ * @param status - The validation status to store.
765
+ */ async setPendingChainValidationStatus(status) {
766
+ if (status) {
767
+ const buffer = serializeValidateCheckpointResult(status);
768
+ await this.#pendingChainValidationStatus.set(buffer);
769
+ } else {
770
+ await this.#pendingChainValidationStatus.delete();
771
+ }
772
+ }
773
+ }