@aztec/archiver 0.0.1-commit.cd76b27 → 0.0.1-commit.ce4f8c4f2

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 (88) hide show
  1. package/dest/archiver.d.ts +3 -4
  2. package/dest/archiver.d.ts.map +1 -1
  3. package/dest/archiver.js +67 -23
  4. package/dest/config.d.ts +3 -3
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +2 -1
  7. package/dest/errors.d.ts +21 -9
  8. package/dest/errors.d.ts.map +1 -1
  9. package/dest/errors.js +27 -14
  10. package/dest/factory.d.ts +4 -5
  11. package/dest/factory.d.ts.map +1 -1
  12. package/dest/factory.js +25 -25
  13. package/dest/l1/bin/retrieve-calldata.js +32 -28
  14. package/dest/l1/calldata_retriever.d.ts +70 -53
  15. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  16. package/dest/l1/calldata_retriever.js +178 -260
  17. package/dest/l1/data_retrieval.d.ts +7 -8
  18. package/dest/l1/data_retrieval.d.ts.map +1 -1
  19. package/dest/l1/data_retrieval.js +18 -17
  20. package/dest/l1/spire_proposer.d.ts +5 -5
  21. package/dest/l1/spire_proposer.d.ts.map +1 -1
  22. package/dest/l1/spire_proposer.js +9 -17
  23. package/dest/modules/data_source_base.d.ts +5 -5
  24. package/dest/modules/data_source_base.d.ts.map +1 -1
  25. package/dest/modules/data_source_base.js +5 -5
  26. package/dest/modules/data_store_updater.d.ts +17 -12
  27. package/dest/modules/data_store_updater.d.ts.map +1 -1
  28. package/dest/modules/data_store_updater.js +78 -77
  29. package/dest/modules/instrumentation.d.ts +12 -1
  30. package/dest/modules/instrumentation.d.ts.map +1 -1
  31. package/dest/modules/instrumentation.js +10 -0
  32. package/dest/modules/l1_synchronizer.d.ts +3 -7
  33. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  34. package/dest/modules/l1_synchronizer.js +46 -11
  35. package/dest/store/block_store.d.ts +12 -13
  36. package/dest/store/block_store.d.ts.map +1 -1
  37. package/dest/store/block_store.js +61 -61
  38. package/dest/store/contract_class_store.d.ts +2 -3
  39. package/dest/store/contract_class_store.d.ts.map +1 -1
  40. package/dest/store/contract_class_store.js +7 -67
  41. package/dest/store/contract_instance_store.d.ts +1 -1
  42. package/dest/store/contract_instance_store.d.ts.map +1 -1
  43. package/dest/store/contract_instance_store.js +6 -2
  44. package/dest/store/kv_archiver_store.d.ts +28 -18
  45. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  46. package/dest/store/kv_archiver_store.js +34 -21
  47. package/dest/store/log_store.d.ts +6 -3
  48. package/dest/store/log_store.d.ts.map +1 -1
  49. package/dest/store/log_store.js +93 -16
  50. package/dest/store/message_store.d.ts +5 -1
  51. package/dest/store/message_store.d.ts.map +1 -1
  52. package/dest/store/message_store.js +14 -1
  53. package/dest/test/fake_l1_state.d.ts +10 -1
  54. package/dest/test/fake_l1_state.d.ts.map +1 -1
  55. package/dest/test/fake_l1_state.js +81 -15
  56. package/dest/test/mock_l2_block_source.d.ts +4 -3
  57. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  58. package/dest/test/mock_l2_block_source.js +7 -4
  59. package/dest/test/mock_structs.d.ts +4 -1
  60. package/dest/test/mock_structs.d.ts.map +1 -1
  61. package/dest/test/mock_structs.js +13 -1
  62. package/dest/test/noop_l1_archiver.d.ts +4 -1
  63. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  64. package/dest/test/noop_l1_archiver.js +5 -1
  65. package/package.json +13 -13
  66. package/src/archiver.ts +80 -23
  67. package/src/config.ts +8 -1
  68. package/src/errors.ts +40 -24
  69. package/src/factory.ts +23 -16
  70. package/src/l1/README.md +25 -68
  71. package/src/l1/bin/retrieve-calldata.ts +40 -27
  72. package/src/l1/calldata_retriever.ts +231 -383
  73. package/src/l1/data_retrieval.ts +20 -25
  74. package/src/l1/spire_proposer.ts +7 -15
  75. package/src/modules/data_source_base.ts +11 -6
  76. package/src/modules/data_store_updater.ts +83 -107
  77. package/src/modules/instrumentation.ts +20 -0
  78. package/src/modules/l1_synchronizer.ts +55 -20
  79. package/src/store/block_store.ts +72 -69
  80. package/src/store/contract_class_store.ts +8 -106
  81. package/src/store/contract_instance_store.ts +8 -5
  82. package/src/store/kv_archiver_store.ts +43 -32
  83. package/src/store/log_store.ts +126 -27
  84. package/src/store/message_store.ts +20 -1
  85. package/src/test/fake_l1_state.ts +110 -19
  86. package/src/test/mock_l2_block_source.ts +15 -3
  87. package/src/test/mock_structs.ts +20 -6
  88. package/src/test/noop_l1_archiver.ts +7 -1
@@ -1,15 +1,14 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
2
  import { EpochCache } from '@aztec/epoch-cache';
3
3
  import { InboxContract, RollupContract } from '@aztec/ethereum/contracts';
4
- import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
5
4
  import type { L1BlockId } from '@aztec/ethereum/l1-types';
6
5
  import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
6
+ import { asyncPool } from '@aztec/foundation/async-pool';
7
7
  import { maxBigint } from '@aztec/foundation/bigint';
8
8
  import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
9
9
  import { Buffer32 } from '@aztec/foundation/buffer';
10
10
  import { pick } from '@aztec/foundation/collection';
11
11
  import { Fr } from '@aztec/foundation/curves/bn254';
12
- import { EthAddress } from '@aztec/foundation/eth-address';
13
12
  import { type Logger, createLogger } from '@aztec/foundation/log';
14
13
  import { count } from '@aztec/foundation/string';
15
14
  import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
@@ -61,10 +60,6 @@ export class ArchiverL1Synchronizer implements Traceable {
61
60
  private readonly debugClient: ViemPublicDebugClient,
62
61
  private readonly rollup: RollupContract,
63
62
  private readonly inbox: InboxContract,
64
- private readonly l1Addresses: Pick<
65
- L1ContractAddresses,
66
- 'registryAddress' | 'governanceProposerAddress' | 'slashFactoryAddress'
67
- > & { slashingProposerAddress: EthAddress },
68
63
  private readonly store: KVArchiverDataStore,
69
64
  private config: {
70
65
  batchSize: number;
@@ -75,13 +70,18 @@ export class ArchiverL1Synchronizer implements Traceable {
75
70
  private readonly epochCache: EpochCache,
76
71
  private readonly dateProvider: DateProvider,
77
72
  private readonly instrumentation: ArchiverInstrumentation,
78
- private readonly l1Constants: L1RollupConstants & { l1StartBlockHash: Buffer32; genesisArchiveRoot: Fr },
73
+ private readonly l1Constants: L1RollupConstants & {
74
+ l1StartBlockHash: Buffer32;
75
+ genesisArchiveRoot: Fr;
76
+ },
79
77
  private readonly events: ArchiverEmitter,
80
78
  tracer: Tracer,
81
79
  l2TipsCache?: L2TipsCache,
82
80
  private readonly log: Logger = createLogger('archiver:l1-sync'),
83
81
  ) {
84
- this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache);
82
+ this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache, {
83
+ rollupManaLimit: l1Constants.rollupManaLimit,
84
+ });
85
85
  this.tracer = tracer;
86
86
  }
87
87
 
@@ -217,6 +217,9 @@ export class ArchiverL1Synchronizer implements Traceable {
217
217
  this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
218
218
  }
219
219
 
220
+ // Update the finalized L2 checkpoint based on L1 finality.
221
+ await this.updateFinalizedCheckpoint();
222
+
220
223
  // After syncing has completed, update the current l1 block number and timestamp,
221
224
  // otherwise we risk announcing to the world that we've synced to a given point,
222
225
  // but the corresponding blocks have not been processed (see #12631).
@@ -232,6 +235,27 @@ export class ArchiverL1Synchronizer implements Traceable {
232
235
  });
233
236
  }
234
237
 
238
+ /** Query L1 for its finalized block and update the finalized checkpoint accordingly. */
239
+ private async updateFinalizedCheckpoint(): Promise<void> {
240
+ try {
241
+ const finalizedL1Block = await this.publicClient.getBlock({ blockTag: 'finalized', includeTransactions: false });
242
+ const finalizedL1BlockNumber = finalizedL1Block.number;
243
+ const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
244
+ blockNumber: finalizedL1BlockNumber,
245
+ });
246
+ const localFinalizedCheckpointNumber = await this.store.getFinalizedCheckpointNumber();
247
+ if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
248
+ await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
249
+ this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
250
+ finalizedCheckpointNumber,
251
+ finalizedL1BlockNumber,
252
+ });
253
+ }
254
+ } catch (err) {
255
+ this.log.warn(`Failed to update finalized checkpoint: ${err}`);
256
+ }
257
+ }
258
+
235
259
  /** Prune all proposed local blocks that should have been checkpointed by now. */
236
260
  private async pruneUncheckpointedBlocks(currentL1Timestamp: bigint) {
237
261
  const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
@@ -310,17 +334,20 @@ export class ArchiverL1Synchronizer implements Traceable {
310
334
 
311
335
  const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
312
336
 
313
- const checkpointPromises = Array.from({ length: checkpointsToUnwind })
314
- .fill(0)
315
- .map((_, i) => this.store.getCheckpointData(CheckpointNumber(i + pruneFrom)));
316
- const checkpoints = await Promise.all(checkpointPromises);
317
-
318
- const blockPromises = await Promise.all(
319
- checkpoints
320
- .filter(isDefined)
321
- .map(cp => this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber))),
337
+ // Fetch checkpoints and blocks in bounded batches to avoid unbounded concurrent
338
+ // promises when the gap between local pending and proven checkpoint numbers is large.
339
+ const BATCH_SIZE = 10;
340
+ const indices = Array.from({ length: checkpointsToUnwind }, (_, i) => CheckpointNumber(i + pruneFrom));
341
+ const checkpoints = (await asyncPool(BATCH_SIZE, indices, idx => this.store.getCheckpointData(idx))).filter(
342
+ isDefined,
322
343
  );
323
- const newBlocks = blockPromises.filter(isDefined).flat();
344
+ const newBlocks = (
345
+ await asyncPool(BATCH_SIZE, checkpoints, cp =>
346
+ this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber)),
347
+ )
348
+ )
349
+ .filter(isDefined)
350
+ .flat();
324
351
 
325
352
  // Emit an event for listening services to react to the chain prune
326
353
  this.events.emit(L2BlockSourceEvents.L2PruneUnproven, {
@@ -368,6 +395,7 @@ export class ArchiverL1Synchronizer implements Traceable {
368
395
  const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
369
396
  const localLastMessage = await this.store.getLastL1ToL2Message();
370
397
  const remoteMessagesState = await this.inbox.getState({ blockNumber: currentL1BlockNumber });
398
+ await this.store.setInboxTreeInProgress(remoteMessagesState.treeInProgress);
371
399
 
372
400
  this.log.trace(`Retrieved remote inbox state at L1 block ${currentL1BlockNumber}.`, {
373
401
  localMessagesInserted,
@@ -708,7 +736,6 @@ export class ArchiverL1Synchronizer implements Traceable {
708
736
  this.blobClient,
709
737
  searchStartBlock, // TODO(palla/reorg): If the L2 reorg was due to an L1 reorg, we need to start search earlier
710
738
  searchEndBlock,
711
- this.l1Addresses,
712
739
  this.instrumentation,
713
740
  this.log,
714
741
  !initialSyncComplete, // isHistoricalSync
@@ -803,6 +830,14 @@ export class ArchiverL1Synchronizer implements Traceable {
803
830
  );
804
831
  }
805
832
 
833
+ for (const published of validCheckpoints) {
834
+ this.instrumentation.processCheckpointL1Timing({
835
+ slotNumber: published.checkpoint.header.slotNumber,
836
+ l1Timestamp: published.l1.timestamp,
837
+ l1Constants: this.l1Constants,
838
+ });
839
+ }
840
+
806
841
  try {
807
842
  const updatedValidationResult =
808
843
  rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
@@ -821,7 +856,7 @@ export class ArchiverL1Synchronizer implements Traceable {
821
856
  const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
822
857
  const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
823
858
 
824
- this.log.warn(
859
+ this.log.info(
825
860
  `Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`,
826
861
  { prunedBlocks: result.prunedBlocks.map(b => b.toBlockInfo()), prunedSlotNumber, prunedCheckpointNumber },
827
862
  );
@@ -20,7 +20,7 @@ import {
20
20
  serializeValidateCheckpointResult,
21
21
  } from '@aztec/stdlib/block';
22
22
  import { type CheckpointData, L1PublishedData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
23
- import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
23
+ import { type L1RollupConstants, getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
24
24
  import { CheckpointHeader } from '@aztec/stdlib/rollup';
25
25
  import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
26
26
  import {
@@ -35,15 +35,14 @@ import {
35
35
  } from '@aztec/stdlib/tx';
36
36
 
37
37
  import {
38
+ BlockAlreadyCheckpointedError,
38
39
  BlockArchiveNotConsistentError,
39
40
  BlockIndexNotSequentialError,
40
41
  BlockNotFoundError,
41
42
  BlockNumberNotSequentialError,
42
43
  CannotOverwriteCheckpointedBlockError,
43
44
  CheckpointNotFoundError,
44
- CheckpointNumberNotConsistentError,
45
45
  CheckpointNumberNotSequentialError,
46
- InitialBlockNumberNotSequentialError,
47
46
  InitialCheckpointNumberNotSequentialError,
48
47
  } from '../errors.js';
49
48
 
@@ -97,6 +96,9 @@ export class BlockStore {
97
96
  /** Stores last proven checkpoint */
98
97
  #lastProvenCheckpoint: AztecAsyncSingleton<number>;
99
98
 
99
+ /** Stores last finalized checkpoint (proven at or before the finalized L1 block) */
100
+ #lastFinalizedCheckpoint: AztecAsyncSingleton<number>;
101
+
100
102
  /** Stores the pending chain validation status */
101
103
  #pendingChainValidationStatus: AztecAsyncSingleton<Buffer>;
102
104
 
@@ -111,10 +113,7 @@ export class BlockStore {
111
113
 
112
114
  #log = createLogger('archiver:block_store');
113
115
 
114
- constructor(
115
- private db: AztecAsyncKVStore,
116
- private l1Constants: Pick<L1RollupConstants, 'epochDuration'>,
117
- ) {
116
+ constructor(private db: AztecAsyncKVStore) {
118
117
  this.#blocks = db.openMap('archiver_blocks');
119
118
  this.#blockTxs = db.openMap('archiver_block_txs');
120
119
  this.#txEffects = db.openMap('archiver_tx_effects');
@@ -123,41 +122,42 @@ export class BlockStore {
123
122
  this.#blockArchiveIndex = db.openMap('archiver_block_archive_index');
124
123
  this.#lastSynchedL1Block = db.openSingleton('archiver_last_synched_l1_block');
125
124
  this.#lastProvenCheckpoint = db.openSingleton('archiver_last_proven_l2_checkpoint');
125
+ this.#lastFinalizedCheckpoint = db.openSingleton('archiver_last_finalized_l2_checkpoint');
126
126
  this.#pendingChainValidationStatus = db.openSingleton('archiver_pending_chain_validation_status');
127
127
  this.#checkpoints = db.openMap('archiver_checkpoints');
128
128
  this.#slotToCheckpoint = db.openMap('archiver_slot_to_checkpoint');
129
129
  }
130
130
 
131
131
  /**
132
- * Computes the finalized block number based on the proven block number.
133
- * A block is considered finalized when it's 2 epochs behind the proven block.
134
- * TODO(#13569): Compute proper finalized block number based on L1 finalized block.
135
- * TODO(palla/mbps): Even the provisional computation is wrong, since it should subtract checkpoints, not blocks
132
+ * Returns the finalized L2 block number. An L2 block is finalized when it was proven
133
+ * in an L1 block that has itself been finalized on Ethereum.
136
134
  * @returns The finalized block number.
137
135
  */
138
136
  async getFinalizedL2BlockNumber(): Promise<BlockNumber> {
139
- const provenBlockNumber = await this.getProvenBlockNumber();
140
- return BlockNumber(Math.max(provenBlockNumber - this.l1Constants.epochDuration * 2, 0));
137
+ const finalizedCheckpointNumber = await this.getFinalizedCheckpointNumber();
138
+ if (finalizedCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
139
+ return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
140
+ }
141
+ const checkpointStorage = await this.#checkpoints.getAsync(finalizedCheckpointNumber);
142
+ if (!checkpointStorage) {
143
+ throw new CheckpointNotFoundError(finalizedCheckpointNumber);
144
+ }
145
+ return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
141
146
  }
142
147
 
143
148
  /**
144
- * Append new proposed blocks to the store's list. All blocks must be for the 'current' checkpoint.
145
- * These are uncheckpointed blocks that have been proposed by the sequencer but not yet included in a checkpoint on L1.
149
+ * Append a new proposed block to the store.
150
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
146
151
  * For checkpointed blocks (already published to L1), use addCheckpoints() instead.
147
- * @param blocks - The proposed L2 blocks to be added to the store.
152
+ * @param block - The proposed L2 block to be added to the store.
148
153
  * @returns True if the operation is successful.
149
154
  */
150
- async addProposedBlocks(blocks: L2Block[], opts: { force?: boolean } = {}): Promise<boolean> {
151
- if (blocks.length === 0) {
152
- return true;
153
- }
154
-
155
+ async addProposedBlock(block: L2Block, opts: { force?: boolean } = {}): Promise<boolean> {
155
156
  return await this.db.transactionAsync(async () => {
156
- // Check that the block immediately before the first block to be added is present in the store.
157
- const firstBlockNumber = blocks[0].number;
158
- const firstBlockCheckpointNumber = blocks[0].checkpointNumber;
159
- const firstBlockIndex = blocks[0].indexWithinCheckpoint;
160
- const firstBlockLastArchive = blocks[0].header.lastArchive.root;
157
+ const blockNumber = block.number;
158
+ const blockCheckpointNumber = block.checkpointNumber;
159
+ const blockIndex = block.indexWithinCheckpoint;
160
+ const blockLastArchive = block.header.lastArchive.root;
161
161
 
162
162
  // Extract the latest block and checkpoint numbers
163
163
  const previousBlockNumber = await this.getLatestBlockNumber();
@@ -165,71 +165,52 @@ export class BlockStore {
165
165
 
166
166
  // Verify we're not overwriting checkpointed blocks
167
167
  const lastCheckpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
168
- if (!opts.force && firstBlockNumber <= lastCheckpointedBlockNumber) {
169
- throw new CannotOverwriteCheckpointedBlockError(firstBlockNumber, lastCheckpointedBlockNumber);
168
+ if (!opts.force && blockNumber <= lastCheckpointedBlockNumber) {
169
+ // Check if the proposed block matches the already-checkpointed one
170
+ const existingBlock = await this.getBlock(BlockNumber(blockNumber));
171
+ if (existingBlock && existingBlock.archive.root.equals(block.archive.root)) {
172
+ throw new BlockAlreadyCheckpointedError(blockNumber);
173
+ }
174
+ throw new CannotOverwriteCheckpointedBlockError(blockNumber, lastCheckpointedBlockNumber);
170
175
  }
171
176
 
172
- // Check that the first block number is the expected one
173
- if (!opts.force && previousBlockNumber !== firstBlockNumber - 1) {
174
- throw new InitialBlockNumberNotSequentialError(firstBlockNumber, previousBlockNumber);
177
+ // Check that the block number is the expected one
178
+ if (!opts.force && previousBlockNumber !== blockNumber - 1) {
179
+ throw new BlockNumberNotSequentialError(blockNumber, previousBlockNumber);
175
180
  }
176
181
 
177
182
  // The same check as above but for checkpoints
178
- if (!opts.force && previousCheckpointNumber !== firstBlockCheckpointNumber - 1) {
179
- throw new InitialCheckpointNumberNotSequentialError(firstBlockCheckpointNumber, previousCheckpointNumber);
183
+ if (!opts.force && previousCheckpointNumber !== blockCheckpointNumber - 1) {
184
+ throw new CheckpointNumberNotSequentialError(blockCheckpointNumber, previousCheckpointNumber);
180
185
  }
181
186
 
182
187
  // Extract the previous block if there is one and see if it is for the same checkpoint or not
183
188
  const previousBlockResult = await this.getBlock(previousBlockNumber);
184
189
 
185
- let expectedFirstblockIndex = 0;
190
+ let expectedBlockIndex = 0;
186
191
  let previousBlockIndex: number | undefined = undefined;
187
192
  if (previousBlockResult !== undefined) {
188
- if (previousBlockResult.checkpointNumber === firstBlockCheckpointNumber) {
193
+ if (previousBlockResult.checkpointNumber === blockCheckpointNumber) {
189
194
  // The previous block is for the same checkpoint, therefore our index should follow it
190
195
  previousBlockIndex = previousBlockResult.indexWithinCheckpoint;
191
- expectedFirstblockIndex = previousBlockIndex + 1;
196
+ expectedBlockIndex = previousBlockIndex + 1;
192
197
  }
193
- if (!previousBlockResult.archive.root.equals(firstBlockLastArchive)) {
198
+ if (!previousBlockResult.archive.root.equals(blockLastArchive)) {
194
199
  throw new BlockArchiveNotConsistentError(
195
- firstBlockNumber,
200
+ blockNumber,
196
201
  previousBlockResult.number,
197
- firstBlockLastArchive,
202
+ blockLastArchive,
198
203
  previousBlockResult.archive.root,
199
204
  );
200
205
  }
201
206
  }
202
207
 
203
- // Now check that the first block has the expected index value
204
- if (!opts.force && expectedFirstblockIndex !== firstBlockIndex) {
205
- throw new BlockIndexNotSequentialError(firstBlockIndex, previousBlockIndex);
208
+ // Now check that the block has the expected index value
209
+ if (!opts.force && expectedBlockIndex !== blockIndex) {
210
+ throw new BlockIndexNotSequentialError(blockIndex, previousBlockIndex);
206
211
  }
207
212
 
208
- // Iterate over blocks array and insert them, checking that the block numbers and indexes are sequential. Also check they are for the correct checkpoint.
209
- let previousBlock: L2Block | undefined = undefined;
210
- for (const block of blocks) {
211
- if (!opts.force && previousBlock) {
212
- if (previousBlock.number + 1 !== block.number) {
213
- throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
214
- }
215
- if (previousBlock.indexWithinCheckpoint + 1 !== block.indexWithinCheckpoint) {
216
- throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
217
- }
218
- if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
219
- throw new BlockArchiveNotConsistentError(
220
- block.number,
221
- previousBlock.number,
222
- block.header.lastArchive.root,
223
- previousBlock.archive.root,
224
- );
225
- }
226
- }
227
- if (!opts.force && firstBlockCheckpointNumber !== block.checkpointNumber) {
228
- throw new CheckpointNumberNotConsistentError(block.checkpointNumber, firstBlockCheckpointNumber);
229
- }
230
- previousBlock = block;
231
- await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
232
- }
213
+ await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
233
214
 
234
215
  return true;
235
216
  });
@@ -871,7 +852,10 @@ export class BlockStore {
871
852
  * @param txHash - The hash of a tx we try to get the receipt for.
872
853
  * @returns The requested tx receipt (or undefined if not found).
873
854
  */
874
- async getSettledTxReceipt(txHash: TxHash): Promise<TxReceipt | undefined> {
855
+ async getSettledTxReceipt(
856
+ txHash: TxHash,
857
+ l1Constants?: Pick<L1RollupConstants, 'epochDuration'>,
858
+ ): Promise<TxReceipt | undefined> {
875
859
  const txEffect = await this.getTxEffect(txHash);
876
860
  if (!txEffect) {
877
861
  return undefined;
@@ -880,10 +864,11 @@ export class BlockStore {
880
864
  const blockNumber = BlockNumber(txEffect.l2BlockNumber);
881
865
 
882
866
  // Use existing archiver methods to determine finalization level
883
- const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber] = await Promise.all([
867
+ const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber, blockData] = await Promise.all([
884
868
  this.getProvenBlockNumber(),
885
869
  this.getCheckpointedL2BlockNumber(),
886
870
  this.getFinalizedL2BlockNumber(),
871
+ this.getBlockData(blockNumber),
887
872
  ]);
888
873
 
889
874
  let status: TxStatus;
@@ -897,6 +882,9 @@ export class BlockStore {
897
882
  status = TxStatus.PROPOSED;
898
883
  }
899
884
 
885
+ const epochNumber =
886
+ blockData && l1Constants ? getEpochAtSlot(blockData.header.globalVariables.slotNumber, l1Constants) : undefined;
887
+
900
888
  return new TxReceipt(
901
889
  txHash,
902
890
  status,
@@ -905,6 +893,7 @@ export class BlockStore {
905
893
  txEffect.data.transactionFee.toBigInt(),
906
894
  txEffect.l2BlockHash,
907
895
  blockNumber,
896
+ epochNumber,
908
897
  );
909
898
  }
910
899
 
@@ -976,6 +965,20 @@ export class BlockStore {
976
965
  return result;
977
966
  }
978
967
 
968
+ async getFinalizedCheckpointNumber(): Promise<CheckpointNumber> {
969
+ const [latestCheckpointNumber, finalizedCheckpointNumber] = await Promise.all([
970
+ this.getLatestCheckpointNumber(),
971
+ this.#lastFinalizedCheckpoint.getAsync(),
972
+ ]);
973
+ return (finalizedCheckpointNumber ?? 0) > latestCheckpointNumber
974
+ ? latestCheckpointNumber
975
+ : CheckpointNumber(finalizedCheckpointNumber ?? 0);
976
+ }
977
+
978
+ setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber) {
979
+ return this.#lastFinalizedCheckpoint.set(checkpointNumber);
980
+ }
981
+
979
982
  #computeBlockRange(start: BlockNumber, limit: number): Required<Pick<Range<number>, 'start' | 'limit'>> {
980
983
  if (limit < 1) {
981
984
  throw new Error(`Invalid limit: ${limit}`);
@@ -2,14 +2,7 @@ import { Fr } from '@aztec/foundation/curves/bn254';
2
2
  import { toArray } from '@aztec/foundation/iterable';
3
3
  import { BufferReader, numToUInt8, serializeToBuffer } from '@aztec/foundation/serialize';
4
4
  import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
5
- import { FunctionSelector } from '@aztec/stdlib/abi';
6
- import type {
7
- ContractClassPublic,
8
- ContractClassPublicWithBlockNumber,
9
- ExecutablePrivateFunctionWithMembershipProof,
10
- UtilityFunctionWithMembershipProof,
11
- } from '@aztec/stdlib/contract';
12
- import { Vector } from '@aztec/stdlib/types';
5
+ import type { ContractClassPublic, ContractClassPublicWithBlockNumber } from '@aztec/stdlib/contract';
13
6
 
14
7
  /**
15
8
  * LMDB-based contract class storage for the archiver.
@@ -29,11 +22,15 @@ export class ContractClassStore {
29
22
  blockNumber: number,
30
23
  ): Promise<void> {
31
24
  await this.db.transactionAsync(async () => {
32
- await this.#contractClasses.setIfNotExists(
33
- contractClass.id.toString(),
25
+ const key = contractClass.id.toString();
26
+ if (await this.#contractClasses.hasAsync(key)) {
27
+ throw new Error(`Contract class ${key} already exists, cannot add again at block ${blockNumber}`);
28
+ }
29
+ await this.#contractClasses.set(
30
+ key,
34
31
  serializeContractClassPublic({ ...contractClass, l2BlockNumber: blockNumber }),
35
32
  );
36
- await this.#bytecodeCommitments.setIfNotExists(contractClass.id.toString(), bytecodeCommitment.toBuffer());
33
+ await this.#bytecodeCommitments.set(key, bytecodeCommitment.toBuffer());
37
34
  });
38
35
  }
39
36
 
@@ -60,37 +57,6 @@ export class ContractClassStore {
60
57
  async getContractClassIds(): Promise<Fr[]> {
61
58
  return (await toArray(this.#contractClasses.keysAsync())).map(key => Fr.fromHexString(key));
62
59
  }
63
-
64
- async addFunctions(
65
- contractClassId: Fr,
66
- newPrivateFunctions: ExecutablePrivateFunctionWithMembershipProof[],
67
- newUtilityFunctions: UtilityFunctionWithMembershipProof[],
68
- ): Promise<boolean> {
69
- await this.db.transactionAsync(async () => {
70
- const existingClassBuffer = await this.#contractClasses.getAsync(contractClassId.toString());
71
- if (!existingClassBuffer) {
72
- throw new Error(`Unknown contract class ${contractClassId} when adding private functions to store`);
73
- }
74
-
75
- const existingClass = deserializeContractClassPublic(existingClassBuffer);
76
- const { privateFunctions: existingPrivateFns, utilityFunctions: existingUtilityFns } = existingClass;
77
-
78
- const updatedClass: Omit<ContractClassPublicWithBlockNumber, 'id'> = {
79
- ...existingClass,
80
- privateFunctions: [
81
- ...existingPrivateFns,
82
- ...newPrivateFunctions.filter(newFn => !existingPrivateFns.some(f => f.selector.equals(newFn.selector))),
83
- ],
84
- utilityFunctions: [
85
- ...existingUtilityFns,
86
- ...newUtilityFunctions.filter(newFn => !existingUtilityFns.some(f => f.selector.equals(newFn.selector))),
87
- ],
88
- };
89
- await this.#contractClasses.set(contractClassId.toString(), serializeContractClassPublic(updatedClass));
90
- });
91
-
92
- return true;
93
- }
94
60
  }
95
61
 
96
62
  function serializeContractClassPublic(contractClass: Omit<ContractClassPublicWithBlockNumber, 'id'>): Buffer {
@@ -98,83 +64,19 @@ function serializeContractClassPublic(contractClass: Omit<ContractClassPublicWit
98
64
  contractClass.l2BlockNumber,
99
65
  numToUInt8(contractClass.version),
100
66
  contractClass.artifactHash,
101
- contractClass.privateFunctions.length,
102
- contractClass.privateFunctions.map(serializePrivateFunction),
103
- contractClass.utilityFunctions.length,
104
- contractClass.utilityFunctions.map(serializeUtilityFunction),
105
67
  contractClass.packedBytecode.length,
106
68
  contractClass.packedBytecode,
107
69
  contractClass.privateFunctionsRoot,
108
70
  );
109
71
  }
110
72
 
111
- function serializePrivateFunction(fn: ExecutablePrivateFunctionWithMembershipProof): Buffer {
112
- return serializeToBuffer(
113
- fn.selector,
114
- fn.vkHash,
115
- fn.bytecode.length,
116
- fn.bytecode,
117
- fn.functionMetadataHash,
118
- fn.artifactMetadataHash,
119
- fn.utilityFunctionsTreeRoot,
120
- new Vector(fn.privateFunctionTreeSiblingPath),
121
- fn.privateFunctionTreeLeafIndex,
122
- new Vector(fn.artifactTreeSiblingPath),
123
- fn.artifactTreeLeafIndex,
124
- );
125
- }
126
-
127
- function serializeUtilityFunction(fn: UtilityFunctionWithMembershipProof): Buffer {
128
- return serializeToBuffer(
129
- fn.selector,
130
- fn.bytecode.length,
131
- fn.bytecode,
132
- fn.functionMetadataHash,
133
- fn.artifactMetadataHash,
134
- fn.privateFunctionsArtifactTreeRoot,
135
- new Vector(fn.artifactTreeSiblingPath),
136
- fn.artifactTreeLeafIndex,
137
- );
138
- }
139
-
140
73
  function deserializeContractClassPublic(buffer: Buffer): Omit<ContractClassPublicWithBlockNumber, 'id'> {
141
74
  const reader = BufferReader.asReader(buffer);
142
75
  return {
143
76
  l2BlockNumber: reader.readNumber(),
144
77
  version: reader.readUInt8() as 1,
145
78
  artifactHash: reader.readObject(Fr),
146
- privateFunctions: reader.readVector({ fromBuffer: deserializePrivateFunction }),
147
- utilityFunctions: reader.readVector({ fromBuffer: deserializeUtilityFunction }),
148
79
  packedBytecode: reader.readBuffer(),
149
80
  privateFunctionsRoot: reader.readObject(Fr),
150
81
  };
151
82
  }
152
-
153
- function deserializePrivateFunction(buffer: Buffer | BufferReader): ExecutablePrivateFunctionWithMembershipProof {
154
- const reader = BufferReader.asReader(buffer);
155
- return {
156
- selector: reader.readObject(FunctionSelector),
157
- vkHash: reader.readObject(Fr),
158
- bytecode: reader.readBuffer(),
159
- functionMetadataHash: reader.readObject(Fr),
160
- artifactMetadataHash: reader.readObject(Fr),
161
- utilityFunctionsTreeRoot: reader.readObject(Fr),
162
- privateFunctionTreeSiblingPath: reader.readVector(Fr),
163
- privateFunctionTreeLeafIndex: reader.readNumber(),
164
- artifactTreeSiblingPath: reader.readVector(Fr),
165
- artifactTreeLeafIndex: reader.readNumber(),
166
- };
167
- }
168
-
169
- function deserializeUtilityFunction(buffer: Buffer | BufferReader): UtilityFunctionWithMembershipProof {
170
- const reader = BufferReader.asReader(buffer);
171
- return {
172
- selector: reader.readObject(FunctionSelector),
173
- bytecode: reader.readBuffer(),
174
- functionMetadataHash: reader.readObject(Fr),
175
- artifactMetadataHash: reader.readObject(Fr),
176
- privateFunctionsArtifactTreeRoot: reader.readObject(Fr),
177
- artifactTreeSiblingPath: reader.readVector(Fr),
178
- artifactTreeLeafIndex: reader.readNumber(),
179
- };
180
- }
@@ -27,11 +27,14 @@ export class ContractInstanceStore {
27
27
 
28
28
  addContractInstance(contractInstance: ContractInstanceWithAddress, blockNumber: number): Promise<void> {
29
29
  return this.db.transactionAsync(async () => {
30
- await this.#contractInstances.set(
31
- contractInstance.address.toString(),
32
- new SerializableContractInstance(contractInstance).toBuffer(),
33
- );
34
- await this.#contractInstancePublishedAt.set(contractInstance.address.toString(), blockNumber);
30
+ const key = contractInstance.address.toString();
31
+ if (await this.#contractInstances.hasAsync(key)) {
32
+ throw new Error(
33
+ `Contract instance at ${key} already exists (deployed at block ${await this.#contractInstancePublishedAt.getAsync(key)}), cannot add again at block ${blockNumber}`,
34
+ );
35
+ }
36
+ await this.#contractInstances.set(key, new SerializableContractInstance(contractInstance).toBuffer());
37
+ await this.#contractInstancePublishedAt.set(key, blockNumber);
35
38
  });
36
39
  }
37
40