@aztec/archiver 0.0.1-commit.9d2bcf6d → 0.0.1-commit.9d619b6c6

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 (114) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +13 -8
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +90 -114
  5. package/dest/config.d.ts +5 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +15 -3
  8. package/dest/errors.d.ts +50 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +67 -16
  11. package/dest/factory.d.ts +4 -5
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +33 -27
  14. package/dest/index.d.ts +4 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +3 -1
  17. package/dest/l1/bin/retrieve-calldata.js +36 -33
  18. package/dest/l1/calldata_retriever.d.ts +73 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +191 -259
  21. package/dest/l1/data_retrieval.d.ts +26 -17
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +42 -47
  24. package/dest/l1/spire_proposer.d.ts +5 -5
  25. package/dest/l1/spire_proposer.d.ts.map +1 -1
  26. package/dest/l1/spire_proposer.js +9 -17
  27. package/dest/l1/validate_historical_logs.d.ts +23 -0
  28. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  29. package/dest/l1/validate_historical_logs.js +108 -0
  30. package/dest/modules/data_source_base.d.ts +14 -7
  31. package/dest/modules/data_source_base.d.ts.map +1 -1
  32. package/dest/modules/data_source_base.js +39 -77
  33. package/dest/modules/data_store_updater.d.ts +35 -15
  34. package/dest/modules/data_store_updater.d.ts.map +1 -1
  35. package/dest/modules/data_store_updater.js +137 -96
  36. package/dest/modules/instrumentation.d.ts +21 -3
  37. package/dest/modules/instrumentation.d.ts.map +1 -1
  38. package/dest/modules/instrumentation.js +41 -8
  39. package/dest/modules/l1_synchronizer.d.ts +10 -9
  40. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  41. package/dest/modules/l1_synchronizer.js +279 -150
  42. package/dest/modules/validation.d.ts +1 -1
  43. package/dest/modules/validation.d.ts.map +1 -1
  44. package/dest/modules/validation.js +2 -2
  45. package/dest/store/block_store.d.ts +73 -28
  46. package/dest/store/block_store.d.ts.map +1 -1
  47. package/dest/store/block_store.js +395 -136
  48. package/dest/store/contract_class_store.d.ts +2 -3
  49. package/dest/store/contract_class_store.d.ts.map +1 -1
  50. package/dest/store/contract_class_store.js +7 -67
  51. package/dest/store/contract_instance_store.d.ts +1 -1
  52. package/dest/store/contract_instance_store.d.ts.map +1 -1
  53. package/dest/store/contract_instance_store.js +6 -2
  54. package/dest/store/kv_archiver_store.d.ts +67 -24
  55. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  56. package/dest/store/kv_archiver_store.js +82 -27
  57. package/dest/store/l2_tips_cache.d.ts +20 -0
  58. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  59. package/dest/store/l2_tips_cache.js +109 -0
  60. package/dest/store/log_store.d.ts +6 -3
  61. package/dest/store/log_store.d.ts.map +1 -1
  62. package/dest/store/log_store.js +150 -55
  63. package/dest/store/message_store.d.ts +5 -1
  64. package/dest/store/message_store.d.ts.map +1 -1
  65. package/dest/store/message_store.js +21 -9
  66. package/dest/test/fake_l1_state.d.ts +24 -1
  67. package/dest/test/fake_l1_state.d.ts.map +1 -1
  68. package/dest/test/fake_l1_state.js +145 -28
  69. package/dest/test/mock_archiver.d.ts +1 -1
  70. package/dest/test/mock_archiver.d.ts.map +1 -1
  71. package/dest/test/mock_archiver.js +3 -2
  72. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  73. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  74. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  75. package/dest/test/mock_l2_block_source.d.ts +26 -5
  76. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  77. package/dest/test/mock_l2_block_source.js +160 -89
  78. package/dest/test/mock_structs.d.ts +4 -1
  79. package/dest/test/mock_structs.d.ts.map +1 -1
  80. package/dest/test/mock_structs.js +13 -1
  81. package/dest/test/noop_l1_archiver.d.ts +4 -1
  82. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  83. package/dest/test/noop_l1_archiver.js +9 -3
  84. package/package.json +13 -13
  85. package/src/archiver.ts +120 -137
  86. package/src/config.ts +22 -2
  87. package/src/errors.ts +104 -26
  88. package/src/factory.ts +47 -24
  89. package/src/index.ts +3 -1
  90. package/src/l1/README.md +25 -68
  91. package/src/l1/bin/retrieve-calldata.ts +46 -39
  92. package/src/l1/calldata_retriever.ts +250 -379
  93. package/src/l1/data_retrieval.ts +58 -69
  94. package/src/l1/spire_proposer.ts +7 -15
  95. package/src/l1/validate_historical_logs.ts +140 -0
  96. package/src/modules/data_source_base.ts +78 -98
  97. package/src/modules/data_store_updater.ts +164 -126
  98. package/src/modules/instrumentation.ts +56 -9
  99. package/src/modules/l1_synchronizer.ts +357 -188
  100. package/src/modules/validation.ts +2 -2
  101. package/src/store/block_store.ts +503 -172
  102. package/src/store/contract_class_store.ts +8 -106
  103. package/src/store/contract_instance_store.ts +8 -5
  104. package/src/store/kv_archiver_store.ts +130 -41
  105. package/src/store/l2_tips_cache.ts +134 -0
  106. package/src/store/log_store.ts +221 -63
  107. package/src/store/message_store.ts +27 -10
  108. package/src/structs/inbox_message.ts +1 -1
  109. package/src/test/fake_l1_state.ts +193 -32
  110. package/src/test/mock_archiver.ts +3 -2
  111. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  112. package/src/test/mock_l2_block_source.ts +209 -82
  113. package/src/test/mock_structs.ts +20 -6
  114. package/src/test/noop_l1_archiver.ts +10 -2
@@ -6,32 +6,34 @@ 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, CheckpointedL2Block, CommitteeAttestation, 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, BlockIndexNotSequentialError, BlockNotFoundError, BlockNumberNotSequentialError, CannotOverwriteCheckpointedBlockError, CheckpointNotFoundError, CheckpointNumberNotSequentialError, InitialCheckpointNumberNotSequentialError, NoProposedCheckpointToPromoteError, ProposedCheckpointArchiveRootMismatchError, ProposedCheckpointNotSequentialError, ProposedCheckpointPromotionNotSequentialError, ProposedCheckpointStaleError } 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
22
  /** Map checkpoint number to checkpoint data */ #checkpoints;
23
+ /** Map slot number to checkpoint number, for looking up checkpoints by slot range. */ #slotToCheckpoint;
23
24
  /** Map block hash to list of tx hashes */ #blockTxs;
24
25
  /** Tx hash to serialized IndexedTxEffect */ #txEffects;
25
26
  /** Stores L1 block number in which the last processed L2 block was included */ #lastSynchedL1Block;
26
27
  /** Stores last proven checkpoint */ #lastProvenCheckpoint;
28
+ /** Stores last finalized checkpoint (proven at or before the finalized L1 block) */ #lastFinalizedCheckpoint;
27
29
  /** Stores the pending chain validation status */ #pendingChainValidationStatus;
28
30
  /** Index mapping a contract's address (as a string) to its location in a block */ #contractIndex;
29
31
  /** Index mapping block hash to block number */ #blockHashIndex;
30
32
  /** Index mapping block archive to block number */ #blockArchiveIndex;
33
+ /** Singleton: assumes max 1-deep pipeline. For deeper pipelining, replace with a map keyed by checkpoint number. */ #proposedCheckpoint;
31
34
  #log;
32
- constructor(db, l1Constants){
35
+ constructor(db){
33
36
  this.db = db;
34
- this.l1Constants = l1Constants;
35
37
  this.#log = createLogger('archiver:block_store');
36
38
  this.#blocks = db.openMap('archiver_blocks');
37
39
  this.#blockTxs = db.openMap('archiver_block_txs');
@@ -41,94 +43,94 @@ export { TxReceipt } from '@aztec/stdlib/tx';
41
43
  this.#blockArchiveIndex = db.openMap('archiver_block_archive_index');
42
44
  this.#lastSynchedL1Block = db.openSingleton('archiver_last_synched_l1_block');
43
45
  this.#lastProvenCheckpoint = db.openSingleton('archiver_last_proven_l2_checkpoint');
46
+ this.#lastFinalizedCheckpoint = db.openSingleton('archiver_last_finalized_l2_checkpoint');
44
47
  this.#pendingChainValidationStatus = db.openSingleton('archiver_pending_chain_validation_status');
45
48
  this.#checkpoints = db.openMap('archiver_checkpoints');
49
+ this.#slotToCheckpoint = db.openMap('archiver_slot_to_checkpoint');
50
+ this.#proposedCheckpoint = db.openSingleton('proposed_checkpoint_data');
46
51
  }
47
52
  /**
48
- * Computes the finalized block number based on the proven block number.
49
- * A block is considered finalized when it's 2 epochs behind the proven block.
50
- * TODO(#13569): Compute proper finalized block number based on L1 finalized block.
51
- * TODO(palla/mbps): Even the provisional computation is wrong, since it should subtract checkpoints, not blocks
53
+ * Returns the finalized L2 block number. An L2 block is finalized when it was proven
54
+ * in an L1 block that has itself been finalized on Ethereum.
52
55
  * @returns The finalized block number.
53
56
  */ async getFinalizedL2BlockNumber() {
54
- const provenBlockNumber = await this.getProvenBlockNumber();
55
- return BlockNumber(Math.max(provenBlockNumber - this.l1Constants.epochDuration * 2, 0));
57
+ const finalizedCheckpointNumber = await this.getFinalizedCheckpointNumber();
58
+ if (finalizedCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
59
+ return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
60
+ }
61
+ const checkpointStorage = await this.#checkpoints.getAsync(finalizedCheckpointNumber);
62
+ if (!checkpointStorage) {
63
+ throw new CheckpointNotFoundError(finalizedCheckpointNumber);
64
+ }
65
+ return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
56
66
  }
57
67
  /**
58
- * Append new proposed blocks to the store's list. All blocks must be for the 'current' checkpoint.
59
- * These are uncheckpointed blocks that have been proposed by the sequencer but not yet included in a checkpoint on L1.
68
+ * Append a new proposed block to the store.
69
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
60
70
  * For checkpointed blocks (already published to L1), use addCheckpoints() instead.
61
- * @param blocks - The proposed L2 blocks to be added to the store.
71
+ * @param block - The proposed L2 block to be added to the store.
62
72
  * @returns True if the operation is successful.
63
- */ async addProposedBlocks(blocks, opts = {}) {
64
- if (blocks.length === 0) {
65
- return true;
66
- }
73
+ */ async addProposedBlock(block, opts = {}) {
67
74
  return await this.db.transactionAsync(async ()=>{
68
- // Check that the block immediately before the first block to be added is present in the store.
69
- const firstBlockNumber = blocks[0].number;
70
- const firstBlockCheckpointNumber = blocks[0].checkpointNumber;
71
- const firstBlockIndex = blocks[0].indexWithinCheckpoint;
72
- const firstBlockLastArchive = blocks[0].header.lastArchive.root;
75
+ const blockNumber = block.number;
76
+ const blockCheckpointNumber = block.checkpointNumber;
77
+ const blockIndex = block.indexWithinCheckpoint;
78
+ const blockLastArchive = block.header.lastArchive.root;
73
79
  // Extract the latest block and checkpoint numbers
74
- const previousBlockNumber = await this.getLatestBlockNumber();
80
+ const previousBlockNumber = await this.getLatestL2BlockNumber();
81
+ const proposedCheckpointNumber = await this.getProposedCheckpointNumber();
75
82
  const previousCheckpointNumber = await this.getLatestCheckpointNumber();
76
83
  // Verify we're not overwriting checkpointed blocks
77
84
  const lastCheckpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
78
- if (!opts.force && firstBlockNumber <= lastCheckpointedBlockNumber) {
79
- throw new CannotOverwriteCheckpointedBlockError(firstBlockNumber, lastCheckpointedBlockNumber);
85
+ if (!opts.force && blockNumber <= lastCheckpointedBlockNumber) {
86
+ // Check if the proposed block matches the already-checkpointed one
87
+ const existingBlock = await this.getBlock(BlockNumber(blockNumber));
88
+ if (existingBlock && existingBlock.archive.root.equals(block.archive.root)) {
89
+ throw new BlockAlreadyCheckpointedError(blockNumber);
90
+ }
91
+ throw new CannotOverwriteCheckpointedBlockError(blockNumber, lastCheckpointedBlockNumber);
80
92
  }
81
- // Check that the first block number is the expected one
82
- if (!opts.force && previousBlockNumber !== firstBlockNumber - 1) {
83
- throw new InitialBlockNumberNotSequentialError(firstBlockNumber, previousBlockNumber);
93
+ // Check that the block number is the expected one
94
+ if (!opts.force && previousBlockNumber !== blockNumber - 1) {
95
+ throw new BlockNumberNotSequentialError(blockNumber, previousBlockNumber);
84
96
  }
85
- // The same check as above but for checkpoints
86
- if (!opts.force && previousCheckpointNumber !== firstBlockCheckpointNumber - 1) {
87
- throw new InitialCheckpointNumberNotSequentialError(firstBlockCheckpointNumber, previousCheckpointNumber);
97
+ // The same check as above but for checkpoints. Accept the block if either the confirmed
98
+ // checkpoint or the pending (locally validated but not yet confirmed) checkpoint matches.
99
+ const expectedCheckpointNumber = blockCheckpointNumber - 1;
100
+ if (!opts.force && previousCheckpointNumber !== expectedCheckpointNumber && proposedCheckpointNumber !== expectedCheckpointNumber) {
101
+ const [reported, source] = proposedCheckpointNumber > previousCheckpointNumber ? [
102
+ proposedCheckpointNumber,
103
+ 'proposed'
104
+ ] : [
105
+ previousCheckpointNumber,
106
+ 'confirmed'
107
+ ];
108
+ throw new CheckpointNumberNotSequentialError(blockCheckpointNumber, reported, source);
88
109
  }
89
110
  // Extract the previous block if there is one and see if it is for the same checkpoint or not
90
111
  const previousBlockResult = await this.getBlock(previousBlockNumber);
91
- let expectedFirstblockIndex = 0;
112
+ let expectedBlockIndex = 0;
92
113
  let previousBlockIndex = undefined;
93
114
  if (previousBlockResult !== undefined) {
94
- if (previousBlockResult.checkpointNumber === firstBlockCheckpointNumber) {
115
+ if (previousBlockResult.checkpointNumber === blockCheckpointNumber) {
95
116
  // The previous block is for the same checkpoint, therefore our index should follow it
96
117
  previousBlockIndex = previousBlockResult.indexWithinCheckpoint;
97
- expectedFirstblockIndex = previousBlockIndex + 1;
118
+ expectedBlockIndex = previousBlockIndex + 1;
98
119
  }
99
- if (!previousBlockResult.archive.root.equals(firstBlockLastArchive)) {
100
- throw new BlockArchiveNotConsistentError(firstBlockNumber, previousBlockResult.number, firstBlockLastArchive, previousBlockResult.archive.root);
120
+ if (!previousBlockResult.archive.root.equals(blockLastArchive)) {
121
+ throw new BlockArchiveNotConsistentError(blockNumber, previousBlockResult.number, blockLastArchive, previousBlockResult.archive.root);
101
122
  }
102
123
  }
103
- // Now check that the first block has the expected index value
104
- if (!opts.force && expectedFirstblockIndex !== firstBlockIndex) {
105
- throw new BlockIndexNotSequentialError(firstBlockIndex, previousBlockIndex);
106
- }
107
- // Iterate over blocks array and insert them, checking that the block numbers and indexes are sequential. Also check they are for the correct checkpoint.
108
- let previousBlock = undefined;
109
- for (const block of blocks){
110
- if (!opts.force && previousBlock) {
111
- if (previousBlock.number + 1 !== block.number) {
112
- throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
113
- }
114
- if (previousBlock.indexWithinCheckpoint + 1 !== block.indexWithinCheckpoint) {
115
- throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
116
- }
117
- if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
118
- throw new BlockArchiveNotConsistentError(block.number, previousBlock.number, block.header.lastArchive.root, previousBlock.archive.root);
119
- }
120
- }
121
- if (!opts.force && firstBlockCheckpointNumber !== block.checkpointNumber) {
122
- throw new CheckpointNumberNotConsistentError(block.checkpointNumber, firstBlockCheckpointNumber);
123
- }
124
- previousBlock = block;
125
- await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
124
+ // Now check that the block has the expected index value
125
+ if (!opts.force && expectedBlockIndex !== blockIndex) {
126
+ throw new BlockIndexNotSequentialError(blockIndex, previousBlockIndex);
126
127
  }
128
+ await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
127
129
  return true;
128
130
  });
129
131
  }
130
132
  /**
131
- * Append new cheskpoints to the store's list.
133
+ * Append new checkpoints to the store's list.
132
134
  * @param checkpoints - The L2 checkpoints to be added to the store.
133
135
  * @returns True if the operation is successful.
134
136
  */ async addCheckpoints(checkpoints, opts = {}) {
@@ -136,32 +138,26 @@ export { TxReceipt } from '@aztec/stdlib/tx';
136
138
  return true;
137
139
  }
138
140
  return await this.db.transactionAsync(async ()=>{
139
- // Check that the checkpoint immediately before the first block to be added is present in the store.
140
141
  const firstCheckpointNumber = checkpoints[0].checkpoint.number;
141
142
  const previousCheckpointNumber = await this.getLatestCheckpointNumber();
142
- if (previousCheckpointNumber !== firstCheckpointNumber - 1 && !opts.force) {
143
- throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
144
- }
145
- // Extract the previous checkpoint if there is one
146
- let previousCheckpointData = undefined;
147
- if (previousCheckpointNumber !== INITIAL_CHECKPOINT_NUMBER - 1) {
148
- // There should be a previous checkpoint
149
- previousCheckpointData = await this.getCheckpointData(previousCheckpointNumber);
150
- if (previousCheckpointData === undefined) {
151
- throw new CheckpointNotFoundError(previousCheckpointNumber);
143
+ // Handle already-stored checkpoints at the start of the batch.
144
+ // This can happen after an L1 reorg re-includes a checkpoint in a different L1 block.
145
+ // We accept them if archives match (same content) and update their L1 metadata.
146
+ if (!opts.force && firstCheckpointNumber <= previousCheckpointNumber) {
147
+ checkpoints = await this.skipOrUpdateAlreadyStoredCheckpoints(checkpoints, previousCheckpointNumber);
148
+ if (checkpoints.length === 0) {
149
+ return true;
152
150
  }
153
- }
154
- let previousBlockNumber = undefined;
155
- let previousBlock = undefined;
156
- // If we have a previous checkpoint then we need to get the previous block number
157
- if (previousCheckpointData !== undefined) {
158
- previousBlockNumber = BlockNumber(previousCheckpointData.startBlock + previousCheckpointData.numBlocks - 1);
159
- previousBlock = await this.getBlock(previousBlockNumber);
160
- if (previousBlock === undefined) {
161
- // We should be able to get the required previous block
162
- throw new BlockNotFoundError(previousBlockNumber);
151
+ // Re-check sequentiality after skipping
152
+ const newFirstNumber = checkpoints[0].checkpoint.number;
153
+ if (previousCheckpointNumber !== newFirstNumber - 1) {
154
+ throw new InitialCheckpointNumberNotSequentialError(newFirstNumber, previousCheckpointNumber);
163
155
  }
156
+ } else if (previousCheckpointNumber !== firstCheckpointNumber - 1 && !opts.force) {
157
+ throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
164
158
  }
159
+ // Get the last block of the previous checkpoint for archive chaining
160
+ let previousBlock = await this.getPreviousCheckpointBlock(checkpoints[0].checkpoint.number);
165
161
  // Iterate over checkpoints array and insert them, checking that the block numbers are sequential.
166
162
  let previousCheckpoint = undefined;
167
163
  for (const checkpoint of checkpoints){
@@ -169,48 +165,116 @@ export { TxReceipt } from '@aztec/stdlib/tx';
169
165
  throw new CheckpointNumberNotSequentialError(checkpoint.checkpoint.number, previousCheckpoint.checkpoint.number);
170
166
  }
171
167
  previousCheckpoint = checkpoint;
172
- // Store every block in the database. the block may already exist, but this has come from chain and is assumed to be correct.
168
+ // Validate block sequencing, indexes, and archive chaining
169
+ this.validateCheckpointBlocks(checkpoint.checkpoint.blocks, previousBlock);
170
+ // Store every block in the database (may already exist, but L1 data is authoritative)
173
171
  for(let i = 0; i < checkpoint.checkpoint.blocks.length; i++){
174
- const block = checkpoint.checkpoint.blocks[i];
175
- if (previousBlock) {
176
- // The blocks should have a sequential block number
177
- if (previousBlock.number !== block.number - 1) {
178
- throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
179
- }
180
- // If the blocks are for the same checkpoint then they should have sequential indexes
181
- if (previousBlock.checkpointNumber === block.checkpointNumber && previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1) {
182
- throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
183
- }
184
- if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
185
- throw new BlockArchiveNotConsistentError(block.number, previousBlock.number, block.header.lastArchive.root, previousBlock.archive.root);
186
- }
187
- } else {
188
- // No previous block, must be block 1 at checkpoint index 0
189
- if (block.indexWithinCheckpoint !== 0) {
190
- throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
191
- }
192
- if (block.number !== INITIAL_L2_BLOCK_NUM) {
193
- throw new BlockNumberNotSequentialError(block.number, undefined);
194
- }
195
- }
196
- previousBlock = block;
197
- await this.addBlockToDatabase(block, checkpoint.checkpoint.number, i);
172
+ await this.addBlockToDatabase(checkpoint.checkpoint.blocks[i], checkpoint.checkpoint.number, i);
198
173
  }
174
+ previousBlock = checkpoint.checkpoint.blocks.at(-1);
199
175
  // Store the checkpoint in the database
200
176
  await this.#checkpoints.set(checkpoint.checkpoint.number, {
201
177
  header: checkpoint.checkpoint.header.toBuffer(),
202
178
  archive: checkpoint.checkpoint.archive.toBuffer(),
179
+ checkpointOutHash: checkpoint.checkpoint.getCheckpointOutHash().toBuffer(),
203
180
  l1: checkpoint.l1.toBuffer(),
204
181
  attestations: checkpoint.attestations.map((attestation)=>attestation.toBuffer()),
205
182
  checkpointNumber: checkpoint.checkpoint.number,
206
183
  startBlock: checkpoint.checkpoint.blocks[0].number,
207
- numBlocks: checkpoint.checkpoint.blocks.length
184
+ blockCount: checkpoint.checkpoint.blocks.length
208
185
  });
186
+ // Update slot-to-checkpoint index
187
+ await this.#slotToCheckpoint.set(checkpoint.checkpoint.header.slotNumber, checkpoint.checkpoint.number);
209
188
  }
189
+ // Clear the proposed checkpoint if any of the confirmed checkpoints match or supersede it
190
+ const lastConfirmedCheckpointNumber = checkpoints[checkpoints.length - 1].checkpoint.number;
191
+ await this.clearProposedCheckpointIfSuperseded(lastConfirmedCheckpointNumber);
210
192
  await this.#lastSynchedL1Block.set(checkpoints[checkpoints.length - 1].l1.blockNumber);
211
193
  return true;
212
194
  });
213
195
  }
196
+ /**
197
+ * Handles checkpoints at the start of a batch that are already stored (e.g. due to L1 reorg).
198
+ * Verifies the archive root matches, updates L1 metadata, and returns only the new checkpoints.
199
+ */ async skipOrUpdateAlreadyStoredCheckpoints(checkpoints, latestStored) {
200
+ let i = 0;
201
+ for(; i < checkpoints.length && checkpoints[i].checkpoint.number <= latestStored; i++){
202
+ const incoming = checkpoints[i];
203
+ const stored = await this.getCheckpointData(incoming.checkpoint.number);
204
+ if (!stored) {
205
+ break;
206
+ }
207
+ // Verify the checkpoint content matches (archive root)
208
+ if (!stored.archive.root.equals(incoming.checkpoint.archive.root)) {
209
+ 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}`);
210
+ }
211
+ // Update L1 metadata and attestations for the already-stored checkpoint
212
+ this.#log.warn(`Checkpoint ${incoming.checkpoint.number} already stored, updating L1 info ` + `(L1 block ${stored.l1.blockNumber} -> ${incoming.l1.blockNumber})`);
213
+ await this.#checkpoints.set(incoming.checkpoint.number, {
214
+ header: incoming.checkpoint.header.toBuffer(),
215
+ archive: incoming.checkpoint.archive.toBuffer(),
216
+ checkpointOutHash: incoming.checkpoint.getCheckpointOutHash().toBuffer(),
217
+ l1: incoming.l1.toBuffer(),
218
+ attestations: incoming.attestations.map((a)=>a.toBuffer()),
219
+ checkpointNumber: incoming.checkpoint.number,
220
+ startBlock: incoming.checkpoint.blocks[0].number,
221
+ blockCount: incoming.checkpoint.blocks.length
222
+ });
223
+ // Update the sync point to reflect the new L1 block
224
+ await this.#lastSynchedL1Block.set(incoming.l1.blockNumber);
225
+ }
226
+ return checkpoints.slice(i);
227
+ }
228
+ /**
229
+ * Gets the last block of the checkpoint before the given one.
230
+ * Returns undefined if there is no previous checkpoint (i.e. genesis).
231
+ */ async getPreviousCheckpointBlock(checkpointNumber) {
232
+ const previousCheckpointNumber = CheckpointNumber(checkpointNumber - 1);
233
+ if (previousCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
234
+ return undefined;
235
+ }
236
+ const previousCheckpointData = await this.getCheckpointData(previousCheckpointNumber);
237
+ if (previousCheckpointData === undefined) {
238
+ throw new CheckpointNotFoundError(previousCheckpointNumber);
239
+ }
240
+ const previousBlockNumber = BlockNumber(previousCheckpointData.startBlock + previousCheckpointData.blockCount - 1);
241
+ const previousBlock = await this.getBlock(previousBlockNumber);
242
+ if (previousBlock === undefined) {
243
+ throw new BlockNotFoundError(previousBlockNumber);
244
+ }
245
+ return previousBlock;
246
+ }
247
+ /**
248
+ * Validates that blocks are sequential, have correct indexes, and chain via archive roots.
249
+ * This is the same validation used for both confirmed checkpoints (addCheckpoints) and
250
+ * proposed checkpoints (setProposedCheckpoint).
251
+ */ validateCheckpointBlocks(blocks, previousBlock) {
252
+ for (const block of blocks){
253
+ if (previousBlock) {
254
+ if (previousBlock.number !== block.number - 1) {
255
+ throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
256
+ }
257
+ if (previousBlock.checkpointNumber === block.checkpointNumber) {
258
+ if (previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1) {
259
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
260
+ }
261
+ } else if (block.indexWithinCheckpoint !== 0) {
262
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
263
+ }
264
+ if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
265
+ throw new BlockArchiveNotConsistentError(block.number, previousBlock.number, block.header.lastArchive.root, previousBlock.archive.root);
266
+ }
267
+ } else {
268
+ if (block.indexWithinCheckpoint !== 0) {
269
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
270
+ }
271
+ if (block.number !== INITIAL_L2_BLOCK_NUM) {
272
+ throw new BlockNumberNotSequentialError(block.number, undefined);
273
+ }
274
+ }
275
+ previousBlock = block;
276
+ }
277
+ }
214
278
  async addBlockToDatabase(block, checkpointNumber, indexWithinCheckpoint) {
215
279
  const blockHash = await block.hash();
216
280
  await this.#blocks.set(block.number, {
@@ -274,15 +338,25 @@ export { TxReceipt } from '@aztec/stdlib/tx';
274
338
  if (!targetCheckpoint) {
275
339
  throw new Error(`Target checkpoint ${checkpointNumber} not found in store`);
276
340
  }
277
- lastBlockToKeep = BlockNumber(targetCheckpoint.startBlock + targetCheckpoint.numBlocks - 1);
341
+ lastBlockToKeep = BlockNumber(targetCheckpoint.startBlock + targetCheckpoint.blockCount - 1);
278
342
  }
279
343
  // Remove all blocks after lastBlockToKeep (both checkpointed and uncheckpointed)
280
344
  const blocksRemoved = await this.removeBlocksAfter(lastBlockToKeep);
281
345
  // Remove all checkpoints after the target
282
346
  for(let c = latestCheckpointNumber; c > checkpointNumber; c = CheckpointNumber(c - 1)){
347
+ const checkpointStorage = await this.#checkpoints.getAsync(c);
348
+ if (checkpointStorage) {
349
+ const slotNumber = CheckpointHeader.fromBuffer(checkpointStorage.header).slotNumber;
350
+ await this.#slotToCheckpoint.delete(slotNumber);
351
+ }
283
352
  await this.#checkpoints.delete(c);
284
353
  this.#log.debug(`Removed checkpoint ${c}`);
285
354
  }
355
+ // Clear any proposed checkpoint that was orphaned by the removal (its base chain no longer exists)
356
+ const proposedCheckpointNumber = await this.getProposedCheckpointNumber();
357
+ if (proposedCheckpointNumber > checkpointNumber) {
358
+ await this.#proposedCheckpoint.delete();
359
+ }
286
360
  return {
287
361
  blocksRemoved
288
362
  };
@@ -306,17 +380,30 @@ export { TxReceipt } from '@aztec/stdlib/tx';
306
380
  }
307
381
  return checkpoints;
308
382
  }
383
+ /** Returns checkpoint data for all checkpoints whose slot falls within the given range (inclusive). */ async getCheckpointDataForSlotRange(startSlot, endSlot) {
384
+ const result = [];
385
+ for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync({
386
+ start: startSlot,
387
+ end: endSlot + 1
388
+ })){
389
+ const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
390
+ if (checkpointStorage) {
391
+ result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage));
392
+ }
393
+ }
394
+ return result;
395
+ }
309
396
  checkpointDataFromCheckpointStorage(checkpointStorage) {
310
- const data = {
397
+ return {
311
398
  header: CheckpointHeader.fromBuffer(checkpointStorage.header),
312
399
  archive: AppendOnlyTreeSnapshot.fromBuffer(checkpointStorage.archive),
400
+ checkpointOutHash: Fr.fromBuffer(checkpointStorage.checkpointOutHash),
313
401
  checkpointNumber: CheckpointNumber(checkpointStorage.checkpointNumber),
314
- startBlock: checkpointStorage.startBlock,
315
- numBlocks: checkpointStorage.numBlocks,
402
+ startBlock: BlockNumber(checkpointStorage.startBlock),
403
+ blockCount: checkpointStorage.blockCount,
316
404
  l1: L1PublishedData.fromBuffer(checkpointStorage.l1),
317
- attestations: checkpointStorage.attestations
405
+ attestations: checkpointStorage.attestations.map((buf)=>CommitteeAttestation.fromBuffer(buf))
318
406
  };
319
- return data;
320
407
  }
321
408
  async getBlocksForCheckpoint(checkpointNumber) {
322
409
  const checkpoint = await this.#checkpoints.getAsync(checkpointNumber);
@@ -325,7 +412,7 @@ export { TxReceipt } from '@aztec/stdlib/tx';
325
412
  }
326
413
  const blocksForCheckpoint = await toArray(this.#blocks.entriesAsync({
327
414
  start: checkpoint.startBlock,
328
- end: checkpoint.startBlock + checkpoint.numBlocks
415
+ end: checkpoint.startBlock + checkpoint.blockCount
329
416
  }));
330
417
  const converted = await Promise.all(blocksForCheckpoint.map((x)=>this.getBlockFromBlockStorage(x[0], x[1])));
331
418
  return converted.filter(isDefined);
@@ -362,7 +449,7 @@ export { TxReceipt } from '@aztec/stdlib/tx';
362
449
  return await this.db.transactionAsync(async ()=>{
363
450
  const removedBlocks = [];
364
451
  // Get the latest block number to determine the range
365
- const latestBlockNumber = await this.getLatestBlockNumber();
452
+ const latestBlockNumber = await this.getLatestL2BlockNumber();
366
453
  // Iterate from blockNumber + 1 to latestBlockNumber
367
454
  for(let bn = blockNumber + 1; bn <= latestBlockNumber; bn++){
368
455
  const block = await this.getBlock(BlockNumber(bn));
@@ -386,16 +473,9 @@ export { TxReceipt } from '@aztec/stdlib/tx';
386
473
  if (!checkpointStorage) {
387
474
  throw new CheckpointNotFoundError(provenCheckpointNumber);
388
475
  } else {
389
- return BlockNumber(checkpointStorage.startBlock + checkpointStorage.numBlocks - 1);
476
+ return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
390
477
  }
391
478
  }
392
- async getLatestBlockNumber() {
393
- const [latestBlocknumber] = await toArray(this.#blocks.keysAsync({
394
- reverse: true,
395
- limit: 1
396
- }));
397
- return typeof latestBlocknumber === 'number' ? BlockNumber(latestBlocknumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
398
- }
399
479
  async getLatestCheckpointNumber() {
400
480
  const [latestCheckpointNumber] = await toArray(this.#checkpoints.keysAsync({
401
481
  reverse: true,
@@ -406,6 +486,108 @@ export { TxReceipt } from '@aztec/stdlib/tx';
406
486
  }
407
487
  return CheckpointNumber(latestCheckpointNumber);
408
488
  }
489
+ async hasProposedCheckpoint() {
490
+ const proposed = await this.#proposedCheckpoint.getAsync();
491
+ return proposed !== undefined;
492
+ }
493
+ /** Deletes the proposed checkpoint from storage. */ async deleteProposedCheckpoint() {
494
+ await this.#proposedCheckpoint.delete();
495
+ }
496
+ /**
497
+ * Promotes the proposed checkpoint singleton to a confirmed checkpoint entry.
498
+ * This persists the checkpoint to the store, clears the proposed singleton, and updates the L1 sync point.
499
+ * Should only be called after the checkpoint has been validated.
500
+ * @param expectedArchiveRoot - The archive root to match against the proposed checkpoint, to guard against races.
501
+ */ async promoteProposedToCheckpointed(l1, attestations, expectedArchiveRoot) {
502
+ return await this.db.transactionAsync(async ()=>{
503
+ const proposed = await this.getProposedCheckpointOnly();
504
+ if (!proposed) {
505
+ throw new NoProposedCheckpointToPromoteError();
506
+ }
507
+ if (!proposed.archive.root.equals(expectedArchiveRoot)) {
508
+ throw new ProposedCheckpointArchiveRootMismatchError(expectedArchiveRoot, proposed.archive.root);
509
+ }
510
+ // Verify sequentiality: promoted checkpoint must follow the latest confirmed one
511
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
512
+ if (latestCheckpointNumber !== proposed.checkpointNumber - 1) {
513
+ throw new ProposedCheckpointPromotionNotSequentialError(proposed.checkpointNumber, latestCheckpointNumber);
514
+ }
515
+ // Write the checkpoint entry
516
+ await this.#checkpoints.set(proposed.checkpointNumber, {
517
+ header: proposed.header.toBuffer(),
518
+ archive: proposed.archive.toBuffer(),
519
+ checkpointOutHash: proposed.checkpointOutHash.toBuffer(),
520
+ l1: l1.toBuffer(),
521
+ attestations: attestations.map((attestation)=>attestation.toBuffer()),
522
+ checkpointNumber: proposed.checkpointNumber,
523
+ startBlock: proposed.startBlock,
524
+ blockCount: proposed.blockCount
525
+ });
526
+ // Update the slot-to-checkpoint index
527
+ await this.#slotToCheckpoint.set(proposed.header.slotNumber, proposed.checkpointNumber);
528
+ // Clear the proposed checkpoint singleton
529
+ await this.#proposedCheckpoint.delete();
530
+ // Update the last synced L1 block
531
+ await this.#lastSynchedL1Block.set(l1.blockNumber);
532
+ });
533
+ }
534
+ /** Clears the proposed checkpoint if the given confirmed checkpoint number supersedes it. */ async clearProposedCheckpointIfSuperseded(confirmedCheckpointNumber) {
535
+ const proposedCheckpointNumber = await this.getProposedCheckpointNumber();
536
+ if (proposedCheckpointNumber <= confirmedCheckpointNumber) {
537
+ await this.#proposedCheckpoint.delete();
538
+ }
539
+ }
540
+ /** Returns the proposed checkpoint data, or undefined if no proposed checkpoint exists. No fallback to confirmed. */ async getProposedCheckpointOnly() {
541
+ const stored = await this.#proposedCheckpoint.getAsync();
542
+ if (!stored) {
543
+ return undefined;
544
+ }
545
+ return this.convertToProposedCheckpointData(stored);
546
+ }
547
+ /**
548
+ * Gets the checkpoint at the proposed tip
549
+ * - pending checkpoint if it exists
550
+ * - fallsback to latest confirmed checkpoint otherwise
551
+ * @returns CommonCheckpointData
552
+ */ async getProposedCheckpoint() {
553
+ const stored = await this.#proposedCheckpoint.getAsync();
554
+ if (!stored) {
555
+ return this.getCheckpointData(await this.getLatestCheckpointNumber());
556
+ }
557
+ return this.convertToProposedCheckpointData(stored);
558
+ }
559
+ convertToProposedCheckpointData(stored) {
560
+ return {
561
+ checkpointNumber: CheckpointNumber(stored.checkpointNumber),
562
+ header: CheckpointHeader.fromBuffer(stored.header),
563
+ archive: AppendOnlyTreeSnapshot.fromBuffer(stored.archive),
564
+ checkpointOutHash: Fr.fromBuffer(stored.checkpointOutHash),
565
+ startBlock: BlockNumber(stored.startBlock),
566
+ blockCount: stored.blockCount,
567
+ totalManaUsed: BigInt(stored.totalManaUsed),
568
+ feeAssetPriceModifier: BigInt(stored.feeAssetPriceModifier)
569
+ };
570
+ }
571
+ /**
572
+ * Attempts to get the proposedCheckpoint's number, if there is not one, then fallback to the latest confirmed checkpoint number.
573
+ * @returns CheckpointNumber
574
+ */ async getProposedCheckpointNumber() {
575
+ const proposed = await this.getProposedCheckpoint();
576
+ if (!proposed) {
577
+ return await this.getLatestCheckpointNumber();
578
+ }
579
+ return CheckpointNumber(proposed.checkpointNumber);
580
+ }
581
+ /**
582
+ * Attempts to get the proposedCheckpoint's block number, if there is not one, then fallback to the checkpointed block number
583
+ * @returns BlockNumber
584
+ */ async getProposedCheckpointL2BlockNumber() {
585
+ const proposed = await this.getProposedCheckpoint();
586
+ if (!proposed) {
587
+ return await this.getCheckpointedL2BlockNumber();
588
+ }
589
+ return BlockNumber(proposed.startBlock + proposed.blockCount - 1);
590
+ }
409
591
  async getCheckpointedBlock(number) {
410
592
  const blockStorage = await this.#blocks.getAsync(number);
411
593
  if (!blockStorage) {
@@ -468,6 +650,28 @@ export { TxReceipt } from '@aztec/stdlib/tx';
468
650
  }
469
651
  }
470
652
  /**
653
+ * Gets block metadata (without tx data) by block number.
654
+ * @param blockNumber - The number of the block to return.
655
+ * @returns The requested block data.
656
+ */ async getBlockData(blockNumber) {
657
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
658
+ if (!blockStorage || !blockStorage.header) {
659
+ return undefined;
660
+ }
661
+ return this.getBlockDataFromBlockStorage(blockStorage);
662
+ }
663
+ /**
664
+ * Gets block metadata (without tx data) by archive root.
665
+ * @param archive - The archive root of the block to return.
666
+ * @returns The requested block data.
667
+ */ async getBlockDataByArchive(archive) {
668
+ const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
669
+ if (blockNumber === undefined) {
670
+ return undefined;
671
+ }
672
+ return this.getBlockData(BlockNumber(blockNumber));
673
+ }
674
+ /**
471
675
  * Gets an L2 block.
472
676
  * @param blockNumber - The number of the block to return.
473
677
  * @returns The requested L2 block.
@@ -557,12 +761,19 @@ export { TxReceipt } from '@aztec/stdlib/tx';
557
761
  ];
558
762
  }
559
763
  }
764
+ getBlockDataFromBlockStorage(blockStorage) {
765
+ return {
766
+ header: BlockHeader.fromBuffer(blockStorage.header),
767
+ archive: AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),
768
+ blockHash: BlockHash.fromBuffer(blockStorage.blockHash),
769
+ checkpointNumber: CheckpointNumber(blockStorage.checkpointNumber),
770
+ indexWithinCheckpoint: IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint)
771
+ };
772
+ }
560
773
  async getBlockFromBlockStorage(blockNumber, blockStorage) {
561
- const header = BlockHeader.fromBuffer(blockStorage.header);
562
- const archive = AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive);
563
- const blockHash = blockStorage.blockHash;
564
- header.setHash(Fr.fromBuffer(blockHash));
565
- const blockHashString = bufferToHex(blockHash);
774
+ const { header, archive, blockHash, checkpointNumber, indexWithinCheckpoint } = this.getBlockDataFromBlockStorage(blockStorage);
775
+ header.setHash(blockHash);
776
+ const blockHashString = bufferToHex(blockStorage.blockHash);
566
777
  const blockTxsBuffer = await this.#blockTxs.getAsync(blockHashString);
567
778
  if (blockTxsBuffer === undefined) {
568
779
  this.#log.warn(`Could not find body for block ${header.globalVariables.blockNumber} ${blockHash}`);
@@ -580,7 +791,7 @@ export { TxReceipt } from '@aztec/stdlib/tx';
580
791
  txEffects.push(deserializeIndexedTxEffect(txEffect).data);
581
792
  }
582
793
  const body = new Body(txEffects);
583
- const block = new L2Block(archive, header, body, CheckpointNumber(blockStorage.checkpointNumber), IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint));
794
+ const block = new L2Block(archive, header, body, checkpointNumber, indexWithinCheckpoint);
584
795
  if (block.number !== blockNumber) {
585
796
  throw new Error(`Block number mismatch when retrieving block from archive (expected ${blockNumber} but got ${block.number} with hash ${blockHashString})`);
586
797
  }
@@ -601,17 +812,18 @@ export { TxReceipt } from '@aztec/stdlib/tx';
601
812
  * Gets a receipt of a settled tx.
602
813
  * @param txHash - The hash of a tx we try to get the receipt for.
603
814
  * @returns The requested tx receipt (or undefined if not found).
604
- */ async getSettledTxReceipt(txHash) {
815
+ */ async getSettledTxReceipt(txHash, l1Constants) {
605
816
  const txEffect = await this.getTxEffect(txHash);
606
817
  if (!txEffect) {
607
818
  return undefined;
608
819
  }
609
820
  const blockNumber = BlockNumber(txEffect.l2BlockNumber);
610
821
  // Use existing archiver methods to determine finalization level
611
- const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber] = await Promise.all([
822
+ const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber, blockData] = await Promise.all([
612
823
  this.getProvenBlockNumber(),
613
824
  this.getCheckpointedL2BlockNumber(),
614
- this.getFinalizedL2BlockNumber()
825
+ this.getFinalizedL2BlockNumber(),
826
+ this.getBlockData(blockNumber)
615
827
  ]);
616
828
  let status;
617
829
  if (blockNumber <= finalizedBlockNumber) {
@@ -623,7 +835,8 @@ export { TxReceipt } from '@aztec/stdlib/tx';
623
835
  } else {
624
836
  status = TxStatus.PROPOSED;
625
837
  }
626
- return new TxReceipt(txHash, status, TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode), undefined, txEffect.data.transactionFee.toBigInt(), txEffect.l2BlockHash, blockNumber);
838
+ const epochNumber = blockData && l1Constants ? getEpochAtSlot(blockData.header.globalVariables.slotNumber, l1Constants) : undefined;
839
+ return new TxReceipt(txHash, status, TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode), undefined, txEffect.data.transactionFee.toBigInt(), txEffect.l2BlockHash, blockNumber, epochNumber);
627
840
  }
628
841
  /**
629
842
  * Looks up which block included the requested tx effect.
@@ -656,7 +869,7 @@ export { TxReceipt } from '@aztec/stdlib/tx';
656
869
  if (!checkpoint) {
657
870
  return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
658
871
  }
659
- return BlockNumber(checkpoint.startBlock + checkpoint.numBlocks - 1);
872
+ return BlockNumber(checkpoint.startBlock + checkpoint.blockCount - 1);
660
873
  }
661
874
  async getLatestL2BlockNumber() {
662
875
  const [lastBlockNumber] = await toArray(this.#blocks.keysAsync({
@@ -674,6 +887,42 @@ export { TxReceipt } from '@aztec/stdlib/tx';
674
887
  setSynchedL1BlockNumber(l1BlockNumber) {
675
888
  return this.#lastSynchedL1Block.set(l1BlockNumber);
676
889
  }
890
+ /** Sets the proposed checkpoint (not yet L1-confirmed). Only accepts confirmed + 1.
891
+ * Computes archive and checkpointOutHash from the stored blocks. */ async setProposedCheckpoint(proposed) {
892
+ return await this.db.transactionAsync(async ()=>{
893
+ const current = await this.getProposedCheckpointNumber();
894
+ if (proposed.checkpointNumber <= current) {
895
+ throw new ProposedCheckpointStaleError(proposed.checkpointNumber, current);
896
+ }
897
+ const confirmed = await this.getLatestCheckpointNumber();
898
+ if (proposed.checkpointNumber !== confirmed + 1) {
899
+ throw new ProposedCheckpointNotSequentialError(proposed.checkpointNumber, confirmed);
900
+ }
901
+ // Ensure the previous checkpoint + blocks exist
902
+ const previousBlock = await this.getPreviousCheckpointBlock(proposed.checkpointNumber);
903
+ const blocks = [];
904
+ for(let i = 0; i < proposed.blockCount; i++){
905
+ const block = await this.getBlock(BlockNumber(proposed.startBlock + i));
906
+ if (!block) {
907
+ throw new BlockNotFoundError(proposed.startBlock + i);
908
+ }
909
+ blocks.push(block);
910
+ }
911
+ this.validateCheckpointBlocks(blocks, previousBlock);
912
+ const archive = blocks[blocks.length - 1].archive;
913
+ const checkpointOutHash = Checkpoint.getCheckpointOutHash(blocks);
914
+ await this.#proposedCheckpoint.set({
915
+ header: proposed.header.toBuffer(),
916
+ archive: archive.toBuffer(),
917
+ checkpointOutHash: checkpointOutHash.toBuffer(),
918
+ checkpointNumber: proposed.checkpointNumber,
919
+ startBlock: proposed.startBlock,
920
+ blockCount: proposed.blockCount,
921
+ totalManaUsed: proposed.totalManaUsed.toString(),
922
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString()
923
+ });
924
+ });
925
+ }
677
926
  async getProvenCheckpointNumber() {
678
927
  const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
679
928
  this.getLatestCheckpointNumber(),
@@ -685,6 +934,16 @@ export { TxReceipt } from '@aztec/stdlib/tx';
685
934
  const result = await this.#lastProvenCheckpoint.set(checkpointNumber);
686
935
  return result;
687
936
  }
937
+ async getFinalizedCheckpointNumber() {
938
+ const [latestCheckpointNumber, finalizedCheckpointNumber] = await Promise.all([
939
+ this.getLatestCheckpointNumber(),
940
+ this.#lastFinalizedCheckpoint.getAsync()
941
+ ]);
942
+ return (finalizedCheckpointNumber ?? 0) > latestCheckpointNumber ? latestCheckpointNumber : CheckpointNumber(finalizedCheckpointNumber ?? 0);
943
+ }
944
+ setFinalizedCheckpointNumber(checkpointNumber) {
945
+ return this.#lastFinalizedCheckpoint.set(checkpointNumber);
946
+ }
688
947
  #computeBlockRange(start, limit) {
689
948
  if (limit < 1) {
690
949
  throw new Error(`Invalid limit: ${limit}`);