@aztec/archiver 0.0.1-commit.343b43af6 → 0.0.1-commit.350e0a4d
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 -16
- package/dest/archiver.d.ts.map +1 -1
- package/dest/archiver.js +295 -79
- package/dest/config.d.ts +7 -3
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +38 -14
- package/dest/errors.d.ts +50 -2
- package/dest/errors.d.ts.map +1 -1
- package/dest/errors.js +74 -2
- package/dest/factory.d.ts +12 -7
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +49 -32
- 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 +459 -221
- 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 -67
- package/dest/store/block_store.d.ts.map +1 -1
- package/dest/store/block_store.js +669 -233
- 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 -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 +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 +11 -1
- package/dest/store/message_store.d.ts.map +1 -1
- package/dest/store/message_store.js +50 -8
- 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 +91 -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 +227 -178
- 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 -85
- package/src/config.ts +43 -13
- package/src/errors.ts +117 -2
- package/src/factory.ts +61 -27
- 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 -187
- package/src/modules/data_store_updater.ts +204 -149
- package/src/modules/instrumentation.ts +43 -10
- package/src/modules/l1_synchronizer.ts +623 -265
- package/src/modules/outbox_trees_resolver.ts +199 -0
- package/src/modules/validation.ts +80 -23
- package/src/store/block_store.ts +822 -280
- 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 +302 -559
- package/src/store/log_store_codec.ts +143 -0
- package/src/store/message_store.ts +59 -9
- package/src/structs/inbox_message.ts +1 -1
- package/src/test/fake_l1_state.ts +114 -32
- package/src/test/mock_l2_block_source.ts +284 -225
- 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 -362
- package/dest/store/kv_archiver_store.d.ts.map +0 -1
- package/dest/store/kv_archiver_store.js +0 -476
- package/src/store/kv_archiver_store.ts +0 -685
package/src/store/block_store.ts
CHANGED
|
@@ -12,14 +12,24 @@ import {
|
|
|
12
12
|
type BlockData,
|
|
13
13
|
BlockHash,
|
|
14
14
|
Body,
|
|
15
|
-
CheckpointedL2Block,
|
|
16
15
|
CommitteeAttestation,
|
|
16
|
+
GENESIS_CHECKPOINT_HEADER_HASH,
|
|
17
17
|
L2Block,
|
|
18
|
+
type L2TipId,
|
|
19
|
+
type L2Tips,
|
|
18
20
|
type ValidateCheckpointResult,
|
|
19
21
|
deserializeValidateCheckpointResult,
|
|
20
22
|
serializeValidateCheckpointResult,
|
|
21
23
|
} from '@aztec/stdlib/block';
|
|
22
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
Checkpoint,
|
|
26
|
+
type CheckpointData,
|
|
27
|
+
type CommonCheckpointData,
|
|
28
|
+
L1PublishedData,
|
|
29
|
+
type ProposedCheckpointData,
|
|
30
|
+
type ProposedCheckpointInput,
|
|
31
|
+
PublishedCheckpoint,
|
|
32
|
+
} from '@aztec/stdlib/checkpoint';
|
|
23
33
|
import { CheckpointHeader } from '@aztec/stdlib/rollup';
|
|
24
34
|
import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
|
|
25
35
|
import {
|
|
@@ -27,8 +37,6 @@ import {
|
|
|
27
37
|
type IndexedTxEffect,
|
|
28
38
|
TxEffect,
|
|
29
39
|
TxHash,
|
|
30
|
-
TxReceipt,
|
|
31
|
-
TxStatus,
|
|
32
40
|
deserializeIndexedTxEffect,
|
|
33
41
|
serializeIndexedTxEffect,
|
|
34
42
|
} from '@aztec/stdlib/tx';
|
|
@@ -36,6 +44,7 @@ import {
|
|
|
36
44
|
import {
|
|
37
45
|
BlockAlreadyCheckpointedError,
|
|
38
46
|
BlockArchiveNotConsistentError,
|
|
47
|
+
BlockCheckpointNumberNotSequentialError,
|
|
39
48
|
BlockIndexNotSequentialError,
|
|
40
49
|
BlockNotFoundError,
|
|
41
50
|
BlockNumberNotSequentialError,
|
|
@@ -43,9 +52,13 @@ import {
|
|
|
43
52
|
CheckpointNotFoundError,
|
|
44
53
|
CheckpointNumberNotSequentialError,
|
|
45
54
|
InitialCheckpointNumberNotSequentialError,
|
|
55
|
+
NoProposedCheckpointToPromoteError,
|
|
56
|
+
ProposedCheckpointArchiveRootMismatchError,
|
|
57
|
+
ProposedCheckpointNotSequentialError,
|
|
58
|
+
ProposedCheckpointPromotionNotSequentialError,
|
|
46
59
|
} from '../errors.js';
|
|
47
60
|
|
|
48
|
-
export {
|
|
61
|
+
export type { TxEffect, TxHash, TxReceipt } from '@aztec/stdlib/tx';
|
|
49
62
|
|
|
50
63
|
type BlockIndexValue = [blockNumber: number, index: number];
|
|
51
64
|
|
|
@@ -57,19 +70,78 @@ type BlockStorage = {
|
|
|
57
70
|
indexWithinCheckpoint: number;
|
|
58
71
|
};
|
|
59
72
|
|
|
60
|
-
|
|
73
|
+
/** Reason a checkpoint was rejected during sync. */
|
|
74
|
+
export type RejectedCheckpointReason = 'invalid-attestations' | 'descends-from-invalid-attestations';
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* A checkpoint observed on L1 that the archiver decided not to ingest, recorded so that
|
|
78
|
+
* any descendant that builds on top of it can also be skipped (rather than throwing
|
|
79
|
+
* `InitialCheckpointNumberNotSequentialError` and looping). An entry is dropped via
|
|
80
|
+
* {@link BlockStore.removeRejectedCheckpointByArchiveRoot} once a checkpoint with the same
|
|
81
|
+
* archive root is later ingested as valid (e.g. it gathered enough attestations), which
|
|
82
|
+
* re-enables its descendants.
|
|
83
|
+
*/
|
|
84
|
+
export type RejectedCheckpoint = {
|
|
85
|
+
/** Checkpoint number this entry represents. */
|
|
86
|
+
checkpointNumber: CheckpointNumber;
|
|
87
|
+
/** Archive root produced by this rejected checkpoint (matched against descendants' `lastArchiveRoot`). */
|
|
88
|
+
archiveRoot: Fr;
|
|
89
|
+
/** `lastArchiveRoot` from this checkpoint's header (the ancestor it built on). */
|
|
90
|
+
parentArchiveRoot: Fr;
|
|
91
|
+
/** Slot number of the rejected checkpoint. */
|
|
92
|
+
slotNumber: SlotNumber;
|
|
93
|
+
/** L1 publication data for the rejected checkpoint (block number, hash, timestamp). */
|
|
94
|
+
l1: L1PublishedData;
|
|
95
|
+
/** Why the entry was recorded. */
|
|
96
|
+
reason: RejectedCheckpointReason;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
type RejectedCheckpointStorage = {
|
|
100
|
+
checkpointNumber: number;
|
|
101
|
+
archiveRoot: Buffer;
|
|
102
|
+
parentArchiveRoot: Buffer;
|
|
103
|
+
slotNumber: number;
|
|
104
|
+
l1: Buffer;
|
|
105
|
+
reason: RejectedCheckpointReason;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/** Checkpoint Storage shared between Checkpoints + Proposed Checkpoints */
|
|
109
|
+
type CommonCheckpointStorage = {
|
|
61
110
|
header: Buffer;
|
|
62
111
|
archive: Buffer;
|
|
63
112
|
checkpointOutHash: Buffer;
|
|
64
113
|
checkpointNumber: number;
|
|
65
114
|
startBlock: number;
|
|
66
115
|
blockCount: number;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
type CheckpointStorage = CommonCheckpointStorage & {
|
|
67
119
|
l1: Buffer;
|
|
68
120
|
attestations: Buffer[];
|
|
121
|
+
feeAssetPriceModifier: string;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
/** Storage format for a proposed checkpoint (attested but not yet L1-confirmed). */
|
|
125
|
+
type ProposedCheckpointStorage = CommonCheckpointStorage & {
|
|
126
|
+
totalManaUsed: string;
|
|
127
|
+
feeAssetPriceModifier: string;
|
|
69
128
|
};
|
|
70
129
|
|
|
71
130
|
export type RemoveCheckpointsResult = { blocksRemoved: L2Block[] | undefined };
|
|
72
131
|
|
|
132
|
+
/**
|
|
133
|
+
* Single-block lookup with the chain-tip `tag` variant of {@link BlockQuery} already resolved
|
|
134
|
+
* to a concrete block number. The `tag` branch is unrepresentable here so storage code does
|
|
135
|
+
* not need to handle it at runtime.
|
|
136
|
+
*/
|
|
137
|
+
export type ResolvedBlockQuery = { number: BlockNumber } | { hash: BlockHash } | { archive: Fr };
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Range lookup with the `epoch` variant of {@link BlocksQuery} already resolved to a
|
|
141
|
+
* `{ from, limit }` pair. Storage code never needs to map epoch numbers to block ranges.
|
|
142
|
+
*/
|
|
143
|
+
export type ResolvedBlocksQuery = { from: BlockNumber; limit: number; onlyCheckpointed?: boolean };
|
|
144
|
+
|
|
73
145
|
/**
|
|
74
146
|
* LMDB-based block storage for the archiver.
|
|
75
147
|
*/
|
|
@@ -77,7 +149,10 @@ export class BlockStore {
|
|
|
77
149
|
/** Map block number to block data */
|
|
78
150
|
#blocks: AztecAsyncMap<number, BlockStorage>;
|
|
79
151
|
|
|
80
|
-
/** Map checkpoint number
|
|
152
|
+
/** Map keyed by checkpoint number holding proposed (locally-validated, not yet L1-confirmed) checkpoints. */
|
|
153
|
+
#proposedCheckpoints: AztecAsyncMap<number, ProposedCheckpointStorage>;
|
|
154
|
+
|
|
155
|
+
/** Map checkpoint number to checkpoint data for mined checkpoints only */
|
|
81
156
|
#checkpoints: AztecAsyncMap<number, CheckpointStorage>;
|
|
82
157
|
|
|
83
158
|
/** Map slot number to checkpoint number, for looking up checkpoints by slot range. */
|
|
@@ -110,6 +185,12 @@ export class BlockStore {
|
|
|
110
185
|
/** Index mapping block archive to block number */
|
|
111
186
|
#blockArchiveIndex: AztecAsyncMap<string, number>;
|
|
112
187
|
|
|
188
|
+
/** Map rejected checkpoints (due to invalid attestations) by archive root */
|
|
189
|
+
#rejectedCheckpoints: AztecAsyncMap<string, RejectedCheckpointStorage>;
|
|
190
|
+
|
|
191
|
+
/** Index mapping a rejected checkpoint's number to its archive root, so the latest can be read in reverse order */
|
|
192
|
+
#rejectedCheckpointsByNumber: AztecAsyncMap<number, string>;
|
|
193
|
+
|
|
113
194
|
#log = createLogger('archiver:block_store');
|
|
114
195
|
|
|
115
196
|
constructor(private db: AztecAsyncKVStore) {
|
|
@@ -125,6 +206,9 @@ export class BlockStore {
|
|
|
125
206
|
this.#pendingChainValidationStatus = db.openSingleton('archiver_pending_chain_validation_status');
|
|
126
207
|
this.#checkpoints = db.openMap('archiver_checkpoints');
|
|
127
208
|
this.#slotToCheckpoint = db.openMap('archiver_slot_to_checkpoint');
|
|
209
|
+
this.#proposedCheckpoints = db.openMap('archiver_proposed_checkpoints');
|
|
210
|
+
this.#rejectedCheckpoints = db.openMap('archiver_rejected_checkpoints');
|
|
211
|
+
this.#rejectedCheckpointsByNumber = db.openMap('archiver_rejected_checkpoints_by_number');
|
|
128
212
|
}
|
|
129
213
|
|
|
130
214
|
/**
|
|
@@ -159,14 +243,14 @@ export class BlockStore {
|
|
|
159
243
|
const blockLastArchive = block.header.lastArchive.root;
|
|
160
244
|
|
|
161
245
|
// Extract the latest block and checkpoint numbers
|
|
162
|
-
const previousBlockNumber = await this.
|
|
163
|
-
const
|
|
246
|
+
const previousBlockNumber = await this.getLatestL2BlockNumber();
|
|
247
|
+
const latestCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
164
248
|
|
|
165
249
|
// Verify we're not overwriting checkpointed blocks
|
|
166
250
|
const lastCheckpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
|
|
167
251
|
if (!opts.force && blockNumber <= lastCheckpointedBlockNumber) {
|
|
168
252
|
// Check if the proposed block matches the already-checkpointed one
|
|
169
|
-
const existingBlock = await this.
|
|
253
|
+
const existingBlock = await this.getBlockData({ number: BlockNumber(blockNumber) });
|
|
170
254
|
if (existingBlock && existingBlock.archive.root.equals(block.archive.root)) {
|
|
171
255
|
throw new BlockAlreadyCheckpointedError(blockNumber);
|
|
172
256
|
}
|
|
@@ -178,13 +262,18 @@ export class BlockStore {
|
|
|
178
262
|
throw new BlockNumberNotSequentialError(blockNumber, previousBlockNumber);
|
|
179
263
|
}
|
|
180
264
|
|
|
181
|
-
//
|
|
182
|
-
|
|
183
|
-
|
|
265
|
+
// Accept the block if either the confirmed checkpoint or a pending checkpoint matches
|
|
266
|
+
// the expected predecessor. We look for a pending entry at exactly blockCheckpointNumber - 1.
|
|
267
|
+
const expectedCheckpointNumber = blockCheckpointNumber - 1;
|
|
268
|
+
const hasPendingAtExpected = await this.#proposedCheckpoints.hasAsync(expectedCheckpointNumber);
|
|
269
|
+
if (!opts.force && latestCheckpointNumber !== expectedCheckpointNumber && !hasPendingAtExpected) {
|
|
270
|
+
const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
|
|
271
|
+
const previous = CheckpointNumber(Math.max(latestCheckpointNumber, latestPendingKey ?? 0));
|
|
272
|
+
throw new BlockCheckpointNumberNotSequentialError(BlockNumber(blockNumber), blockCheckpointNumber, previous);
|
|
184
273
|
}
|
|
185
274
|
|
|
186
275
|
// Extract the previous block if there is one and see if it is for the same checkpoint or not
|
|
187
|
-
const previousBlockResult = await this.
|
|
276
|
+
const previousBlockResult = await this.getBlockData({ number: previousBlockNumber });
|
|
188
277
|
|
|
189
278
|
let expectedBlockIndex = 0;
|
|
190
279
|
let previousBlockIndex: number | undefined = undefined;
|
|
@@ -197,7 +286,7 @@ export class BlockStore {
|
|
|
197
286
|
if (!previousBlockResult.archive.root.equals(blockLastArchive)) {
|
|
198
287
|
throw new BlockArchiveNotConsistentError(
|
|
199
288
|
blockNumber,
|
|
200
|
-
previousBlockResult.
|
|
289
|
+
previousBlockResult.header.globalVariables.blockNumber,
|
|
201
290
|
blockLastArchive,
|
|
202
291
|
previousBlockResult.archive.root,
|
|
203
292
|
);
|
|
@@ -216,47 +305,45 @@ export class BlockStore {
|
|
|
216
305
|
}
|
|
217
306
|
|
|
218
307
|
/**
|
|
219
|
-
* Append new
|
|
308
|
+
* Append new checkpoints to the store's list.
|
|
309
|
+
* Checkpoints at the start of the batch that are already stored (e.g. re-included by an L1 reorg)
|
|
310
|
+
* are accepted if their archive root matches: their L1 metadata is updated but they are not
|
|
311
|
+
* re-inserted, and they are excluded from the returned array.
|
|
220
312
|
* @param checkpoints - The L2 checkpoints to be added to the store.
|
|
221
|
-
* @returns
|
|
313
|
+
* @returns The checkpoints that were actually inserted (excluding already-stored ones).
|
|
222
314
|
*/
|
|
223
|
-
async addCheckpoints(
|
|
315
|
+
async addCheckpoints(
|
|
316
|
+
checkpoints: PublishedCheckpoint[],
|
|
317
|
+
opts: { force?: boolean } = {},
|
|
318
|
+
): Promise<PublishedCheckpoint[]> {
|
|
224
319
|
if (checkpoints.length === 0) {
|
|
225
|
-
return
|
|
320
|
+
return [];
|
|
226
321
|
}
|
|
227
322
|
|
|
228
323
|
return await this.db.transactionAsync(async () => {
|
|
229
|
-
// Check that the checkpoint immediately before the first block to be added is present in the store.
|
|
230
324
|
const firstCheckpointNumber = checkpoints[0].checkpoint.number;
|
|
231
325
|
const previousCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
232
326
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
// There should be a previous checkpoint
|
|
241
|
-
previousCheckpointData = await this.getCheckpointData(previousCheckpointNumber);
|
|
242
|
-
if (previousCheckpointData === undefined) {
|
|
243
|
-
throw new CheckpointNotFoundError(previousCheckpointNumber);
|
|
327
|
+
// Handle already-stored checkpoints at the start of the batch.
|
|
328
|
+
// This can happen after an L1 reorg re-includes a checkpoint in a different L1 block.
|
|
329
|
+
// We accept them if archives match (same content) and update their L1 metadata.
|
|
330
|
+
if (!opts.force && firstCheckpointNumber <= previousCheckpointNumber) {
|
|
331
|
+
checkpoints = await this.skipOrUpdateAlreadyStoredCheckpoints(checkpoints, previousCheckpointNumber);
|
|
332
|
+
if (checkpoints.length === 0) {
|
|
333
|
+
return [];
|
|
244
334
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
// If we have a previous checkpoint then we need to get the previous block number
|
|
251
|
-
if (previousCheckpointData !== undefined) {
|
|
252
|
-
previousBlockNumber = BlockNumber(previousCheckpointData.startBlock + previousCheckpointData.blockCount - 1);
|
|
253
|
-
previousBlock = await this.getBlock(previousBlockNumber);
|
|
254
|
-
if (previousBlock === undefined) {
|
|
255
|
-
// We should be able to get the required previous block
|
|
256
|
-
throw new BlockNotFoundError(previousBlockNumber);
|
|
335
|
+
// Re-check sequentiality after skipping
|
|
336
|
+
const newFirstNumber = checkpoints[0].checkpoint.number;
|
|
337
|
+
if (previousCheckpointNumber !== newFirstNumber - 1) {
|
|
338
|
+
throw new InitialCheckpointNumberNotSequentialError(newFirstNumber, previousCheckpointNumber);
|
|
257
339
|
}
|
|
340
|
+
} else if (previousCheckpointNumber !== firstCheckpointNumber - 1 && !opts.force) {
|
|
341
|
+
throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
|
|
258
342
|
}
|
|
259
343
|
|
|
344
|
+
// Get the last block of the previous checkpoint for archive chaining
|
|
345
|
+
let previousBlock = await this.getPreviousCheckpointBlock(checkpoints[0].checkpoint.number);
|
|
346
|
+
|
|
260
347
|
// Iterate over checkpoints array and insert them, checking that the block numbers are sequential.
|
|
261
348
|
let previousCheckpoint: PublishedCheckpoint | undefined = undefined;
|
|
262
349
|
for (const checkpoint of checkpoints) {
|
|
@@ -272,42 +359,14 @@ export class BlockStore {
|
|
|
272
359
|
}
|
|
273
360
|
previousCheckpoint = checkpoint;
|
|
274
361
|
|
|
275
|
-
//
|
|
276
|
-
|
|
277
|
-
const block = checkpoint.checkpoint.blocks[i];
|
|
278
|
-
if (previousBlock) {
|
|
279
|
-
// The blocks should have a sequential block number
|
|
280
|
-
if (previousBlock.number !== block.number - 1) {
|
|
281
|
-
throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
|
|
282
|
-
}
|
|
283
|
-
// If the blocks are for the same checkpoint then they should have sequential indexes
|
|
284
|
-
if (
|
|
285
|
-
previousBlock.checkpointNumber === block.checkpointNumber &&
|
|
286
|
-
previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1
|
|
287
|
-
) {
|
|
288
|
-
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
|
|
289
|
-
}
|
|
290
|
-
if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
|
|
291
|
-
throw new BlockArchiveNotConsistentError(
|
|
292
|
-
block.number,
|
|
293
|
-
previousBlock.number,
|
|
294
|
-
block.header.lastArchive.root,
|
|
295
|
-
previousBlock.archive.root,
|
|
296
|
-
);
|
|
297
|
-
}
|
|
298
|
-
} else {
|
|
299
|
-
// No previous block, must be block 1 at checkpoint index 0
|
|
300
|
-
if (block.indexWithinCheckpoint !== 0) {
|
|
301
|
-
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
|
|
302
|
-
}
|
|
303
|
-
if (block.number !== INITIAL_L2_BLOCK_NUM) {
|
|
304
|
-
throw new BlockNumberNotSequentialError(block.number, undefined);
|
|
305
|
-
}
|
|
306
|
-
}
|
|
362
|
+
// Validate block sequencing, indexes, and archive chaining
|
|
363
|
+
this.validateCheckpointBlocks(checkpoint.checkpoint.blocks, previousBlock);
|
|
307
364
|
|
|
308
|
-
|
|
309
|
-
|
|
365
|
+
// Store every block in the database (may already exist, but L1 data is authoritative)
|
|
366
|
+
for (let i = 0; i < checkpoint.checkpoint.blocks.length; i++) {
|
|
367
|
+
await this.addBlockToDatabase(checkpoint.checkpoint.blocks[i], checkpoint.checkpoint.number, i);
|
|
310
368
|
}
|
|
369
|
+
previousBlock = checkpoint.checkpoint.blocks.at(-1);
|
|
311
370
|
|
|
312
371
|
// Store the checkpoint in the database
|
|
313
372
|
await this.#checkpoints.set(checkpoint.checkpoint.number, {
|
|
@@ -319,17 +378,135 @@ export class BlockStore {
|
|
|
319
378
|
checkpointNumber: checkpoint.checkpoint.number,
|
|
320
379
|
startBlock: checkpoint.checkpoint.blocks[0].number,
|
|
321
380
|
blockCount: checkpoint.checkpoint.blocks.length,
|
|
381
|
+
feeAssetPriceModifier: checkpoint.checkpoint.feeAssetPriceModifier.toString(),
|
|
322
382
|
});
|
|
323
383
|
|
|
324
384
|
// Update slot-to-checkpoint index
|
|
325
385
|
await this.#slotToCheckpoint.set(checkpoint.checkpoint.header.slotNumber, checkpoint.checkpoint.number);
|
|
386
|
+
|
|
387
|
+
// Remove proposed checkpoint if it exists, since L1 is authoritative
|
|
388
|
+
await this.#proposedCheckpoints.delete(checkpoint.checkpoint.number);
|
|
389
|
+
|
|
390
|
+
// Drop any rejected entry for this archive root: a checkpoint that was previously rejected
|
|
391
|
+
// (e.g. invalid attestations) is now being ingested as valid, so its descendants are allowed.
|
|
392
|
+
await this.removeRejectedCheckpointByArchiveRoot(checkpoint.checkpoint.archive.root);
|
|
326
393
|
}
|
|
327
394
|
|
|
328
|
-
await this
|
|
329
|
-
return
|
|
395
|
+
await this.advanceSynchedL1BlockNumber(checkpoints[checkpoints.length - 1].l1.blockNumber);
|
|
396
|
+
return checkpoints;
|
|
330
397
|
});
|
|
331
398
|
}
|
|
332
399
|
|
|
400
|
+
/**
|
|
401
|
+
* Handles checkpoints at the start of a batch that are already stored (e.g. due to L1 reorg).
|
|
402
|
+
* Verifies the archive root matches, updates L1 metadata, and returns only the new checkpoints.
|
|
403
|
+
*/
|
|
404
|
+
private async skipOrUpdateAlreadyStoredCheckpoints(
|
|
405
|
+
checkpoints: PublishedCheckpoint[],
|
|
406
|
+
latestStored: CheckpointNumber,
|
|
407
|
+
): Promise<PublishedCheckpoint[]> {
|
|
408
|
+
let i = 0;
|
|
409
|
+
for (; i < checkpoints.length && checkpoints[i].checkpoint.number <= latestStored; i++) {
|
|
410
|
+
const incoming = checkpoints[i];
|
|
411
|
+
const stored = await this.getCheckpointData(incoming.checkpoint.number);
|
|
412
|
+
if (!stored) {
|
|
413
|
+
// Should not happen if latestStored is correct, but be safe
|
|
414
|
+
break;
|
|
415
|
+
}
|
|
416
|
+
// Verify the checkpoint content matches (archive root)
|
|
417
|
+
if (!stored.archive.root.equals(incoming.checkpoint.archive.root)) {
|
|
418
|
+
throw new Error(
|
|
419
|
+
`Checkpoint ${incoming.checkpoint.number} already exists in store but with a different archive root. ` +
|
|
420
|
+
`Stored: ${stored.archive.root}, incoming: ${incoming.checkpoint.archive.root}`,
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
// Update L1 metadata and attestations for the already-stored checkpoint
|
|
424
|
+
this.#log.warn(
|
|
425
|
+
`Checkpoint ${incoming.checkpoint.number} already stored, updating L1 info ` +
|
|
426
|
+
`(L1 block ${stored.l1.blockNumber} -> ${incoming.l1.blockNumber})`,
|
|
427
|
+
);
|
|
428
|
+
await this.#checkpoints.set(incoming.checkpoint.number, {
|
|
429
|
+
header: incoming.checkpoint.header.toBuffer(),
|
|
430
|
+
archive: incoming.checkpoint.archive.toBuffer(),
|
|
431
|
+
checkpointOutHash: incoming.checkpoint.getCheckpointOutHash().toBuffer(),
|
|
432
|
+
l1: incoming.l1.toBuffer(),
|
|
433
|
+
attestations: incoming.attestations.map(a => a.toBuffer()),
|
|
434
|
+
checkpointNumber: incoming.checkpoint.number,
|
|
435
|
+
startBlock: incoming.checkpoint.blocks[0].number,
|
|
436
|
+
blockCount: incoming.checkpoint.blocks.length,
|
|
437
|
+
feeAssetPriceModifier: incoming.checkpoint.feeAssetPriceModifier.toString(),
|
|
438
|
+
});
|
|
439
|
+
// Update the sync point to reflect the new L1 block
|
|
440
|
+
await this.advanceSynchedL1BlockNumber(incoming.l1.blockNumber);
|
|
441
|
+
}
|
|
442
|
+
return checkpoints.slice(i);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Gets the last block of the checkpoint before the given one.
|
|
447
|
+
* Returns undefined if there is no previous checkpoint (i.e. genesis).
|
|
448
|
+
*/
|
|
449
|
+
private async getPreviousCheckpointBlock(checkpointNumber: CheckpointNumber): Promise<L2Block | undefined> {
|
|
450
|
+
const previousCheckpointNumber = CheckpointNumber(checkpointNumber - 1);
|
|
451
|
+
if (previousCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
|
|
452
|
+
return undefined;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// Check across both proposed and mined checkpoints
|
|
456
|
+
const predecessor =
|
|
457
|
+
(await this.getProposedCheckpointByNumber(previousCheckpointNumber)) ??
|
|
458
|
+
(await this.getCheckpointData(previousCheckpointNumber));
|
|
459
|
+
|
|
460
|
+
if (!predecessor) {
|
|
461
|
+
throw new CheckpointNotFoundError(previousCheckpointNumber);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const previousBlockNumber = BlockNumber(predecessor.startBlock + predecessor.blockCount - 1);
|
|
465
|
+
const previousBlock = await this.getBlock({ number: previousBlockNumber });
|
|
466
|
+
if (previousBlock === undefined) {
|
|
467
|
+
throw new BlockNotFoundError(previousBlockNumber);
|
|
468
|
+
}
|
|
469
|
+
return previousBlock;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Validates that blocks are sequential, have correct indexes, and chain via archive roots.
|
|
474
|
+
* This is the same validation used for both confirmed checkpoints (addCheckpoints) and
|
|
475
|
+
* proposed checkpoints (addProposedCheckpoint).
|
|
476
|
+
*/
|
|
477
|
+
private validateCheckpointBlocks(blocks: L2Block[], previousBlock: L2Block | undefined): void {
|
|
478
|
+
for (const block of blocks) {
|
|
479
|
+
if (previousBlock) {
|
|
480
|
+
if (previousBlock.number !== block.number - 1) {
|
|
481
|
+
throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
|
|
482
|
+
}
|
|
483
|
+
if (previousBlock.checkpointNumber === block.checkpointNumber) {
|
|
484
|
+
if (previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1) {
|
|
485
|
+
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
|
|
486
|
+
}
|
|
487
|
+
} else if (block.indexWithinCheckpoint !== 0) {
|
|
488
|
+
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
|
|
489
|
+
}
|
|
490
|
+
if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
|
|
491
|
+
throw new BlockArchiveNotConsistentError(
|
|
492
|
+
block.number,
|
|
493
|
+
previousBlock.number,
|
|
494
|
+
block.header.lastArchive.root,
|
|
495
|
+
previousBlock.archive.root,
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
} else {
|
|
499
|
+
if (block.indexWithinCheckpoint !== 0) {
|
|
500
|
+
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
|
|
501
|
+
}
|
|
502
|
+
if (block.number !== INITIAL_L2_BLOCK_NUM) {
|
|
503
|
+
throw new BlockNumberNotSequentialError(block.number, undefined);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
previousBlock = block;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
333
510
|
private async addBlockToDatabase(block: L2Block, checkpointNumber: number, indexWithinCheckpoint: number) {
|
|
334
511
|
const blockHash = await block.hash();
|
|
335
512
|
|
|
@@ -347,6 +524,7 @@ export class BlockStore {
|
|
|
347
524
|
l2BlockNumber: block.number,
|
|
348
525
|
l2BlockHash: blockHash,
|
|
349
526
|
txIndexInBlock: i,
|
|
527
|
+
slotNumber: block.header.globalVariables.slotNumber,
|
|
350
528
|
};
|
|
351
529
|
await this.#txEffects.set(txEffect.data.txHash.toString(), serializeIndexedTxEffect(txEffect));
|
|
352
530
|
}
|
|
@@ -422,6 +600,9 @@ export class BlockStore {
|
|
|
422
600
|
this.#log.debug(`Removed checkpoint ${c}`);
|
|
423
601
|
}
|
|
424
602
|
|
|
603
|
+
// Evict all pending checkpoints > checkpointNumber (their base chain no longer exists)
|
|
604
|
+
await this.evictProposedCheckpointsFrom(CheckpointNumber(checkpointNumber + 1));
|
|
605
|
+
|
|
425
606
|
return { blocksRemoved };
|
|
426
607
|
});
|
|
427
608
|
}
|
|
@@ -446,6 +627,26 @@ export class BlockStore {
|
|
|
446
627
|
return checkpoints;
|
|
447
628
|
}
|
|
448
629
|
|
|
630
|
+
/**
|
|
631
|
+
* Returns up to `limit` checkpoints anchored at `fromSlot`, ordered nearest-first, walking the slot index.
|
|
632
|
+
* With `reverse`, takes the checkpoints at or before `fromSlot` (descending by slot); otherwise the
|
|
633
|
+
* checkpoints at or after it (ascending). `limit: 1, reverse: true` yields the latest checkpoint at or
|
|
634
|
+
* before the slot in a single range scan.
|
|
635
|
+
*/
|
|
636
|
+
async getCheckpointsBySlot(fromSlot: SlotNumber, limit: number, reverse: boolean): Promise<CheckpointData[]> {
|
|
637
|
+
// The KV range bounds are direction-dependent: forward is [start, end), reverse is (start, end], so a
|
|
638
|
+
// reverse scan uses `end: fromSlot` (inclusive) with no +1 to include the checkpoint at fromSlot itself.
|
|
639
|
+
const range = reverse ? { end: fromSlot, reverse: true, limit } : { start: fromSlot, limit };
|
|
640
|
+
const result: CheckpointData[] = [];
|
|
641
|
+
for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync(range)) {
|
|
642
|
+
const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
|
|
643
|
+
if (checkpointStorage) {
|
|
644
|
+
result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage));
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
return result;
|
|
648
|
+
}
|
|
649
|
+
|
|
449
650
|
/** Returns checkpoint data for all checkpoints whose slot falls within the given range (inclusive). */
|
|
450
651
|
async getCheckpointDataForSlotRange(startSlot: SlotNumber, endSlot: SlotNumber): Promise<CheckpointData[]> {
|
|
451
652
|
const result: CheckpointData[] = [];
|
|
@@ -461,6 +662,22 @@ export class BlockStore {
|
|
|
461
662
|
return result;
|
|
462
663
|
}
|
|
463
664
|
|
|
665
|
+
/**
|
|
666
|
+
* Returns the checkpoint numbers for all checkpoints whose slot falls within the given range (inclusive).
|
|
667
|
+
* Lighter than {@link getCheckpointDataForSlotRange} when callers only need to identify which
|
|
668
|
+
* checkpoints fall in the range and will fetch full data for at most a few of them.
|
|
669
|
+
*/
|
|
670
|
+
async getCheckpointNumbersForSlotRange(startSlot: SlotNumber, endSlot: SlotNumber): Promise<CheckpointNumber[]> {
|
|
671
|
+
const result: CheckpointNumber[] = [];
|
|
672
|
+
for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync({
|
|
673
|
+
start: startSlot,
|
|
674
|
+
end: endSlot + 1,
|
|
675
|
+
})) {
|
|
676
|
+
result.push(CheckpointNumber(checkpointNumber));
|
|
677
|
+
}
|
|
678
|
+
return result;
|
|
679
|
+
}
|
|
680
|
+
|
|
464
681
|
private checkpointDataFromCheckpointStorage(checkpointStorage: CheckpointStorage): CheckpointData {
|
|
465
682
|
return {
|
|
466
683
|
header: CheckpointHeader.fromBuffer(checkpointStorage.header),
|
|
@@ -469,6 +686,7 @@ export class BlockStore {
|
|
|
469
686
|
checkpointNumber: CheckpointNumber(checkpointStorage.checkpointNumber),
|
|
470
687
|
startBlock: BlockNumber(checkpointStorage.startBlock),
|
|
471
688
|
blockCount: checkpointStorage.blockCount,
|
|
689
|
+
feeAssetPriceModifier: BigInt(checkpointStorage.feeAssetPriceModifier),
|
|
472
690
|
l1: L1PublishedData.fromBuffer(checkpointStorage.l1),
|
|
473
691
|
attestations: checkpointStorage.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
|
|
474
692
|
};
|
|
@@ -527,11 +745,11 @@ export class BlockStore {
|
|
|
527
745
|
const removedBlocks: L2Block[] = [];
|
|
528
746
|
|
|
529
747
|
// Get the latest block number to determine the range
|
|
530
|
-
const latestBlockNumber = await this.
|
|
748
|
+
const latestBlockNumber = await this.getLatestL2BlockNumber();
|
|
531
749
|
|
|
532
750
|
// Iterate from blockNumber + 1 to latestBlockNumber
|
|
533
751
|
for (let bn = blockNumber + 1; bn <= latestBlockNumber; bn++) {
|
|
534
|
-
const block = await this.getBlock(BlockNumber(bn));
|
|
752
|
+
const block = await this.getBlock({ number: BlockNumber(bn) });
|
|
535
753
|
|
|
536
754
|
if (block === undefined) {
|
|
537
755
|
this.#log.warn(`Cannot remove block ${bn} from the store since we don't have it`);
|
|
@@ -560,13 +778,6 @@ export class BlockStore {
|
|
|
560
778
|
}
|
|
561
779
|
}
|
|
562
780
|
|
|
563
|
-
async getLatestBlockNumber(): Promise<BlockNumber> {
|
|
564
|
-
const [latestBlocknumber] = await toArray(this.#blocks.keysAsync({ reverse: true, limit: 1 }));
|
|
565
|
-
return typeof latestBlocknumber === 'number'
|
|
566
|
-
? BlockNumber(latestBlocknumber)
|
|
567
|
-
: BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
568
|
-
}
|
|
569
|
-
|
|
570
781
|
async getLatestCheckpointNumber(): Promise<CheckpointNumber> {
|
|
571
782
|
const [latestCheckpointNumber] = await toArray(this.#checkpoints.keysAsync({ reverse: true, limit: 1 }));
|
|
572
783
|
if (latestCheckpointNumber === undefined) {
|
|
@@ -575,175 +786,204 @@ export class BlockStore {
|
|
|
575
786
|
return CheckpointNumber(latestCheckpointNumber);
|
|
576
787
|
}
|
|
577
788
|
|
|
578
|
-
async
|
|
579
|
-
const
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
const block = await this.getBlockFromBlockStorage(number, blockStorage);
|
|
588
|
-
if (!block) {
|
|
589
|
-
return undefined;
|
|
789
|
+
async hasProposedCheckpoint(): Promise<boolean> {
|
|
790
|
+
const [key] = await toArray(this.#proposedCheckpoints.keysAsync({ limit: 1 }));
|
|
791
|
+
return key !== undefined;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** Deletes all pending proposed checkpoints from storage. */
|
|
795
|
+
async deleteProposedCheckpoints(): Promise<void> {
|
|
796
|
+
for await (const key of this.#proposedCheckpoints.keysAsync()) {
|
|
797
|
+
await this.#proposedCheckpoints.delete(key);
|
|
590
798
|
}
|
|
591
|
-
return new CheckpointedL2Block(
|
|
592
|
-
CheckpointNumber(checkpoint.checkpointNumber),
|
|
593
|
-
block,
|
|
594
|
-
L1PublishedData.fromBuffer(checkpoint.l1),
|
|
595
|
-
checkpoint.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
|
|
596
|
-
);
|
|
597
799
|
}
|
|
598
800
|
|
|
599
801
|
/**
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
*
|
|
603
|
-
* @
|
|
802
|
+
* Promotes a specific pending checkpoint to a confirmed checkpoint entry.
|
|
803
|
+
* This persists the checkpoint to the store, removes only that pending entry, and updates the L1 sync point.
|
|
804
|
+
* Remaining pending entries (e.g. N+1, N+2) are left intact — they chain off the just-promoted one.
|
|
805
|
+
* @param checkpointNumber - The checkpoint number to promote.
|
|
806
|
+
* @param l1 - L1 published data for the checkpoint.
|
|
807
|
+
* @param attestations - Committee attestations.
|
|
808
|
+
* @param expectedArchiveRoot - Archive root guard against races.
|
|
604
809
|
*/
|
|
605
|
-
async
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
const checkpointedBlock = new CheckpointedL2Block(
|
|
616
|
-
CheckpointNumber(checkpoint.checkpointNumber),
|
|
617
|
-
block,
|
|
618
|
-
L1PublishedData.fromBuffer(checkpoint.l1),
|
|
619
|
-
checkpoint.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
|
|
620
|
-
);
|
|
621
|
-
yield checkpointedBlock;
|
|
622
|
-
}
|
|
810
|
+
async promoteProposedToCheckpointed(
|
|
811
|
+
checkpointNumber: CheckpointNumber,
|
|
812
|
+
l1: L1PublishedData,
|
|
813
|
+
attestations: CommitteeAttestation[],
|
|
814
|
+
expectedArchiveRoot: Fr,
|
|
815
|
+
): Promise<void> {
|
|
816
|
+
return await this.db.transactionAsync(async () => {
|
|
817
|
+
const proposed = await this.getProposedCheckpointByNumber(checkpointNumber);
|
|
818
|
+
if (!proposed) {
|
|
819
|
+
throw new NoProposedCheckpointToPromoteError();
|
|
623
820
|
}
|
|
624
|
-
|
|
821
|
+
if (!proposed.archive.root.equals(expectedArchiveRoot)) {
|
|
822
|
+
throw new ProposedCheckpointArchiveRootMismatchError(expectedArchiveRoot, proposed.archive.root);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// Verify sequentiality: promoted checkpoint must follow the latest confirmed one
|
|
826
|
+
const latestCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
827
|
+
if (latestCheckpointNumber !== proposed.checkpointNumber - 1) {
|
|
828
|
+
throw new ProposedCheckpointPromotionNotSequentialError(proposed.checkpointNumber, latestCheckpointNumber);
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
// Write the checkpoint entry
|
|
832
|
+
await this.#checkpoints.set(proposed.checkpointNumber, {
|
|
833
|
+
header: proposed.header.toBuffer(),
|
|
834
|
+
archive: proposed.archive.toBuffer(),
|
|
835
|
+
checkpointOutHash: proposed.checkpointOutHash.toBuffer(),
|
|
836
|
+
l1: l1.toBuffer(),
|
|
837
|
+
attestations: attestations.map(attestation => attestation.toBuffer()),
|
|
838
|
+
checkpointNumber: proposed.checkpointNumber,
|
|
839
|
+
startBlock: proposed.startBlock,
|
|
840
|
+
blockCount: proposed.blockCount,
|
|
841
|
+
feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
|
|
842
|
+
});
|
|
843
|
+
|
|
844
|
+
// Update the slot-to-checkpoint index
|
|
845
|
+
await this.#slotToCheckpoint.set(proposed.header.slotNumber, proposed.checkpointNumber);
|
|
846
|
+
|
|
847
|
+
// Remove only this pending entry — remaining entries N+1, N+2, ... stay valid
|
|
848
|
+
await this.#proposedCheckpoints.delete(proposed.checkpointNumber);
|
|
849
|
+
|
|
850
|
+
// Drop any rejected entry for this archive root: a checkpoint that was previously rejected
|
|
851
|
+
// (e.g. invalid attestations) is now being promoted as valid, so its descendants are allowed.
|
|
852
|
+
await this.removeRejectedCheckpointByArchiveRoot(proposed.archive.root);
|
|
853
|
+
|
|
854
|
+
// Update the last synced L1 block
|
|
855
|
+
await this.advanceSynchedL1BlockNumber(l1.blockNumber);
|
|
856
|
+
});
|
|
625
857
|
}
|
|
626
858
|
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
859
|
+
/**
|
|
860
|
+
* Returns the latest pending checkpoint (highest-numbered entry), or undefined if none.
|
|
861
|
+
* No fallback to confirmed.
|
|
862
|
+
*/
|
|
863
|
+
async getLastProposedCheckpoint(): Promise<ProposedCheckpointData | undefined> {
|
|
864
|
+
const [key] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
|
|
865
|
+
if (key === undefined) {
|
|
630
866
|
return undefined;
|
|
631
867
|
}
|
|
632
|
-
|
|
868
|
+
const stored = await this.#proposedCheckpoints.getAsync(key);
|
|
869
|
+
return stored ? this.convertToProposedCheckpointData(stored) : undefined;
|
|
633
870
|
}
|
|
634
871
|
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
}
|
|
640
|
-
return this.getCheckpointedBlock(BlockNumber(blockNumber));
|
|
872
|
+
/** Returns the pending checkpoint for a specific checkpoint number, or undefined if not found. */
|
|
873
|
+
async getProposedCheckpointByNumber(n: CheckpointNumber): Promise<ProposedCheckpointData | undefined> {
|
|
874
|
+
const stored = await this.#proposedCheckpoints.getAsync(n);
|
|
875
|
+
return stored ? this.convertToProposedCheckpointData(stored) : undefined;
|
|
641
876
|
}
|
|
642
877
|
|
|
643
878
|
/**
|
|
644
|
-
*
|
|
645
|
-
*
|
|
646
|
-
*
|
|
647
|
-
* @returns The requested L2 blocks
|
|
879
|
+
* Returns the pending checkpoint whose header slot matches the given slot, or undefined if not found.
|
|
880
|
+
* Iterates `#proposedCheckpoints` rather than reading an index because the map carries 0–1 entries
|
|
881
|
+
* in normal operation (bounded by the proposer pipelining window). Returns the first match.
|
|
648
882
|
*/
|
|
649
|
-
async
|
|
650
|
-
for await (const [
|
|
651
|
-
const
|
|
652
|
-
if (
|
|
653
|
-
|
|
883
|
+
async getProposedCheckpointBySlot(slot: SlotNumber): Promise<ProposedCheckpointData | undefined> {
|
|
884
|
+
for await (const [, stored] of this.#proposedCheckpoints.entriesAsync()) {
|
|
885
|
+
const header = CheckpointHeader.fromBuffer(stored.header);
|
|
886
|
+
if (header.slotNumber === slot) {
|
|
887
|
+
return this.convertToProposedCheckpointData(stored);
|
|
654
888
|
}
|
|
655
889
|
}
|
|
890
|
+
return undefined;
|
|
656
891
|
}
|
|
657
892
|
|
|
658
893
|
/**
|
|
659
|
-
*
|
|
660
|
-
*
|
|
661
|
-
*
|
|
894
|
+
* Evicts all pending checkpoints with checkpoint number >= fromNumber.
|
|
895
|
+
* Used for divergent-mined-checkpoint cleanup: when L1 mines checkpoint N with a different archive,
|
|
896
|
+
* all pending >= N must be evicted since they chain off the now-invalid pending N.
|
|
662
897
|
*/
|
|
663
|
-
async
|
|
664
|
-
const
|
|
665
|
-
|
|
666
|
-
|
|
898
|
+
async evictProposedCheckpointsFrom(fromNumber: CheckpointNumber): Promise<void> {
|
|
899
|
+
const keysToDelete: number[] = [];
|
|
900
|
+
for await (const key of this.#proposedCheckpoints.keysAsync()) {
|
|
901
|
+
if (key >= fromNumber) {
|
|
902
|
+
keysToDelete.push(key);
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
for (const key of keysToDelete) {
|
|
906
|
+
await this.#proposedCheckpoints.delete(key);
|
|
667
907
|
}
|
|
668
|
-
return this.getBlockDataFromBlockStorage(blockStorage);
|
|
669
908
|
}
|
|
670
909
|
|
|
671
910
|
/**
|
|
672
|
-
* Gets
|
|
673
|
-
*
|
|
674
|
-
*
|
|
911
|
+
* Gets the checkpoint at the proposed tip:
|
|
912
|
+
* - latest pending checkpoint if any exist
|
|
913
|
+
* - fallsback to latest confirmed checkpoint otherwise
|
|
675
914
|
*/
|
|
676
|
-
async
|
|
677
|
-
const
|
|
678
|
-
if (
|
|
679
|
-
return
|
|
915
|
+
async getLastCheckpoint(): Promise<CommonCheckpointData | undefined> {
|
|
916
|
+
const latest = await this.getLastProposedCheckpoint();
|
|
917
|
+
if (!latest) {
|
|
918
|
+
return this.getCheckpointData(await this.getLatestCheckpointNumber());
|
|
680
919
|
}
|
|
681
|
-
return
|
|
920
|
+
return latest;
|
|
682
921
|
}
|
|
683
922
|
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
923
|
+
private convertToProposedCheckpointData(stored: ProposedCheckpointStorage): ProposedCheckpointData {
|
|
924
|
+
return {
|
|
925
|
+
checkpointNumber: CheckpointNumber(stored.checkpointNumber),
|
|
926
|
+
header: CheckpointHeader.fromBuffer(stored.header),
|
|
927
|
+
archive: AppendOnlyTreeSnapshot.fromBuffer(stored.archive),
|
|
928
|
+
checkpointOutHash: Fr.fromBuffer(stored.checkpointOutHash),
|
|
929
|
+
startBlock: BlockNumber(stored.startBlock),
|
|
930
|
+
blockCount: stored.blockCount,
|
|
931
|
+
totalManaUsed: BigInt(stored.totalManaUsed),
|
|
932
|
+
feeAssetPriceModifier: BigInt(stored.feeAssetPriceModifier),
|
|
933
|
+
};
|
|
695
934
|
}
|
|
696
935
|
|
|
697
936
|
/**
|
|
698
|
-
*
|
|
699
|
-
* @
|
|
700
|
-
* @returns The requested L2 block.
|
|
937
|
+
* Attempts to get the proposedCheckpoint's number, if there is not one, then fallback to the latest confirmed checkpoint number.
|
|
938
|
+
* @returns CheckpointNumber
|
|
701
939
|
*/
|
|
702
|
-
async
|
|
703
|
-
const
|
|
704
|
-
if (
|
|
705
|
-
return
|
|
940
|
+
async getProposedCheckpointNumber(): Promise<CheckpointNumber> {
|
|
941
|
+
const proposed = await this.getLastCheckpoint();
|
|
942
|
+
if (!proposed) {
|
|
943
|
+
return await this.getLatestCheckpointNumber();
|
|
706
944
|
}
|
|
707
|
-
return
|
|
945
|
+
return CheckpointNumber(proposed.checkpointNumber);
|
|
708
946
|
}
|
|
709
947
|
|
|
710
948
|
/**
|
|
711
|
-
*
|
|
712
|
-
* @
|
|
713
|
-
* @returns The requested L2 block.
|
|
949
|
+
* Attempts to get the proposedCheckpoint's block number, if there is not one, then fallback to the checkpointed block number
|
|
950
|
+
* @returns BlockNumber
|
|
714
951
|
*/
|
|
715
|
-
async
|
|
716
|
-
const
|
|
717
|
-
if (
|
|
718
|
-
return
|
|
952
|
+
async getProposedCheckpointL2BlockNumber(): Promise<BlockNumber> {
|
|
953
|
+
const proposed = await this.getLastCheckpoint();
|
|
954
|
+
if (!proposed) {
|
|
955
|
+
return await this.getCheckpointedL2BlockNumber();
|
|
719
956
|
}
|
|
720
|
-
return
|
|
957
|
+
return BlockNumber(proposed.startBlock + proposed.blockCount - 1);
|
|
721
958
|
}
|
|
722
959
|
|
|
723
|
-
/**
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
960
|
+
/** Returns the checkpoint number that contains the given slot (or undefined if not found). */
|
|
961
|
+
async getCheckpointNumberBySlot(slot: SlotNumber): Promise<CheckpointNumber | undefined> {
|
|
962
|
+
const checkpointNumber = await this.#slotToCheckpoint.getAsync(slot);
|
|
963
|
+
return checkpointNumber === undefined ? undefined : CheckpointNumber(checkpointNumber);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/** Gets a single L2 block matching the given resolved query. */
|
|
967
|
+
async getBlock(query: ResolvedBlockQuery): Promise<L2Block | undefined> {
|
|
968
|
+
const blockNumber = await this.getBlockNumber(query);
|
|
730
969
|
if (blockNumber === undefined) {
|
|
731
970
|
return undefined;
|
|
732
971
|
}
|
|
733
972
|
const blockStorage = await this.#blocks.getAsync(blockNumber);
|
|
734
|
-
if (!blockStorage
|
|
973
|
+
if (!blockStorage) {
|
|
735
974
|
return undefined;
|
|
736
975
|
}
|
|
737
|
-
return
|
|
976
|
+
return this.getBlockFromBlockStorage(blockNumber, blockStorage);
|
|
738
977
|
}
|
|
739
978
|
|
|
740
|
-
/**
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
979
|
+
/** Gets a collection of L2 blocks for a resolved range. */
|
|
980
|
+
getBlocks(query: ResolvedBlocksQuery): Promise<L2Block[]> {
|
|
981
|
+
return toArray(this.iterateBlocks(query));
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/** Gets single block metadata matching the given resolved query. */
|
|
985
|
+
async getBlockData(query: ResolvedBlockQuery): Promise<BlockData | undefined> {
|
|
986
|
+
const blockNumber = await this.getBlockNumber(query);
|
|
747
987
|
if (blockNumber === undefined) {
|
|
748
988
|
return undefined;
|
|
749
989
|
}
|
|
@@ -751,24 +991,36 @@ export class BlockStore {
|
|
|
751
991
|
if (!blockStorage || !blockStorage.header) {
|
|
752
992
|
return undefined;
|
|
753
993
|
}
|
|
754
|
-
return
|
|
994
|
+
return this.getBlockDataFromBlockStorage(blockStorage);
|
|
755
995
|
}
|
|
756
996
|
|
|
757
|
-
/**
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
async *
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
if (
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
997
|
+
/** Gets a collection of block metadata entries for a resolved range. */
|
|
998
|
+
getBlocksData(query: ResolvedBlocksQuery): Promise<BlockData[]> {
|
|
999
|
+
return toArray(this.iterateBlocksData(query));
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/** Async iterator over L2 blocks for a resolved range. */
|
|
1003
|
+
private async *iterateBlocks(query: ResolvedBlocksQuery): AsyncIterableIterator<L2Block> {
|
|
1004
|
+
const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
|
|
1005
|
+
for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)) {
|
|
1006
|
+
if (cap !== undefined && blockNumber > cap) {
|
|
1007
|
+
break;
|
|
1008
|
+
}
|
|
1009
|
+
const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
|
|
1010
|
+
if (block) {
|
|
1011
|
+
yield block;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/** Async iterator over block metadata for a resolved range. */
|
|
1017
|
+
private async *iterateBlocksData(query: ResolvedBlocksQuery): AsyncIterableIterator<BlockData> {
|
|
1018
|
+
const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
|
|
1019
|
+
for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)) {
|
|
1020
|
+
if (cap !== undefined && blockNumber > cap) {
|
|
1021
|
+
break;
|
|
770
1022
|
}
|
|
771
|
-
yield
|
|
1023
|
+
yield this.getBlockDataFromBlockStorage(blockStorage);
|
|
772
1024
|
}
|
|
773
1025
|
}
|
|
774
1026
|
|
|
@@ -785,11 +1037,29 @@ export class BlockStore {
|
|
|
785
1037
|
}
|
|
786
1038
|
}
|
|
787
1039
|
|
|
1040
|
+
/** Resolves a ResolvedBlockQuery discriminant to a block number, or undefined if not found. */
|
|
1041
|
+
async getBlockNumber(query: ResolvedBlockQuery): Promise<BlockNumber | undefined> {
|
|
1042
|
+
let blockNumber: BlockNumber | undefined;
|
|
1043
|
+
if ('number' in query) {
|
|
1044
|
+
blockNumber = query.number;
|
|
1045
|
+
} else if ('hash' in query) {
|
|
1046
|
+
const n = await this.#blockHashIndex.getAsync(query.hash.toString());
|
|
1047
|
+
blockNumber = n !== undefined ? BlockNumber(n) : undefined;
|
|
1048
|
+
} else {
|
|
1049
|
+
const n = await this.#blockArchiveIndex.getAsync(query.archive.toString());
|
|
1050
|
+
blockNumber = n !== undefined ? BlockNumber(n) : undefined;
|
|
1051
|
+
}
|
|
1052
|
+
if (blockNumber === undefined) {
|
|
1053
|
+
return undefined;
|
|
1054
|
+
}
|
|
1055
|
+
return blockNumber;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
788
1058
|
private getBlockDataFromBlockStorage(blockStorage: BlockStorage): BlockData {
|
|
789
1059
|
return {
|
|
790
1060
|
header: BlockHeader.fromBuffer(blockStorage.header),
|
|
791
1061
|
archive: AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),
|
|
792
|
-
blockHash:
|
|
1062
|
+
blockHash: BlockHash.fromBuffer(blockStorage.blockHash),
|
|
793
1063
|
checkpointNumber: CheckpointNumber(blockStorage.checkpointNumber),
|
|
794
1064
|
indexWithinCheckpoint: IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint),
|
|
795
1065
|
};
|
|
@@ -846,48 +1116,6 @@ export class BlockStore {
|
|
|
846
1116
|
return deserializeIndexedTxEffect(buffer);
|
|
847
1117
|
}
|
|
848
1118
|
|
|
849
|
-
/**
|
|
850
|
-
* Gets a receipt of a settled tx.
|
|
851
|
-
* @param txHash - The hash of a tx we try to get the receipt for.
|
|
852
|
-
* @returns The requested tx receipt (or undefined if not found).
|
|
853
|
-
*/
|
|
854
|
-
async getSettledTxReceipt(txHash: TxHash): Promise<TxReceipt | undefined> {
|
|
855
|
-
const txEffect = await this.getTxEffect(txHash);
|
|
856
|
-
if (!txEffect) {
|
|
857
|
-
return undefined;
|
|
858
|
-
}
|
|
859
|
-
|
|
860
|
-
const blockNumber = BlockNumber(txEffect.l2BlockNumber);
|
|
861
|
-
|
|
862
|
-
// Use existing archiver methods to determine finalization level
|
|
863
|
-
const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber] = await Promise.all([
|
|
864
|
-
this.getProvenBlockNumber(),
|
|
865
|
-
this.getCheckpointedL2BlockNumber(),
|
|
866
|
-
this.getFinalizedL2BlockNumber(),
|
|
867
|
-
]);
|
|
868
|
-
|
|
869
|
-
let status: TxStatus;
|
|
870
|
-
if (blockNumber <= finalizedBlockNumber) {
|
|
871
|
-
status = TxStatus.FINALIZED;
|
|
872
|
-
} else if (blockNumber <= provenBlockNumber) {
|
|
873
|
-
status = TxStatus.PROVEN;
|
|
874
|
-
} else if (blockNumber <= checkpointedBlockNumber) {
|
|
875
|
-
status = TxStatus.CHECKPOINTED;
|
|
876
|
-
} else {
|
|
877
|
-
status = TxStatus.PROPOSED;
|
|
878
|
-
}
|
|
879
|
-
|
|
880
|
-
return new TxReceipt(
|
|
881
|
-
txHash,
|
|
882
|
-
status,
|
|
883
|
-
TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode),
|
|
884
|
-
undefined,
|
|
885
|
-
txEffect.data.transactionFee.toBigInt(),
|
|
886
|
-
txEffect.l2BlockHash,
|
|
887
|
-
blockNumber,
|
|
888
|
-
);
|
|
889
|
-
}
|
|
890
|
-
|
|
891
1119
|
/**
|
|
892
1120
|
* Looks up which block included the requested tx effect.
|
|
893
1121
|
* @param txHash - The txHash of the tx.
|
|
@@ -898,10 +1126,45 @@ export class BlockStore {
|
|
|
898
1126
|
if (!txEffect) {
|
|
899
1127
|
return undefined;
|
|
900
1128
|
}
|
|
901
|
-
|
|
1129
|
+
// Read only the IndexedTxEffect header (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4)`); the
|
|
1130
|
+
// large tail (the full TxEffect with logs etc.) is irrelevant here.
|
|
1131
|
+
const view = Buffer.from(txEffect.buffer, txEffect.byteOffset, txEffect.byteLength);
|
|
1132
|
+
const l2BlockNumber = view.readUInt32BE(32);
|
|
1133
|
+
const txIndexInBlock = view.readUInt32BE(36);
|
|
902
1134
|
return [l2BlockNumber, txIndexInBlock];
|
|
903
1135
|
}
|
|
904
1136
|
|
|
1137
|
+
/**
|
|
1138
|
+
* Batched, partial deserializer that fetches `noteHashes` and `nullifiers` (all of them) for the given
|
|
1139
|
+
* txs. For each input txHash, returns a `[noteHashes, nullifiers]` tuple. Returns `[[], []]` for any
|
|
1140
|
+
* unknown txHash. Preserves input order. Used by the log read path when `includeEffects` is set to
|
|
1141
|
+
* attach effect data on demand without paying for a full {@link TxEffect} deserialization.
|
|
1142
|
+
*
|
|
1143
|
+
* The on-disk `IndexedTxEffect` layout starts with a fixed-length header
|
|
1144
|
+
* (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4) + slotNumber(4) + revertCode(1) + txHash(32) +
|
|
1145
|
+
* transactionFee(32)` = 109 bytes), followed by `noteHashes` and `nullifiers` (both u8-length-prefixed `Fr`
|
|
1146
|
+
* vectors). We
|
|
1147
|
+
* skip the header, then read the two vectors, and stop — the large tail (`l2ToL1Msgs`,
|
|
1148
|
+
* `publicDataWrites`, `privateLogs`, `publicLogs`, `contractClassLogs`) is never touched.
|
|
1149
|
+
*/
|
|
1150
|
+
public getNoteHashesAndNullifiers(txHashes: TxHash[]): Promise<[Fr[], Fr[]][]> {
|
|
1151
|
+
return Promise.all(
|
|
1152
|
+
txHashes.map(async (txHash): Promise<[Fr[], Fr[]]> => {
|
|
1153
|
+
const buffer = await this.#txEffects.getAsync(txHash.toString());
|
|
1154
|
+
if (!buffer) {
|
|
1155
|
+
return [[], []];
|
|
1156
|
+
}
|
|
1157
|
+
const reader = BufferReader.asReader(buffer);
|
|
1158
|
+
// Skip the fixed-length header: blockHash + l2BlockNumber + txIndexInBlock + slotNumber + revertCode +
|
|
1159
|
+
// txHash + transactionFee.
|
|
1160
|
+
reader.readBytes(32 + 4 + 4 + 4 + 1 + 32 + 32);
|
|
1161
|
+
const noteHashes = reader.readVectorUint8Prefix(Fr);
|
|
1162
|
+
const nullifiers = reader.readVectorUint8Prefix(Fr);
|
|
1163
|
+
return [noteHashes, nullifiers];
|
|
1164
|
+
}),
|
|
1165
|
+
);
|
|
1166
|
+
}
|
|
1167
|
+
|
|
905
1168
|
/**
|
|
906
1169
|
* Looks up which block deployed a particular contract.
|
|
907
1170
|
* @param contractAddress - The address of the contract to look up.
|
|
@@ -929,6 +1192,159 @@ export class BlockStore {
|
|
|
929
1192
|
return typeof lastBlockNumber === 'number' ? BlockNumber(lastBlockNumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
930
1193
|
}
|
|
931
1194
|
|
|
1195
|
+
/**
|
|
1196
|
+
* Resolves all four L2 chain tips (proposed, checkpointed, proven, finalized) in a single
|
|
1197
|
+
* read-only transaction so the snapshot is internally consistent. Each underlying record is
|
|
1198
|
+
* read at most once: latest block and latest confirmed checkpoint are loaded directly (no
|
|
1199
|
+
* separate "find the number, then look up data" hop), the proven/finalized checkpoint
|
|
1200
|
+
* singletons are read once and their storage entries are reused if they coincide with the
|
|
1201
|
+
* latest checkpoint, and per-tip block hashes are deduped when two tips land on the same block
|
|
1202
|
+
* (e.g. finalized == proven).
|
|
1203
|
+
*
|
|
1204
|
+
* The result is guaranteed to satisfy `finalized <= proven <= checkpointed <= proposed` (by
|
|
1205
|
+
* block number). Genesis is represented by `(INITIAL_L2_BLOCK_NUM - 1)` and the supplied
|
|
1206
|
+
* `genesisBlockHash`, paired with the synthetic genesis checkpoint id.
|
|
1207
|
+
*
|
|
1208
|
+
* @param genesisBlockHash - Block hash to report for the synthetic pre-initial block (used when
|
|
1209
|
+
* a tip is still at genesis).
|
|
1210
|
+
*/
|
|
1211
|
+
async getL2TipsData(genesisBlockHash: BlockHash): Promise<L2Tips> {
|
|
1212
|
+
return await this.db.transactionAsync(async () => {
|
|
1213
|
+
// Define genesis tips
|
|
1214
|
+
const genesisBlockNumber = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
1215
|
+
const genesisCheckpointNumber = CheckpointNumber(INITIAL_CHECKPOINT_NUMBER - 1);
|
|
1216
|
+
const genesisBlockId = { number: genesisBlockNumber, hash: genesisBlockHash.toString() };
|
|
1217
|
+
const genesisCheckpointId = {
|
|
1218
|
+
number: genesisCheckpointNumber,
|
|
1219
|
+
hash: GENESIS_CHECKPOINT_HEADER_HASH.toString(),
|
|
1220
|
+
};
|
|
1221
|
+
const genesisTip: L2TipId = { block: genesisBlockId, checkpoint: genesisCheckpointId };
|
|
1222
|
+
|
|
1223
|
+
// Load latest block and checkpoint entries
|
|
1224
|
+
const [latestBlockEntry] = await toArray(this.#blocks.entriesAsync({ reverse: true, limit: 1 }));
|
|
1225
|
+
const [latestCheckpointEntry] = await toArray(this.#checkpoints.entriesAsync({ reverse: true, limit: 1 }));
|
|
1226
|
+
const latestCheckpointNumber = latestCheckpointEntry
|
|
1227
|
+
? CheckpointNumber(latestCheckpointEntry[0])
|
|
1228
|
+
: genesisCheckpointNumber;
|
|
1229
|
+
|
|
1230
|
+
// Load proven and finalized checkpoint number pointers
|
|
1231
|
+
const [provenRaw, finalizedRaw] = await Promise.all([
|
|
1232
|
+
this.#lastProvenCheckpoint.getAsync(),
|
|
1233
|
+
this.#lastFinalizedCheckpoint.getAsync(),
|
|
1234
|
+
]);
|
|
1235
|
+
|
|
1236
|
+
// Clamp to enforce finalized <= proven <= checkpointed.
|
|
1237
|
+
const provenCheckpointNumber = CheckpointNumber(Math.min(provenRaw ?? 0, latestCheckpointNumber));
|
|
1238
|
+
const finalizedCheckpointNumber = CheckpointNumber(Math.min(finalizedRaw ?? 0, provenCheckpointNumber));
|
|
1239
|
+
|
|
1240
|
+
// Avoid loading the same checkpoint more than once
|
|
1241
|
+
const checkpointStorageCache = new Map<CheckpointNumber, CheckpointStorage>();
|
|
1242
|
+
if (latestCheckpointEntry) {
|
|
1243
|
+
checkpointStorageCache.set(CheckpointNumber(latestCheckpointEntry[0]), latestCheckpointEntry[1]);
|
|
1244
|
+
}
|
|
1245
|
+
const loadCheckpointStorage = async (n: CheckpointNumber): Promise<CheckpointStorage | undefined> => {
|
|
1246
|
+
if (n === 0) {
|
|
1247
|
+
return undefined;
|
|
1248
|
+
}
|
|
1249
|
+
if (!checkpointStorageCache.has(n)) {
|
|
1250
|
+
const checkpointStorage = await this.#checkpoints.getAsync(n);
|
|
1251
|
+
if (!checkpointStorage) {
|
|
1252
|
+
throw new CheckpointNotFoundError(n);
|
|
1253
|
+
}
|
|
1254
|
+
checkpointStorageCache.set(n, checkpointStorage);
|
|
1255
|
+
}
|
|
1256
|
+
return checkpointStorageCache.get(n)!;
|
|
1257
|
+
};
|
|
1258
|
+
|
|
1259
|
+
// Load proven and finalized checkpoint storage entries
|
|
1260
|
+
const provenCheckpoint = await loadCheckpointStorage(provenCheckpointNumber);
|
|
1261
|
+
const finalizedCheckpoint = await loadCheckpointStorage(finalizedCheckpointNumber);
|
|
1262
|
+
|
|
1263
|
+
// Avoid loading the same block hash multiple times when tips land on the same block
|
|
1264
|
+
const blockHashCache = new Map<number, string>();
|
|
1265
|
+
blockHashCache.set(genesisBlockNumber, genesisBlockHash.toString());
|
|
1266
|
+
if (latestBlockEntry) {
|
|
1267
|
+
blockHashCache.set(latestBlockEntry[0], BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString());
|
|
1268
|
+
}
|
|
1269
|
+
const loadBlockHash = async (n: BlockNumber): Promise<string> => {
|
|
1270
|
+
if (!blockHashCache.has(n)) {
|
|
1271
|
+
const blockStorage = await this.#blocks.getAsync(n);
|
|
1272
|
+
if (!blockStorage) {
|
|
1273
|
+
throw new BlockNotFoundError(n);
|
|
1274
|
+
}
|
|
1275
|
+
const blockHash = BlockHash.fromBuffer(blockStorage.blockHash).toString();
|
|
1276
|
+
blockHashCache.set(n, blockHash);
|
|
1277
|
+
}
|
|
1278
|
+
return blockHashCache.get(n)!;
|
|
1279
|
+
};
|
|
1280
|
+
|
|
1281
|
+
// Build proposed chain tip (this one has block only, no checkpoint)
|
|
1282
|
+
const proposedBlockId =
|
|
1283
|
+
latestBlockEntry === undefined
|
|
1284
|
+
? genesisBlockId
|
|
1285
|
+
: {
|
|
1286
|
+
number: BlockNumber(latestBlockEntry[0]),
|
|
1287
|
+
hash: BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString(),
|
|
1288
|
+
};
|
|
1289
|
+
|
|
1290
|
+
// Build other tips from checkpoint data, reading corresponding block data from the cache
|
|
1291
|
+
const buildTipFromCheckpoint = async (
|
|
1292
|
+
stored: ProposedCheckpointStorage | CheckpointStorage | undefined,
|
|
1293
|
+
): Promise<L2TipId> => {
|
|
1294
|
+
if (!stored) {
|
|
1295
|
+
return genesisTip;
|
|
1296
|
+
}
|
|
1297
|
+
const blockNumber = BlockNumber(stored.startBlock + stored.blockCount - 1);
|
|
1298
|
+
const blockHash = await loadBlockHash(blockNumber);
|
|
1299
|
+
const header = CheckpointHeader.fromBuffer(stored.header);
|
|
1300
|
+
return {
|
|
1301
|
+
block: { number: blockNumber, hash: blockHash },
|
|
1302
|
+
checkpoint: { number: CheckpointNumber(stored.checkpointNumber), hash: header.hash().toString() },
|
|
1303
|
+
};
|
|
1304
|
+
};
|
|
1305
|
+
|
|
1306
|
+
const checkpointedTip = await buildTipFromCheckpoint(latestCheckpointEntry?.[1]);
|
|
1307
|
+
const provenTip = await buildTipFromCheckpoint(provenCheckpoint);
|
|
1308
|
+
const finalizedTip = await buildTipFromCheckpoint(finalizedCheckpoint);
|
|
1309
|
+
|
|
1310
|
+
// A checkpointed block past the latest stored block would mean a checkpoint
|
|
1311
|
+
// references blocks that aren't in blocks.
|
|
1312
|
+
if (proposedBlockId.number < checkpointedTip.block.number) {
|
|
1313
|
+
throw new Error(
|
|
1314
|
+
`Inconsistent block store: latest block ${proposedBlockId.number} is behind checkpointed block ${checkpointedTip.block.number}`,
|
|
1315
|
+
);
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
// Assert that checkpoint numbers are increasing
|
|
1319
|
+
if (
|
|
1320
|
+
finalizedTip.checkpoint.number > provenTip.checkpoint.number ||
|
|
1321
|
+
provenTip.checkpoint.number > checkpointedTip.checkpoint.number
|
|
1322
|
+
) {
|
|
1323
|
+
throw new Error(
|
|
1324
|
+
`Inconsistent checkpoint numbers in chain tips: finalized=${finalizedTip.checkpoint.number} proven=${provenTip.checkpoint.number} checkpointed=${checkpointedTip.checkpoint.number}`,
|
|
1325
|
+
);
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
// Assert block numbers are increasing
|
|
1329
|
+
if (
|
|
1330
|
+
finalizedTip.block.number > provenTip.block.number ||
|
|
1331
|
+
provenTip.block.number > checkpointedTip.block.number ||
|
|
1332
|
+
checkpointedTip.block.number > proposedBlockId.number
|
|
1333
|
+
) {
|
|
1334
|
+
throw new Error(
|
|
1335
|
+
`Inconsistent block numbers in chain tips: finalized=${finalizedTip.block.number} proven=${provenTip.block.number} checkpointed=${checkpointedTip.block.number} proposed=${proposedBlockId.number}`,
|
|
1336
|
+
);
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
return {
|
|
1340
|
+
proposed: proposedBlockId,
|
|
1341
|
+
checkpointed: checkpointedTip,
|
|
1342
|
+
proven: provenTip,
|
|
1343
|
+
finalized: finalizedTip,
|
|
1344
|
+
};
|
|
1345
|
+
});
|
|
1346
|
+
}
|
|
1347
|
+
|
|
932
1348
|
/**
|
|
933
1349
|
* Gets the most recent L1 block processed.
|
|
934
1350
|
* @returns The L1 block that published the latest L2 block
|
|
@@ -941,14 +1357,62 @@ export class BlockStore {
|
|
|
941
1357
|
return this.#lastSynchedL1Block.set(l1BlockNumber);
|
|
942
1358
|
}
|
|
943
1359
|
|
|
1360
|
+
/**
|
|
1361
|
+
* Adds a proposed checkpoint to the pending queue.
|
|
1362
|
+
* Accepts proposed.checkpointNumber === latestTip + 1, where latestTip is the highest of
|
|
1363
|
+
* confirmed and the highest pending checkpoint number.
|
|
1364
|
+
* Computes archive and checkpointOutHash from the stored blocks.
|
|
1365
|
+
*/
|
|
1366
|
+
async addProposedCheckpoint(proposed: ProposedCheckpointInput) {
|
|
1367
|
+
return await this.db.transactionAsync(async () => {
|
|
1368
|
+
const confirmed = await this.getLatestCheckpointNumber();
|
|
1369
|
+
const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
|
|
1370
|
+
const latestTip = CheckpointNumber(
|
|
1371
|
+
latestPendingKey !== undefined ? Math.max(latestPendingKey, confirmed) : confirmed,
|
|
1372
|
+
);
|
|
1373
|
+
|
|
1374
|
+
if (proposed.checkpointNumber !== latestTip + 1) {
|
|
1375
|
+
throw new ProposedCheckpointNotSequentialError(proposed.checkpointNumber, latestTip);
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// Ensure the predecessor block (from pending or confirmed chain) exists
|
|
1379
|
+
const previousBlock = await this.getPreviousCheckpointBlock(proposed.checkpointNumber);
|
|
1380
|
+
const blocks: L2Block[] = [];
|
|
1381
|
+
for (let i = 0; i < proposed.blockCount; i++) {
|
|
1382
|
+
const block = await this.getBlock({ number: BlockNumber(proposed.startBlock + i) });
|
|
1383
|
+
if (!block) {
|
|
1384
|
+
throw new BlockNotFoundError(proposed.startBlock + i);
|
|
1385
|
+
}
|
|
1386
|
+
blocks.push(block);
|
|
1387
|
+
}
|
|
1388
|
+
this.validateCheckpointBlocks(blocks, previousBlock);
|
|
1389
|
+
|
|
1390
|
+
const archive = blocks[blocks.length - 1].archive;
|
|
1391
|
+
const checkpointOutHash = Checkpoint.getCheckpointOutHash(blocks);
|
|
1392
|
+
|
|
1393
|
+
await this.#proposedCheckpoints.set(proposed.checkpointNumber, {
|
|
1394
|
+
header: proposed.header.toBuffer(),
|
|
1395
|
+
archive: archive.toBuffer(),
|
|
1396
|
+
checkpointOutHash: checkpointOutHash.toBuffer(),
|
|
1397
|
+
checkpointNumber: proposed.checkpointNumber,
|
|
1398
|
+
startBlock: proposed.startBlock,
|
|
1399
|
+
blockCount: proposed.blockCount,
|
|
1400
|
+
totalManaUsed: proposed.totalManaUsed.toString(),
|
|
1401
|
+
feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
|
|
1402
|
+
});
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
|
|
944
1406
|
async getProvenCheckpointNumber(): Promise<CheckpointNumber> {
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
1407
|
+
return await this.db.transactionAsync(async () => {
|
|
1408
|
+
const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
|
|
1409
|
+
this.getLatestCheckpointNumber(),
|
|
1410
|
+
this.#lastProvenCheckpoint.getAsync(),
|
|
1411
|
+
]);
|
|
1412
|
+
return (provenCheckpointNumber ?? 0) > latestCheckpointNumber
|
|
1413
|
+
? latestCheckpointNumber
|
|
1414
|
+
: CheckpointNumber(provenCheckpointNumber ?? 0);
|
|
1415
|
+
});
|
|
952
1416
|
}
|
|
953
1417
|
|
|
954
1418
|
async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber) {
|
|
@@ -957,13 +1421,15 @@ export class BlockStore {
|
|
|
957
1421
|
}
|
|
958
1422
|
|
|
959
1423
|
async getFinalizedCheckpointNumber(): Promise<CheckpointNumber> {
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
1424
|
+
return await this.db.transactionAsync(async () => {
|
|
1425
|
+
const [provenCheckpointNumber, finalizedCheckpointNumber] = await Promise.all([
|
|
1426
|
+
this.getProvenCheckpointNumber(),
|
|
1427
|
+
this.#lastFinalizedCheckpoint.getAsync(),
|
|
1428
|
+
]);
|
|
1429
|
+
return (finalizedCheckpointNumber ?? 0) > provenCheckpointNumber
|
|
1430
|
+
? provenCheckpointNumber
|
|
1431
|
+
: CheckpointNumber(finalizedCheckpointNumber ?? 0);
|
|
1432
|
+
});
|
|
967
1433
|
}
|
|
968
1434
|
|
|
969
1435
|
setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber) {
|
|
@@ -1006,4 +1472,80 @@ export class BlockStore {
|
|
|
1006
1472
|
await this.#pendingChainValidationStatus.delete();
|
|
1007
1473
|
}
|
|
1008
1474
|
}
|
|
1475
|
+
|
|
1476
|
+
/** Records a rejected-checkpoint entry, keyed by its own archive root. */
|
|
1477
|
+
async addRejectedCheckpoint(entry: RejectedCheckpoint): Promise<void> {
|
|
1478
|
+
const archiveRootHex = entry.archiveRoot.toString();
|
|
1479
|
+
await this.#rejectedCheckpoints.set(archiveRootHex, {
|
|
1480
|
+
checkpointNumber: entry.checkpointNumber,
|
|
1481
|
+
archiveRoot: entry.archiveRoot.toBuffer(),
|
|
1482
|
+
parentArchiveRoot: entry.parentArchiveRoot.toBuffer(),
|
|
1483
|
+
slotNumber: entry.slotNumber,
|
|
1484
|
+
l1: entry.l1.toBuffer(),
|
|
1485
|
+
reason: entry.reason,
|
|
1486
|
+
});
|
|
1487
|
+
await this.#rejectedCheckpointsByNumber.set(entry.checkpointNumber, archiveRootHex);
|
|
1488
|
+
await this.advanceSynchedL1BlockNumber(entry.l1.blockNumber);
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
/** Returns the rejected-checkpoint entry with the given archive root, or undefined if not present. */
|
|
1492
|
+
async getRejectedCheckpointByArchiveRoot(archiveRoot: Fr): Promise<RejectedCheckpoint | undefined> {
|
|
1493
|
+
const stored = await this.#rejectedCheckpoints.getAsync(archiveRoot.toString());
|
|
1494
|
+
return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
/** Returns the rejected-checkpoint entry recorded for the given checkpoint number, or undefined if none. */
|
|
1498
|
+
async getRejectedCheckpointByNumber(checkpointNumber: CheckpointNumber): Promise<RejectedCheckpoint | undefined> {
|
|
1499
|
+
const archiveRootHex = await this.#rejectedCheckpointsByNumber.getAsync(checkpointNumber);
|
|
1500
|
+
if (archiveRootHex === undefined) {
|
|
1501
|
+
return undefined;
|
|
1502
|
+
}
|
|
1503
|
+
const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
|
|
1504
|
+
return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
/** Returns the highest checkpoint number recorded across all rejected entries, or `INITIAL_CHECKPOINT_NUMBER - 1` if none. */
|
|
1508
|
+
async getLatestRejectedCheckpointNumber(): Promise<CheckpointNumber> {
|
|
1509
|
+
const [latest] = await toArray(this.#rejectedCheckpointsByNumber.keysAsync({ reverse: true, limit: 1 }));
|
|
1510
|
+
return CheckpointNumber(latest ?? INITIAL_CHECKPOINT_NUMBER - 1);
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
/** Removes a rejected-checkpoint entry by its archive root (used when an entry no longer matches L1). */
|
|
1514
|
+
async removeRejectedCheckpointByArchiveRoot(archiveRoot: Fr): Promise<void> {
|
|
1515
|
+
const archiveRootHex = archiveRoot.toString();
|
|
1516
|
+
const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
|
|
1517
|
+
await this.#rejectedCheckpoints.delete(archiveRootHex);
|
|
1518
|
+
if (stored) {
|
|
1519
|
+
// Only clear the by-number index if it still points at this archive root, so a distinct
|
|
1520
|
+
// entry that shares the checkpoint number (e.g. an L1 reorg replacement) is not dropped.
|
|
1521
|
+
const indexed = await this.#rejectedCheckpointsByNumber.getAsync(stored.checkpointNumber);
|
|
1522
|
+
if (indexed === archiveRootHex) {
|
|
1523
|
+
await this.#rejectedCheckpointsByNumber.delete(stored.checkpointNumber);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
/**
|
|
1529
|
+
* Advances the stored last-synched L1 block number to `l1BlockNumber` only if it is strictly
|
|
1530
|
+
* greater than the current value. Use this whenever ingesting checkpoint-shaped data so the
|
|
1531
|
+
* sync pointer never walks backwards on out-of-order writes (e.g. an invalid checkpoint
|
|
1532
|
+
* advance followed by a valid-checkpoint commit landing at an earlier L1 block).
|
|
1533
|
+
*/
|
|
1534
|
+
private async advanceSynchedL1BlockNumber(l1BlockNumber: bigint): Promise<void> {
|
|
1535
|
+
const current = await this.#lastSynchedL1Block.getAsync();
|
|
1536
|
+
if (current === undefined || l1BlockNumber > current) {
|
|
1537
|
+
await this.#lastSynchedL1Block.set(l1BlockNumber);
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
private rejectedCheckpointFromStorage(stored: RejectedCheckpointStorage): RejectedCheckpoint {
|
|
1542
|
+
return {
|
|
1543
|
+
checkpointNumber: CheckpointNumber(stored.checkpointNumber),
|
|
1544
|
+
archiveRoot: Fr.fromBuffer(stored.archiveRoot),
|
|
1545
|
+
parentArchiveRoot: Fr.fromBuffer(stored.parentArchiveRoot),
|
|
1546
|
+
slotNumber: SlotNumber(stored.slotNumber),
|
|
1547
|
+
l1: L1PublishedData.fromBuffer(stored.l1),
|
|
1548
|
+
reason: stored.reason,
|
|
1549
|
+
};
|
|
1550
|
+
}
|
|
1009
1551
|
}
|