@aztec-labs/archiver 6.0.0-rc.2 → 6.0.0-rc.4

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 (62) hide show
  1. package/dest/archiver.d.ts +11 -2
  2. package/dest/archiver.d.ts.map +1 -1
  3. package/dest/archiver.js +94 -2
  4. package/dest/config.js +1 -1
  5. package/dest/errors.d.ts +12 -1
  6. package/dest/errors.d.ts.map +1 -1
  7. package/dest/errors.js +12 -0
  8. package/dest/l1/bin/retrieve-calldata.js +7 -5
  9. package/dest/l1/calldata_retriever.d.ts +5 -2
  10. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  11. package/dest/l1/calldata_retriever.js +8 -3
  12. package/dest/l1/data_retrieval.d.ts +2 -1
  13. package/dest/l1/data_retrieval.d.ts.map +1 -1
  14. package/dest/l1/data_retrieval.js +14 -9
  15. package/dest/l1/validate_trace.d.ts +3 -1
  16. package/dest/l1/validate_trace.d.ts.map +1 -1
  17. package/dest/l1/validate_trace.js +8 -3
  18. package/dest/modules/checkpoint_ingestor.d.ts +71 -0
  19. package/dest/modules/checkpoint_ingestor.d.ts.map +1 -0
  20. package/dest/modules/checkpoint_ingestor.js +516 -0
  21. package/dest/modules/data_store_updater.d.ts +6 -11
  22. package/dest/modules/data_store_updater.d.ts.map +1 -1
  23. package/dest/modules/data_store_updater.js +4 -3
  24. package/dest/modules/instrumentation.d.ts +8 -4
  25. package/dest/modules/instrumentation.d.ts.map +1 -1
  26. package/dest/modules/instrumentation.js +8 -2
  27. package/dest/modules/l1_synchronizer.d.ts +3 -7
  28. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  29. package/dest/modules/l1_synchronizer.js +84 -420
  30. package/dest/modules/pending_chain_validation_tracker.d.ts +21 -0
  31. package/dest/modules/pending_chain_validation_tracker.d.ts.map +1 -0
  32. package/dest/modules/pending_chain_validation_tracker.js +32 -0
  33. package/dest/modules/validation.d.ts +2 -2
  34. package/dest/modules/validation.d.ts.map +1 -1
  35. package/dest/modules/validation.js +17 -11
  36. package/dest/store/block_store.d.ts +1 -1
  37. package/dest/store/block_store.d.ts.map +1 -1
  38. package/dest/store/block_store.js +8 -2
  39. package/dest/store/log_store_codec.d.ts +2 -1
  40. package/dest/store/log_store_codec.d.ts.map +1 -1
  41. package/dest/store/log_store_codec.js +1 -0
  42. package/dest/test/fake_l1_state.d.ts +21 -1
  43. package/dest/test/fake_l1_state.d.ts.map +1 -1
  44. package/dest/test/fake_l1_state.js +82 -30
  45. package/package.json +15 -15
  46. package/src/archiver.ts +112 -3
  47. package/src/config.ts +1 -1
  48. package/src/errors.ts +21 -0
  49. package/src/l1/README.md +5 -0
  50. package/src/l1/bin/retrieve-calldata.ts +5 -3
  51. package/src/l1/calldata_retriever.ts +8 -3
  52. package/src/l1/data_retrieval.ts +13 -11
  53. package/src/l1/validate_trace.ts +11 -2
  54. package/src/modules/checkpoint_ingestor.ts +742 -0
  55. package/src/modules/data_store_updater.ts +7 -13
  56. package/src/modules/instrumentation.ts +17 -3
  57. package/src/modules/l1_synchronizer.ts +116 -563
  58. package/src/modules/pending_chain_validation_tracker.ts +43 -0
  59. package/src/modules/validation.ts +13 -9
  60. package/src/store/block_store.ts +6 -0
  61. package/src/store/log_store_codec.ts +1 -0
  62. package/src/test/fake_l1_state.ts +94 -31
@@ -1 +1 @@
1
- {"version":3,"file":"validate_trace.d.ts","sourceRoot":"","sources":["../../src/l1/validate_trace.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAe,KAAK,cAAc,EAAgB,MAAM,4BAA4B,CAAC;AA2C5F,0CAA0C;AAC1C,MAAM,WAAW,iBAAiB;IAChC,6DAA6D;IAC7D,gBAAgB,EAAE,OAAO,CAAC;IAC1B,wDAAwD;IACxD,sBAAsB,EAAE,OAAO,CAAC;IAChC,2EAA2E;IAC3E,aAAa,EAAE,OAAO,CAAC;IACvB,sEAAsE;IACtE,mBAAmB,EAAE,OAAO,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,qBAAqB,EAC7B,QAAQ,CAAC,EAAE,cAAc,GACxB,OAAO,CAAC,iBAAiB,CAAC,CAiG5B;AAMD;;;;;;;;GAQG;AACH,wBAAsB,+BAA+B,CACnD,MAAM,EAAE,qBAAqB,EAC7B,yBAAyB,EAAE,OAAO,EAClC,QAAQ,CAAC,EAAE,cAAc,GACxB,OAAO,CAAC,IAAI,CAAC,CA6Cf"}
1
+ {"version":3,"file":"validate_trace.d.ts","sourceRoot":"","sources":["../../src/l1/validate_trace.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAe,KAAK,cAAc,EAAgB,MAAM,4BAA4B,CAAC;AA2C5F,0CAA0C;AAC1C,MAAM,WAAW,iBAAiB;IAChC,6DAA6D;IAC7D,gBAAgB,EAAE,OAAO,CAAC;IAC1B,wDAAwD;IACxD,sBAAsB,EAAE,OAAO,CAAC;IAChC,2EAA2E;IAC3E,aAAa,EAAE,OAAO,CAAC;IACvB,sEAAsE;IACtE,mBAAmB,EAAE,OAAO,CAAC;IAC7B,uGAAuG;IACvG,WAAW,EAAE,OAAO,CAAC;CACtB;AAED;;;;;;GAMG;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,qBAAqB,EAC7B,QAAQ,CAAC,EAAE,cAAc,GACxB,OAAO,CAAC,iBAAiB,CAAC,CAmG5B;AAMD;;;;;;;;GAQG;AACH,wBAAsB,+BAA+B,CACnD,MAAM,EAAE,qBAAqB,EAC7B,yBAAyB,EAAE,OAAO,EAClC,QAAQ,CAAC,EAAE,cAAc,GACxB,OAAO,CAAC,IAAI,CAAC,CAkDf"}
@@ -48,7 +48,8 @@ import { traceTransactionResponseSchema } from './trace_tx.js';
48
48
  debugTraceRecent: false,
49
49
  traceTransactionRecent: false,
50
50
  debugTraceOld: false,
51
- traceTransactionOld: false
51
+ traceTransactionOld: false,
52
+ noTxToProbe: false
52
53
  };
53
54
  try {
54
55
  // Get the latest block
@@ -65,6 +66,7 @@ import { traceTransactionResponseSchema } from './trace_tx.js';
65
66
  }
66
67
  if (!hasTxs(latestBlock)) {
67
68
  logger.warn('No blocks with transactions found from latest back to genesis, cannot validate trace availability');
69
+ result.noTxToProbe = true;
68
70
  return result;
69
71
  }
70
72
  // Get a transaction from the found block
@@ -141,14 +143,17 @@ function hasTxs(block) {
141
143
  methods.push('trace_transaction');
142
144
  }
143
145
  logger.warn(`Ethereum client only supports trace methods for recent blocks (${methods.join(', ')}). Historical transaction traces may not be available.`);
146
+ } else if (availability.noTxToProbe) {
147
+ // An idle dev or test chain can have no recent transaction to trace, which says nothing about the endpoint
148
+ logger.warn('Starting without confirming that the Ethereum debug client supports trace methods');
144
149
  } else {
145
150
  // Error case: no support at all
146
- const errorMessage = 'Ethereum debug client does not support debug_traceTransaction or trace_transaction methods. Transaction tracing will not be available. This may impact archiver syncing.';
151
+ const errorMessage = 'Ethereum debug client does not support debug_traceTransaction or trace_transaction methods. ' + 'The archiver needs a trace to read checkpoints published through contracts it does not recognize, ' + 'and stops syncing at the first one it cannot read. Point ETHEREUM_DEBUG_HOSTS at a trace-capable endpoint.';
147
152
  if (ethereumAllowNoDebugHosts) {
148
153
  logger.warn(`${errorMessage} Continuing because ETHEREUM_ALLOW_NO_DEBUG_HOSTS is set to true.`);
149
154
  } else {
150
155
  logger.error(errorMessage);
151
- throw new Error(`${errorMessage} Set ETHEREUM_ALLOW_NO_DEBUG_HOSTS=true to bypass this check.`);
156
+ throw new Error(`${errorMessage} Set ETHEREUM_ALLOW_NO_DEBUG_HOSTS=true to start anyway.`);
152
157
  }
153
158
  }
154
159
  }
@@ -0,0 +1,71 @@
1
+ import type { BlobClientInterface } from '@aztec-labs/blob-client/client';
2
+ import { type EpochCache } from '@aztec-labs/epoch-cache';
3
+ import type { RollupContract } from '@aztec-labs/ethereum/contracts';
4
+ import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec-labs/ethereum/types';
5
+ import type { Logger } from '@aztec-labs/foundation/log';
6
+ import { type ArchiverEmitter, type L2Block, type ValidateCheckpointResult } from '@aztec-labs/stdlib/block';
7
+ import { type L1RollupConstants } from '@aztec-labs/stdlib/epoch-helpers';
8
+ import { type Tracer } from '@aztec-labs/telemetry-client';
9
+ import type { RejectedCheckpoint } from '../store/block_store.js';
10
+ import type { ArchiverDataStores } from '../store/data_stores.js';
11
+ import type { ArchiverDataStoreUpdater } from './data_store_updater.js';
12
+ import type { ArchiverInstrumentation } from './instrumentation.js';
13
+ /** A checkpoint observed in L1 calldata this iteration, whether ingested or rejected. */
14
+ export type SeenCheckpoint = Pick<RejectedCheckpoint, 'checkpointNumber' | 'l1'>;
15
+ /** Collaborators the checkpoint ingestor shares with the L1 synchronizer. */
16
+ export type CheckpointIngestorDeps = {
17
+ rollup: RollupContract;
18
+ publicClient: ViemPublicClient;
19
+ debugClient: ViemPublicDebugClient;
20
+ blobClient: BlobClientInterface;
21
+ epochCache: EpochCache;
22
+ stores: ArchiverDataStores;
23
+ updater: ArchiverDataStoreUpdater;
24
+ events: ArchiverEmitter;
25
+ instrumentation: ArchiverInstrumentation;
26
+ l1Constants: L1RollupConstants;
27
+ tracer: Tracer;
28
+ log: Logger;
29
+ };
30
+ /** Ingestion settings, read on every pass so config updates apply to the next one. */
31
+ export type CheckpointIngestorOptions = {
32
+ batchSizeInL1Blocks: bigint;
33
+ skipValidateCheckpointAttestations: boolean;
34
+ skipPromoteProposedCheckpointDuringL1Sync: boolean;
35
+ };
36
+ /**
37
+ * Ingests the checkpoints L1 published in a range of L1 blocks: retrieves their calldata in batches, screens
38
+ * attestations and rejected ancestry from calldata alone, promotes a matching locally proposed checkpoint instead of
39
+ * fetching its blobs, fetches blobs for the rest and persists each batch. It rewinds the L1 sync point when a batch
40
+ * turns out not to be consecutive with the stored chain, and never leaves it past where a batch started if the batch
41
+ * fails before it is persisted.
42
+ */
43
+ export declare class CheckpointIngestor {
44
+ private readonly deps;
45
+ private readonly getOptions;
46
+ constructor(deps: CheckpointIngestorDeps, getOptions: () => CheckpointIngestorOptions);
47
+ /** Ingests every checkpoint published in the L1 block range (from, to], batch by batch, in L1 order. */
48
+ ingest(from: bigint, to: bigint, opts: {
49
+ initialSyncComplete: boolean;
50
+ initialValidationStatus: ValidateCheckpointResult | undefined;
51
+ }): Promise<{
52
+ blocksAdded: L2Block[];
53
+ lastSeenCheckpoint: SeenCheckpoint | undefined;
54
+ }>;
55
+ private getSignatureContext;
56
+ private nextRange;
57
+ private retrieveCalldata;
58
+ private ingestBatch;
59
+ private planBatch;
60
+ private screen;
61
+ private recordRejected;
62
+ private buildPublished;
63
+ private persistBatch;
64
+ private rewindSyncPointAfterGap;
65
+ private restoreSyncPointAfterFailedBatch;
66
+ private logDownloaded;
67
+ private reportEquivocationIfSameSigner;
68
+ private getL1ProposerForSlot;
69
+ private matchProposedCheckpoint;
70
+ }
71
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2hlY2twb2ludF9pbmdlc3Rvci5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL21vZHVsZXMvY2hlY2twb2ludF9pbmdlc3Rvci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxtQkFBbUIsRUFBRSxNQUFNLGdDQUFnQyxDQUFDO0FBQzFFLE9BQU8sRUFBRSxLQUFLLFVBQVUsRUFBMEIsTUFBTSx5QkFBeUIsQ0FBQztBQUNsRixPQUFPLEtBQUssRUFBRSxjQUFjLEVBQUUsTUFBTSxnQ0FBZ0MsQ0FBQztBQUNyRSxPQUFPLEtBQUssRUFBRSxnQkFBZ0IsRUFBRSxxQkFBcUIsRUFBRSxNQUFNLDRCQUE0QixDQUFDO0FBSzFGLE9BQU8sS0FB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BAAuB;CA+EtC"}
@@ -0,0 +1,516 @@
1
+ import { requireStableCommittee } from '@aztec-labs/epoch-cache';
2
+ import { asyncPool } from '@aztec-labs/foundation/async-pool';
3
+ import { BlockNumber, CheckpointNumber } from '@aztec-labs/foundation/branded-types';
4
+ import { partition, pick } from '@aztec-labs/foundation/collection';
5
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
6
+ import { elapsed } from '@aztec-labs/foundation/timer';
7
+ import { L2BlockSourceEvents } from '@aztec-labs/stdlib/block';
8
+ import { Checkpoint, PublishedCheckpoint } from '@aztec-labs/stdlib/checkpoint';
9
+ import { getEpochAtSlot, getTimestampForSlot } from '@aztec-labs/stdlib/epoch-helpers';
10
+ import { execInSpan } from '@aztec-labs/telemetry-client';
11
+ import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
12
+ import { getCheckpointBlobDataFromBlobs, retrieveCheckpointCalldataFromRollup, retrievedToPublishedCheckpoint } from '../l1/data_retrieval.js';
13
+ import { PendingChainValidationTracker } from './pending_chain_validation_tracker.js';
14
+ import { resolveCheckpointAttestationsFromCalldata } from './validation.js';
15
+ /**
16
+ * Ingests the checkpoints L1 published in a range of L1 blocks: retrieves their calldata in batches, screens
17
+ * attestations and rejected ancestry from calldata alone, promotes a matching locally proposed checkpoint instead of
18
+ * fetching its blobs, fetches blobs for the rest and persists each batch. It rewinds the L1 sync point when a batch
19
+ * turns out not to be consecutive with the stored chain, and never leaves it past where a batch started if the batch
20
+ * fails before it is persisted.
21
+ */ export class CheckpointIngestor {
22
+ deps;
23
+ getOptions;
24
+ constructor(deps, getOptions){
25
+ this.deps = deps;
26
+ this.getOptions = getOptions;
27
+ }
28
+ /** Ingests every checkpoint published in the L1 block range (from, to], batch by batch, in L1 order. */ async ingest(from, to, opts) {
29
+ const validation = new PendingChainValidationTracker(opts.initialValidationStatus);
30
+ const blocksAdded = [];
31
+ let lastSeenCheckpoint;
32
+ // Retrieve checkpoints in batches. Each batch is estimated to accommodate up to 'blockBatchSize' L1 blocks,
33
+ // computed using the L2 block time vs the L1 block time.
34
+ let searchStartBlock = from;
35
+ let searchEndBlock = from;
36
+ do {
37
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, to);
38
+ const calldataCheckpoints = await this.retrieveCalldata(searchStartBlock, searchEndBlock);
39
+ if (calldataCheckpoints.length === 0) {
40
+ continue;
41
+ }
42
+ const { plan, added } = await this.ingestBatch(calldataCheckpoints, {
43
+ searchStartBlock,
44
+ searchEndBlock
45
+ }, validation, opts.initialSyncComplete);
46
+ blocksAdded.push(...added);
47
+ lastSeenCheckpoint = plan.lastSeenCheckpoint;
48
+ }while (searchEndBlock < to)
49
+ return {
50
+ blocksAdded,
51
+ lastSeenCheckpoint
52
+ };
53
+ }
54
+ getSignatureContext() {
55
+ return {
56
+ chainId: this.deps.publicClient.chain.id,
57
+ rollupAddress: EthAddress.fromString(this.deps.rollup.address)
58
+ };
59
+ }
60
+ nextRange(end, limit) {
61
+ const nextStart = end + 1n;
62
+ const nextEnd = nextStart + this.getOptions().batchSizeInL1Blocks;
63
+ if (nextEnd > limit) {
64
+ return [
65
+ nextStart,
66
+ limit
67
+ ];
68
+ }
69
+ return [
70
+ nextStart,
71
+ nextEnd
72
+ ];
73
+ }
74
+ /**
75
+ * Retrieves the calldata of the checkpoints published in an L1 block range, sorted by L1 block. Blobs are not
76
+ * fetched yet, since we may be able to just get that data out of the proposed chain.
77
+ */ async retrieveCalldata(searchStartBlock, searchEndBlock) {
78
+ this.deps.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
79
+ const calldataCheckpoints = await execInSpan(this.deps.tracer, 'Archiver.retrieveCheckpointCalldataFromRollup', ()=>retrieveCheckpointCalldataFromRollup(this.deps.rollup, this.deps.publicClient, this.deps.debugClient, searchStartBlock, searchEndBlock, this.deps.instrumentation, this.deps.log));
80
+ if (calldataCheckpoints.length === 0) {
81
+ // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
82
+ // See further details in the TODO(#8621) comment in ArchiverL1Synchronizer.reconcileCheckpointedChain.
83
+ this.deps.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
84
+ return [];
85
+ }
86
+ this.deps.log.debug(`Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`, {
87
+ lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
88
+ searchStartBlock,
89
+ searchEndBlock
90
+ });
91
+ return calldataCheckpoints;
92
+ }
93
+ /**
94
+ * Plans and persists one non-empty batch of retrieved checkpoints.
95
+ *
96
+ * Screening records rejected checkpoints as it goes, and each such write advances the L1 sync point past the
97
+ * rejected checkpoint's L1 block before the batch's valid checkpoints are persisted. If anything in the batch
98
+ * throws before the batch is persisted, the sync point is restored to where it stood before the batch, so the next
99
+ * iteration processes the whole batch again instead of skipping its valid checkpoints. Once the batch is persisted
100
+ * the sync point is left alone: replaying it would refetch blobs for checkpoints already stored, including promoted
101
+ * ones this node never fetched blobs for, and stall if those blobs are unavailable.
102
+ */ async ingestBatch(calldataCheckpoints, range, validation, initialSyncComplete) {
103
+ const syncPointBeforeBatch = await this.deps.stores.blocks.getSynchedL1BlockNumber();
104
+ const progress = {
105
+ persisted: false
106
+ };
107
+ try {
108
+ const plan = await this.planBatch(calldataCheckpoints, validation, initialSyncComplete);
109
+ const added = await this.persistBatch(plan, progress);
110
+ this.logDownloaded(plan.published);
111
+ return {
112
+ plan,
113
+ added
114
+ };
115
+ } catch (err) {
116
+ await this.restoreSyncPointAfterFailedBatch(syncPointBeforeBatch, range, progress);
117
+ throw err;
118
+ }
119
+ }
120
+ /**
121
+ * Decides everything about a batch before touching the store, other than recording rejected checkpoints. The
122
+ * proposed-copy lookup runs on the last checkpoint before screening, so a diverging local copy is evicted (and its
123
+ * equivocation reported) even when L1's checkpoint is then rejected, and a matching copy whose L1 checkpoint is
124
+ * rejected is not promoted.
125
+ */ async planBatch(calldataCheckpoints, validation, initialSyncComplete) {
126
+ // Decode and validate attestations from CALLDATA before fetching any blobs, so a checkpoint with invalid
127
+ // attestations is rejected without decoding a possibly malformed blob. Runs even when validation is
128
+ // disabled, since promotion and persistence need the decoded attestations.
129
+ const resolvedCheckpoints = await asyncPool(10, calldataCheckpoints, async (calldataCheckpoint)=>{
130
+ const { attestations, validationResult } = await resolveCheckpointAttestationsFromCalldata(calldataCheckpoint, this.deps.epochCache, this.deps.l1Constants, this.getSignatureContext(), this.deps.log);
131
+ return {
132
+ checkpoint: {
133
+ ...calldataCheckpoint,
134
+ attestations
135
+ },
136
+ validationResult
137
+ };
138
+ });
139
+ // Check if the last checkpoint matches a local pending entry (so we can skip blob fetch).
140
+ // We only check the last one; if it matches, the blob fetch is skipped for that entry.
141
+ // TODO(palla/pipelining): We may have more than a single checkpoint to promote
142
+ const lastCalldataCheckpoint = resolvedCheckpoints[resolvedCheckpoints.length - 1].checkpoint;
143
+ const match = await this.matchProposedCheckpoint(lastCalldataCheckpoint);
144
+ const checkpointToPromote = match.kind === 'promote' ? match.checkpoint : undefined;
145
+ const checkpointsToIngest = await this.screen(resolvedCheckpoints, validation);
146
+ const published = await this.buildPublished(checkpointsToIngest, checkpointToPromote, initialSyncComplete);
147
+ // Split valid checkpoints: the promoted one (if any) is persisted via the proposed-promotion path,
148
+ // the rest via addCheckpoints. Both paths run within the same store transaction for atomicity.
149
+ const [[promoted], toAdd] = partition(published, (c)=>c.checkpoint.number === checkpointToPromote?.checkpoint.number);
150
+ return {
151
+ published,
152
+ toAdd,
153
+ promoted,
154
+ evictProposedFrom: match.kind === 'evict' ? match.fromCheckpointNumber : undefined,
155
+ validationUpdate: validation.update,
156
+ // The last checkpoint seen on L1 this batch (valid or rejected), tracked from calldata since
157
+ // rejected checkpoints are no longer built into PublishedCheckpoints.
158
+ lastSeenCheckpoint: pick(lastCalldataCheckpoint, 'checkpointNumber', 'l1')
159
+ };
160
+ }
161
+ /**
162
+ * Screens checkpoints by their calldata attestation verdicts before fetching any blobs. A checkpoint with invalid
163
+ * attestations (or one descending from a rejected ancestor) is rejected here without fetching its blobs, so a
164
+ * malformed blob does not throw during decode before the rejection path runs and stall sync.
165
+ *
166
+ * Rejected checkpoints are recorded as they are found, outside the transaction that persists the batch, so a later
167
+ * checkpoint in the same batch can find its rejected ancestor. Each record advances the L1 sync point past it.
168
+ * Returns the accepted checkpoints in L1 order.
169
+ */ async screen(resolvedCheckpoints, validation) {
170
+ const checkpointsToIngest = [];
171
+ // Archive roots accepted earlier in this batch. The store only drops a rejected entry for a root when the batch
172
+ // is persisted, so an accepted checkpoint whose root was also rejected (an earlier post of the same checkpoint
173
+ // with invalid attestations) would otherwise still look rejected to the children that follow it in this batch.
174
+ const acceptedArchiveRoots = new Set();
175
+ for (const { checkpoint: calldataCheckpoint, validationResult: resolvedValidationResult } of resolvedCheckpoints){
176
+ // Check the attestations uploaded by the publisher to L1 are correct.
177
+ // Rollup contract does not validate attestations to save on gas, so this
178
+ // falls on the nodes to verify offchain and skip those checkpoints.
179
+ const validationResult = this.getOptions().skipValidateCheckpointAttestations ? {
180
+ valid: true
181
+ } : resolvedValidationResult;
182
+ // Also skip the checkpoint if it builds on a previously-rejected ancestor. Without
183
+ // this, addCheckpoints would throw InitialCheckpointNumberNotSequentialError when the
184
+ // ancestor was skipped earlier (e.g. due to invalid attestations), the catch handler
185
+ // would roll back the L1 sync point, and the next iteration would re-fetch and re-throw.
186
+ const parentArchiveRoot = calldataCheckpoint.header.lastArchiveRoot;
187
+ const rejectedAncestor = acceptedArchiveRoots.has(parentArchiveRoot.toString()) ? undefined : await this.deps.stores.blocks.getRejectedCheckpointByArchiveRoot(parentArchiveRoot);
188
+ validation.observe(validationResult, {
189
+ hasRejectedAncestor: rejectedAncestor !== undefined
190
+ });
191
+ if (!validationResult.valid) {
192
+ this.deps.log.warn(`Skipping checkpoint ${calldataCheckpoint.checkpointNumber} due to invalid attestations`, {
193
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
194
+ l1BlockNumber: calldataCheckpoint.l1.blockNumber,
195
+ ...pick(validationResult, 'reason')
196
+ });
197
+ // Emit event for invalid checkpoint detection
198
+ this.deps.events.emit(L2BlockSourceEvents.InvalidAttestationsCheckpointDetected, {
199
+ type: L2BlockSourceEvents.InvalidAttestationsCheckpointDetected,
200
+ validationResult
201
+ });
202
+ // Persist a rejected-ancestor entry so any later checkpoint that builds on this one
203
+ // is detected and skipped (rather than tripping the addCheckpoints consecutive-number
204
+ // check and causing the sync point to roll back in a loop).
205
+ await this.recordRejected(calldataCheckpoint, 'invalid-attestations');
206
+ continue;
207
+ }
208
+ if (rejectedAncestor) {
209
+ const descendantInfo = {
210
+ archive: calldataCheckpoint.archiveRoot,
211
+ lastArchive: calldataCheckpoint.header.lastArchiveRoot,
212
+ slotNumber: calldataCheckpoint.header.slotNumber,
213
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
214
+ timestamp: calldataCheckpoint.header.timestamp
215
+ };
216
+ this.deps.log.warn(`Skipping checkpoint ${calldataCheckpoint.checkpointNumber} as it is a descendant of ` + `rejected checkpoint ${rejectedAncestor.checkpointNumber} (${rejectedAncestor.reason})`, {
217
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
218
+ l1BlockNumber: calldataCheckpoint.l1.blockNumber,
219
+ l1BlockHash: calldataCheckpoint.l1.blockHash,
220
+ ancestorCheckpointNumber: rejectedAncestor.checkpointNumber,
221
+ ancestorArchiveRoot: rejectedAncestor.archiveRoot.toString(),
222
+ ancestorReason: rejectedAncestor.reason
223
+ });
224
+ this.deps.events.emit(L2BlockSourceEvents.DescendentOfInvalidAttestationsCheckpointDetected, {
225
+ type: L2BlockSourceEvents.DescendentOfInvalidAttestationsCheckpointDetected,
226
+ checkpoint: descendantInfo,
227
+ ancestorArchiveRoot: rejectedAncestor.archiveRoot,
228
+ ancestorCheckpointNumber: rejectedAncestor.checkpointNumber
229
+ });
230
+ // Persist this chainpoint as rejected as well, so we can construct a chain of
231
+ // skipped checkpoints starting from the first one with invalid attestations.
232
+ await this.recordRejected(calldataCheckpoint, 'descends-from-invalid-attestations');
233
+ continue;
234
+ }
235
+ checkpointsToIngest.push(calldataCheckpoint);
236
+ acceptedArchiveRoots.add(calldataCheckpoint.archiveRoot.toString());
237
+ }
238
+ return checkpointsToIngest;
239
+ }
240
+ recordRejected(calldataCheckpoint, reason) {
241
+ return this.deps.stores.blocks.addRejectedCheckpoint({
242
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
243
+ archiveRoot: calldataCheckpoint.archiveRoot,
244
+ parentArchiveRoot: calldataCheckpoint.header.lastArchiveRoot,
245
+ slotNumber: calldataCheckpoint.header.slotNumber,
246
+ l1: calldataCheckpoint.l1,
247
+ reason
248
+ });
249
+ }
250
+ /** Builds the published checkpoints for the accepted ones, in L1 order, fetching blobs for all but the promoted one. */ async buildPublished(checkpointsToIngest, checkpointToPromote, initialSyncComplete) {
251
+ // Fetch blobs in parallel only for the surviving (attestation-valid, non-descendant) checkpoints,
252
+ // then build the full published checkpoints. The last calldata checkpoint may be promotable from a
253
+ // local proposed block (checkpointToPromote), in which case it carries no blob to fetch. A missing or
254
+ // undecodable blob throws and propagates, and the batch guard restores the L1 sync point so the fetch is retried.
255
+ const toFetchBlobs = checkpointToPromote ? checkpointsToIngest.filter((c)=>c.checkpointNumber !== checkpointToPromote.checkpoint.number) : checkpointsToIngest;
256
+ const blobFetched = await asyncPool(10, toFetchBlobs, async (checkpoint)=>retrievedToPublishedCheckpoint({
257
+ ...checkpoint,
258
+ checkpointBlobData: await getCheckpointBlobDataFromBlobs(this.deps.blobClient, checkpoint.l1.blockHash, checkpoint.blobHashes, checkpoint.checkpointNumber, this.deps.log, !initialSyncComplete, checkpoint.parentBeaconBlockRoot, checkpoint.l1.timestamp)
259
+ }));
260
+ // Index the built checkpoints by number so we can ingest them in calldata order, slotting in the
261
+ // promoted checkpoint (built from a local proposed block rather than blobs).
262
+ const publishedByNumber = new Map(blobFetched.map((publishedCheckpoint)=>[
263
+ publishedCheckpoint.checkpoint.number,
264
+ publishedCheckpoint
265
+ ]));
266
+ if (checkpointToPromote) {
267
+ publishedByNumber.set(checkpointToPromote.checkpoint.number, checkpointToPromote);
268
+ }
269
+ const validCheckpoints = [];
270
+ for (const calldataCheckpoint of checkpointsToIngest){
271
+ const published = publishedByNumber.get(calldataCheckpoint.checkpointNumber);
272
+ validCheckpoints.push(published);
273
+ this.deps.log.debug(`Ingesting new checkpoint ${published.checkpoint.number} with ${published.checkpoint.blocks.length} blocks`, {
274
+ checkpointHash: published.checkpoint.hash(),
275
+ l1BlockNumber: published.l1.blockNumber,
276
+ ...published.checkpoint.header.toInspect(),
277
+ blocks: published.checkpoint.blocks.map((b)=>b.getStats())
278
+ });
279
+ }
280
+ for (const published of validCheckpoints){
281
+ this.deps.instrumentation.processCheckpointL1Timing({
282
+ slotNumber: published.checkpoint.header.slotNumber,
283
+ l1Timestamp: published.l1.timestamp,
284
+ l1Constants: this.deps.l1Constants
285
+ });
286
+ }
287
+ return validCheckpoints;
288
+ }
289
+ /**
290
+ * Persists a planned batch in one store transaction, then reports its blocks and any local blocks it pruned.
291
+ * Marks `progress.persisted` once `addCheckpoints` has returned, which is after its transaction committed and the
292
+ * frontier cache refreshed, so a failed refresh still counts as not persisted. Rewinds the L1 sync point if the batch
293
+ * is not consecutive with the stored chain. Returns the blocks persisted from L1 payloads.
294
+ */ async persistBatch(plan, progress) {
295
+ try {
296
+ const [processDuration, result] = await elapsed(()=>execInSpan(this.deps.tracer, 'Archiver.addCheckpoints', async ()=>{
297
+ const addResult = await this.deps.updater.addCheckpoints(plan.toAdd, plan.validationUpdate, plan.promoted, plan.evictProposedFrom);
298
+ // Set before the span wrappers finish, so a throw while closing the span doesn't count as unpersisted.
299
+ progress.persisted = true;
300
+ return addResult;
301
+ }));
302
+ if (plan.published.length > 0) {
303
+ this.deps.instrumentation.processNewCheckpointedBlocks(processDuration / plan.published.length, plan.published.flatMap((c)=>c.checkpoint.blocks));
304
+ }
305
+ // Record blocks newly fetched from L1 checkpoint payloads as added. The promoted checkpoint (if any) is
306
+ // excluded: its blocks were already in local archiver storage (added via the proposed-block path) so the
307
+ // block stream does not need them re-downloaded.
308
+ const added = plan.toAdd.flatMap((c)=>c.checkpoint.blocks);
309
+ // If blocks were pruned due to conflict with L1 checkpoints, emit event
310
+ if (result.prunedBlocks && result.prunedBlocks.length > 0) {
311
+ const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
312
+ const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
313
+ this.deps.log.info(`Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`, {
314
+ prunedBlocks: result.prunedBlocks.map((b)=>b.toBlockInfo()),
315
+ prunedSlotNumber,
316
+ prunedCheckpointNumber
317
+ });
318
+ this.deps.instrumentation.recordPrune('l1_conflict');
319
+ // Emit event for listening services to react to the prune.
320
+ // Note: slotNumber comes from the first pruned block. If pruned blocks theoretically spanned multiple slots,
321
+ // only one slot number would be reported (though in practice all blocks in a checkpoint span a single slot).
322
+ this.deps.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
323
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
324
+ slotNumber: prunedSlotNumber,
325
+ blocks: result.prunedBlocks
326
+ });
327
+ }
328
+ return added;
329
+ } catch (err) {
330
+ if (err instanceof InitialCheckpointNumberNotSequentialError) {
331
+ await this.rewindSyncPointAfterGap(err);
332
+ }
333
+ throw err;
334
+ }
335
+ }
336
+ /**
337
+ * Moves the L1 sync point back to the previous checkpoint's L1 block (falling back to the finalized checkpoint's,
338
+ * then to the rollup's start block), so the next iteration fetches the checkpoints missing before the batch.
339
+ */ async rewindSyncPointAfterGap(err) {
340
+ const { previousCheckpointNumber, newCheckpointNumber } = err;
341
+ const previousCheckpoint = previousCheckpointNumber ? await this.deps.stores.blocks.getCheckpointData(CheckpointNumber(previousCheckpointNumber)) : undefined;
342
+ const lastFinalizedCheckpoint = await this.deps.stores.blocks.getCheckpointData(await this.deps.stores.blocks.getFinalizedCheckpointNumber());
343
+ const updatedL1SyncPoint = previousCheckpoint?.l1.blockNumber ?? lastFinalizedCheckpoint?.l1.blockNumber ?? this.deps.l1Constants.l1StartBlock;
344
+ await this.deps.stores.blocks.setSynchedL1BlockNumber(updatedL1SyncPoint);
345
+ this.deps.log.warn(`Attempting to insert checkpoint ${newCheckpointNumber} with previous block ${previousCheckpointNumber}. Rolling back L1 sync point to ${updatedL1SyncPoint} to try and fetch the missing blocks.`, {
346
+ previousCheckpointNumber,
347
+ previousCheckpoint: previousCheckpoint?.header.toInspect(),
348
+ lastFinalizedCheckpoint: lastFinalizedCheckpoint?.header.toInspect(),
349
+ l1StartBlock: this.deps.l1Constants.l1StartBlock,
350
+ newCheckpointNumber,
351
+ updatedL1SyncPoint
352
+ });
353
+ }
354
+ /** Lowers the L1 sync point back to where it stood before a failed batch, unless the batch was persisted. */ async restoreSyncPointAfterFailedBatch(syncPointBeforeBatch, { searchStartBlock, searchEndBlock }, progress) {
355
+ const restoreTo = syncPointBeforeBatch ?? this.deps.l1Constants.l1StartBlock;
356
+ const currentSyncPoint = await this.deps.stores.blocks.getSynchedL1BlockNumber();
357
+ // Only ever lower it, so a deeper rewind made while handling the error (e.g. on a checkpoint gap) is kept.
358
+ if (!progress.persisted && currentSyncPoint !== undefined && currentSyncPoint > restoreTo) {
359
+ this.deps.log.warn(`Restoring L1 sync point to ${restoreTo} after failing to process checkpoints`, {
360
+ currentSyncPoint,
361
+ restoreTo,
362
+ searchStartBlock,
363
+ searchEndBlock
364
+ });
365
+ await this.deps.stores.blocks.setSynchedL1BlockNumber(restoreTo);
366
+ }
367
+ }
368
+ logDownloaded(published) {
369
+ for (const checkpoint of published){
370
+ this.deps.log.info(`Downloaded checkpoint ${checkpoint.checkpoint.number}`, {
371
+ checkpointHash: checkpoint.checkpoint.hash(),
372
+ checkpointNumber: checkpoint.checkpoint.number,
373
+ blockCount: checkpoint.checkpoint.blocks.length,
374
+ txCount: checkpoint.checkpoint.blocks.reduce((acc, b)=>acc + b.body.txEffects.length, 0),
375
+ header: checkpoint.checkpoint.header.toInspect(),
376
+ archiveRoot: checkpoint.checkpoint.archive.root.toString(),
377
+ archiveNextLeafIndex: checkpoint.checkpoint.archive.nextAvailableLeafIndex
378
+ });
379
+ }
380
+ }
381
+ /**
382
+ * Reports equivocation for a local proposed checkpoint that diverges from the L1 checkpoint at the same slot, but
383
+ * only when one key signed both. Two checkpoints for one slot from different proposers are not equivocation: a
384
+ * proposal made before the slot's proposer was final can be superseded by the real proposer's checkpoint on L1.
385
+ * Never throws, so a failed lookup leaves the divergence unattributed without holding up sync.
386
+ */ async reportEquivocationIfSameSigner(proposed, calldataCheckpoint) {
387
+ const { checkpointNumber } = calldataCheckpoint;
388
+ const { slotNumber } = calldataCheckpoint.header;
389
+ let l1Proposer;
390
+ if (proposed.signer) {
391
+ try {
392
+ l1Proposer = await this.getL1ProposerForSlot(slotNumber);
393
+ } catch (err) {
394
+ this.deps.log.warn(`Failed to get the L1 proposer for slot ${slotNumber}`, {
395
+ checkpointNumber,
396
+ slotNumber,
397
+ err
398
+ });
399
+ }
400
+ }
401
+ if (!proposed.signer || !l1Proposer || !proposed.signer.equals(l1Proposer)) {
402
+ this.deps.log.warn(`Not attributing equivocation for checkpoint ${checkpointNumber}: the local proposed copy and the L1 checkpoint have no common signer`, {
403
+ checkpointNumber,
404
+ slotNumber,
405
+ proposedSigner: proposed.signer?.toString(),
406
+ l1Proposer: l1Proposer?.toString()
407
+ });
408
+ return;
409
+ }
410
+ this.deps.events.emit(L2BlockSourceEvents.CheckpointEquivocationDetected, {
411
+ type: L2BlockSourceEvents.CheckpointEquivocationDetected,
412
+ slotNumber,
413
+ checkpointNumber,
414
+ l1ArchiveRoot: calldataCheckpoint.archiveRoot,
415
+ proposedArchiveRoot: proposed.archive.root,
416
+ signer: proposed.signer
417
+ });
418
+ }
419
+ /**
420
+ * Asks the rollup who had to sign the checkpoint it accepted for a past slot. `propose` only succeeds when the slot's
421
+ * proposer signed the checkpoint, and the rollup derives that proposer from history keyed by timestamp, so querying
422
+ * at the latest L1 block returns the address `propose` checked. The propose calldata cannot tell this: the
423
+ * CheckpointProposed event commits to neither the signers nor the bundle signature, so a reverted copy of the call
424
+ * signed by another key matches the event just as well. Returns undefined when L1 did not check the committee's
425
+ * proposer, because an escape hatch was open for the epoch, or when the committee was empty. Throws while the epoch's
426
+ * committee is not stable, since whether its escape hatch was open is not known yet.
427
+ */ async getL1ProposerForSlot(slot) {
428
+ const epoch = getEpochAtSlot(slot, this.deps.l1Constants);
429
+ const { isEscapeHatchOpen } = requireStableCommittee(await this.deps.epochCache.getCommitteeForEpoch(epoch));
430
+ if (isEscapeHatchOpen) {
431
+ return undefined;
432
+ }
433
+ const proposer = await this.deps.rollup.getProposerAt(getTimestampForSlot(slot, this.deps.l1Constants));
434
+ return proposer.isZero() ? undefined : proposer;
435
+ }
436
+ /**
437
+ * Checks if a specific checkpoint matches a local pending entry, and if so, loads local data to build
438
+ * a synthetic published checkpoint (skipping blob fetch), returned as a `promote` match.
439
+ *
440
+ * Returns an `evict` match when the L1 checkpoint does NOT match local pending data for that number, so the
441
+ * caller can evict the entire pending suffix >= fromCheckpointNumber (those entries chain off the now-invalid
442
+ * local state) within the same addCheckpoints transaction.
443
+ */ async matchProposedCheckpoint(calldataCheckpoint) {
444
+ if (this.getOptions().skipPromoteProposedCheckpointDuringL1Sync || !calldataCheckpoint) {
445
+ return {
446
+ kind: 'none'
447
+ };
448
+ }
449
+ // Look up the specific pending entry for the checkpoint being mined, not just the tip
450
+ const proposed = await this.deps.stores.blocks.getProposedCheckpointByNumber(calldataCheckpoint.checkpointNumber);
451
+ if (!proposed) {
452
+ return {
453
+ kind: 'none'
454
+ };
455
+ }
456
+ if (!proposed.header.equals(calldataCheckpoint.header) || !proposed.archive.root.equals(calldataCheckpoint.archiveRoot) || proposed.feeAssetPriceModifier !== calldataCheckpoint.feeAssetPriceModifier) {
457
+ this.deps.log.warn(`Local proposed checkpoint ${proposed.checkpointNumber} does not match checkpoint retrieved from L1, overriding with L1 data`, {
458
+ proposedCheckpointNumber: proposed.checkpointNumber,
459
+ proposedHeader: proposed.header.toInspect(),
460
+ proposedArchiveRoot: proposed.archive.root.toString(),
461
+ proposedFeeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
462
+ calldataCheckpointNumber: calldataCheckpoint.checkpointNumber,
463
+ calldataHeader: calldataCheckpoint.header.toInspect(),
464
+ calldataArchiveRoot: calldataCheckpoint.archiveRoot.toString(),
465
+ calldataFeeAssetPriceModifier: calldataCheckpoint.feeAssetPriceModifier.toString()
466
+ });
467
+ // Only emit when the slots match — uncheckpointed entries are pruned above so this
468
+ // should always hold, but guard defensively to avoid mis-attributing a slash.
469
+ if (proposed.header.slotNumber === calldataCheckpoint.header.slotNumber) {
470
+ await this.reportEquivocationIfSameSigner(proposed, calldataCheckpoint);
471
+ }
472
+ // Return a divergence signal so the caller can evict pending >= this number
473
+ return {
474
+ kind: 'evict',
475
+ fromCheckpointNumber: proposed.checkpointNumber
476
+ };
477
+ }
478
+ this.deps.log.debug(`Building published checkpoint from proposed ${calldataCheckpoint.checkpointNumber} (skipping blob fetch)`, {
479
+ proposedHeader: proposed.header.toInspect(),
480
+ proposedArchiveRoot: proposed.archive.root.toString()
481
+ });
482
+ const blocks = await this.deps.stores.blocks.getBlocks({
483
+ from: BlockNumber(proposed.startBlock),
484
+ limit: proposed.blockCount
485
+ });
486
+ if (blocks.length !== proposed.blockCount) {
487
+ this.deps.log.warn(`Local proposed checkpoint ${proposed.checkpointNumber} has wrong block count (expected ${proposed.blockCount} blocks starting at ${proposed.startBlock} but got ${blocks.length})`, {
488
+ proposedCheckpointNumber: proposed.checkpointNumber,
489
+ proposedStartBlock: proposed.startBlock,
490
+ proposedBlockCount: proposed.blockCount,
491
+ retrievedBlocks: blocks.map((b)=>b.number)
492
+ });
493
+ return {
494
+ kind: 'none'
495
+ };
496
+ }
497
+ const checkpoint = Checkpoint.from({
498
+ archive: proposed.archive,
499
+ header: proposed.header,
500
+ blocks,
501
+ number: proposed.checkpointNumber,
502
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier
503
+ });
504
+ const promotedCheckpoint = PublishedCheckpoint.from({
505
+ checkpoint,
506
+ l1: calldataCheckpoint.l1,
507
+ attestations: calldataCheckpoint.attestations,
508
+ verbatimAttestations: calldataCheckpoint.verbatimAttestations
509
+ });
510
+ this.deps.instrumentation.processCheckpointPromoted();
511
+ return {
512
+ kind: 'promote',
513
+ checkpoint: promotedCheckpoint
514
+ };
515
+ }
516
+ }