@aztec/archiver 0.0.1-commit.b6e433891 → 0.0.1-commit.b8a057fa
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.
- package/README.md +19 -11
- package/dest/archiver.d.ts +71 -15
- package/dest/archiver.d.ts.map +1 -1
- package/dest/archiver.js +295 -78
- package/dest/config.d.ts +7 -3
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +39 -16
- package/dest/errors.d.ts +44 -10
- package/dest/errors.d.ts.map +1 -1
- package/dest/errors.js +66 -12
- package/dest/factory.d.ts +12 -7
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +40 -25
- package/dest/index.d.ts +11 -3
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +10 -2
- package/dest/l1/calldata_retriever.d.ts +9 -1
- package/dest/l1/calldata_retriever.d.ts.map +1 -1
- package/dest/l1/calldata_retriever.js +22 -11
- package/dest/l1/data_retrieval.d.ts +25 -11
- package/dest/l1/data_retrieval.d.ts.map +1 -1
- package/dest/l1/data_retrieval.js +25 -32
- package/dest/l1/trace_tx.d.ts +12 -66
- package/dest/l1/trace_tx.d.ts.map +1 -1
- package/dest/l1/validate_historical_logs.d.ts +23 -0
- package/dest/l1/validate_historical_logs.d.ts.map +1 -0
- package/dest/l1/validate_historical_logs.js +108 -0
- package/dest/modules/contract_data_source_adapter.d.ts +25 -0
- package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
- package/dest/modules/contract_data_source_adapter.js +32 -0
- package/dest/modules/data_source_base.d.ts +71 -48
- package/dest/modules/data_source_base.d.ts.map +1 -1
- package/dest/modules/data_source_base.js +250 -144
- package/dest/modules/data_store_updater.d.ts +30 -13
- package/dest/modules/data_store_updater.d.ts.map +1 -1
- package/dest/modules/data_store_updater.js +169 -118
- package/dest/modules/instrumentation.d.ts +15 -2
- package/dest/modules/instrumentation.d.ts.map +1 -1
- package/dest/modules/instrumentation.js +48 -9
- package/dest/modules/l1_synchronizer.d.ts +13 -8
- package/dest/modules/l1_synchronizer.d.ts.map +1 -1
- package/dest/modules/l1_synchronizer.js +453 -219
- package/dest/modules/outbox_trees_resolver.d.ts +62 -0
- package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
- package/dest/modules/outbox_trees_resolver.js +162 -0
- package/dest/modules/validation.d.ts +30 -7
- package/dest/modules/validation.d.ts.map +1 -1
- package/dest/modules/validation.js +35 -17
- package/dest/store/block_store.d.ts +176 -68
- package/dest/store/block_store.d.ts.map +1 -1
- package/dest/store/block_store.js +669 -236
- package/dest/store/contract_class_store.d.ts +17 -4
- package/dest/store/contract_class_store.d.ts.map +1 -1
- package/dest/store/contract_class_store.js +42 -68
- package/dest/store/contract_instance_store.d.ts +28 -1
- package/dest/store/contract_instance_store.d.ts.map +1 -1
- package/dest/store/contract_instance_store.js +54 -2
- package/dest/store/data_stores.d.ts +68 -0
- package/dest/store/data_stores.d.ts.map +1 -0
- package/dest/store/data_stores.js +54 -0
- package/dest/store/function_names_cache.d.ts +17 -0
- package/dest/store/function_names_cache.d.ts.map +1 -0
- package/dest/store/function_names_cache.js +30 -0
- package/dest/store/l2_tips_cache.d.ts +13 -7
- package/dest/store/l2_tips_cache.d.ts.map +1 -1
- package/dest/store/l2_tips_cache.js +13 -76
- package/dest/store/log_store.d.ts +42 -40
- package/dest/store/log_store.d.ts.map +1 -1
- package/dest/store/log_store.js +257 -480
- package/dest/store/log_store_codec.d.ts +78 -0
- package/dest/store/log_store_codec.d.ts.map +1 -0
- package/dest/store/log_store_codec.js +110 -0
- package/dest/store/message_store.d.ts +9 -3
- package/dest/store/message_store.d.ts.map +1 -1
- package/dest/store/message_store.js +39 -10
- package/dest/test/fake_l1_state.d.ts +15 -3
- package/dest/test/fake_l1_state.d.ts.map +1 -1
- package/dest/test/fake_l1_state.js +83 -21
- package/dest/test/mock_l2_block_source.d.ts +48 -50
- package/dest/test/mock_l2_block_source.d.ts.map +1 -1
- package/dest/test/mock_l2_block_source.js +228 -179
- package/dest/test/mock_structs.d.ts +1 -1
- package/dest/test/mock_structs.d.ts.map +1 -1
- package/dest/test/mock_structs.js +2 -2
- package/dest/test/noop_l1_archiver.d.ts +14 -6
- package/dest/test/noop_l1_archiver.d.ts.map +1 -1
- package/dest/test/noop_l1_archiver.js +26 -10
- package/package.json +14 -14
- package/src/archiver.ts +383 -84
- package/src/config.ts +43 -20
- package/src/errors.ts +103 -18
- package/src/factory.ts +56 -24
- package/src/index.ts +18 -2
- package/src/l1/calldata_retriever.ts +29 -11
- package/src/l1/data_retrieval.ts +44 -46
- package/src/l1/validate_historical_logs.ts +140 -0
- package/src/modules/contract_data_source_adapter.ts +46 -0
- package/src/modules/data_source_base.ts +325 -192
- package/src/modules/data_store_updater.ts +204 -149
- package/src/modules/instrumentation.ts +43 -10
- package/src/modules/l1_synchronizer.ts +612 -259
- package/src/modules/outbox_trees_resolver.ts +199 -0
- package/src/modules/validation.ts +80 -23
- package/src/store/block_store.ts +822 -289
- package/src/store/contract_class_store.ts +49 -103
- package/src/store/contract_instance_store.ts +68 -5
- package/src/store/data_stores.ts +104 -0
- package/src/store/function_names_cache.ts +37 -0
- package/src/store/l2_tips_cache.ts +16 -70
- package/src/store/log_store.ts +296 -652
- package/src/store/log_store_codec.ts +143 -0
- package/src/store/message_store.ts +43 -12
- package/src/structs/inbox_message.ts +1 -1
- package/src/test/fake_l1_state.ts +102 -30
- package/src/test/mock_l2_block_source.ts +285 -232
- package/src/test/mock_structs.ts +5 -2
- package/src/test/noop_l1_archiver.ts +54 -11
- package/dest/store/kv_archiver_store.d.ts +0 -367
- package/dest/store/kv_archiver_store.d.ts.map +0 -1
- package/dest/store/kv_archiver_store.js +0 -481
- package/src/store/kv_archiver_store.ts +0 -697
|
@@ -1,37 +1,56 @@
|
|
|
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
|
+
import { getFinalizedL1Block } from '@aztec/ethereum/queries';
|
|
5
6
|
import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
|
|
6
7
|
import { asyncPool } from '@aztec/foundation/async-pool';
|
|
7
8
|
import { maxBigint } from '@aztec/foundation/bigint';
|
|
8
9
|
import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
|
|
9
|
-
import { Buffer32 } from '@aztec/foundation/buffer';
|
|
10
|
-
import { pick } from '@aztec/foundation/collection';
|
|
10
|
+
import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
|
|
11
|
+
import { compactArray, partition, pick } from '@aztec/foundation/collection';
|
|
11
12
|
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
13
|
+
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
12
14
|
import { type Logger, createLogger } from '@aztec/foundation/log';
|
|
15
|
+
import { retryTimes } from '@aztec/foundation/retry';
|
|
13
16
|
import { count } from '@aztec/foundation/string';
|
|
14
17
|
import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
|
|
15
|
-
import { isDefined } from '@aztec/foundation/types';
|
|
16
|
-
import {
|
|
17
|
-
|
|
18
|
+
import { isDefined, isErrorClass } from '@aztec/foundation/types';
|
|
19
|
+
import {
|
|
20
|
+
type ArchiverEmitter,
|
|
21
|
+
type L2Block,
|
|
22
|
+
L2BlockSourceEvents,
|
|
23
|
+
type ValidateCheckpointResult,
|
|
24
|
+
} from '@aztec/stdlib/block';
|
|
25
|
+
import {
|
|
26
|
+
Checkpoint,
|
|
27
|
+
type CheckpointData,
|
|
28
|
+
type CheckpointInfo,
|
|
29
|
+
type L1PublishedData,
|
|
30
|
+
PublishedCheckpoint,
|
|
31
|
+
} from '@aztec/stdlib/checkpoint';
|
|
18
32
|
import { type L1RollupConstants, getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
|
|
19
33
|
import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
|
|
34
|
+
import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
|
|
20
35
|
import { type Traceable, type Tracer, execInSpan, trackSpan } from '@aztec/telemetry-client';
|
|
21
36
|
|
|
22
37
|
import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
|
|
23
38
|
import {
|
|
24
|
-
|
|
39
|
+
type RetrievedCheckpointFromCalldata,
|
|
40
|
+
getCheckpointBlobDataFromBlobs,
|
|
41
|
+
retrieveCheckpointCalldataFromRollup,
|
|
25
42
|
retrieveL1ToL2Message,
|
|
26
43
|
retrieveL1ToL2Messages,
|
|
27
44
|
retrievedToPublishedCheckpoint,
|
|
28
45
|
} from '../l1/data_retrieval.js';
|
|
29
|
-
import type {
|
|
46
|
+
import type { RejectedCheckpoint } from '../store/block_store.js';
|
|
47
|
+
import { type ArchiverDataStores, getArchiverSynchPoint } from '../store/data_stores.js';
|
|
30
48
|
import type { L2TipsCache } from '../store/l2_tips_cache.js';
|
|
49
|
+
import { MessageStoreError } from '../store/message_store.js';
|
|
31
50
|
import type { InboxMessage } from '../structs/inbox_message.js';
|
|
32
51
|
import { ArchiverDataStoreUpdater } from './data_store_updater.js';
|
|
33
52
|
import type { ArchiverInstrumentation } from './instrumentation.js';
|
|
34
|
-
import {
|
|
53
|
+
import { validateCheckpointAttestationsFromCalldata } from './validation.js';
|
|
35
54
|
|
|
36
55
|
type RollupStatus = {
|
|
37
56
|
provenCheckpointNumber: CheckpointNumber;
|
|
@@ -39,13 +58,17 @@ type RollupStatus = {
|
|
|
39
58
|
pendingCheckpointNumber: CheckpointNumber;
|
|
40
59
|
pendingArchive: string;
|
|
41
60
|
validationResult: ValidateCheckpointResult | undefined;
|
|
61
|
+
/** Last valid checkpoint observed on L1 and synced on this iteration */
|
|
42
62
|
lastRetrievedCheckpoint?: PublishedCheckpoint;
|
|
43
|
-
|
|
63
|
+
/** Last checkpoint observed on L1 across both valid and rejected entries on this iteration */
|
|
64
|
+
lastSeenCheckpoint?: { checkpointNumber: CheckpointNumber; l1: L1PublishedData };
|
|
65
|
+
/** Blocks added while handling checkpoints this iteration, for the aggregate block source update event. */
|
|
66
|
+
blocksAdded: L2Block[];
|
|
44
67
|
};
|
|
45
68
|
|
|
46
69
|
/**
|
|
47
70
|
* Handles L1 synchronization for the archiver.
|
|
48
|
-
* Responsible for fetching checkpoints, L1
|
|
71
|
+
* Responsible for fetching checkpoints, L1 to L2 messages, and handling L1 reorgs.
|
|
49
72
|
*/
|
|
50
73
|
export class ArchiverL1Synchronizer implements Traceable {
|
|
51
74
|
private l1BlockNumber: bigint | undefined;
|
|
@@ -60,10 +83,11 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
60
83
|
private readonly debugClient: ViemPublicDebugClient,
|
|
61
84
|
private readonly rollup: RollupContract,
|
|
62
85
|
private readonly inbox: InboxContract,
|
|
63
|
-
private readonly
|
|
86
|
+
private readonly stores: ArchiverDataStores,
|
|
64
87
|
private config: {
|
|
65
88
|
batchSize: number;
|
|
66
89
|
skipValidateCheckpointAttestations?: boolean;
|
|
90
|
+
skipPromoteProposedCheckpointDuringL1Sync?: boolean;
|
|
67
91
|
maxAllowedEthClientDriftSeconds: number;
|
|
68
92
|
},
|
|
69
93
|
private readonly blobClient: BlobClientInterface,
|
|
@@ -79,7 +103,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
79
103
|
l2TipsCache?: L2TipsCache,
|
|
80
104
|
private readonly log: Logger = createLogger('archiver:l1-sync'),
|
|
81
105
|
) {
|
|
82
|
-
this.updater = new ArchiverDataStoreUpdater(this.
|
|
106
|
+
this.updater = new ArchiverDataStoreUpdater(this.stores, l2TipsCache, {
|
|
83
107
|
rollupManaLimit: l1Constants.rollupManaLimit,
|
|
84
108
|
});
|
|
85
109
|
this.tracer = tracer;
|
|
@@ -89,6 +113,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
89
113
|
public setConfig(newConfig: {
|
|
90
114
|
batchSize: number;
|
|
91
115
|
skipValidateCheckpointAttestations?: boolean;
|
|
116
|
+
skipPromoteProposedCheckpointDuringL1Sync?: boolean;
|
|
92
117
|
maxAllowedEthClientDriftSeconds: number;
|
|
93
118
|
}) {
|
|
94
119
|
this.config = newConfig;
|
|
@@ -104,6 +129,13 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
104
129
|
return this.l1Timestamp;
|
|
105
130
|
}
|
|
106
131
|
|
|
132
|
+
private getSignatureContext(): CoordinationSignatureContext {
|
|
133
|
+
return {
|
|
134
|
+
chainId: this.publicClient.chain.id,
|
|
135
|
+
rollupAddress: EthAddress.fromString(this.rollup.address),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
107
139
|
/** Checks that the ethereum node we are connected to has a latest timestamp no more than the allowed drift. Throw if not. */
|
|
108
140
|
public async testEthereumNodeSynced(): Promise<void> {
|
|
109
141
|
const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
|
|
@@ -120,70 +152,60 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
120
152
|
}
|
|
121
153
|
|
|
122
154
|
@trackSpan('Archiver.syncFromL1')
|
|
123
|
-
public async syncFromL1(initialSyncComplete: boolean): Promise<
|
|
155
|
+
public async syncFromL1(initialSyncComplete: boolean): Promise<L2Block[]> {
|
|
156
|
+
const blocksAdded: L2Block[] = [];
|
|
157
|
+
|
|
158
|
+
// In between the various calls to L1, the block number can move meaning some of the following
|
|
159
|
+
// calls will return data for blocks that were not present during earlier calls. To combat this
|
|
160
|
+
// we ensure that all data retrieval methods only retrieve data up to the currentBlockNumber
|
|
161
|
+
// captured at the top of this function.
|
|
124
162
|
const currentL1Block = await this.publicClient.getBlock({ includeTransactions: false });
|
|
125
163
|
const currentL1BlockNumber = currentL1Block.number;
|
|
126
164
|
const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
|
|
127
165
|
const currentL1Timestamp = currentL1Block.timestamp;
|
|
166
|
+
const currentL1BlockData = { l1BlockNumber: currentL1BlockNumber, l1BlockHash: currentL1BlockHash };
|
|
128
167
|
|
|
129
168
|
if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
|
|
130
169
|
this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
|
|
131
|
-
return;
|
|
170
|
+
return blocksAdded;
|
|
132
171
|
}
|
|
133
172
|
|
|
134
|
-
//
|
|
173
|
+
// Log at error if the latest L1 block timestamp is too old
|
|
135
174
|
const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
|
|
136
175
|
const now = this.dateProvider.nowInSeconds();
|
|
137
176
|
if (maxAllowedDelay > 0 && Number(currentL1Timestamp) <= now - maxAllowedDelay) {
|
|
138
|
-
this.log.
|
|
177
|
+
this.log.error(
|
|
139
178
|
`Latest L1 block ${currentL1BlockNumber} timestamp ${currentL1Timestamp} is too old. Make sure your Ethereum node is synced.`,
|
|
140
179
|
{ currentL1BlockNumber, currentL1Timestamp, now, maxAllowedDelay },
|
|
141
180
|
);
|
|
142
181
|
}
|
|
143
182
|
|
|
144
|
-
//
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
},
|
|
151
|
-
} = await this.store.getSynchPoint();
|
|
183
|
+
// Query finalized block on L1
|
|
184
|
+
const rawFinalizedL1Block = await getFinalizedL1Block(this.publicClient);
|
|
185
|
+
const finalizedL1Block: L1BlockId | undefined = rawFinalizedL1Block && {
|
|
186
|
+
l1BlockNumber: rawFinalizedL1Block.number,
|
|
187
|
+
l1BlockHash: Buffer32.fromString(rawFinalizedL1Block.hash),
|
|
188
|
+
};
|
|
152
189
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
190
|
+
// Load sync point for blocks defaulting to start block
|
|
191
|
+
const { blocksSynchedTo = this.l1Constants.l1StartBlock } = await getArchiverSynchPoint(this.stores);
|
|
192
|
+
this.log.debug(`Starting new archiver sync iteration`, { blocksSynchedTo, currentL1BlockData, finalizedL1Block });
|
|
193
|
+
|
|
194
|
+
// 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.
|
|
195
|
+
// 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
|
|
196
|
+
// block, when that wouldn't be the case, since L1 to L2 messages would need another iteration.
|
|
197
|
+
await retryTimes(
|
|
198
|
+
() => this.handleL1ToL2Messages(currentL1BlockData, finalizedL1Block),
|
|
199
|
+
'Handling L1 to L2 messages',
|
|
200
|
+
3,
|
|
201
|
+
0.1,
|
|
202
|
+
);
|
|
159
203
|
|
|
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
204
|
if (currentL1BlockNumber > blocksSynchedTo) {
|
|
184
205
|
// First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
|
|
185
206
|
// pending chain validation status, proven checkpoint number, and synched L1 block number.
|
|
186
207
|
const rollupStatus = await this.handleCheckpoints(blocksSynchedTo, currentL1BlockNumber, initialSyncComplete);
|
|
208
|
+
blocksAdded.push(...rollupStatus.blocksAdded);
|
|
187
209
|
|
|
188
210
|
// Then we try pruning uncheckpointed blocks if a new slot was mined without checkpoints
|
|
189
211
|
await this.pruneUncheckpointedBlocks(currentL1Timestamp);
|
|
@@ -199,18 +221,10 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
199
221
|
currentL1Timestamp,
|
|
200
222
|
);
|
|
201
223
|
|
|
202
|
-
// If the last checkpoint we processed had an invalid attestation, we manually advance the L1 syncpoint
|
|
203
|
-
// past it, since otherwise we'll keep downloading it and reprocessing it on every iteration until
|
|
204
|
-
// we get a valid checkpoint to advance the syncpoint.
|
|
205
|
-
if (!rollupStatus.validationResult?.valid && rollupStatus.lastL1BlockWithCheckpoint !== undefined) {
|
|
206
|
-
await this.store.setCheckpointSynchedL1BlockNumber(rollupStatus.lastL1BlockWithCheckpoint);
|
|
207
|
-
}
|
|
208
|
-
|
|
209
224
|
// And lastly we check if we are missing any checkpoints behind us due to a possible L1 reorg.
|
|
210
225
|
// We only do this if rollup cant prune on the next submission. Otherwise we will end up
|
|
211
|
-
// re-syncing the checkpoints we have just unwound above.
|
|
212
|
-
|
|
213
|
-
if (!rollupCanPrune && rollupStatus.validationResult?.valid) {
|
|
226
|
+
// re-syncing the checkpoints we have just unwound above.
|
|
227
|
+
if (!rollupCanPrune) {
|
|
214
228
|
await this.checkForNewCheckpointsBeforeL1SyncPoint(rollupStatus, blocksSynchedTo, currentL1BlockNumber);
|
|
215
229
|
}
|
|
216
230
|
|
|
@@ -218,7 +232,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
218
232
|
}
|
|
219
233
|
|
|
220
234
|
// Update the finalized L2 checkpoint based on L1 finality.
|
|
221
|
-
await this.updateFinalizedCheckpoint();
|
|
235
|
+
await this.updateFinalizedCheckpoint(finalizedL1Block);
|
|
222
236
|
|
|
223
237
|
// After syncing has completed, update the current l1 block number and timestamp,
|
|
224
238
|
// otherwise we risk announcing to the world that we've synced to a given point,
|
|
@@ -233,17 +247,22 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
233
247
|
l1TimestampAtStart: currentL1Timestamp,
|
|
234
248
|
l1BlockNumberAtEnd,
|
|
235
249
|
});
|
|
250
|
+
|
|
251
|
+
return blocksAdded;
|
|
236
252
|
}
|
|
237
253
|
|
|
238
|
-
/**
|
|
239
|
-
private async updateFinalizedCheckpoint(): Promise<void> {
|
|
254
|
+
/** Updates the finalized checkpoint using the pre-fetched finalized L1 block from the current sync iteration. */
|
|
255
|
+
private async updateFinalizedCheckpoint(finalizedL1Block: L1BlockId | undefined): Promise<void> {
|
|
240
256
|
try {
|
|
241
|
-
|
|
242
|
-
|
|
257
|
+
if (!finalizedL1Block) {
|
|
258
|
+
this.log.trace(`Skipping finalized checkpoint update: L1 has no finalized block yet.`);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const finalizedL1BlockNumber = finalizedL1Block.l1BlockNumber;
|
|
243
262
|
const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
|
|
244
263
|
blockNumber: finalizedL1BlockNumber,
|
|
245
264
|
});
|
|
246
|
-
const localFinalizedCheckpointNumber = await this.
|
|
265
|
+
const localFinalizedCheckpointNumber = await this.stores.blocks.getFinalizedCheckpointNumber();
|
|
247
266
|
if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
|
|
248
267
|
await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
|
|
249
268
|
this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
|
|
@@ -251,16 +270,19 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
251
270
|
finalizedL1BlockNumber,
|
|
252
271
|
});
|
|
253
272
|
}
|
|
254
|
-
} catch (err) {
|
|
255
|
-
|
|
273
|
+
} catch (err: any) {
|
|
274
|
+
// The rollup contract may not exist at the finalized L1 block right after deployment.
|
|
275
|
+
if (!err?.message?.includes('returned no data')) {
|
|
276
|
+
this.log.warn(`Failed to update finalized checkpoint: ${err}`);
|
|
277
|
+
}
|
|
256
278
|
}
|
|
257
279
|
}
|
|
258
280
|
|
|
259
281
|
/** Prune all proposed local blocks that should have been checkpointed by now. */
|
|
260
|
-
private async pruneUncheckpointedBlocks(currentL1Timestamp: bigint) {
|
|
282
|
+
private async pruneUncheckpointedBlocks(currentL1Timestamp: bigint): Promise<void> {
|
|
261
283
|
const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
|
|
262
|
-
this.
|
|
263
|
-
this.
|
|
284
|
+
this.stores.blocks.getCheckpointedL2BlockNumber(),
|
|
285
|
+
this.stores.blocks.getLatestL2BlockNumber(),
|
|
264
286
|
]);
|
|
265
287
|
|
|
266
288
|
// If there are no uncheckpointed blocks, we got nothing to do
|
|
@@ -269,29 +291,35 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
269
291
|
return;
|
|
270
292
|
}
|
|
271
293
|
|
|
272
|
-
// What's the slot of the first uncheckpointed block?
|
|
273
|
-
const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
|
|
274
|
-
const [firstUncheckpointedBlockHeader] = await this.store.getBlockHeaders(firstUncheckpointedBlockNumber, 1);
|
|
275
|
-
const firstUncheckpointedBlockSlot = firstUncheckpointedBlockHeader?.getSlot();
|
|
276
|
-
|
|
277
294
|
// What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
|
|
278
295
|
const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
|
|
296
|
+
const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
|
|
279
297
|
|
|
280
|
-
//
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
);
|
|
286
|
-
const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
|
|
298
|
+
// What's the slot of the first uncheckpointed block?
|
|
299
|
+
const firstUncheckpointedBlockData = await this.stores.blocks.getBlockData({
|
|
300
|
+
number: firstUncheckpointedBlockNumber,
|
|
301
|
+
});
|
|
302
|
+
const firstUncheckpointedBlockSlot = firstUncheckpointedBlockData?.header.getSlot();
|
|
287
303
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
304
|
+
if (firstUncheckpointedBlockSlot === undefined || firstUncheckpointedBlockSlot >= slotAtNextL1Block) {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Prune provisional blocks from slots that have ended without being checkpointed.
|
|
309
|
+
// This also clears any proposed checkpoint whose blocks are being pruned.
|
|
310
|
+
this.log.warn(
|
|
311
|
+
`Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`,
|
|
312
|
+
{ firstUncheckpointedBlockHeader: firstUncheckpointedBlockData?.header.toInspect(), slotAtNextL1Block },
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
|
|
316
|
+
if (prunedBlocks.length > 0) {
|
|
317
|
+
this.instrumentation.recordPrune('uncheckpointed');
|
|
318
|
+
this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
|
|
319
|
+
type: L2BlockSourceEvents.L2PruneUncheckpointed,
|
|
320
|
+
slotNumber: firstUncheckpointedBlockSlot,
|
|
321
|
+
blocks: prunedBlocks,
|
|
322
|
+
});
|
|
295
323
|
}
|
|
296
324
|
}
|
|
297
325
|
|
|
@@ -317,7 +345,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
317
345
|
currentL1Timestamp: bigint,
|
|
318
346
|
): Promise<{ rollupCanPrune: boolean }> {
|
|
319
347
|
const rollupCanPrune = await this.canPrune(currentL1BlockNumber, currentL1Timestamp);
|
|
320
|
-
const localPendingCheckpointNumber = await this.
|
|
348
|
+
const localPendingCheckpointNumber = await this.stores.blocks.getLatestCheckpointNumber();
|
|
321
349
|
const canPrune = localPendingCheckpointNumber > provenCheckpointNumber && rollupCanPrune;
|
|
322
350
|
|
|
323
351
|
if (canPrune) {
|
|
@@ -338,12 +366,12 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
338
366
|
// promises when the gap between local pending and proven checkpoint numbers is large.
|
|
339
367
|
const BATCH_SIZE = 10;
|
|
340
368
|
const indices = Array.from({ length: checkpointsToUnwind }, (_, i) => CheckpointNumber(i + pruneFrom));
|
|
341
|
-
const checkpoints = (
|
|
342
|
-
|
|
343
|
-
);
|
|
369
|
+
const checkpoints = (
|
|
370
|
+
await asyncPool(BATCH_SIZE, indices, idx => this.stores.blocks.getCheckpointData(idx))
|
|
371
|
+
).filter(isDefined);
|
|
344
372
|
const newBlocks = (
|
|
345
373
|
await asyncPool(BATCH_SIZE, checkpoints, cp =>
|
|
346
|
-
this.
|
|
374
|
+
this.stores.blocks.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber)),
|
|
347
375
|
)
|
|
348
376
|
)
|
|
349
377
|
.filter(isDefined)
|
|
@@ -363,12 +391,12 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
363
391
|
this.log.warn(
|
|
364
392
|
`Removed ${count(checkpointsToUnwind, 'checkpoint')} after checkpoint ${provenCheckpointNumber} ` +
|
|
365
393
|
`due to predicted reorg at L1 block ${currentL1BlockNumber}. ` +
|
|
366
|
-
`Updated latest checkpoint is ${await this.
|
|
394
|
+
`Updated latest checkpoint is ${await this.stores.blocks.getLatestCheckpointNumber()}.`,
|
|
367
395
|
);
|
|
368
396
|
this.instrumentation.processPrune(timer.ms());
|
|
369
397
|
// TODO(palla/reorg): Do we need to set the block synched L1 block number here?
|
|
370
398
|
// Seems like the next iteration should handle this.
|
|
371
|
-
// await this.
|
|
399
|
+
// await this.stores.blocks.setSynchedL1BlockNumber(currentL1BlockNumber);
|
|
372
400
|
}
|
|
373
401
|
|
|
374
402
|
return { rollupCanPrune };
|
|
@@ -385,68 +413,102 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
385
413
|
}
|
|
386
414
|
|
|
387
415
|
@trackSpan('Archiver.handleL1ToL2Messages')
|
|
388
|
-
private async handleL1ToL2Messages(
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
416
|
+
private async handleL1ToL2Messages(
|
|
417
|
+
currentL1Block: L1BlockId,
|
|
418
|
+
finalizedL1Block: L1BlockId | undefined,
|
|
419
|
+
): Promise<boolean> {
|
|
420
|
+
// Load the syncpoint, which may have been updated in a previous iteration
|
|
421
|
+
const {
|
|
422
|
+
messagesSynchedTo = {
|
|
423
|
+
l1BlockNumber: this.l1Constants.l1StartBlock,
|
|
424
|
+
l1BlockHash: this.l1Constants.l1StartBlockHash,
|
|
425
|
+
},
|
|
426
|
+
} = await getArchiverSynchPoint(this.stores);
|
|
427
|
+
|
|
428
|
+
// Nothing to do if L1 block number has not moved forward
|
|
429
|
+
const currentL1BlockNumber = currentL1Block.l1BlockNumber;
|
|
430
|
+
if (currentL1BlockNumber <= messagesSynchedTo.l1BlockNumber) {
|
|
431
|
+
return true;
|
|
392
432
|
}
|
|
393
433
|
|
|
394
|
-
//
|
|
395
|
-
const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
|
|
396
|
-
const localLastMessage = await this.store.getLastL1ToL2Message();
|
|
434
|
+
// Compare local message store state with the remote. If they match, we just advance the match pointer.
|
|
397
435
|
const remoteMessagesState = await this.inbox.getState({ blockNumber: currentL1BlockNumber });
|
|
398
|
-
await this.
|
|
436
|
+
const localLastMessage = await this.stores.messages.getLastMessage();
|
|
437
|
+
if (await this.localStateMatches(localLastMessage, remoteMessagesState)) {
|
|
438
|
+
this.log.trace(`Local L1 to L2 messages are already in sync with remote at L1 block ${currentL1BlockNumber}`);
|
|
439
|
+
await this.stores.messages.setMessageSyncState(
|
|
440
|
+
currentL1Block,
|
|
441
|
+
remoteMessagesState.treeInProgress,
|
|
442
|
+
finalizedL1Block,
|
|
443
|
+
);
|
|
444
|
+
return true;
|
|
445
|
+
}
|
|
399
446
|
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
447
|
+
// If not, then we are out of sync. Most likely there are new messages on the inbox, so we try retrieving them.
|
|
448
|
+
// However, it could also be the case that there was an L1 reorg and our syncpoint is no longer valid.
|
|
449
|
+
// If that's the case, we'd get an exception out of the message store since the rolling hash of the first message
|
|
450
|
+
// we try to insert would not match the one in the db, in which case we rollback to the last common message with L1.
|
|
451
|
+
try {
|
|
452
|
+
await this.retrieveAndStoreMessages(messagesSynchedTo.l1BlockNumber, currentL1BlockNumber);
|
|
453
|
+
} catch (error) {
|
|
454
|
+
if (isErrorClass(error, MessageStoreError)) {
|
|
455
|
+
this.log.warn(
|
|
456
|
+
`Failed to store L1 to L2 messages retrieved from L1: ${error.message}. Rolling back syncpoint to retry.`,
|
|
457
|
+
{ inboxMessage: error.inboxMessage },
|
|
458
|
+
);
|
|
459
|
+
await this.rollbackL1ToL2Messages(remoteMessagesState);
|
|
460
|
+
return false;
|
|
461
|
+
}
|
|
462
|
+
throw error;
|
|
463
|
+
}
|
|
405
464
|
|
|
406
|
-
//
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
) {
|
|
411
|
-
this.log.
|
|
412
|
-
`
|
|
465
|
+
// Note that, if there are no new messages to insert, but there was an L1 reorg that pruned out last messages,
|
|
466
|
+
// we'd notice by comparing our local state with the remote one again, and seeing they don't match even after
|
|
467
|
+
// our sync attempt. In this case, we also rollback our syncpoint, and trigger a retry.
|
|
468
|
+
const localLastMessageAfterSync = await this.stores.messages.getLastMessage();
|
|
469
|
+
if (!(await this.localStateMatches(localLastMessageAfterSync, remoteMessagesState))) {
|
|
470
|
+
this.log.warn(
|
|
471
|
+
`Local L1 to L2 messages state does not match remote after sync attempt. Rolling back syncpoint to retry.`,
|
|
472
|
+
{ localLastMessageAfterSync, remoteMessagesState },
|
|
413
473
|
);
|
|
414
|
-
|
|
474
|
+
await this.rollbackL1ToL2Messages(remoteMessagesState);
|
|
475
|
+
return false;
|
|
415
476
|
}
|
|
416
477
|
|
|
417
|
-
//
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
remoteLastMessage,
|
|
426
|
-
messagesSyncPoint,
|
|
427
|
-
localLastMessage,
|
|
428
|
-
});
|
|
478
|
+
// Advance the syncpoint after a successful sync
|
|
479
|
+
await this.stores.messages.setMessageSyncState(
|
|
480
|
+
currentL1Block,
|
|
481
|
+
remoteMessagesState.treeInProgress,
|
|
482
|
+
finalizedL1Block,
|
|
483
|
+
);
|
|
484
|
+
return true;
|
|
485
|
+
}
|
|
429
486
|
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
487
|
+
/** Checks if the local rolling hash and message count matches the remote state */
|
|
488
|
+
private async localStateMatches(localLastMessage: InboxMessage | undefined, remoteState: InboxContractState) {
|
|
489
|
+
const localMessageCount = await this.stores.messages.getTotalL1ToL2MessageCount();
|
|
490
|
+
this.log.trace(`Comparing local and remote inbox state`, { localMessageCount, localLastMessage, remoteState });
|
|
491
|
+
|
|
492
|
+
return (
|
|
493
|
+
remoteState.totalMessagesInserted === localMessageCount &&
|
|
494
|
+
remoteState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO)
|
|
495
|
+
);
|
|
496
|
+
}
|
|
436
497
|
|
|
437
|
-
|
|
498
|
+
/** Retrieves L1 to L2 messages from L1 in batches and stores them. */
|
|
499
|
+
private async retrieveAndStoreMessages(fromL1Block: bigint, toL1Block: bigint): Promise<void> {
|
|
438
500
|
let searchStartBlock: bigint = 0n;
|
|
439
|
-
let searchEndBlock: bigint =
|
|
501
|
+
let searchEndBlock: bigint = fromL1Block;
|
|
440
502
|
|
|
441
503
|
let lastMessage: InboxMessage | undefined;
|
|
442
504
|
let messageCount = 0;
|
|
443
505
|
|
|
444
506
|
do {
|
|
445
|
-
[searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock,
|
|
507
|
+
[searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
|
|
446
508
|
this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
|
|
447
509
|
const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
|
|
448
510
|
const timer = new Timer();
|
|
449
|
-
await this.
|
|
511
|
+
await this.stores.messages.addL1ToL2Messages(messages);
|
|
450
512
|
const perMsg = timer.ms() / messages.length;
|
|
451
513
|
this.instrumentation.processNewMessages(messages.length, perMsg);
|
|
452
514
|
for (const msg of messages) {
|
|
@@ -454,81 +516,108 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
454
516
|
lastMessage = msg;
|
|
455
517
|
messageCount++;
|
|
456
518
|
}
|
|
457
|
-
} while (searchEndBlock <
|
|
519
|
+
} while (searchEndBlock < toL1Block);
|
|
458
520
|
|
|
459
|
-
// Log stats for messages retrieved (if any).
|
|
460
521
|
if (messageCount > 0) {
|
|
461
522
|
this.log.info(
|
|
462
523
|
`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`,
|
|
463
524
|
{ lastMessage, messageCount },
|
|
464
525
|
);
|
|
465
526
|
}
|
|
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
527
|
}
|
|
475
528
|
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
[searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
|
|
529
|
+
/**
|
|
530
|
+
* 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.
|
|
531
|
+
* If no common message is found, rolls back all messages and sets the syncpoint to the start block.
|
|
532
|
+
*/
|
|
533
|
+
private async rollbackL1ToL2Messages(remoteMessagesState: InboxContractState): Promise<L1BlockId> {
|
|
534
|
+
const { treeInProgress: remoteTreeInProgress, messagesRollingHash: remoteRollingHash } = remoteMessagesState;
|
|
483
535
|
|
|
484
|
-
|
|
536
|
+
const messagesFinalizedL1Block = await this.stores.messages.getMessagesFinalizedL1Block();
|
|
537
|
+
const finalizedL1BlockNumber = messagesFinalizedL1Block?.l1BlockNumber;
|
|
485
538
|
|
|
486
|
-
|
|
487
|
-
|
|
539
|
+
// Slowly go back through our messages until we find the last common message. We could query the logs in
|
|
540
|
+
// batch as an optimization, but the depth of the reorg should not be deep, and this is a very rare case,
|
|
541
|
+
// so it's fine to query one log at a time.
|
|
542
|
+
let commonMsg: undefined | InboxMessage;
|
|
543
|
+
let messagesToDelete = 0;
|
|
544
|
+
this.log.verbose(`Searching most recent common L1 to L2 message`);
|
|
545
|
+
for await (const localMsg of this.stores.messages.iterateL1ToL2Messages({ reverse: true })) {
|
|
546
|
+
const logCtx = { remoteMsg: undefined as InboxMessage | undefined, localMsg, remoteMessagesState };
|
|
547
|
+
|
|
548
|
+
// First check if the local message rolling hash matches the current rolling hash of the inbox contract,
|
|
549
|
+
// which means we just need to rollback some local messages and we should be back in sync. This means there
|
|
550
|
+
// was an L1 reorg that removed some of the messages we had, but no new messages were added compared.
|
|
551
|
+
if (localMsg.rollingHash.equals(remoteRollingHash)) {
|
|
552
|
+
this.log.info(
|
|
553
|
+
`Found common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber} matching current remote state`,
|
|
554
|
+
logCtx,
|
|
555
|
+
);
|
|
556
|
+
commonMsg = localMsg;
|
|
557
|
+
break;
|
|
488
558
|
}
|
|
489
|
-
} while (searchEndBlock < currentL1BlockNumber);
|
|
490
559
|
|
|
491
|
-
|
|
492
|
-
|
|
560
|
+
// Messages at or below the finalized L1 block cannot have been reorged — accept as common without querying L1.
|
|
561
|
+
if (finalizedL1BlockNumber !== undefined && localMsg.l1BlockNumber <= finalizedL1BlockNumber) {
|
|
562
|
+
this.log.info(`Found common L1 to L2 message at finalized L1 block ${localMsg.l1BlockNumber}`, logCtx);
|
|
563
|
+
commonMsg = localMsg;
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
493
566
|
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
const remoteMsg = await this.retrieveL1ToL2Message(msg.leaf);
|
|
505
|
-
const logCtx = { remoteMsg, localMsg: msg };
|
|
506
|
-
if (remoteMsg && remoteMsg.rollingHash.equals(msg.rollingHash)) {
|
|
507
|
-
this.log.verbose(
|
|
508
|
-
`Found most recent common L1 to L2 message at index ${msg.index} on L1 block ${msg.l1BlockNumber}`,
|
|
567
|
+
// If there's no match with the current remote state, check if the message exists on the inbox contract at all
|
|
568
|
+
// by looking at the inbox events. If the L1 reorg *added* new messages in addition to deleting existing ones,
|
|
569
|
+
// then the current remote state's rolling hash will not match anything we have locally, so we need to check existence
|
|
570
|
+
// of individual messages via logs. Note we use logs and not historical queries so we don't have to depend on
|
|
571
|
+
// an archival rpc node, since the message could be from a long time ago if we're catching up with syncing.
|
|
572
|
+
const remoteMsg = await retrieveL1ToL2Message(this.inbox, localMsg);
|
|
573
|
+
logCtx.remoteMsg = remoteMsg;
|
|
574
|
+
if (remoteMsg && remoteMsg.rollingHash.equals(localMsg.rollingHash)) {
|
|
575
|
+
this.log.info(
|
|
576
|
+
`Found most recent common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber}`,
|
|
509
577
|
logCtx,
|
|
510
578
|
);
|
|
511
579
|
commonMsg = remoteMsg;
|
|
512
580
|
break;
|
|
513
581
|
} else if (remoteMsg) {
|
|
514
|
-
this.log.debug(`Local L1 to L2 message with index ${
|
|
582
|
+
this.log.debug(`Local L1 to L2 message with index ${localMsg.index} has different rolling hash`, logCtx);
|
|
583
|
+
messagesToDelete++;
|
|
515
584
|
} else {
|
|
516
|
-
this.log.debug(`Local L1 to L2 message with index ${
|
|
585
|
+
this.log.debug(`Local L1 to L2 message with index ${localMsg.index} not found on L1`, logCtx);
|
|
586
|
+
messagesToDelete++;
|
|
517
587
|
}
|
|
518
588
|
}
|
|
519
589
|
|
|
520
|
-
// Delete everything after the common message we found.
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
590
|
+
// Delete everything after the common message we found, if anything needs to be deleted.
|
|
591
|
+
// Do not exit early if there are no messages to delete, we still want to update the syncpoint.
|
|
592
|
+
if (messagesToDelete > 0) {
|
|
593
|
+
const lastGoodIndex = commonMsg?.index;
|
|
594
|
+
this.log.warn(`Rolling back all local L1 to L2 messages after index ${lastGoodIndex ?? 'initial'}`);
|
|
595
|
+
await this.stores.messages.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
|
|
596
|
+
}
|
|
524
597
|
|
|
525
598
|
// Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
|
|
526
599
|
// the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
|
|
527
|
-
// after the last common message.
|
|
528
|
-
|
|
529
|
-
const
|
|
530
|
-
|
|
531
|
-
|
|
600
|
+
// after the last common message. Cap at the finalized L1 block: messages at or below finalized cannot
|
|
601
|
+
// have been reorged, so there is no need to walk back any further than that.
|
|
602
|
+
const syncPointL1BlockNumber = maxBigint(
|
|
603
|
+
...compactArray([
|
|
604
|
+
commonMsg ? commonMsg.l1BlockNumber - 1n : undefined,
|
|
605
|
+
finalizedL1BlockNumber,
|
|
606
|
+
this.l1Constants.l1StartBlock,
|
|
607
|
+
]),
|
|
608
|
+
);
|
|
609
|
+
|
|
610
|
+
const syncPointL1BlockHash =
|
|
611
|
+
syncPointL1BlockNumber === finalizedL1BlockNumber
|
|
612
|
+
? messagesFinalizedL1Block!.l1BlockHash
|
|
613
|
+
: await this.getL1BlockHash(syncPointL1BlockNumber);
|
|
614
|
+
|
|
615
|
+
const messagesSyncPoint = { l1BlockNumber: syncPointL1BlockNumber, l1BlockHash: syncPointL1BlockHash };
|
|
616
|
+
await this.stores.messages.setMessageSyncState(messagesSyncPoint, remoteTreeInProgress);
|
|
617
|
+
this.log.verbose(`Updated messages syncpoint to L1 block ${messagesSyncPoint.l1BlockNumber}`, {
|
|
618
|
+
...messagesSyncPoint,
|
|
619
|
+
remoteTreeInProgress,
|
|
620
|
+
});
|
|
532
621
|
return messagesSyncPoint;
|
|
533
622
|
}
|
|
534
623
|
|
|
@@ -546,9 +635,10 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
546
635
|
currentL1BlockNumber: bigint,
|
|
547
636
|
initialSyncComplete: boolean,
|
|
548
637
|
): Promise<RollupStatus> {
|
|
549
|
-
const
|
|
638
|
+
const blocksAdded: L2Block[] = [];
|
|
639
|
+
const localPendingCheckpointNumber = await this.stores.blocks.getLatestCheckpointNumber();
|
|
550
640
|
const initialValidationResult: ValidateCheckpointResult | undefined =
|
|
551
|
-
await this.
|
|
641
|
+
await this.stores.blocks.getPendingChainValidationStatus();
|
|
552
642
|
const {
|
|
553
643
|
provenCheckpointNumber,
|
|
554
644
|
provenArchive,
|
|
@@ -564,6 +654,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
564
654
|
pendingCheckpointNumber,
|
|
565
655
|
pendingArchive: pendingArchive.toString(),
|
|
566
656
|
validationResult: initialValidationResult,
|
|
657
|
+
blocksAdded,
|
|
567
658
|
};
|
|
568
659
|
this.log.trace(`Retrieved rollup status at current L1 block ${currentL1BlockNumber}.`, {
|
|
569
660
|
localPendingCheckpointNumber,
|
|
@@ -578,7 +669,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
578
669
|
// we need to set it to zero. This is an edge case because we dont have a checkpoint zero (initial checkpoint is one),
|
|
579
670
|
// so localCheckpointForDestinationProvenCheckpointNumber would not be found below.
|
|
580
671
|
if (provenCheckpointNumber === 0) {
|
|
581
|
-
const localProvenCheckpointNumber = await this.
|
|
672
|
+
const localProvenCheckpointNumber = await this.stores.blocks.getProvenCheckpointNumber();
|
|
582
673
|
if (localProvenCheckpointNumber !== provenCheckpointNumber) {
|
|
583
674
|
await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
|
|
584
675
|
this.log.info(`Rolled back proven chain to checkpoint ${provenCheckpointNumber}`, { provenCheckpointNumber });
|
|
@@ -586,11 +677,11 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
586
677
|
}
|
|
587
678
|
|
|
588
679
|
const localCheckpointForDestinationProvenCheckpointNumber =
|
|
589
|
-
await this.
|
|
680
|
+
await this.stores.blocks.getCheckpointData(provenCheckpointNumber);
|
|
590
681
|
|
|
591
682
|
// Sanity check. I've hit what seems to be a state where the proven checkpoint is set to a value greater than the latest
|
|
592
683
|
// synched checkpoint when requesting L2Tips from the archiver. This is the only place where the proven checkpoint is set.
|
|
593
|
-
const synched = await this.
|
|
684
|
+
const synched = await this.stores.blocks.getLatestCheckpointNumber();
|
|
594
685
|
if (
|
|
595
686
|
localCheckpointForDestinationProvenCheckpointNumber &&
|
|
596
687
|
synched < localCheckpointForDestinationProvenCheckpointNumber.checkpointNumber
|
|
@@ -610,7 +701,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
610
701
|
localCheckpointForDestinationProvenCheckpointNumber &&
|
|
611
702
|
provenArchive.equals(localCheckpointForDestinationProvenCheckpointNumber.archive.root)
|
|
612
703
|
) {
|
|
613
|
-
const localProvenCheckpointNumber = await this.
|
|
704
|
+
const localProvenCheckpointNumber = await this.stores.blocks.getProvenCheckpointNumber();
|
|
614
705
|
if (localProvenCheckpointNumber !== provenCheckpointNumber) {
|
|
615
706
|
await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
|
|
616
707
|
this.log.info(`Updated proven chain to checkpoint ${provenCheckpointNumber}`, { provenCheckpointNumber });
|
|
@@ -638,7 +729,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
638
729
|
// If we have 0 checkpoints locally and there are no checkpoints onchain there is nothing to do.
|
|
639
730
|
const noCheckpoints = localPendingCheckpointNumber === 0 && pendingCheckpointNumber === 0;
|
|
640
731
|
if (noCheckpoints) {
|
|
641
|
-
await this.
|
|
732
|
+
await this.stores.blocks.setSynchedL1BlockNumber(currentL1BlockNumber);
|
|
642
733
|
this.log.debug(
|
|
643
734
|
`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}, no checkpoints on chain`,
|
|
644
735
|
);
|
|
@@ -650,7 +741,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
650
741
|
// Related to the L2 reorgs of the pending chain. We are only interested in actually addressing a reorg if there
|
|
651
742
|
// are any state that could be impacted by it. If we have no checkpoints, there is no impact.
|
|
652
743
|
if (localPendingCheckpointNumber > 0) {
|
|
653
|
-
const localPendingCheckpoint = await this.
|
|
744
|
+
const localPendingCheckpoint = await this.stores.blocks.getCheckpointData(localPendingCheckpointNumber);
|
|
654
745
|
if (localPendingCheckpoint === undefined) {
|
|
655
746
|
throw new Error(`Missing checkpoint ${localPendingCheckpointNumber}`);
|
|
656
747
|
}
|
|
@@ -665,7 +756,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
665
756
|
// However, in the re-org scenario, our L1 node is temporarily lying to us and we end up potentially missing checkpoints.
|
|
666
757
|
// We must only set this block number based on actually retrieved logs.
|
|
667
758
|
// TODO(#8621): Tackle this properly when we handle L1 Re-orgs.
|
|
668
|
-
// await this.
|
|
759
|
+
// await this.stores.blocks.setSynchedL1BlockNumber(currentL1BlockNumber);
|
|
669
760
|
this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}`);
|
|
670
761
|
return rollupStatus;
|
|
671
762
|
}
|
|
@@ -685,7 +776,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
685
776
|
|
|
686
777
|
let tipAfterUnwind = localPendingCheckpointNumber;
|
|
687
778
|
while (true) {
|
|
688
|
-
const candidateCheckpoint = await this.
|
|
779
|
+
const candidateCheckpoint = await this.stores.blocks.getCheckpointData(tipAfterUnwind);
|
|
689
780
|
if (candidateCheckpoint === undefined) {
|
|
690
781
|
break;
|
|
691
782
|
}
|
|
@@ -706,11 +797,14 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
706
797
|
|
|
707
798
|
const checkpointsToRemove = localPendingCheckpointNumber - tipAfterUnwind;
|
|
708
799
|
await this.updater.removeCheckpointsAfter(CheckpointNumber(tipAfterUnwind));
|
|
800
|
+
if (checkpointsToRemove > 0) {
|
|
801
|
+
this.instrumentation.recordPrune('l1_mismatch');
|
|
802
|
+
}
|
|
709
803
|
|
|
710
804
|
this.log.warn(
|
|
711
805
|
`Removed ${count(checkpointsToRemove, 'checkpoint')} after checkpoint ${tipAfterUnwind} ` +
|
|
712
806
|
`due to mismatched checkpoint hashes at L1 block ${currentL1BlockNumber}. ` +
|
|
713
|
-
`Updated L2 latest checkpoint is ${await this.
|
|
807
|
+
`Updated L2 latest checkpoint is ${await this.stores.blocks.getLatestCheckpointNumber()}.`,
|
|
714
808
|
);
|
|
715
809
|
}
|
|
716
810
|
}
|
|
@@ -720,29 +814,27 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
720
814
|
let searchStartBlock: bigint = blocksSynchedTo;
|
|
721
815
|
let searchEndBlock: bigint = blocksSynchedTo;
|
|
722
816
|
let lastRetrievedCheckpoint: PublishedCheckpoint | undefined;
|
|
723
|
-
let
|
|
817
|
+
let lastSeenCheckpoint: { checkpointNumber: CheckpointNumber; l1: L1PublishedData } | undefined;
|
|
724
818
|
|
|
725
819
|
do {
|
|
726
820
|
[searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
|
|
727
821
|
|
|
728
822
|
this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
|
|
729
823
|
|
|
730
|
-
//
|
|
731
|
-
const
|
|
732
|
-
|
|
824
|
+
// First fetch calldata only, no blobs yet, since we may be able to just get that data out of the proposed chain
|
|
825
|
+
const calldataCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointCalldataFromRollup', () =>
|
|
826
|
+
retrieveCheckpointCalldataFromRollup(
|
|
733
827
|
this.rollup,
|
|
734
828
|
this.publicClient,
|
|
735
829
|
this.debugClient,
|
|
736
|
-
this.blobClient,
|
|
737
830
|
searchStartBlock, // TODO(palla/reorg): If the L2 reorg was due to an L1 reorg, we need to start search earlier
|
|
738
831
|
searchEndBlock,
|
|
739
832
|
this.instrumentation,
|
|
740
833
|
this.log,
|
|
741
|
-
!initialSyncComplete, // isHistoricalSync
|
|
742
834
|
),
|
|
743
835
|
);
|
|
744
836
|
|
|
745
|
-
if (
|
|
837
|
+
if (calldataCheckpoints.length === 0) {
|
|
746
838
|
// We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
|
|
747
839
|
// See further details in earlier comments.
|
|
748
840
|
this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
|
|
@@ -750,40 +842,74 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
750
842
|
}
|
|
751
843
|
|
|
752
844
|
this.log.debug(
|
|
753
|
-
`Retrieved ${
|
|
845
|
+
`Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`,
|
|
754
846
|
{
|
|
755
|
-
lastProcessedCheckpoint:
|
|
847
|
+
lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
|
|
756
848
|
searchStartBlock,
|
|
757
849
|
searchEndBlock,
|
|
758
850
|
},
|
|
759
851
|
);
|
|
760
852
|
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
853
|
+
// Check if the last checkpoint matches a local pending entry (so we can skip blob fetch).
|
|
854
|
+
// We only check the last one; if it matches, the blob fetch is skipped for that entry.
|
|
855
|
+
// TODO(palla/pipelining): We may have more than a single checkpoint to promote
|
|
856
|
+
const lastCalldataCheckpoint = calldataCheckpoints[calldataCheckpoints.length - 1];
|
|
857
|
+
const promoteResult = await this.tryBuildPublishedCheckpointFromProposed(lastCalldataCheckpoint);
|
|
858
|
+
const checkpointToPromote = promoteResult && !('diverged' in promoteResult) ? promoteResult : undefined;
|
|
859
|
+
const evictProposedFrom =
|
|
860
|
+
promoteResult && 'diverged' in promoteResult ? promoteResult.fromCheckpointNumber : undefined;
|
|
861
|
+
|
|
862
|
+
// Validate attestations from CALLDATA before fetching any blobs. A checkpoint with invalid
|
|
863
|
+
// attestations (or one descending from a rejected ancestor) is rejected here without fetching its
|
|
864
|
+
// blobs, so a malformed blob does not throw during decode before the rejection path runs and
|
|
865
|
+
// stall sync. The signed consensus payload (header, archive root, fee asset price
|
|
866
|
+
// modifier) is fully available from calldata.
|
|
867
|
+
const checkpointsToIngest: RetrievedCheckpointFromCalldata[] = [];
|
|
868
|
+
|
|
869
|
+
for (const calldataCheckpoint of calldataCheckpoints) {
|
|
870
|
+
// Check the attestations uploaded by the publisher to L1 are correct.
|
|
871
|
+
// Rollup contract does not validate attestations to save on gas, so this
|
|
872
|
+
// falls on the nodes to verify offchain and skip those checkpoints.
|
|
765
873
|
const validationResult = this.config.skipValidateCheckpointAttestations
|
|
766
874
|
? { valid: true as const }
|
|
767
|
-
: await
|
|
875
|
+
: await validateCheckpointAttestationsFromCalldata(
|
|
876
|
+
calldataCheckpoint,
|
|
877
|
+
this.epochCache,
|
|
878
|
+
this.l1Constants,
|
|
879
|
+
this.getSignatureContext(),
|
|
880
|
+
this.log,
|
|
881
|
+
);
|
|
882
|
+
|
|
883
|
+
// Also skip the checkpoint if it builds on a previously-rejected ancestor. Without
|
|
884
|
+
// this, addCheckpoints would throw InitialCheckpointNumberNotSequentialError when the
|
|
885
|
+
// ancestor was skipped earlier (e.g. due to invalid attestations), the catch handler
|
|
886
|
+
// would roll back the L1 sync point, and the next iteration would re-fetch and re-throw.
|
|
887
|
+
const rejectedAncestor = await this.stores.blocks.getRejectedCheckpointByArchiveRoot(
|
|
888
|
+
calldataCheckpoint.header.lastArchiveRoot,
|
|
889
|
+
);
|
|
768
890
|
|
|
769
|
-
//
|
|
891
|
+
// Update the validation result if it has changed, so we can keep track of the first invalid checkpoint
|
|
770
892
|
// in case there is a sequence of more than one invalid checkpoint, as we need to invalidate the first one.
|
|
771
893
|
// There is an exception though: if a checkpoint is invalidated and replaced with another invalid checkpoint,
|
|
772
894
|
// we need to update the validation result, since we need to be able to invalidate the new one.
|
|
773
895
|
// See test 'chain progresses if an invalid checkpoint is invalidated with an invalid one' for more info.
|
|
774
|
-
if
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
896
|
+
// Do not update the validation result if there is a rejected ancestor, since in that case we want to keep the
|
|
897
|
+
// original invalidation, as the new checkpoint is extending from a previous invalid one.
|
|
898
|
+
const validStatusChanged = rollupStatus.validationResult?.valid !== validationResult.valid;
|
|
899
|
+
const invalidStatusWithSameCheckpointNumber =
|
|
900
|
+
!validationResult.valid &&
|
|
901
|
+
rollupStatus.validationResult &&
|
|
902
|
+
!rollupStatus.validationResult.valid &&
|
|
903
|
+
rollupStatus.validationResult.checkpoint.checkpointNumber === validationResult.checkpoint.checkpointNumber;
|
|
904
|
+
|
|
905
|
+
if (!rejectedAncestor && (validStatusChanged || invalidStatusWithSameCheckpointNumber)) {
|
|
780
906
|
rollupStatus.validationResult = validationResult;
|
|
781
907
|
}
|
|
782
908
|
|
|
783
909
|
if (!validationResult.valid) {
|
|
784
|
-
this.log.warn(`Skipping checkpoint ${
|
|
785
|
-
|
|
786
|
-
l1BlockNumber:
|
|
910
|
+
this.log.warn(`Skipping checkpoint ${calldataCheckpoint.checkpointNumber} due to invalid attestations`, {
|
|
911
|
+
checkpointNumber: calldataCheckpoint.checkpointNumber,
|
|
912
|
+
l1BlockNumber: calldataCheckpoint.l1.blockNumber,
|
|
787
913
|
...pick(validationResult, 'reason'),
|
|
788
914
|
});
|
|
789
915
|
|
|
@@ -793,16 +919,104 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
793
919
|
validationResult,
|
|
794
920
|
});
|
|
795
921
|
|
|
796
|
-
//
|
|
797
|
-
//
|
|
798
|
-
//
|
|
922
|
+
// Persist a rejected-ancestor entry so any later checkpoint that builds on this one
|
|
923
|
+
// is detected and skipped (rather than tripping the addCheckpoints consecutive-number
|
|
924
|
+
// check and causing the sync point to roll back in a loop).
|
|
925
|
+
await this.stores.blocks.addRejectedCheckpoint({
|
|
926
|
+
checkpointNumber: calldataCheckpoint.checkpointNumber,
|
|
927
|
+
archiveRoot: calldataCheckpoint.archiveRoot,
|
|
928
|
+
parentArchiveRoot: calldataCheckpoint.header.lastArchiveRoot,
|
|
929
|
+
slotNumber: calldataCheckpoint.header.slotNumber,
|
|
930
|
+
l1: calldataCheckpoint.l1,
|
|
931
|
+
reason: 'invalid-attestations' as const,
|
|
932
|
+
});
|
|
933
|
+
|
|
799
934
|
continue;
|
|
800
935
|
}
|
|
801
936
|
|
|
937
|
+
if (rejectedAncestor) {
|
|
938
|
+
const descendantInfo: CheckpointInfo = {
|
|
939
|
+
archive: calldataCheckpoint.archiveRoot,
|
|
940
|
+
lastArchive: calldataCheckpoint.header.lastArchiveRoot,
|
|
941
|
+
slotNumber: calldataCheckpoint.header.slotNumber,
|
|
942
|
+
checkpointNumber: calldataCheckpoint.checkpointNumber,
|
|
943
|
+
timestamp: calldataCheckpoint.header.timestamp,
|
|
944
|
+
};
|
|
945
|
+
this.log.warn(
|
|
946
|
+
`Skipping checkpoint ${calldataCheckpoint.checkpointNumber} as it is a descendant of ` +
|
|
947
|
+
`rejected checkpoint ${rejectedAncestor.checkpointNumber} (${rejectedAncestor.reason})`,
|
|
948
|
+
{
|
|
949
|
+
checkpointNumber: calldataCheckpoint.checkpointNumber,
|
|
950
|
+
l1BlockNumber: calldataCheckpoint.l1.blockNumber,
|
|
951
|
+
l1BlockHash: calldataCheckpoint.l1.blockHash,
|
|
952
|
+
ancestorCheckpointNumber: rejectedAncestor.checkpointNumber,
|
|
953
|
+
ancestorArchiveRoot: rejectedAncestor.archiveRoot.toString(),
|
|
954
|
+
ancestorReason: rejectedAncestor.reason,
|
|
955
|
+
},
|
|
956
|
+
);
|
|
957
|
+
|
|
958
|
+
this.events.emit(L2BlockSourceEvents.DescendentOfInvalidAttestationsCheckpointDetected, {
|
|
959
|
+
type: L2BlockSourceEvents.DescendentOfInvalidAttestationsCheckpointDetected,
|
|
960
|
+
checkpoint: descendantInfo,
|
|
961
|
+
ancestorArchiveRoot: rejectedAncestor.archiveRoot,
|
|
962
|
+
ancestorCheckpointNumber: rejectedAncestor.checkpointNumber,
|
|
963
|
+
});
|
|
964
|
+
|
|
965
|
+
// Persist this chainpoint as rejected as well, so we can construct a chain of
|
|
966
|
+
// skipped checkpoints starting from the first one with invalid attestations.
|
|
967
|
+
await this.stores.blocks.addRejectedCheckpoint({
|
|
968
|
+
checkpointNumber: calldataCheckpoint.checkpointNumber,
|
|
969
|
+
archiveRoot: calldataCheckpoint.archiveRoot,
|
|
970
|
+
parentArchiveRoot: calldataCheckpoint.header.lastArchiveRoot,
|
|
971
|
+
slotNumber: calldataCheckpoint.header.slotNumber,
|
|
972
|
+
l1: calldataCheckpoint.l1,
|
|
973
|
+
reason: 'descends-from-invalid-attestations' as const,
|
|
974
|
+
});
|
|
975
|
+
|
|
976
|
+
continue;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
checkpointsToIngest.push(calldataCheckpoint);
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// Fetch blobs in parallel only for the surviving (attestation-valid, non-descendant) checkpoints,
|
|
983
|
+
// then build the full published checkpoints. The last calldata checkpoint may be promotable from a
|
|
984
|
+
// local proposed block (checkpointToPromote), in which case it carries no blob to fetch. A missing or
|
|
985
|
+
// undecodable blob throws and propagates, rolling back the L1 sync point so the fetch is retried.
|
|
986
|
+
const toFetchBlobs = checkpointToPromote
|
|
987
|
+
? checkpointsToIngest.filter(c => c.checkpointNumber !== checkpointToPromote.checkpoint.number)
|
|
988
|
+
: checkpointsToIngest;
|
|
989
|
+
const blobFetched = await asyncPool(10, toFetchBlobs, async checkpoint =>
|
|
990
|
+
retrievedToPublishedCheckpoint({
|
|
991
|
+
...checkpoint,
|
|
992
|
+
checkpointBlobData: await getCheckpointBlobDataFromBlobs(
|
|
993
|
+
this.blobClient,
|
|
994
|
+
checkpoint.l1.blockHash,
|
|
995
|
+
checkpoint.blobHashes,
|
|
996
|
+
checkpoint.checkpointNumber,
|
|
997
|
+
this.log,
|
|
998
|
+
!initialSyncComplete,
|
|
999
|
+
checkpoint.parentBeaconBlockRoot,
|
|
1000
|
+
checkpoint.l1.timestamp,
|
|
1001
|
+
),
|
|
1002
|
+
}),
|
|
1003
|
+
);
|
|
1004
|
+
|
|
1005
|
+
// Index the built checkpoints by number so we can ingest them in calldata order, slotting in the
|
|
1006
|
+
// promoted checkpoint (built from a local proposed block rather than blobs).
|
|
1007
|
+
const publishedByNumber = new Map(blobFetched.map(published => [published.checkpoint.number, published]));
|
|
1008
|
+
if (checkpointToPromote) {
|
|
1009
|
+
publishedByNumber.set(checkpointToPromote.checkpoint.number, checkpointToPromote);
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
const validCheckpoints: PublishedCheckpoint[] = [];
|
|
1013
|
+
for (const calldataCheckpoint of checkpointsToIngest) {
|
|
1014
|
+
const published = publishedByNumber.get(calldataCheckpoint.checkpointNumber)!;
|
|
1015
|
+
|
|
802
1016
|
// Check the inHash of the checkpoint against the l1->l2 messages.
|
|
803
1017
|
// The messages should've been synced up to the currentL1BlockNumber and must be available for the published
|
|
804
1018
|
// checkpoints we just retrieved.
|
|
805
|
-
const l1ToL2Messages = await this.
|
|
1019
|
+
const l1ToL2Messages = await this.stores.messages.getL1ToL2Messages(published.checkpoint.number);
|
|
806
1020
|
const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
|
|
807
1021
|
const publishedInHash = published.checkpoint.header.inHash;
|
|
808
1022
|
if (!computedInHash.equals(publishedInHash)) {
|
|
@@ -841,15 +1055,40 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
841
1055
|
try {
|
|
842
1056
|
const updatedValidationResult =
|
|
843
1057
|
rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
|
|
1058
|
+
|
|
1059
|
+
// Split valid checkpoints: the promoted one (if any) is persisted via the proposed-promotion path,
|
|
1060
|
+
// the rest via addCheckpoints. Both paths run within the same store transaction for atomicity.
|
|
1061
|
+
const [[maybeValidCheckpointToPromote], checkpointsToAdd] = partition(
|
|
1062
|
+
validCheckpoints,
|
|
1063
|
+
c => c.checkpoint.number === checkpointToPromote?.checkpoint.number,
|
|
1064
|
+
);
|
|
1065
|
+
|
|
844
1066
|
const [processDuration, result] = await elapsed(() =>
|
|
845
1067
|
execInSpan(this.tracer, 'Archiver.addCheckpoints', () =>
|
|
846
|
-
this.updater.addCheckpoints(
|
|
1068
|
+
this.updater.addCheckpoints(
|
|
1069
|
+
checkpointsToAdd,
|
|
1070
|
+
updatedValidationResult,
|
|
1071
|
+
maybeValidCheckpointToPromote && {
|
|
1072
|
+
l1: lastCalldataCheckpoint.l1,
|
|
1073
|
+
attestations: lastCalldataCheckpoint.attestations,
|
|
1074
|
+
checkpoint: maybeValidCheckpointToPromote,
|
|
1075
|
+
},
|
|
1076
|
+
evictProposedFrom,
|
|
1077
|
+
),
|
|
847
1078
|
),
|
|
848
1079
|
);
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
1080
|
+
|
|
1081
|
+
if (validCheckpoints.length > 0) {
|
|
1082
|
+
this.instrumentation.processNewCheckpointedBlocks(
|
|
1083
|
+
processDuration / validCheckpoints.length,
|
|
1084
|
+
validCheckpoints.flatMap(c => c.checkpoint.blocks),
|
|
1085
|
+
);
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// Record blocks newly fetched from L1 checkpoint payloads as added. The promoted checkpoint (if any) is
|
|
1089
|
+
// excluded: its blocks were already in local archiver storage (added via the proposed-block path) so the
|
|
1090
|
+
// block stream does not need them re-downloaded.
|
|
1091
|
+
blocksAdded.push(...checkpointsToAdd.flatMap(c => c.checkpoint.blocks));
|
|
853
1092
|
|
|
854
1093
|
// If blocks were pruned due to conflict with L1 checkpoints, emit event
|
|
855
1094
|
if (result.prunedBlocks && result.prunedBlocks.length > 0) {
|
|
@@ -861,6 +1100,8 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
861
1100
|
{ prunedBlocks: result.prunedBlocks.map(b => b.toBlockInfo()), prunedSlotNumber, prunedCheckpointNumber },
|
|
862
1101
|
);
|
|
863
1102
|
|
|
1103
|
+
this.instrumentation.recordPrune('l1_conflict');
|
|
1104
|
+
|
|
864
1105
|
// Emit event for listening services to react to the prune.
|
|
865
1106
|
// Note: slotNumber comes from the first pruned block. If pruned blocks theoretically spanned multiple slots,
|
|
866
1107
|
// only one slot number would be reported (though in practice all blocks in a checkpoint span a single slot).
|
|
@@ -874,14 +1115,23 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
874
1115
|
if (err instanceof InitialCheckpointNumberNotSequentialError) {
|
|
875
1116
|
const { previousCheckpointNumber, newCheckpointNumber } = err;
|
|
876
1117
|
const previousCheckpoint = previousCheckpointNumber
|
|
877
|
-
? await this.
|
|
1118
|
+
? await this.stores.blocks.getCheckpointData(CheckpointNumber(previousCheckpointNumber))
|
|
878
1119
|
: undefined;
|
|
879
|
-
const
|
|
880
|
-
|
|
1120
|
+
const lastFinalizedCheckpoint = await this.stores.blocks.getCheckpointData(
|
|
1121
|
+
await this.stores.blocks.getFinalizedCheckpointNumber(),
|
|
1122
|
+
);
|
|
1123
|
+
const updatedL1SyncPoint =
|
|
1124
|
+
previousCheckpoint?.l1.blockNumber ??
|
|
1125
|
+
lastFinalizedCheckpoint?.l1.blockNumber ??
|
|
1126
|
+
this.l1Constants.l1StartBlock;
|
|
1127
|
+
await this.stores.blocks.setSynchedL1BlockNumber(updatedL1SyncPoint);
|
|
881
1128
|
this.log.warn(
|
|
882
1129
|
`Attempting to insert checkpoint ${newCheckpointNumber} with previous block ${previousCheckpointNumber}. Rolling back L1 sync point to ${updatedL1SyncPoint} to try and fetch the missing blocks.`,
|
|
883
1130
|
{
|
|
884
1131
|
previousCheckpointNumber,
|
|
1132
|
+
previousCheckpoint: previousCheckpoint?.header.toInspect(),
|
|
1133
|
+
lastFinalizedCheckpoint: lastFinalizedCheckpoint?.header.toInspect(),
|
|
1134
|
+
l1StartBlock: this.l1Constants.l1StartBlock,
|
|
885
1135
|
newCheckpointNumber,
|
|
886
1136
|
updatedL1SyncPoint,
|
|
887
1137
|
},
|
|
@@ -902,13 +1152,107 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
902
1152
|
});
|
|
903
1153
|
}
|
|
904
1154
|
lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
|
|
905
|
-
|
|
1155
|
+
// The last checkpoint seen on L1 this batch (valid or rejected), tracked from calldata since
|
|
1156
|
+
// rejected checkpoints are no longer built into PublishedCheckpoints.
|
|
1157
|
+
lastSeenCheckpoint = lastCalldataCheckpoint;
|
|
906
1158
|
} while (searchEndBlock < currentL1BlockNumber);
|
|
907
1159
|
|
|
908
1160
|
// Important that we update AFTER inserting the blocks.
|
|
909
1161
|
await updateProvenCheckpoint();
|
|
910
1162
|
|
|
911
|
-
return { ...rollupStatus, lastRetrievedCheckpoint,
|
|
1163
|
+
return { ...rollupStatus, lastRetrievedCheckpoint, lastSeenCheckpoint };
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
/**
|
|
1167
|
+
* Checks if a specific checkpoint matches a local pending entry, and if so, loads local data to build
|
|
1168
|
+
* a synthetic published checkpoint (skipping blob fetch).
|
|
1169
|
+
*
|
|
1170
|
+
* Returns { diverged: true, fromCheckpointNumber } when the L1 checkpoint does NOT match local pending
|
|
1171
|
+
* data for that number, so the caller can evict the entire pending suffix >= fromCheckpointNumber
|
|
1172
|
+
* (those entries chain off the now-invalid local state) within the same addCheckpoints transaction.
|
|
1173
|
+
*/
|
|
1174
|
+
private async tryBuildPublishedCheckpointFromProposed(
|
|
1175
|
+
calldataCheckpoint: RetrievedCheckpointFromCalldata | undefined,
|
|
1176
|
+
): Promise<PublishedCheckpoint | { diverged: true; fromCheckpointNumber: CheckpointNumber } | undefined> {
|
|
1177
|
+
if (this.config.skipPromoteProposedCheckpointDuringL1Sync || !calldataCheckpoint) {
|
|
1178
|
+
return undefined;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// Look up the specific pending entry for the checkpoint being mined, not just the tip
|
|
1182
|
+
const proposed = await this.stores.blocks.getProposedCheckpointByNumber(calldataCheckpoint.checkpointNumber);
|
|
1183
|
+
if (!proposed) {
|
|
1184
|
+
return undefined;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
if (
|
|
1188
|
+
!proposed.header.equals(calldataCheckpoint.header) ||
|
|
1189
|
+
!proposed.archive.root.equals(calldataCheckpoint.archiveRoot)
|
|
1190
|
+
) {
|
|
1191
|
+
this.log.warn(
|
|
1192
|
+
`Local proposed checkpoint ${proposed.checkpointNumber} does not match checkpoint retrieved from L1, overriding with L1 data`,
|
|
1193
|
+
{
|
|
1194
|
+
proposedCheckpointNumber: proposed.checkpointNumber,
|
|
1195
|
+
proposedHeader: proposed.header.toInspect(),
|
|
1196
|
+
proposedArchiveRoot: proposed.archive.root.toString(),
|
|
1197
|
+
calldataCheckpointNumber: calldataCheckpoint.checkpointNumber,
|
|
1198
|
+
calldataHeader: calldataCheckpoint.header.toInspect(),
|
|
1199
|
+
calldataArchiveRoot: calldataCheckpoint.archiveRoot.toString(),
|
|
1200
|
+
},
|
|
1201
|
+
);
|
|
1202
|
+
// Both the locally-proposed checkpoint and the L1-confirmed one are signed by the
|
|
1203
|
+
// slot proposer; emit a divergence event so the slasher can attribute equivocation.
|
|
1204
|
+
// Only emit when the slots match — uncheckpointed entries are pruned above so this
|
|
1205
|
+
// should always hold, but guard defensively to avoid mis-attributing a slash.
|
|
1206
|
+
if (proposed.header.slotNumber === calldataCheckpoint.header.slotNumber) {
|
|
1207
|
+
this.events.emit(L2BlockSourceEvents.CheckpointEquivocationDetected, {
|
|
1208
|
+
type: L2BlockSourceEvents.CheckpointEquivocationDetected,
|
|
1209
|
+
slotNumber: calldataCheckpoint.header.slotNumber,
|
|
1210
|
+
checkpointNumber: calldataCheckpoint.checkpointNumber,
|
|
1211
|
+
l1ArchiveRoot: calldataCheckpoint.archiveRoot,
|
|
1212
|
+
proposedArchiveRoot: proposed.archive.root,
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
// Return a divergence signal so the caller can evict pending >= this number
|
|
1216
|
+
return { diverged: true, fromCheckpointNumber: proposed.checkpointNumber };
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
this.log.debug(
|
|
1220
|
+
`Building published checkpoint from proposed ${calldataCheckpoint.checkpointNumber} (skipping blob fetch)`,
|
|
1221
|
+
{ proposedHeader: proposed.header.toInspect(), proposedArchiveRoot: proposed.archive.root.toString() },
|
|
1222
|
+
);
|
|
1223
|
+
|
|
1224
|
+
const blocks = await this.stores.blocks.getBlocks({
|
|
1225
|
+
from: BlockNumber(proposed.startBlock),
|
|
1226
|
+
limit: proposed.blockCount,
|
|
1227
|
+
});
|
|
1228
|
+
if (blocks.length !== proposed.blockCount) {
|
|
1229
|
+
this.log.warn(
|
|
1230
|
+
`Local proposed checkpoint ${proposed.checkpointNumber} has wrong block count (expected ${proposed.blockCount} blocks starting at ${proposed.startBlock} but got ${blocks.length})`,
|
|
1231
|
+
{
|
|
1232
|
+
proposedCheckpointNumber: proposed.checkpointNumber,
|
|
1233
|
+
proposedStartBlock: proposed.startBlock,
|
|
1234
|
+
proposedBlockCount: proposed.blockCount,
|
|
1235
|
+
retrievedBlocks: blocks.map(b => b.number),
|
|
1236
|
+
},
|
|
1237
|
+
);
|
|
1238
|
+
return undefined;
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
const checkpoint = Checkpoint.from({
|
|
1242
|
+
archive: proposed.archive,
|
|
1243
|
+
header: proposed.header,
|
|
1244
|
+
blocks,
|
|
1245
|
+
number: proposed.checkpointNumber,
|
|
1246
|
+
feeAssetPriceModifier: proposed.feeAssetPriceModifier,
|
|
1247
|
+
});
|
|
1248
|
+
const promotedCheckpoint = PublishedCheckpoint.from({
|
|
1249
|
+
checkpoint,
|
|
1250
|
+
l1: calldataCheckpoint.l1,
|
|
1251
|
+
attestations: calldataCheckpoint.attestations,
|
|
1252
|
+
});
|
|
1253
|
+
this.instrumentation.processCheckpointPromoted();
|
|
1254
|
+
|
|
1255
|
+
return promotedCheckpoint;
|
|
912
1256
|
}
|
|
913
1257
|
|
|
914
1258
|
private async checkForNewCheckpointsBeforeL1SyncPoint(
|
|
@@ -916,39 +1260,48 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
916
1260
|
blocksSynchedTo: bigint,
|
|
917
1261
|
currentL1BlockNumber: bigint,
|
|
918
1262
|
): Promise<void> {
|
|
919
|
-
const {
|
|
920
|
-
// Compare the last checkpoint we have (either retrieved in this round or loaded from store)
|
|
921
|
-
// rollup contract told us was the latest one (pinned at the currentL1BlockNumber).
|
|
1263
|
+
const { lastSeenCheckpoint, pendingCheckpointNumber } = status;
|
|
1264
|
+
// Compare the last checkpoint (valid or not) we have (either retrieved in this round or loaded from store)
|
|
1265
|
+
// with what the rollup contract told us was the latest one (pinned at the currentL1BlockNumber).
|
|
922
1266
|
const latestLocalCheckpointNumber =
|
|
923
|
-
|
|
1267
|
+
lastSeenCheckpoint?.checkpointNumber ??
|
|
1268
|
+
CheckpointNumber.max(
|
|
1269
|
+
await this.stores.blocks.getLatestCheckpointNumber(),
|
|
1270
|
+
await this.stores.blocks.getLatestRejectedCheckpointNumber(),
|
|
1271
|
+
) ??
|
|
1272
|
+
CheckpointNumber.ZERO;
|
|
1273
|
+
|
|
924
1274
|
if (latestLocalCheckpointNumber < pendingCheckpointNumber) {
|
|
925
1275
|
// Here we have consumed all logs until the `currentL1Block` we pinned at the beginning of the archiver loop,
|
|
926
1276
|
// but still haven't reached the pending checkpoint according to the call to the rollup contract.
|
|
927
1277
|
// We suspect an L1 reorg that added checkpoints *behind* us. If that is the case, it must have happened between
|
|
928
1278
|
// the last checkpoint we saw and the current one, so we reset the last synched L1 block number. In the edge case
|
|
929
1279
|
// we don't have one, we go back 2 L1 epochs, which is the deepest possible reorg (assuming Casper is working).
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
1280
|
+
const latestLocalCheckpoint:
|
|
1281
|
+
| { checkpointNumber: CheckpointNumber; l1: L1PublishedData }
|
|
1282
|
+
| CheckpointData
|
|
1283
|
+
| RejectedCheckpoint
|
|
1284
|
+
| undefined =
|
|
1285
|
+
lastSeenCheckpoint ??
|
|
1286
|
+
(await this.stores.blocks.getCheckpointData(latestLocalCheckpointNumber)) ??
|
|
1287
|
+
(await this.stores.blocks.getRejectedCheckpointByNumber(latestLocalCheckpointNumber));
|
|
1288
|
+
|
|
1289
|
+
const targetL1BlockNumber =
|
|
1290
|
+
latestLocalCheckpoint?.l1.blockNumber ??
|
|
1291
|
+
maxBigint(currentL1BlockNumber - 64n, this.l1Constants.l1StartBlock, 0n);
|
|
1292
|
+
|
|
940
1293
|
this.log.warn(
|
|
941
1294
|
`Failed to reach checkpoint ${pendingCheckpointNumber} at ${currentL1BlockNumber} (latest is ${latestLocalCheckpointNumber}). ` +
|
|
942
1295
|
`Rolling back last synched L1 block number to ${targetL1BlockNumber}.`,
|
|
943
1296
|
{
|
|
944
1297
|
latestLocalCheckpointNumber,
|
|
945
|
-
|
|
1298
|
+
latestLocalCheckpointL1: latestLocalCheckpoint?.l1,
|
|
946
1299
|
blocksSynchedTo,
|
|
947
1300
|
currentL1BlockNumber,
|
|
948
1301
|
...status,
|
|
949
1302
|
},
|
|
950
1303
|
);
|
|
951
|
-
await this.
|
|
1304
|
+
await this.stores.blocks.setSynchedL1BlockNumber(targetL1BlockNumber);
|
|
952
1305
|
} else {
|
|
953
1306
|
this.log.trace(`No new checkpoints behind L1 sync point to retrieve.`, {
|
|
954
1307
|
latestLocalCheckpointNumber,
|
|
@@ -958,7 +1311,7 @@ export class ArchiverL1Synchronizer implements Traceable {
|
|
|
958
1311
|
}
|
|
959
1312
|
|
|
960
1313
|
private async getCheckpointHeader(number: CheckpointNumber) {
|
|
961
|
-
const checkpoint = await this.
|
|
1314
|
+
const checkpoint = await this.stores.blocks.getCheckpointData(number);
|
|
962
1315
|
if (!checkpoint) {
|
|
963
1316
|
return undefined;
|
|
964
1317
|
}
|