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