@aztec/archiver 0.0.1-commit.e0f15ab9b → 0.0.1-commit.e304674f1

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 (67) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +5 -4
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +6 -3
  5. package/dest/errors.d.ts +14 -2
  6. package/dest/errors.d.ts.map +1 -1
  7. package/dest/errors.js +18 -2
  8. package/dest/l1/calldata_retriever.d.ts +1 -1
  9. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  10. package/dest/l1/calldata_retriever.js +2 -1
  11. package/dest/l1/data_retrieval.d.ts +3 -3
  12. package/dest/l1/data_retrieval.d.ts.map +1 -1
  13. package/dest/l1/data_retrieval.js +14 -15
  14. package/dest/modules/data_source_base.d.ts +4 -2
  15. package/dest/modules/data_source_base.d.ts.map +1 -1
  16. package/dest/modules/data_source_base.js +6 -0
  17. package/dest/modules/data_store_updater.d.ts +3 -2
  18. package/dest/modules/data_store_updater.d.ts.map +1 -1
  19. package/dest/modules/data_store_updater.js +9 -0
  20. package/dest/modules/l1_synchronizer.d.ts +3 -2
  21. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  22. package/dest/modules/l1_synchronizer.js +128 -123
  23. package/dest/modules/validation.d.ts +1 -1
  24. package/dest/modules/validation.d.ts.map +1 -1
  25. package/dest/modules/validation.js +2 -2
  26. package/dest/store/block_store.d.ts +39 -4
  27. package/dest/store/block_store.d.ts.map +1 -1
  28. package/dest/store/block_store.js +230 -61
  29. package/dest/store/kv_archiver_store.d.ts +21 -8
  30. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  31. package/dest/store/kv_archiver_store.js +25 -8
  32. package/dest/store/l2_tips_cache.d.ts +2 -1
  33. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  34. package/dest/store/l2_tips_cache.js +25 -5
  35. package/dest/store/message_store.d.ts +3 -3
  36. package/dest/store/message_store.d.ts.map +1 -1
  37. package/dest/store/message_store.js +9 -10
  38. package/dest/test/fake_l1_state.d.ts +9 -1
  39. package/dest/test/fake_l1_state.d.ts.map +1 -1
  40. package/dest/test/fake_l1_state.js +41 -6
  41. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  42. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  43. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  44. package/dest/test/mock_l2_block_source.d.ts +7 -2
  45. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  46. package/dest/test/mock_l2_block_source.js +28 -3
  47. package/dest/test/noop_l1_archiver.d.ts +1 -1
  48. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  49. package/dest/test/noop_l1_archiver.js +0 -1
  50. package/package.json +13 -13
  51. package/src/archiver.ts +13 -7
  52. package/src/errors.ts +30 -2
  53. package/src/l1/calldata_retriever.ts +2 -1
  54. package/src/l1/data_retrieval.ts +8 -12
  55. package/src/modules/data_source_base.ts +15 -1
  56. package/src/modules/data_store_updater.ts +14 -1
  57. package/src/modules/l1_synchronizer.ts +138 -147
  58. package/src/modules/validation.ts +2 -2
  59. package/src/store/block_store.ts +300 -73
  60. package/src/store/kv_archiver_store.ts +43 -12
  61. package/src/store/l2_tips_cache.ts +50 -11
  62. package/src/store/message_store.ts +10 -12
  63. package/src/structs/inbox_message.ts +1 -1
  64. package/src/test/fake_l1_state.ts +56 -7
  65. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  66. package/src/test/mock_l2_block_source.ts +37 -2
  67. package/src/test/noop_l1_archiver.ts +0 -1
package/src/archiver.ts CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  type L2Tips,
20
20
  type ValidateCheckpointResult,
21
21
  } from '@aztec/stdlib/block';
22
- import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
22
+ import { type ProposedCheckpointInput, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
23
23
  import {
24
24
  type L1RollupConstants,
25
25
  getEpochAtSlot,
@@ -91,7 +91,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
91
91
  * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
92
92
  * @param rollup - Rollup contract instance.
93
93
  * @param inbox - Inbox contract instance.
94
- * @param l1Addresses - L1 contract addresses (registry, governance proposer, slash factory, slashing proposer).
94
+ * @param l1Addresses - L1 contract addresses (registry, governance proposer, slashing proposer).
95
95
  * @param dataStore - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
96
96
  * @param config - Archiver configuration options.
97
97
  * @param blobClient - Client for retrieving blob data.
@@ -104,10 +104,9 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
104
104
  private readonly publicClient: ViemPublicClient,
105
105
  private readonly debugClient: ViemPublicDebugClient,
106
106
  private readonly rollup: RollupContract,
107
- private readonly l1Addresses: Pick<
108
- L1ContractAddresses,
109
- 'registryAddress' | 'governanceProposerAddress' | 'slashFactoryAddress'
110
- > & { slashingProposerAddress: EthAddress },
107
+ private readonly l1Addresses: Pick<L1ContractAddresses, 'registryAddress' | 'governanceProposerAddress'> & {
108
+ slashingProposerAddress: EthAddress;
109
+ },
111
110
  readonly dataStore: KVArchiverDataStore,
112
111
  private config: {
113
112
  pollingIntervalMs: number;
@@ -209,6 +208,10 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
209
208
  });
210
209
  }
211
210
 
211
+ public async setProposedCheckpoint(pending: ProposedCheckpointInput): Promise<void> {
212
+ await this.updater.setProposedCheckpoint(pending);
213
+ }
214
+
212
215
  /**
213
216
  * Processes all queued blocks, adding them to the store.
214
217
  * Called at the beginning of each sync iteration.
@@ -486,7 +489,10 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
486
489
  await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
487
490
  this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
488
491
  await this.store.setCheckpointSynchedL1BlockNumber(targetL1BlockNumber);
489
- await this.store.setMessageSynchedL1Block({ l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash });
492
+ await this.store.setMessageSyncState(
493
+ { l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash },
494
+ undefined,
495
+ );
490
496
  if (targetL2BlockNumber < currentProvenBlock) {
491
497
  this.log.info(`Rolling back proven L2 checkpoint to ${targetCheckpointNumber}`);
492
498
  await this.updater.setProvenCheckpointNumber(targetCheckpointNumber);
package/src/errors.ts CHANGED
@@ -26,9 +26,13 @@ export class InitialCheckpointNumberNotSequentialError extends Error {
26
26
  }
27
27
 
28
28
  export class CheckpointNumberNotSequentialError extends Error {
29
- constructor(newCheckpointNumber: number, previous: number | undefined) {
29
+ constructor(
30
+ newCheckpointNumber: number,
31
+ previous: number | undefined,
32
+ source: 'confirmed' | 'proposed' = 'confirmed',
33
+ ) {
30
34
  super(
31
- `Cannot insert new checkpoint ${newCheckpointNumber} given previous checkpoint number in batch is ${previous ?? 'undefined'}`,
35
+ `Cannot insert new checkpoint ${newCheckpointNumber} given previous ${source} checkpoint number is ${previous ?? 'undefined'}`,
32
36
  );
33
37
  }
34
38
  }
@@ -104,6 +108,30 @@ export class L1ToL2MessagesNotReadyError extends Error {
104
108
  }
105
109
  }
106
110
 
111
+ /** Thrown when a proposed checkpoint number is stale (already processed). */
112
+ export class ProposedCheckpointStaleError extends Error {
113
+ constructor(
114
+ public readonly proposedCheckpointNumber: number,
115
+ public readonly currentProposedNumber: number,
116
+ ) {
117
+ super(`Stale proposed checkpoint ${proposedCheckpointNumber}: current proposed is ${currentProposedNumber}`);
118
+ this.name = 'ProposedCheckpointStaleError';
119
+ }
120
+ }
121
+
122
+ /** Thrown when a proposed checkpoint number is not the expected confirmed + 1. */
123
+ export class ProposedCheckpointNotSequentialError extends Error {
124
+ constructor(
125
+ public readonly proposedCheckpointNumber: number,
126
+ public readonly confirmedCheckpointNumber: number,
127
+ ) {
128
+ super(
129
+ `Proposed checkpoint ${proposedCheckpointNumber} is not sequential: expected ${confirmedCheckpointNumber + 1} (confirmed + 1)`,
130
+ );
131
+ this.name = 'ProposedCheckpointNotSequentialError';
132
+ }
133
+ }
134
+
107
135
  /** Thrown when a proposed block conflicts with an already checkpointed block (different content). */
108
136
  export class CannotOverwriteCheckpointedBlockError extends Error {
109
137
  constructor(
@@ -1,6 +1,7 @@
1
1
  import { MULTI_CALL_3_ADDRESS, type ViemCommitteeAttestations, type ViemHeader } from '@aztec/ethereum/contracts';
2
2
  import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
3
3
  import { CheckpointNumber } from '@aztec/foundation/branded-types';
4
+ import { LruSet } from '@aztec/foundation/collection';
4
5
  import { Fr } from '@aztec/foundation/curves/bn254';
5
6
  import { EthAddress } from '@aztec/foundation/eth-address';
6
7
  import type { Logger } from '@aztec/foundation/log';
@@ -44,7 +45,7 @@ type CheckpointData = {
44
45
  */
45
46
  export class CalldataRetriever {
46
47
  /** Tx hashes we've already logged for trace+debug failure (log once per tx per process). */
47
- private static readonly traceFailureWarnedTxHashes = new Set<string>();
48
+ private static readonly traceFailureWarnedTxHashes = new LruSet<string>(1000);
48
49
 
49
50
  /** Clears the trace-failure warned set. For testing only. */
50
51
  static resetTraceFailureWarnedForTesting(): void {
@@ -144,7 +144,7 @@ export async function retrievedToPublishedCheckpoint({
144
144
  * @param blobClient - The blob client client for fetching blob data.
145
145
  * @param searchStartBlock - The block number to use for starting the search.
146
146
  * @param searchEndBlock - The highest block number that we should search up to.
147
- * @param contractAddresses - The contract addresses (governanceProposerAddress, slashFactoryAddress, slashingProposerAddress).
147
+ * @param contractAddresses - The contract addresses (governanceProposerAddress, slashingProposerAddress).
148
148
  * @param instrumentation - The archiver instrumentation instance.
149
149
  * @param logger - The logger instance.
150
150
  * @param isHistoricalSync - Whether this is a historical sync.
@@ -344,14 +344,10 @@ export async function getCheckpointBlobDataFromBlobs(
344
344
  /** Given an L1 to L2 message, retrieves its corresponding event from the Inbox within a specific block range. */
345
345
  export async function retrieveL1ToL2Message(
346
346
  inbox: InboxContract,
347
- leaf: Fr,
348
- fromBlock: bigint,
349
- toBlock: bigint,
347
+ message: InboxMessage,
350
348
  ): Promise<InboxMessage | undefined> {
351
- const logs = await inbox.getMessageSentEventByHash(leaf.toString(), fromBlock, toBlock);
352
-
353
- const messages = mapLogsInboxMessage(logs);
354
- return messages.length > 0 ? messages[0] : undefined;
349
+ const log = await inbox.getMessageSentEventByHash(message.leaf.toString(), message.l1BlockHash.toString());
350
+ return log && mapLogInboxMessage(log);
355
351
  }
356
352
 
357
353
  /**
@@ -374,22 +370,22 @@ export async function retrieveL1ToL2Messages(
374
370
  break;
375
371
  }
376
372
 
377
- retrievedL1ToL2Messages.push(...mapLogsInboxMessage(messageSentLogs));
373
+ retrievedL1ToL2Messages.push(...messageSentLogs.map(mapLogInboxMessage));
378
374
  searchStartBlock = messageSentLogs.at(-1)!.l1BlockNumber + 1n;
379
375
  }
380
376
 
381
377
  return retrievedL1ToL2Messages;
382
378
  }
383
379
 
384
- function mapLogsInboxMessage(logs: MessageSentLog[]): InboxMessage[] {
385
- return logs.map(log => ({
380
+ function mapLogInboxMessage(log: MessageSentLog): InboxMessage {
381
+ return {
386
382
  index: log.args.index,
387
383
  leaf: log.args.leaf,
388
384
  l1BlockNumber: log.l1BlockNumber,
389
385
  l1BlockHash: log.l1BlockHash,
390
386
  checkpointNumber: log.args.checkpointNumber,
391
387
  rollingHash: log.args.rollingHash,
392
- }));
388
+ };
393
389
  }
394
390
 
395
391
  /** Retrieves L2ProofVerified events from the rollup contract. */
@@ -6,7 +6,13 @@ import { isDefined } from '@aztec/foundation/types';
6
6
  import type { FunctionSelector } from '@aztec/stdlib/abi';
7
7
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
8
8
  import { type BlockData, type BlockHash, CheckpointedL2Block, L2Block, type L2Tips } from '@aztec/stdlib/block';
9
- import { Checkpoint, type CheckpointData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
9
+ import {
10
+ Checkpoint,
11
+ type CheckpointData,
12
+ type CommonCheckpointData,
13
+ type ProposedCheckpointData,
14
+ PublishedCheckpoint,
15
+ } from '@aztec/stdlib/checkpoint';
10
16
  import type { ContractClassPublic, ContractDataSource, ContractInstanceWithAddress } from '@aztec/stdlib/contract';
11
17
  import { type L1RollupConstants, getSlotRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
12
18
  import type { GetContractClassLogsResponse, GetPublicLogsResponse } from '@aztec/stdlib/interfaces/client';
@@ -157,6 +163,14 @@ export abstract class ArchiverDataSourceBase
157
163
  return this.store.getSettledTxReceipt(txHash, this.l1Constants);
158
164
  }
159
165
 
166
+ public getProposedCheckpoint(): Promise<CommonCheckpointData | undefined> {
167
+ return this.store.getProposedCheckpoint();
168
+ }
169
+
170
+ public getProposedCheckpointOnly(): Promise<ProposedCheckpointData | undefined> {
171
+ return this.store.getProposedCheckpointOnly();
172
+ }
173
+
160
174
  public isPendingChainInvalid(): Promise<boolean> {
161
175
  return this.getPendingChainValidationStatus().then(status => !status.valid);
162
176
  }
@@ -7,7 +7,7 @@ import {
7
7
  ContractInstanceUpdatedEvent,
8
8
  } from '@aztec/protocol-contracts/instance-registry';
9
9
  import type { L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
10
- import { type PublishedCheckpoint, validateCheckpoint } from '@aztec/stdlib/checkpoint';
10
+ import { type ProposedCheckpointInput, type PublishedCheckpoint, validateCheckpoint } from '@aztec/stdlib/checkpoint';
11
11
  import {
12
12
  type ContractClassPublicWithCommitment,
13
13
  computeContractAddressFromInstance,
@@ -118,6 +118,15 @@ export class ArchiverDataStoreUpdater {
118
118
  return result;
119
119
  }
120
120
 
121
+ public async setProposedCheckpoint(proposedCheckpoint: ProposedCheckpointInput) {
122
+ const result = await this.store.transactionAsync(async () => {
123
+ await this.store.setProposedCheckpoint(proposedCheckpoint);
124
+ await this.l2TipsCache?.refresh();
125
+ });
126
+
127
+ return result;
128
+ }
129
+
121
130
  /**
122
131
  * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
123
132
  * This method handles multiple checkpoints but returns after pruning the first conflict found.
@@ -211,6 +220,10 @@ export class ArchiverDataStoreUpdater {
211
220
  }
212
221
 
213
222
  const result = await this.removeBlocksAfter(blockNumber);
223
+
224
+ // Clear the proposed checkpoint if it exists, since its blocks have been pruned
225
+ await this.store.deleteProposedCheckpoint();
226
+
214
227
  await this.l2TipsCache?.refresh();
215
228
  return result;
216
229
  });
@@ -1,18 +1,19 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
2
  import { EpochCache } from '@aztec/epoch-cache';
3
- import { InboxContract, RollupContract } from '@aztec/ethereum/contracts';
3
+ import { InboxContract, type InboxContractState, RollupContract } from '@aztec/ethereum/contracts';
4
4
  import type { L1BlockId } from '@aztec/ethereum/l1-types';
5
5
  import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
6
6
  import { asyncPool } from '@aztec/foundation/async-pool';
7
7
  import { maxBigint } from '@aztec/foundation/bigint';
8
8
  import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
9
- import { Buffer32 } from '@aztec/foundation/buffer';
9
+ import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
10
10
  import { pick } from '@aztec/foundation/collection';
11
11
  import { Fr } from '@aztec/foundation/curves/bn254';
12
12
  import { type Logger, createLogger } from '@aztec/foundation/log';
13
+ import { retryTimes } from '@aztec/foundation/retry';
13
14
  import { count } from '@aztec/foundation/string';
14
15
  import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
15
- import { isDefined } from '@aztec/foundation/types';
16
+ import { isDefined, isErrorClass } from '@aztec/foundation/types';
16
17
  import { type ArchiverEmitter, L2BlockSourceEvents, type ValidateCheckpointResult } from '@aztec/stdlib/block';
17
18
  import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
18
19
  import { type L1RollupConstants, getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
@@ -28,6 +29,7 @@ import {
28
29
  } from '../l1/data_retrieval.js';
29
30
  import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
30
31
  import type { L2TipsCache } from '../store/l2_tips_cache.js';
32
+ import { MessageStoreError } from '../store/message_store.js';
31
33
  import type { InboxMessage } from '../structs/inbox_message.js';
32
34
  import { ArchiverDataStoreUpdater } from './data_store_updater.js';
33
35
  import type { ArchiverInstrumentation } from './instrumentation.js';
@@ -121,10 +123,15 @@ export class ArchiverL1Synchronizer implements Traceable {
121
123
 
122
124
  @trackSpan('Archiver.syncFromL1')
123
125
  public async syncFromL1(initialSyncComplete: boolean): Promise<void> {
126
+ // In between the various calls to L1, the block number can move meaning some of the following
127
+ // calls will return data for blocks that were not present during earlier calls. To combat this
128
+ // we ensure that all data retrieval methods only retrieve data up to the currentBlockNumber
129
+ // captured at the top of this function.
124
130
  const currentL1Block = await this.publicClient.getBlock({ includeTransactions: false });
125
131
  const currentL1BlockNumber = currentL1Block.number;
126
132
  const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
127
133
  const currentL1Timestamp = currentL1Block.timestamp;
134
+ const currentL1BlockData = { l1BlockNumber: currentL1BlockNumber, l1BlockHash: currentL1BlockHash };
128
135
 
129
136
  if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
130
137
  this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
@@ -141,45 +148,15 @@ export class ArchiverL1Synchronizer implements Traceable {
141
148
  );
142
149
  }
143
150
 
144
- // Load sync point for blocks and messages defaulting to start block
145
- const {
146
- blocksSynchedTo = this.l1Constants.l1StartBlock,
147
- messagesSynchedTo = {
148
- l1BlockNumber: this.l1Constants.l1StartBlock,
149
- l1BlockHash: this.l1Constants.l1StartBlockHash,
150
- },
151
- } = await this.store.getSynchPoint();
151
+ // Load sync point for blocks defaulting to start block
152
+ const { blocksSynchedTo = this.l1Constants.l1StartBlock } = await this.store.getSynchPoint();
153
+ this.log.debug(`Starting new archiver sync iteration`, { blocksSynchedTo, currentL1BlockData });
152
154
 
153
- this.log.debug(`Starting new archiver sync iteration`, {
154
- blocksSynchedTo,
155
- messagesSynchedTo,
156
- currentL1BlockNumber,
157
- currentL1BlockHash,
158
- });
155
+ // Sync L1 to L2 messages. We retry this a few times since there are error conditions that reset the sync point, requiring a new iteration.
156
+ // Note that we cannot just wait for the l1 synchronizer to loop again, since the synchronizer would report as synced up to the current L1
157
+ // block, when that wouldn't be the case, since L1 to L2 messages would need another iteration.
158
+ await retryTimes(() => this.handleL1ToL2Messages(currentL1BlockData), 'Handling L1 to L2 messages', 3, 0.1);
159
159
 
160
- // ********** Ensuring Consistency of data pulled from L1 **********
161
-
162
- /**
163
- * There are a number of calls in this sync operation to L1 for retrieving
164
- * events and transaction data. There are a couple of things we need to bear in mind
165
- * to ensure that data is read exactly once.
166
- *
167
- * The first is the problem of eventually consistent ETH service providers like Infura.
168
- * Each L1 read operation will query data from the last L1 block that it saw emit its kind of data.
169
- * (so pending L1 to L2 messages will read from the last L1 block that emitted a message and so on)
170
- * This will mean the archiver will lag behind L1 and will only advance when there's L2-relevant activity on the chain.
171
- *
172
- * The second is that in between the various calls to L1, the block number can move meaning some
173
- * of the following calls will return data for blocks that were not present during earlier calls.
174
- * To combat this for the time being we simply ensure that all data retrieval methods only retrieve
175
- * data up to the currentBlockNumber captured at the top of this function. We might want to improve on this
176
- * in future but for the time being it should give us the guarantees that we need
177
- */
178
-
179
- // ********** Events that are processed per L1 block **********
180
- await this.handleL1ToL2Messages(messagesSynchedTo, currentL1BlockNumber);
181
-
182
- // ********** Events that are processed per checkpoint **********
183
160
  if (currentL1BlockNumber > blocksSynchedTo) {
184
161
  // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
185
162
  // pending chain validation status, proven checkpoint number, and synched L1 block number.
@@ -251,8 +228,11 @@ export class ArchiverL1Synchronizer implements Traceable {
251
228
  finalizedL1BlockNumber,
252
229
  });
253
230
  }
254
- } catch (err) {
255
- this.log.warn(`Failed to update finalized checkpoint: ${err}`);
231
+ } catch (err: any) {
232
+ // The rollup contract may not exist at the finalized L1 block right after deployment.
233
+ if (!err?.message?.includes('returned no data')) {
234
+ this.log.warn(`Failed to update finalized checkpoint: ${err}`);
235
+ }
256
236
  }
257
237
  }
258
238
 
@@ -269,29 +249,33 @@ export class ArchiverL1Synchronizer implements Traceable {
269
249
  return;
270
250
  }
271
251
 
272
- // What's the slot of the first uncheckpointed block?
252
+ // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
253
+ const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
273
254
  const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
255
+
256
+ // What's the slot of the first uncheckpointed block?
274
257
  const [firstUncheckpointedBlockHeader] = await this.store.getBlockHeaders(firstUncheckpointedBlockNumber, 1);
275
258
  const firstUncheckpointedBlockSlot = firstUncheckpointedBlockHeader?.getSlot();
276
259
 
277
- // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
278
- const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
260
+ if (firstUncheckpointedBlockSlot === undefined || firstUncheckpointedBlockSlot >= slotAtNextL1Block) {
261
+ return;
262
+ }
279
263
 
280
- // Prune provisional blocks from slots that have ended without being checkpointed
281
- if (firstUncheckpointedBlockSlot !== undefined && firstUncheckpointedBlockSlot < slotAtNextL1Block) {
282
- this.log.warn(
283
- `Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`,
284
- { firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(), slotAtNextL1Block },
285
- );
286
- const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
264
+ // Prune provisional blocks from slots that have ended without being checkpointed.
265
+ // This also clears any proposed checkpoint whose blocks are being pruned.
266
+ this.log.warn(
267
+ `Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`,
268
+ { firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(), slotAtNextL1Block },
269
+ );
287
270
 
288
- if (prunedBlocks.length > 0) {
289
- this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
290
- type: L2BlockSourceEvents.L2PruneUncheckpointed,
291
- slotNumber: firstUncheckpointedBlockSlot,
292
- blocks: prunedBlocks,
293
- });
294
- }
271
+ const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
272
+
273
+ if (prunedBlocks.length > 0) {
274
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
275
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
276
+ slotNumber: firstUncheckpointedBlockSlot,
277
+ blocks: prunedBlocks,
278
+ });
295
279
  }
296
280
  }
297
281
 
@@ -385,64 +369,87 @@ export class ArchiverL1Synchronizer implements Traceable {
385
369
  }
386
370
 
387
371
  @trackSpan('Archiver.handleL1ToL2Messages')
388
- private async handleL1ToL2Messages(messagesSyncPoint: L1BlockId, currentL1BlockNumber: bigint): Promise<void> {
389
- this.log.trace(`Handling L1 to L2 messages from ${messagesSyncPoint.l1BlockNumber} to ${currentL1BlockNumber}.`);
390
- if (currentL1BlockNumber <= messagesSyncPoint.l1BlockNumber) {
391
- return;
372
+ private async handleL1ToL2Messages(currentL1Block: L1BlockId): Promise<boolean> {
373
+ // Load the syncpoint, which may have been updated in a previous iteration
374
+ const {
375
+ messagesSynchedTo = {
376
+ l1BlockNumber: this.l1Constants.l1StartBlock,
377
+ l1BlockHash: this.l1Constants.l1StartBlockHash,
378
+ },
379
+ } = await this.store.getSynchPoint();
380
+
381
+ // Nothing to do if L1 block number has not moved forward
382
+ const currentL1BlockNumber = currentL1Block.l1BlockNumber;
383
+ if (currentL1BlockNumber <= messagesSynchedTo.l1BlockNumber) {
384
+ return true;
392
385
  }
393
386
 
394
- // Load remote and local inbox states.
395
- const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
396
- const localLastMessage = await this.store.getLastL1ToL2Message();
387
+ // Compare local message store state with the remote. If they match, we just advance the match pointer.
397
388
  const remoteMessagesState = await this.inbox.getState({ blockNumber: currentL1BlockNumber });
398
- await this.store.setInboxTreeInProgress(remoteMessagesState.treeInProgress);
389
+ const localLastMessage = await this.store.getLastL1ToL2Message();
390
+ if (await this.localStateMatches(localLastMessage, remoteMessagesState)) {
391
+ this.log.trace(`Local L1 to L2 messages are already in sync with remote at L1 block ${currentL1BlockNumber}`);
392
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
393
+ return true;
394
+ }
399
395
 
400
- this.log.trace(`Retrieved remote inbox state at L1 block ${currentL1BlockNumber}.`, {
401
- localMessagesInserted,
402
- localLastMessage,
403
- remoteMessagesState,
404
- });
396
+ // If not, then we are out of sync. Most likely there are new messages on the inbox, so we try retrieving them.
397
+ // However, it could also be the case that there was an L1 reorg and our syncpoint is no longer valid.
398
+ // If that's the case, we'd get an exception out of the message store since the rolling hash of the first message
399
+ // we try to insert would not match the one in the db, in which case we rollback to the last common message with L1.
400
+ try {
401
+ await this.retrieveAndStoreMessages(messagesSynchedTo.l1BlockNumber, currentL1BlockNumber);
402
+ } catch (error) {
403
+ if (isErrorClass(error, MessageStoreError)) {
404
+ this.log.warn(
405
+ `Failed to store L1 to L2 messages retrieved from L1: ${error.message}. Rolling back syncpoint to retry.`,
406
+ { inboxMessage: error.inboxMessage },
407
+ );
408
+ await this.rollbackL1ToL2Messages(remoteMessagesState.treeInProgress);
409
+ return false;
410
+ }
411
+ throw error;
412
+ }
405
413
 
406
- // Compare message count and rolling hash. If they match, no need to retrieve anything.
407
- if (
408
- remoteMessagesState.totalMessagesInserted === localMessagesInserted &&
409
- remoteMessagesState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer32.ZERO)
410
- ) {
411
- this.log.trace(
412
- `No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`,
414
+ // Note that, if there are no new messages to insert, but there was an L1 reorg that pruned out last messages,
415
+ // we'd notice by comparing our local state with the remote one again, and seeing they don't match even after
416
+ // our sync attempt. In this case, we also rollback our syncpoint, and trigger a retry.
417
+ const localLastMessageAfterSync = await this.store.getLastL1ToL2Message();
418
+ if (!(await this.localStateMatches(localLastMessageAfterSync, remoteMessagesState))) {
419
+ this.log.warn(
420
+ `Local L1 to L2 messages state does not match remote after sync attempt. Rolling back syncpoint to retry.`,
421
+ { localLastMessageAfterSync, remoteMessagesState },
413
422
  );
414
- return;
423
+ await this.rollbackL1ToL2Messages(remoteMessagesState.treeInProgress);
424
+ return false;
415
425
  }
416
426
 
417
- // Check if our syncpoint is still valid. If not, there was an L1 reorg and we need to re-retrieve messages.
418
- // Note that we need to fetch it from logs and not from inbox state at the syncpoint l1 block number, since it
419
- // could be older than 128 blocks and non-archive nodes cannot resolve it.
420
- if (localLastMessage) {
421
- const remoteLastMessage = await this.retrieveL1ToL2Message(localLastMessage.leaf);
422
- this.log.trace(`Retrieved remote message for local last`, { remoteLastMessage, localLastMessage });
423
- if (!remoteLastMessage || !remoteLastMessage.rollingHash.equals(localLastMessage.rollingHash)) {
424
- this.log.warn(`Rolling back L1 to L2 messages due to hash mismatch or msg not found.`, {
425
- remoteLastMessage,
426
- messagesSyncPoint,
427
- localLastMessage,
428
- });
427
+ // Advance the syncpoint after a successful sync
428
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
429
+ return true;
430
+ }
429
431
 
430
- messagesSyncPoint = await this.rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint);
431
- this.log.debug(`Rolled back L1 to L2 messages to L1 block ${messagesSyncPoint.l1BlockNumber}.`, {
432
- messagesSyncPoint,
433
- });
434
- }
435
- }
432
+ /** Checks if the local rolling hash and message count matches the remote state */
433
+ private async localStateMatches(localLastMessage: InboxMessage | undefined, remoteState: InboxContractState) {
434
+ const localMessageCount = await this.store.getTotalL1ToL2MessageCount();
435
+ this.log.trace(`Comparing local and remote inbox state`, { localMessageCount, localLastMessage, remoteState });
436
+
437
+ return (
438
+ remoteState.totalMessagesInserted === localMessageCount &&
439
+ remoteState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO)
440
+ );
441
+ }
436
442
 
437
- // Retrieve and save messages in batches. Each batch is estimated to acommodate up to L2 'blockBatchSize' blocks,
443
+ /** Retrieves L1 to L2 messages from L1 in batches and stores them. */
444
+ private async retrieveAndStoreMessages(fromL1Block: bigint, toL1Block: bigint): Promise<void> {
438
445
  let searchStartBlock: bigint = 0n;
439
- let searchEndBlock: bigint = messagesSyncPoint.l1BlockNumber;
446
+ let searchEndBlock: bigint = fromL1Block;
440
447
 
441
448
  let lastMessage: InboxMessage | undefined;
442
449
  let messageCount = 0;
443
450
 
444
451
  do {
445
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
452
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
446
453
  this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
447
454
  const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
448
455
  const timer = new Timer();
@@ -454,81 +461,65 @@ export class ArchiverL1Synchronizer implements Traceable {
454
461
  lastMessage = msg;
455
462
  messageCount++;
456
463
  }
457
- } while (searchEndBlock < currentL1BlockNumber);
464
+ } while (searchEndBlock < toL1Block);
458
465
 
459
- // Log stats for messages retrieved (if any).
460
466
  if (messageCount > 0) {
461
467
  this.log.info(
462
468
  `Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`,
463
469
  { lastMessage, messageCount },
464
470
  );
465
471
  }
466
-
467
- // Warn if the resulting rolling hash does not match the remote state we had retrieved.
468
- if (lastMessage && !lastMessage.rollingHash.equals(remoteMessagesState.messagesRollingHash)) {
469
- this.log.warn(`Last message retrieved rolling hash does not match remote state.`, {
470
- lastMessage,
471
- remoteMessagesState,
472
- });
473
- }
474
- }
475
-
476
- private async retrieveL1ToL2Message(leaf: Fr): Promise<InboxMessage | undefined> {
477
- const currentL1BlockNumber = await this.publicClient.getBlockNumber();
478
- let searchStartBlock: bigint = 0n;
479
- let searchEndBlock: bigint = this.l1Constants.l1StartBlock - 1n;
480
-
481
- do {
482
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
483
-
484
- const message = await retrieveL1ToL2Message(this.inbox, leaf, searchStartBlock, searchEndBlock);
485
-
486
- if (message) {
487
- return message;
488
- }
489
- } while (searchEndBlock < currentL1BlockNumber);
490
-
491
- return undefined;
492
472
  }
493
473
 
494
- private async rollbackL1ToL2Messages(
495
- localLastMessage: InboxMessage,
496
- messagesSyncPoint: L1BlockId,
497
- ): Promise<L1BlockId> {
474
+ /**
475
+ * Rolls back local L1 to L2 messages to the last common message with L1, and updates the syncpoint to the L1 block of that message.
476
+ * If no common message is found, rolls back all messages and sets the syncpoint to the start block.
477
+ */
478
+ private async rollbackL1ToL2Messages(remoteTreeInProgress: bigint): Promise<L1BlockId> {
498
479
  // Slowly go back through our messages until we find the last common message.
499
480
  // We could query the logs in batch as an optimization, but the depth of the reorg should not be deep, and this
500
481
  // is a very rare case, so it's fine to query one log at a time.
501
482
  let commonMsg: undefined | InboxMessage;
502
- this.log.verbose(`Searching most recent common L1 to L2 message at or before index ${localLastMessage.index}`);
503
- for await (const msg of this.store.iterateL1ToL2Messages({ reverse: true, end: localLastMessage.index })) {
504
- const remoteMsg = await this.retrieveL1ToL2Message(msg.leaf);
505
- const logCtx = { remoteMsg, localMsg: msg };
506
- if (remoteMsg && remoteMsg.rollingHash.equals(msg.rollingHash)) {
483
+ let messagesToDelete = 0;
484
+ this.log.verbose(`Searching most recent common L1 to L2 message`);
485
+ for await (const localMsg of this.store.iterateL1ToL2Messages({ reverse: true })) {
486
+ const remoteMsg = await retrieveL1ToL2Message(this.inbox, localMsg);
487
+ const logCtx = { remoteMsg, localMsg: localMsg };
488
+ if (remoteMsg && remoteMsg.rollingHash.equals(localMsg.rollingHash)) {
507
489
  this.log.verbose(
508
- `Found most recent common L1 to L2 message at index ${msg.index} on L1 block ${msg.l1BlockNumber}`,
490
+ `Found most recent common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber}`,
509
491
  logCtx,
510
492
  );
511
493
  commonMsg = remoteMsg;
512
494
  break;
513
495
  } else if (remoteMsg) {
514
- this.log.debug(`Local L1 to L2 message with index ${msg.index} has different rolling hash`, logCtx);
496
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} has different rolling hash`, logCtx);
497
+ messagesToDelete++;
515
498
  } else {
516
- this.log.debug(`Local L1 to L2 message with index ${msg.index} not found on L1`, logCtx);
499
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} not found on L1`, logCtx);
500
+ messagesToDelete++;
517
501
  }
518
502
  }
519
503
 
520
- // Delete everything after the common message we found.
521
- const lastGoodIndex = commonMsg?.index;
522
- this.log.warn(`Deleting all local L1 to L2 messages after index ${lastGoodIndex ?? 'undefined'}`);
523
- await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
504
+ // Delete everything after the common message we found, if anything needs to be deleted.
505
+ // Do not exit early if there are no messages to delete, we still want to update the syncpoint.
506
+ if (messagesToDelete > 0) {
507
+ const lastGoodIndex = commonMsg?.index;
508
+ this.log.warn(`Rolling back all local L1 to L2 messages after index ${lastGoodIndex ?? 'initial'}`);
509
+ await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
510
+ }
524
511
 
525
512
  // Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
526
513
  // the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
527
514
  // after the last common message.
528
515
  const syncPointL1BlockNumber = commonMsg ? commonMsg.l1BlockNumber - 1n : this.l1Constants.l1StartBlock;
529
516
  const syncPointL1BlockHash = await this.getL1BlockHash(syncPointL1BlockNumber);
530
- messagesSyncPoint = { l1BlockNumber: syncPointL1BlockNumber, l1BlockHash: syncPointL1BlockHash };
531
- await this.store.setMessageSynchedL1Block(messagesSyncPoint);
517
+ const messagesSyncPoint = { l1BlockNumber: syncPointL1BlockNumber, l1BlockHash: syncPointL1BlockHash };
518
+ await this.store.setMessageSyncState(messagesSyncPoint, remoteTreeInProgress);
519
+ this.log.verbose(`Updated messages syncpoint to L1 block ${syncPointL1BlockNumber}`, {
520
+ ...messagesSyncPoint,
521
+ remoteTreeInProgress,
522
+ });
532
523
  return messagesSyncPoint;
533
524
  }
534
525