@aztec/archiver 0.0.1-commit.96dac018d → 0.0.1-commit.993d240

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 +36 -17
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +257 -75
  5. package/dest/config.d.ts +6 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +23 -15
  8. package/dest/errors.d.ts +55 -9
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +81 -14
  11. package/dest/factory.d.ts +13 -9
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +47 -35
  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 +2 -1
  18. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  19. package/dest/l1/calldata_retriever.js +15 -5
  20. package/dest/l1/data_retrieval.d.ts +24 -12
  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 +40 -0
  31. package/dest/modules/data_source_base.d.ts +70 -46
  32. package/dest/modules/data_source_base.d.ts.map +1 -1
  33. package/dest/modules/data_source_base.js +270 -135
  34. package/dest/modules/data_store_updater.d.ts +42 -17
  35. package/dest/modules/data_store_updater.d.ts.map +1 -1
  36. package/dest/modules/data_store_updater.js +191 -122
  37. package/dest/modules/instrumentation.d.ts +7 -2
  38. package/dest/modules/instrumentation.d.ts.map +1 -1
  39. package/dest/modules/instrumentation.js +25 -7
  40. package/dest/modules/l1_synchronizer.d.ts +12 -6
  41. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  42. package/dest/modules/l1_synchronizer.js +432 -205
  43. package/dest/modules/validation.d.ts +4 -3
  44. package/dest/modules/validation.d.ts.map +1 -1
  45. package/dest/modules/validation.js +6 -6
  46. package/dest/store/block_store.d.ts +174 -70
  47. package/dest/store/block_store.d.ts.map +1 -1
  48. package/dest/store/block_store.js +696 -250
  49. package/dest/store/contract_class_store.d.ts +17 -4
  50. package/dest/store/contract_class_store.d.ts.map +1 -1
  51. package/dest/store/contract_class_store.js +24 -68
  52. package/dest/store/contract_instance_store.d.ts +28 -1
  53. package/dest/store/contract_instance_store.d.ts.map +1 -1
  54. package/dest/store/contract_instance_store.js +37 -2
  55. package/dest/store/data_stores.d.ts +68 -0
  56. package/dest/store/data_stores.d.ts.map +1 -0
  57. package/dest/store/data_stores.js +54 -0
  58. package/dest/store/function_names_cache.d.ts +17 -0
  59. package/dest/store/function_names_cache.d.ts.map +1 -0
  60. package/dest/store/function_names_cache.js +30 -0
  61. package/dest/store/l2_tips_cache.d.ts +13 -7
  62. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  63. package/dest/store/l2_tips_cache.js +13 -76
  64. package/dest/store/log_store.d.ts +42 -37
  65. package/dest/store/log_store.d.ts.map +1 -1
  66. package/dest/store/log_store.js +262 -408
  67. package/dest/store/log_store_codec.d.ts +70 -0
  68. package/dest/store/log_store_codec.d.ts.map +1 -0
  69. package/dest/store/log_store_codec.js +101 -0
  70. package/dest/store/message_store.d.ts +11 -1
  71. package/dest/store/message_store.d.ts.map +1 -1
  72. package/dest/store/message_store.js +51 -9
  73. package/dest/test/fake_l1_state.d.ts +20 -1
  74. package/dest/test/fake_l1_state.d.ts.map +1 -1
  75. package/dest/test/fake_l1_state.js +114 -18
  76. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  77. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  78. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  79. package/dest/test/mock_l2_block_source.d.ts +52 -46
  80. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  81. package/dest/test/mock_l2_block_source.js +246 -170
  82. package/dest/test/mock_structs.d.ts +4 -1
  83. package/dest/test/mock_structs.d.ts.map +1 -1
  84. package/dest/test/mock_structs.js +13 -1
  85. package/dest/test/noop_l1_archiver.d.ts +12 -6
  86. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  87. package/dest/test/noop_l1_archiver.js +26 -9
  88. package/package.json +14 -14
  89. package/src/archiver.ts +313 -75
  90. package/src/config.ts +32 -12
  91. package/src/errors.ts +122 -21
  92. package/src/factory.ts +54 -29
  93. package/src/index.ts +18 -2
  94. package/src/l1/calldata_retriever.ts +16 -5
  95. package/src/l1/data_retrieval.ts +52 -53
  96. package/src/l1/validate_historical_logs.ts +140 -0
  97. package/src/modules/contract_data_source_adapter.ts +55 -0
  98. package/src/modules/data_source_base.ts +336 -171
  99. package/src/modules/data_store_updater.ts +224 -154
  100. package/src/modules/instrumentation.ts +28 -8
  101. package/src/modules/l1_synchronizer.ts +572 -248
  102. package/src/modules/validation.ts +10 -9
  103. package/src/store/block_store.ts +865 -290
  104. package/src/store/contract_class_store.ts +31 -103
  105. package/src/store/contract_instance_store.ts +51 -5
  106. package/src/store/data_stores.ts +104 -0
  107. package/src/store/function_names_cache.ts +37 -0
  108. package/src/store/l2_tips_cache.ts +16 -70
  109. package/src/store/log_store.ts +301 -559
  110. package/src/store/log_store_codec.ts +132 -0
  111. package/src/store/message_store.ts +60 -10
  112. package/src/structs/inbox_message.ts +1 -1
  113. package/src/test/fake_l1_state.ts +142 -29
  114. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  115. package/src/test/mock_l2_block_source.ts +309 -205
  116. package/src/test/mock_structs.ts +20 -6
  117. package/src/test/noop_l1_archiver.ts +39 -9
  118. package/dest/store/kv_archiver_store.d.ts +0 -354
  119. package/dest/store/kv_archiver_store.d.ts.map +0 -1
  120. package/dest/store/kv_archiver_store.js +0 -464
  121. package/src/store/kv_archiver_store.ts +0 -671
@@ -1,38 +1,41 @@
1
1
  import { INITIAL_CHECKPOINT_NUMBER, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
- import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint } from '@aztec/foundation/branded-types';
2
+ import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
3
3
  import { Fr } from '@aztec/foundation/curves/bn254';
4
4
  import { toArray } from '@aztec/foundation/iterable';
5
5
  import { createLogger } from '@aztec/foundation/log';
6
6
  import { BufferReader } from '@aztec/foundation/serialize';
7
7
  import { bufferToHex } from '@aztec/foundation/string';
8
8
  import { isDefined } from '@aztec/foundation/types';
9
- import { Body, CheckpointedL2Block, CommitteeAttestation, L2Block, deserializeValidateCheckpointResult, serializeValidateCheckpointResult } from '@aztec/stdlib/block';
10
- import { L1PublishedData } from '@aztec/stdlib/checkpoint';
9
+ import { BlockHash, Body, CommitteeAttestation, GENESIS_CHECKPOINT_HEADER_HASH, L2Block, deserializeValidateCheckpointResult, serializeValidateCheckpointResult } from '@aztec/stdlib/block';
10
+ import { Checkpoint, L1PublishedData } from '@aztec/stdlib/checkpoint';
11
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
11
12
  import { CheckpointHeader } from '@aztec/stdlib/rollup';
12
13
  import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
13
14
  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
+ import { BlockAlreadyCheckpointedError, BlockArchiveNotConsistentError, BlockCheckpointNumberNotSequentialError, BlockIndexNotSequentialError, BlockNotFoundError, BlockNumberNotSequentialError, CannotOverwriteCheckpointedBlockError, CheckpointNotFoundError, CheckpointNumberNotSequentialError, InitialCheckpointNumberNotSequentialError, NoProposedCheckpointToPromoteError, ProposedCheckpointArchiveRootMismatchError, ProposedCheckpointNotSequentialError, ProposedCheckpointPromotionNotSequentialError } from '../errors.js';
15
16
  export { TxReceipt } from '@aztec/stdlib/tx';
16
17
  /**
17
18
  * LMDB-based block storage for the archiver.
18
19
  */ export class BlockStore {
19
20
  db;
20
- l1Constants;
21
21
  /** Map block number to block data */ #blocks;
22
- /** Map checkpoint number to checkpoint data */ #checkpoints;
22
+ /** Map keyed by checkpoint number holding proposed (locally-validated, not yet L1-confirmed) checkpoints. */ #proposedCheckpoints;
23
+ /** Map checkpoint number to checkpoint data for mined checkpoints only */ #checkpoints;
23
24
  /** Map slot number to checkpoint number, for looking up checkpoints by slot range. */ #slotToCheckpoint;
24
25
  /** Map block hash to list of tx hashes */ #blockTxs;
25
26
  /** Tx hash to serialized IndexedTxEffect */ #txEffects;
26
27
  /** Stores L1 block number in which the last processed L2 block was included */ #lastSynchedL1Block;
27
28
  /** Stores last proven checkpoint */ #lastProvenCheckpoint;
29
+ /** Stores last finalized checkpoint (proven at or before the finalized L1 block) */ #lastFinalizedCheckpoint;
28
30
  /** Stores the pending chain validation status */ #pendingChainValidationStatus;
29
31
  /** Index mapping a contract's address (as a string) to its location in a block */ #contractIndex;
30
32
  /** Index mapping block hash to block number */ #blockHashIndex;
31
33
  /** Index mapping block archive to block number */ #blockArchiveIndex;
34
+ /** Map rejected checkpoints (due to invalid attestations) by archive root */ #rejectedCheckpoints;
35
+ /** Index mapping a rejected checkpoint's number to its archive root, so the latest can be read in reverse order */ #rejectedCheckpointsByNumber;
32
36
  #log;
33
- constructor(db, l1Constants){
37
+ constructor(db){
34
38
  this.db = db;
35
- this.l1Constants = l1Constants;
36
39
  this.#log = createLogger('archiver:block_store');
37
40
  this.#blocks = db.openMap('archiver_blocks');
38
41
  this.#blockTxs = db.openMap('archiver_block_txs');
@@ -42,95 +45,98 @@ export { TxReceipt } from '@aztec/stdlib/tx';
42
45
  this.#blockArchiveIndex = db.openMap('archiver_block_archive_index');
43
46
  this.#lastSynchedL1Block = db.openSingleton('archiver_last_synched_l1_block');
44
47
  this.#lastProvenCheckpoint = db.openSingleton('archiver_last_proven_l2_checkpoint');
48
+ this.#lastFinalizedCheckpoint = db.openSingleton('archiver_last_finalized_l2_checkpoint');
45
49
  this.#pendingChainValidationStatus = db.openSingleton('archiver_pending_chain_validation_status');
46
50
  this.#checkpoints = db.openMap('archiver_checkpoints');
47
51
  this.#slotToCheckpoint = db.openMap('archiver_slot_to_checkpoint');
52
+ this.#proposedCheckpoints = db.openMap('archiver_proposed_checkpoints');
53
+ this.#rejectedCheckpoints = db.openMap('archiver_rejected_checkpoints');
54
+ this.#rejectedCheckpointsByNumber = db.openMap('archiver_rejected_checkpoints_by_number');
48
55
  }
49
56
  /**
50
- * Computes the finalized block number based on the proven block number.
51
- * A block is considered finalized when it's 2 epochs behind the proven block.
52
- * TODO(#13569): Compute proper finalized block number based on L1 finalized block.
53
- * TODO(palla/mbps): Even the provisional computation is wrong, since it should subtract checkpoints, not blocks
57
+ * Returns the finalized L2 block number. An L2 block is finalized when it was proven
58
+ * in an L1 block that has itself been finalized on Ethereum.
54
59
  * @returns The finalized block number.
55
60
  */ async getFinalizedL2BlockNumber() {
56
- const provenBlockNumber = await this.getProvenBlockNumber();
57
- return BlockNumber(Math.max(provenBlockNumber - this.l1Constants.epochDuration * 2, 0));
61
+ const finalizedCheckpointNumber = await this.getFinalizedCheckpointNumber();
62
+ if (finalizedCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
63
+ return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
64
+ }
65
+ const checkpointStorage = await this.#checkpoints.getAsync(finalizedCheckpointNumber);
66
+ if (!checkpointStorage) {
67
+ throw new CheckpointNotFoundError(finalizedCheckpointNumber);
68
+ }
69
+ return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
58
70
  }
59
71
  /**
60
- * Append new proposed blocks to the store's list. All blocks must be for the 'current' checkpoint.
61
- * These are uncheckpointed blocks that have been proposed by the sequencer but not yet included in a checkpoint on L1.
72
+ * Append a new proposed block to the store.
73
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
62
74
  * For checkpointed blocks (already published to L1), use addCheckpoints() instead.
63
- * @param blocks - The proposed L2 blocks to be added to the store.
75
+ * @param block - The proposed L2 block to be added to the store.
64
76
  * @returns True if the operation is successful.
65
- */ async addProposedBlocks(blocks, opts = {}) {
66
- if (blocks.length === 0) {
67
- return true;
68
- }
77
+ */ async addProposedBlock(block, opts = {}) {
69
78
  return await this.db.transactionAsync(async ()=>{
70
- // Check that the block immediately before the first block to be added is present in the store.
71
- const firstBlockNumber = blocks[0].number;
72
- const firstBlockCheckpointNumber = blocks[0].checkpointNumber;
73
- const firstBlockIndex = blocks[0].indexWithinCheckpoint;
74
- const firstBlockLastArchive = blocks[0].header.lastArchive.root;
79
+ const blockNumber = block.number;
80
+ const blockCheckpointNumber = block.checkpointNumber;
81
+ const blockIndex = block.indexWithinCheckpoint;
82
+ const blockLastArchive = block.header.lastArchive.root;
75
83
  // Extract the latest block and checkpoint numbers
76
- const previousBlockNumber = await this.getLatestBlockNumber();
77
- const previousCheckpointNumber = await this.getLatestCheckpointNumber();
84
+ const previousBlockNumber = await this.getLatestL2BlockNumber();
85
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
78
86
  // Verify we're not overwriting checkpointed blocks
79
87
  const lastCheckpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
80
- if (!opts.force && firstBlockNumber <= lastCheckpointedBlockNumber) {
81
- throw new CannotOverwriteCheckpointedBlockError(firstBlockNumber, lastCheckpointedBlockNumber);
88
+ if (!opts.force && blockNumber <= lastCheckpointedBlockNumber) {
89
+ // Check if the proposed block matches the already-checkpointed one
90
+ const existingBlock = await this.getBlockData({
91
+ number: BlockNumber(blockNumber)
92
+ });
93
+ if (existingBlock && existingBlock.archive.root.equals(block.archive.root)) {
94
+ throw new BlockAlreadyCheckpointedError(blockNumber);
95
+ }
96
+ throw new CannotOverwriteCheckpointedBlockError(blockNumber, lastCheckpointedBlockNumber);
82
97
  }
83
- // Check that the first block number is the expected one
84
- if (!opts.force && previousBlockNumber !== firstBlockNumber - 1) {
85
- throw new InitialBlockNumberNotSequentialError(firstBlockNumber, previousBlockNumber);
98
+ // Check that the block number is the expected one
99
+ if (!opts.force && previousBlockNumber !== blockNumber - 1) {
100
+ throw new BlockNumberNotSequentialError(blockNumber, previousBlockNumber);
86
101
  }
87
- // The same check as above but for checkpoints
88
- if (!opts.force && previousCheckpointNumber !== firstBlockCheckpointNumber - 1) {
89
- throw new InitialCheckpointNumberNotSequentialError(firstBlockCheckpointNumber, previousCheckpointNumber);
102
+ // Accept the block if either the confirmed checkpoint or a pending checkpoint matches
103
+ // the expected predecessor. We look for a pending entry at exactly blockCheckpointNumber - 1.
104
+ const expectedCheckpointNumber = blockCheckpointNumber - 1;
105
+ const hasPendingAtExpected = await this.#proposedCheckpoints.hasAsync(expectedCheckpointNumber);
106
+ if (!opts.force && latestCheckpointNumber !== expectedCheckpointNumber && !hasPendingAtExpected) {
107
+ const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({
108
+ reverse: true,
109
+ limit: 1
110
+ }));
111
+ const previous = CheckpointNumber(Math.max(latestCheckpointNumber, latestPendingKey ?? 0));
112
+ throw new BlockCheckpointNumberNotSequentialError(BlockNumber(blockNumber), blockCheckpointNumber, previous);
90
113
  }
91
114
  // Extract the previous block if there is one and see if it is for the same checkpoint or not
92
- const previousBlockResult = await this.getBlock(previousBlockNumber);
93
- let expectedFirstblockIndex = 0;
115
+ const previousBlockResult = await this.getBlockData({
116
+ number: previousBlockNumber
117
+ });
118
+ let expectedBlockIndex = 0;
94
119
  let previousBlockIndex = undefined;
95
120
  if (previousBlockResult !== undefined) {
96
- if (previousBlockResult.checkpointNumber === firstBlockCheckpointNumber) {
121
+ if (previousBlockResult.checkpointNumber === blockCheckpointNumber) {
97
122
  // The previous block is for the same checkpoint, therefore our index should follow it
98
123
  previousBlockIndex = previousBlockResult.indexWithinCheckpoint;
99
- expectedFirstblockIndex = previousBlockIndex + 1;
124
+ expectedBlockIndex = previousBlockIndex + 1;
100
125
  }
101
- if (!previousBlockResult.archive.root.equals(firstBlockLastArchive)) {
102
- throw new BlockArchiveNotConsistentError(firstBlockNumber, previousBlockResult.number, firstBlockLastArchive, previousBlockResult.archive.root);
126
+ if (!previousBlockResult.archive.root.equals(blockLastArchive)) {
127
+ throw new BlockArchiveNotConsistentError(blockNumber, previousBlockResult.header.globalVariables.blockNumber, blockLastArchive, previousBlockResult.archive.root);
103
128
  }
104
129
  }
105
- // Now check that the first block has the expected index value
106
- if (!opts.force && expectedFirstblockIndex !== firstBlockIndex) {
107
- throw new BlockIndexNotSequentialError(firstBlockIndex, previousBlockIndex);
108
- }
109
- // Iterate over blocks array and insert them, checking that the block numbers and indexes are sequential. Also check they are for the correct checkpoint.
110
- let previousBlock = undefined;
111
- for (const block of blocks){
112
- if (!opts.force && previousBlock) {
113
- if (previousBlock.number + 1 !== block.number) {
114
- throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
115
- }
116
- if (previousBlock.indexWithinCheckpoint + 1 !== block.indexWithinCheckpoint) {
117
- throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
118
- }
119
- if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
120
- throw new BlockArchiveNotConsistentError(block.number, previousBlock.number, block.header.lastArchive.root, previousBlock.archive.root);
121
- }
122
- }
123
- if (!opts.force && firstBlockCheckpointNumber !== block.checkpointNumber) {
124
- throw new CheckpointNumberNotConsistentError(block.checkpointNumber, firstBlockCheckpointNumber);
125
- }
126
- previousBlock = block;
127
- await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
130
+ // Now check that the block has the expected index value
131
+ if (!opts.force && expectedBlockIndex !== blockIndex) {
132
+ throw new BlockIndexNotSequentialError(blockIndex, previousBlockIndex);
128
133
  }
134
+ await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
129
135
  return true;
130
136
  });
131
137
  }
132
138
  /**
133
- * Append new cheskpoints to the store's list.
139
+ * Append new checkpoints to the store's list.
134
140
  * @param checkpoints - The L2 checkpoints to be added to the store.
135
141
  * @returns True if the operation is successful.
136
142
  */ async addCheckpoints(checkpoints, opts = {}) {
@@ -138,32 +144,26 @@ export { TxReceipt } from '@aztec/stdlib/tx';
138
144
  return true;
139
145
  }
140
146
  return await this.db.transactionAsync(async ()=>{
141
- // Check that the checkpoint immediately before the first block to be added is present in the store.
142
147
  const firstCheckpointNumber = checkpoints[0].checkpoint.number;
143
148
  const previousCheckpointNumber = await this.getLatestCheckpointNumber();
144
- if (previousCheckpointNumber !== firstCheckpointNumber - 1 && !opts.force) {
145
- throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
146
- }
147
- // Extract the previous checkpoint if there is one
148
- let previousCheckpointData = undefined;
149
- if (previousCheckpointNumber !== INITIAL_CHECKPOINT_NUMBER - 1) {
150
- // There should be a previous checkpoint
151
- previousCheckpointData = await this.getCheckpointData(previousCheckpointNumber);
152
- if (previousCheckpointData === undefined) {
153
- throw new CheckpointNotFoundError(previousCheckpointNumber);
149
+ // Handle already-stored checkpoints at the start of the batch.
150
+ // This can happen after an L1 reorg re-includes a checkpoint in a different L1 block.
151
+ // We accept them if archives match (same content) and update their L1 metadata.
152
+ if (!opts.force && firstCheckpointNumber <= previousCheckpointNumber) {
153
+ checkpoints = await this.skipOrUpdateAlreadyStoredCheckpoints(checkpoints, previousCheckpointNumber);
154
+ if (checkpoints.length === 0) {
155
+ return true;
154
156
  }
155
- }
156
- let previousBlockNumber = undefined;
157
- let previousBlock = undefined;
158
- // If we have a previous checkpoint then we need to get the previous block number
159
- if (previousCheckpointData !== undefined) {
160
- previousBlockNumber = BlockNumber(previousCheckpointData.startBlock + previousCheckpointData.blockCount - 1);
161
- previousBlock = await this.getBlock(previousBlockNumber);
162
- if (previousBlock === undefined) {
163
- // We should be able to get the required previous block
164
- throw new BlockNotFoundError(previousBlockNumber);
157
+ // Re-check sequentiality after skipping
158
+ const newFirstNumber = checkpoints[0].checkpoint.number;
159
+ if (previousCheckpointNumber !== newFirstNumber - 1) {
160
+ throw new InitialCheckpointNumberNotSequentialError(newFirstNumber, previousCheckpointNumber);
165
161
  }
162
+ } else if (previousCheckpointNumber !== firstCheckpointNumber - 1 && !opts.force) {
163
+ throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
166
164
  }
165
+ // Get the last block of the previous checkpoint for archive chaining
166
+ let previousBlock = await this.getPreviousCheckpointBlock(checkpoints[0].checkpoint.number);
167
167
  // Iterate over checkpoints array and insert them, checking that the block numbers are sequential.
168
168
  let previousCheckpoint = undefined;
169
169
  for (const checkpoint of checkpoints){
@@ -171,33 +171,13 @@ export { TxReceipt } from '@aztec/stdlib/tx';
171
171
  throw new CheckpointNumberNotSequentialError(checkpoint.checkpoint.number, previousCheckpoint.checkpoint.number);
172
172
  }
173
173
  previousCheckpoint = checkpoint;
174
- // Store every block in the database. the block may already exist, but this has come from chain and is assumed to be correct.
174
+ // Validate block sequencing, indexes, and archive chaining
175
+ this.validateCheckpointBlocks(checkpoint.checkpoint.blocks, previousBlock);
176
+ // Store every block in the database (may already exist, but L1 data is authoritative)
175
177
  for(let i = 0; i < checkpoint.checkpoint.blocks.length; i++){
176
- const block = checkpoint.checkpoint.blocks[i];
177
- if (previousBlock) {
178
- // The blocks should have a sequential block number
179
- if (previousBlock.number !== block.number - 1) {
180
- throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
181
- }
182
- // If the blocks are for the same checkpoint then they should have sequential indexes
183
- if (previousBlock.checkpointNumber === block.checkpointNumber && previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1) {
184
- throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
185
- }
186
- if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
187
- throw new BlockArchiveNotConsistentError(block.number, previousBlock.number, block.header.lastArchive.root, previousBlock.archive.root);
188
- }
189
- } else {
190
- // No previous block, must be block 1 at checkpoint index 0
191
- if (block.indexWithinCheckpoint !== 0) {
192
- throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
193
- }
194
- if (block.number !== INITIAL_L2_BLOCK_NUM) {
195
- throw new BlockNumberNotSequentialError(block.number, undefined);
196
- }
197
- }
198
- previousBlock = block;
199
- await this.addBlockToDatabase(block, checkpoint.checkpoint.number, i);
178
+ await this.addBlockToDatabase(checkpoint.checkpoint.blocks[i], checkpoint.checkpoint.number, i);
200
179
  }
180
+ previousBlock = checkpoint.checkpoint.blocks.at(-1);
201
181
  // Store the checkpoint in the database
202
182
  await this.#checkpoints.set(checkpoint.checkpoint.number, {
203
183
  header: checkpoint.checkpoint.header.toBuffer(),
@@ -207,15 +187,107 @@ export { TxReceipt } from '@aztec/stdlib/tx';
207
187
  attestations: checkpoint.attestations.map((attestation)=>attestation.toBuffer()),
208
188
  checkpointNumber: checkpoint.checkpoint.number,
209
189
  startBlock: checkpoint.checkpoint.blocks[0].number,
210
- blockCount: checkpoint.checkpoint.blocks.length
190
+ blockCount: checkpoint.checkpoint.blocks.length,
191
+ feeAssetPriceModifier: checkpoint.checkpoint.feeAssetPriceModifier.toString()
211
192
  });
212
193
  // Update slot-to-checkpoint index
213
194
  await this.#slotToCheckpoint.set(checkpoint.checkpoint.header.slotNumber, checkpoint.checkpoint.number);
195
+ // Remove proposed checkpoint if it exists, since L1 is authoritative
196
+ await this.#proposedCheckpoints.delete(checkpoint.checkpoint.number);
197
+ // Drop any rejected entry for this archive root: a checkpoint that was previously rejected
198
+ // (e.g. invalid attestations) is now being ingested as valid, so its descendants are allowed.
199
+ await this.removeRejectedCheckpointByArchiveRoot(checkpoint.checkpoint.archive.root);
214
200
  }
215
- await this.#lastSynchedL1Block.set(checkpoints[checkpoints.length - 1].l1.blockNumber);
201
+ await this.advanceSynchedL1BlockNumber(checkpoints[checkpoints.length - 1].l1.blockNumber);
216
202
  return true;
217
203
  });
218
204
  }
205
+ /**
206
+ * Handles checkpoints at the start of a batch that are already stored (e.g. due to L1 reorg).
207
+ * Verifies the archive root matches, updates L1 metadata, and returns only the new checkpoints.
208
+ */ async skipOrUpdateAlreadyStoredCheckpoints(checkpoints, latestStored) {
209
+ let i = 0;
210
+ for(; i < checkpoints.length && checkpoints[i].checkpoint.number <= latestStored; i++){
211
+ const incoming = checkpoints[i];
212
+ const stored = await this.getCheckpointData(incoming.checkpoint.number);
213
+ if (!stored) {
214
+ break;
215
+ }
216
+ // Verify the checkpoint content matches (archive root)
217
+ if (!stored.archive.root.equals(incoming.checkpoint.archive.root)) {
218
+ throw new Error(`Checkpoint ${incoming.checkpoint.number} already exists in store but with a different archive root. ` + `Stored: ${stored.archive.root}, incoming: ${incoming.checkpoint.archive.root}`);
219
+ }
220
+ // Update L1 metadata and attestations for the already-stored checkpoint
221
+ this.#log.warn(`Checkpoint ${incoming.checkpoint.number} already stored, updating L1 info ` + `(L1 block ${stored.l1.blockNumber} -> ${incoming.l1.blockNumber})`);
222
+ await this.#checkpoints.set(incoming.checkpoint.number, {
223
+ header: incoming.checkpoint.header.toBuffer(),
224
+ archive: incoming.checkpoint.archive.toBuffer(),
225
+ checkpointOutHash: incoming.checkpoint.getCheckpointOutHash().toBuffer(),
226
+ l1: incoming.l1.toBuffer(),
227
+ attestations: incoming.attestations.map((a)=>a.toBuffer()),
228
+ checkpointNumber: incoming.checkpoint.number,
229
+ startBlock: incoming.checkpoint.blocks[0].number,
230
+ blockCount: incoming.checkpoint.blocks.length,
231
+ feeAssetPriceModifier: incoming.checkpoint.feeAssetPriceModifier.toString()
232
+ });
233
+ // Update the sync point to reflect the new L1 block
234
+ await this.advanceSynchedL1BlockNumber(incoming.l1.blockNumber);
235
+ }
236
+ return checkpoints.slice(i);
237
+ }
238
+ /**
239
+ * Gets the last block of the checkpoint before the given one.
240
+ * Returns undefined if there is no previous checkpoint (i.e. genesis).
241
+ */ async getPreviousCheckpointBlock(checkpointNumber) {
242
+ const previousCheckpointNumber = CheckpointNumber(checkpointNumber - 1);
243
+ if (previousCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
244
+ return undefined;
245
+ }
246
+ // Check across both proposed and mined checkpoints
247
+ const predecessor = await this.getProposedCheckpointByNumber(previousCheckpointNumber) ?? await this.getCheckpointData(previousCheckpointNumber);
248
+ if (!predecessor) {
249
+ throw new CheckpointNotFoundError(previousCheckpointNumber);
250
+ }
251
+ const previousBlockNumber = BlockNumber(predecessor.startBlock + predecessor.blockCount - 1);
252
+ const previousBlock = await this.getBlock({
253
+ number: previousBlockNumber
254
+ });
255
+ if (previousBlock === undefined) {
256
+ throw new BlockNotFoundError(previousBlockNumber);
257
+ }
258
+ return previousBlock;
259
+ }
260
+ /**
261
+ * Validates that blocks are sequential, have correct indexes, and chain via archive roots.
262
+ * This is the same validation used for both confirmed checkpoints (addCheckpoints) and
263
+ * proposed checkpoints (addProposedCheckpoint).
264
+ */ validateCheckpointBlocks(blocks, previousBlock) {
265
+ for (const block of blocks){
266
+ if (previousBlock) {
267
+ if (previousBlock.number !== block.number - 1) {
268
+ throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
269
+ }
270
+ if (previousBlock.checkpointNumber === block.checkpointNumber) {
271
+ if (previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1) {
272
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
273
+ }
274
+ } else if (block.indexWithinCheckpoint !== 0) {
275
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
276
+ }
277
+ if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
278
+ throw new BlockArchiveNotConsistentError(block.number, previousBlock.number, block.header.lastArchive.root, previousBlock.archive.root);
279
+ }
280
+ } else {
281
+ if (block.indexWithinCheckpoint !== 0) {
282
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
283
+ }
284
+ if (block.number !== INITIAL_L2_BLOCK_NUM) {
285
+ throw new BlockNumberNotSequentialError(block.number, undefined);
286
+ }
287
+ }
288
+ previousBlock = block;
289
+ }
290
+ }
219
291
  async addBlockToDatabase(block, checkpointNumber, indexWithinCheckpoint) {
220
292
  const blockHash = await block.hash();
221
293
  await this.#blocks.set(block.number, {
@@ -293,6 +365,8 @@ export { TxReceipt } from '@aztec/stdlib/tx';
293
365
  await this.#checkpoints.delete(c);
294
366
  this.#log.debug(`Removed checkpoint ${c}`);
295
367
  }
368
+ // Evict all pending checkpoints > checkpointNumber (their base chain no longer exists)
369
+ await this.evictProposedCheckpointsFrom(CheckpointNumber(checkpointNumber + 1));
296
370
  return {
297
371
  blocksRemoved
298
372
  };
@@ -329,6 +403,20 @@ export { TxReceipt } from '@aztec/stdlib/tx';
329
403
  }
330
404
  return result;
331
405
  }
406
+ /**
407
+ * Returns the checkpoint numbers for all checkpoints whose slot falls within the given range (inclusive).
408
+ * Lighter than {@link getCheckpointDataForSlotRange} when callers only need to identify which
409
+ * checkpoints fall in the range and will fetch full data for at most a few of them.
410
+ */ async getCheckpointNumbersForSlotRange(startSlot, endSlot) {
411
+ const result = [];
412
+ for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync({
413
+ start: startSlot,
414
+ end: endSlot + 1
415
+ })){
416
+ result.push(CheckpointNumber(checkpointNumber));
417
+ }
418
+ return result;
419
+ }
332
420
  checkpointDataFromCheckpointStorage(checkpointStorage) {
333
421
  return {
334
422
  header: CheckpointHeader.fromBuffer(checkpointStorage.header),
@@ -337,6 +425,7 @@ export { TxReceipt } from '@aztec/stdlib/tx';
337
425
  checkpointNumber: CheckpointNumber(checkpointStorage.checkpointNumber),
338
426
  startBlock: BlockNumber(checkpointStorage.startBlock),
339
427
  blockCount: checkpointStorage.blockCount,
428
+ feeAssetPriceModifier: BigInt(checkpointStorage.feeAssetPriceModifier),
340
429
  l1: L1PublishedData.fromBuffer(checkpointStorage.l1),
341
430
  attestations: checkpointStorage.attestations.map((buf)=>CommitteeAttestation.fromBuffer(buf))
342
431
  };
@@ -385,10 +474,12 @@ export { TxReceipt } from '@aztec/stdlib/tx';
385
474
  return await this.db.transactionAsync(async ()=>{
386
475
  const removedBlocks = [];
387
476
  // Get the latest block number to determine the range
388
- const latestBlockNumber = await this.getLatestBlockNumber();
477
+ const latestBlockNumber = await this.getLatestL2BlockNumber();
389
478
  // Iterate from blockNumber + 1 to latestBlockNumber
390
479
  for(let bn = blockNumber + 1; bn <= latestBlockNumber; bn++){
391
- const block = await this.getBlock(BlockNumber(bn));
480
+ const block = await this.getBlock({
481
+ number: BlockNumber(bn)
482
+ });
392
483
  if (block === undefined) {
393
484
  this.#log.warn(`Cannot remove block ${bn} from the store since we don't have it`);
394
485
  continue;
@@ -412,13 +503,6 @@ export { TxReceipt } from '@aztec/stdlib/tx';
412
503
  return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
413
504
  }
414
505
  }
415
- async getLatestBlockNumber() {
416
- const [latestBlocknumber] = await toArray(this.#blocks.keysAsync({
417
- reverse: true,
418
- limit: 1
419
- }));
420
- return typeof latestBlocknumber === 'number' ? BlockNumber(latestBlocknumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
421
- }
422
506
  async getLatestCheckpointNumber() {
423
507
  const [latestCheckpointNumber] = await toArray(this.#checkpoints.keysAsync({
424
508
  reverse: true,
@@ -429,143 +513,171 @@ export { TxReceipt } from '@aztec/stdlib/tx';
429
513
  }
430
514
  return CheckpointNumber(latestCheckpointNumber);
431
515
  }
432
- async getCheckpointedBlock(number) {
433
- const blockStorage = await this.#blocks.getAsync(number);
434
- if (!blockStorage) {
435
- return undefined;
436
- }
437
- const checkpoint = await this.#checkpoints.getAsync(blockStorage.checkpointNumber);
438
- if (!checkpoint) {
439
- return undefined;
440
- }
441
- const block = await this.getBlockFromBlockStorage(number, blockStorage);
442
- if (!block) {
443
- return undefined;
516
+ async hasProposedCheckpoint() {
517
+ const [key] = await toArray(this.#proposedCheckpoints.keysAsync({
518
+ limit: 1
519
+ }));
520
+ return key !== undefined;
521
+ }
522
+ /** Deletes all pending proposed checkpoints from storage. */ async deleteProposedCheckpoints() {
523
+ for await (const key of this.#proposedCheckpoints.keysAsync()){
524
+ await this.#proposedCheckpoints.delete(key);
444
525
  }
445
- return new CheckpointedL2Block(CheckpointNumber(checkpoint.checkpointNumber), block, L1PublishedData.fromBuffer(checkpoint.l1), checkpoint.attestations.map((buf)=>CommitteeAttestation.fromBuffer(buf)));
446
526
  }
447
527
  /**
448
- * Gets up to `limit` amount of Checkpointed L2 blocks starting from `from`.
449
- * @param start - Number of the first block to return (inclusive).
450
- * @param limit - The number of blocks to return.
451
- * @returns The requested L2 blocks
452
- */ async *getCheckpointedBlocks(start, limit) {
453
- const checkpointCache = new Map();
454
- for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)){
455
- const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
456
- if (block) {
457
- const checkpoint = checkpointCache.get(CheckpointNumber(blockStorage.checkpointNumber)) ?? await this.#checkpoints.getAsync(blockStorage.checkpointNumber);
458
- if (checkpoint) {
459
- checkpointCache.set(CheckpointNumber(blockStorage.checkpointNumber), checkpoint);
460
- const checkpointedBlock = new CheckpointedL2Block(CheckpointNumber(checkpoint.checkpointNumber), block, L1PublishedData.fromBuffer(checkpoint.l1), checkpoint.attestations.map((buf)=>CommitteeAttestation.fromBuffer(buf)));
461
- yield checkpointedBlock;
462
- }
528
+ * Promotes a specific pending checkpoint to a confirmed checkpoint entry.
529
+ * This persists the checkpoint to the store, removes only that pending entry, and updates the L1 sync point.
530
+ * Remaining pending entries (e.g. N+1, N+2) are left intact — they chain off the just-promoted one.
531
+ * @param checkpointNumber - The checkpoint number to promote.
532
+ * @param l1 - L1 published data for the checkpoint.
533
+ * @param attestations - Committee attestations.
534
+ * @param expectedArchiveRoot - Archive root guard against races.
535
+ */ async promoteProposedToCheckpointed(checkpointNumber, l1, attestations, expectedArchiveRoot) {
536
+ return await this.db.transactionAsync(async ()=>{
537
+ const proposed = await this.getProposedCheckpointByNumber(checkpointNumber);
538
+ if (!proposed) {
539
+ throw new NoProposedCheckpointToPromoteError();
463
540
  }
464
- }
541
+ if (!proposed.archive.root.equals(expectedArchiveRoot)) {
542
+ throw new ProposedCheckpointArchiveRootMismatchError(expectedArchiveRoot, proposed.archive.root);
543
+ }
544
+ // Verify sequentiality: promoted checkpoint must follow the latest confirmed one
545
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
546
+ if (latestCheckpointNumber !== proposed.checkpointNumber - 1) {
547
+ throw new ProposedCheckpointPromotionNotSequentialError(proposed.checkpointNumber, latestCheckpointNumber);
548
+ }
549
+ // Write the checkpoint entry
550
+ await this.#checkpoints.set(proposed.checkpointNumber, {
551
+ header: proposed.header.toBuffer(),
552
+ archive: proposed.archive.toBuffer(),
553
+ checkpointOutHash: proposed.checkpointOutHash.toBuffer(),
554
+ l1: l1.toBuffer(),
555
+ attestations: attestations.map((attestation)=>attestation.toBuffer()),
556
+ checkpointNumber: proposed.checkpointNumber,
557
+ startBlock: proposed.startBlock,
558
+ blockCount: proposed.blockCount,
559
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString()
560
+ });
561
+ // Update the slot-to-checkpoint index
562
+ await this.#slotToCheckpoint.set(proposed.header.slotNumber, proposed.checkpointNumber);
563
+ // Remove only this pending entry — remaining entries N+1, N+2, ... stay valid
564
+ await this.#proposedCheckpoints.delete(proposed.checkpointNumber);
565
+ // Drop any rejected entry for this archive root: a checkpoint that was previously rejected
566
+ // (e.g. invalid attestations) is now being promoted as valid, so its descendants are allowed.
567
+ await this.removeRejectedCheckpointByArchiveRoot(proposed.archive.root);
568
+ // Update the last synced L1 block
569
+ await this.advanceSynchedL1BlockNumber(l1.blockNumber);
570
+ });
465
571
  }
466
- async getCheckpointedBlockByHash(blockHash) {
467
- const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
468
- if (blockNumber === undefined) {
572
+ /**
573
+ * Returns the latest pending checkpoint (highest-numbered entry), or undefined if none.
574
+ * No fallback to confirmed.
575
+ */ async getLastProposedCheckpoint() {
576
+ const [key] = await toArray(this.#proposedCheckpoints.keysAsync({
577
+ reverse: true,
578
+ limit: 1
579
+ }));
580
+ if (key === undefined) {
469
581
  return undefined;
470
582
  }
471
- return this.getCheckpointedBlock(BlockNumber(blockNumber));
583
+ const stored = await this.#proposedCheckpoints.getAsync(key);
584
+ return stored ? this.convertToProposedCheckpointData(stored) : undefined;
472
585
  }
473
- async getCheckpointedBlockByArchive(archive) {
474
- const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
475
- if (blockNumber === undefined) {
476
- return undefined;
477
- }
478
- return this.getCheckpointedBlock(BlockNumber(blockNumber));
586
+ /** Returns the pending checkpoint for a specific checkpoint number, or undefined if not found. */ async getProposedCheckpointByNumber(n) {
587
+ const stored = await this.#proposedCheckpoints.getAsync(n);
588
+ return stored ? this.convertToProposedCheckpointData(stored) : undefined;
479
589
  }
480
590
  /**
481
- * Gets up to `limit` amount of L2 blocks starting from `from`.
482
- * @param start - Number of the first block to return (inclusive).
483
- * @param limit - The number of blocks to return.
484
- * @returns The requested L2 blocks
485
- */ async *getBlocks(start, limit) {
486
- for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)){
487
- const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
488
- if (block) {
489
- yield block;
591
+ * Returns the pending checkpoint whose header slot matches the given slot, or undefined if not found.
592
+ * Iterates `#proposedCheckpoints` rather than reading an index because the map carries 0–1 entries
593
+ * in normal operation (bounded by the proposer pipelining window). Returns the first match.
594
+ */ async getProposedCheckpointBySlot(slot) {
595
+ for await (const [, stored] of this.#proposedCheckpoints.entriesAsync()){
596
+ const header = CheckpointHeader.fromBuffer(stored.header);
597
+ if (header.slotNumber === slot) {
598
+ return this.convertToProposedCheckpointData(stored);
490
599
  }
491
600
  }
601
+ return undefined;
492
602
  }
493
603
  /**
494
- * Gets block metadata (without tx data) by block number.
495
- * @param blockNumber - The number of the block to return.
496
- * @returns The requested block data.
497
- */ async getBlockData(blockNumber) {
498
- const blockStorage = await this.#blocks.getAsync(blockNumber);
499
- if (!blockStorage || !blockStorage.header) {
500
- return undefined;
604
+ * Evicts all pending checkpoints with checkpoint number >= fromNumber.
605
+ * Used for divergent-mined-checkpoint cleanup: when L1 mines checkpoint N with a different archive,
606
+ * all pending >= N must be evicted since they chain off the now-invalid pending N.
607
+ */ async evictProposedCheckpointsFrom(fromNumber) {
608
+ const keysToDelete = [];
609
+ for await (const key of this.#proposedCheckpoints.keysAsync()){
610
+ if (key >= fromNumber) {
611
+ keysToDelete.push(key);
612
+ }
501
613
  }
502
- return this.getBlockDataFromBlockStorage(blockStorage);
503
- }
504
- /**
505
- * Gets block metadata (without tx data) by archive root.
506
- * @param archive - The archive root of the block to return.
507
- * @returns The requested block data.
508
- */ async getBlockDataByArchive(archive) {
509
- const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
510
- if (blockNumber === undefined) {
511
- return undefined;
614
+ for (const key of keysToDelete){
615
+ await this.#proposedCheckpoints.delete(key);
512
616
  }
513
- return this.getBlockData(BlockNumber(blockNumber));
514
617
  }
515
618
  /**
516
- * Gets an L2 block.
517
- * @param blockNumber - The number of the block to return.
518
- * @returns The requested L2 block.
519
- */ async getBlock(blockNumber) {
520
- const blockStorage = await this.#blocks.getAsync(blockNumber);
521
- if (!blockStorage || !blockStorage.header) {
522
- return Promise.resolve(undefined);
619
+ * Gets the checkpoint at the proposed tip:
620
+ * - latest pending checkpoint if any exist
621
+ * - fallsback to latest confirmed checkpoint otherwise
622
+ */ async getLastCheckpoint() {
623
+ const latest = await this.getLastProposedCheckpoint();
624
+ if (!latest) {
625
+ return this.getCheckpointData(await this.getLatestCheckpointNumber());
523
626
  }
524
- return this.getBlockFromBlockStorage(blockNumber, blockStorage);
627
+ return latest;
628
+ }
629
+ convertToProposedCheckpointData(stored) {
630
+ return {
631
+ checkpointNumber: CheckpointNumber(stored.checkpointNumber),
632
+ header: CheckpointHeader.fromBuffer(stored.header),
633
+ archive: AppendOnlyTreeSnapshot.fromBuffer(stored.archive),
634
+ checkpointOutHash: Fr.fromBuffer(stored.checkpointOutHash),
635
+ startBlock: BlockNumber(stored.startBlock),
636
+ blockCount: stored.blockCount,
637
+ totalManaUsed: BigInt(stored.totalManaUsed),
638
+ feeAssetPriceModifier: BigInt(stored.feeAssetPriceModifier)
639
+ };
525
640
  }
526
641
  /**
527
- * Gets an L2 block by its hash.
528
- * @param blockHash - The hash of the block to return.
529
- * @returns The requested L2 block.
530
- */ async getBlockByHash(blockHash) {
531
- const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
532
- if (blockNumber === undefined) {
533
- return undefined;
642
+ * Attempts to get the proposedCheckpoint's number, if there is not one, then fallback to the latest confirmed checkpoint number.
643
+ * @returns CheckpointNumber
644
+ */ async getProposedCheckpointNumber() {
645
+ const proposed = await this.getLastCheckpoint();
646
+ if (!proposed) {
647
+ return await this.getLatestCheckpointNumber();
534
648
  }
535
- return this.getBlock(BlockNumber(blockNumber));
649
+ return CheckpointNumber(proposed.checkpointNumber);
536
650
  }
537
651
  /**
538
- * Gets an L2 block by its archive root.
539
- * @param archive - The archive root of the block to return.
540
- * @returns The requested L2 block.
541
- */ async getBlockByArchive(archive) {
542
- const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
543
- if (blockNumber === undefined) {
544
- return undefined;
652
+ * Attempts to get the proposedCheckpoint's block number, if there is not one, then fallback to the checkpointed block number
653
+ * @returns BlockNumber
654
+ */ async getProposedCheckpointL2BlockNumber() {
655
+ const proposed = await this.getLastCheckpoint();
656
+ if (!proposed) {
657
+ return await this.getCheckpointedL2BlockNumber();
545
658
  }
546
- return this.getBlock(BlockNumber(blockNumber));
659
+ return BlockNumber(proposed.startBlock + proposed.blockCount - 1);
547
660
  }
548
- /**
549
- * Gets a block header by its hash.
550
- * @param blockHash - The hash of the block to return.
551
- * @returns The requested block header.
552
- */ async getBlockHeaderByHash(blockHash) {
553
- const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
661
+ /** Returns the checkpoint number that contains the given slot (or undefined if not found). */ async getCheckpointNumberBySlot(slot) {
662
+ const checkpointNumber = await this.#slotToCheckpoint.getAsync(slot);
663
+ return checkpointNumber === undefined ? undefined : CheckpointNumber(checkpointNumber);
664
+ }
665
+ /** Gets a single L2 block matching the given resolved query. */ async getBlock(query) {
666
+ const blockNumber = await this.getBlockNumber(query);
554
667
  if (blockNumber === undefined) {
555
668
  return undefined;
556
669
  }
557
670
  const blockStorage = await this.#blocks.getAsync(blockNumber);
558
- if (!blockStorage || !blockStorage.header) {
671
+ if (!blockStorage) {
559
672
  return undefined;
560
673
  }
561
- return BlockHeader.fromBuffer(blockStorage.header);
674
+ return this.getBlockFromBlockStorage(blockNumber, blockStorage);
562
675
  }
563
- /**
564
- * Gets a block header by its archive root.
565
- * @param archive - The archive root of the block to return.
566
- * @returns The requested block header.
567
- */ async getBlockHeaderByArchive(archive) {
568
- const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
676
+ /** Gets a collection of L2 blocks for a resolved range. */ getBlocks(query) {
677
+ return toArray(this.iterateBlocks(query));
678
+ }
679
+ /** Gets single block metadata matching the given resolved query. */ async getBlockData(query) {
680
+ const blockNumber = await this.getBlockNumber(query);
569
681
  if (blockNumber === undefined) {
570
682
  return undefined;
571
683
  }
@@ -573,20 +685,30 @@ export { TxReceipt } from '@aztec/stdlib/tx';
573
685
  if (!blockStorage || !blockStorage.header) {
574
686
  return undefined;
575
687
  }
576
- return BlockHeader.fromBuffer(blockStorage.header);
688
+ return this.getBlockDataFromBlockStorage(blockStorage);
577
689
  }
578
- /**
579
- * Gets the headers for a sequence of L2 blocks.
580
- * @param start - Number of the first block to return (inclusive).
581
- * @param limit - The number of blocks to return.
582
- * @returns The requested L2 block headers
583
- */ async *getBlockHeaders(start, limit) {
584
- for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)){
585
- const header = BlockHeader.fromBuffer(blockStorage.header);
586
- if (header.getBlockNumber() !== blockNumber) {
587
- throw new Error(`Block number mismatch when retrieving block header from archive (expected ${blockNumber} but got ${header.getBlockNumber()})`);
690
+ /** Gets a collection of block metadata entries for a resolved range. */ getBlocksData(query) {
691
+ return toArray(this.iterateBlocksData(query));
692
+ }
693
+ /** Async iterator over L2 blocks for a resolved range. */ async *iterateBlocks(query) {
694
+ const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
695
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)){
696
+ if (cap !== undefined && blockNumber > cap) {
697
+ break;
698
+ }
699
+ const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
700
+ if (block) {
701
+ yield block;
588
702
  }
589
- yield header;
703
+ }
704
+ }
705
+ /** Async iterator over block metadata for a resolved range. */ async *iterateBlocksData(query) {
706
+ const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
707
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)){
708
+ if (cap !== undefined && blockNumber > cap) {
709
+ break;
710
+ }
711
+ yield this.getBlockDataFromBlockStorage(blockStorage);
590
712
  }
591
713
  }
592
714
  async *getBlockStorages(start, limit) {
@@ -602,11 +724,27 @@ export { TxReceipt } from '@aztec/stdlib/tx';
602
724
  ];
603
725
  }
604
726
  }
727
+ /** Resolves a ResolvedBlockQuery discriminant to a block number, or undefined if not found. */ async getBlockNumber(query) {
728
+ let blockNumber;
729
+ if ('number' in query) {
730
+ blockNumber = query.number;
731
+ } else if ('hash' in query) {
732
+ const n = await this.#blockHashIndex.getAsync(query.hash.toString());
733
+ blockNumber = n !== undefined ? BlockNumber(n) : undefined;
734
+ } else {
735
+ const n = await this.#blockArchiveIndex.getAsync(query.archive.toString());
736
+ blockNumber = n !== undefined ? BlockNumber(n) : undefined;
737
+ }
738
+ if (blockNumber === undefined) {
739
+ return undefined;
740
+ }
741
+ return blockNumber;
742
+ }
605
743
  getBlockDataFromBlockStorage(blockStorage) {
606
744
  return {
607
745
  header: BlockHeader.fromBuffer(blockStorage.header),
608
746
  archive: AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),
609
- blockHash: Fr.fromBuffer(blockStorage.blockHash),
747
+ blockHash: BlockHash.fromBuffer(blockStorage.blockHash),
610
748
  checkpointNumber: CheckpointNumber(blockStorage.checkpointNumber),
611
749
  indexWithinCheckpoint: IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint)
612
750
  };
@@ -653,17 +791,20 @@ export { TxReceipt } from '@aztec/stdlib/tx';
653
791
  * Gets a receipt of a settled tx.
654
792
  * @param txHash - The hash of a tx we try to get the receipt for.
655
793
  * @returns The requested tx receipt (or undefined if not found).
656
- */ async getSettledTxReceipt(txHash) {
794
+ */ async getSettledTxReceipt(txHash, l1Constants) {
657
795
  const txEffect = await this.getTxEffect(txHash);
658
796
  if (!txEffect) {
659
797
  return undefined;
660
798
  }
661
799
  const blockNumber = BlockNumber(txEffect.l2BlockNumber);
662
800
  // Use existing archiver methods to determine finalization level
663
- const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber] = await Promise.all([
801
+ const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber, blockData] = await Promise.all([
664
802
  this.getProvenBlockNumber(),
665
803
  this.getCheckpointedL2BlockNumber(),
666
- this.getFinalizedL2BlockNumber()
804
+ this.getFinalizedL2BlockNumber(),
805
+ this.getBlockData({
806
+ number: blockNumber
807
+ })
667
808
  ]);
668
809
  let status;
669
810
  if (blockNumber <= finalizedBlockNumber) {
@@ -675,7 +816,8 @@ export { TxReceipt } from '@aztec/stdlib/tx';
675
816
  } else {
676
817
  status = TxStatus.PROPOSED;
677
818
  }
678
- return new TxReceipt(txHash, status, TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode), undefined, txEffect.data.transactionFee.toBigInt(), txEffect.l2BlockHash, blockNumber);
819
+ const epochNumber = blockData && l1Constants ? getEpochAtSlot(blockData.header.globalVariables.slotNumber, l1Constants) : undefined;
820
+ return new TxReceipt(txHash, status, TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode), undefined, txEffect.data.transactionFee.toBigInt(), txEffect.l2BlockHash, blockNumber, epochNumber);
679
821
  }
680
822
  /**
681
823
  * Looks up which block included the requested tx effect.
@@ -686,13 +828,48 @@ export { TxReceipt } from '@aztec/stdlib/tx';
686
828
  if (!txEffect) {
687
829
  return undefined;
688
830
  }
689
- const { l2BlockNumber, txIndexInBlock } = deserializeIndexedTxEffect(txEffect);
831
+ // Read only the IndexedTxEffect header (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4)`); the
832
+ // large tail (the full TxEffect with logs etc.) is irrelevant here.
833
+ const view = Buffer.from(txEffect.buffer, txEffect.byteOffset, txEffect.byteLength);
834
+ const l2BlockNumber = view.readUInt32BE(32);
835
+ const txIndexInBlock = view.readUInt32BE(36);
690
836
  return [
691
837
  l2BlockNumber,
692
838
  txIndexInBlock
693
839
  ];
694
840
  }
695
841
  /**
842
+ * Batched, partial deserializer that fetches `noteHashes` and `nullifiers` (all of them) for the given
843
+ * txs. For each input txHash, returns a `[noteHashes, nullifiers]` tuple. Returns `[[], []]` for any
844
+ * unknown txHash. Preserves input order. Used by the log read path when `includeEffects` is set to
845
+ * attach effect data on demand without paying for a full {@link TxEffect} deserialization.
846
+ *
847
+ * The on-disk `IndexedTxEffect` layout starts with a fixed-length header
848
+ * (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4) + revertCode(1) + txHash(32) + transactionFee(32)` =
849
+ * 105 bytes), followed by `noteHashes` and `nullifiers` (both u8-length-prefixed `Fr` vectors). We
850
+ * skip the header, then read the two vectors, and stop — the large tail (`l2ToL1Msgs`,
851
+ * `publicDataWrites`, `privateLogs`, `publicLogs`, `contractClassLogs`) is never touched.
852
+ */ getNoteHashesAndNullifiers(txHashes) {
853
+ return Promise.all(txHashes.map(async (txHash)=>{
854
+ const buffer = await this.#txEffects.getAsync(txHash.toString());
855
+ if (!buffer) {
856
+ return [
857
+ [],
858
+ []
859
+ ];
860
+ }
861
+ const reader = BufferReader.asReader(buffer);
862
+ // Skip the fixed-length header: blockHash + l2BlockNumber + txIndexInBlock + revertCode + txHash + transactionFee.
863
+ reader.readBytes(32 + 4 + 4 + 1 + 32 + 32);
864
+ const noteHashes = reader.readVectorUint8Prefix(Fr);
865
+ const nullifiers = reader.readVectorUint8Prefix(Fr);
866
+ return [
867
+ noteHashes,
868
+ nullifiers
869
+ ];
870
+ }));
871
+ }
872
+ /**
696
873
  * Looks up which block deployed a particular contract.
697
874
  * @param contractAddress - The address of the contract to look up.
698
875
  * @returns The block number and index of the contract.
@@ -718,6 +895,152 @@ export { TxReceipt } from '@aztec/stdlib/tx';
718
895
  return typeof lastBlockNumber === 'number' ? BlockNumber(lastBlockNumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
719
896
  }
720
897
  /**
898
+ * Resolves all five L2 chain tips (proposed, proposedCheckpoint, checkpointed, proven, finalized)
899
+ * in a single read-only transaction so the snapshot is internally consistent. Each underlying
900
+ * record is read at most once: latest block, latest confirmed checkpoint, and latest pending
901
+ * checkpoint are each loaded directly (no separate "find the number, then look up data" hop),
902
+ * the proven/finalized checkpoint singletons are read once and their storage entries are
903
+ * reused if they coincide with the latest checkpoint, and per-tip block hashes are deduped
904
+ * when two tips land on the same block (e.g. finalized == proven, or proposedCheckpoint falls
905
+ * back to checkpointed when no pending checkpoint exists).
906
+ *
907
+ * The result is guaranteed to satisfy `finalized <= proven <= checkpointed <= proposed` (by
908
+ * block number). Genesis is represented by `(INITIAL_L2_BLOCK_NUM - 1)` and the supplied
909
+ * `genesisBlockHash`, paired with the synthetic genesis checkpoint id.
910
+ *
911
+ * @param genesisBlockHash - Block hash to report for the synthetic pre-initial block (used when
912
+ * a tip is still at genesis).
913
+ */ async getL2TipsData(genesisBlockHash) {
914
+ return await this.db.transactionAsync(async ()=>{
915
+ // Define genesis tips
916
+ const genesisBlockNumber = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
917
+ const genesisCheckpointNumber = CheckpointNumber(INITIAL_CHECKPOINT_NUMBER - 1);
918
+ const genesisBlockId = {
919
+ number: genesisBlockNumber,
920
+ hash: genesisBlockHash.toString()
921
+ };
922
+ const genesisCheckpointId = {
923
+ number: genesisCheckpointNumber,
924
+ hash: GENESIS_CHECKPOINT_HEADER_HASH.toString()
925
+ };
926
+ const genesisTip = {
927
+ block: genesisBlockId,
928
+ checkpoint: genesisCheckpointId
929
+ };
930
+ // Load latest block and checkpoint entries
931
+ const [latestBlockEntry] = await toArray(this.#blocks.entriesAsync({
932
+ reverse: true,
933
+ limit: 1
934
+ }));
935
+ const [proposedCheckpointEntry] = await toArray(this.#proposedCheckpoints.entriesAsync({
936
+ reverse: true,
937
+ limit: 1
938
+ }));
939
+ const [latestCheckpointEntry] = await toArray(this.#checkpoints.entriesAsync({
940
+ reverse: true,
941
+ limit: 1
942
+ }));
943
+ const latestCheckpointNumber = latestCheckpointEntry ? CheckpointNumber(latestCheckpointEntry[0]) : genesisCheckpointNumber;
944
+ // Load proven and finalized checkpoint number pointers
945
+ const [provenRaw, finalizedRaw] = await Promise.all([
946
+ this.#lastProvenCheckpoint.getAsync(),
947
+ this.#lastFinalizedCheckpoint.getAsync()
948
+ ]);
949
+ // Clamp to enforce finalized <= proven <= checkpointed.
950
+ const provenCheckpointNumber = CheckpointNumber(Math.min(provenRaw ?? 0, latestCheckpointNumber));
951
+ const finalizedCheckpointNumber = CheckpointNumber(Math.min(finalizedRaw ?? 0, provenCheckpointNumber));
952
+ // Avoid loading the same checkpoint more than once
953
+ const checkpointStorageCache = new Map();
954
+ if (latestCheckpointEntry) {
955
+ checkpointStorageCache.set(CheckpointNumber(latestCheckpointEntry[0]), latestCheckpointEntry[1]);
956
+ }
957
+ const loadCheckpointStorage = async (n)=>{
958
+ if (n === 0) {
959
+ return undefined;
960
+ }
961
+ if (!checkpointStorageCache.has(n)) {
962
+ const checkpointStorage = await this.#checkpoints.getAsync(n);
963
+ if (!checkpointStorage) {
964
+ throw new CheckpointNotFoundError(n);
965
+ }
966
+ checkpointStorageCache.set(n, checkpointStorage);
967
+ }
968
+ return checkpointStorageCache.get(n);
969
+ };
970
+ // Load proven and finalized checkpoint storage entries
971
+ const provenCheckpoint = await loadCheckpointStorage(provenCheckpointNumber);
972
+ const finalizedCheckpoint = await loadCheckpointStorage(finalizedCheckpointNumber);
973
+ // Avoid loading the same block hash multiple times when tips land on the same block
974
+ const blockHashCache = new Map();
975
+ blockHashCache.set(genesisBlockNumber, genesisBlockHash.toString());
976
+ if (latestBlockEntry) {
977
+ blockHashCache.set(latestBlockEntry[0], BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString());
978
+ }
979
+ const loadBlockHash = async (n)=>{
980
+ if (!blockHashCache.has(n)) {
981
+ const blockStorage = await this.#blocks.getAsync(n);
982
+ if (!blockStorage) {
983
+ throw new BlockNotFoundError(n);
984
+ }
985
+ const blockHash = BlockHash.fromBuffer(blockStorage.blockHash).toString();
986
+ blockHashCache.set(n, blockHash);
987
+ }
988
+ return blockHashCache.get(n);
989
+ };
990
+ // Build proposed chain tip (this one has block only, no checkpoint)
991
+ const proposedBlockId = latestBlockEntry === undefined ? genesisBlockId : {
992
+ number: BlockNumber(latestBlockEntry[0]),
993
+ hash: BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString()
994
+ };
995
+ // Build other tips from checkpoint data, reading corresponding block data from the cache
996
+ const buildTipFromCheckpoint = async (stored)=>{
997
+ if (!stored) {
998
+ return genesisTip;
999
+ }
1000
+ const blockNumber = BlockNumber(stored.startBlock + stored.blockCount - 1);
1001
+ const blockHash = await loadBlockHash(blockNumber);
1002
+ const header = CheckpointHeader.fromBuffer(stored.header);
1003
+ return {
1004
+ block: {
1005
+ number: blockNumber,
1006
+ hash: blockHash
1007
+ },
1008
+ checkpoint: {
1009
+ number: CheckpointNumber(stored.checkpointNumber),
1010
+ hash: header.hash().toString()
1011
+ }
1012
+ };
1013
+ };
1014
+ const checkpointedTip = await buildTipFromCheckpoint(latestCheckpointEntry?.[1]);
1015
+ const provenTip = await buildTipFromCheckpoint(provenCheckpoint);
1016
+ const finalizedTip = await buildTipFromCheckpoint(finalizedCheckpoint);
1017
+ // Proposed checkpoint falls back to the checkpoint tip if it's not set. And if local storage is
1018
+ // inconsistent and the proposed checkpoint is behind the checkpointed tip, we patch that and
1019
+ // report the checkpointed tip as the proposed checkpoint to maintain the invariant.
1020
+ const proposedCheckpointTip = proposedCheckpointEntry === undefined || proposedCheckpointEntry[0] <= latestCheckpointNumber ? checkpointedTip : await buildTipFromCheckpoint(proposedCheckpointEntry[1]);
1021
+ // A checkpointed block past the latest stored block would mean a checkpoint
1022
+ // references blocks that aren't in blocks.
1023
+ if (proposedBlockId.number < checkpointedTip.block.number) {
1024
+ throw new Error(`Inconsistent block store: latest block ${proposedBlockId.number} is behind checkpointed block ${checkpointedTip.block.number}`);
1025
+ }
1026
+ // Assert that checkpoint numbers are increasing
1027
+ if (finalizedTip.checkpoint.number > provenTip.checkpoint.number || provenTip.checkpoint.number > checkpointedTip.checkpoint.number || checkpointedTip.checkpoint.number > proposedCheckpointTip.checkpoint.number) {
1028
+ throw new Error(`Inconsistent checkpoint numbers in chain tips: finalized=${finalizedTip.checkpoint.number} proven=${provenTip.checkpoint.number} checkpointed=${checkpointedTip.checkpoint.number} proposed=${proposedCheckpointTip.checkpoint.number}`);
1029
+ }
1030
+ // Assert block numbers are increasing
1031
+ if (finalizedTip.block.number > provenTip.block.number || provenTip.block.number > checkpointedTip.block.number || checkpointedTip.block.number > proposedCheckpointTip.block.number || proposedCheckpointTip.block.number > proposedBlockId.number) {
1032
+ throw new Error(`Inconsistent block numbers in chain tips: finalized=${finalizedTip.block.number} proven=${provenTip.block.number} checkpointed=${checkpointedTip.block.number} proposedCheckpoint=${proposedCheckpointTip.block.number} proposed=${proposedBlockId.number}`);
1033
+ }
1034
+ return {
1035
+ proposed: proposedBlockId,
1036
+ proposedCheckpoint: proposedCheckpointTip,
1037
+ checkpointed: checkpointedTip,
1038
+ proven: provenTip,
1039
+ finalized: finalizedTip
1040
+ };
1041
+ });
1042
+ }
1043
+ /**
721
1044
  * Gets the most recent L1 block processed.
722
1045
  * @returns The L1 block that published the latest L2 block
723
1046
  */ getSynchedL1BlockNumber() {
@@ -726,17 +1049,74 @@ export { TxReceipt } from '@aztec/stdlib/tx';
726
1049
  setSynchedL1BlockNumber(l1BlockNumber) {
727
1050
  return this.#lastSynchedL1Block.set(l1BlockNumber);
728
1051
  }
1052
+ /**
1053
+ * Adds a proposed checkpoint to the pending queue.
1054
+ * Accepts proposed.checkpointNumber === latestTip + 1, where latestTip is the highest of
1055
+ * confirmed and the highest pending checkpoint number.
1056
+ * Computes archive and checkpointOutHash from the stored blocks.
1057
+ */ async addProposedCheckpoint(proposed) {
1058
+ return await this.db.transactionAsync(async ()=>{
1059
+ const confirmed = await this.getLatestCheckpointNumber();
1060
+ const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({
1061
+ reverse: true,
1062
+ limit: 1
1063
+ }));
1064
+ const latestTip = CheckpointNumber(latestPendingKey !== undefined ? Math.max(latestPendingKey, confirmed) : confirmed);
1065
+ if (proposed.checkpointNumber !== latestTip + 1) {
1066
+ throw new ProposedCheckpointNotSequentialError(proposed.checkpointNumber, latestTip);
1067
+ }
1068
+ // Ensure the predecessor block (from pending or confirmed chain) exists
1069
+ const previousBlock = await this.getPreviousCheckpointBlock(proposed.checkpointNumber);
1070
+ const blocks = [];
1071
+ for(let i = 0; i < proposed.blockCount; i++){
1072
+ const block = await this.getBlock({
1073
+ number: BlockNumber(proposed.startBlock + i)
1074
+ });
1075
+ if (!block) {
1076
+ throw new BlockNotFoundError(proposed.startBlock + i);
1077
+ }
1078
+ blocks.push(block);
1079
+ }
1080
+ this.validateCheckpointBlocks(blocks, previousBlock);
1081
+ const archive = blocks[blocks.length - 1].archive;
1082
+ const checkpointOutHash = Checkpoint.getCheckpointOutHash(blocks);
1083
+ await this.#proposedCheckpoints.set(proposed.checkpointNumber, {
1084
+ header: proposed.header.toBuffer(),
1085
+ archive: archive.toBuffer(),
1086
+ checkpointOutHash: checkpointOutHash.toBuffer(),
1087
+ checkpointNumber: proposed.checkpointNumber,
1088
+ startBlock: proposed.startBlock,
1089
+ blockCount: proposed.blockCount,
1090
+ totalManaUsed: proposed.totalManaUsed.toString(),
1091
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString()
1092
+ });
1093
+ });
1094
+ }
729
1095
  async getProvenCheckpointNumber() {
730
- const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
731
- this.getLatestCheckpointNumber(),
732
- this.#lastProvenCheckpoint.getAsync()
733
- ]);
734
- return (provenCheckpointNumber ?? 0) > latestCheckpointNumber ? latestCheckpointNumber : CheckpointNumber(provenCheckpointNumber ?? 0);
1096
+ return await this.db.transactionAsync(async ()=>{
1097
+ const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
1098
+ this.getLatestCheckpointNumber(),
1099
+ this.#lastProvenCheckpoint.getAsync()
1100
+ ]);
1101
+ return (provenCheckpointNumber ?? 0) > latestCheckpointNumber ? latestCheckpointNumber : CheckpointNumber(provenCheckpointNumber ?? 0);
1102
+ });
735
1103
  }
736
1104
  async setProvenCheckpointNumber(checkpointNumber) {
737
1105
  const result = await this.#lastProvenCheckpoint.set(checkpointNumber);
738
1106
  return result;
739
1107
  }
1108
+ async getFinalizedCheckpointNumber() {
1109
+ return await this.db.transactionAsync(async ()=>{
1110
+ const [provenCheckpointNumber, finalizedCheckpointNumber] = await Promise.all([
1111
+ this.getProvenCheckpointNumber(),
1112
+ this.#lastFinalizedCheckpoint.getAsync()
1113
+ ]);
1114
+ return (finalizedCheckpointNumber ?? 0) > provenCheckpointNumber ? provenCheckpointNumber : CheckpointNumber(finalizedCheckpointNumber ?? 0);
1115
+ });
1116
+ }
1117
+ setFinalizedCheckpointNumber(checkpointNumber) {
1118
+ return this.#lastFinalizedCheckpoint.set(checkpointNumber);
1119
+ }
740
1120
  #computeBlockRange(start, limit) {
741
1121
  if (limit < 1) {
742
1122
  throw new Error(`Invalid limit: ${limit}`);
@@ -770,4 +1150,70 @@ export { TxReceipt } from '@aztec/stdlib/tx';
770
1150
  await this.#pendingChainValidationStatus.delete();
771
1151
  }
772
1152
  }
1153
+ /** Records a rejected-checkpoint entry, keyed by its own archive root. */ async addRejectedCheckpoint(entry) {
1154
+ const archiveRootHex = entry.archiveRoot.toString();
1155
+ await this.#rejectedCheckpoints.set(archiveRootHex, {
1156
+ checkpointNumber: entry.checkpointNumber,
1157
+ archiveRoot: entry.archiveRoot.toBuffer(),
1158
+ parentArchiveRoot: entry.parentArchiveRoot.toBuffer(),
1159
+ slotNumber: entry.slotNumber,
1160
+ l1: entry.l1.toBuffer(),
1161
+ reason: entry.reason
1162
+ });
1163
+ await this.#rejectedCheckpointsByNumber.set(entry.checkpointNumber, archiveRootHex);
1164
+ await this.advanceSynchedL1BlockNumber(entry.l1.blockNumber);
1165
+ }
1166
+ /** Returns the rejected-checkpoint entry with the given archive root, or undefined if not present. */ async getRejectedCheckpointByArchiveRoot(archiveRoot) {
1167
+ const stored = await this.#rejectedCheckpoints.getAsync(archiveRoot.toString());
1168
+ return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
1169
+ }
1170
+ /** Returns the rejected-checkpoint entry recorded for the given checkpoint number, or undefined if none. */ async getRejectedCheckpointByNumber(checkpointNumber) {
1171
+ const archiveRootHex = await this.#rejectedCheckpointsByNumber.getAsync(checkpointNumber);
1172
+ if (archiveRootHex === undefined) {
1173
+ return undefined;
1174
+ }
1175
+ const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
1176
+ return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
1177
+ }
1178
+ /** Returns the highest checkpoint number recorded across all rejected entries, or `INITIAL_CHECKPOINT_NUMBER - 1` if none. */ async getLatestRejectedCheckpointNumber() {
1179
+ const [latest] = await toArray(this.#rejectedCheckpointsByNumber.keysAsync({
1180
+ reverse: true,
1181
+ limit: 1
1182
+ }));
1183
+ return CheckpointNumber(latest ?? INITIAL_CHECKPOINT_NUMBER - 1);
1184
+ }
1185
+ /** Removes a rejected-checkpoint entry by its archive root (used when an entry no longer matches L1). */ async removeRejectedCheckpointByArchiveRoot(archiveRoot) {
1186
+ const archiveRootHex = archiveRoot.toString();
1187
+ const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
1188
+ await this.#rejectedCheckpoints.delete(archiveRootHex);
1189
+ if (stored) {
1190
+ // Only clear the by-number index if it still points at this archive root, so a distinct
1191
+ // entry that shares the checkpoint number (e.g. an L1 reorg replacement) is not dropped.
1192
+ const indexed = await this.#rejectedCheckpointsByNumber.getAsync(stored.checkpointNumber);
1193
+ if (indexed === archiveRootHex) {
1194
+ await this.#rejectedCheckpointsByNumber.delete(stored.checkpointNumber);
1195
+ }
1196
+ }
1197
+ }
1198
+ /**
1199
+ * Advances the stored last-synched L1 block number to `l1BlockNumber` only if it is strictly
1200
+ * greater than the current value. Use this whenever ingesting checkpoint-shaped data so the
1201
+ * sync pointer never walks backwards on out-of-order writes (e.g. an invalid checkpoint
1202
+ * advance followed by a valid-checkpoint commit landing at an earlier L1 block).
1203
+ */ async advanceSynchedL1BlockNumber(l1BlockNumber) {
1204
+ const current = await this.#lastSynchedL1Block.getAsync();
1205
+ if (current === undefined || l1BlockNumber > current) {
1206
+ await this.#lastSynchedL1Block.set(l1BlockNumber);
1207
+ }
1208
+ }
1209
+ rejectedCheckpointFromStorage(stored) {
1210
+ return {
1211
+ checkpointNumber: CheckpointNumber(stored.checkpointNumber),
1212
+ archiveRoot: Fr.fromBuffer(stored.archiveRoot),
1213
+ parentArchiveRoot: Fr.fromBuffer(stored.parentArchiveRoot),
1214
+ slotNumber: SlotNumber(stored.slotNumber),
1215
+ l1: L1PublishedData.fromBuffer(stored.l1),
1216
+ reason: stored.reason
1217
+ };
1218
+ }
773
1219
  }