@aztec/archiver 0.0.1-commit.9372f48 → 0.0.1-commit.949a33fd8

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 +22 -11
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +152 -145
  5. package/dest/config.d.ts +5 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +16 -4
  8. package/dest/errors.d.ts +61 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +88 -14
  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 +74 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +197 -260
  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 +18 -7
  31. package/dest/modules/data_source_base.d.ts.map +1 -1
  32. package/dest/modules/data_source_base.js +51 -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 +139 -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 +11 -9
  40. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  41. package/dest/modules/l1_synchronizer.js +304 -151
  42. package/dest/modules/validation.d.ts +4 -3
  43. package/dest/modules/validation.d.ts.map +1 -1
  44. package/dest/modules/validation.js +6 -6
  45. package/dest/store/block_store.d.ts +98 -28
  46. package/dest/store/block_store.d.ts.map +1 -1
  47. package/dest/store/block_store.js +465 -138
  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 +85 -24
  55. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  56. package/dest/store/kv_archiver_store.js +106 -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 +25 -1
  67. package/dest/test/fake_l1_state.d.ts.map +1 -1
  68. package/dest/test/fake_l1_state.js +166 -32
  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 +35 -5
  76. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  77. package/dest/test/mock_l2_block_source.js +182 -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 +187 -164
  86. package/src/config.ts +23 -2
  87. package/src/errors.ts +133 -22
  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 +261 -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 +95 -98
  97. package/src/modules/data_store_updater.ts +168 -126
  98. package/src/modules/instrumentation.ts +56 -9
  99. package/src/modules/l1_synchronizer.ts +384 -188
  100. package/src/modules/validation.ts +10 -9
  101. package/src/store/block_store.ts +569 -174
  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 +167 -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 +213 -42
  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 +230 -82
  113. package/src/test/mock_structs.ts +20 -6
  114. package/src/test/noop_l1_archiver.ts +10 -2
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';
@@ -12,46 +11,55 @@ import { EthAddress } from '@aztec/foundation/eth-address';
12
11
  import { type Logger, createLogger } from '@aztec/foundation/log';
13
12
  import { type PromiseWithResolvers, promiseWithResolvers } from '@aztec/foundation/promise';
14
13
  import { RunningPromise, makeLoggingErrorHandler } from '@aztec/foundation/running-promise';
15
- import { DateProvider } from '@aztec/foundation/timer';
14
+ import { DateProvider, elapsed } from '@aztec/foundation/timer';
16
15
  import {
17
16
  type ArchiverEmitter,
18
- type CheckpointId,
19
- GENESIS_CHECKPOINT_HEADER_HASH,
20
17
  L2Block,
21
18
  type L2BlockSink,
22
19
  type L2Tips,
23
20
  type ValidateCheckpointResult,
24
21
  } from '@aztec/stdlib/block';
25
- import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
22
+ import { type ProposedCheckpointInput, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
26
23
  import {
27
24
  type L1RollupConstants,
28
- getEpochNumberAtTimestamp,
25
+ getEpochAtSlot,
29
26
  getSlotAtNextL1Block,
30
- getSlotAtTimestamp,
31
27
  getSlotRangeForEpoch,
28
+ getTimestampForSlot,
32
29
  getTimestampRangeForEpoch,
33
30
  } from '@aztec/stdlib/epoch-helpers';
34
31
  import { type TelemetryClient, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
35
32
 
36
33
  import { type ArchiverConfig, mapArchiverConfig } from './config.js';
37
- import { NoBlobBodiesFoundError } from './errors.js';
34
+ import { BlockAlreadyCheckpointedError, BlockOrCheckpointSlotExpiredError, NoBlobBodiesFoundError } from './errors.js';
35
+ import { validateAndLogHistoricalLogsAvailability } from './l1/validate_historical_logs.js';
38
36
  import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
39
37
  import { ArchiverDataSourceBase } from './modules/data_source_base.js';
40
38
  import { ArchiverDataStoreUpdater } from './modules/data_store_updater.js';
41
39
  import type { ArchiverInstrumentation } from './modules/instrumentation.js';
42
40
  import type { ArchiverL1Synchronizer } from './modules/l1_synchronizer.js';
43
41
  import type { KVArchiverDataStore } from './store/kv_archiver_store.js';
42
+ import { L2TipsCache } from './store/l2_tips_cache.js';
44
43
 
45
44
  /** Export ArchiverEmitter for use in factory and tests. */
46
45
  export type { ArchiverEmitter };
47
46
 
48
47
  /** Request to add a block to the archiver, queued for processing by the sync loop. */
49
48
  type AddBlockRequest = {
49
+ type: 'block';
50
50
  block: L2Block;
51
51
  resolve: () => void;
52
52
  reject: (err: Error) => void;
53
53
  };
54
54
 
55
+ /** Request to add a proposed checkpoint to the archiver, queued for processing by the sync loop. */
56
+ type AddProposedCheckpointRequest = {
57
+ type: 'checkpoint';
58
+ checkpoint: ProposedCheckpointInput;
59
+ resolve: () => void;
60
+ reject: (err: Error) => void;
61
+ };
62
+
55
63
  export type ArchiverDeps = {
56
64
  telemetry?: TelemetryClient;
57
65
  blobClient: BlobClientInterface;
@@ -77,25 +85,29 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
77
85
  private initialSyncComplete: boolean = false;
78
86
  private initialSyncPromise: PromiseWithResolvers<void>;
79
87
 
80
- /** Queue of blocks to be added to the store, processed by the sync loop. */
81
- private blockQueue: AddBlockRequest[] = [];
88
+ /** Queue of blocks and checkpoints to be added to the store, processed by the sync loop. */
89
+ private inboundQueue: (AddBlockRequest | AddProposedCheckpointRequest)[] = [];
82
90
 
83
91
  /** Helper to handle updates to the store */
84
92
  private readonly updater: ArchiverDataStoreUpdater;
85
93
 
94
+ /** In-memory cache for L2 chain tips. */
95
+ private readonly l2TipsCache: L2TipsCache;
96
+
86
97
  public readonly tracer: Tracer;
87
98
 
99
+ private readonly instrumentation: ArchiverInstrumentation;
100
+
88
101
  /**
89
102
  * Creates a new instance of the Archiver.
90
103
  * @param publicClient - A client for interacting with the Ethereum node.
91
104
  * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
92
105
  * @param rollup - Rollup contract instance.
93
106
  * @param inbox - Inbox contract instance.
94
- * @param l1Addresses - L1 contract addresses (registry, governance proposer, slash factory, slashing proposer).
107
+ * @param l1Addresses - L1 contract addresses (registry, governance proposer, slashing proposer).
95
108
  * @param dataStore - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
96
109
  * @param config - Archiver configuration options.
97
110
  * @param blobClient - Client for retrieving blob data.
98
- * @param epochCache - Cache for epoch-related data.
99
111
  * @param dateProvider - Provider for current date/time.
100
112
  * @param instrumentation - Instrumentation for metrics and tracing.
101
113
  * @param l1Constants - L1 rollup constants.
@@ -107,8 +119,10 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
107
119
  private readonly rollup: RollupContract,
108
120
  private readonly l1Addresses: Pick<
109
121
  L1ContractAddresses,
110
- 'registryAddress' | 'governanceProposerAddress' | 'slashFactoryAddress'
111
- > & { slashingProposerAddress: EthAddress },
122
+ 'rollupAddress' | 'registryAddress' | 'inboxAddress' | 'governanceProposerAddress'
123
+ > & {
124
+ slashingProposerAddress: EthAddress;
125
+ },
112
126
  readonly dataStore: KVArchiverDataStore,
113
127
  private config: {
114
128
  pollingIntervalMs: number;
@@ -116,21 +130,30 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
116
130
  skipValidateCheckpointAttestations?: boolean;
117
131
  maxAllowedEthClientDriftSeconds: number;
118
132
  ethereumAllowNoDebugHosts?: boolean;
133
+ skipHistoricalLogsCheck?: boolean;
119
134
  },
120
135
  private readonly blobClient: BlobClientInterface,
121
136
  instrumentation: ArchiverInstrumentation,
122
- protected override readonly l1Constants: L1RollupConstants & { l1StartBlockHash: Buffer32; genesisArchiveRoot: Fr },
137
+ protected override readonly l1Constants: L1RollupConstants & {
138
+ l1StartBlockHash: Buffer32;
139
+ genesisArchiveRoot: Fr;
140
+ },
123
141
  synchronizer: ArchiverL1Synchronizer,
124
142
  events: ArchiverEmitter,
143
+ l2TipsCache?: L2TipsCache,
125
144
  private readonly log: Logger = createLogger('archiver'),
126
145
  ) {
127
146
  super(dataStore, l1Constants);
128
147
 
129
148
  this.tracer = instrumentation.tracer;
149
+ this.instrumentation = instrumentation;
130
150
  this.initialSyncPromise = promiseWithResolvers();
131
151
  this.synchronizer = synchronizer;
132
152
  this.events = events;
133
- this.updater = new ArchiverDataStoreUpdater(this.dataStore);
153
+ this.l2TipsCache = l2TipsCache ?? new L2TipsCache(this.dataStore.blockStore);
154
+ this.updater = new ArchiverDataStoreUpdater(this.dataStore, this.l2TipsCache, {
155
+ rollupManaLimit: l1Constants.rollupManaLimit,
156
+ });
134
157
 
135
158
  // Running promise starts with a small interval inbetween runs, so all iterations needed for the initial sync
136
159
  // are done as fast as possible. This then gets updated once the initial sync completes.
@@ -164,6 +187,17 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
164
187
  this.config.ethereumAllowNoDebugHosts ?? false,
165
188
  this.log.getBindings(),
166
189
  );
190
+ await validateAndLogHistoricalLogsAvailability(
191
+ this.publicClient,
192
+ {
193
+ rollupAddress: this.l1Addresses.rollupAddress,
194
+ inboxAddress: this.l1Addresses.inboxAddress,
195
+ registryAddress: this.l1Addresses.registryAddress,
196
+ governanceProposerAddress: this.l1Addresses.governanceProposerAddress,
197
+ },
198
+ this.config.skipHistoricalLogsCheck ?? false,
199
+ this.log.getBindings(),
200
+ );
167
201
 
168
202
  // Log initial state for the archiver
169
203
  const { l1StartBlock } = this.l1Constants;
@@ -185,6 +219,14 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
185
219
  return this.runningPromise.trigger();
186
220
  }
187
221
 
222
+ public trySyncImmediate() {
223
+ try {
224
+ return this.syncImmediate();
225
+ } catch (err) {
226
+ this.log.error(`Failed to trigger immediate archiver sync: ${err}`, err);
227
+ }
228
+ }
229
+
188
230
  /**
189
231
  * Queues a block to be added to the archiver store and triggers processing.
190
232
  * The block will be processed by the sync loop.
@@ -193,53 +235,85 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
193
235
  * @returns A promise that resolves when the block has been added to the store, or rejects on error.
194
236
  */
195
237
  public addBlock(block: L2Block): Promise<void> {
196
- return new Promise<void>((resolve, reject) => {
197
- this.blockQueue.push({ block, resolve, reject });
198
- this.log.debug(`Queued block ${block.number} for processing`);
199
- // Trigger an immediate sync, but don't wait for it - the promise resolves when the block is processed
200
- this.syncImmediate().catch(err => {
201
- this.log.error(`Sync immediate call failed: ${err}`);
202
- });
203
- });
238
+ const promise = promiseWithResolvers<void>();
239
+ this.inboundQueue.push({ block, ...promise, type: 'block' });
240
+ this.log.debug(`Queued block ${block.number} for processing`);
241
+ void this.trySyncImmediate();
242
+ return promise.promise;
204
243
  }
205
244
 
206
245
  /**
207
- * Processes all queued blocks, adding them to the store.
246
+ * Queues a new proposed checkpoint into the archiver store.
247
+ * Checks that the checkpoint is not for an L2 slot already synced from L1.
248
+ * Resolves once the checkpoint has been processed.
249
+ */
250
+ public addProposedCheckpoint(pending: ProposedCheckpointInput): Promise<void> {
251
+ const promise = promiseWithResolvers<void>();
252
+ this.inboundQueue.push({ checkpoint: pending, ...promise, type: 'checkpoint' });
253
+ this.log.debug(`Queued checkpoint ${pending.checkpointNumber} for processing`);
254
+ void this.trySyncImmediate();
255
+ return promise.promise;
256
+ }
257
+
258
+ /**
259
+ * Processes all queued blocks and checkpoints, adding them to the store.
208
260
  * Called at the beginning of each sync iteration.
209
- * Blocks are processed in the order they were queued.
261
+ * Items are processed in the order they were queued.
210
262
  */
211
- private async processQueuedBlocks(): Promise<void> {
212
- if (this.blockQueue.length === 0) {
263
+ private async processInboundQueue(): Promise<void> {
264
+ if (this.inboundQueue.length === 0) {
213
265
  return;
214
266
  }
215
267
 
216
- // Take all blocks from the queue
217
- const queuedItems = this.blockQueue.splice(0, this.blockQueue.length);
218
- this.log.debug(`Processing ${queuedItems.length} queued block(s)`);
268
+ // Take all items from the queue
269
+ const queuedItems = this.inboundQueue.splice(0, this.inboundQueue.length);
270
+ this.log.debug(`Processing ${queuedItems.length} queued inbound items`);
219
271
 
220
272
  // Calculate slot threshold for validation
221
273
  const l1Timestamp = this.synchronizer.getL1Timestamp();
222
274
  const slotAtNextL1Block =
223
275
  l1Timestamp === undefined ? undefined : getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
224
276
 
225
- // Process each block individually to properly resolve/reject each promise
226
- for (const { block, resolve, reject } of queuedItems) {
227
- const blockSlot = block.header.globalVariables.slotNumber;
228
- if (slotAtNextL1Block !== undefined && blockSlot < slotAtNextL1Block) {
277
+ // Helpers for manipulating blocks and checkpoints in the queue
278
+ const getSlot: (item: AddBlockRequest | AddProposedCheckpointRequest) => SlotNumber = item =>
279
+ item.type === 'block' ? item.block.header.globalVariables.slotNumber : item.checkpoint.header.slotNumber;
280
+ const getNumber: (item: AddBlockRequest | AddProposedCheckpointRequest) => number = item =>
281
+ item.type === 'block' ? item.block.number : item.checkpoint.checkpointNumber;
282
+
283
+ // Process each item individually to properly resolve/reject each promise
284
+ for (const item of queuedItems) {
285
+ const { resolve, reject, type } = item;
286
+ const itemSlot = getSlot(item);
287
+ const itemNumber = getNumber(item);
288
+ if (slotAtNextL1Block !== undefined && itemSlot < slotAtNextL1Block) {
289
+ const nextSlotTimestamp = getTimestampForSlot(slotAtNextL1Block, this.l1Constants);
229
290
  this.log.warn(
230
- `Rejecting proposed block ${block.number} for past slot ${blockSlot} (current is ${slotAtNextL1Block})`,
231
- { block: block.toBlockInfo(), l1Timestamp, slotAtNextL1Block },
291
+ `Rejecting proposed ${type} ${itemNumber} for past slot ${itemSlot} (current ${slotAtNextL1Block})`,
292
+ { number: itemNumber, type, l1Timestamp, slotAtNextL1Block, nextSlotTimestamp },
232
293
  );
233
- reject(new Error(`Block ${block.number} is for past slot ${blockSlot} (current is ${slotAtNextL1Block})`));
294
+ reject(new BlockOrCheckpointSlotExpiredError(itemSlot, nextSlotTimestamp, l1Timestamp));
234
295
  continue;
235
296
  }
236
297
 
237
298
  try {
238
- await this.updater.addProposedBlocks([block]);
239
- this.log.debug(`Added block ${block.number} to store`);
299
+ if (type === 'block') {
300
+ const [durationMs] = await elapsed(() => this.updater.addProposedBlock(item.block));
301
+ this.instrumentation.processNewProposedBlock(durationMs, item.block);
302
+ } else {
303
+ await this.updater.addProposedCheckpoint(item.checkpoint);
304
+ }
305
+ this.log.debug(`Added ${type} ${itemNumber} to store`);
240
306
  resolve();
241
307
  } catch (err: any) {
242
- this.log.error(`Failed to add block ${block.number} to store: ${err.message}`);
308
+ if (err instanceof BlockAlreadyCheckpointedError) {
309
+ this.log.debug(`Proposed block ${itemNumber} matches already checkpointed block, ignoring late proposal`);
310
+ resolve();
311
+ continue;
312
+ }
313
+ this.log.error(`Failed to add ${type} ${itemNumber} to store: ${err.message}`, err, {
314
+ number: itemNumber,
315
+ type,
316
+ });
243
317
  reject(err);
244
318
  }
245
319
  }
@@ -255,7 +329,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
255
329
  @trackSpan('Archiver.sync')
256
330
  private async sync() {
257
331
  // Process any queued blocks first, before doing L1 sync
258
- await this.processQueuedBlocks();
332
+ await this.processInboundQueue();
259
333
  // Now perform L1 sync
260
334
  await this.syncFromL1();
261
335
  }
@@ -330,16 +404,49 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
330
404
  return Promise.resolve(this.synchronizer.getL1Timestamp());
331
405
  }
332
406
 
333
- public getL2SlotNumber(): Promise<SlotNumber | undefined> {
407
+ public async getSyncedL2SlotNumber(): Promise<SlotNumber | undefined> {
408
+ // The synced L2 slot is the latest slot for which we have all L1 data,
409
+ // either because we have seen all L1 blocks for that slot, or because
410
+ // we have seen the corresponding checkpoint.
411
+
412
+ let slotFromL1Sync: SlotNumber | undefined;
334
413
  const l1Timestamp = this.synchronizer.getL1Timestamp();
335
- return Promise.resolve(l1Timestamp === undefined ? undefined : getSlotAtTimestamp(l1Timestamp, this.l1Constants));
414
+ if (l1Timestamp !== undefined) {
415
+ const nextL1BlockSlot = getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
416
+ if (Number(nextL1BlockSlot) > 0) {
417
+ slotFromL1Sync = SlotNumber.add(nextL1BlockSlot, -1);
418
+ }
419
+ }
420
+
421
+ let slotFromCheckpoint: SlotNumber | undefined;
422
+ const latestCheckpointNumber = await this.store.getSynchedCheckpointNumber();
423
+ if (latestCheckpointNumber > 0) {
424
+ const checkpointData = await this.store.getCheckpointData(latestCheckpointNumber);
425
+ if (checkpointData) {
426
+ slotFromCheckpoint = checkpointData.header.slotNumber;
427
+ }
428
+ }
429
+
430
+ if (slotFromL1Sync === undefined && slotFromCheckpoint === undefined) {
431
+ return undefined;
432
+ }
433
+ return SlotNumber(Math.max(slotFromL1Sync ?? 0, slotFromCheckpoint ?? 0));
336
434
  }
337
435
 
338
- public getL2EpochNumber(): Promise<EpochNumber | undefined> {
339
- const l1Timestamp = this.synchronizer.getL1Timestamp();
340
- return Promise.resolve(
341
- l1Timestamp === undefined ? undefined : getEpochNumberAtTimestamp(l1Timestamp, this.l1Constants),
342
- );
436
+ public async getSyncedL2EpochNumber(): Promise<EpochNumber | undefined> {
437
+ const syncedSlot = await this.getSyncedL2SlotNumber();
438
+ if (syncedSlot === undefined) {
439
+ return undefined;
440
+ }
441
+ // An epoch is fully synced when all its slots are synced.
442
+ // We check if syncedSlot is the last slot of its epoch; if so, that epoch is fully synced.
443
+ // Otherwise, only the previous epoch is fully synced.
444
+ const epoch = getEpochAtSlot(syncedSlot, this.l1Constants);
445
+ const [, endSlot] = getSlotRangeForEpoch(epoch, this.l1Constants);
446
+ if (syncedSlot >= endSlot) {
447
+ return epoch;
448
+ }
449
+ return Number(epoch) > 0 ? EpochNumber(Number(epoch) - 1) : undefined;
343
450
  }
344
451
 
345
452
  public async isEpochComplete(epochNumber: EpochNumber): Promise<boolean> {
@@ -391,115 +498,11 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
391
498
  return true;
392
499
  }
393
500
 
394
- public async getL2Tips(): Promise<L2Tips> {
395
- const [latestBlockNumber, provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber] = await Promise.all([
396
- this.getBlockNumber(),
397
- this.getProvenBlockNumber(),
398
- this.getCheckpointedL2BlockNumber(),
399
- this.getFinalizedL2BlockNumber(),
400
- ] as const);
401
-
402
- const beforeInitialblockNumber = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
403
-
404
- // Get the latest block header and checkpointed blocks for proven, finalised and checkpointed blocks
405
- const [latestBlockHeader, provenCheckpointedBlock, finalizedCheckpointedBlock, checkpointedBlock] =
406
- await Promise.all([
407
- latestBlockNumber > beforeInitialblockNumber ? this.getBlockHeader(latestBlockNumber) : undefined,
408
- provenBlockNumber > beforeInitialblockNumber ? this.getCheckpointedBlock(provenBlockNumber) : undefined,
409
- finalizedBlockNumber > beforeInitialblockNumber ? this.getCheckpointedBlock(finalizedBlockNumber) : undefined,
410
- checkpointedBlockNumber > beforeInitialblockNumber
411
- ? this.getCheckpointedBlock(checkpointedBlockNumber)
412
- : undefined,
413
- ] as const);
414
-
415
- if (latestBlockNumber > beforeInitialblockNumber && !latestBlockHeader) {
416
- throw new Error(`Failed to retrieve latest block header for block ${latestBlockNumber}`);
417
- }
418
-
419
- // Checkpointed blocks must exist for proven, finalized and checkpointed tips if they are beyond the initial block number.
420
- if (checkpointedBlockNumber > beforeInitialblockNumber && !checkpointedBlock?.block.header) {
421
- throw new Error(
422
- `Failed to retrieve checkpointed block header for block ${checkpointedBlockNumber} (latest block is ${latestBlockNumber})`,
423
- );
424
- }
425
-
426
- if (provenBlockNumber > beforeInitialblockNumber && !provenCheckpointedBlock?.block.header) {
427
- throw new Error(
428
- `Failed to retrieve proven checkpointed for block ${provenBlockNumber} (latest block is ${latestBlockNumber})`,
429
- );
430
- }
431
-
432
- if (finalizedBlockNumber > beforeInitialblockNumber && !finalizedCheckpointedBlock?.block.header) {
433
- throw new Error(
434
- `Failed to retrieve finalized block header for block ${finalizedBlockNumber} (latest block is ${latestBlockNumber})`,
435
- );
436
- }
437
-
438
- const latestBlockHeaderHash = (await latestBlockHeader?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
439
- const provenBlockHeaderHash = (await provenCheckpointedBlock?.block.header?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
440
- const finalizedBlockHeaderHash =
441
- (await finalizedCheckpointedBlock?.block.header?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
442
- const checkpointedBlockHeaderHash = (await checkpointedBlock?.block.header?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
443
-
444
- // Now attempt to retrieve checkpoints for proven, finalised and checkpointed blocks
445
- const [[provenBlockCheckpoint], [finalizedBlockCheckpoint], [checkpointedBlockCheckpoint]] = await Promise.all([
446
- provenCheckpointedBlock !== undefined
447
- ? await this.getCheckpoints(provenCheckpointedBlock?.checkpointNumber, 1)
448
- : [undefined],
449
- finalizedCheckpointedBlock !== undefined
450
- ? await this.getCheckpoints(finalizedCheckpointedBlock?.checkpointNumber, 1)
451
- : [undefined],
452
- checkpointedBlock !== undefined ? await this.getCheckpoints(checkpointedBlock?.checkpointNumber, 1) : [undefined],
453
- ]);
454
-
455
- const initialcheckpointId: CheckpointId = {
456
- number: CheckpointNumber.ZERO,
457
- hash: GENESIS_CHECKPOINT_HEADER_HASH.toString(),
458
- };
459
-
460
- const makeCheckpointId = (checkpoint: PublishedCheckpoint | undefined) => {
461
- if (checkpoint === undefined) {
462
- return initialcheckpointId;
463
- }
464
- return {
465
- number: checkpoint.checkpoint.number,
466
- hash: checkpoint.checkpoint.hash().toString(),
467
- };
468
- };
469
-
470
- const l2Tips: L2Tips = {
471
- proposed: {
472
- number: latestBlockNumber,
473
- hash: latestBlockHeaderHash.toString(),
474
- },
475
- proven: {
476
- block: {
477
- number: provenBlockNumber,
478
- hash: provenBlockHeaderHash.toString(),
479
- },
480
- checkpoint: makeCheckpointId(provenBlockCheckpoint),
481
- },
482
- finalized: {
483
- block: {
484
- number: finalizedBlockNumber,
485
- hash: finalizedBlockHeaderHash.toString(),
486
- },
487
- checkpoint: makeCheckpointId(finalizedBlockCheckpoint),
488
- },
489
- checkpointed: {
490
- block: {
491
- number: checkpointedBlockNumber,
492
- hash: checkpointedBlockHeaderHash.toString(),
493
- },
494
- checkpoint: makeCheckpointId(checkpointedBlockCheckpoint),
495
- },
496
- };
497
-
498
- return l2Tips;
501
+ public getL2Tips(): Promise<L2Tips> {
502
+ return this.l2TipsCache.getL2Tips();
499
503
  }
500
504
 
501
505
  public async rollbackTo(targetL2BlockNumber: BlockNumber): Promise<void> {
502
- // TODO(pw/mbps): This still assumes 1 block per checkpoint
503
506
  const currentBlocks = await this.getL2Tips();
504
507
  const currentL2Block = currentBlocks.proposed.number;
505
508
  const currentProvenBlock = currentBlocks.proven.block.number;
@@ -511,8 +514,25 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
511
514
  if (!targetL2Block) {
512
515
  throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
513
516
  }
514
- const targetL1BlockNumber = targetL2Block.l1.blockNumber;
515
517
  const targetCheckpointNumber = targetL2Block.checkpointNumber;
518
+
519
+ // Rollback operates at checkpoint granularity: the target block must be the last block of its checkpoint.
520
+ const checkpointData = await this.store.getCheckpointData(targetCheckpointNumber);
521
+ if (checkpointData) {
522
+ const lastBlockInCheckpoint = BlockNumber(checkpointData.startBlock + checkpointData.blockCount - 1);
523
+ if (targetL2BlockNumber !== lastBlockInCheckpoint) {
524
+ const previousCheckpointBoundary =
525
+ checkpointData.startBlock > 1 ? BlockNumber(checkpointData.startBlock - 1) : BlockNumber(0);
526
+ throw new Error(
527
+ `Target L2 block ${targetL2BlockNumber} is not at a checkpoint boundary. ` +
528
+ `Checkpoint ${targetCheckpointNumber} spans blocks ${checkpointData.startBlock} to ${lastBlockInCheckpoint}. ` +
529
+ `Use block ${lastBlockInCheckpoint} to roll back to this checkpoint, ` +
530
+ `or block ${previousCheckpointBoundary} to roll back to the previous one.`,
531
+ );
532
+ }
533
+ }
534
+
535
+ const targetL1BlockNumber = targetL2Block.l1.blockNumber;
516
536
  const targetL1Block = await this.publicClient.getBlock({
517
537
  blockNumber: targetL1BlockNumber,
518
538
  includeTransactions: false,
@@ -529,15 +549,18 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
529
549
  await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
530
550
  this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
531
551
  await this.store.setCheckpointSynchedL1BlockNumber(targetL1BlockNumber);
532
- await this.store.setMessageSynchedL1Block({ l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash });
552
+ await this.store.setMessageSyncState(
553
+ { l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash },
554
+ undefined,
555
+ );
533
556
  if (targetL2BlockNumber < currentProvenBlock) {
534
- this.log.info(`Clearing proven L2 block number`);
535
- await this.store.setProvenCheckpointNumber(CheckpointNumber.ZERO);
557
+ this.log.info(`Rolling back proven L2 checkpoint to ${targetCheckpointNumber}`);
558
+ await this.updater.setProvenCheckpointNumber(targetCheckpointNumber);
559
+ }
560
+ const currentFinalizedBlock = currentBlocks.finalized.block.number;
561
+ if (targetL2BlockNumber < currentFinalizedBlock) {
562
+ this.log.info(`Rolling back finalized L2 checkpoint to ${targetCheckpointNumber}`);
563
+ await this.updater.setFinalizedCheckpointNumber(targetCheckpointNumber);
536
564
  }
537
- // TODO(palla/reorg): Set the finalized block when we add support for it.
538
- // if (targetL2BlockNumber < currentFinalizedBlock) {
539
- // this.log.info(`Clearing finalized L2 block number`);
540
- // await this.store.setFinalizedL2BlockNumber(0);
541
- // }
542
565
  }
543
566
  }
package/src/config.ts CHANGED
@@ -7,8 +7,14 @@ import {
7
7
  booleanConfigHelper,
8
8
  getConfigFromMappings,
9
9
  numberConfigHelper,
10
+ optionalNumberConfigHelper,
10
11
  } from '@aztec/foundation/config';
11
- import { type ChainConfig, chainConfigMappings } from '@aztec/stdlib/config';
12
+ import {
13
+ type ChainConfig,
14
+ type PipelineConfig,
15
+ chainConfigMappings,
16
+ pipelineConfigMappings,
17
+ } from '@aztec/stdlib/config';
12
18
  import type { ArchiverSpecificConfig } from '@aztec/stdlib/interfaces/server';
13
19
 
14
20
  /**
@@ -21,11 +27,13 @@ import type { ArchiverSpecificConfig } from '@aztec/stdlib/interfaces/server';
21
27
  export type ArchiverConfig = ArchiverSpecificConfig &
22
28
  L1ReaderConfig &
23
29
  L1ContractsConfig &
30
+ PipelineConfig & // required to pass through to epoch cache
24
31
  BlobClientConfig &
25
32
  ChainConfig;
26
33
 
27
34
  export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
28
35
  ...blobClientConfigMapping,
36
+ ...pipelineConfigMappings,
29
37
  archiverPollingIntervalMS: {
30
38
  env: 'ARCHIVER_POLLING_INTERVAL_MS',
31
39
  description: 'The polling interval in ms for retrieving new L2 blocks and encrypted logs.',
@@ -43,13 +51,17 @@ export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
43
51
  },
44
52
  archiverStoreMapSizeKb: {
45
53
  env: 'ARCHIVER_STORE_MAP_SIZE_KB',
46
- parseEnv: (val: string | undefined) => (val ? +val : undefined),
54
+ ...optionalNumberConfigHelper(),
47
55
  description: 'The maximum possible size of the archiver DB in KB. Overwrites the general dataStoreMapSizeKb.',
48
56
  },
49
57
  skipValidateCheckpointAttestations: {
50
58
  description: 'Skip validating checkpoint attestations (for testing purposes only)',
51
59
  ...booleanConfigHelper(false),
52
60
  },
61
+ skipPromoteProposedCheckpointDuringL1Sync: {
62
+ description: 'Skip promoting proposed checkpoints during L1 sync (for testing purposes only)',
63
+ ...booleanConfigHelper(false),
64
+ },
53
65
  maxAllowedEthClientDriftSeconds: {
54
66
  env: 'MAX_ALLOWED_ETH_CLIENT_DRIFT_SECONDS',
55
67
  description: 'Maximum allowed drift in seconds between the Ethereum client and current time.',
@@ -60,6 +72,13 @@ export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
60
72
  description: 'Whether to allow starting the archiver without debug/trace method support on Ethereum hosts',
61
73
  ...booleanConfigHelper(true),
62
74
  },
75
+ archiverSkipHistoricalLogsCheck: {
76
+ env: 'ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK',
77
+ description:
78
+ 'Skip the startup check that probes the L1 RPC for historical Rollup contract logs. ' +
79
+ 'Set to true to bypass the check when the connected RPC node is known to prune old logs.',
80
+ ...booleanConfigHelper(false),
81
+ },
63
82
  ...chainConfigMappings,
64
83
  ...l1ReaderConfigMappings,
65
84
  viemPollingIntervalMS: {
@@ -89,7 +108,9 @@ export function mapArchiverConfig(config: Partial<ArchiverConfig>) {
89
108
  pollingIntervalMs: config.archiverPollingIntervalMS,
90
109
  batchSize: config.archiverBatchSize,
91
110
  skipValidateCheckpointAttestations: config.skipValidateCheckpointAttestations,
111
+ skipPromoteProposedCheckpointDuringL1Sync: config.skipPromoteProposedCheckpointDuringL1Sync,
92
112
  maxAllowedEthClientDriftSeconds: config.maxAllowedEthClientDriftSeconds,
93
113
  ethereumAllowNoDebugHosts: config.ethereumAllowNoDebugHosts,
114
+ skipHistoricalLogsCheck: config.archiverSkipHistoricalLogsCheck,
94
115
  };
95
116
  }