@aztec/archiver 0.0.1-commit.3469e52 → 0.0.1-commit.35158ae7e

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 (107) hide show
  1. package/README.md +9 -0
  2. package/dest/archiver.d.ts +12 -9
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +98 -124
  5. package/dest/config.d.ts +3 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +2 -1
  8. package/dest/errors.d.ts +26 -9
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +34 -13
  11. package/dest/factory.d.ts +4 -2
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +29 -23
  14. package/dest/index.d.ts +2 -1
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +1 -0
  17. package/dest/l1/bin/retrieve-calldata.js +35 -32
  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 +190 -259
  21. package/dest/l1/data_retrieval.d.ts +9 -9
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +24 -22
  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_trace.d.ts +6 -3
  28. package/dest/l1/validate_trace.d.ts.map +1 -1
  29. package/dest/l1/validate_trace.js +13 -9
  30. package/dest/modules/data_source_base.d.ts +27 -23
  31. package/dest/modules/data_source_base.d.ts.map +1 -1
  32. package/dest/modules/data_source_base.js +49 -124
  33. package/dest/modules/data_store_updater.d.ts +42 -26
  34. package/dest/modules/data_store_updater.d.ts.map +1 -1
  35. package/dest/modules/data_store_updater.js +149 -129
  36. package/dest/modules/instrumentation.d.ts +17 -4
  37. package/dest/modules/instrumentation.d.ts.map +1 -1
  38. package/dest/modules/instrumentation.js +36 -12
  39. package/dest/modules/l1_synchronizer.d.ts +5 -8
  40. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  41. package/dest/modules/l1_synchronizer.js +59 -25
  42. package/dest/store/block_store.d.ts +49 -32
  43. package/dest/store/block_store.d.ts.map +1 -1
  44. package/dest/store/block_store.js +188 -95
  45. package/dest/store/contract_class_store.d.ts +2 -3
  46. package/dest/store/contract_class_store.d.ts.map +1 -1
  47. package/dest/store/contract_class_store.js +16 -72
  48. package/dest/store/contract_instance_store.d.ts +1 -1
  49. package/dest/store/contract_instance_store.d.ts.map +1 -1
  50. package/dest/store/contract_instance_store.js +6 -2
  51. package/dest/store/kv_archiver_store.d.ts +64 -36
  52. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  53. package/dest/store/kv_archiver_store.js +63 -29
  54. package/dest/store/l2_tips_cache.d.ts +19 -0
  55. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  56. package/dest/store/l2_tips_cache.js +89 -0
  57. package/dest/store/log_store.d.ts +9 -6
  58. package/dest/store/log_store.d.ts.map +1 -1
  59. package/dest/store/log_store.js +150 -53
  60. package/dest/store/message_store.d.ts +5 -1
  61. package/dest/store/message_store.d.ts.map +1 -1
  62. package/dest/store/message_store.js +14 -1
  63. package/dest/test/fake_l1_state.d.ts +16 -4
  64. package/dest/test/fake_l1_state.d.ts.map +1 -1
  65. package/dest/test/fake_l1_state.js +95 -23
  66. package/dest/test/index.js +3 -1
  67. package/dest/test/mock_archiver.d.ts +1 -1
  68. package/dest/test/mock_archiver.d.ts.map +1 -1
  69. package/dest/test/mock_archiver.js +3 -2
  70. package/dest/test/mock_l2_block_source.d.ts +39 -23
  71. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  72. package/dest/test/mock_l2_block_source.js +157 -112
  73. package/dest/test/mock_structs.d.ts +6 -2
  74. package/dest/test/mock_structs.d.ts.map +1 -1
  75. package/dest/test/mock_structs.js +24 -10
  76. package/dest/test/noop_l1_archiver.d.ts +26 -0
  77. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  78. package/dest/test/noop_l1_archiver.js +72 -0
  79. package/package.json +14 -13
  80. package/src/archiver.ts +126 -151
  81. package/src/config.ts +8 -1
  82. package/src/errors.ts +52 -24
  83. package/src/factory.ts +46 -22
  84. package/src/index.ts +1 -0
  85. package/src/l1/README.md +25 -68
  86. package/src/l1/bin/retrieve-calldata.ts +45 -33
  87. package/src/l1/calldata_retriever.ts +249 -379
  88. package/src/l1/data_retrieval.ts +27 -29
  89. package/src/l1/spire_proposer.ts +7 -15
  90. package/src/l1/validate_trace.ts +24 -6
  91. package/src/modules/data_source_base.ts +84 -169
  92. package/src/modules/data_store_updater.ts +166 -161
  93. package/src/modules/instrumentation.ts +46 -14
  94. package/src/modules/l1_synchronizer.ts +72 -36
  95. package/src/store/block_store.ts +239 -140
  96. package/src/store/contract_class_store.ts +16 -110
  97. package/src/store/contract_instance_store.ts +8 -5
  98. package/src/store/kv_archiver_store.ts +104 -53
  99. package/src/store/l2_tips_cache.ts +89 -0
  100. package/src/store/log_store.ts +231 -70
  101. package/src/store/message_store.ts +20 -1
  102. package/src/test/fake_l1_state.ts +127 -28
  103. package/src/test/index.ts +3 -0
  104. package/src/test/mock_archiver.ts +3 -2
  105. package/src/test/mock_l2_block_source.ts +211 -129
  106. package/src/test/mock_structs.ts +45 -15
  107. package/src/test/noop_l1_archiver.ts +115 -0
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@aztec/archiver",
3
- "version": "0.0.1-commit.3469e52",
3
+ "version": "0.0.1-commit.35158ae7e",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/index.js",
7
7
  "./test": "./dest/test/index.js",
8
+ "./test/noop-l1": "./dest/test/noop_l1_archiver.js",
8
9
  "./config": "./dest/config.js"
9
10
  },
10
11
  "typedocOptions": {
@@ -64,18 +65,18 @@
64
65
  ]
65
66
  },
66
67
  "dependencies": {
67
- "@aztec/blob-client": "0.0.1-commit.3469e52",
68
- "@aztec/blob-lib": "0.0.1-commit.3469e52",
69
- "@aztec/constants": "0.0.1-commit.3469e52",
70
- "@aztec/epoch-cache": "0.0.1-commit.3469e52",
71
- "@aztec/ethereum": "0.0.1-commit.3469e52",
72
- "@aztec/foundation": "0.0.1-commit.3469e52",
73
- "@aztec/kv-store": "0.0.1-commit.3469e52",
74
- "@aztec/l1-artifacts": "0.0.1-commit.3469e52",
75
- "@aztec/noir-protocol-circuits-types": "0.0.1-commit.3469e52",
76
- "@aztec/protocol-contracts": "0.0.1-commit.3469e52",
77
- "@aztec/stdlib": "0.0.1-commit.3469e52",
78
- "@aztec/telemetry-client": "0.0.1-commit.3469e52",
68
+ "@aztec/blob-client": "0.0.1-commit.35158ae7e",
69
+ "@aztec/blob-lib": "0.0.1-commit.35158ae7e",
70
+ "@aztec/constants": "0.0.1-commit.35158ae7e",
71
+ "@aztec/epoch-cache": "0.0.1-commit.35158ae7e",
72
+ "@aztec/ethereum": "0.0.1-commit.35158ae7e",
73
+ "@aztec/foundation": "0.0.1-commit.35158ae7e",
74
+ "@aztec/kv-store": "0.0.1-commit.35158ae7e",
75
+ "@aztec/l1-artifacts": "0.0.1-commit.35158ae7e",
76
+ "@aztec/noir-protocol-circuits-types": "0.0.1-commit.35158ae7e",
77
+ "@aztec/protocol-contracts": "0.0.1-commit.35158ae7e",
78
+ "@aztec/stdlib": "0.0.1-commit.35158ae7e",
79
+ "@aztec/telemetry-client": "0.0.1-commit.35158ae7e",
79
80
  "lodash.groupby": "^4.6.0",
80
81
  "lodash.omit": "^4.5.0",
81
82
  "tslib": "^2.5.0",
package/src/archiver.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
- import { GENESIS_BLOCK_HEADER_HASH, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
3
2
  import { EpochCache } from '@aztec/epoch-cache';
4
3
  import { BlockTagTooOldError, RollupContract } from '@aztec/ethereum/contracts';
5
4
  import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
@@ -15,9 +14,7 @@ import { RunningPromise, makeLoggingErrorHandler } from '@aztec/foundation/runni
15
14
  import { DateProvider } from '@aztec/foundation/timer';
16
15
  import {
17
16
  type ArchiverEmitter,
18
- type CheckpointId,
19
- GENESIS_CHECKPOINT_HEADER_HASH,
20
- L2BlockNew,
17
+ L2Block,
21
18
  type L2BlockSink,
22
19
  type L2Tips,
23
20
  type ValidateCheckpointResult,
@@ -25,28 +22,29 @@ import {
25
22
  import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
26
23
  import {
27
24
  type L1RollupConstants,
28
- getEpochNumberAtTimestamp,
29
- getSlotAtTimestamp,
25
+ getEpochAtSlot,
26
+ getSlotAtNextL1Block,
30
27
  getSlotRangeForEpoch,
31
28
  getTimestampRangeForEpoch,
32
29
  } from '@aztec/stdlib/epoch-helpers';
33
30
  import { type TelemetryClient, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
34
31
 
35
32
  import { type ArchiverConfig, mapArchiverConfig } from './config.js';
36
- import { NoBlobBodiesFoundError } from './errors.js';
33
+ import { BlockAlreadyCheckpointedError, NoBlobBodiesFoundError } from './errors.js';
37
34
  import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
38
35
  import { ArchiverDataSourceBase } from './modules/data_source_base.js';
39
36
  import { ArchiverDataStoreUpdater } from './modules/data_store_updater.js';
40
37
  import type { ArchiverInstrumentation } from './modules/instrumentation.js';
41
38
  import type { ArchiverL1Synchronizer } from './modules/l1_synchronizer.js';
42
39
  import type { KVArchiverDataStore } from './store/kv_archiver_store.js';
40
+ import { L2TipsCache } from './store/l2_tips_cache.js';
43
41
 
44
42
  /** Export ArchiverEmitter for use in factory and tests. */
45
43
  export type { ArchiverEmitter };
46
44
 
47
45
  /** Request to add a block to the archiver, queued for processing by the sync loop. */
48
46
  type AddBlockRequest = {
49
- block: L2BlockNew;
47
+ block: L2Block;
50
48
  resolve: () => void;
51
49
  reject: (err: Error) => void;
52
50
  };
@@ -68,7 +66,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
68
66
  public readonly events: ArchiverEmitter;
69
67
 
70
68
  /** A loop in which we will be continually fetching new checkpoints. */
71
- private runningPromise: RunningPromise;
69
+ protected runningPromise: RunningPromise;
72
70
 
73
71
  /** L1 synchronizer that handles fetching checkpoints and messages from L1. */
74
72
  private readonly synchronizer: ArchiverL1Synchronizer;
@@ -82,6 +80,9 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
82
80
  /** Helper to handle updates to the store */
83
81
  private readonly updater: ArchiverDataStoreUpdater;
84
82
 
83
+ /** In-memory cache for L2 chain tips. */
84
+ private readonly l2TipsCache: L2TipsCache;
85
+
85
86
  public readonly tracer: Tracer;
86
87
 
87
88
  /**
@@ -94,7 +95,6 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
94
95
  * @param dataStore - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
95
96
  * @param config - Archiver configuration options.
96
97
  * @param blobClient - Client for retrieving blob data.
97
- * @param epochCache - Cache for epoch-related data.
98
98
  * @param dateProvider - Provider for current date/time.
99
99
  * @param instrumentation - Instrumentation for metrics and tracing.
100
100
  * @param l1Constants - L1 rollup constants.
@@ -118,9 +118,13 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
118
118
  },
119
119
  private readonly blobClient: BlobClientInterface,
120
120
  instrumentation: ArchiverInstrumentation,
121
- protected override readonly l1Constants: L1RollupConstants & { l1StartBlockHash: Buffer32; genesisArchiveRoot: Fr },
121
+ protected override readonly l1Constants: L1RollupConstants & {
122
+ l1StartBlockHash: Buffer32;
123
+ genesisArchiveRoot: Fr;
124
+ },
122
125
  synchronizer: ArchiverL1Synchronizer,
123
126
  events: ArchiverEmitter,
127
+ l2TipsCache?: L2TipsCache,
124
128
  private readonly log: Logger = createLogger('archiver'),
125
129
  ) {
126
130
  super(dataStore, l1Constants);
@@ -129,7 +133,10 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
129
133
  this.initialSyncPromise = promiseWithResolvers();
130
134
  this.synchronizer = synchronizer;
131
135
  this.events = events;
132
- this.updater = new ArchiverDataStoreUpdater(this.dataStore);
136
+ this.l2TipsCache = l2TipsCache ?? new L2TipsCache(this.dataStore.blockStore);
137
+ this.updater = new ArchiverDataStoreUpdater(this.dataStore, this.l2TipsCache, {
138
+ rollupManaLimit: l1Constants.rollupManaLimit,
139
+ });
133
140
 
134
141
  // Running promise starts with a small interval inbetween runs, so all iterations needed for the initial sync
135
142
  // are done as fast as possible. This then gets updated once the initial sync completes.
@@ -158,7 +165,11 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
158
165
 
159
166
  await this.blobClient.testSources();
160
167
  await this.synchronizer.testEthereumNodeSynced();
161
- await validateAndLogTraceAvailability(this.debugClient, this.config.ethereumAllowNoDebugHosts ?? false);
168
+ await validateAndLogTraceAvailability(
169
+ this.debugClient,
170
+ this.config.ethereumAllowNoDebugHosts ?? false,
171
+ this.log.getBindings(),
172
+ );
162
173
 
163
174
  // Log initial state for the archiver
164
175
  const { l1StartBlock } = this.l1Constants;
@@ -187,7 +198,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
187
198
  * @param block - The L2 block to add.
188
199
  * @returns A promise that resolves when the block has been added to the store, or rejects on error.
189
200
  */
190
- public addBlock(block: L2BlockNew): Promise<void> {
201
+ public addBlock(block: L2Block): Promise<void> {
191
202
  return new Promise<void>((resolve, reject) => {
192
203
  this.blockQueue.push({ block, resolve, reject });
193
204
  this.log.debug(`Queued block ${block.number} for processing`);
@@ -212,13 +223,33 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
212
223
  const queuedItems = this.blockQueue.splice(0, this.blockQueue.length);
213
224
  this.log.debug(`Processing ${queuedItems.length} queued block(s)`);
214
225
 
226
+ // Calculate slot threshold for validation
227
+ const l1Timestamp = this.synchronizer.getL1Timestamp();
228
+ const slotAtNextL1Block =
229
+ l1Timestamp === undefined ? undefined : getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
230
+
215
231
  // Process each block individually to properly resolve/reject each promise
216
232
  for (const { block, resolve, reject } of queuedItems) {
233
+ const blockSlot = block.header.globalVariables.slotNumber;
234
+ if (slotAtNextL1Block !== undefined && blockSlot < slotAtNextL1Block) {
235
+ this.log.warn(
236
+ `Rejecting proposed block ${block.number} for past slot ${blockSlot} (current is ${slotAtNextL1Block})`,
237
+ { block: block.toBlockInfo(), l1Timestamp, slotAtNextL1Block },
238
+ );
239
+ reject(new Error(`Block ${block.number} is for past slot ${blockSlot} (current is ${slotAtNextL1Block})`));
240
+ continue;
241
+ }
242
+
217
243
  try {
218
- await this.updater.addBlocks([block]);
244
+ await this.updater.addProposedBlock(block);
219
245
  this.log.debug(`Added block ${block.number} to store`);
220
246
  resolve();
221
247
  } catch (err: any) {
248
+ if (err instanceof BlockAlreadyCheckpointedError) {
249
+ this.log.debug(`Proposed block ${block.number} matches already checkpointed block, ignoring late proposal`);
250
+ resolve();
251
+ continue;
252
+ }
222
253
  this.log.error(`Failed to add block ${block.number} to store: ${err.message}`);
223
254
  reject(err);
224
255
  }
@@ -310,21 +341,57 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
310
341
  return Promise.resolve(this.synchronizer.getL1Timestamp());
311
342
  }
312
343
 
313
- public getL2SlotNumber(): Promise<SlotNumber | undefined> {
344
+ public async getSyncedL2SlotNumber(): Promise<SlotNumber | undefined> {
345
+ // The synced L2 slot is the latest slot for which we have all L1 data,
346
+ // either because we have seen all L1 blocks for that slot, or because
347
+ // we have seen the corresponding checkpoint.
348
+
349
+ let slotFromL1Sync: SlotNumber | undefined;
314
350
  const l1Timestamp = this.synchronizer.getL1Timestamp();
315
- return Promise.resolve(l1Timestamp === undefined ? undefined : getSlotAtTimestamp(l1Timestamp, this.l1Constants));
351
+ if (l1Timestamp !== undefined) {
352
+ const nextL1BlockSlot = getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
353
+ if (Number(nextL1BlockSlot) > 0) {
354
+ slotFromL1Sync = SlotNumber.add(nextL1BlockSlot, -1);
355
+ }
356
+ }
357
+
358
+ let slotFromCheckpoint: SlotNumber | undefined;
359
+ const latestCheckpointNumber = await this.store.getSynchedCheckpointNumber();
360
+ if (latestCheckpointNumber > 0) {
361
+ const checkpointData = await this.store.getCheckpointData(latestCheckpointNumber);
362
+ if (checkpointData) {
363
+ slotFromCheckpoint = checkpointData.header.slotNumber;
364
+ }
365
+ }
366
+
367
+ if (slotFromL1Sync === undefined && slotFromCheckpoint === undefined) {
368
+ return undefined;
369
+ }
370
+ return SlotNumber(Math.max(slotFromL1Sync ?? 0, slotFromCheckpoint ?? 0));
316
371
  }
317
372
 
318
- public getL2EpochNumber(): Promise<EpochNumber | undefined> {
319
- const l1Timestamp = this.synchronizer.getL1Timestamp();
320
- return Promise.resolve(
321
- l1Timestamp === undefined ? undefined : getEpochNumberAtTimestamp(l1Timestamp, this.l1Constants),
322
- );
373
+ public async getSyncedL2EpochNumber(): Promise<EpochNumber | undefined> {
374
+ const syncedSlot = await this.getSyncedL2SlotNumber();
375
+ if (syncedSlot === undefined) {
376
+ return undefined;
377
+ }
378
+ // An epoch is fully synced when all its slots are synced.
379
+ // We check if syncedSlot is the last slot of its epoch; if so, that epoch is fully synced.
380
+ // Otherwise, only the previous epoch is fully synced.
381
+ const epoch = getEpochAtSlot(syncedSlot, this.l1Constants);
382
+ const [, endSlot] = getSlotRangeForEpoch(epoch, this.l1Constants);
383
+ if (syncedSlot >= endSlot) {
384
+ return epoch;
385
+ }
386
+ return Number(epoch) > 0 ? EpochNumber(Number(epoch) - 1) : undefined;
323
387
  }
324
388
 
325
389
  public async isEpochComplete(epochNumber: EpochNumber): Promise<boolean> {
326
- // The epoch is complete if the current L2 block is the last one in the epoch (or later)
327
- const header = await this.getBlockHeader('latest');
390
+ // The epoch is complete if the current checkpointed L2 block is the last one in the epoch (or later).
391
+ // We use the checkpointed block number (synced from L1) instead of 'latest' to avoid returning true
392
+ // prematurely when proposed blocks have been pushed to the archiver but not yet checkpointed on L1.
393
+ const checkpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
394
+ const header = checkpointedBlockNumber > 0 ? await this.getBlockHeader(checkpointedBlockNumber) : undefined;
328
395
  const slot = header ? header.globalVariables.slotNumber : undefined;
329
396
  const [_startSlot, endSlot] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
330
397
  if (slot && slot >= endSlot) {
@@ -355,8 +422,8 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
355
422
  return this.initialSyncComplete;
356
423
  }
357
424
 
358
- public unwindCheckpoints(from: CheckpointNumber, checkpointsToUnwind: number): Promise<boolean> {
359
- return this.updater.unwindCheckpoints(from, checkpointsToUnwind);
425
+ public removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
426
+ return this.updater.removeCheckpointsAfter(checkpointNumber);
360
427
  }
361
428
 
362
429
  /** Used by TXE to add checkpoints directly without syncing from L1. */
@@ -364,125 +431,15 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
364
431
  checkpoints: PublishedCheckpoint[],
365
432
  pendingChainValidationStatus?: ValidateCheckpointResult,
366
433
  ): Promise<boolean> {
367
- await this.updater.setNewCheckpointData(checkpoints, pendingChainValidationStatus);
434
+ await this.updater.addCheckpoints(checkpoints, pendingChainValidationStatus);
368
435
  return true;
369
436
  }
370
437
 
371
- public async getL2Tips(): Promise<L2Tips> {
372
- const [latestBlockNumber, provenBlockNumber, checkpointedBlockNumber] = await Promise.all([
373
- this.getBlockNumber(),
374
- this.getProvenBlockNumber(),
375
- this.getCheckpointedBlockNumber(),
376
- ] as const);
377
-
378
- // TODO(#13569): Compute proper finalized block number based on L1 finalized block.
379
- // We just force it 2 epochs worth of proven data for now.
380
- // NOTE: update end-to-end/src/e2e_epochs/epochs_empty_blocks.test.ts as that uses finalized blocks in computations
381
- const finalizedBlockNumber = BlockNumber(Math.max(provenBlockNumber - this.l1Constants.epochDuration * 2, 0));
382
-
383
- const beforeInitialblockNumber = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
384
-
385
- // Get the latest block header and checkpointed blocks for proven, finalised and checkpointed blocks
386
- const [latestBlockHeader, provenCheckpointedBlock, finalizedCheckpointedBlock, checkpointedBlock] =
387
- await Promise.all([
388
- latestBlockNumber > beforeInitialblockNumber ? this.getBlockHeader(latestBlockNumber) : undefined,
389
- provenBlockNumber > beforeInitialblockNumber ? this.getCheckpointedBlock(provenBlockNumber) : undefined,
390
- finalizedBlockNumber > beforeInitialblockNumber ? this.getCheckpointedBlock(finalizedBlockNumber) : undefined,
391
- checkpointedBlockNumber > beforeInitialblockNumber
392
- ? this.getCheckpointedBlock(checkpointedBlockNumber)
393
- : undefined,
394
- ] as const);
395
-
396
- if (latestBlockNumber > beforeInitialblockNumber && !latestBlockHeader) {
397
- throw new Error(`Failed to retrieve latest block header for block ${latestBlockNumber}`);
398
- }
399
-
400
- // Checkpointed blocks must exist for proven, finalized and checkpointed tips if they are beyond the initial block number.
401
- if (checkpointedBlockNumber > beforeInitialblockNumber && !checkpointedBlock?.block.header) {
402
- throw new Error(
403
- `Failed to retrieve checkpointed block header for block ${checkpointedBlockNumber} (latest block is ${latestBlockNumber})`,
404
- );
405
- }
406
-
407
- if (provenBlockNumber > beforeInitialblockNumber && !provenCheckpointedBlock?.block.header) {
408
- throw new Error(
409
- `Failed to retrieve proven checkpointed for block ${provenBlockNumber} (latest block is ${latestBlockNumber})`,
410
- );
411
- }
412
-
413
- if (finalizedBlockNumber > beforeInitialblockNumber && !finalizedCheckpointedBlock?.block.header) {
414
- throw new Error(
415
- `Failed to retrieve finalized block header for block ${finalizedBlockNumber} (latest block is ${latestBlockNumber})`,
416
- );
417
- }
418
-
419
- const latestBlockHeaderHash = (await latestBlockHeader?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
420
- const provenBlockHeaderHash = (await provenCheckpointedBlock?.block.header?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
421
- const finalizedBlockHeaderHash =
422
- (await finalizedCheckpointedBlock?.block.header?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
423
- const checkpointedBlockHeaderHash = (await checkpointedBlock?.block.header?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
424
-
425
- // Now attempt to retrieve checkpoints for proven, finalised and checkpointed blocks
426
- const [[provenBlockCheckpoint], [finalizedBlockCheckpoint], [checkpointedBlockCheckpoint]] = await Promise.all([
427
- provenCheckpointedBlock !== undefined
428
- ? await this.getPublishedCheckpoints(provenCheckpointedBlock?.checkpointNumber, 1)
429
- : [undefined],
430
- finalizedCheckpointedBlock !== undefined
431
- ? await this.getPublishedCheckpoints(finalizedCheckpointedBlock?.checkpointNumber, 1)
432
- : [undefined],
433
- checkpointedBlock !== undefined
434
- ? await this.getPublishedCheckpoints(checkpointedBlock?.checkpointNumber, 1)
435
- : [undefined],
436
- ]);
437
-
438
- const initialcheckpointId: CheckpointId = {
439
- number: CheckpointNumber.ZERO,
440
- hash: GENESIS_CHECKPOINT_HEADER_HASH.toString(),
441
- };
442
-
443
- const makeCheckpointId = (checkpoint: PublishedCheckpoint | undefined) => {
444
- if (checkpoint === undefined) {
445
- return initialcheckpointId;
446
- }
447
- return {
448
- number: checkpoint.checkpoint.number,
449
- hash: checkpoint.checkpoint.hash().toString(),
450
- };
451
- };
452
-
453
- const l2Tips: L2Tips = {
454
- proposed: {
455
- number: latestBlockNumber,
456
- hash: latestBlockHeaderHash.toString(),
457
- },
458
- proven: {
459
- block: {
460
- number: provenBlockNumber,
461
- hash: provenBlockHeaderHash.toString(),
462
- },
463
- checkpoint: makeCheckpointId(provenBlockCheckpoint),
464
- },
465
- finalized: {
466
- block: {
467
- number: finalizedBlockNumber,
468
- hash: finalizedBlockHeaderHash.toString(),
469
- },
470
- checkpoint: makeCheckpointId(finalizedBlockCheckpoint),
471
- },
472
- checkpointed: {
473
- block: {
474
- number: checkpointedBlockNumber,
475
- hash: checkpointedBlockHeaderHash.toString(),
476
- },
477
- checkpoint: makeCheckpointId(checkpointedBlockCheckpoint),
478
- },
479
- };
480
-
481
- return l2Tips;
438
+ public getL2Tips(): Promise<L2Tips> {
439
+ return this.l2TipsCache.getL2Tips();
482
440
  }
483
441
 
484
442
  public async rollbackTo(targetL2BlockNumber: BlockNumber): Promise<void> {
485
- // TODO(pw/mbps): This still assumes 1 block per checkpoint
486
443
  const currentBlocks = await this.getL2Tips();
487
444
  const currentL2Block = currentBlocks.proposed.number;
488
445
  const currentProvenBlock = currentBlocks.proven.block.number;
@@ -490,13 +447,29 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
490
447
  if (targetL2BlockNumber >= currentL2Block) {
491
448
  throw new Error(`Target L2 block ${targetL2BlockNumber} must be less than current L2 block ${currentL2Block}`);
492
449
  }
493
- const blocksToUnwind = currentL2Block - targetL2BlockNumber;
494
450
  const targetL2Block = await this.store.getCheckpointedBlock(targetL2BlockNumber);
495
451
  if (!targetL2Block) {
496
452
  throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
497
453
  }
454
+ const targetCheckpointNumber = targetL2Block.checkpointNumber;
455
+
456
+ // Rollback operates at checkpoint granularity: the target block must be the last block of its checkpoint.
457
+ const checkpointData = await this.store.getCheckpointData(targetCheckpointNumber);
458
+ if (checkpointData) {
459
+ const lastBlockInCheckpoint = BlockNumber(checkpointData.startBlock + checkpointData.blockCount - 1);
460
+ if (targetL2BlockNumber !== lastBlockInCheckpoint) {
461
+ const previousCheckpointBoundary =
462
+ checkpointData.startBlock > 1 ? BlockNumber(checkpointData.startBlock - 1) : BlockNumber(0);
463
+ throw new Error(
464
+ `Target L2 block ${targetL2BlockNumber} is not at a checkpoint boundary. ` +
465
+ `Checkpoint ${targetCheckpointNumber} spans blocks ${checkpointData.startBlock} to ${lastBlockInCheckpoint}. ` +
466
+ `Use block ${lastBlockInCheckpoint} to roll back to this checkpoint, ` +
467
+ `or block ${previousCheckpointBoundary} to roll back to the previous one.`,
468
+ );
469
+ }
470
+ }
471
+
498
472
  const targetL1BlockNumber = targetL2Block.l1.blockNumber;
499
- const targetCheckpointNumber = CheckpointNumber.fromBlockNumber(targetL2BlockNumber);
500
473
  const targetL1Block = await this.publicClient.getBlock({
501
474
  blockNumber: targetL1BlockNumber,
502
475
  includeTransactions: false,
@@ -505,21 +478,23 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
505
478
  throw new Error(`Missing L1 block ${targetL1BlockNumber}`);
506
479
  }
507
480
  const targetL1BlockHash = Buffer32.fromString(targetL1Block.hash);
508
- this.log.info(`Unwinding ${blocksToUnwind} checkpoints from L2 block ${currentL2Block}`);
509
- await this.updater.unwindCheckpoints(CheckpointNumber(currentL2Block), blocksToUnwind);
510
- this.log.info(`Unwinding L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
481
+ this.log.info(
482
+ `Removing checkpoints after checkpoint ${targetCheckpointNumber} (target block ${targetL2BlockNumber})`,
483
+ );
484
+ await this.updater.removeCheckpointsAfter(targetCheckpointNumber);
485
+ this.log.info(`Rolling back L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
511
486
  await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
512
487
  this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
513
488
  await this.store.setCheckpointSynchedL1BlockNumber(targetL1BlockNumber);
514
489
  await this.store.setMessageSynchedL1Block({ l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash });
515
490
  if (targetL2BlockNumber < currentProvenBlock) {
516
- this.log.info(`Clearing proven L2 block number`);
517
- await this.store.setProvenCheckpointNumber(CheckpointNumber.ZERO);
491
+ this.log.info(`Rolling back proven L2 checkpoint to ${targetCheckpointNumber}`);
492
+ await this.updater.setProvenCheckpointNumber(targetCheckpointNumber);
493
+ }
494
+ const currentFinalizedBlock = currentBlocks.finalized.block.number;
495
+ if (targetL2BlockNumber < currentFinalizedBlock) {
496
+ this.log.info(`Rolling back finalized L2 checkpoint to ${targetCheckpointNumber}`);
497
+ await this.updater.setFinalizedCheckpointNumber(targetCheckpointNumber);
518
498
  }
519
- // TODO(palla/reorg): Set the finalized block when we add support for it.
520
- // if (targetL2BlockNumber < currentFinalizedBlock) {
521
- // this.log.info(`Clearing finalized L2 block number`);
522
- // await this.store.setFinalizedL2BlockNumber(0);
523
- // }
524
499
  }
525
500
  }
package/src/config.ts CHANGED
@@ -8,7 +8,12 @@ import {
8
8
  getConfigFromMappings,
9
9
  numberConfigHelper,
10
10
  } from '@aztec/foundation/config';
11
- import { type ChainConfig, chainConfigMappings } from '@aztec/stdlib/config';
11
+ import {
12
+ type ChainConfig,
13
+ type PipelineConfig,
14
+ chainConfigMappings,
15
+ pipelineConfigMappings,
16
+ } from '@aztec/stdlib/config';
12
17
  import type { ArchiverSpecificConfig } from '@aztec/stdlib/interfaces/server';
13
18
 
14
19
  /**
@@ -21,11 +26,13 @@ import type { ArchiverSpecificConfig } from '@aztec/stdlib/interfaces/server';
21
26
  export type ArchiverConfig = ArchiverSpecificConfig &
22
27
  L1ReaderConfig &
23
28
  L1ContractsConfig &
29
+ PipelineConfig & // required to pass through to epoch cache
24
30
  BlobClientConfig &
25
31
  ChainConfig;
26
32
 
27
33
  export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
28
34
  ...blobClientConfigMapping,
35
+ ...pipelineConfigMappings,
29
36
  archiverPollingIntervalMS: {
30
37
  env: 'ARCHIVER_POLLING_INTERVAL_MS',
31
38
  description: 'The polling interval in ms for retrieving new L2 blocks and encrypted logs.',
package/src/errors.ts CHANGED
@@ -6,24 +6,9 @@ export class NoBlobBodiesFoundError extends Error {
6
6
  }
7
7
  }
8
8
 
9
- export class InitialBlockNumberNotSequentialError extends Error {
10
- constructor(
11
- public readonly newBlockNumber: number,
12
- public readonly previousBlockNumber: number | undefined,
13
- ) {
14
- super(
15
- `Cannot insert new block ${newBlockNumber} given previous block number in store is ${
16
- previousBlockNumber ?? 'undefined'
17
- }`,
18
- );
19
- }
20
- }
21
-
22
9
  export class BlockNumberNotSequentialError extends Error {
23
10
  constructor(newBlockNumber: number, previous: number | undefined) {
24
- super(
25
- `Cannot insert new block ${newBlockNumber} given previous block number in batch is ${previous ?? 'undefined'}`,
26
- );
11
+ super(`Cannot insert new block ${newBlockNumber} given previous block number is ${previous ?? 'undefined'}`);
27
12
  }
28
13
  }
29
14
 
@@ -48,14 +33,6 @@ export class CheckpointNumberNotSequentialError extends Error {
48
33
  }
49
34
  }
50
35
 
51
- export class CheckpointNumberNotConsistentError extends Error {
52
- constructor(newCheckpointNumber: number, previous: number | undefined) {
53
- super(
54
- `Cannot insert block for new checkpoint ${newCheckpointNumber} given previous block was checkpoint ${previous ?? 'undefined'}`,
55
- );
56
- }
57
- }
58
-
59
36
  export class BlockIndexNotSequentialError extends Error {
60
37
  constructor(newBlockIndex: number, previousBlockIndex: number | undefined) {
61
38
  super(
@@ -88,3 +65,54 @@ export class BlockNotFoundError extends Error {
88
65
  super(`Failed to find expected block number ${blockNumber}`);
89
66
  }
90
67
  }
68
+
69
+ /** Thrown when a proposed block matches a block that was already checkpointed. This is expected for late proposals. */
70
+ export class BlockAlreadyCheckpointedError extends Error {
71
+ constructor(public readonly blockNumber: number) {
72
+ super(`Block ${blockNumber} has already been checkpointed with the same content`);
73
+ this.name = 'BlockAlreadyCheckpointedError';
74
+ }
75
+ }
76
+
77
+ /** Thrown when logs are added for a tag whose last stored log has a higher block number than the new log. */
78
+ export class OutOfOrderLogInsertionError extends Error {
79
+ constructor(
80
+ public readonly logType: 'private' | 'public',
81
+ public readonly tag: string,
82
+ public readonly lastBlockNumber: number,
83
+ public readonly newBlockNumber: number,
84
+ ) {
85
+ super(
86
+ `Out-of-order ${logType} log insertion for tag ${tag}: ` +
87
+ `last existing log is from block ${lastBlockNumber} but new log is from block ${newBlockNumber}`,
88
+ );
89
+ this.name = 'OutOfOrderLogInsertionError';
90
+ }
91
+ }
92
+
93
+ /** Thrown when L1 to L2 messages are requested for a checkpoint whose message tree hasn't been sealed yet. */
94
+ export class L1ToL2MessagesNotReadyError extends Error {
95
+ constructor(
96
+ public readonly checkpointNumber: number,
97
+ public readonly inboxTreeInProgress: bigint,
98
+ ) {
99
+ super(
100
+ `Cannot get L1 to L2 messages for checkpoint ${checkpointNumber}: ` +
101
+ `inbox tree in progress is ${inboxTreeInProgress}, messages not yet sealed`,
102
+ );
103
+ this.name = 'L1ToL2MessagesNotReadyError';
104
+ }
105
+ }
106
+
107
+ /** Thrown when a proposed block conflicts with an already checkpointed block (different content). */
108
+ export class CannotOverwriteCheckpointedBlockError extends Error {
109
+ constructor(
110
+ public readonly blockNumber: number,
111
+ public readonly lastCheckpointedBlock: number,
112
+ ) {
113
+ super(
114
+ `Cannot add block ${blockNumber}: would overwrite checkpointed data (checkpointed up to block ${lastCheckpointedBlock})`,
115
+ );
116
+ this.name = 'CannotOverwriteCheckpointedBlockError';
117
+ }
118
+ }