@aztec/archiver 0.0.1-commit.a89ec08 → 0.0.1-commit.aa0c64f

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 (121) hide show
  1. package/README.md +19 -11
  2. package/dest/archiver.d.ts +71 -16
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +276 -71
  5. package/dest/config.d.ts +7 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +43 -14
  8. package/dest/errors.d.ts +50 -2
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +74 -2
  11. package/dest/factory.d.ts +19 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +67 -24
  14. package/dest/index.d.ts +11 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +10 -2
  17. package/dest/l1/calldata_retriever.d.ts +9 -1
  18. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  19. package/dest/l1/calldata_retriever.js +22 -11
  20. package/dest/l1/data_retrieval.d.ts +30 -13
  21. package/dest/l1/data_retrieval.d.ts.map +1 -1
  22. package/dest/l1/data_retrieval.js +36 -37
  23. package/dest/l1/trace_tx.d.ts +12 -66
  24. package/dest/l1/trace_tx.d.ts.map +1 -1
  25. package/dest/l1/validate_historical_logs.d.ts +23 -0
  26. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  27. package/dest/l1/validate_historical_logs.js +108 -0
  28. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  29. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  30. package/dest/modules/contract_data_source_adapter.js +32 -0
  31. package/dest/modules/data_source_base.d.ts +71 -48
  32. package/dest/modules/data_source_base.d.ts.map +1 -1
  33. package/dest/modules/data_source_base.js +250 -144
  34. package/dest/modules/data_store_updater.d.ts +30 -13
  35. package/dest/modules/data_store_updater.d.ts.map +1 -1
  36. package/dest/modules/data_store_updater.js +129 -111
  37. package/dest/modules/instrumentation.d.ts +26 -2
  38. package/dest/modules/instrumentation.d.ts.map +1 -1
  39. package/dest/modules/instrumentation.js +58 -9
  40. package/dest/modules/l1_synchronizer.d.ts +13 -8
  41. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  42. package/dest/modules/l1_synchronizer.js +463 -224
  43. package/dest/modules/outbox_trees_resolver.d.ts +62 -0
  44. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  45. package/dest/modules/outbox_trees_resolver.js +162 -0
  46. package/dest/modules/validation.d.ts +30 -7
  47. package/dest/modules/validation.d.ts.map +1 -1
  48. package/dest/modules/validation.js +35 -17
  49. package/dest/store/block_store.d.ts +175 -68
  50. package/dest/store/block_store.d.ts.map +1 -1
  51. package/dest/store/block_store.js +627 -239
  52. package/dest/store/contract_class_store.d.ts +17 -4
  53. package/dest/store/contract_class_store.d.ts.map +1 -1
  54. package/dest/store/contract_class_store.js +37 -67
  55. package/dest/store/contract_instance_store.d.ts +28 -1
  56. package/dest/store/contract_instance_store.d.ts.map +1 -1
  57. package/dest/store/contract_instance_store.js +49 -1
  58. package/dest/store/data_stores.d.ts +68 -0
  59. package/dest/store/data_stores.d.ts.map +1 -0
  60. package/dest/store/data_stores.js +54 -0
  61. package/dest/store/function_names_cache.d.ts +17 -0
  62. package/dest/store/function_names_cache.d.ts.map +1 -0
  63. package/dest/store/function_names_cache.js +30 -0
  64. package/dest/store/l2_tips_cache.d.ts +13 -7
  65. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  66. package/dest/store/l2_tips_cache.js +13 -76
  67. package/dest/store/log_store.d.ts +42 -37
  68. package/dest/store/log_store.d.ts.map +1 -1
  69. package/dest/store/log_store.js +259 -443
  70. package/dest/store/log_store_codec.d.ts +78 -0
  71. package/dest/store/log_store_codec.d.ts.map +1 -0
  72. package/dest/store/log_store_codec.js +110 -0
  73. package/dest/store/message_store.d.ts +11 -1
  74. package/dest/store/message_store.d.ts.map +1 -1
  75. package/dest/store/message_store.js +50 -8
  76. package/dest/test/fake_l1_state.d.ts +8 -3
  77. package/dest/test/fake_l1_state.d.ts.map +1 -1
  78. package/dest/test/fake_l1_state.js +78 -21
  79. package/dest/test/mock_l2_block_source.d.ts +48 -50
  80. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  81. package/dest/test/mock_l2_block_source.js +228 -179
  82. package/dest/test/mock_structs.d.ts +1 -1
  83. package/dest/test/mock_structs.d.ts.map +1 -1
  84. package/dest/test/mock_structs.js +2 -2
  85. package/dest/test/noop_l1_archiver.d.ts +14 -6
  86. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  87. package/dest/test/noop_l1_archiver.js +26 -10
  88. package/package.json +15 -14
  89. package/src/archiver.ts +361 -77
  90. package/src/config.ts +51 -13
  91. package/src/errors.ts +117 -2
  92. package/src/factory.ts +81 -22
  93. package/src/index.ts +18 -2
  94. package/src/l1/calldata_retriever.ts +29 -11
  95. package/src/l1/data_retrieval.ts +60 -54
  96. package/src/l1/validate_historical_logs.ts +140 -0
  97. package/src/modules/contract_data_source_adapter.ts +46 -0
  98. package/src/modules/data_source_base.ts +325 -187
  99. package/src/modules/data_store_updater.ts +155 -139
  100. package/src/modules/instrumentation.ts +63 -10
  101. package/src/modules/l1_synchronizer.ts +630 -273
  102. package/src/modules/outbox_trees_resolver.ts +199 -0
  103. package/src/modules/validation.ts +80 -23
  104. package/src/store/block_store.ts +766 -290
  105. package/src/store/contract_class_store.ts +43 -101
  106. package/src/store/contract_instance_store.ts +61 -1
  107. package/src/store/data_stores.ts +104 -0
  108. package/src/store/function_names_cache.ts +37 -0
  109. package/src/store/l2_tips_cache.ts +16 -70
  110. package/src/store/log_store.ts +298 -609
  111. package/src/store/log_store_codec.ts +143 -0
  112. package/src/store/message_store.ts +59 -9
  113. package/src/structs/inbox_message.ts +1 -1
  114. package/src/test/fake_l1_state.ts +99 -32
  115. package/src/test/mock_l2_block_source.ts +285 -232
  116. package/src/test/mock_structs.ts +5 -2
  117. package/src/test/noop_l1_archiver.ts +54 -11
  118. package/dest/store/kv_archiver_store.d.ts +0 -362
  119. package/dest/store/kv_archiver_store.d.ts.map +0 -1
  120. package/dest/store/kv_archiver_store.js +0 -475
  121. package/src/store/kv_archiver_store.ts +0 -685
@@ -12,15 +12,24 @@ import {
12
12
  type BlockData,
13
13
  BlockHash,
14
14
  Body,
15
- CheckpointedL2Block,
16
15
  CommitteeAttestation,
16
+ GENESIS_CHECKPOINT_HEADER_HASH,
17
17
  L2Block,
18
+ type L2TipId,
19
+ type L2Tips,
18
20
  type ValidateCheckpointResult,
19
21
  deserializeValidateCheckpointResult,
20
22
  serializeValidateCheckpointResult,
21
23
  } from '@aztec/stdlib/block';
22
- import { type CheckpointData, L1PublishedData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
23
- import { type L1RollupConstants, getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
24
+ import {
25
+ Checkpoint,
26
+ type CheckpointData,
27
+ type CommonCheckpointData,
28
+ L1PublishedData,
29
+ type ProposedCheckpointData,
30
+ type ProposedCheckpointInput,
31
+ PublishedCheckpoint,
32
+ } from '@aztec/stdlib/checkpoint';
24
33
  import { CheckpointHeader } from '@aztec/stdlib/rollup';
25
34
  import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
26
35
  import {
@@ -28,8 +37,6 @@ import {
28
37
  type IndexedTxEffect,
29
38
  TxEffect,
30
39
  TxHash,
31
- TxReceipt,
32
- TxStatus,
33
40
  deserializeIndexedTxEffect,
34
41
  serializeIndexedTxEffect,
35
42
  } from '@aztec/stdlib/tx';
@@ -37,6 +44,7 @@ import {
37
44
  import {
38
45
  BlockAlreadyCheckpointedError,
39
46
  BlockArchiveNotConsistentError,
47
+ BlockCheckpointNumberNotSequentialError,
40
48
  BlockIndexNotSequentialError,
41
49
  BlockNotFoundError,
42
50
  BlockNumberNotSequentialError,
@@ -44,9 +52,13 @@ import {
44
52
  CheckpointNotFoundError,
45
53
  CheckpointNumberNotSequentialError,
46
54
  InitialCheckpointNumberNotSequentialError,
55
+ NoProposedCheckpointToPromoteError,
56
+ ProposedCheckpointArchiveRootMismatchError,
57
+ ProposedCheckpointNotSequentialError,
58
+ ProposedCheckpointPromotionNotSequentialError,
47
59
  } from '../errors.js';
48
60
 
49
- export { TxReceipt, type TxEffect, type TxHash } from '@aztec/stdlib/tx';
61
+ export type { TxEffect, TxHash, TxReceipt } from '@aztec/stdlib/tx';
50
62
 
51
63
  type BlockIndexValue = [blockNumber: number, index: number];
52
64
 
@@ -58,19 +70,78 @@ type BlockStorage = {
58
70
  indexWithinCheckpoint: number;
59
71
  };
60
72
 
61
- type CheckpointStorage = {
73
+ /** Reason a checkpoint was rejected during sync. */
74
+ export type RejectedCheckpointReason = 'invalid-attestations' | 'descends-from-invalid-attestations';
75
+
76
+ /**
77
+ * A checkpoint observed on L1 that the archiver decided not to ingest, recorded so that
78
+ * any descendant that builds on top of it can also be skipped (rather than throwing
79
+ * `InitialCheckpointNumberNotSequentialError` and looping). An entry is dropped via
80
+ * {@link BlockStore.removeRejectedCheckpointByArchiveRoot} once a checkpoint with the same
81
+ * archive root is later ingested as valid (e.g. it gathered enough attestations), which
82
+ * re-enables its descendants.
83
+ */
84
+ export type RejectedCheckpoint = {
85
+ /** Checkpoint number this entry represents. */
86
+ checkpointNumber: CheckpointNumber;
87
+ /** Archive root produced by this rejected checkpoint (matched against descendants' `lastArchiveRoot`). */
88
+ archiveRoot: Fr;
89
+ /** `lastArchiveRoot` from this checkpoint's header (the ancestor it built on). */
90
+ parentArchiveRoot: Fr;
91
+ /** Slot number of the rejected checkpoint. */
92
+ slotNumber: SlotNumber;
93
+ /** L1 publication data for the rejected checkpoint (block number, hash, timestamp). */
94
+ l1: L1PublishedData;
95
+ /** Why the entry was recorded. */
96
+ reason: RejectedCheckpointReason;
97
+ };
98
+
99
+ type RejectedCheckpointStorage = {
100
+ checkpointNumber: number;
101
+ archiveRoot: Buffer;
102
+ parentArchiveRoot: Buffer;
103
+ slotNumber: number;
104
+ l1: Buffer;
105
+ reason: RejectedCheckpointReason;
106
+ };
107
+
108
+ /** Checkpoint Storage shared between Checkpoints + Proposed Checkpoints */
109
+ type CommonCheckpointStorage = {
62
110
  header: Buffer;
63
111
  archive: Buffer;
64
112
  checkpointOutHash: Buffer;
65
113
  checkpointNumber: number;
66
114
  startBlock: number;
67
115
  blockCount: number;
116
+ };
117
+
118
+ type CheckpointStorage = CommonCheckpointStorage & {
68
119
  l1: Buffer;
69
120
  attestations: Buffer[];
121
+ feeAssetPriceModifier: string;
122
+ };
123
+
124
+ /** Storage format for a proposed checkpoint (attested but not yet L1-confirmed). */
125
+ type ProposedCheckpointStorage = CommonCheckpointStorage & {
126
+ totalManaUsed: string;
127
+ feeAssetPriceModifier: string;
70
128
  };
71
129
 
72
130
  export type RemoveCheckpointsResult = { blocksRemoved: L2Block[] | undefined };
73
131
 
132
+ /**
133
+ * Single-block lookup with the chain-tip `tag` variant of {@link BlockQuery} already resolved
134
+ * to a concrete block number. The `tag` branch is unrepresentable here so storage code does
135
+ * not need to handle it at runtime.
136
+ */
137
+ export type ResolvedBlockQuery = { number: BlockNumber } | { hash: BlockHash } | { archive: Fr };
138
+
139
+ /**
140
+ * Range lookup with the `epoch` variant of {@link BlocksQuery} already resolved to a
141
+ * `{ from, limit }` pair. Storage code never needs to map epoch numbers to block ranges.
142
+ */
143
+ export type ResolvedBlocksQuery = { from: BlockNumber; limit: number; onlyCheckpointed?: boolean };
144
+
74
145
  /**
75
146
  * LMDB-based block storage for the archiver.
76
147
  */
@@ -78,7 +149,10 @@ export class BlockStore {
78
149
  /** Map block number to block data */
79
150
  #blocks: AztecAsyncMap<number, BlockStorage>;
80
151
 
81
- /** Map checkpoint number to checkpoint data */
152
+ /** Map keyed by checkpoint number holding proposed (locally-validated, not yet L1-confirmed) checkpoints. */
153
+ #proposedCheckpoints: AztecAsyncMap<number, ProposedCheckpointStorage>;
154
+
155
+ /** Map checkpoint number to checkpoint data for mined checkpoints only */
82
156
  #checkpoints: AztecAsyncMap<number, CheckpointStorage>;
83
157
 
84
158
  /** Map slot number to checkpoint number, for looking up checkpoints by slot range. */
@@ -111,6 +185,12 @@ export class BlockStore {
111
185
  /** Index mapping block archive to block number */
112
186
  #blockArchiveIndex: AztecAsyncMap<string, number>;
113
187
 
188
+ /** Map rejected checkpoints (due to invalid attestations) by archive root */
189
+ #rejectedCheckpoints: AztecAsyncMap<string, RejectedCheckpointStorage>;
190
+
191
+ /** Index mapping a rejected checkpoint's number to its archive root, so the latest can be read in reverse order */
192
+ #rejectedCheckpointsByNumber: AztecAsyncMap<number, string>;
193
+
114
194
  #log = createLogger('archiver:block_store');
115
195
 
116
196
  constructor(private db: AztecAsyncKVStore) {
@@ -126,6 +206,9 @@ export class BlockStore {
126
206
  this.#pendingChainValidationStatus = db.openSingleton('archiver_pending_chain_validation_status');
127
207
  this.#checkpoints = db.openMap('archiver_checkpoints');
128
208
  this.#slotToCheckpoint = db.openMap('archiver_slot_to_checkpoint');
209
+ this.#proposedCheckpoints = db.openMap('archiver_proposed_checkpoints');
210
+ this.#rejectedCheckpoints = db.openMap('archiver_rejected_checkpoints');
211
+ this.#rejectedCheckpointsByNumber = db.openMap('archiver_rejected_checkpoints_by_number');
129
212
  }
130
213
 
131
214
  /**
@@ -160,14 +243,14 @@ export class BlockStore {
160
243
  const blockLastArchive = block.header.lastArchive.root;
161
244
 
162
245
  // Extract the latest block and checkpoint numbers
163
- const previousBlockNumber = await this.getLatestBlockNumber();
164
- const previousCheckpointNumber = await this.getLatestCheckpointNumber();
246
+ const previousBlockNumber = await this.getLatestL2BlockNumber();
247
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
165
248
 
166
249
  // Verify we're not overwriting checkpointed blocks
167
250
  const lastCheckpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
168
251
  if (!opts.force && blockNumber <= lastCheckpointedBlockNumber) {
169
252
  // Check if the proposed block matches the already-checkpointed one
170
- const existingBlock = await this.getBlock(BlockNumber(blockNumber));
253
+ const existingBlock = await this.getBlockData({ number: BlockNumber(blockNumber) });
171
254
  if (existingBlock && existingBlock.archive.root.equals(block.archive.root)) {
172
255
  throw new BlockAlreadyCheckpointedError(blockNumber);
173
256
  }
@@ -179,13 +262,18 @@ export class BlockStore {
179
262
  throw new BlockNumberNotSequentialError(blockNumber, previousBlockNumber);
180
263
  }
181
264
 
182
- // The same check as above but for checkpoints
183
- if (!opts.force && previousCheckpointNumber !== blockCheckpointNumber - 1) {
184
- throw new CheckpointNumberNotSequentialError(blockCheckpointNumber, previousCheckpointNumber);
265
+ // Accept the block if either the confirmed checkpoint or a pending checkpoint matches
266
+ // the expected predecessor. We look for a pending entry at exactly blockCheckpointNumber - 1.
267
+ const expectedCheckpointNumber = blockCheckpointNumber - 1;
268
+ const hasPendingAtExpected = await this.#proposedCheckpoints.hasAsync(expectedCheckpointNumber);
269
+ if (!opts.force && latestCheckpointNumber !== expectedCheckpointNumber && !hasPendingAtExpected) {
270
+ const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
271
+ const previous = CheckpointNumber(Math.max(latestCheckpointNumber, latestPendingKey ?? 0));
272
+ throw new BlockCheckpointNumberNotSequentialError(BlockNumber(blockNumber), blockCheckpointNumber, previous);
185
273
  }
186
274
 
187
275
  // Extract the previous block if there is one and see if it is for the same checkpoint or not
188
- const previousBlockResult = await this.getBlock(previousBlockNumber);
276
+ const previousBlockResult = await this.getBlockData({ number: previousBlockNumber });
189
277
 
190
278
  let expectedBlockIndex = 0;
191
279
  let previousBlockIndex: number | undefined = undefined;
@@ -198,7 +286,7 @@ export class BlockStore {
198
286
  if (!previousBlockResult.archive.root.equals(blockLastArchive)) {
199
287
  throw new BlockArchiveNotConsistentError(
200
288
  blockNumber,
201
- previousBlockResult.number,
289
+ previousBlockResult.header.globalVariables.blockNumber,
202
290
  blockLastArchive,
203
291
  previousBlockResult.archive.root,
204
292
  );
@@ -217,13 +305,19 @@ export class BlockStore {
217
305
  }
218
306
 
219
307
  /**
220
- * Append new cheskpoints to the store's list.
308
+ * Append new checkpoints to the store's list.
309
+ * Checkpoints at the start of the batch that are already stored (e.g. re-included by an L1 reorg)
310
+ * are accepted if their archive root matches: their L1 metadata is updated but they are not
311
+ * re-inserted, and they are excluded from the returned array.
221
312
  * @param checkpoints - The L2 checkpoints to be added to the store.
222
- * @returns True if the operation is successful.
313
+ * @returns The checkpoints that were actually inserted (excluding already-stored ones).
223
314
  */
224
- async addCheckpoints(checkpoints: PublishedCheckpoint[], opts: { force?: boolean } = {}): Promise<boolean> {
315
+ async addCheckpoints(
316
+ checkpoints: PublishedCheckpoint[],
317
+ opts: { force?: boolean } = {},
318
+ ): Promise<PublishedCheckpoint[]> {
225
319
  if (checkpoints.length === 0) {
226
- return true;
320
+ return [];
227
321
  }
228
322
 
229
323
  return await this.db.transactionAsync(async () => {
@@ -236,7 +330,7 @@ export class BlockStore {
236
330
  if (!opts.force && firstCheckpointNumber <= previousCheckpointNumber) {
237
331
  checkpoints = await this.skipOrUpdateAlreadyStoredCheckpoints(checkpoints, previousCheckpointNumber);
238
332
  if (checkpoints.length === 0) {
239
- return true;
333
+ return [];
240
334
  }
241
335
  // Re-check sequentiality after skipping
242
336
  const newFirstNumber = checkpoints[0].checkpoint.number;
@@ -247,29 +341,8 @@ export class BlockStore {
247
341
  throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
248
342
  }
249
343
 
250
- // Extract the previous checkpoint if there is one
251
- const currentFirstCheckpointNumber = checkpoints[0].checkpoint.number;
252
- let previousCheckpointData: CheckpointData | undefined = undefined;
253
- if (currentFirstCheckpointNumber - 1 !== INITIAL_CHECKPOINT_NUMBER - 1) {
254
- // There should be a previous checkpoint
255
- previousCheckpointData = await this.getCheckpointData(CheckpointNumber(currentFirstCheckpointNumber - 1));
256
- if (previousCheckpointData === undefined) {
257
- throw new CheckpointNotFoundError(CheckpointNumber(currentFirstCheckpointNumber - 1));
258
- }
259
- }
260
-
261
- let previousBlockNumber: BlockNumber | undefined = undefined;
262
- let previousBlock: L2Block | undefined = undefined;
263
-
264
- // If we have a previous checkpoint then we need to get the previous block number
265
- if (previousCheckpointData !== undefined) {
266
- previousBlockNumber = BlockNumber(previousCheckpointData.startBlock + previousCheckpointData.blockCount - 1);
267
- previousBlock = await this.getBlock(previousBlockNumber);
268
- if (previousBlock === undefined) {
269
- // We should be able to get the required previous block
270
- throw new BlockNotFoundError(previousBlockNumber);
271
- }
272
- }
344
+ // Get the last block of the previous checkpoint for archive chaining
345
+ let previousBlock = await this.getPreviousCheckpointBlock(checkpoints[0].checkpoint.number);
273
346
 
274
347
  // Iterate over checkpoints array and insert them, checking that the block numbers are sequential.
275
348
  let previousCheckpoint: PublishedCheckpoint | undefined = undefined;
@@ -286,42 +359,14 @@ export class BlockStore {
286
359
  }
287
360
  previousCheckpoint = checkpoint;
288
361
 
289
- // Store every block in the database. the block may already exist, but this has come from chain and is assumed to be correct.
290
- for (let i = 0; i < checkpoint.checkpoint.blocks.length; i++) {
291
- const block = checkpoint.checkpoint.blocks[i];
292
- if (previousBlock) {
293
- // The blocks should have a sequential block number
294
- if (previousBlock.number !== block.number - 1) {
295
- throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
296
- }
297
- // If the blocks are for the same checkpoint then they should have sequential indexes
298
- if (
299
- previousBlock.checkpointNumber === block.checkpointNumber &&
300
- previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1
301
- ) {
302
- throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
303
- }
304
- if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
305
- throw new BlockArchiveNotConsistentError(
306
- block.number,
307
- previousBlock.number,
308
- block.header.lastArchive.root,
309
- previousBlock.archive.root,
310
- );
311
- }
312
- } else {
313
- // No previous block, must be block 1 at checkpoint index 0
314
- if (block.indexWithinCheckpoint !== 0) {
315
- throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
316
- }
317
- if (block.number !== INITIAL_L2_BLOCK_NUM) {
318
- throw new BlockNumberNotSequentialError(block.number, undefined);
319
- }
320
- }
362
+ // Validate block sequencing, indexes, and archive chaining
363
+ this.validateCheckpointBlocks(checkpoint.checkpoint.blocks, previousBlock);
321
364
 
322
- previousBlock = block;
323
- await this.addBlockToDatabase(block, checkpoint.checkpoint.number, i);
365
+ // Store every block in the database (may already exist, but L1 data is authoritative)
366
+ for (let i = 0; i < checkpoint.checkpoint.blocks.length; i++) {
367
+ await this.addBlockToDatabase(checkpoint.checkpoint.blocks[i], checkpoint.checkpoint.number, i);
324
368
  }
369
+ previousBlock = checkpoint.checkpoint.blocks.at(-1);
325
370
 
326
371
  // Store the checkpoint in the database
327
372
  await this.#checkpoints.set(checkpoint.checkpoint.number, {
@@ -333,14 +378,22 @@ export class BlockStore {
333
378
  checkpointNumber: checkpoint.checkpoint.number,
334
379
  startBlock: checkpoint.checkpoint.blocks[0].number,
335
380
  blockCount: checkpoint.checkpoint.blocks.length,
381
+ feeAssetPriceModifier: checkpoint.checkpoint.feeAssetPriceModifier.toString(),
336
382
  });
337
383
 
338
384
  // Update slot-to-checkpoint index
339
385
  await this.#slotToCheckpoint.set(checkpoint.checkpoint.header.slotNumber, checkpoint.checkpoint.number);
386
+
387
+ // Remove proposed checkpoint if it exists, since L1 is authoritative
388
+ await this.#proposedCheckpoints.delete(checkpoint.checkpoint.number);
389
+
390
+ // Drop any rejected entry for this archive root: a checkpoint that was previously rejected
391
+ // (e.g. invalid attestations) is now being ingested as valid, so its descendants are allowed.
392
+ await this.removeRejectedCheckpointByArchiveRoot(checkpoint.checkpoint.archive.root);
340
393
  }
341
394
 
342
- await this.#lastSynchedL1Block.set(checkpoints[checkpoints.length - 1].l1.blockNumber);
343
- return true;
395
+ await this.advanceSynchedL1BlockNumber(checkpoints[checkpoints.length - 1].l1.blockNumber);
396
+ return checkpoints;
344
397
  });
345
398
  }
346
399
 
@@ -381,13 +434,79 @@ export class BlockStore {
381
434
  checkpointNumber: incoming.checkpoint.number,
382
435
  startBlock: incoming.checkpoint.blocks[0].number,
383
436
  blockCount: incoming.checkpoint.blocks.length,
437
+ feeAssetPriceModifier: incoming.checkpoint.feeAssetPriceModifier.toString(),
384
438
  });
385
439
  // Update the sync point to reflect the new L1 block
386
- await this.#lastSynchedL1Block.set(incoming.l1.blockNumber);
440
+ await this.advanceSynchedL1BlockNumber(incoming.l1.blockNumber);
387
441
  }
388
442
  return checkpoints.slice(i);
389
443
  }
390
444
 
445
+ /**
446
+ * Gets the last block of the checkpoint before the given one.
447
+ * Returns undefined if there is no previous checkpoint (i.e. genesis).
448
+ */
449
+ private async getPreviousCheckpointBlock(checkpointNumber: CheckpointNumber): Promise<L2Block | undefined> {
450
+ const previousCheckpointNumber = CheckpointNumber(checkpointNumber - 1);
451
+ if (previousCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
452
+ return undefined;
453
+ }
454
+
455
+ // Check across both proposed and mined checkpoints
456
+ const predecessor =
457
+ (await this.getProposedCheckpointByNumber(previousCheckpointNumber)) ??
458
+ (await this.getCheckpointData(previousCheckpointNumber));
459
+
460
+ if (!predecessor) {
461
+ throw new CheckpointNotFoundError(previousCheckpointNumber);
462
+ }
463
+
464
+ const previousBlockNumber = BlockNumber(predecessor.startBlock + predecessor.blockCount - 1);
465
+ const previousBlock = await this.getBlock({ number: previousBlockNumber });
466
+ if (previousBlock === undefined) {
467
+ throw new BlockNotFoundError(previousBlockNumber);
468
+ }
469
+ return previousBlock;
470
+ }
471
+
472
+ /**
473
+ * Validates that blocks are sequential, have correct indexes, and chain via archive roots.
474
+ * This is the same validation used for both confirmed checkpoints (addCheckpoints) and
475
+ * proposed checkpoints (addProposedCheckpoint).
476
+ */
477
+ private validateCheckpointBlocks(blocks: L2Block[], previousBlock: L2Block | undefined): void {
478
+ for (const block of blocks) {
479
+ if (previousBlock) {
480
+ if (previousBlock.number !== block.number - 1) {
481
+ throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
482
+ }
483
+ if (previousBlock.checkpointNumber === block.checkpointNumber) {
484
+ if (previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1) {
485
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
486
+ }
487
+ } else if (block.indexWithinCheckpoint !== 0) {
488
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
489
+ }
490
+ if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
491
+ throw new BlockArchiveNotConsistentError(
492
+ block.number,
493
+ previousBlock.number,
494
+ block.header.lastArchive.root,
495
+ previousBlock.archive.root,
496
+ );
497
+ }
498
+ } else {
499
+ if (block.indexWithinCheckpoint !== 0) {
500
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
501
+ }
502
+ if (block.number !== INITIAL_L2_BLOCK_NUM) {
503
+ throw new BlockNumberNotSequentialError(block.number, undefined);
504
+ }
505
+ }
506
+ previousBlock = block;
507
+ }
508
+ }
509
+
391
510
  private async addBlockToDatabase(block: L2Block, checkpointNumber: number, indexWithinCheckpoint: number) {
392
511
  const blockHash = await block.hash();
393
512
 
@@ -405,6 +524,7 @@ export class BlockStore {
405
524
  l2BlockNumber: block.number,
406
525
  l2BlockHash: blockHash,
407
526
  txIndexInBlock: i,
527
+ slotNumber: block.header.globalVariables.slotNumber,
408
528
  };
409
529
  await this.#txEffects.set(txEffect.data.txHash.toString(), serializeIndexedTxEffect(txEffect));
410
530
  }
@@ -480,6 +600,9 @@ export class BlockStore {
480
600
  this.#log.debug(`Removed checkpoint ${c}`);
481
601
  }
482
602
 
603
+ // Evict all pending checkpoints > checkpointNumber (their base chain no longer exists)
604
+ await this.evictProposedCheckpointsFrom(CheckpointNumber(checkpointNumber + 1));
605
+
483
606
  return { blocksRemoved };
484
607
  });
485
608
  }
@@ -504,6 +627,26 @@ export class BlockStore {
504
627
  return checkpoints;
505
628
  }
506
629
 
630
+ /**
631
+ * Returns up to `limit` checkpoints anchored at `fromSlot`, ordered nearest-first, walking the slot index.
632
+ * With `reverse`, takes the checkpoints at or before `fromSlot` (descending by slot); otherwise the
633
+ * checkpoints at or after it (ascending). `limit: 1, reverse: true` yields the latest checkpoint at or
634
+ * before the slot in a single range scan.
635
+ */
636
+ async getCheckpointsBySlot(fromSlot: SlotNumber, limit: number, reverse: boolean): Promise<CheckpointData[]> {
637
+ // The KV range bounds are direction-dependent: forward is [start, end), reverse is (start, end], so a
638
+ // reverse scan uses `end: fromSlot` (inclusive) with no +1 to include the checkpoint at fromSlot itself.
639
+ const range = reverse ? { end: fromSlot, reverse: true, limit } : { start: fromSlot, limit };
640
+ const result: CheckpointData[] = [];
641
+ for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync(range)) {
642
+ const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
643
+ if (checkpointStorage) {
644
+ result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage));
645
+ }
646
+ }
647
+ return result;
648
+ }
649
+
507
650
  /** Returns checkpoint data for all checkpoints whose slot falls within the given range (inclusive). */
508
651
  async getCheckpointDataForSlotRange(startSlot: SlotNumber, endSlot: SlotNumber): Promise<CheckpointData[]> {
509
652
  const result: CheckpointData[] = [];
@@ -519,6 +662,22 @@ export class BlockStore {
519
662
  return result;
520
663
  }
521
664
 
665
+ /**
666
+ * Returns the checkpoint numbers for all checkpoints whose slot falls within the given range (inclusive).
667
+ * Lighter than {@link getCheckpointDataForSlotRange} when callers only need to identify which
668
+ * checkpoints fall in the range and will fetch full data for at most a few of them.
669
+ */
670
+ async getCheckpointNumbersForSlotRange(startSlot: SlotNumber, endSlot: SlotNumber): Promise<CheckpointNumber[]> {
671
+ const result: CheckpointNumber[] = [];
672
+ for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync({
673
+ start: startSlot,
674
+ end: endSlot + 1,
675
+ })) {
676
+ result.push(CheckpointNumber(checkpointNumber));
677
+ }
678
+ return result;
679
+ }
680
+
522
681
  private checkpointDataFromCheckpointStorage(checkpointStorage: CheckpointStorage): CheckpointData {
523
682
  return {
524
683
  header: CheckpointHeader.fromBuffer(checkpointStorage.header),
@@ -527,6 +686,7 @@ export class BlockStore {
527
686
  checkpointNumber: CheckpointNumber(checkpointStorage.checkpointNumber),
528
687
  startBlock: BlockNumber(checkpointStorage.startBlock),
529
688
  blockCount: checkpointStorage.blockCount,
689
+ feeAssetPriceModifier: BigInt(checkpointStorage.feeAssetPriceModifier),
530
690
  l1: L1PublishedData.fromBuffer(checkpointStorage.l1),
531
691
  attestations: checkpointStorage.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
532
692
  };
@@ -585,11 +745,11 @@ export class BlockStore {
585
745
  const removedBlocks: L2Block[] = [];
586
746
 
587
747
  // Get the latest block number to determine the range
588
- const latestBlockNumber = await this.getLatestBlockNumber();
748
+ const latestBlockNumber = await this.getLatestL2BlockNumber();
589
749
 
590
750
  // Iterate from blockNumber + 1 to latestBlockNumber
591
751
  for (let bn = blockNumber + 1; bn <= latestBlockNumber; bn++) {
592
- const block = await this.getBlock(BlockNumber(bn));
752
+ const block = await this.getBlock({ number: BlockNumber(bn) });
593
753
 
594
754
  if (block === undefined) {
595
755
  this.#log.warn(`Cannot remove block ${bn} from the store since we don't have it`);
@@ -618,13 +778,6 @@ export class BlockStore {
618
778
  }
619
779
  }
620
780
 
621
- async getLatestBlockNumber(): Promise<BlockNumber> {
622
- const [latestBlocknumber] = await toArray(this.#blocks.keysAsync({ reverse: true, limit: 1 }));
623
- return typeof latestBlocknumber === 'number'
624
- ? BlockNumber(latestBlocknumber)
625
- : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
626
- }
627
-
628
781
  async getLatestCheckpointNumber(): Promise<CheckpointNumber> {
629
782
  const [latestCheckpointNumber] = await toArray(this.#checkpoints.keysAsync({ reverse: true, limit: 1 }));
630
783
  if (latestCheckpointNumber === undefined) {
@@ -633,175 +786,204 @@ export class BlockStore {
633
786
  return CheckpointNumber(latestCheckpointNumber);
634
787
  }
635
788
 
636
- async getCheckpointedBlock(number: BlockNumber): Promise<CheckpointedL2Block | undefined> {
637
- const blockStorage = await this.#blocks.getAsync(number);
638
- if (!blockStorage) {
639
- return undefined;
640
- }
641
- const checkpoint = await this.#checkpoints.getAsync(blockStorage.checkpointNumber);
642
- if (!checkpoint) {
643
- return undefined;
644
- }
645
- const block = await this.getBlockFromBlockStorage(number, blockStorage);
646
- if (!block) {
647
- return undefined;
789
+ async hasProposedCheckpoint(): Promise<boolean> {
790
+ const [key] = await toArray(this.#proposedCheckpoints.keysAsync({ limit: 1 }));
791
+ return key !== undefined;
792
+ }
793
+
794
+ /** Deletes all pending proposed checkpoints from storage. */
795
+ async deleteProposedCheckpoints(): Promise<void> {
796
+ for await (const key of this.#proposedCheckpoints.keysAsync()) {
797
+ await this.#proposedCheckpoints.delete(key);
648
798
  }
649
- return new CheckpointedL2Block(
650
- CheckpointNumber(checkpoint.checkpointNumber),
651
- block,
652
- L1PublishedData.fromBuffer(checkpoint.l1),
653
- checkpoint.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
654
- );
655
799
  }
656
800
 
657
801
  /**
658
- * Gets up to `limit` amount of Checkpointed L2 blocks starting from `from`.
659
- * @param start - Number of the first block to return (inclusive).
660
- * @param limit - The number of blocks to return.
661
- * @returns The requested L2 blocks
802
+ * Promotes a specific pending checkpoint to a confirmed checkpoint entry.
803
+ * This persists the checkpoint to the store, removes only that pending entry, and updates the L1 sync point.
804
+ * Remaining pending entries (e.g. N+1, N+2) are left intact — they chain off the just-promoted one.
805
+ * @param checkpointNumber - The checkpoint number to promote.
806
+ * @param l1 - L1 published data for the checkpoint.
807
+ * @param attestations - Committee attestations.
808
+ * @param expectedArchiveRoot - Archive root guard against races.
662
809
  */
663
- async *getCheckpointedBlocks(start: BlockNumber, limit: number): AsyncIterableIterator<CheckpointedL2Block> {
664
- const checkpointCache = new Map<CheckpointNumber, CheckpointStorage>();
665
- for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)) {
666
- const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
667
- if (block) {
668
- const checkpoint =
669
- checkpointCache.get(CheckpointNumber(blockStorage.checkpointNumber)) ??
670
- (await this.#checkpoints.getAsync(blockStorage.checkpointNumber));
671
- if (checkpoint) {
672
- checkpointCache.set(CheckpointNumber(blockStorage.checkpointNumber), checkpoint);
673
- const checkpointedBlock = new CheckpointedL2Block(
674
- CheckpointNumber(checkpoint.checkpointNumber),
675
- block,
676
- L1PublishedData.fromBuffer(checkpoint.l1),
677
- checkpoint.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
678
- );
679
- yield checkpointedBlock;
680
- }
810
+ async promoteProposedToCheckpointed(
811
+ checkpointNumber: CheckpointNumber,
812
+ l1: L1PublishedData,
813
+ attestations: CommitteeAttestation[],
814
+ expectedArchiveRoot: Fr,
815
+ ): Promise<void> {
816
+ return await this.db.transactionAsync(async () => {
817
+ const proposed = await this.getProposedCheckpointByNumber(checkpointNumber);
818
+ if (!proposed) {
819
+ throw new NoProposedCheckpointToPromoteError();
681
820
  }
682
- }
821
+ if (!proposed.archive.root.equals(expectedArchiveRoot)) {
822
+ throw new ProposedCheckpointArchiveRootMismatchError(expectedArchiveRoot, proposed.archive.root);
823
+ }
824
+
825
+ // Verify sequentiality: promoted checkpoint must follow the latest confirmed one
826
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
827
+ if (latestCheckpointNumber !== proposed.checkpointNumber - 1) {
828
+ throw new ProposedCheckpointPromotionNotSequentialError(proposed.checkpointNumber, latestCheckpointNumber);
829
+ }
830
+
831
+ // Write the checkpoint entry
832
+ await this.#checkpoints.set(proposed.checkpointNumber, {
833
+ header: proposed.header.toBuffer(),
834
+ archive: proposed.archive.toBuffer(),
835
+ checkpointOutHash: proposed.checkpointOutHash.toBuffer(),
836
+ l1: l1.toBuffer(),
837
+ attestations: attestations.map(attestation => attestation.toBuffer()),
838
+ checkpointNumber: proposed.checkpointNumber,
839
+ startBlock: proposed.startBlock,
840
+ blockCount: proposed.blockCount,
841
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
842
+ });
843
+
844
+ // Update the slot-to-checkpoint index
845
+ await this.#slotToCheckpoint.set(proposed.header.slotNumber, proposed.checkpointNumber);
846
+
847
+ // Remove only this pending entry — remaining entries N+1, N+2, ... stay valid
848
+ await this.#proposedCheckpoints.delete(proposed.checkpointNumber);
849
+
850
+ // Drop any rejected entry for this archive root: a checkpoint that was previously rejected
851
+ // (e.g. invalid attestations) is now being promoted as valid, so its descendants are allowed.
852
+ await this.removeRejectedCheckpointByArchiveRoot(proposed.archive.root);
853
+
854
+ // Update the last synced L1 block
855
+ await this.advanceSynchedL1BlockNumber(l1.blockNumber);
856
+ });
683
857
  }
684
858
 
685
- async getCheckpointedBlockByHash(blockHash: BlockHash): Promise<CheckpointedL2Block | undefined> {
686
- const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
687
- if (blockNumber === undefined) {
859
+ /**
860
+ * Returns the latest pending checkpoint (highest-numbered entry), or undefined if none.
861
+ * No fallback to confirmed.
862
+ */
863
+ async getLastProposedCheckpoint(): Promise<ProposedCheckpointData | undefined> {
864
+ const [key] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
865
+ if (key === undefined) {
688
866
  return undefined;
689
867
  }
690
- return this.getCheckpointedBlock(BlockNumber(blockNumber));
868
+ const stored = await this.#proposedCheckpoints.getAsync(key);
869
+ return stored ? this.convertToProposedCheckpointData(stored) : undefined;
691
870
  }
692
871
 
693
- async getCheckpointedBlockByArchive(archive: Fr): Promise<CheckpointedL2Block | undefined> {
694
- const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
695
- if (blockNumber === undefined) {
696
- return undefined;
697
- }
698
- return this.getCheckpointedBlock(BlockNumber(blockNumber));
872
+ /** Returns the pending checkpoint for a specific checkpoint number, or undefined if not found. */
873
+ async getProposedCheckpointByNumber(n: CheckpointNumber): Promise<ProposedCheckpointData | undefined> {
874
+ const stored = await this.#proposedCheckpoints.getAsync(n);
875
+ return stored ? this.convertToProposedCheckpointData(stored) : undefined;
699
876
  }
700
877
 
701
878
  /**
702
- * Gets up to `limit` amount of L2 blocks starting from `from`.
703
- * @param start - Number of the first block to return (inclusive).
704
- * @param limit - The number of blocks to return.
705
- * @returns The requested L2 blocks
879
+ * Returns the pending checkpoint whose header slot matches the given slot, or undefined if not found.
880
+ * Iterates `#proposedCheckpoints` rather than reading an index because the map carries 0–1 entries
881
+ * in normal operation (bounded by the proposer pipelining window). Returns the first match.
706
882
  */
707
- async *getBlocks(start: BlockNumber, limit: number): AsyncIterableIterator<L2Block> {
708
- for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)) {
709
- const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
710
- if (block) {
711
- yield block;
883
+ async getProposedCheckpointBySlot(slot: SlotNumber): Promise<ProposedCheckpointData | undefined> {
884
+ for await (const [, stored] of this.#proposedCheckpoints.entriesAsync()) {
885
+ const header = CheckpointHeader.fromBuffer(stored.header);
886
+ if (header.slotNumber === slot) {
887
+ return this.convertToProposedCheckpointData(stored);
712
888
  }
713
889
  }
890
+ return undefined;
714
891
  }
715
892
 
716
893
  /**
717
- * Gets block metadata (without tx data) by block number.
718
- * @param blockNumber - The number of the block to return.
719
- * @returns The requested block data.
894
+ * Evicts all pending checkpoints with checkpoint number >= fromNumber.
895
+ * Used for divergent-mined-checkpoint cleanup: when L1 mines checkpoint N with a different archive,
896
+ * all pending >= N must be evicted since they chain off the now-invalid pending N.
720
897
  */
721
- async getBlockData(blockNumber: BlockNumber): Promise<BlockData | undefined> {
722
- const blockStorage = await this.#blocks.getAsync(blockNumber);
723
- if (!blockStorage || !blockStorage.header) {
724
- return undefined;
898
+ async evictProposedCheckpointsFrom(fromNumber: CheckpointNumber): Promise<void> {
899
+ const keysToDelete: number[] = [];
900
+ for await (const key of this.#proposedCheckpoints.keysAsync()) {
901
+ if (key >= fromNumber) {
902
+ keysToDelete.push(key);
903
+ }
904
+ }
905
+ for (const key of keysToDelete) {
906
+ await this.#proposedCheckpoints.delete(key);
725
907
  }
726
- return this.getBlockDataFromBlockStorage(blockStorage);
727
908
  }
728
909
 
729
910
  /**
730
- * Gets block metadata (without tx data) by archive root.
731
- * @param archive - The archive root of the block to return.
732
- * @returns The requested block data.
911
+ * Gets the checkpoint at the proposed tip:
912
+ * - latest pending checkpoint if any exist
913
+ * - fallsback to latest confirmed checkpoint otherwise
733
914
  */
734
- async getBlockDataByArchive(archive: Fr): Promise<BlockData | undefined> {
735
- const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
736
- if (blockNumber === undefined) {
737
- return undefined;
915
+ async getLastCheckpoint(): Promise<CommonCheckpointData | undefined> {
916
+ const latest = await this.getLastProposedCheckpoint();
917
+ if (!latest) {
918
+ return this.getCheckpointData(await this.getLatestCheckpointNumber());
738
919
  }
739
- return this.getBlockData(BlockNumber(blockNumber));
920
+ return latest;
740
921
  }
741
922
 
742
- /**
743
- * Gets an L2 block.
744
- * @param blockNumber - The number of the block to return.
745
- * @returns The requested L2 block.
746
- */
747
- async getBlock(blockNumber: BlockNumber): Promise<L2Block | undefined> {
748
- const blockStorage = await this.#blocks.getAsync(blockNumber);
749
- if (!blockStorage || !blockStorage.header) {
750
- return Promise.resolve(undefined);
751
- }
752
- return this.getBlockFromBlockStorage(blockNumber, blockStorage);
923
+ private convertToProposedCheckpointData(stored: ProposedCheckpointStorage): ProposedCheckpointData {
924
+ return {
925
+ checkpointNumber: CheckpointNumber(stored.checkpointNumber),
926
+ header: CheckpointHeader.fromBuffer(stored.header),
927
+ archive: AppendOnlyTreeSnapshot.fromBuffer(stored.archive),
928
+ checkpointOutHash: Fr.fromBuffer(stored.checkpointOutHash),
929
+ startBlock: BlockNumber(stored.startBlock),
930
+ blockCount: stored.blockCount,
931
+ totalManaUsed: BigInt(stored.totalManaUsed),
932
+ feeAssetPriceModifier: BigInt(stored.feeAssetPriceModifier),
933
+ };
753
934
  }
754
935
 
755
936
  /**
756
- * Gets an L2 block by its hash.
757
- * @param blockHash - The hash of the block to return.
758
- * @returns The requested L2 block.
937
+ * Attempts to get the proposedCheckpoint's number, if there is not one, then fallback to the latest confirmed checkpoint number.
938
+ * @returns CheckpointNumber
759
939
  */
760
- async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
761
- const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
762
- if (blockNumber === undefined) {
763
- return undefined;
940
+ async getProposedCheckpointNumber(): Promise<CheckpointNumber> {
941
+ const proposed = await this.getLastCheckpoint();
942
+ if (!proposed) {
943
+ return await this.getLatestCheckpointNumber();
764
944
  }
765
- return this.getBlock(BlockNumber(blockNumber));
945
+ return CheckpointNumber(proposed.checkpointNumber);
766
946
  }
767
947
 
768
948
  /**
769
- * Gets an L2 block by its archive root.
770
- * @param archive - The archive root of the block to return.
771
- * @returns The requested L2 block.
949
+ * Attempts to get the proposedCheckpoint's block number, if there is not one, then fallback to the checkpointed block number
950
+ * @returns BlockNumber
772
951
  */
773
- async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
774
- const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
775
- if (blockNumber === undefined) {
776
- return undefined;
952
+ async getProposedCheckpointL2BlockNumber(): Promise<BlockNumber> {
953
+ const proposed = await this.getLastCheckpoint();
954
+ if (!proposed) {
955
+ return await this.getCheckpointedL2BlockNumber();
777
956
  }
778
- return this.getBlock(BlockNumber(blockNumber));
957
+ return BlockNumber(proposed.startBlock + proposed.blockCount - 1);
779
958
  }
780
959
 
781
- /**
782
- * Gets a block header by its hash.
783
- * @param blockHash - The hash of the block to return.
784
- * @returns The requested block header.
785
- */
786
- async getBlockHeaderByHash(blockHash: BlockHash): Promise<BlockHeader | undefined> {
787
- const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
960
+ /** Returns the checkpoint number that contains the given slot (or undefined if not found). */
961
+ async getCheckpointNumberBySlot(slot: SlotNumber): Promise<CheckpointNumber | undefined> {
962
+ const checkpointNumber = await this.#slotToCheckpoint.getAsync(slot);
963
+ return checkpointNumber === undefined ? undefined : CheckpointNumber(checkpointNumber);
964
+ }
965
+
966
+ /** Gets a single L2 block matching the given resolved query. */
967
+ async getBlock(query: ResolvedBlockQuery): Promise<L2Block | undefined> {
968
+ const blockNumber = await this.getBlockNumber(query);
788
969
  if (blockNumber === undefined) {
789
970
  return undefined;
790
971
  }
791
972
  const blockStorage = await this.#blocks.getAsync(blockNumber);
792
- if (!blockStorage || !blockStorage.header) {
973
+ if (!blockStorage) {
793
974
  return undefined;
794
975
  }
795
- return BlockHeader.fromBuffer(blockStorage.header);
976
+ return this.getBlockFromBlockStorage(blockNumber, blockStorage);
796
977
  }
797
978
 
798
- /**
799
- * Gets a block header by its archive root.
800
- * @param archive - The archive root of the block to return.
801
- * @returns The requested block header.
802
- */
803
- async getBlockHeaderByArchive(archive: Fr): Promise<BlockHeader | undefined> {
804
- const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
979
+ /** Gets a collection of L2 blocks for a resolved range. */
980
+ getBlocks(query: ResolvedBlocksQuery): Promise<L2Block[]> {
981
+ return toArray(this.iterateBlocks(query));
982
+ }
983
+
984
+ /** Gets single block metadata matching the given resolved query. */
985
+ async getBlockData(query: ResolvedBlockQuery): Promise<BlockData | undefined> {
986
+ const blockNumber = await this.getBlockNumber(query);
805
987
  if (blockNumber === undefined) {
806
988
  return undefined;
807
989
  }
@@ -809,24 +991,36 @@ export class BlockStore {
809
991
  if (!blockStorage || !blockStorage.header) {
810
992
  return undefined;
811
993
  }
812
- return BlockHeader.fromBuffer(blockStorage.header);
994
+ return this.getBlockDataFromBlockStorage(blockStorage);
813
995
  }
814
996
 
815
- /**
816
- * Gets the headers for a sequence of L2 blocks.
817
- * @param start - Number of the first block to return (inclusive).
818
- * @param limit - The number of blocks to return.
819
- * @returns The requested L2 block headers
820
- */
821
- async *getBlockHeaders(start: BlockNumber, limit: number): AsyncIterableIterator<BlockHeader> {
822
- for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)) {
823
- const header = BlockHeader.fromBuffer(blockStorage.header);
824
- if (header.getBlockNumber() !== blockNumber) {
825
- throw new Error(
826
- `Block number mismatch when retrieving block header from archive (expected ${blockNumber} but got ${header.getBlockNumber()})`,
827
- );
997
+ /** Gets a collection of block metadata entries for a resolved range. */
998
+ getBlocksData(query: ResolvedBlocksQuery): Promise<BlockData[]> {
999
+ return toArray(this.iterateBlocksData(query));
1000
+ }
1001
+
1002
+ /** Async iterator over L2 blocks for a resolved range. */
1003
+ private async *iterateBlocks(query: ResolvedBlocksQuery): AsyncIterableIterator<L2Block> {
1004
+ const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
1005
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)) {
1006
+ if (cap !== undefined && blockNumber > cap) {
1007
+ break;
1008
+ }
1009
+ const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
1010
+ if (block) {
1011
+ yield block;
1012
+ }
1013
+ }
1014
+ }
1015
+
1016
+ /** Async iterator over block metadata for a resolved range. */
1017
+ private async *iterateBlocksData(query: ResolvedBlocksQuery): AsyncIterableIterator<BlockData> {
1018
+ const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
1019
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)) {
1020
+ if (cap !== undefined && blockNumber > cap) {
1021
+ break;
828
1022
  }
829
- yield header;
1023
+ yield this.getBlockDataFromBlockStorage(blockStorage);
830
1024
  }
831
1025
  }
832
1026
 
@@ -843,11 +1037,29 @@ export class BlockStore {
843
1037
  }
844
1038
  }
845
1039
 
1040
+ /** Resolves a ResolvedBlockQuery discriminant to a block number, or undefined if not found. */
1041
+ async getBlockNumber(query: ResolvedBlockQuery): Promise<BlockNumber | undefined> {
1042
+ let blockNumber: BlockNumber | undefined;
1043
+ if ('number' in query) {
1044
+ blockNumber = query.number;
1045
+ } else if ('hash' in query) {
1046
+ const n = await this.#blockHashIndex.getAsync(query.hash.toString());
1047
+ blockNumber = n !== undefined ? BlockNumber(n) : undefined;
1048
+ } else {
1049
+ const n = await this.#blockArchiveIndex.getAsync(query.archive.toString());
1050
+ blockNumber = n !== undefined ? BlockNumber(n) : undefined;
1051
+ }
1052
+ if (blockNumber === undefined) {
1053
+ return undefined;
1054
+ }
1055
+ return blockNumber;
1056
+ }
1057
+
846
1058
  private getBlockDataFromBlockStorage(blockStorage: BlockStorage): BlockData {
847
1059
  return {
848
1060
  header: BlockHeader.fromBuffer(blockStorage.header),
849
1061
  archive: AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),
850
- blockHash: Fr.fromBuffer(blockStorage.blockHash),
1062
+ blockHash: BlockHash.fromBuffer(blockStorage.blockHash),
851
1063
  checkpointNumber: CheckpointNumber(blockStorage.checkpointNumber),
852
1064
  indexWithinCheckpoint: IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint),
853
1065
  };
@@ -904,56 +1116,6 @@ export class BlockStore {
904
1116
  return deserializeIndexedTxEffect(buffer);
905
1117
  }
906
1118
 
907
- /**
908
- * Gets a receipt of a settled tx.
909
- * @param txHash - The hash of a tx we try to get the receipt for.
910
- * @returns The requested tx receipt (or undefined if not found).
911
- */
912
- async getSettledTxReceipt(
913
- txHash: TxHash,
914
- l1Constants?: Pick<L1RollupConstants, 'epochDuration'>,
915
- ): Promise<TxReceipt | undefined> {
916
- const txEffect = await this.getTxEffect(txHash);
917
- if (!txEffect) {
918
- return undefined;
919
- }
920
-
921
- const blockNumber = BlockNumber(txEffect.l2BlockNumber);
922
-
923
- // Use existing archiver methods to determine finalization level
924
- const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber, blockData] = await Promise.all([
925
- this.getProvenBlockNumber(),
926
- this.getCheckpointedL2BlockNumber(),
927
- this.getFinalizedL2BlockNumber(),
928
- this.getBlockData(blockNumber),
929
- ]);
930
-
931
- let status: TxStatus;
932
- if (blockNumber <= finalizedBlockNumber) {
933
- status = TxStatus.FINALIZED;
934
- } else if (blockNumber <= provenBlockNumber) {
935
- status = TxStatus.PROVEN;
936
- } else if (blockNumber <= checkpointedBlockNumber) {
937
- status = TxStatus.CHECKPOINTED;
938
- } else {
939
- status = TxStatus.PROPOSED;
940
- }
941
-
942
- const epochNumber =
943
- blockData && l1Constants ? getEpochAtSlot(blockData.header.globalVariables.slotNumber, l1Constants) : undefined;
944
-
945
- return new TxReceipt(
946
- txHash,
947
- status,
948
- TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode),
949
- undefined,
950
- txEffect.data.transactionFee.toBigInt(),
951
- txEffect.l2BlockHash,
952
- blockNumber,
953
- epochNumber,
954
- );
955
- }
956
-
957
1119
  /**
958
1120
  * Looks up which block included the requested tx effect.
959
1121
  * @param txHash - The txHash of the tx.
@@ -964,10 +1126,45 @@ export class BlockStore {
964
1126
  if (!txEffect) {
965
1127
  return undefined;
966
1128
  }
967
- const { l2BlockNumber, txIndexInBlock } = deserializeIndexedTxEffect(txEffect);
1129
+ // Read only the IndexedTxEffect header (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4)`); the
1130
+ // large tail (the full TxEffect with logs etc.) is irrelevant here.
1131
+ const view = Buffer.from(txEffect.buffer, txEffect.byteOffset, txEffect.byteLength);
1132
+ const l2BlockNumber = view.readUInt32BE(32);
1133
+ const txIndexInBlock = view.readUInt32BE(36);
968
1134
  return [l2BlockNumber, txIndexInBlock];
969
1135
  }
970
1136
 
1137
+ /**
1138
+ * Batched, partial deserializer that fetches `noteHashes` and `nullifiers` (all of them) for the given
1139
+ * txs. For each input txHash, returns a `[noteHashes, nullifiers]` tuple. Returns `[[], []]` for any
1140
+ * unknown txHash. Preserves input order. Used by the log read path when `includeEffects` is set to
1141
+ * attach effect data on demand without paying for a full {@link TxEffect} deserialization.
1142
+ *
1143
+ * The on-disk `IndexedTxEffect` layout starts with a fixed-length header
1144
+ * (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4) + slotNumber(4) + revertCode(1) + txHash(32) +
1145
+ * transactionFee(32)` = 109 bytes), followed by `noteHashes` and `nullifiers` (both u8-length-prefixed `Fr`
1146
+ * vectors). We
1147
+ * skip the header, then read the two vectors, and stop — the large tail (`l2ToL1Msgs`,
1148
+ * `publicDataWrites`, `privateLogs`, `publicLogs`, `contractClassLogs`) is never touched.
1149
+ */
1150
+ public getNoteHashesAndNullifiers(txHashes: TxHash[]): Promise<[Fr[], Fr[]][]> {
1151
+ return Promise.all(
1152
+ txHashes.map(async (txHash): Promise<[Fr[], Fr[]]> => {
1153
+ const buffer = await this.#txEffects.getAsync(txHash.toString());
1154
+ if (!buffer) {
1155
+ return [[], []];
1156
+ }
1157
+ const reader = BufferReader.asReader(buffer);
1158
+ // Skip the fixed-length header: blockHash + l2BlockNumber + txIndexInBlock + slotNumber + revertCode +
1159
+ // txHash + transactionFee.
1160
+ reader.readBytes(32 + 4 + 4 + 4 + 1 + 32 + 32);
1161
+ const noteHashes = reader.readVectorUint8Prefix(Fr);
1162
+ const nullifiers = reader.readVectorUint8Prefix(Fr);
1163
+ return [noteHashes, nullifiers];
1164
+ }),
1165
+ );
1166
+ }
1167
+
971
1168
  /**
972
1169
  * Looks up which block deployed a particular contract.
973
1170
  * @param contractAddress - The address of the contract to look up.
@@ -995,6 +1192,159 @@ export class BlockStore {
995
1192
  return typeof lastBlockNumber === 'number' ? BlockNumber(lastBlockNumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
996
1193
  }
997
1194
 
1195
+ /**
1196
+ * Resolves all four L2 chain tips (proposed, checkpointed, proven, finalized) in a single
1197
+ * read-only transaction so the snapshot is internally consistent. Each underlying record is
1198
+ * read at most once: latest block and latest confirmed checkpoint are loaded directly (no
1199
+ * separate "find the number, then look up data" hop), the proven/finalized checkpoint
1200
+ * singletons are read once and their storage entries are reused if they coincide with the
1201
+ * latest checkpoint, and per-tip block hashes are deduped when two tips land on the same block
1202
+ * (e.g. finalized == proven).
1203
+ *
1204
+ * The result is guaranteed to satisfy `finalized <= proven <= checkpointed <= proposed` (by
1205
+ * block number). Genesis is represented by `(INITIAL_L2_BLOCK_NUM - 1)` and the supplied
1206
+ * `genesisBlockHash`, paired with the synthetic genesis checkpoint id.
1207
+ *
1208
+ * @param genesisBlockHash - Block hash to report for the synthetic pre-initial block (used when
1209
+ * a tip is still at genesis).
1210
+ */
1211
+ async getL2TipsData(genesisBlockHash: BlockHash): Promise<L2Tips> {
1212
+ return await this.db.transactionAsync(async () => {
1213
+ // Define genesis tips
1214
+ const genesisBlockNumber = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
1215
+ const genesisCheckpointNumber = CheckpointNumber(INITIAL_CHECKPOINT_NUMBER - 1);
1216
+ const genesisBlockId = { number: genesisBlockNumber, hash: genesisBlockHash.toString() };
1217
+ const genesisCheckpointId = {
1218
+ number: genesisCheckpointNumber,
1219
+ hash: GENESIS_CHECKPOINT_HEADER_HASH.toString(),
1220
+ };
1221
+ const genesisTip: L2TipId = { block: genesisBlockId, checkpoint: genesisCheckpointId };
1222
+
1223
+ // Load latest block and checkpoint entries
1224
+ const [latestBlockEntry] = await toArray(this.#blocks.entriesAsync({ reverse: true, limit: 1 }));
1225
+ const [latestCheckpointEntry] = await toArray(this.#checkpoints.entriesAsync({ reverse: true, limit: 1 }));
1226
+ const latestCheckpointNumber = latestCheckpointEntry
1227
+ ? CheckpointNumber(latestCheckpointEntry[0])
1228
+ : genesisCheckpointNumber;
1229
+
1230
+ // Load proven and finalized checkpoint number pointers
1231
+ const [provenRaw, finalizedRaw] = await Promise.all([
1232
+ this.#lastProvenCheckpoint.getAsync(),
1233
+ this.#lastFinalizedCheckpoint.getAsync(),
1234
+ ]);
1235
+
1236
+ // Clamp to enforce finalized <= proven <= checkpointed.
1237
+ const provenCheckpointNumber = CheckpointNumber(Math.min(provenRaw ?? 0, latestCheckpointNumber));
1238
+ const finalizedCheckpointNumber = CheckpointNumber(Math.min(finalizedRaw ?? 0, provenCheckpointNumber));
1239
+
1240
+ // Avoid loading the same checkpoint more than once
1241
+ const checkpointStorageCache = new Map<CheckpointNumber, CheckpointStorage>();
1242
+ if (latestCheckpointEntry) {
1243
+ checkpointStorageCache.set(CheckpointNumber(latestCheckpointEntry[0]), latestCheckpointEntry[1]);
1244
+ }
1245
+ const loadCheckpointStorage = async (n: CheckpointNumber): Promise<CheckpointStorage | undefined> => {
1246
+ if (n === 0) {
1247
+ return undefined;
1248
+ }
1249
+ if (!checkpointStorageCache.has(n)) {
1250
+ const checkpointStorage = await this.#checkpoints.getAsync(n);
1251
+ if (!checkpointStorage) {
1252
+ throw new CheckpointNotFoundError(n);
1253
+ }
1254
+ checkpointStorageCache.set(n, checkpointStorage);
1255
+ }
1256
+ return checkpointStorageCache.get(n)!;
1257
+ };
1258
+
1259
+ // Load proven and finalized checkpoint storage entries
1260
+ const provenCheckpoint = await loadCheckpointStorage(provenCheckpointNumber);
1261
+ const finalizedCheckpoint = await loadCheckpointStorage(finalizedCheckpointNumber);
1262
+
1263
+ // Avoid loading the same block hash multiple times when tips land on the same block
1264
+ const blockHashCache = new Map<number, string>();
1265
+ blockHashCache.set(genesisBlockNumber, genesisBlockHash.toString());
1266
+ if (latestBlockEntry) {
1267
+ blockHashCache.set(latestBlockEntry[0], BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString());
1268
+ }
1269
+ const loadBlockHash = async (n: BlockNumber): Promise<string> => {
1270
+ if (!blockHashCache.has(n)) {
1271
+ const blockStorage = await this.#blocks.getAsync(n);
1272
+ if (!blockStorage) {
1273
+ throw new BlockNotFoundError(n);
1274
+ }
1275
+ const blockHash = BlockHash.fromBuffer(blockStorage.blockHash).toString();
1276
+ blockHashCache.set(n, blockHash);
1277
+ }
1278
+ return blockHashCache.get(n)!;
1279
+ };
1280
+
1281
+ // Build proposed chain tip (this one has block only, no checkpoint)
1282
+ const proposedBlockId =
1283
+ latestBlockEntry === undefined
1284
+ ? genesisBlockId
1285
+ : {
1286
+ number: BlockNumber(latestBlockEntry[0]),
1287
+ hash: BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString(),
1288
+ };
1289
+
1290
+ // Build other tips from checkpoint data, reading corresponding block data from the cache
1291
+ const buildTipFromCheckpoint = async (
1292
+ stored: ProposedCheckpointStorage | CheckpointStorage | undefined,
1293
+ ): Promise<L2TipId> => {
1294
+ if (!stored) {
1295
+ return genesisTip;
1296
+ }
1297
+ const blockNumber = BlockNumber(stored.startBlock + stored.blockCount - 1);
1298
+ const blockHash = await loadBlockHash(blockNumber);
1299
+ const header = CheckpointHeader.fromBuffer(stored.header);
1300
+ return {
1301
+ block: { number: blockNumber, hash: blockHash },
1302
+ checkpoint: { number: CheckpointNumber(stored.checkpointNumber), hash: header.hash().toString() },
1303
+ };
1304
+ };
1305
+
1306
+ const checkpointedTip = await buildTipFromCheckpoint(latestCheckpointEntry?.[1]);
1307
+ const provenTip = await buildTipFromCheckpoint(provenCheckpoint);
1308
+ const finalizedTip = await buildTipFromCheckpoint(finalizedCheckpoint);
1309
+
1310
+ // A checkpointed block past the latest stored block would mean a checkpoint
1311
+ // references blocks that aren't in blocks.
1312
+ if (proposedBlockId.number < checkpointedTip.block.number) {
1313
+ throw new Error(
1314
+ `Inconsistent block store: latest block ${proposedBlockId.number} is behind checkpointed block ${checkpointedTip.block.number}`,
1315
+ );
1316
+ }
1317
+
1318
+ // Assert that checkpoint numbers are increasing
1319
+ if (
1320
+ finalizedTip.checkpoint.number > provenTip.checkpoint.number ||
1321
+ provenTip.checkpoint.number > checkpointedTip.checkpoint.number
1322
+ ) {
1323
+ throw new Error(
1324
+ `Inconsistent checkpoint numbers in chain tips: finalized=${finalizedTip.checkpoint.number} proven=${provenTip.checkpoint.number} checkpointed=${checkpointedTip.checkpoint.number}`,
1325
+ );
1326
+ }
1327
+
1328
+ // Assert block numbers are increasing
1329
+ if (
1330
+ finalizedTip.block.number > provenTip.block.number ||
1331
+ provenTip.block.number > checkpointedTip.block.number ||
1332
+ checkpointedTip.block.number > proposedBlockId.number
1333
+ ) {
1334
+ throw new Error(
1335
+ `Inconsistent block numbers in chain tips: finalized=${finalizedTip.block.number} proven=${provenTip.block.number} checkpointed=${checkpointedTip.block.number} proposed=${proposedBlockId.number}`,
1336
+ );
1337
+ }
1338
+
1339
+ return {
1340
+ proposed: proposedBlockId,
1341
+ checkpointed: checkpointedTip,
1342
+ proven: provenTip,
1343
+ finalized: finalizedTip,
1344
+ };
1345
+ });
1346
+ }
1347
+
998
1348
  /**
999
1349
  * Gets the most recent L1 block processed.
1000
1350
  * @returns The L1 block that published the latest L2 block
@@ -1007,14 +1357,62 @@ export class BlockStore {
1007
1357
  return this.#lastSynchedL1Block.set(l1BlockNumber);
1008
1358
  }
1009
1359
 
1360
+ /**
1361
+ * Adds a proposed checkpoint to the pending queue.
1362
+ * Accepts proposed.checkpointNumber === latestTip + 1, where latestTip is the highest of
1363
+ * confirmed and the highest pending checkpoint number.
1364
+ * Computes archive and checkpointOutHash from the stored blocks.
1365
+ */
1366
+ async addProposedCheckpoint(proposed: ProposedCheckpointInput) {
1367
+ return await this.db.transactionAsync(async () => {
1368
+ const confirmed = await this.getLatestCheckpointNumber();
1369
+ const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
1370
+ const latestTip = CheckpointNumber(
1371
+ latestPendingKey !== undefined ? Math.max(latestPendingKey, confirmed) : confirmed,
1372
+ );
1373
+
1374
+ if (proposed.checkpointNumber !== latestTip + 1) {
1375
+ throw new ProposedCheckpointNotSequentialError(proposed.checkpointNumber, latestTip);
1376
+ }
1377
+
1378
+ // Ensure the predecessor block (from pending or confirmed chain) exists
1379
+ const previousBlock = await this.getPreviousCheckpointBlock(proposed.checkpointNumber);
1380
+ const blocks: L2Block[] = [];
1381
+ for (let i = 0; i < proposed.blockCount; i++) {
1382
+ const block = await this.getBlock({ number: BlockNumber(proposed.startBlock + i) });
1383
+ if (!block) {
1384
+ throw new BlockNotFoundError(proposed.startBlock + i);
1385
+ }
1386
+ blocks.push(block);
1387
+ }
1388
+ this.validateCheckpointBlocks(blocks, previousBlock);
1389
+
1390
+ const archive = blocks[blocks.length - 1].archive;
1391
+ const checkpointOutHash = Checkpoint.getCheckpointOutHash(blocks);
1392
+
1393
+ await this.#proposedCheckpoints.set(proposed.checkpointNumber, {
1394
+ header: proposed.header.toBuffer(),
1395
+ archive: archive.toBuffer(),
1396
+ checkpointOutHash: checkpointOutHash.toBuffer(),
1397
+ checkpointNumber: proposed.checkpointNumber,
1398
+ startBlock: proposed.startBlock,
1399
+ blockCount: proposed.blockCount,
1400
+ totalManaUsed: proposed.totalManaUsed.toString(),
1401
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
1402
+ });
1403
+ });
1404
+ }
1405
+
1010
1406
  async getProvenCheckpointNumber(): Promise<CheckpointNumber> {
1011
- const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
1012
- this.getLatestCheckpointNumber(),
1013
- this.#lastProvenCheckpoint.getAsync(),
1014
- ]);
1015
- return (provenCheckpointNumber ?? 0) > latestCheckpointNumber
1016
- ? latestCheckpointNumber
1017
- : CheckpointNumber(provenCheckpointNumber ?? 0);
1407
+ return await this.db.transactionAsync(async () => {
1408
+ const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
1409
+ this.getLatestCheckpointNumber(),
1410
+ this.#lastProvenCheckpoint.getAsync(),
1411
+ ]);
1412
+ return (provenCheckpointNumber ?? 0) > latestCheckpointNumber
1413
+ ? latestCheckpointNumber
1414
+ : CheckpointNumber(provenCheckpointNumber ?? 0);
1415
+ });
1018
1416
  }
1019
1417
 
1020
1418
  async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber) {
@@ -1023,13 +1421,15 @@ export class BlockStore {
1023
1421
  }
1024
1422
 
1025
1423
  async getFinalizedCheckpointNumber(): Promise<CheckpointNumber> {
1026
- const [latestCheckpointNumber, finalizedCheckpointNumber] = await Promise.all([
1027
- this.getLatestCheckpointNumber(),
1028
- this.#lastFinalizedCheckpoint.getAsync(),
1029
- ]);
1030
- return (finalizedCheckpointNumber ?? 0) > latestCheckpointNumber
1031
- ? latestCheckpointNumber
1032
- : CheckpointNumber(finalizedCheckpointNumber ?? 0);
1424
+ return await this.db.transactionAsync(async () => {
1425
+ const [provenCheckpointNumber, finalizedCheckpointNumber] = await Promise.all([
1426
+ this.getProvenCheckpointNumber(),
1427
+ this.#lastFinalizedCheckpoint.getAsync(),
1428
+ ]);
1429
+ return (finalizedCheckpointNumber ?? 0) > provenCheckpointNumber
1430
+ ? provenCheckpointNumber
1431
+ : CheckpointNumber(finalizedCheckpointNumber ?? 0);
1432
+ });
1033
1433
  }
1034
1434
 
1035
1435
  setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber) {
@@ -1072,4 +1472,80 @@ export class BlockStore {
1072
1472
  await this.#pendingChainValidationStatus.delete();
1073
1473
  }
1074
1474
  }
1475
+
1476
+ /** Records a rejected-checkpoint entry, keyed by its own archive root. */
1477
+ async addRejectedCheckpoint(entry: RejectedCheckpoint): Promise<void> {
1478
+ const archiveRootHex = entry.archiveRoot.toString();
1479
+ await this.#rejectedCheckpoints.set(archiveRootHex, {
1480
+ checkpointNumber: entry.checkpointNumber,
1481
+ archiveRoot: entry.archiveRoot.toBuffer(),
1482
+ parentArchiveRoot: entry.parentArchiveRoot.toBuffer(),
1483
+ slotNumber: entry.slotNumber,
1484
+ l1: entry.l1.toBuffer(),
1485
+ reason: entry.reason,
1486
+ });
1487
+ await this.#rejectedCheckpointsByNumber.set(entry.checkpointNumber, archiveRootHex);
1488
+ await this.advanceSynchedL1BlockNumber(entry.l1.blockNumber);
1489
+ }
1490
+
1491
+ /** Returns the rejected-checkpoint entry with the given archive root, or undefined if not present. */
1492
+ async getRejectedCheckpointByArchiveRoot(archiveRoot: Fr): Promise<RejectedCheckpoint | undefined> {
1493
+ const stored = await this.#rejectedCheckpoints.getAsync(archiveRoot.toString());
1494
+ return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
1495
+ }
1496
+
1497
+ /** Returns the rejected-checkpoint entry recorded for the given checkpoint number, or undefined if none. */
1498
+ async getRejectedCheckpointByNumber(checkpointNumber: CheckpointNumber): Promise<RejectedCheckpoint | undefined> {
1499
+ const archiveRootHex = await this.#rejectedCheckpointsByNumber.getAsync(checkpointNumber);
1500
+ if (archiveRootHex === undefined) {
1501
+ return undefined;
1502
+ }
1503
+ const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
1504
+ return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
1505
+ }
1506
+
1507
+ /** Returns the highest checkpoint number recorded across all rejected entries, or `INITIAL_CHECKPOINT_NUMBER - 1` if none. */
1508
+ async getLatestRejectedCheckpointNumber(): Promise<CheckpointNumber> {
1509
+ const [latest] = await toArray(this.#rejectedCheckpointsByNumber.keysAsync({ reverse: true, limit: 1 }));
1510
+ return CheckpointNumber(latest ?? INITIAL_CHECKPOINT_NUMBER - 1);
1511
+ }
1512
+
1513
+ /** Removes a rejected-checkpoint entry by its archive root (used when an entry no longer matches L1). */
1514
+ async removeRejectedCheckpointByArchiveRoot(archiveRoot: Fr): Promise<void> {
1515
+ const archiveRootHex = archiveRoot.toString();
1516
+ const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
1517
+ await this.#rejectedCheckpoints.delete(archiveRootHex);
1518
+ if (stored) {
1519
+ // Only clear the by-number index if it still points at this archive root, so a distinct
1520
+ // entry that shares the checkpoint number (e.g. an L1 reorg replacement) is not dropped.
1521
+ const indexed = await this.#rejectedCheckpointsByNumber.getAsync(stored.checkpointNumber);
1522
+ if (indexed === archiveRootHex) {
1523
+ await this.#rejectedCheckpointsByNumber.delete(stored.checkpointNumber);
1524
+ }
1525
+ }
1526
+ }
1527
+
1528
+ /**
1529
+ * Advances the stored last-synched L1 block number to `l1BlockNumber` only if it is strictly
1530
+ * greater than the current value. Use this whenever ingesting checkpoint-shaped data so the
1531
+ * sync pointer never walks backwards on out-of-order writes (e.g. an invalid checkpoint
1532
+ * advance followed by a valid-checkpoint commit landing at an earlier L1 block).
1533
+ */
1534
+ private async advanceSynchedL1BlockNumber(l1BlockNumber: bigint): Promise<void> {
1535
+ const current = await this.#lastSynchedL1Block.getAsync();
1536
+ if (current === undefined || l1BlockNumber > current) {
1537
+ await this.#lastSynchedL1Block.set(l1BlockNumber);
1538
+ }
1539
+ }
1540
+
1541
+ private rejectedCheckpointFromStorage(stored: RejectedCheckpointStorage): RejectedCheckpoint {
1542
+ return {
1543
+ checkpointNumber: CheckpointNumber(stored.checkpointNumber),
1544
+ archiveRoot: Fr.fromBuffer(stored.archiveRoot),
1545
+ parentArchiveRoot: Fr.fromBuffer(stored.parentArchiveRoot),
1546
+ slotNumber: SlotNumber(stored.slotNumber),
1547
+ l1: L1PublishedData.fromBuffer(stored.l1),
1548
+ reason: stored.reason,
1549
+ };
1550
+ }
1075
1551
  }