@aztec/archiver 0.0.1-commit.29c6b1a3 → 0.0.1-commit.2c0ee1788

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