@aztec/archiver 0.0.1-commit.f504929 → 0.0.1-commit.f5a9928
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 -13
- package/dest/archiver.d.ts +73 -18
- package/dest/archiver.d.ts.map +1 -1
- package/dest/archiver.js +321 -81
- package/dest/config.d.ts +7 -3
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +43 -14
- 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 +20 -9
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +85 -37
- 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 +73 -50
- 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 +42 -17
- package/dest/modules/data_store_updater.d.ts.map +1 -1
- package/dest/modules/data_store_updater.js +198 -123
- 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 +14 -8
- package/dest/modules/l1_synchronizer.d.ts.map +1 -1
- package/dest/modules/l1_synchronizer.js +477 -213
- package/dest/modules/outbox_trees_resolver.d.ts +64 -0
- package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
- package/dest/modules/outbox_trees_resolver.js +184 -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 +186 -78
- package/dest/store/block_store.d.ts.map +1 -1
- package/dest/store/block_store.js +763 -290
- 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 +58 -6
- 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 +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 +117 -21
- package/dest/test/mock_l2_block_source.d.ts +51 -52
- package/dest/test/mock_l2_block_source.d.ts.map +1 -1
- package/dest/test/mock_l2_block_source.js +232 -180
- 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 +15 -3
- package/dest/test/noop_l1_archiver.d.ts +17 -6
- package/dest/test/noop_l1_archiver.d.ts.map +1 -1
- package/dest/test/noop_l1_archiver.js +31 -11
- package/package.json +15 -14
- package/src/archiver.ts +415 -90
- package/src/config.ts +51 -13
- package/src/errors.ts +122 -21
- package/src/factory.ts +99 -30
- 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 +327 -189
- package/src/modules/data_store_updater.ts +235 -155
- package/src/modules/instrumentation.ts +43 -10
- package/src/modules/l1_synchronizer.ts +646 -259
- package/src/modules/outbox_trees_resolver.ts +220 -0
- package/src/modules/validation.ts +80 -23
- package/src/store/block_store.ts +930 -348
- package/src/store/contract_class_store.ts +49 -103
- package/src/store/contract_instance_store.ts +74 -11
- 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 +60 -10
- package/src/structs/inbox_message.ts +1 -1
- package/src/test/fake_l1_state.ts +145 -32
- package/src/test/mock_l2_block_source.ts +292 -227
- package/src/test/mock_structs.ts +25 -8
- package/src/test/noop_l1_archiver.ts +61 -12
- 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
package/src/store/block_store.ts
CHANGED
|
@@ -12,15 +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 {
|
|
23
|
-
|
|
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';
|
|
24
33
|
import { CheckpointHeader } from '@aztec/stdlib/rollup';
|
|
25
34
|
import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
|
|
26
35
|
import {
|
|
@@ -28,26 +37,28 @@ import {
|
|
|
28
37
|
type IndexedTxEffect,
|
|
29
38
|
TxEffect,
|
|
30
39
|
TxHash,
|
|
31
|
-
TxReceipt,
|
|
32
|
-
TxStatus,
|
|
33
40
|
deserializeIndexedTxEffect,
|
|
34
41
|
serializeIndexedTxEffect,
|
|
35
42
|
} from '@aztec/stdlib/tx';
|
|
36
43
|
|
|
37
44
|
import {
|
|
45
|
+
BlockAlreadyCheckpointedError,
|
|
38
46
|
BlockArchiveNotConsistentError,
|
|
47
|
+
BlockCheckpointNumberNotSequentialError,
|
|
39
48
|
BlockIndexNotSequentialError,
|
|
40
49
|
BlockNotFoundError,
|
|
41
50
|
BlockNumberNotSequentialError,
|
|
42
51
|
CannotOverwriteCheckpointedBlockError,
|
|
43
52
|
CheckpointNotFoundError,
|
|
44
|
-
CheckpointNumberNotConsistentError,
|
|
45
53
|
CheckpointNumberNotSequentialError,
|
|
46
|
-
InitialBlockNumberNotSequentialError,
|
|
47
54
|
InitialCheckpointNumberNotSequentialError,
|
|
55
|
+
NoProposedCheckpointToPromoteError,
|
|
56
|
+
ProposedCheckpointArchiveRootMismatchError,
|
|
57
|
+
ProposedCheckpointNotSequentialError,
|
|
58
|
+
ProposedCheckpointPromotionNotSequentialError,
|
|
48
59
|
} from '../errors.js';
|
|
49
60
|
|
|
50
|
-
export {
|
|
61
|
+
export type { TxEffect, TxHash, TxReceipt } from '@aztec/stdlib/tx';
|
|
51
62
|
|
|
52
63
|
type BlockIndexValue = [blockNumber: number, index: number];
|
|
53
64
|
|
|
@@ -59,19 +70,78 @@ type BlockStorage = {
|
|
|
59
70
|
indexWithinCheckpoint: number;
|
|
60
71
|
};
|
|
61
72
|
|
|
62
|
-
|
|
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 = {
|
|
63
110
|
header: Buffer;
|
|
64
111
|
archive: Buffer;
|
|
65
112
|
checkpointOutHash: Buffer;
|
|
66
113
|
checkpointNumber: number;
|
|
67
114
|
startBlock: number;
|
|
68
115
|
blockCount: number;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
type CheckpointStorage = CommonCheckpointStorage & {
|
|
69
119
|
l1: Buffer;
|
|
70
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;
|
|
71
128
|
};
|
|
72
129
|
|
|
73
130
|
export type RemoveCheckpointsResult = { blocksRemoved: L2Block[] | undefined };
|
|
74
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
|
+
|
|
75
145
|
/**
|
|
76
146
|
* LMDB-based block storage for the archiver.
|
|
77
147
|
*/
|
|
@@ -79,7 +149,10 @@ export class BlockStore {
|
|
|
79
149
|
/** Map block number to block data */
|
|
80
150
|
#blocks: AztecAsyncMap<number, BlockStorage>;
|
|
81
151
|
|
|
82
|
-
/** 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 */
|
|
83
156
|
#checkpoints: AztecAsyncMap<number, CheckpointStorage>;
|
|
84
157
|
|
|
85
158
|
/** Map slot number to checkpoint number, for looking up checkpoints by slot range. */
|
|
@@ -97,6 +170,9 @@ export class BlockStore {
|
|
|
97
170
|
/** Stores last proven checkpoint */
|
|
98
171
|
#lastProvenCheckpoint: AztecAsyncSingleton<number>;
|
|
99
172
|
|
|
173
|
+
/** Stores last finalized checkpoint (proven at or before the finalized L1 block) */
|
|
174
|
+
#lastFinalizedCheckpoint: AztecAsyncSingleton<number>;
|
|
175
|
+
|
|
100
176
|
/** Stores the pending chain validation status */
|
|
101
177
|
#pendingChainValidationStatus: AztecAsyncSingleton<Buffer>;
|
|
102
178
|
|
|
@@ -109,12 +185,15 @@ export class BlockStore {
|
|
|
109
185
|
/** Index mapping block archive to block number */
|
|
110
186
|
#blockArchiveIndex: AztecAsyncMap<string, number>;
|
|
111
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
|
+
|
|
112
194
|
#log = createLogger('archiver:block_store');
|
|
113
195
|
|
|
114
|
-
constructor(
|
|
115
|
-
private db: AztecAsyncKVStore,
|
|
116
|
-
private l1Constants: Pick<L1RollupConstants, 'epochDuration'>,
|
|
117
|
-
) {
|
|
196
|
+
constructor(private db: AztecAsyncKVStore) {
|
|
118
197
|
this.#blocks = db.openMap('archiver_blocks');
|
|
119
198
|
this.#blockTxs = db.openMap('archiver_block_txs');
|
|
120
199
|
this.#txEffects = db.openMap('archiver_tx_effects');
|
|
@@ -123,160 +202,148 @@ export class BlockStore {
|
|
|
123
202
|
this.#blockArchiveIndex = db.openMap('archiver_block_archive_index');
|
|
124
203
|
this.#lastSynchedL1Block = db.openSingleton('archiver_last_synched_l1_block');
|
|
125
204
|
this.#lastProvenCheckpoint = db.openSingleton('archiver_last_proven_l2_checkpoint');
|
|
205
|
+
this.#lastFinalizedCheckpoint = db.openSingleton('archiver_last_finalized_l2_checkpoint');
|
|
126
206
|
this.#pendingChainValidationStatus = db.openSingleton('archiver_pending_chain_validation_status');
|
|
127
207
|
this.#checkpoints = db.openMap('archiver_checkpoints');
|
|
128
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');
|
|
129
212
|
}
|
|
130
213
|
|
|
131
214
|
/**
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
* TODO(#13569): Compute proper finalized block number based on L1 finalized block.
|
|
135
|
-
* TODO(palla/mbps): Even the provisional computation is wrong, since it should subtract checkpoints, not blocks
|
|
215
|
+
* Returns the finalized L2 block number. An L2 block is finalized when it was proven
|
|
216
|
+
* in an L1 block that has itself been finalized on Ethereum.
|
|
136
217
|
* @returns The finalized block number.
|
|
137
218
|
*/
|
|
138
219
|
async getFinalizedL2BlockNumber(): Promise<BlockNumber> {
|
|
139
|
-
const
|
|
140
|
-
|
|
220
|
+
const finalizedCheckpointNumber = await this.getFinalizedCheckpointNumber();
|
|
221
|
+
if (finalizedCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
|
|
222
|
+
return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
223
|
+
}
|
|
224
|
+
const checkpointStorage = await this.#checkpoints.getAsync(finalizedCheckpointNumber);
|
|
225
|
+
if (!checkpointStorage) {
|
|
226
|
+
throw new CheckpointNotFoundError(finalizedCheckpointNumber);
|
|
227
|
+
}
|
|
228
|
+
return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
|
|
141
229
|
}
|
|
142
230
|
|
|
143
231
|
/**
|
|
144
|
-
* Append new proposed
|
|
145
|
-
*
|
|
232
|
+
* Append a new proposed block to the store.
|
|
233
|
+
* This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
|
|
146
234
|
* For checkpointed blocks (already published to L1), use addCheckpoints() instead.
|
|
147
|
-
* @param
|
|
235
|
+
* @param block - The proposed L2 block to be added to the store.
|
|
148
236
|
* @returns True if the operation is successful.
|
|
149
237
|
*/
|
|
150
|
-
async
|
|
151
|
-
if (blocks.length === 0) {
|
|
152
|
-
return true;
|
|
153
|
-
}
|
|
154
|
-
|
|
238
|
+
async addProposedBlock(block: L2Block, opts: { force?: boolean } = {}): Promise<boolean> {
|
|
155
239
|
return await this.db.transactionAsync(async () => {
|
|
156
|
-
|
|
157
|
-
const
|
|
158
|
-
const
|
|
159
|
-
const
|
|
160
|
-
const firstBlockLastArchive = blocks[0].header.lastArchive.root;
|
|
240
|
+
const blockNumber = block.number;
|
|
241
|
+
const blockCheckpointNumber = block.checkpointNumber;
|
|
242
|
+
const blockIndex = block.indexWithinCheckpoint;
|
|
243
|
+
const blockLastArchive = block.header.lastArchive.root;
|
|
161
244
|
|
|
162
245
|
// Extract the latest block and checkpoint numbers
|
|
163
|
-
const previousBlockNumber = await this.
|
|
164
|
-
const
|
|
246
|
+
const previousBlockNumber = await this.getLatestL2BlockNumber();
|
|
247
|
+
const latestCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
165
248
|
|
|
166
249
|
// Verify we're not overwriting checkpointed blocks
|
|
167
250
|
const lastCheckpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
|
|
168
|
-
if (!opts.force &&
|
|
169
|
-
|
|
251
|
+
if (!opts.force && blockNumber <= lastCheckpointedBlockNumber) {
|
|
252
|
+
// Check if the proposed block matches the already-checkpointed one
|
|
253
|
+
const existingBlock = await this.getBlockData({ number: BlockNumber(blockNumber) });
|
|
254
|
+
if (existingBlock && existingBlock.archive.root.equals(block.archive.root)) {
|
|
255
|
+
throw new BlockAlreadyCheckpointedError(blockNumber);
|
|
256
|
+
}
|
|
257
|
+
throw new CannotOverwriteCheckpointedBlockError(blockNumber, lastCheckpointedBlockNumber);
|
|
170
258
|
}
|
|
171
259
|
|
|
172
|
-
// Check that the
|
|
173
|
-
if (!opts.force && previousBlockNumber !==
|
|
174
|
-
throw new
|
|
260
|
+
// Check that the block number is the expected one
|
|
261
|
+
if (!opts.force && previousBlockNumber !== blockNumber - 1) {
|
|
262
|
+
throw new BlockNumberNotSequentialError(blockNumber, previousBlockNumber);
|
|
175
263
|
}
|
|
176
264
|
|
|
177
|
-
//
|
|
178
|
-
|
|
179
|
-
|
|
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);
|
|
180
273
|
}
|
|
181
274
|
|
|
182
275
|
// Extract the previous block if there is one and see if it is for the same checkpoint or not
|
|
183
|
-
const previousBlockResult = await this.
|
|
276
|
+
const previousBlockResult = await this.getBlockData({ number: previousBlockNumber });
|
|
184
277
|
|
|
185
|
-
let
|
|
278
|
+
let expectedBlockIndex = 0;
|
|
186
279
|
let previousBlockIndex: number | undefined = undefined;
|
|
187
280
|
if (previousBlockResult !== undefined) {
|
|
188
|
-
if (previousBlockResult.checkpointNumber ===
|
|
281
|
+
if (previousBlockResult.checkpointNumber === blockCheckpointNumber) {
|
|
189
282
|
// The previous block is for the same checkpoint, therefore our index should follow it
|
|
190
283
|
previousBlockIndex = previousBlockResult.indexWithinCheckpoint;
|
|
191
|
-
|
|
284
|
+
expectedBlockIndex = previousBlockIndex + 1;
|
|
192
285
|
}
|
|
193
|
-
if (!previousBlockResult.archive.root.equals(
|
|
286
|
+
if (!previousBlockResult.archive.root.equals(blockLastArchive)) {
|
|
194
287
|
throw new BlockArchiveNotConsistentError(
|
|
195
|
-
|
|
196
|
-
previousBlockResult.
|
|
197
|
-
|
|
288
|
+
blockNumber,
|
|
289
|
+
previousBlockResult.header.globalVariables.blockNumber,
|
|
290
|
+
blockLastArchive,
|
|
198
291
|
previousBlockResult.archive.root,
|
|
199
292
|
);
|
|
200
293
|
}
|
|
201
294
|
}
|
|
202
295
|
|
|
203
|
-
// Now check that the
|
|
204
|
-
if (!opts.force &&
|
|
205
|
-
throw new BlockIndexNotSequentialError(
|
|
296
|
+
// Now check that the block has the expected index value
|
|
297
|
+
if (!opts.force && expectedBlockIndex !== blockIndex) {
|
|
298
|
+
throw new BlockIndexNotSequentialError(blockIndex, previousBlockIndex);
|
|
206
299
|
}
|
|
207
300
|
|
|
208
|
-
|
|
209
|
-
let previousBlock: L2Block | undefined = undefined;
|
|
210
|
-
for (const block of blocks) {
|
|
211
|
-
if (!opts.force && previousBlock) {
|
|
212
|
-
if (previousBlock.number + 1 !== block.number) {
|
|
213
|
-
throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
|
|
214
|
-
}
|
|
215
|
-
if (previousBlock.indexWithinCheckpoint + 1 !== block.indexWithinCheckpoint) {
|
|
216
|
-
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
|
|
217
|
-
}
|
|
218
|
-
if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
|
|
219
|
-
throw new BlockArchiveNotConsistentError(
|
|
220
|
-
block.number,
|
|
221
|
-
previousBlock.number,
|
|
222
|
-
block.header.lastArchive.root,
|
|
223
|
-
previousBlock.archive.root,
|
|
224
|
-
);
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
if (!opts.force && firstBlockCheckpointNumber !== block.checkpointNumber) {
|
|
228
|
-
throw new CheckpointNumberNotConsistentError(block.checkpointNumber, firstBlockCheckpointNumber);
|
|
229
|
-
}
|
|
230
|
-
previousBlock = block;
|
|
231
|
-
await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
|
|
232
|
-
}
|
|
301
|
+
await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
|
|
233
302
|
|
|
234
303
|
return true;
|
|
235
304
|
});
|
|
236
305
|
}
|
|
237
306
|
|
|
238
307
|
/**
|
|
239
|
-
* 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.
|
|
240
312
|
* @param checkpoints - The L2 checkpoints to be added to the store.
|
|
241
|
-
* @returns
|
|
313
|
+
* @returns The checkpoints that were actually inserted (excluding already-stored ones).
|
|
242
314
|
*/
|
|
243
|
-
async addCheckpoints(
|
|
315
|
+
async addCheckpoints(
|
|
316
|
+
checkpoints: PublishedCheckpoint[],
|
|
317
|
+
opts: { force?: boolean } = {},
|
|
318
|
+
): Promise<PublishedCheckpoint[]> {
|
|
244
319
|
if (checkpoints.length === 0) {
|
|
245
|
-
return
|
|
320
|
+
return [];
|
|
246
321
|
}
|
|
247
322
|
|
|
248
323
|
return await this.db.transactionAsync(async () => {
|
|
249
|
-
// Check that the checkpoint immediately before the first block to be added is present in the store.
|
|
250
324
|
const firstCheckpointNumber = checkpoints[0].checkpoint.number;
|
|
251
325
|
const previousCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
252
326
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
// There should be a previous checkpoint
|
|
261
|
-
previousCheckpointData = await this.getCheckpointData(previousCheckpointNumber);
|
|
262
|
-
if (previousCheckpointData === undefined) {
|
|
263
|
-
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 [];
|
|
264
334
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
// If we have a previous checkpoint then we need to get the previous block number
|
|
271
|
-
if (previousCheckpointData !== undefined) {
|
|
272
|
-
previousBlockNumber = BlockNumber(previousCheckpointData.startBlock + previousCheckpointData.blockCount - 1);
|
|
273
|
-
previousBlock = await this.getBlock(previousBlockNumber);
|
|
274
|
-
if (previousBlock === undefined) {
|
|
275
|
-
// We should be able to get the required previous block
|
|
276
|
-
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);
|
|
277
339
|
}
|
|
340
|
+
} else if (previousCheckpointNumber !== firstCheckpointNumber - 1 && !opts.force) {
|
|
341
|
+
throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
|
|
278
342
|
}
|
|
279
343
|
|
|
344
|
+
// Get the last block of the previous checkpoint for archive chaining
|
|
345
|
+
let previousBlock = await this.getPreviousCheckpointBlock(checkpoints[0].checkpoint.number);
|
|
346
|
+
|
|
280
347
|
// Iterate over checkpoints array and insert them, checking that the block numbers are sequential.
|
|
281
348
|
let previousCheckpoint: PublishedCheckpoint | undefined = undefined;
|
|
282
349
|
for (const checkpoint of checkpoints) {
|
|
@@ -292,42 +359,14 @@ export class BlockStore {
|
|
|
292
359
|
}
|
|
293
360
|
previousCheckpoint = checkpoint;
|
|
294
361
|
|
|
295
|
-
//
|
|
296
|
-
|
|
297
|
-
const block = checkpoint.checkpoint.blocks[i];
|
|
298
|
-
if (previousBlock) {
|
|
299
|
-
// The blocks should have a sequential block number
|
|
300
|
-
if (previousBlock.number !== block.number - 1) {
|
|
301
|
-
throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
|
|
302
|
-
}
|
|
303
|
-
// If the blocks are for the same checkpoint then they should have sequential indexes
|
|
304
|
-
if (
|
|
305
|
-
previousBlock.checkpointNumber === block.checkpointNumber &&
|
|
306
|
-
previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1
|
|
307
|
-
) {
|
|
308
|
-
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
|
|
309
|
-
}
|
|
310
|
-
if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
|
|
311
|
-
throw new BlockArchiveNotConsistentError(
|
|
312
|
-
block.number,
|
|
313
|
-
previousBlock.number,
|
|
314
|
-
block.header.lastArchive.root,
|
|
315
|
-
previousBlock.archive.root,
|
|
316
|
-
);
|
|
317
|
-
}
|
|
318
|
-
} else {
|
|
319
|
-
// No previous block, must be block 1 at checkpoint index 0
|
|
320
|
-
if (block.indexWithinCheckpoint !== 0) {
|
|
321
|
-
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
|
|
322
|
-
}
|
|
323
|
-
if (block.number !== INITIAL_L2_BLOCK_NUM) {
|
|
324
|
-
throw new BlockNumberNotSequentialError(block.number, undefined);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
362
|
+
// Validate block sequencing, indexes, and archive chaining
|
|
363
|
+
this.validateCheckpointBlocks(checkpoint.checkpoint.blocks, previousBlock);
|
|
327
364
|
|
|
328
|
-
|
|
329
|
-
|
|
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);
|
|
330
368
|
}
|
|
369
|
+
previousBlock = checkpoint.checkpoint.blocks.at(-1);
|
|
331
370
|
|
|
332
371
|
// Store the checkpoint in the database
|
|
333
372
|
await this.#checkpoints.set(checkpoint.checkpoint.number, {
|
|
@@ -339,17 +378,135 @@ export class BlockStore {
|
|
|
339
378
|
checkpointNumber: checkpoint.checkpoint.number,
|
|
340
379
|
startBlock: checkpoint.checkpoint.blocks[0].number,
|
|
341
380
|
blockCount: checkpoint.checkpoint.blocks.length,
|
|
381
|
+
feeAssetPriceModifier: checkpoint.checkpoint.feeAssetPriceModifier.toString(),
|
|
342
382
|
});
|
|
343
383
|
|
|
344
384
|
// Update slot-to-checkpoint index
|
|
345
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);
|
|
346
393
|
}
|
|
347
394
|
|
|
348
|
-
await this
|
|
349
|
-
return
|
|
395
|
+
await this.advanceSynchedL1BlockNumber(checkpoints[checkpoints.length - 1].l1.blockNumber);
|
|
396
|
+
return checkpoints;
|
|
350
397
|
});
|
|
351
398
|
}
|
|
352
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
|
+
|
|
353
510
|
private async addBlockToDatabase(block: L2Block, checkpointNumber: number, indexWithinCheckpoint: number) {
|
|
354
511
|
const blockHash = await block.hash();
|
|
355
512
|
|
|
@@ -367,6 +524,7 @@ export class BlockStore {
|
|
|
367
524
|
l2BlockNumber: block.number,
|
|
368
525
|
l2BlockHash: blockHash,
|
|
369
526
|
txIndexInBlock: i,
|
|
527
|
+
slotNumber: block.header.globalVariables.slotNumber,
|
|
370
528
|
};
|
|
371
529
|
await this.#txEffects.set(txEffect.data.txHash.toString(), serializeIndexedTxEffect(txEffect));
|
|
372
530
|
}
|
|
@@ -379,20 +537,58 @@ export class BlockStore {
|
|
|
379
537
|
}
|
|
380
538
|
|
|
381
539
|
/** Deletes a block and all associated data (tx effects, indices). */
|
|
382
|
-
private async deleteBlock(
|
|
540
|
+
private async deleteBlock(blockNumber: number, blockStorage: BlockStorage): Promise<void> {
|
|
383
541
|
// Delete the block from the main blocks map
|
|
384
|
-
await this.#blocks.delete(
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
542
|
+
await this.#blocks.delete(blockNumber);
|
|
543
|
+
|
|
544
|
+
const blockHash = bufferToHex(blockStorage.blockHash);
|
|
545
|
+
|
|
546
|
+
// Delete the tx effects of the block's txs, skipping entries that no longer point at this block: if
|
|
547
|
+
// another stored block also contains the tx, the entry points at that block, and deleting it here would
|
|
548
|
+
// orphan that block's index. Honest chains never store the same tx twice (duplicate nullifiers are
|
|
549
|
+
// rejected at build, re-execution, and world-state sync), so the store must not turn such a state into
|
|
550
|
+
// corruption of the surviving block if it ever appears.
|
|
551
|
+
const blockTxsBuffer = await this.#blockTxs.getAsync(blockHash);
|
|
552
|
+
if (blockTxsBuffer !== undefined) {
|
|
553
|
+
const reader = BufferReader.asReader(blockTxsBuffer);
|
|
554
|
+
const txHashes: string[] = [];
|
|
555
|
+
while (!reader.isEmpty()) {
|
|
556
|
+
txHashes.push(reader.readObject(TxHash).toString());
|
|
557
|
+
}
|
|
558
|
+
await Promise.all(txHashes.map(txHash => this.deleteTxEffect(txHash, blockStorage.blockHash)));
|
|
559
|
+
}
|
|
388
560
|
|
|
389
561
|
// Delete block txs mapping
|
|
390
|
-
const blockHash = (await block.hash()).toString();
|
|
391
562
|
await this.#blockTxs.delete(blockHash);
|
|
392
563
|
|
|
393
564
|
// Clean up indices
|
|
394
565
|
await this.#blockHashIndex.delete(blockHash);
|
|
395
|
-
await this.#blockArchiveIndex.delete(
|
|
566
|
+
await this.#blockArchiveIndex.delete(AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive).root.toString());
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** Deletes a tx effect only if it is still owned by (points at) the given block. */
|
|
570
|
+
private async deleteTxEffect(txHash: string, blockHash: Buffer): Promise<void> {
|
|
571
|
+
const stored = await this.#txEffects.getAsync(txHash);
|
|
572
|
+
if (stored === undefined) {
|
|
573
|
+
this.#log.warn(`Missing tx effect for tx ${txHash} while removing its block`, {
|
|
574
|
+
txHash,
|
|
575
|
+
blockHash: bufferToHex(blockHash),
|
|
576
|
+
});
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
// An IndexedTxEffect starts with the owning block hash (32 bytes) — see getTxLocation.
|
|
580
|
+
if (!Buffer.from(stored.buffer, stored.byteOffset, 32).equals(blockHash)) {
|
|
581
|
+
// Fires only when two stored blocks listed the same tx — a state upstream validation should make
|
|
582
|
+
// unreachable. Keep the entry (it belongs to the surviving block) but flag the duplication loudly.
|
|
583
|
+
this.#log.warn(`Tx effect for tx ${txHash} is owned by a block other than the one being removed`, {
|
|
584
|
+
txHash,
|
|
585
|
+
removedBlockHash: bufferToHex(blockHash),
|
|
586
|
+
owningBlockHash: bufferToHex(Buffer.from(stored.buffer, stored.byteOffset, 32)),
|
|
587
|
+
});
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
await this.#txEffects.delete(txHash);
|
|
396
592
|
}
|
|
397
593
|
|
|
398
594
|
/**
|
|
@@ -442,6 +638,9 @@ export class BlockStore {
|
|
|
442
638
|
this.#log.debug(`Removed checkpoint ${c}`);
|
|
443
639
|
}
|
|
444
640
|
|
|
641
|
+
// Evict all pending checkpoints > checkpointNumber (their base chain no longer exists)
|
|
642
|
+
await this.evictProposedCheckpointsFrom(CheckpointNumber(checkpointNumber + 1));
|
|
643
|
+
|
|
445
644
|
return { blocksRemoved };
|
|
446
645
|
});
|
|
447
646
|
}
|
|
@@ -466,6 +665,26 @@ export class BlockStore {
|
|
|
466
665
|
return checkpoints;
|
|
467
666
|
}
|
|
468
667
|
|
|
668
|
+
/**
|
|
669
|
+
* Returns up to `limit` checkpoints anchored at `fromSlot`, ordered nearest-first, walking the slot index.
|
|
670
|
+
* With `reverse`, takes the checkpoints at or before `fromSlot` (descending by slot); otherwise the
|
|
671
|
+
* checkpoints at or after it (ascending). `limit: 1, reverse: true` yields the latest checkpoint at or
|
|
672
|
+
* before the slot in a single range scan.
|
|
673
|
+
*/
|
|
674
|
+
async getCheckpointsBySlot(fromSlot: SlotNumber, limit: number, reverse: boolean): Promise<CheckpointData[]> {
|
|
675
|
+
// The KV range bounds are direction-dependent: forward is [start, end), reverse is (start, end], so a
|
|
676
|
+
// reverse scan uses `end: fromSlot` (inclusive) with no +1 to include the checkpoint at fromSlot itself.
|
|
677
|
+
const range = reverse ? { end: fromSlot, reverse: true, limit } : { start: fromSlot, limit };
|
|
678
|
+
const result: CheckpointData[] = [];
|
|
679
|
+
for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync(range)) {
|
|
680
|
+
const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
|
|
681
|
+
if (checkpointStorage) {
|
|
682
|
+
result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage));
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
return result;
|
|
686
|
+
}
|
|
687
|
+
|
|
469
688
|
/** Returns checkpoint data for all checkpoints whose slot falls within the given range (inclusive). */
|
|
470
689
|
async getCheckpointDataForSlotRange(startSlot: SlotNumber, endSlot: SlotNumber): Promise<CheckpointData[]> {
|
|
471
690
|
const result: CheckpointData[] = [];
|
|
@@ -481,6 +700,22 @@ export class BlockStore {
|
|
|
481
700
|
return result;
|
|
482
701
|
}
|
|
483
702
|
|
|
703
|
+
/**
|
|
704
|
+
* Returns the checkpoint numbers for all checkpoints whose slot falls within the given range (inclusive).
|
|
705
|
+
* Lighter than {@link getCheckpointDataForSlotRange} when callers only need to identify which
|
|
706
|
+
* checkpoints fall in the range and will fetch full data for at most a few of them.
|
|
707
|
+
*/
|
|
708
|
+
async getCheckpointNumbersForSlotRange(startSlot: SlotNumber, endSlot: SlotNumber): Promise<CheckpointNumber[]> {
|
|
709
|
+
const result: CheckpointNumber[] = [];
|
|
710
|
+
for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync({
|
|
711
|
+
start: startSlot,
|
|
712
|
+
end: endSlot + 1,
|
|
713
|
+
})) {
|
|
714
|
+
result.push(CheckpointNumber(checkpointNumber));
|
|
715
|
+
}
|
|
716
|
+
return result;
|
|
717
|
+
}
|
|
718
|
+
|
|
484
719
|
private checkpointDataFromCheckpointStorage(checkpointStorage: CheckpointStorage): CheckpointData {
|
|
485
720
|
return {
|
|
486
721
|
header: CheckpointHeader.fromBuffer(checkpointStorage.header),
|
|
@@ -489,6 +724,7 @@ export class BlockStore {
|
|
|
489
724
|
checkpointNumber: CheckpointNumber(checkpointStorage.checkpointNumber),
|
|
490
725
|
startBlock: BlockNumber(checkpointStorage.startBlock),
|
|
491
726
|
blockCount: checkpointStorage.blockCount,
|
|
727
|
+
feeAssetPriceModifier: BigInt(checkpointStorage.feeAssetPriceModifier),
|
|
492
728
|
l1: L1PublishedData.fromBuffer(checkpointStorage.l1),
|
|
493
729
|
attestations: checkpointStorage.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
|
|
494
730
|
};
|
|
@@ -547,20 +783,28 @@ export class BlockStore {
|
|
|
547
783
|
const removedBlocks: L2Block[] = [];
|
|
548
784
|
|
|
549
785
|
// Get the latest block number to determine the range
|
|
550
|
-
const latestBlockNumber = await this.
|
|
786
|
+
const latestBlockNumber = await this.getLatestL2BlockNumber();
|
|
551
787
|
|
|
552
788
|
// Iterate from blockNumber + 1 to latestBlockNumber
|
|
553
789
|
for (let bn = blockNumber + 1; bn <= latestBlockNumber; bn++) {
|
|
554
|
-
const
|
|
790
|
+
const blockStorage = await this.#blocks.getAsync(bn);
|
|
555
791
|
|
|
556
|
-
if (
|
|
792
|
+
if (blockStorage === undefined) {
|
|
557
793
|
this.#log.warn(`Cannot remove block ${bn} from the store since we don't have it`);
|
|
558
794
|
continue;
|
|
559
795
|
}
|
|
560
796
|
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
this
|
|
797
|
+
// Load the full block for the returned list when possible, but clean up from the raw row regardless:
|
|
798
|
+
// a block whose body can no longer be fully loaded must still release its row, tx effects, and indices,
|
|
799
|
+
// or later inserts at this number leave stale tx-effect entries pointing into the new chain.
|
|
800
|
+
const block = await this.getBlockFromBlockStorage(bn, blockStorage);
|
|
801
|
+
if (block !== undefined) {
|
|
802
|
+
removedBlocks.push(block);
|
|
803
|
+
} else {
|
|
804
|
+
this.#log.warn(`Removing block ${bn} whose body could not be fully loaded`);
|
|
805
|
+
}
|
|
806
|
+
await this.deleteBlock(bn, blockStorage);
|
|
807
|
+
this.#log.debug(`Removed block ${bn} ${bufferToHex(blockStorage.blockHash)}`);
|
|
564
808
|
}
|
|
565
809
|
|
|
566
810
|
return removedBlocks;
|
|
@@ -580,13 +824,6 @@ export class BlockStore {
|
|
|
580
824
|
}
|
|
581
825
|
}
|
|
582
826
|
|
|
583
|
-
async getLatestBlockNumber(): Promise<BlockNumber> {
|
|
584
|
-
const [latestBlocknumber] = await toArray(this.#blocks.keysAsync({ reverse: true, limit: 1 }));
|
|
585
|
-
return typeof latestBlocknumber === 'number'
|
|
586
|
-
? BlockNumber(latestBlocknumber)
|
|
587
|
-
: BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
588
|
-
}
|
|
589
|
-
|
|
590
827
|
async getLatestCheckpointNumber(): Promise<CheckpointNumber> {
|
|
591
828
|
const [latestCheckpointNumber] = await toArray(this.#checkpoints.keysAsync({ reverse: true, limit: 1 }));
|
|
592
829
|
if (latestCheckpointNumber === undefined) {
|
|
@@ -595,175 +832,204 @@ export class BlockStore {
|
|
|
595
832
|
return CheckpointNumber(latestCheckpointNumber);
|
|
596
833
|
}
|
|
597
834
|
|
|
598
|
-
async
|
|
599
|
-
const
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
const block = await this.getBlockFromBlockStorage(number, blockStorage);
|
|
608
|
-
if (!block) {
|
|
609
|
-
return undefined;
|
|
835
|
+
async hasProposedCheckpoint(): Promise<boolean> {
|
|
836
|
+
const [key] = await toArray(this.#proposedCheckpoints.keysAsync({ limit: 1 }));
|
|
837
|
+
return key !== undefined;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/** Deletes all pending proposed checkpoints from storage. */
|
|
841
|
+
async deleteProposedCheckpoints(): Promise<void> {
|
|
842
|
+
for await (const key of this.#proposedCheckpoints.keysAsync()) {
|
|
843
|
+
await this.#proposedCheckpoints.delete(key);
|
|
610
844
|
}
|
|
611
|
-
return new CheckpointedL2Block(
|
|
612
|
-
CheckpointNumber(checkpoint.checkpointNumber),
|
|
613
|
-
block,
|
|
614
|
-
L1PublishedData.fromBuffer(checkpoint.l1),
|
|
615
|
-
checkpoint.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
|
|
616
|
-
);
|
|
617
845
|
}
|
|
618
846
|
|
|
619
847
|
/**
|
|
620
|
-
*
|
|
621
|
-
*
|
|
622
|
-
*
|
|
623
|
-
* @
|
|
848
|
+
* Promotes a specific pending checkpoint to a confirmed checkpoint entry.
|
|
849
|
+
* This persists the checkpoint to the store, removes only that pending entry, and updates the L1 sync point.
|
|
850
|
+
* Remaining pending entries (e.g. N+1, N+2) are left intact — they chain off the just-promoted one.
|
|
851
|
+
* @param checkpointNumber - The checkpoint number to promote.
|
|
852
|
+
* @param l1 - L1 published data for the checkpoint.
|
|
853
|
+
* @param attestations - Committee attestations.
|
|
854
|
+
* @param expectedArchiveRoot - Archive root guard against races.
|
|
624
855
|
*/
|
|
625
|
-
async
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
const checkpointedBlock = new CheckpointedL2Block(
|
|
636
|
-
CheckpointNumber(checkpoint.checkpointNumber),
|
|
637
|
-
block,
|
|
638
|
-
L1PublishedData.fromBuffer(checkpoint.l1),
|
|
639
|
-
checkpoint.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
|
|
640
|
-
);
|
|
641
|
-
yield checkpointedBlock;
|
|
642
|
-
}
|
|
856
|
+
async promoteProposedToCheckpointed(
|
|
857
|
+
checkpointNumber: CheckpointNumber,
|
|
858
|
+
l1: L1PublishedData,
|
|
859
|
+
attestations: CommitteeAttestation[],
|
|
860
|
+
expectedArchiveRoot: Fr,
|
|
861
|
+
): Promise<void> {
|
|
862
|
+
return await this.db.transactionAsync(async () => {
|
|
863
|
+
const proposed = await this.getProposedCheckpointByNumber(checkpointNumber);
|
|
864
|
+
if (!proposed) {
|
|
865
|
+
throw new NoProposedCheckpointToPromoteError();
|
|
643
866
|
}
|
|
644
|
-
|
|
867
|
+
if (!proposed.archive.root.equals(expectedArchiveRoot)) {
|
|
868
|
+
throw new ProposedCheckpointArchiveRootMismatchError(expectedArchiveRoot, proposed.archive.root);
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// Verify sequentiality: promoted checkpoint must follow the latest confirmed one
|
|
872
|
+
const latestCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
873
|
+
if (latestCheckpointNumber !== proposed.checkpointNumber - 1) {
|
|
874
|
+
throw new ProposedCheckpointPromotionNotSequentialError(proposed.checkpointNumber, latestCheckpointNumber);
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
// Write the checkpoint entry
|
|
878
|
+
await this.#checkpoints.set(proposed.checkpointNumber, {
|
|
879
|
+
header: proposed.header.toBuffer(),
|
|
880
|
+
archive: proposed.archive.toBuffer(),
|
|
881
|
+
checkpointOutHash: proposed.checkpointOutHash.toBuffer(),
|
|
882
|
+
l1: l1.toBuffer(),
|
|
883
|
+
attestations: attestations.map(attestation => attestation.toBuffer()),
|
|
884
|
+
checkpointNumber: proposed.checkpointNumber,
|
|
885
|
+
startBlock: proposed.startBlock,
|
|
886
|
+
blockCount: proposed.blockCount,
|
|
887
|
+
feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
|
|
888
|
+
});
|
|
889
|
+
|
|
890
|
+
// Update the slot-to-checkpoint index
|
|
891
|
+
await this.#slotToCheckpoint.set(proposed.header.slotNumber, proposed.checkpointNumber);
|
|
892
|
+
|
|
893
|
+
// Remove only this pending entry — remaining entries N+1, N+2, ... stay valid
|
|
894
|
+
await this.#proposedCheckpoints.delete(proposed.checkpointNumber);
|
|
895
|
+
|
|
896
|
+
// Drop any rejected entry for this archive root: a checkpoint that was previously rejected
|
|
897
|
+
// (e.g. invalid attestations) is now being promoted as valid, so its descendants are allowed.
|
|
898
|
+
await this.removeRejectedCheckpointByArchiveRoot(proposed.archive.root);
|
|
899
|
+
|
|
900
|
+
// Update the last synced L1 block
|
|
901
|
+
await this.advanceSynchedL1BlockNumber(l1.blockNumber);
|
|
902
|
+
});
|
|
645
903
|
}
|
|
646
904
|
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
905
|
+
/**
|
|
906
|
+
* Returns the latest pending checkpoint (highest-numbered entry), or undefined if none.
|
|
907
|
+
* No fallback to confirmed.
|
|
908
|
+
*/
|
|
909
|
+
async getLastProposedCheckpoint(): Promise<ProposedCheckpointData | undefined> {
|
|
910
|
+
const [key] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
|
|
911
|
+
if (key === undefined) {
|
|
650
912
|
return undefined;
|
|
651
913
|
}
|
|
652
|
-
|
|
914
|
+
const stored = await this.#proposedCheckpoints.getAsync(key);
|
|
915
|
+
return stored ? this.convertToProposedCheckpointData(stored) : undefined;
|
|
653
916
|
}
|
|
654
917
|
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
}
|
|
660
|
-
return this.getCheckpointedBlock(BlockNumber(blockNumber));
|
|
918
|
+
/** Returns the pending checkpoint for a specific checkpoint number, or undefined if not found. */
|
|
919
|
+
async getProposedCheckpointByNumber(n: CheckpointNumber): Promise<ProposedCheckpointData | undefined> {
|
|
920
|
+
const stored = await this.#proposedCheckpoints.getAsync(n);
|
|
921
|
+
return stored ? this.convertToProposedCheckpointData(stored) : undefined;
|
|
661
922
|
}
|
|
662
923
|
|
|
663
924
|
/**
|
|
664
|
-
*
|
|
665
|
-
*
|
|
666
|
-
*
|
|
667
|
-
* @returns The requested L2 blocks
|
|
925
|
+
* Returns the pending checkpoint whose header slot matches the given slot, or undefined if not found.
|
|
926
|
+
* Iterates `#proposedCheckpoints` rather than reading an index because the map carries 0–1 entries
|
|
927
|
+
* in normal operation (bounded by the proposer pipelining window). Returns the first match.
|
|
668
928
|
*/
|
|
669
|
-
async
|
|
670
|
-
for await (const [
|
|
671
|
-
const
|
|
672
|
-
if (
|
|
673
|
-
|
|
929
|
+
async getProposedCheckpointBySlot(slot: SlotNumber): Promise<ProposedCheckpointData | undefined> {
|
|
930
|
+
for await (const [, stored] of this.#proposedCheckpoints.entriesAsync()) {
|
|
931
|
+
const header = CheckpointHeader.fromBuffer(stored.header);
|
|
932
|
+
if (header.slotNumber === slot) {
|
|
933
|
+
return this.convertToProposedCheckpointData(stored);
|
|
674
934
|
}
|
|
675
935
|
}
|
|
936
|
+
return undefined;
|
|
676
937
|
}
|
|
677
938
|
|
|
678
939
|
/**
|
|
679
|
-
*
|
|
680
|
-
*
|
|
681
|
-
*
|
|
940
|
+
* Evicts all pending checkpoints with checkpoint number >= fromNumber.
|
|
941
|
+
* Used for divergent-mined-checkpoint cleanup: when L1 mines checkpoint N with a different archive,
|
|
942
|
+
* all pending >= N must be evicted since they chain off the now-invalid pending N.
|
|
682
943
|
*/
|
|
683
|
-
async
|
|
684
|
-
const
|
|
685
|
-
|
|
686
|
-
|
|
944
|
+
async evictProposedCheckpointsFrom(fromNumber: CheckpointNumber): Promise<void> {
|
|
945
|
+
const keysToDelete: number[] = [];
|
|
946
|
+
for await (const key of this.#proposedCheckpoints.keysAsync()) {
|
|
947
|
+
if (key >= fromNumber) {
|
|
948
|
+
keysToDelete.push(key);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
for (const key of keysToDelete) {
|
|
952
|
+
await this.#proposedCheckpoints.delete(key);
|
|
687
953
|
}
|
|
688
|
-
return this.getBlockDataFromBlockStorage(blockStorage);
|
|
689
954
|
}
|
|
690
955
|
|
|
691
956
|
/**
|
|
692
|
-
* Gets
|
|
693
|
-
*
|
|
694
|
-
*
|
|
957
|
+
* Gets the checkpoint at the proposed tip:
|
|
958
|
+
* - latest pending checkpoint if any exist
|
|
959
|
+
* - fallsback to latest confirmed checkpoint otherwise
|
|
695
960
|
*/
|
|
696
|
-
async
|
|
697
|
-
const
|
|
698
|
-
if (
|
|
699
|
-
return
|
|
961
|
+
async getLastCheckpoint(): Promise<CommonCheckpointData | undefined> {
|
|
962
|
+
const latest = await this.getLastProposedCheckpoint();
|
|
963
|
+
if (!latest) {
|
|
964
|
+
return this.getCheckpointData(await this.getLatestCheckpointNumber());
|
|
700
965
|
}
|
|
701
|
-
return
|
|
966
|
+
return latest;
|
|
702
967
|
}
|
|
703
968
|
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
969
|
+
private convertToProposedCheckpointData(stored: ProposedCheckpointStorage): ProposedCheckpointData {
|
|
970
|
+
return {
|
|
971
|
+
checkpointNumber: CheckpointNumber(stored.checkpointNumber),
|
|
972
|
+
header: CheckpointHeader.fromBuffer(stored.header),
|
|
973
|
+
archive: AppendOnlyTreeSnapshot.fromBuffer(stored.archive),
|
|
974
|
+
checkpointOutHash: Fr.fromBuffer(stored.checkpointOutHash),
|
|
975
|
+
startBlock: BlockNumber(stored.startBlock),
|
|
976
|
+
blockCount: stored.blockCount,
|
|
977
|
+
totalManaUsed: BigInt(stored.totalManaUsed),
|
|
978
|
+
feeAssetPriceModifier: BigInt(stored.feeAssetPriceModifier),
|
|
979
|
+
};
|
|
715
980
|
}
|
|
716
981
|
|
|
717
982
|
/**
|
|
718
|
-
*
|
|
719
|
-
* @
|
|
720
|
-
* @returns The requested L2 block.
|
|
983
|
+
* Attempts to get the proposedCheckpoint's number, if there is not one, then fallback to the latest confirmed checkpoint number.
|
|
984
|
+
* @returns CheckpointNumber
|
|
721
985
|
*/
|
|
722
|
-
async
|
|
723
|
-
const
|
|
724
|
-
if (
|
|
725
|
-
return
|
|
986
|
+
async getProposedCheckpointNumber(): Promise<CheckpointNumber> {
|
|
987
|
+
const proposed = await this.getLastCheckpoint();
|
|
988
|
+
if (!proposed) {
|
|
989
|
+
return await this.getLatestCheckpointNumber();
|
|
726
990
|
}
|
|
727
|
-
return
|
|
991
|
+
return CheckpointNumber(proposed.checkpointNumber);
|
|
728
992
|
}
|
|
729
993
|
|
|
730
994
|
/**
|
|
731
|
-
*
|
|
732
|
-
* @
|
|
733
|
-
* @returns The requested L2 block.
|
|
995
|
+
* Attempts to get the proposedCheckpoint's block number, if there is not one, then fallback to the checkpointed block number
|
|
996
|
+
* @returns BlockNumber
|
|
734
997
|
*/
|
|
735
|
-
async
|
|
736
|
-
const
|
|
737
|
-
if (
|
|
738
|
-
return
|
|
998
|
+
async getProposedCheckpointL2BlockNumber(): Promise<BlockNumber> {
|
|
999
|
+
const proposed = await this.getLastCheckpoint();
|
|
1000
|
+
if (!proposed) {
|
|
1001
|
+
return await this.getCheckpointedL2BlockNumber();
|
|
739
1002
|
}
|
|
740
|
-
return
|
|
1003
|
+
return BlockNumber(proposed.startBlock + proposed.blockCount - 1);
|
|
741
1004
|
}
|
|
742
1005
|
|
|
743
|
-
/**
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
1006
|
+
/** Returns the checkpoint number that contains the given slot (or undefined if not found). */
|
|
1007
|
+
async getCheckpointNumberBySlot(slot: SlotNumber): Promise<CheckpointNumber | undefined> {
|
|
1008
|
+
const checkpointNumber = await this.#slotToCheckpoint.getAsync(slot);
|
|
1009
|
+
return checkpointNumber === undefined ? undefined : CheckpointNumber(checkpointNumber);
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/** Gets a single L2 block matching the given resolved query. */
|
|
1013
|
+
async getBlock(query: ResolvedBlockQuery): Promise<L2Block | undefined> {
|
|
1014
|
+
const blockNumber = await this.getBlockNumber(query);
|
|
750
1015
|
if (blockNumber === undefined) {
|
|
751
1016
|
return undefined;
|
|
752
1017
|
}
|
|
753
1018
|
const blockStorage = await this.#blocks.getAsync(blockNumber);
|
|
754
|
-
if (!blockStorage
|
|
1019
|
+
if (!blockStorage) {
|
|
755
1020
|
return undefined;
|
|
756
1021
|
}
|
|
757
|
-
return
|
|
1022
|
+
return this.getBlockFromBlockStorage(blockNumber, blockStorage);
|
|
758
1023
|
}
|
|
759
1024
|
|
|
760
|
-
/**
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
1025
|
+
/** Gets a collection of L2 blocks for a resolved range. */
|
|
1026
|
+
getBlocks(query: ResolvedBlocksQuery): Promise<L2Block[]> {
|
|
1027
|
+
return toArray(this.iterateBlocks(query));
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
/** Gets single block metadata matching the given resolved query. */
|
|
1031
|
+
async getBlockData(query: ResolvedBlockQuery): Promise<BlockData | undefined> {
|
|
1032
|
+
const blockNumber = await this.getBlockNumber(query);
|
|
767
1033
|
if (blockNumber === undefined) {
|
|
768
1034
|
return undefined;
|
|
769
1035
|
}
|
|
@@ -771,24 +1037,36 @@ export class BlockStore {
|
|
|
771
1037
|
if (!blockStorage || !blockStorage.header) {
|
|
772
1038
|
return undefined;
|
|
773
1039
|
}
|
|
774
|
-
return
|
|
1040
|
+
return this.getBlockDataFromBlockStorage(blockStorage);
|
|
775
1041
|
}
|
|
776
1042
|
|
|
777
|
-
/**
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
async *
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
if (
|
|
787
|
-
|
|
788
|
-
`Block number mismatch when retrieving block header from archive (expected ${blockNumber} but got ${header.getBlockNumber()})`,
|
|
789
|
-
);
|
|
1043
|
+
/** Gets a collection of block metadata entries for a resolved range. */
|
|
1044
|
+
getBlocksData(query: ResolvedBlocksQuery): Promise<BlockData[]> {
|
|
1045
|
+
return toArray(this.iterateBlocksData(query));
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
/** Async iterator over L2 blocks for a resolved range. */
|
|
1049
|
+
private async *iterateBlocks(query: ResolvedBlocksQuery): AsyncIterableIterator<L2Block> {
|
|
1050
|
+
const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
|
|
1051
|
+
for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)) {
|
|
1052
|
+
if (cap !== undefined && blockNumber > cap) {
|
|
1053
|
+
break;
|
|
790
1054
|
}
|
|
791
|
-
|
|
1055
|
+
const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
|
|
1056
|
+
if (block) {
|
|
1057
|
+
yield block;
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
/** Async iterator over block metadata for a resolved range. */
|
|
1063
|
+
private async *iterateBlocksData(query: ResolvedBlocksQuery): AsyncIterableIterator<BlockData> {
|
|
1064
|
+
const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
|
|
1065
|
+
for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)) {
|
|
1066
|
+
if (cap !== undefined && blockNumber > cap) {
|
|
1067
|
+
break;
|
|
1068
|
+
}
|
|
1069
|
+
yield this.getBlockDataFromBlockStorage(blockStorage);
|
|
792
1070
|
}
|
|
793
1071
|
}
|
|
794
1072
|
|
|
@@ -805,11 +1083,29 @@ export class BlockStore {
|
|
|
805
1083
|
}
|
|
806
1084
|
}
|
|
807
1085
|
|
|
1086
|
+
/** Resolves a ResolvedBlockQuery discriminant to a block number, or undefined if not found. */
|
|
1087
|
+
async getBlockNumber(query: ResolvedBlockQuery): Promise<BlockNumber | undefined> {
|
|
1088
|
+
let blockNumber: BlockNumber | undefined;
|
|
1089
|
+
if ('number' in query) {
|
|
1090
|
+
blockNumber = query.number;
|
|
1091
|
+
} else if ('hash' in query) {
|
|
1092
|
+
const n = await this.#blockHashIndex.getAsync(query.hash.toString());
|
|
1093
|
+
blockNumber = n !== undefined ? BlockNumber(n) : undefined;
|
|
1094
|
+
} else {
|
|
1095
|
+
const n = await this.#blockArchiveIndex.getAsync(query.archive.toString());
|
|
1096
|
+
blockNumber = n !== undefined ? BlockNumber(n) : undefined;
|
|
1097
|
+
}
|
|
1098
|
+
if (blockNumber === undefined) {
|
|
1099
|
+
return undefined;
|
|
1100
|
+
}
|
|
1101
|
+
return blockNumber;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
808
1104
|
private getBlockDataFromBlockStorage(blockStorage: BlockStorage): BlockData {
|
|
809
1105
|
return {
|
|
810
1106
|
header: BlockHeader.fromBuffer(blockStorage.header),
|
|
811
1107
|
archive: AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),
|
|
812
|
-
blockHash:
|
|
1108
|
+
blockHash: BlockHash.fromBuffer(blockStorage.blockHash),
|
|
813
1109
|
checkpointNumber: CheckpointNumber(blockStorage.checkpointNumber),
|
|
814
1110
|
indexWithinCheckpoint: IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint),
|
|
815
1111
|
};
|
|
@@ -866,48 +1162,6 @@ export class BlockStore {
|
|
|
866
1162
|
return deserializeIndexedTxEffect(buffer);
|
|
867
1163
|
}
|
|
868
1164
|
|
|
869
|
-
/**
|
|
870
|
-
* Gets a receipt of a settled tx.
|
|
871
|
-
* @param txHash - The hash of a tx we try to get the receipt for.
|
|
872
|
-
* @returns The requested tx receipt (or undefined if not found).
|
|
873
|
-
*/
|
|
874
|
-
async getSettledTxReceipt(txHash: TxHash): Promise<TxReceipt | undefined> {
|
|
875
|
-
const txEffect = await this.getTxEffect(txHash);
|
|
876
|
-
if (!txEffect) {
|
|
877
|
-
return undefined;
|
|
878
|
-
}
|
|
879
|
-
|
|
880
|
-
const blockNumber = BlockNumber(txEffect.l2BlockNumber);
|
|
881
|
-
|
|
882
|
-
// Use existing archiver methods to determine finalization level
|
|
883
|
-
const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber] = await Promise.all([
|
|
884
|
-
this.getProvenBlockNumber(),
|
|
885
|
-
this.getCheckpointedL2BlockNumber(),
|
|
886
|
-
this.getFinalizedL2BlockNumber(),
|
|
887
|
-
]);
|
|
888
|
-
|
|
889
|
-
let status: TxStatus;
|
|
890
|
-
if (blockNumber <= finalizedBlockNumber) {
|
|
891
|
-
status = TxStatus.FINALIZED;
|
|
892
|
-
} else if (blockNumber <= provenBlockNumber) {
|
|
893
|
-
status = TxStatus.PROVEN;
|
|
894
|
-
} else if (blockNumber <= checkpointedBlockNumber) {
|
|
895
|
-
status = TxStatus.CHECKPOINTED;
|
|
896
|
-
} else {
|
|
897
|
-
status = TxStatus.PROPOSED;
|
|
898
|
-
}
|
|
899
|
-
|
|
900
|
-
return new TxReceipt(
|
|
901
|
-
txHash,
|
|
902
|
-
status,
|
|
903
|
-
TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode),
|
|
904
|
-
undefined,
|
|
905
|
-
txEffect.data.transactionFee.toBigInt(),
|
|
906
|
-
txEffect.l2BlockHash,
|
|
907
|
-
blockNumber,
|
|
908
|
-
);
|
|
909
|
-
}
|
|
910
|
-
|
|
911
1165
|
/**
|
|
912
1166
|
* Looks up which block included the requested tx effect.
|
|
913
1167
|
* @param txHash - The txHash of the tx.
|
|
@@ -918,10 +1172,45 @@ export class BlockStore {
|
|
|
918
1172
|
if (!txEffect) {
|
|
919
1173
|
return undefined;
|
|
920
1174
|
}
|
|
921
|
-
|
|
1175
|
+
// Read only the IndexedTxEffect header (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4)`); the
|
|
1176
|
+
// large tail (the full TxEffect with logs etc.) is irrelevant here.
|
|
1177
|
+
const view = Buffer.from(txEffect.buffer, txEffect.byteOffset, txEffect.byteLength);
|
|
1178
|
+
const l2BlockNumber = view.readUInt32BE(32);
|
|
1179
|
+
const txIndexInBlock = view.readUInt32BE(36);
|
|
922
1180
|
return [l2BlockNumber, txIndexInBlock];
|
|
923
1181
|
}
|
|
924
1182
|
|
|
1183
|
+
/**
|
|
1184
|
+
* Batched, partial deserializer that fetches `noteHashes` and `nullifiers` (all of them) for the given
|
|
1185
|
+
* txs. For each input txHash, returns a `[noteHashes, nullifiers]` tuple. Returns `[[], []]` for any
|
|
1186
|
+
* unknown txHash. Preserves input order. Used by the log read path when `includeEffects` is set to
|
|
1187
|
+
* attach effect data on demand without paying for a full {@link TxEffect} deserialization.
|
|
1188
|
+
*
|
|
1189
|
+
* The on-disk `IndexedTxEffect` layout starts with a fixed-length header
|
|
1190
|
+
* (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4) + slotNumber(4) + revertCode(1) + txHash(32) +
|
|
1191
|
+
* transactionFee(32)` = 109 bytes), followed by `noteHashes` and `nullifiers` (both u8-length-prefixed `Fr`
|
|
1192
|
+
* vectors). We
|
|
1193
|
+
* skip the header, then read the two vectors, and stop — the large tail (`l2ToL1Msgs`,
|
|
1194
|
+
* `publicDataWrites`, `privateLogs`, `publicLogs`, `contractClassLogs`) is never touched.
|
|
1195
|
+
*/
|
|
1196
|
+
public getNoteHashesAndNullifiers(txHashes: TxHash[]): Promise<[Fr[], Fr[]][]> {
|
|
1197
|
+
return Promise.all(
|
|
1198
|
+
txHashes.map(async (txHash): Promise<[Fr[], Fr[]]> => {
|
|
1199
|
+
const buffer = await this.#txEffects.getAsync(txHash.toString());
|
|
1200
|
+
if (!buffer) {
|
|
1201
|
+
return [[], []];
|
|
1202
|
+
}
|
|
1203
|
+
const reader = BufferReader.asReader(buffer);
|
|
1204
|
+
// Skip the fixed-length header: blockHash + l2BlockNumber + txIndexInBlock + slotNumber + revertCode +
|
|
1205
|
+
// txHash + transactionFee.
|
|
1206
|
+
reader.readBytes(32 + 4 + 4 + 4 + 1 + 32 + 32);
|
|
1207
|
+
const noteHashes = reader.readVectorUint8Prefix(Fr);
|
|
1208
|
+
const nullifiers = reader.readVectorUint8Prefix(Fr);
|
|
1209
|
+
return [noteHashes, nullifiers];
|
|
1210
|
+
}),
|
|
1211
|
+
);
|
|
1212
|
+
}
|
|
1213
|
+
|
|
925
1214
|
/**
|
|
926
1215
|
* Looks up which block deployed a particular contract.
|
|
927
1216
|
* @param contractAddress - The address of the contract to look up.
|
|
@@ -949,6 +1238,159 @@ export class BlockStore {
|
|
|
949
1238
|
return typeof lastBlockNumber === 'number' ? BlockNumber(lastBlockNumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
950
1239
|
}
|
|
951
1240
|
|
|
1241
|
+
/**
|
|
1242
|
+
* Resolves all four L2 chain tips (proposed, checkpointed, proven, finalized) in a single
|
|
1243
|
+
* read-only transaction so the snapshot is internally consistent. Each underlying record is
|
|
1244
|
+
* read at most once: latest block and latest confirmed checkpoint are loaded directly (no
|
|
1245
|
+
* separate "find the number, then look up data" hop), the proven/finalized checkpoint
|
|
1246
|
+
* singletons are read once and their storage entries are reused if they coincide with the
|
|
1247
|
+
* latest checkpoint, and per-tip block hashes are deduped when two tips land on the same block
|
|
1248
|
+
* (e.g. finalized == proven).
|
|
1249
|
+
*
|
|
1250
|
+
* The result is guaranteed to satisfy `finalized <= proven <= checkpointed <= proposed` (by
|
|
1251
|
+
* block number). Genesis is represented by `(INITIAL_L2_BLOCK_NUM - 1)` and the supplied
|
|
1252
|
+
* `genesisBlockHash`, paired with the synthetic genesis checkpoint id.
|
|
1253
|
+
*
|
|
1254
|
+
* @param genesisBlockHash - Block hash to report for the synthetic pre-initial block (used when
|
|
1255
|
+
* a tip is still at genesis).
|
|
1256
|
+
*/
|
|
1257
|
+
async getL2TipsData(genesisBlockHash: BlockHash): Promise<L2Tips> {
|
|
1258
|
+
return await this.db.transactionAsync(async () => {
|
|
1259
|
+
// Define genesis tips
|
|
1260
|
+
const genesisBlockNumber = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
1261
|
+
const genesisCheckpointNumber = CheckpointNumber(INITIAL_CHECKPOINT_NUMBER - 1);
|
|
1262
|
+
const genesisBlockId = { number: genesisBlockNumber, hash: genesisBlockHash.toString() };
|
|
1263
|
+
const genesisCheckpointId = {
|
|
1264
|
+
number: genesisCheckpointNumber,
|
|
1265
|
+
hash: GENESIS_CHECKPOINT_HEADER_HASH.toString(),
|
|
1266
|
+
};
|
|
1267
|
+
const genesisTip: L2TipId = { block: genesisBlockId, checkpoint: genesisCheckpointId };
|
|
1268
|
+
|
|
1269
|
+
// Load latest block and checkpoint entries
|
|
1270
|
+
const [latestBlockEntry] = await toArray(this.#blocks.entriesAsync({ reverse: true, limit: 1 }));
|
|
1271
|
+
const [latestCheckpointEntry] = await toArray(this.#checkpoints.entriesAsync({ reverse: true, limit: 1 }));
|
|
1272
|
+
const latestCheckpointNumber = latestCheckpointEntry
|
|
1273
|
+
? CheckpointNumber(latestCheckpointEntry[0])
|
|
1274
|
+
: genesisCheckpointNumber;
|
|
1275
|
+
|
|
1276
|
+
// Load proven and finalized checkpoint number pointers
|
|
1277
|
+
const [provenRaw, finalizedRaw] = await Promise.all([
|
|
1278
|
+
this.#lastProvenCheckpoint.getAsync(),
|
|
1279
|
+
this.#lastFinalizedCheckpoint.getAsync(),
|
|
1280
|
+
]);
|
|
1281
|
+
|
|
1282
|
+
// Clamp to enforce finalized <= proven <= checkpointed.
|
|
1283
|
+
const provenCheckpointNumber = CheckpointNumber(Math.min(provenRaw ?? 0, latestCheckpointNumber));
|
|
1284
|
+
const finalizedCheckpointNumber = CheckpointNumber(Math.min(finalizedRaw ?? 0, provenCheckpointNumber));
|
|
1285
|
+
|
|
1286
|
+
// Avoid loading the same checkpoint more than once
|
|
1287
|
+
const checkpointStorageCache = new Map<CheckpointNumber, CheckpointStorage>();
|
|
1288
|
+
if (latestCheckpointEntry) {
|
|
1289
|
+
checkpointStorageCache.set(CheckpointNumber(latestCheckpointEntry[0]), latestCheckpointEntry[1]);
|
|
1290
|
+
}
|
|
1291
|
+
const loadCheckpointStorage = async (n: CheckpointNumber): Promise<CheckpointStorage | undefined> => {
|
|
1292
|
+
if (n === 0) {
|
|
1293
|
+
return undefined;
|
|
1294
|
+
}
|
|
1295
|
+
if (!checkpointStorageCache.has(n)) {
|
|
1296
|
+
const checkpointStorage = await this.#checkpoints.getAsync(n);
|
|
1297
|
+
if (!checkpointStorage) {
|
|
1298
|
+
throw new CheckpointNotFoundError(n);
|
|
1299
|
+
}
|
|
1300
|
+
checkpointStorageCache.set(n, checkpointStorage);
|
|
1301
|
+
}
|
|
1302
|
+
return checkpointStorageCache.get(n)!;
|
|
1303
|
+
};
|
|
1304
|
+
|
|
1305
|
+
// Load proven and finalized checkpoint storage entries
|
|
1306
|
+
const provenCheckpoint = await loadCheckpointStorage(provenCheckpointNumber);
|
|
1307
|
+
const finalizedCheckpoint = await loadCheckpointStorage(finalizedCheckpointNumber);
|
|
1308
|
+
|
|
1309
|
+
// Avoid loading the same block hash multiple times when tips land on the same block
|
|
1310
|
+
const blockHashCache = new Map<number, string>();
|
|
1311
|
+
blockHashCache.set(genesisBlockNumber, genesisBlockHash.toString());
|
|
1312
|
+
if (latestBlockEntry) {
|
|
1313
|
+
blockHashCache.set(latestBlockEntry[0], BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString());
|
|
1314
|
+
}
|
|
1315
|
+
const loadBlockHash = async (n: BlockNumber): Promise<string> => {
|
|
1316
|
+
if (!blockHashCache.has(n)) {
|
|
1317
|
+
const blockStorage = await this.#blocks.getAsync(n);
|
|
1318
|
+
if (!blockStorage) {
|
|
1319
|
+
throw new BlockNotFoundError(n);
|
|
1320
|
+
}
|
|
1321
|
+
const blockHash = BlockHash.fromBuffer(blockStorage.blockHash).toString();
|
|
1322
|
+
blockHashCache.set(n, blockHash);
|
|
1323
|
+
}
|
|
1324
|
+
return blockHashCache.get(n)!;
|
|
1325
|
+
};
|
|
1326
|
+
|
|
1327
|
+
// Build proposed chain tip (this one has block only, no checkpoint)
|
|
1328
|
+
const proposedBlockId =
|
|
1329
|
+
latestBlockEntry === undefined
|
|
1330
|
+
? genesisBlockId
|
|
1331
|
+
: {
|
|
1332
|
+
number: BlockNumber(latestBlockEntry[0]),
|
|
1333
|
+
hash: BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString(),
|
|
1334
|
+
};
|
|
1335
|
+
|
|
1336
|
+
// Build other tips from checkpoint data, reading corresponding block data from the cache
|
|
1337
|
+
const buildTipFromCheckpoint = async (
|
|
1338
|
+
stored: ProposedCheckpointStorage | CheckpointStorage | undefined,
|
|
1339
|
+
): Promise<L2TipId> => {
|
|
1340
|
+
if (!stored) {
|
|
1341
|
+
return genesisTip;
|
|
1342
|
+
}
|
|
1343
|
+
const blockNumber = BlockNumber(stored.startBlock + stored.blockCount - 1);
|
|
1344
|
+
const blockHash = await loadBlockHash(blockNumber);
|
|
1345
|
+
const header = CheckpointHeader.fromBuffer(stored.header);
|
|
1346
|
+
return {
|
|
1347
|
+
block: { number: blockNumber, hash: blockHash },
|
|
1348
|
+
checkpoint: { number: CheckpointNumber(stored.checkpointNumber), hash: header.hash().toString() },
|
|
1349
|
+
};
|
|
1350
|
+
};
|
|
1351
|
+
|
|
1352
|
+
const checkpointedTip = await buildTipFromCheckpoint(latestCheckpointEntry?.[1]);
|
|
1353
|
+
const provenTip = await buildTipFromCheckpoint(provenCheckpoint);
|
|
1354
|
+
const finalizedTip = await buildTipFromCheckpoint(finalizedCheckpoint);
|
|
1355
|
+
|
|
1356
|
+
// A checkpointed block past the latest stored block would mean a checkpoint
|
|
1357
|
+
// references blocks that aren't in blocks.
|
|
1358
|
+
if (proposedBlockId.number < checkpointedTip.block.number) {
|
|
1359
|
+
throw new Error(
|
|
1360
|
+
`Inconsistent block store: latest block ${proposedBlockId.number} is behind checkpointed block ${checkpointedTip.block.number}`,
|
|
1361
|
+
);
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
// Assert that checkpoint numbers are increasing
|
|
1365
|
+
if (
|
|
1366
|
+
finalizedTip.checkpoint.number > provenTip.checkpoint.number ||
|
|
1367
|
+
provenTip.checkpoint.number > checkpointedTip.checkpoint.number
|
|
1368
|
+
) {
|
|
1369
|
+
throw new Error(
|
|
1370
|
+
`Inconsistent checkpoint numbers in chain tips: finalized=${finalizedTip.checkpoint.number} proven=${provenTip.checkpoint.number} checkpointed=${checkpointedTip.checkpoint.number}`,
|
|
1371
|
+
);
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
// Assert block numbers are increasing
|
|
1375
|
+
if (
|
|
1376
|
+
finalizedTip.block.number > provenTip.block.number ||
|
|
1377
|
+
provenTip.block.number > checkpointedTip.block.number ||
|
|
1378
|
+
checkpointedTip.block.number > proposedBlockId.number
|
|
1379
|
+
) {
|
|
1380
|
+
throw new Error(
|
|
1381
|
+
`Inconsistent block numbers in chain tips: finalized=${finalizedTip.block.number} proven=${provenTip.block.number} checkpointed=${checkpointedTip.block.number} proposed=${proposedBlockId.number}`,
|
|
1382
|
+
);
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
return {
|
|
1386
|
+
proposed: proposedBlockId,
|
|
1387
|
+
checkpointed: checkpointedTip,
|
|
1388
|
+
proven: provenTip,
|
|
1389
|
+
finalized: finalizedTip,
|
|
1390
|
+
};
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
|
|
952
1394
|
/**
|
|
953
1395
|
* Gets the most recent L1 block processed.
|
|
954
1396
|
* @returns The L1 block that published the latest L2 block
|
|
@@ -961,14 +1403,62 @@ export class BlockStore {
|
|
|
961
1403
|
return this.#lastSynchedL1Block.set(l1BlockNumber);
|
|
962
1404
|
}
|
|
963
1405
|
|
|
1406
|
+
/**
|
|
1407
|
+
* Adds a proposed checkpoint to the pending queue.
|
|
1408
|
+
* Accepts proposed.checkpointNumber === latestTip + 1, where latestTip is the highest of
|
|
1409
|
+
* confirmed and the highest pending checkpoint number.
|
|
1410
|
+
* Computes archive and checkpointOutHash from the stored blocks.
|
|
1411
|
+
*/
|
|
1412
|
+
async addProposedCheckpoint(proposed: ProposedCheckpointInput) {
|
|
1413
|
+
return await this.db.transactionAsync(async () => {
|
|
1414
|
+
const confirmed = await this.getLatestCheckpointNumber();
|
|
1415
|
+
const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
|
|
1416
|
+
const latestTip = CheckpointNumber(
|
|
1417
|
+
latestPendingKey !== undefined ? Math.max(latestPendingKey, confirmed) : confirmed,
|
|
1418
|
+
);
|
|
1419
|
+
|
|
1420
|
+
if (proposed.checkpointNumber !== latestTip + 1) {
|
|
1421
|
+
throw new ProposedCheckpointNotSequentialError(proposed.checkpointNumber, latestTip);
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
// Ensure the predecessor block (from pending or confirmed chain) exists
|
|
1425
|
+
const previousBlock = await this.getPreviousCheckpointBlock(proposed.checkpointNumber);
|
|
1426
|
+
const blocks: L2Block[] = [];
|
|
1427
|
+
for (let i = 0; i < proposed.blockCount; i++) {
|
|
1428
|
+
const block = await this.getBlock({ number: BlockNumber(proposed.startBlock + i) });
|
|
1429
|
+
if (!block) {
|
|
1430
|
+
throw new BlockNotFoundError(proposed.startBlock + i);
|
|
1431
|
+
}
|
|
1432
|
+
blocks.push(block);
|
|
1433
|
+
}
|
|
1434
|
+
this.validateCheckpointBlocks(blocks, previousBlock);
|
|
1435
|
+
|
|
1436
|
+
const archive = blocks[blocks.length - 1].archive;
|
|
1437
|
+
const checkpointOutHash = Checkpoint.getCheckpointOutHash(blocks);
|
|
1438
|
+
|
|
1439
|
+
await this.#proposedCheckpoints.set(proposed.checkpointNumber, {
|
|
1440
|
+
header: proposed.header.toBuffer(),
|
|
1441
|
+
archive: archive.toBuffer(),
|
|
1442
|
+
checkpointOutHash: checkpointOutHash.toBuffer(),
|
|
1443
|
+
checkpointNumber: proposed.checkpointNumber,
|
|
1444
|
+
startBlock: proposed.startBlock,
|
|
1445
|
+
blockCount: proposed.blockCount,
|
|
1446
|
+
totalManaUsed: proposed.totalManaUsed.toString(),
|
|
1447
|
+
feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
|
|
1448
|
+
});
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
|
|
964
1452
|
async getProvenCheckpointNumber(): Promise<CheckpointNumber> {
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
1453
|
+
return await this.db.transactionAsync(async () => {
|
|
1454
|
+
const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
|
|
1455
|
+
this.getLatestCheckpointNumber(),
|
|
1456
|
+
this.#lastProvenCheckpoint.getAsync(),
|
|
1457
|
+
]);
|
|
1458
|
+
return (provenCheckpointNumber ?? 0) > latestCheckpointNumber
|
|
1459
|
+
? latestCheckpointNumber
|
|
1460
|
+
: CheckpointNumber(provenCheckpointNumber ?? 0);
|
|
1461
|
+
});
|
|
972
1462
|
}
|
|
973
1463
|
|
|
974
1464
|
async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber) {
|
|
@@ -976,6 +1466,22 @@ export class BlockStore {
|
|
|
976
1466
|
return result;
|
|
977
1467
|
}
|
|
978
1468
|
|
|
1469
|
+
async getFinalizedCheckpointNumber(): Promise<CheckpointNumber> {
|
|
1470
|
+
return await this.db.transactionAsync(async () => {
|
|
1471
|
+
const [provenCheckpointNumber, finalizedCheckpointNumber] = await Promise.all([
|
|
1472
|
+
this.getProvenCheckpointNumber(),
|
|
1473
|
+
this.#lastFinalizedCheckpoint.getAsync(),
|
|
1474
|
+
]);
|
|
1475
|
+
return (finalizedCheckpointNumber ?? 0) > provenCheckpointNumber
|
|
1476
|
+
? provenCheckpointNumber
|
|
1477
|
+
: CheckpointNumber(finalizedCheckpointNumber ?? 0);
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber) {
|
|
1482
|
+
return this.#lastFinalizedCheckpoint.set(checkpointNumber);
|
|
1483
|
+
}
|
|
1484
|
+
|
|
979
1485
|
#computeBlockRange(start: BlockNumber, limit: number): Required<Pick<Range<number>, 'start' | 'limit'>> {
|
|
980
1486
|
if (limit < 1) {
|
|
981
1487
|
throw new Error(`Invalid limit: ${limit}`);
|
|
@@ -1012,4 +1518,80 @@ export class BlockStore {
|
|
|
1012
1518
|
await this.#pendingChainValidationStatus.delete();
|
|
1013
1519
|
}
|
|
1014
1520
|
}
|
|
1521
|
+
|
|
1522
|
+
/** Records a rejected-checkpoint entry, keyed by its own archive root. */
|
|
1523
|
+
async addRejectedCheckpoint(entry: RejectedCheckpoint): Promise<void> {
|
|
1524
|
+
const archiveRootHex = entry.archiveRoot.toString();
|
|
1525
|
+
await this.#rejectedCheckpoints.set(archiveRootHex, {
|
|
1526
|
+
checkpointNumber: entry.checkpointNumber,
|
|
1527
|
+
archiveRoot: entry.archiveRoot.toBuffer(),
|
|
1528
|
+
parentArchiveRoot: entry.parentArchiveRoot.toBuffer(),
|
|
1529
|
+
slotNumber: entry.slotNumber,
|
|
1530
|
+
l1: entry.l1.toBuffer(),
|
|
1531
|
+
reason: entry.reason,
|
|
1532
|
+
});
|
|
1533
|
+
await this.#rejectedCheckpointsByNumber.set(entry.checkpointNumber, archiveRootHex);
|
|
1534
|
+
await this.advanceSynchedL1BlockNumber(entry.l1.blockNumber);
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
/** Returns the rejected-checkpoint entry with the given archive root, or undefined if not present. */
|
|
1538
|
+
async getRejectedCheckpointByArchiveRoot(archiveRoot: Fr): Promise<RejectedCheckpoint | undefined> {
|
|
1539
|
+
const stored = await this.#rejectedCheckpoints.getAsync(archiveRoot.toString());
|
|
1540
|
+
return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
/** Returns the rejected-checkpoint entry recorded for the given checkpoint number, or undefined if none. */
|
|
1544
|
+
async getRejectedCheckpointByNumber(checkpointNumber: CheckpointNumber): Promise<RejectedCheckpoint | undefined> {
|
|
1545
|
+
const archiveRootHex = await this.#rejectedCheckpointsByNumber.getAsync(checkpointNumber);
|
|
1546
|
+
if (archiveRootHex === undefined) {
|
|
1547
|
+
return undefined;
|
|
1548
|
+
}
|
|
1549
|
+
const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
|
|
1550
|
+
return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
/** Returns the highest checkpoint number recorded across all rejected entries, or `INITIAL_CHECKPOINT_NUMBER - 1` if none. */
|
|
1554
|
+
async getLatestRejectedCheckpointNumber(): Promise<CheckpointNumber> {
|
|
1555
|
+
const [latest] = await toArray(this.#rejectedCheckpointsByNumber.keysAsync({ reverse: true, limit: 1 }));
|
|
1556
|
+
return CheckpointNumber(latest ?? INITIAL_CHECKPOINT_NUMBER - 1);
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
/** Removes a rejected-checkpoint entry by its archive root (used when an entry no longer matches L1). */
|
|
1560
|
+
async removeRejectedCheckpointByArchiveRoot(archiveRoot: Fr): Promise<void> {
|
|
1561
|
+
const archiveRootHex = archiveRoot.toString();
|
|
1562
|
+
const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
|
|
1563
|
+
await this.#rejectedCheckpoints.delete(archiveRootHex);
|
|
1564
|
+
if (stored) {
|
|
1565
|
+
// Only clear the by-number index if it still points at this archive root, so a distinct
|
|
1566
|
+
// entry that shares the checkpoint number (e.g. an L1 reorg replacement) is not dropped.
|
|
1567
|
+
const indexed = await this.#rejectedCheckpointsByNumber.getAsync(stored.checkpointNumber);
|
|
1568
|
+
if (indexed === archiveRootHex) {
|
|
1569
|
+
await this.#rejectedCheckpointsByNumber.delete(stored.checkpointNumber);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
/**
|
|
1575
|
+
* Advances the stored last-synched L1 block number to `l1BlockNumber` only if it is strictly
|
|
1576
|
+
* greater than the current value. Use this whenever ingesting checkpoint-shaped data so the
|
|
1577
|
+
* sync pointer never walks backwards on out-of-order writes (e.g. an invalid checkpoint
|
|
1578
|
+
* advance followed by a valid-checkpoint commit landing at an earlier L1 block).
|
|
1579
|
+
*/
|
|
1580
|
+
private async advanceSynchedL1BlockNumber(l1BlockNumber: bigint): Promise<void> {
|
|
1581
|
+
const current = await this.#lastSynchedL1Block.getAsync();
|
|
1582
|
+
if (current === undefined || l1BlockNumber > current) {
|
|
1583
|
+
await this.#lastSynchedL1Block.set(l1BlockNumber);
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
private rejectedCheckpointFromStorage(stored: RejectedCheckpointStorage): RejectedCheckpoint {
|
|
1588
|
+
return {
|
|
1589
|
+
checkpointNumber: CheckpointNumber(stored.checkpointNumber),
|
|
1590
|
+
archiveRoot: Fr.fromBuffer(stored.archiveRoot),
|
|
1591
|
+
parentArchiveRoot: Fr.fromBuffer(stored.parentArchiveRoot),
|
|
1592
|
+
slotNumber: SlotNumber(stored.slotNumber),
|
|
1593
|
+
l1: L1PublishedData.fromBuffer(stored.l1),
|
|
1594
|
+
reason: stored.reason,
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1015
1597
|
}
|