@aztec/archiver 0.0.1-commit.c2eed6949 → 0.0.1-commit.c52d6e7

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 (121) hide show
  1. package/README.md +19 -11
  2. package/dest/archiver.d.ts +71 -15
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +276 -70
  5. package/dest/config.d.ts +7 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +44 -16
  8. package/dest/errors.d.ts +44 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +66 -12
  11. package/dest/factory.d.ts +18 -6
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +66 -21
  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/calldata_retriever.d.ts +9 -1
  18. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  19. package/dest/l1/calldata_retriever.js +22 -11
  20. package/dest/l1/data_retrieval.d.ts +25 -11
  21. package/dest/l1/data_retrieval.d.ts.map +1 -1
  22. package/dest/l1/data_retrieval.js +25 -32
  23. package/dest/l1/trace_tx.d.ts +12 -66
  24. package/dest/l1/trace_tx.d.ts.map +1 -1
  25. package/dest/l1/validate_historical_logs.d.ts +23 -0
  26. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  27. package/dest/l1/validate_historical_logs.js +108 -0
  28. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  29. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  30. package/dest/modules/contract_data_source_adapter.js +32 -0
  31. package/dest/modules/data_source_base.d.ts +71 -48
  32. package/dest/modules/data_source_base.d.ts.map +1 -1
  33. package/dest/modules/data_source_base.js +250 -144
  34. package/dest/modules/data_store_updater.d.ts +28 -8
  35. package/dest/modules/data_store_updater.d.ts.map +1 -1
  36. package/dest/modules/data_store_updater.js +124 -55
  37. package/dest/modules/instrumentation.d.ts +15 -2
  38. package/dest/modules/instrumentation.d.ts.map +1 -1
  39. package/dest/modules/instrumentation.js +48 -9
  40. package/dest/modules/l1_synchronizer.d.ts +13 -8
  41. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  42. package/dest/modules/l1_synchronizer.js +453 -219
  43. package/dest/modules/outbox_trees_resolver.d.ts +64 -0
  44. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  45. package/dest/modules/outbox_trees_resolver.js +184 -0
  46. package/dest/modules/validation.d.ts +30 -7
  47. package/dest/modules/validation.d.ts.map +1 -1
  48. package/dest/modules/validation.js +35 -17
  49. package/dest/store/block_store.d.ts +177 -68
  50. package/dest/store/block_store.d.ts.map +1 -1
  51. package/dest/store/block_store.js +719 -246
  52. package/dest/store/contract_class_store.d.ts +17 -3
  53. package/dest/store/contract_class_store.d.ts.map +1 -1
  54. package/dest/store/contract_class_store.js +36 -2
  55. package/dest/store/contract_instance_store.d.ts +28 -1
  56. package/dest/store/contract_instance_store.d.ts.map +1 -1
  57. package/dest/store/contract_instance_store.js +49 -1
  58. package/dest/store/data_stores.d.ts +68 -0
  59. package/dest/store/data_stores.d.ts.map +1 -0
  60. package/dest/store/data_stores.js +54 -0
  61. package/dest/store/function_names_cache.d.ts +17 -0
  62. package/dest/store/function_names_cache.d.ts.map +1 -0
  63. package/dest/store/function_names_cache.js +30 -0
  64. package/dest/store/l2_tips_cache.d.ts +13 -7
  65. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  66. package/dest/store/l2_tips_cache.js +13 -76
  67. package/dest/store/log_store.d.ts +42 -40
  68. package/dest/store/log_store.d.ts.map +1 -1
  69. package/dest/store/log_store.js +257 -480
  70. package/dest/store/log_store_codec.d.ts +78 -0
  71. package/dest/store/log_store_codec.d.ts.map +1 -0
  72. package/dest/store/log_store_codec.js +110 -0
  73. package/dest/store/message_store.d.ts +9 -3
  74. package/dest/store/message_store.d.ts.map +1 -1
  75. package/dest/store/message_store.js +39 -10
  76. package/dest/test/fake_l1_state.d.ts +15 -3
  77. package/dest/test/fake_l1_state.d.ts.map +1 -1
  78. package/dest/test/fake_l1_state.js +83 -21
  79. package/dest/test/mock_l2_block_source.d.ts +48 -50
  80. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  81. package/dest/test/mock_l2_block_source.js +228 -179
  82. package/dest/test/mock_structs.d.ts +1 -1
  83. package/dest/test/mock_structs.d.ts.map +1 -1
  84. package/dest/test/mock_structs.js +2 -2
  85. package/dest/test/noop_l1_archiver.d.ts +14 -6
  86. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  87. package/dest/test/noop_l1_archiver.js +26 -10
  88. package/package.json +14 -14
  89. package/src/archiver.ts +362 -76
  90. package/src/config.ts +51 -20
  91. package/src/errors.ts +103 -18
  92. package/src/factory.ts +80 -19
  93. package/src/index.ts +18 -2
  94. package/src/l1/calldata_retriever.ts +29 -11
  95. package/src/l1/data_retrieval.ts +44 -46
  96. package/src/l1/validate_historical_logs.ts +140 -0
  97. package/src/modules/contract_data_source_adapter.ts +46 -0
  98. package/src/modules/data_source_base.ts +325 -192
  99. package/src/modules/data_store_updater.ts +152 -57
  100. package/src/modules/instrumentation.ts +43 -10
  101. package/src/modules/l1_synchronizer.ts +612 -259
  102. package/src/modules/outbox_trees_resolver.ts +220 -0
  103. package/src/modules/validation.ts +80 -23
  104. package/src/store/block_store.ts +879 -300
  105. package/src/store/contract_class_store.ts +47 -3
  106. package/src/store/contract_instance_store.ts +61 -1
  107. package/src/store/data_stores.ts +104 -0
  108. package/src/store/function_names_cache.ts +37 -0
  109. package/src/store/l2_tips_cache.ts +16 -70
  110. package/src/store/log_store.ts +296 -652
  111. package/src/store/log_store_codec.ts +143 -0
  112. package/src/store/message_store.ts +43 -12
  113. package/src/structs/inbox_message.ts +1 -1
  114. package/src/test/fake_l1_state.ts +102 -30
  115. package/src/test/mock_l2_block_source.ts +285 -232
  116. package/src/test/mock_structs.ts +5 -2
  117. package/src/test/noop_l1_archiver.ts +54 -11
  118. package/dest/store/kv_archiver_store.d.ts +0 -364
  119. package/dest/store/kv_archiver_store.d.ts.map +0 -1
  120. package/dest/store/kv_archiver_store.js +0 -477
  121. package/src/store/kv_archiver_store.ts +0 -682
package/src/archiver.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
2
  import { EpochCache } from '@aztec/epoch-cache';
3
- import { BlockTagTooOldError, RollupContract } from '@aztec/ethereum/contracts';
3
+ import { BlockTagTooOldError, OutboxContract, RollupContract } from '@aztec/ethereum/contracts';
4
4
  import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
5
5
  import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
6
6
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
@@ -11,32 +11,41 @@ import { EthAddress } from '@aztec/foundation/eth-address';
11
11
  import { type Logger, createLogger } from '@aztec/foundation/log';
12
12
  import { type PromiseWithResolvers, promiseWithResolvers } from '@aztec/foundation/promise';
13
13
  import { RunningPromise, makeLoggingErrorHandler } from '@aztec/foundation/running-promise';
14
- import { DateProvider } from '@aztec/foundation/timer';
14
+ import { DateProvider, elapsed } from '@aztec/foundation/timer';
15
15
  import {
16
16
  type ArchiverEmitter,
17
+ type BlockHash,
17
18
  L2Block,
18
19
  type L2BlockSink,
20
+ L2BlockSourceEvents,
19
21
  type L2Tips,
20
22
  type ValidateCheckpointResult,
23
+ l2TipsEqual,
21
24
  } from '@aztec/stdlib/block';
22
- import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
25
+ import { type ProposedCheckpointInput, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
23
26
  import {
24
27
  type L1RollupConstants,
25
28
  getEpochAtSlot,
26
29
  getSlotAtNextL1Block,
27
30
  getSlotRangeForEpoch,
31
+ getTimestampForSlot,
28
32
  getTimestampRangeForEpoch,
29
33
  } from '@aztec/stdlib/epoch-helpers';
34
+ import type { L2ToL1MembershipWitness } from '@aztec/stdlib/messaging';
35
+ import { ConsensusTimetable } from '@aztec/stdlib/timetable';
36
+ import type { BlockHeader, TxHash } from '@aztec/stdlib/tx';
30
37
  import { type TelemetryClient, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
31
38
 
32
39
  import { type ArchiverConfig, mapArchiverConfig } from './config.js';
33
- import { BlockAlreadyCheckpointedError, NoBlobBodiesFoundError } from './errors.js';
40
+ import { BlockAlreadyCheckpointedError, BlockOrCheckpointSlotExpiredError, NoBlobBodiesFoundError } from './errors.js';
41
+ import { validateAndLogHistoricalLogsAvailability } from './l1/validate_historical_logs.js';
34
42
  import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
35
43
  import { ArchiverDataSourceBase } from './modules/data_source_base.js';
36
44
  import { ArchiverDataStoreUpdater } from './modules/data_store_updater.js';
37
45
  import type { ArchiverInstrumentation } from './modules/instrumentation.js';
38
46
  import type { ArchiverL1Synchronizer } from './modules/l1_synchronizer.js';
39
- import type { KVArchiverDataStore } from './store/kv_archiver_store.js';
47
+ import { OutboxTreesResolver } from './modules/outbox_trees_resolver.js';
48
+ import { type ArchiverDataStores, backupArchiverDataStores, getArchiverSynchPoint } from './store/data_stores.js';
40
49
  import { L2TipsCache } from './store/l2_tips_cache.js';
41
50
 
42
51
  /** Export ArchiverEmitter for use in factory and tests. */
@@ -44,11 +53,20 @@ export type { ArchiverEmitter };
44
53
 
45
54
  /** Request to add a block to the archiver, queued for processing by the sync loop. */
46
55
  type AddBlockRequest = {
56
+ type: 'block';
47
57
  block: L2Block;
48
58
  resolve: () => void;
49
59
  reject: (err: Error) => void;
50
60
  };
51
61
 
62
+ /** Request to add a proposed checkpoint to the archiver, queued for processing by the sync loop. */
63
+ type AddProposedCheckpointRequest = {
64
+ type: 'checkpoint';
65
+ checkpoint: ProposedCheckpointInput;
66
+ resolve: () => void;
67
+ reject: (err: Error) => void;
68
+ };
69
+
52
70
  export type ArchiverDeps = {
53
71
  telemetry?: TelemetryClient;
54
72
  blobClient: BlobClientInterface;
@@ -56,6 +74,16 @@ export type ArchiverDeps = {
56
74
  dateProvider?: DateProvider;
57
75
  };
58
76
 
77
+ /** Minimal dependency for observing whether a checkpoint proposal was received for a slot. */
78
+ export type CheckpointProposalPresence = {
79
+ /** Returns true when a checkpoint proposal for `slot` has been retained locally. */
80
+ hasCheckpointProposalForSlot(slot: SlotNumber): Promise<boolean>;
81
+ };
82
+
83
+ const noCheckpointProposalPresence: CheckpointProposalPresence = {
84
+ hasCheckpointProposalForSlot: () => Promise.resolve(false),
85
+ };
86
+
59
87
  /**
60
88
  * Pulls checkpoints in a non-blocking manner and provides interface for their retrieval.
61
89
  * Responsible for handling robust L1 polling so that other components do not need to
@@ -71,11 +99,14 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
71
99
  /** L1 synchronizer that handles fetching checkpoints and messages from L1. */
72
100
  private readonly synchronizer: ArchiverL1Synchronizer;
73
101
 
102
+ /** Resolver for L2-to-L1 message membership witnesses, built over this archiver's read view. */
103
+ private readonly outboxTreesResolver: OutboxTreesResolver;
104
+
74
105
  private initialSyncComplete: boolean = false;
75
106
  private initialSyncPromise: PromiseWithResolvers<void>;
76
107
 
77
- /** Queue of blocks to be added to the store, processed by the sync loop. */
78
- private blockQueue: AddBlockRequest[] = [];
108
+ /** Queue of blocks and checkpoints to be added to the store, processed by the sync loop. */
109
+ private inboundQueue: (AddBlockRequest | AddProposedCheckpointRequest)[] = [];
79
110
 
80
111
  /** Helper to handle updates to the store */
81
112
  private readonly updater: ArchiverDataStoreUpdater;
@@ -83,38 +114,57 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
83
114
  /** In-memory cache for L2 chain tips. */
84
115
  private readonly l2TipsCache: L2TipsCache;
85
116
 
117
+ /** Consensus timing model used for proposed-checkpoint arrival expectations. */
118
+ private readonly timetable: ConsensusTimetable;
119
+
86
120
  public readonly tracer: Tracer;
87
121
 
122
+ private readonly instrumentation: ArchiverInstrumentation;
123
+
88
124
  /**
89
125
  * Creates a new instance of the Archiver.
90
126
  * @param publicClient - A client for interacting with the Ethereum node.
91
127
  * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
92
128
  * @param rollup - Rollup contract instance.
129
+ * @param outbox - Outbox contract instance, used to read per-epoch L2-to-L1 message roots.
93
130
  * @param inbox - Inbox contract instance.
94
- * @param l1Addresses - L1 contract addresses (registry, governance proposer, slash factory, slashing proposer).
95
- * @param dataStore - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
131
+ * @param l1Addresses - L1 contract addresses (registry, governance proposer, slashing proposer).
132
+ * @param dataStores - Archiver substores for storage & retrieval of blocks, encrypted logs & contract data.
96
133
  * @param config - Archiver configuration options.
97
134
  * @param blobClient - Client for retrieving blob data.
98
- * @param dateProvider - Provider for current date/time.
99
135
  * @param instrumentation - Instrumentation for metrics and tracing.
100
136
  * @param l1Constants - L1 rollup constants.
137
+ * @param synchronizer - L1 synchronizer that handles fetching checkpoints and messages from L1.
138
+ * @param events - Event emitter shared with the synchronizer.
139
+ * @param initialHeader - Genesis block header.
140
+ * @param initialBlockHash - Precomputed hash of the genesis block header.
141
+ * @param l2TipsCache - In-memory cache for L2 chain tips.
142
+ * @param dateProvider - Provider for current date/time, used for wall-clock orphan-block pruning.
101
143
  * @param log - A logger.
102
144
  */
103
145
  constructor(
104
146
  private readonly publicClient: ViemPublicClient,
105
147
  private readonly debugClient: ViemPublicDebugClient,
106
148
  private readonly rollup: RollupContract,
149
+ private readonly outbox: OutboxContract,
107
150
  private readonly l1Addresses: Pick<
108
151
  L1ContractAddresses,
109
- 'registryAddress' | 'governanceProposerAddress' | 'slashFactoryAddress'
110
- > & { slashingProposerAddress: EthAddress },
111
- readonly dataStore: KVArchiverDataStore,
152
+ 'rollupAddress' | 'registryAddress' | 'inboxAddress' | 'governanceProposerAddress'
153
+ > & {
154
+ slashingProposerAddress: EthAddress;
155
+ },
156
+ readonly dataStores: ArchiverDataStores,
112
157
  private config: {
113
158
  pollingIntervalMs: number;
114
159
  batchSize: number;
115
160
  skipValidateCheckpointAttestations?: boolean;
116
161
  maxAllowedEthClientDriftSeconds: number;
117
162
  ethereumAllowNoDebugHosts?: boolean;
163
+ skipHistoricalLogsCheck?: boolean;
164
+ checkpointProposalSyncGrace: number;
165
+ orphanPruneNoProposalTolerance: number;
166
+ skipOrphanProposedBlockPruning: boolean;
167
+ blockDuration: number;
118
168
  },
119
169
  private readonly blobClient: BlobClientInterface,
120
170
  instrumentation: ArchiverInstrumentation,
@@ -124,20 +174,40 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
124
174
  },
125
175
  synchronizer: ArchiverL1Synchronizer,
126
176
  events: ArchiverEmitter,
127
- l2TipsCache?: L2TipsCache,
177
+ initialHeader: BlockHeader,
178
+ initialBlockHash: BlockHash,
179
+ l2TipsCache: L2TipsCache,
180
+ private readonly dateProvider: DateProvider,
181
+ private checkpointProposalPresence: CheckpointProposalPresence = noCheckpointProposalPresence,
128
182
  private readonly log: Logger = createLogger('archiver'),
129
183
  ) {
130
- super(dataStore, l1Constants);
184
+ super(dataStores, l1Constants, initialHeader, initialBlockHash, l1Constants.genesisArchiveRoot);
131
185
 
132
186
  this.tracer = instrumentation.tracer;
187
+ this.instrumentation = instrumentation;
133
188
  this.initialSyncPromise = promiseWithResolvers();
134
189
  this.synchronizer = synchronizer;
135
190
  this.events = events;
136
- this.l2TipsCache = l2TipsCache ?? new L2TipsCache(this.dataStore.blockStore);
137
- this.updater = new ArchiverDataStoreUpdater(this.dataStore, this.l2TipsCache, {
191
+ this.l2TipsCache = l2TipsCache;
192
+ this.timetable = new ConsensusTimetable({
193
+ l1Constants,
194
+ blockDuration: this.config.blockDuration,
195
+ checkpointProposalSyncGrace: this.config.checkpointProposalSyncGrace,
196
+ });
197
+ this.updater = new ArchiverDataStoreUpdater(this.dataStores, this.l2TipsCache, {
138
198
  rollupManaLimit: l1Constants.rollupManaLimit,
139
199
  });
140
200
 
201
+ // The resolver reads its witness data from this archiver and pins its lazy Outbox-root fetches
202
+ // to the archiver's synced L1 block. No method on `this` is invoked during construction.
203
+ this.outboxTreesResolver = new OutboxTreesResolver(
204
+ this.outbox,
205
+ this,
206
+ this.dataStores.db,
207
+ () => Promise.resolve(this.getL1BlockNumber()),
208
+ l1Constants.epochDuration,
209
+ );
210
+
141
211
  // Running promise starts with a small interval inbetween runs, so all iterations needed for the initial sync
142
212
  // are done as fast as possible. This then gets updated once the initial sync completes.
143
213
  this.runningPromise = new RunningPromise(
@@ -148,6 +218,27 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
148
218
  );
149
219
  }
150
220
 
221
+ /**
222
+ * Returns the L2-to-L1 membership witness for `message` emitted by tx `txHash`. The node selects
223
+ * the smallest partial-proof root on the Outbox that covers the tx's checkpoint and builds the
224
+ * witness against it.
225
+ *
226
+ * The node reads the Outbox roots lazily, pinned to its synced L1 block, so the witness reflects
227
+ * the node's synced view. Returns `undefined` if the tx isn't yet in a block/epoch or no covering
228
+ * root has landed on L1 as of the synced block.
229
+ *
230
+ * Caveat: roots are cached only for the current synced L1 block and re-fetched once the node
231
+ * advances, so a reorg is picked up on the next synced-block advance rather than re-validated per
232
+ * request.
233
+ */
234
+ public getL2ToL1MembershipWitness(
235
+ txHash: TxHash,
236
+ message: Fr,
237
+ messageIndexInTx?: number,
238
+ ): Promise<L2ToL1MembershipWitness | undefined> {
239
+ return this.outboxTreesResolver.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
240
+ }
241
+
151
242
  /** Updates archiver config */
152
243
  public updateConfig(newConfig: Partial<ArchiverConfig>) {
153
244
  this.config = merge(this.config, mapArchiverConfig(newConfig));
@@ -170,11 +261,24 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
170
261
  this.config.ethereumAllowNoDebugHosts ?? false,
171
262
  this.log.getBindings(),
172
263
  );
264
+ await validateAndLogHistoricalLogsAvailability(
265
+ this.publicClient,
266
+ {
267
+ rollupAddress: this.l1Addresses.rollupAddress,
268
+ inboxAddress: this.l1Addresses.inboxAddress,
269
+ registryAddress: this.l1Addresses.registryAddress,
270
+ governanceProposerAddress: this.l1Addresses.governanceProposerAddress,
271
+ },
272
+ this.config.skipHistoricalLogsCheck ?? false,
273
+ this.log.getBindings(),
274
+ );
173
275
 
174
276
  // Log initial state for the archiver
175
277
  const { l1StartBlock } = this.l1Constants;
176
- const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = l1StartBlock } = await this.store.getSynchPoint();
177
- const currentL2Checkpoint = await this.getSynchedCheckpointNumber();
278
+ const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = l1StartBlock } = await getArchiverSynchPoint(
279
+ this.stores,
280
+ );
281
+ const currentL2Checkpoint = await this.getCheckpointNumber();
178
282
  this.log.info(
179
283
  `Starting archiver sync to rollup contract ${this.rollup.address} from L1 block ${blocksSynchedTo} and L2 checkpoint ${currentL2Checkpoint}`,
180
284
  { blocksSynchedTo, messagesSynchedTo, currentL2Checkpoint },
@@ -191,6 +295,19 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
191
295
  return this.runningPromise.trigger();
192
296
  }
193
297
 
298
+ /** Sets the proposal-presence provider used by orphan proposed-block pruning. */
299
+ public setCheckpointProposalPresence(checkpointProposalPresence: CheckpointProposalPresence): void {
300
+ this.checkpointProposalPresence = checkpointProposalPresence;
301
+ }
302
+
303
+ public trySyncImmediate() {
304
+ try {
305
+ return this.syncImmediate();
306
+ } catch (err) {
307
+ this.log.error(`Failed to trigger immediate archiver sync: ${err}`, err);
308
+ }
309
+ }
310
+
194
311
  /**
195
312
  * Queues a block to be added to the archiver store and triggers processing.
196
313
  * The block will be processed by the sync loop.
@@ -199,61 +316,92 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
199
316
  * @returns A promise that resolves when the block has been added to the store, or rejects on error.
200
317
  */
201
318
  public addBlock(block: L2Block): Promise<void> {
202
- return new Promise<void>((resolve, reject) => {
203
- this.blockQueue.push({ block, resolve, reject });
204
- this.log.debug(`Queued block ${block.number} for processing`);
205
- // Trigger an immediate sync, but don't wait for it - the promise resolves when the block is processed
206
- this.syncImmediate().catch(err => {
207
- this.log.error(`Sync immediate call failed: ${err}`);
208
- });
209
- });
319
+ const promise = promiseWithResolvers<void>();
320
+ this.inboundQueue.push({ block, ...promise, type: 'block' });
321
+ this.log.debug(`Queued block ${block.number} for processing`);
322
+ void this.trySyncImmediate();
323
+ return promise.promise;
324
+ }
325
+
326
+ /**
327
+ * Queues a new proposed checkpoint into the archiver store.
328
+ * Checks that the checkpoint is not for an L2 slot already synced from L1.
329
+ * Resolves once the checkpoint has been processed.
330
+ */
331
+ public addProposedCheckpoint(pending: ProposedCheckpointInput): Promise<void> {
332
+ const promise = promiseWithResolvers<void>();
333
+ this.inboundQueue.push({ checkpoint: pending, ...promise, type: 'checkpoint' });
334
+ this.log.debug(`Queued checkpoint ${pending.checkpointNumber} for processing`);
335
+ void this.trySyncImmediate();
336
+ return promise.promise;
210
337
  }
211
338
 
212
339
  /**
213
- * Processes all queued blocks, adding them to the store.
340
+ * Processes all queued blocks and checkpoints, adding them to the store.
214
341
  * Called at the beginning of each sync iteration.
215
- * Blocks are processed in the order they were queued.
342
+ * Items are processed in the order they were queued.
216
343
  */
217
- private async processQueuedBlocks(): Promise<void> {
218
- if (this.blockQueue.length === 0) {
219
- return;
344
+ private async processInboundQueue(): Promise<L2Block[]> {
345
+ const blocksAdded: L2Block[] = [];
346
+ if (this.inboundQueue.length === 0) {
347
+ return blocksAdded;
220
348
  }
221
349
 
222
- // Take all blocks from the queue
223
- const queuedItems = this.blockQueue.splice(0, this.blockQueue.length);
224
- this.log.debug(`Processing ${queuedItems.length} queued block(s)`);
350
+ // Take all items from the queue
351
+ const queuedItems = this.inboundQueue.splice(0, this.inboundQueue.length);
352
+ this.log.debug(`Processing ${queuedItems.length} queued inbound items`);
225
353
 
226
354
  // Calculate slot threshold for validation
227
355
  const l1Timestamp = this.synchronizer.getL1Timestamp();
228
356
  const slotAtNextL1Block =
229
357
  l1Timestamp === undefined ? undefined : getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
230
358
 
231
- // Process each block individually to properly resolve/reject each promise
232
- for (const { block, resolve, reject } of queuedItems) {
233
- const blockSlot = block.header.globalVariables.slotNumber;
234
- if (slotAtNextL1Block !== undefined && blockSlot < slotAtNextL1Block) {
359
+ // Helpers for manipulating blocks and checkpoints in the queue
360
+ const getSlot: (item: AddBlockRequest | AddProposedCheckpointRequest) => SlotNumber = item =>
361
+ item.type === 'block' ? item.block.header.globalVariables.slotNumber : item.checkpoint.header.slotNumber;
362
+ const getNumber: (item: AddBlockRequest | AddProposedCheckpointRequest) => number = item =>
363
+ item.type === 'block' ? item.block.number : item.checkpoint.checkpointNumber;
364
+
365
+ // Process each item individually to properly resolve/reject each promise
366
+ for (const item of queuedItems) {
367
+ const { resolve, reject, type } = item;
368
+ const itemSlot = getSlot(item);
369
+ const itemNumber = getNumber(item);
370
+ if (slotAtNextL1Block !== undefined && itemSlot < slotAtNextL1Block) {
371
+ const nextSlotTimestamp = getTimestampForSlot(slotAtNextL1Block, this.l1Constants);
235
372
  this.log.warn(
236
- `Rejecting proposed block ${block.number} for past slot ${blockSlot} (current is ${slotAtNextL1Block})`,
237
- { block: block.toBlockInfo(), l1Timestamp, slotAtNextL1Block },
373
+ `Rejecting proposed ${type} ${itemNumber} for past slot ${itemSlot} (current ${slotAtNextL1Block})`,
374
+ { number: itemNumber, type, l1Timestamp, slotAtNextL1Block, nextSlotTimestamp },
238
375
  );
239
- reject(new Error(`Block ${block.number} is for past slot ${blockSlot} (current is ${slotAtNextL1Block})`));
376
+ reject(new BlockOrCheckpointSlotExpiredError(itemSlot, nextSlotTimestamp, l1Timestamp));
240
377
  continue;
241
378
  }
242
379
 
243
380
  try {
244
- await this.updater.addProposedBlock(block);
245
- this.log.debug(`Added block ${block.number} to store`);
381
+ if (type === 'block') {
382
+ const [durationMs] = await elapsed(() => this.updater.addProposedBlock(item.block));
383
+ this.instrumentation.processNewProposedBlock(durationMs, item.block);
384
+ blocksAdded.push(item.block);
385
+ } else {
386
+ await this.updater.addProposedCheckpoint(item.checkpoint);
387
+ }
388
+ this.log.debug(`Added ${type} ${itemNumber} to store`);
246
389
  resolve();
247
390
  } catch (err: any) {
248
391
  if (err instanceof BlockAlreadyCheckpointedError) {
249
- this.log.debug(`Proposed block ${block.number} matches already checkpointed block, ignoring late proposal`);
392
+ this.log.debug(`Proposed block ${itemNumber} matches already checkpointed block, ignoring late proposal`);
393
+ // A late proposal that matches an already-checkpointed block adds nothing new, so it is not appended.
250
394
  resolve();
251
395
  continue;
252
396
  }
253
- this.log.error(`Failed to add block ${block.number} to store: ${err.message}`);
397
+ this.log.error(`Failed to add ${type} ${itemNumber} to store: ${err.message}`, err, {
398
+ number: itemNumber,
399
+ type,
400
+ });
254
401
  reject(err);
255
402
  }
256
403
  }
404
+ return blocksAdded;
257
405
  }
258
406
 
259
407
  public waitForInitialSync() {
@@ -265,15 +413,136 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
265
413
  */
266
414
  @trackSpan('Archiver.sync')
267
415
  private async sync() {
416
+ // Capture the tips before any mutation so the aggregate event can report what moved this pass.
417
+ const fromTips = await this.getL2Tips();
418
+
419
+ // Accumulate the blocks added across the pass's sub-steps (queued proposals + L1 checkpoint payloads).
420
+ const blocksAdded: L2Block[] = [];
268
421
  // Process any queued blocks first, before doing L1 sync
269
- await this.processQueuedBlocks();
422
+ blocksAdded.push(...(await this.processInboundQueue()));
270
423
  // Now perform L1 sync
271
- await this.syncFromL1();
424
+ blocksAdded.push(...(await this.syncFromL1()));
425
+ // Prune proposed blocks with no corresponding proposed checkpoint after the appropriate materialization deadline.
426
+ await this.pruneOrphanProposedBlocks();
427
+
428
+ // Emit a single aggregate update event after all pass work has committed and the tips cache has refreshed,
429
+ // so `toTips` and the source state observed by listeners are consistent with the event payload. The pass
430
+ // mutated state if the tips moved (added blocks, a prune, or a thin tier movement) or blocks were added; a
431
+ // fully-synced no-op pass emits nothing.
432
+ const toTips = await this.getL2Tips();
433
+ if (!l2TipsEqual(fromTips, toTips) || blocksAdded.length > 0) {
434
+ this.events.emit(L2BlockSourceEvents.L2BlockSourceUpdated, {
435
+ type: L2BlockSourceEvents.L2BlockSourceUpdated,
436
+ fromTips,
437
+ toTips,
438
+ blocksAdded,
439
+ });
440
+ }
272
441
  }
273
442
 
274
- private async syncFromL1() {
443
+ /**
444
+ * Prunes a block-only local tip that was built atop a checkpoint that was never itself proposed.
445
+ *
446
+ * Under pipelining, a proposer publishes the blocks for a checkpoint (block-only proposals) before
447
+ * assembling and publishing the enclosing proposed checkpoint at the end of the build slot. A node
448
+ * that received those blocks but never the proposed checkpoint is left with an orphan tip it must not build on.
449
+ * If no checkpoint proposal was received for the orphan slot, we prune after the receive deadline plus local
450
+ * tolerance. If a checkpoint proposal was received but has not materialized into proposed archiver state,
451
+ * we prune after the consensus materialization deadline.
452
+ *
453
+ * The uncheckpointed suffix is scanned in order. Blocks covered by proposed checkpoints are left in
454
+ * place; the first block not covered by a proposed checkpoint starts the orphan suffix to prune.
455
+ */
456
+ private async pruneOrphanProposedBlocks(): Promise<void> {
457
+ if (this.config.skipOrphanProposedBlockPruning) {
458
+ return;
459
+ }
460
+ const tips = await this.getL2Tips();
461
+ const now = BigInt(this.dateProvider.nowInSeconds());
462
+
463
+ // Frontier block covered by a proposed (or, falling back, confirmed) checkpoint. Blocks beyond it
464
+ // have no enclosing checkpoint proposal and are the orphan-pruning candidates.
465
+ const proposedCheckpointBlockNumber = await this.stores.blocks.getProposedCheckpointL2BlockNumber();
466
+
467
+ // The proposed tip is a proposed-checkpointed block, so there are no orphan proposed blocks to prune
468
+ if (proposedCheckpointBlockNumber === tips.proposed.number) {
469
+ this.log.trace(`No orphan proposed blocks to prune: proposed tip ${tips.proposed.number} is checkpointed`, {
470
+ proposed: tips.proposed,
471
+ proposedCheckpointBlockNumber,
472
+ });
473
+ return;
474
+ }
475
+
476
+ // Load the blocks that are candidates for pruning (ie blocks without a proposed checkpoint covering them)
477
+ const blocksWithoutProposedCheckpoint = await this.stores.blocks.getBlocksData({
478
+ from: BlockNumber(proposedCheckpointBlockNumber + 1),
479
+ limit: tips.proposed.number - proposedCheckpointBlockNumber,
480
+ });
481
+
482
+ // Iterate through them in order, the first one with a slot that should have received a proposed checkpoint
483
+ // is the first orphan block, and all blocks after it are also orphaned and should be pruned.
484
+ let lastSlotChecked = undefined;
485
+ for (const blockData of blocksWithoutProposedCheckpoint) {
486
+ // No need to recheck if this block had the same slot as the previous one.
487
+ const blockSlot = blockData.header.getSlot();
488
+ const blockNumber = blockData.header.getBlockNumber();
489
+ if (lastSlotChecked !== undefined && blockSlot === lastSlotChecked) {
490
+ continue;
491
+ }
492
+ lastSlotChecked = blockSlot;
493
+
494
+ const hasCheckpointProposal = await this.checkpointProposalPresence.hasCheckpointProposalForSlot(blockSlot);
495
+ const deadlineType = hasCheckpointProposal ? 'checkpoint-proposal-synced' : 'checkpoint-proposal-received';
496
+ const selectedDeadline = BigInt(
497
+ hasCheckpointProposal
498
+ ? this.timetable.getCheckpointProposalSyncedDeadline(blockSlot)
499
+ : Math.ceil(
500
+ this.timetable.getCheckpointProposalReceiveDeadline(blockSlot) +
501
+ this.config.orphanPruneNoProposalTolerance,
502
+ ),
503
+ );
504
+
505
+ // If it's still not checkpointed once strictly past the selected deadline, prune it along with all blocks after
506
+ // it. A proposal may still legitimately arrive or materialize at exactly its deadline, so the tip is only
507
+ // orphaned once that instant has fully elapsed.
508
+ if (now > selectedDeadline) {
509
+ const pruneAfterBlockNumber = BlockNumber(blockNumber - 1);
510
+ this.log.warn(
511
+ `Pruning orphan blocks after block ${pruneAfterBlockNumber}: block at slot ${blockSlot} belongs to ` +
512
+ `checkpoint ${blockData.checkpointNumber} which has no matching proposed checkpoint`,
513
+ {
514
+ firstUncheckpointedBlockHeader: blockData.header.toInspect(),
515
+ blockCheckpointNumber: blockData.checkpointNumber,
516
+ blockNumber,
517
+ blockSlot,
518
+ hasCheckpointProposal,
519
+ deadlineType,
520
+ selectedDeadline,
521
+ now,
522
+ },
523
+ );
524
+
525
+ const prunedBlocks = await this.updater.removeBlocksWithoutProposedCheckpointAfter(pruneAfterBlockNumber);
526
+ if (prunedBlocks.length > 0) {
527
+ this.instrumentation.recordPrune('orphan');
528
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
529
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
530
+ slotNumber: blockSlot,
531
+ blocks: prunedBlocks,
532
+ });
533
+ }
534
+ return;
535
+ }
536
+ }
537
+
538
+ this.log.trace('No orphan proposed blocks to prune: all uncheckpointed blocks are still within deadline', {
539
+ blocksWithoutProposedCheckpoint: blocksWithoutProposedCheckpoint.map(b => b.header.toInspect()),
540
+ });
541
+ }
542
+
543
+ private async syncFromL1(): Promise<L2Block[]> {
275
544
  // Delegate to the L1 synchronizer
276
- await this.synchronizer.syncFromL1(this.initialSyncComplete);
545
+ const blocksAdded = await this.synchronizer.syncFromL1(this.initialSyncComplete);
277
546
 
278
547
  // Check if we've completed initial sync
279
548
  const currentL1BlockNumber = this.synchronizer.getL1BlockNumber();
@@ -282,7 +551,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
282
551
  if (currentL1BlockNumber + 1n >= l1BlockNumberAtEnd) {
283
552
  this.log.info(`Initial archiver sync to L1 block ${currentL1BlockNumber} complete`, {
284
553
  l1BlockNumber: currentL1BlockNumber,
285
- syncPoint: await this.store.getSynchPoint(),
554
+ syncPoint: await getArchiverSynchPoint(this.stores),
286
555
  ...(await this.getL2Tips()),
287
556
  });
288
557
  this.runningPromise.setPollingIntervalMS(this.config.pollingIntervalMs);
@@ -290,6 +559,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
290
559
  this.initialSyncPromise.resolve();
291
560
  }
292
561
  }
562
+ return blocksAdded;
293
563
  }
294
564
 
295
565
  /** Resumes the archiver after a stop. */
@@ -314,7 +584,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
314
584
  }
315
585
 
316
586
  public backupTo(destPath: string): Promise<string> {
317
- return this.dataStore.backupTo(destPath);
587
+ return backupArchiverDataStores(this.dataStores, destPath);
318
588
  }
319
589
 
320
590
  public getL1Constants(): Promise<L1RollupConstants> {
@@ -356,9 +626,9 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
356
626
  }
357
627
 
358
628
  let slotFromCheckpoint: SlotNumber | undefined;
359
- const latestCheckpointNumber = await this.store.getSynchedCheckpointNumber();
629
+ const latestCheckpointNumber = await this.stores.blocks.getLatestCheckpointNumber();
360
630
  if (latestCheckpointNumber > 0) {
361
- const checkpointData = await this.store.getCheckpointData(latestCheckpointNumber);
631
+ const checkpointData = await this.stores.blocks.getCheckpointData(latestCheckpointNumber);
362
632
  if (checkpointData) {
363
633
  slotFromCheckpoint = checkpointData.header.slotNumber;
364
634
  }
@@ -390,8 +660,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
390
660
  // The epoch is complete if the current checkpointed L2 block is the last one in the epoch (or later).
391
661
  // We use the checkpointed block number (synced from L1) instead of 'latest' to avoid returning true
392
662
  // 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;
663
+ const header = (await this.getBlockData({ tag: 'checkpointed' }))?.header;
395
664
  const slot = header ? header.globalVariables.slotNumber : undefined;
396
665
  const [_startSlot, endSlot] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
397
666
  if (slot && slot >= endSlot) {
@@ -426,6 +695,15 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
426
695
  return this.updater.removeCheckpointsAfter(checkpointNumber);
427
696
  }
428
697
 
698
+ /**
699
+ * Removes all uncheckpointed blocks strictly after `blockNumber`, along with the proposed checkpoints
700
+ * that referenced them. Used by the AutomineSequencer to undo a local insert whose propose tx failed
701
+ * to land on L1 (no reorg needed — nothing reached L1). Refuses to touch checkpointed blocks.
702
+ */
703
+ public removeUncheckpointedBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
704
+ return this.updater.removeUncheckpointedBlocksAfter(blockNumber);
705
+ }
706
+
429
707
  /** Used by TXE to add checkpoints directly without syncing from L1. */
430
708
  public async addCheckpoints(
431
709
  checkpoints: PublishedCheckpoint[],
@@ -447,29 +725,34 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
447
725
  if (targetL2BlockNumber >= currentL2Block) {
448
726
  throw new Error(`Target L2 block ${targetL2BlockNumber} must be less than current L2 block ${currentL2Block}`);
449
727
  }
450
- const targetL2Block = await this.store.getCheckpointedBlock(targetL2BlockNumber);
451
- if (!targetL2Block) {
728
+ const checkpointedTip = await this.stores.blocks.getCheckpointedL2BlockNumber();
729
+ if (targetL2BlockNumber > checkpointedTip) {
730
+ throw new Error(`Target L2 block ${targetL2BlockNumber} is not checkpointed yet`);
731
+ }
732
+ const targetBlockData = await this.stores.blocks.getBlockData({ number: targetL2BlockNumber });
733
+ if (!targetBlockData) {
452
734
  throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
453
735
  }
454
- const targetCheckpointNumber = targetL2Block.checkpointNumber;
736
+ const targetCheckpointNumber = targetBlockData.checkpointNumber;
455
737
 
456
738
  // 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
- }
739
+ const checkpointData = await this.stores.blocks.getCheckpointData(targetCheckpointNumber);
740
+ if (!checkpointData) {
741
+ throw new Error(`Checkpoint ${targetCheckpointNumber} not found for block ${targetL2BlockNumber}`);
742
+ }
743
+ const lastBlockInCheckpoint = BlockNumber(checkpointData.startBlock + checkpointData.blockCount - 1);
744
+ if (targetL2BlockNumber !== lastBlockInCheckpoint) {
745
+ const previousCheckpointBoundary =
746
+ checkpointData.startBlock > 1 ? BlockNumber(checkpointData.startBlock - 1) : BlockNumber(0);
747
+ throw new Error(
748
+ `Target L2 block ${targetL2BlockNumber} is not at a checkpoint boundary. ` +
749
+ `Checkpoint ${targetCheckpointNumber} spans blocks ${checkpointData.startBlock} to ${lastBlockInCheckpoint}. ` +
750
+ `Use block ${lastBlockInCheckpoint} to roll back to this checkpoint, ` +
751
+ `or block ${previousCheckpointBoundary} to roll back to the previous one.`,
752
+ );
470
753
  }
471
754
 
472
- const targetL1BlockNumber = targetL2Block.l1.blockNumber;
755
+ const targetL1BlockNumber = checkpointData.l1.blockNumber;
473
756
  const targetL1Block = await this.publicClient.getBlock({
474
757
  blockNumber: targetL1BlockNumber,
475
758
  includeTransactions: false,
@@ -483,10 +766,13 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
483
766
  );
484
767
  await this.updater.removeCheckpointsAfter(targetCheckpointNumber);
485
768
  this.log.info(`Rolling back L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
486
- await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
769
+ await this.stores.messages.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
487
770
  this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
488
- await this.store.setCheckpointSynchedL1BlockNumber(targetL1BlockNumber);
489
- await this.store.setMessageSynchedL1Block({ l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash });
771
+ await this.stores.blocks.setSynchedL1BlockNumber(targetL1BlockNumber);
772
+ await this.stores.messages.setMessageSyncState(
773
+ { l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash },
774
+ undefined,
775
+ );
490
776
  if (targetL2BlockNumber < currentProvenBlock) {
491
777
  this.log.info(`Rolling back proven L2 checkpoint to ${targetCheckpointNumber}`);
492
778
  await this.updater.setProvenCheckpointNumber(targetCheckpointNumber);