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

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