@aztec/archiver 0.0.1-commit.96bb3f7 → 0.0.1-commit.993d240
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -22
- package/dest/archiver.d.ts +158 -0
- package/dest/archiver.d.ts.map +1 -0
- package/dest/archiver.js +881 -0
- package/dest/config.d.ts +33 -0
- package/dest/config.d.ts.map +1 -0
- package/dest/{archiver/config.js → config.js} +31 -14
- package/dest/errors.d.ts +87 -0
- package/dest/errors.d.ts.map +1 -0
- package/dest/errors.js +129 -0
- package/dest/factory.d.ts +16 -10
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +112 -20
- package/dest/index.d.ts +19 -4
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +17 -3
- package/dest/interfaces.d.ts +9 -0
- package/dest/interfaces.d.ts.map +1 -0
- package/dest/interfaces.js +3 -0
- package/dest/{archiver/l1 → l1}/bin/retrieve-calldata.d.ts +1 -1
- package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
- package/dest/{archiver/l1 → l1}/bin/retrieve-calldata.js +35 -32
- package/dest/l1/calldata_retriever.d.ts +136 -0
- package/dest/l1/calldata_retriever.d.ts.map +1 -0
- package/dest/l1/calldata_retriever.js +412 -0
- package/dest/l1/data_retrieval.d.ts +97 -0
- package/dest/l1/data_retrieval.d.ts.map +1 -0
- package/dest/{archiver/l1 → l1}/data_retrieval.js +65 -89
- package/dest/{archiver/l1 → l1}/debug_tx.d.ts +1 -1
- package/dest/l1/debug_tx.d.ts.map +1 -0
- package/dest/{archiver/l1 → l1}/spire_proposer.d.ts +5 -5
- package/dest/l1/spire_proposer.d.ts.map +1 -0
- package/dest/{archiver/l1 → l1}/spire_proposer.js +9 -17
- package/dest/l1/trace_tx.d.ts +43 -0
- package/dest/l1/trace_tx.d.ts.map +1 -0
- package/dest/l1/types.d.ts +12 -0
- package/dest/l1/types.d.ts.map +1 -0
- 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/{archiver/l1 → l1}/validate_trace.d.ts +6 -3
- package/dest/l1/validate_trace.d.ts.map +1 -0
- package/dest/{archiver/l1 → l1}/validate_trace.js +13 -9
- package/dest/modules/contract_data_source_adapter.d.ts +25 -0
- package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
- package/dest/modules/contract_data_source_adapter.js +40 -0
- package/dest/modules/data_source_base.d.ts +113 -0
- package/dest/modules/data_source_base.d.ts.map +1 -0
- package/dest/modules/data_source_base.js +351 -0
- package/dest/modules/data_store_updater.d.ts +105 -0
- package/dest/modules/data_store_updater.d.ts.map +1 -0
- package/dest/modules/data_store_updater.js +392 -0
- package/dest/modules/instrumentation.d.ts +55 -0
- package/dest/modules/instrumentation.d.ts.map +1 -0
- package/dest/{archiver → modules}/instrumentation.js +61 -19
- package/dest/modules/l1_synchronizer.d.ts +77 -0
- package/dest/modules/l1_synchronizer.d.ts.map +1 -0
- package/dest/modules/l1_synchronizer.js +1344 -0
- package/dest/modules/validation.d.ts +18 -0
- package/dest/modules/validation.d.ts.map +1 -0
- package/dest/{archiver → modules}/validation.js +12 -6
- package/dest/store/block_store.d.ts +300 -0
- package/dest/store/block_store.d.ts.map +1 -0
- package/dest/store/block_store.js +1219 -0
- package/dest/store/contract_class_store.d.ts +31 -0
- package/dest/store/contract_class_store.d.ts.map +1 -0
- package/dest/store/contract_class_store.js +80 -0
- package/dest/store/contract_instance_store.d.ts +51 -0
- package/dest/store/contract_instance_store.d.ts.map +1 -0
- package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +38 -3
- 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 +25 -0
- package/dest/store/l2_tips_cache.d.ts.map +1 -0
- package/dest/store/l2_tips_cache.js +26 -0
- package/dest/store/log_store.d.ts +59 -0
- package/dest/store/log_store.d.ts.map +1 -0
- package/dest/store/log_store.js +310 -0
- package/dest/store/log_store_codec.d.ts +70 -0
- package/dest/store/log_store_codec.d.ts.map +1 -0
- package/dest/store/log_store_codec.js +101 -0
- package/dest/store/message_store.d.ts +50 -0
- package/dest/store/message_store.d.ts.map +1 -0
- package/dest/{archiver/kv_archiver_store → store}/message_store.js +51 -9
- package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
- package/dest/structs/data_retrieval.d.ts.map +1 -0
- package/dest/structs/inbox_message.d.ts +15 -0
- package/dest/structs/inbox_message.d.ts.map +1 -0
- package/dest/{archiver/structs → structs}/published.d.ts +1 -1
- package/dest/structs/published.d.ts.map +1 -0
- package/dest/test/fake_l1_state.d.ts +214 -0
- package/dest/test/fake_l1_state.d.ts.map +1 -0
- package/dest/test/fake_l1_state.js +517 -0
- package/dest/test/index.d.ts +2 -1
- package/dest/test/index.d.ts.map +1 -1
- package/dest/test/index.js +4 -1
- package/dest/test/mock_archiver.d.ts +2 -2
- package/dest/test/mock_archiver.d.ts.map +1 -1
- package/dest/test/mock_archiver.js +3 -3
- package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
- package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
- package/dest/test/mock_l1_to_l2_message_source.js +2 -1
- package/dest/test/mock_l2_block_source.d.ts +65 -41
- package/dest/test/mock_l2_block_source.d.ts.map +1 -1
- package/dest/test/mock_l2_block_source.js +330 -151
- package/dest/test/mock_structs.d.ts +81 -3
- package/dest/test/mock_structs.d.ts.map +1 -1
- package/dest/test/mock_structs.js +152 -7
- package/dest/test/noop_l1_archiver.d.ts +29 -0
- package/dest/test/noop_l1_archiver.d.ts.map +1 -0
- package/dest/test/noop_l1_archiver.js +85 -0
- package/package.json +17 -18
- package/src/archiver.ts +681 -0
- package/src/{archiver/config.ts → config.ts} +43 -12
- package/src/errors.ts +203 -0
- package/src/factory.ts +175 -22
- package/src/index.ts +27 -3
- package/src/interfaces.ts +9 -0
- package/src/l1/README.md +55 -0
- package/src/{archiver/l1 → l1}/bin/retrieve-calldata.ts +45 -33
- package/src/l1/calldata_retriever.ts +522 -0
- package/src/{archiver/l1 → l1}/data_retrieval.ts +106 -134
- package/src/{archiver/l1 → l1}/spire_proposer.ts +7 -15
- package/src/l1/validate_historical_logs.ts +140 -0
- package/src/{archiver/l1 → l1}/validate_trace.ts +24 -6
- package/src/modules/contract_data_source_adapter.ts +55 -0
- package/src/modules/data_source_base.ts +493 -0
- package/src/modules/data_store_updater.ts +518 -0
- package/src/{archiver → modules}/instrumentation.ts +72 -20
- package/src/modules/l1_synchronizer.ts +1257 -0
- package/src/{archiver → modules}/validation.ts +15 -9
- package/src/store/block_store.ts +1590 -0
- package/src/store/contract_class_store.ts +108 -0
- package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +52 -6
- package/src/store/data_stores.ts +104 -0
- package/src/store/function_names_cache.ts +37 -0
- package/src/store/l2_tips_cache.ts +35 -0
- package/src/store/log_store.ts +379 -0
- package/src/store/log_store_codec.ts +132 -0
- package/src/{archiver/kv_archiver_store → store}/message_store.ts +60 -10
- package/src/{archiver/structs → structs}/inbox_message.ts +1 -1
- package/src/test/fake_l1_state.ts +770 -0
- package/src/test/index.ts +4 -0
- package/src/test/mock_archiver.ts +4 -3
- package/src/test/mock_l1_to_l2_message_source.ts +1 -0
- package/src/test/mock_l2_block_source.ts +403 -171
- package/src/test/mock_structs.ts +283 -8
- package/src/test/noop_l1_archiver.ts +139 -0
- package/dest/archiver/archiver.d.ts +0 -307
- package/dest/archiver/archiver.d.ts.map +0 -1
- package/dest/archiver/archiver.js +0 -2102
- package/dest/archiver/archiver_store.d.ts +0 -315
- package/dest/archiver/archiver_store.d.ts.map +0 -1
- package/dest/archiver/archiver_store.js +0 -4
- package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
- package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
- package/dest/archiver/archiver_store_test_suite.js +0 -2770
- package/dest/archiver/config.d.ts +0 -22
- package/dest/archiver/config.d.ts.map +0 -1
- package/dest/archiver/errors.d.ts +0 -36
- package/dest/archiver/errors.d.ts.map +0 -1
- package/dest/archiver/errors.js +0 -54
- package/dest/archiver/index.d.ts +0 -7
- package/dest/archiver/index.d.ts.map +0 -1
- package/dest/archiver/index.js +0 -4
- package/dest/archiver/instrumentation.d.ts +0 -37
- package/dest/archiver/instrumentation.d.ts.map +0 -1
- package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -164
- package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
- package/dest/archiver/kv_archiver_store/block_store.js +0 -626
- package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
- package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
- package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
- package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
- package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
- package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -159
- package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
- package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -316
- package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -45
- package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
- package/dest/archiver/kv_archiver_store/log_store.js +0 -401
- package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -40
- package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
- package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +0 -1
- package/dest/archiver/l1/calldata_retriever.d.ts +0 -112
- package/dest/archiver/l1/calldata_retriever.d.ts.map +0 -1
- package/dest/archiver/l1/calldata_retriever.js +0 -471
- package/dest/archiver/l1/data_retrieval.d.ts +0 -90
- package/dest/archiver/l1/data_retrieval.d.ts.map +0 -1
- package/dest/archiver/l1/debug_tx.d.ts.map +0 -1
- package/dest/archiver/l1/spire_proposer.d.ts.map +0 -1
- package/dest/archiver/l1/trace_tx.d.ts +0 -97
- package/dest/archiver/l1/trace_tx.d.ts.map +0 -1
- package/dest/archiver/l1/types.d.ts +0 -12
- package/dest/archiver/l1/types.d.ts.map +0 -1
- package/dest/archiver/l1/validate_trace.d.ts.map +0 -1
- package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
- package/dest/archiver/structs/inbox_message.d.ts +0 -15
- package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
- package/dest/archiver/structs/published.d.ts.map +0 -1
- package/dest/archiver/validation.d.ts +0 -17
- package/dest/archiver/validation.d.ts.map +0 -1
- package/dest/rpc/index.d.ts +0 -9
- package/dest/rpc/index.d.ts.map +0 -1
- package/dest/rpc/index.js +0 -15
- package/src/archiver/archiver.ts +0 -2265
- package/src/archiver/archiver_store.ts +0 -380
- package/src/archiver/archiver_store_test_suite.ts +0 -2842
- package/src/archiver/errors.ts +0 -90
- package/src/archiver/index.ts +0 -6
- package/src/archiver/kv_archiver_store/block_store.ts +0 -850
- package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
- package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -442
- package/src/archiver/kv_archiver_store/log_store.ts +0 -516
- package/src/archiver/l1/README.md +0 -98
- package/src/archiver/l1/calldata_retriever.ts +0 -641
- package/src/rpc/index.ts +0 -16
- /package/dest/{archiver/l1 → l1}/debug_tx.js +0 -0
- /package/dest/{archiver/l1 → l1}/trace_tx.js +0 -0
- /package/dest/{archiver/l1 → l1}/types.js +0 -0
- /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
- /package/dest/{archiver/structs → structs}/inbox_message.js +0 -0
- /package/dest/{archiver/structs → structs}/published.js +0 -0
- /package/src/{archiver/l1 → l1}/debug_tx.ts +0 -0
- /package/src/{archiver/l1 → l1}/trace_tx.ts +0 -0
- /package/src/{archiver/l1 → l1}/types.ts +0 -0
- /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
- /package/src/{archiver/structs → structs}/published.ts +0 -0
|
@@ -0,0 +1,1219 @@
|
|
|
1
|
+
import { INITIAL_CHECKPOINT_NUMBER, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
|
|
2
|
+
import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
|
|
3
|
+
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
4
|
+
import { toArray } from '@aztec/foundation/iterable';
|
|
5
|
+
import { createLogger } from '@aztec/foundation/log';
|
|
6
|
+
import { BufferReader } from '@aztec/foundation/serialize';
|
|
7
|
+
import { bufferToHex } from '@aztec/foundation/string';
|
|
8
|
+
import { isDefined } from '@aztec/foundation/types';
|
|
9
|
+
import { BlockHash, Body, CommitteeAttestation, GENESIS_CHECKPOINT_HEADER_HASH, L2Block, deserializeValidateCheckpointResult, serializeValidateCheckpointResult } from '@aztec/stdlib/block';
|
|
10
|
+
import { Checkpoint, L1PublishedData } from '@aztec/stdlib/checkpoint';
|
|
11
|
+
import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
|
|
12
|
+
import { CheckpointHeader } from '@aztec/stdlib/rollup';
|
|
13
|
+
import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
|
|
14
|
+
import { BlockHeader, TxHash, TxReceipt, TxStatus, deserializeIndexedTxEffect, serializeIndexedTxEffect } from '@aztec/stdlib/tx';
|
|
15
|
+
import { BlockAlreadyCheckpointedError, BlockArchiveNotConsistentError, BlockCheckpointNumberNotSequentialError, BlockIndexNotSequentialError, BlockNotFoundError, BlockNumberNotSequentialError, CannotOverwriteCheckpointedBlockError, CheckpointNotFoundError, CheckpointNumberNotSequentialError, InitialCheckpointNumberNotSequentialError, NoProposedCheckpointToPromoteError, ProposedCheckpointArchiveRootMismatchError, ProposedCheckpointNotSequentialError, ProposedCheckpointPromotionNotSequentialError } from '../errors.js';
|
|
16
|
+
export { TxReceipt } from '@aztec/stdlib/tx';
|
|
17
|
+
/**
|
|
18
|
+
* LMDB-based block storage for the archiver.
|
|
19
|
+
*/ export class BlockStore {
|
|
20
|
+
db;
|
|
21
|
+
/** Map block number to block data */ #blocks;
|
|
22
|
+
/** Map keyed by checkpoint number holding proposed (locally-validated, not yet L1-confirmed) checkpoints. */ #proposedCheckpoints;
|
|
23
|
+
/** Map checkpoint number to checkpoint data for mined checkpoints only */ #checkpoints;
|
|
24
|
+
/** Map slot number to checkpoint number, for looking up checkpoints by slot range. */ #slotToCheckpoint;
|
|
25
|
+
/** Map block hash to list of tx hashes */ #blockTxs;
|
|
26
|
+
/** Tx hash to serialized IndexedTxEffect */ #txEffects;
|
|
27
|
+
/** Stores L1 block number in which the last processed L2 block was included */ #lastSynchedL1Block;
|
|
28
|
+
/** Stores last proven checkpoint */ #lastProvenCheckpoint;
|
|
29
|
+
/** Stores last finalized checkpoint (proven at or before the finalized L1 block) */ #lastFinalizedCheckpoint;
|
|
30
|
+
/** Stores the pending chain validation status */ #pendingChainValidationStatus;
|
|
31
|
+
/** Index mapping a contract's address (as a string) to its location in a block */ #contractIndex;
|
|
32
|
+
/** Index mapping block hash to block number */ #blockHashIndex;
|
|
33
|
+
/** Index mapping block archive to block number */ #blockArchiveIndex;
|
|
34
|
+
/** Map rejected checkpoints (due to invalid attestations) by archive root */ #rejectedCheckpoints;
|
|
35
|
+
/** Index mapping a rejected checkpoint's number to its archive root, so the latest can be read in reverse order */ #rejectedCheckpointsByNumber;
|
|
36
|
+
#log;
|
|
37
|
+
constructor(db){
|
|
38
|
+
this.db = db;
|
|
39
|
+
this.#log = createLogger('archiver:block_store');
|
|
40
|
+
this.#blocks = db.openMap('archiver_blocks');
|
|
41
|
+
this.#blockTxs = db.openMap('archiver_block_txs');
|
|
42
|
+
this.#txEffects = db.openMap('archiver_tx_effects');
|
|
43
|
+
this.#contractIndex = db.openMap('archiver_contract_index');
|
|
44
|
+
this.#blockHashIndex = db.openMap('archiver_block_hash_index');
|
|
45
|
+
this.#blockArchiveIndex = db.openMap('archiver_block_archive_index');
|
|
46
|
+
this.#lastSynchedL1Block = db.openSingleton('archiver_last_synched_l1_block');
|
|
47
|
+
this.#lastProvenCheckpoint = db.openSingleton('archiver_last_proven_l2_checkpoint');
|
|
48
|
+
this.#lastFinalizedCheckpoint = db.openSingleton('archiver_last_finalized_l2_checkpoint');
|
|
49
|
+
this.#pendingChainValidationStatus = db.openSingleton('archiver_pending_chain_validation_status');
|
|
50
|
+
this.#checkpoints = db.openMap('archiver_checkpoints');
|
|
51
|
+
this.#slotToCheckpoint = db.openMap('archiver_slot_to_checkpoint');
|
|
52
|
+
this.#proposedCheckpoints = db.openMap('archiver_proposed_checkpoints');
|
|
53
|
+
this.#rejectedCheckpoints = db.openMap('archiver_rejected_checkpoints');
|
|
54
|
+
this.#rejectedCheckpointsByNumber = db.openMap('archiver_rejected_checkpoints_by_number');
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Returns the finalized L2 block number. An L2 block is finalized when it was proven
|
|
58
|
+
* in an L1 block that has itself been finalized on Ethereum.
|
|
59
|
+
* @returns The finalized block number.
|
|
60
|
+
*/ async getFinalizedL2BlockNumber() {
|
|
61
|
+
const finalizedCheckpointNumber = await this.getFinalizedCheckpointNumber();
|
|
62
|
+
if (finalizedCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
|
|
63
|
+
return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
64
|
+
}
|
|
65
|
+
const checkpointStorage = await this.#checkpoints.getAsync(finalizedCheckpointNumber);
|
|
66
|
+
if (!checkpointStorage) {
|
|
67
|
+
throw new CheckpointNotFoundError(finalizedCheckpointNumber);
|
|
68
|
+
}
|
|
69
|
+
return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Append a new proposed block to the store.
|
|
73
|
+
* This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
|
|
74
|
+
* For checkpointed blocks (already published to L1), use addCheckpoints() instead.
|
|
75
|
+
* @param block - The proposed L2 block to be added to the store.
|
|
76
|
+
* @returns True if the operation is successful.
|
|
77
|
+
*/ async addProposedBlock(block, opts = {}) {
|
|
78
|
+
return await this.db.transactionAsync(async ()=>{
|
|
79
|
+
const blockNumber = block.number;
|
|
80
|
+
const blockCheckpointNumber = block.checkpointNumber;
|
|
81
|
+
const blockIndex = block.indexWithinCheckpoint;
|
|
82
|
+
const blockLastArchive = block.header.lastArchive.root;
|
|
83
|
+
// Extract the latest block and checkpoint numbers
|
|
84
|
+
const previousBlockNumber = await this.getLatestL2BlockNumber();
|
|
85
|
+
const latestCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
86
|
+
// Verify we're not overwriting checkpointed blocks
|
|
87
|
+
const lastCheckpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
|
|
88
|
+
if (!opts.force && blockNumber <= lastCheckpointedBlockNumber) {
|
|
89
|
+
// Check if the proposed block matches the already-checkpointed one
|
|
90
|
+
const existingBlock = await this.getBlockData({
|
|
91
|
+
number: BlockNumber(blockNumber)
|
|
92
|
+
});
|
|
93
|
+
if (existingBlock && existingBlock.archive.root.equals(block.archive.root)) {
|
|
94
|
+
throw new BlockAlreadyCheckpointedError(blockNumber);
|
|
95
|
+
}
|
|
96
|
+
throw new CannotOverwriteCheckpointedBlockError(blockNumber, lastCheckpointedBlockNumber);
|
|
97
|
+
}
|
|
98
|
+
// Check that the block number is the expected one
|
|
99
|
+
if (!opts.force && previousBlockNumber !== blockNumber - 1) {
|
|
100
|
+
throw new BlockNumberNotSequentialError(blockNumber, previousBlockNumber);
|
|
101
|
+
}
|
|
102
|
+
// Accept the block if either the confirmed checkpoint or a pending checkpoint matches
|
|
103
|
+
// the expected predecessor. We look for a pending entry at exactly blockCheckpointNumber - 1.
|
|
104
|
+
const expectedCheckpointNumber = blockCheckpointNumber - 1;
|
|
105
|
+
const hasPendingAtExpected = await this.#proposedCheckpoints.hasAsync(expectedCheckpointNumber);
|
|
106
|
+
if (!opts.force && latestCheckpointNumber !== expectedCheckpointNumber && !hasPendingAtExpected) {
|
|
107
|
+
const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({
|
|
108
|
+
reverse: true,
|
|
109
|
+
limit: 1
|
|
110
|
+
}));
|
|
111
|
+
const previous = CheckpointNumber(Math.max(latestCheckpointNumber, latestPendingKey ?? 0));
|
|
112
|
+
throw new BlockCheckpointNumberNotSequentialError(BlockNumber(blockNumber), blockCheckpointNumber, previous);
|
|
113
|
+
}
|
|
114
|
+
// Extract the previous block if there is one and see if it is for the same checkpoint or not
|
|
115
|
+
const previousBlockResult = await this.getBlockData({
|
|
116
|
+
number: previousBlockNumber
|
|
117
|
+
});
|
|
118
|
+
let expectedBlockIndex = 0;
|
|
119
|
+
let previousBlockIndex = undefined;
|
|
120
|
+
if (previousBlockResult !== undefined) {
|
|
121
|
+
if (previousBlockResult.checkpointNumber === blockCheckpointNumber) {
|
|
122
|
+
// The previous block is for the same checkpoint, therefore our index should follow it
|
|
123
|
+
previousBlockIndex = previousBlockResult.indexWithinCheckpoint;
|
|
124
|
+
expectedBlockIndex = previousBlockIndex + 1;
|
|
125
|
+
}
|
|
126
|
+
if (!previousBlockResult.archive.root.equals(blockLastArchive)) {
|
|
127
|
+
throw new BlockArchiveNotConsistentError(blockNumber, previousBlockResult.header.globalVariables.blockNumber, blockLastArchive, previousBlockResult.archive.root);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// Now check that the block has the expected index value
|
|
131
|
+
if (!opts.force && expectedBlockIndex !== blockIndex) {
|
|
132
|
+
throw new BlockIndexNotSequentialError(blockIndex, previousBlockIndex);
|
|
133
|
+
}
|
|
134
|
+
await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
|
|
135
|
+
return true;
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Append new checkpoints to the store's list.
|
|
140
|
+
* @param checkpoints - The L2 checkpoints to be added to the store.
|
|
141
|
+
* @returns True if the operation is successful.
|
|
142
|
+
*/ async addCheckpoints(checkpoints, opts = {}) {
|
|
143
|
+
if (checkpoints.length === 0) {
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
146
|
+
return await this.db.transactionAsync(async ()=>{
|
|
147
|
+
const firstCheckpointNumber = checkpoints[0].checkpoint.number;
|
|
148
|
+
const previousCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
149
|
+
// Handle already-stored checkpoints at the start of the batch.
|
|
150
|
+
// This can happen after an L1 reorg re-includes a checkpoint in a different L1 block.
|
|
151
|
+
// We accept them if archives match (same content) and update their L1 metadata.
|
|
152
|
+
if (!opts.force && firstCheckpointNumber <= previousCheckpointNumber) {
|
|
153
|
+
checkpoints = await this.skipOrUpdateAlreadyStoredCheckpoints(checkpoints, previousCheckpointNumber);
|
|
154
|
+
if (checkpoints.length === 0) {
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
// Re-check sequentiality after skipping
|
|
158
|
+
const newFirstNumber = checkpoints[0].checkpoint.number;
|
|
159
|
+
if (previousCheckpointNumber !== newFirstNumber - 1) {
|
|
160
|
+
throw new InitialCheckpointNumberNotSequentialError(newFirstNumber, previousCheckpointNumber);
|
|
161
|
+
}
|
|
162
|
+
} else if (previousCheckpointNumber !== firstCheckpointNumber - 1 && !opts.force) {
|
|
163
|
+
throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
|
|
164
|
+
}
|
|
165
|
+
// Get the last block of the previous checkpoint for archive chaining
|
|
166
|
+
let previousBlock = await this.getPreviousCheckpointBlock(checkpoints[0].checkpoint.number);
|
|
167
|
+
// Iterate over checkpoints array and insert them, checking that the block numbers are sequential.
|
|
168
|
+
let previousCheckpoint = undefined;
|
|
169
|
+
for (const checkpoint of checkpoints){
|
|
170
|
+
if (!opts.force && previousCheckpoint && previousCheckpoint.checkpoint.number + 1 !== checkpoint.checkpoint.number) {
|
|
171
|
+
throw new CheckpointNumberNotSequentialError(checkpoint.checkpoint.number, previousCheckpoint.checkpoint.number);
|
|
172
|
+
}
|
|
173
|
+
previousCheckpoint = checkpoint;
|
|
174
|
+
// Validate block sequencing, indexes, and archive chaining
|
|
175
|
+
this.validateCheckpointBlocks(checkpoint.checkpoint.blocks, previousBlock);
|
|
176
|
+
// Store every block in the database (may already exist, but L1 data is authoritative)
|
|
177
|
+
for(let i = 0; i < checkpoint.checkpoint.blocks.length; i++){
|
|
178
|
+
await this.addBlockToDatabase(checkpoint.checkpoint.blocks[i], checkpoint.checkpoint.number, i);
|
|
179
|
+
}
|
|
180
|
+
previousBlock = checkpoint.checkpoint.blocks.at(-1);
|
|
181
|
+
// Store the checkpoint in the database
|
|
182
|
+
await this.#checkpoints.set(checkpoint.checkpoint.number, {
|
|
183
|
+
header: checkpoint.checkpoint.header.toBuffer(),
|
|
184
|
+
archive: checkpoint.checkpoint.archive.toBuffer(),
|
|
185
|
+
checkpointOutHash: checkpoint.checkpoint.getCheckpointOutHash().toBuffer(),
|
|
186
|
+
l1: checkpoint.l1.toBuffer(),
|
|
187
|
+
attestations: checkpoint.attestations.map((attestation)=>attestation.toBuffer()),
|
|
188
|
+
checkpointNumber: checkpoint.checkpoint.number,
|
|
189
|
+
startBlock: checkpoint.checkpoint.blocks[0].number,
|
|
190
|
+
blockCount: checkpoint.checkpoint.blocks.length,
|
|
191
|
+
feeAssetPriceModifier: checkpoint.checkpoint.feeAssetPriceModifier.toString()
|
|
192
|
+
});
|
|
193
|
+
// Update slot-to-checkpoint index
|
|
194
|
+
await this.#slotToCheckpoint.set(checkpoint.checkpoint.header.slotNumber, checkpoint.checkpoint.number);
|
|
195
|
+
// Remove proposed checkpoint if it exists, since L1 is authoritative
|
|
196
|
+
await this.#proposedCheckpoints.delete(checkpoint.checkpoint.number);
|
|
197
|
+
// Drop any rejected entry for this archive root: a checkpoint that was previously rejected
|
|
198
|
+
// (e.g. invalid attestations) is now being ingested as valid, so its descendants are allowed.
|
|
199
|
+
await this.removeRejectedCheckpointByArchiveRoot(checkpoint.checkpoint.archive.root);
|
|
200
|
+
}
|
|
201
|
+
await this.advanceSynchedL1BlockNumber(checkpoints[checkpoints.length - 1].l1.blockNumber);
|
|
202
|
+
return true;
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Handles checkpoints at the start of a batch that are already stored (e.g. due to L1 reorg).
|
|
207
|
+
* Verifies the archive root matches, updates L1 metadata, and returns only the new checkpoints.
|
|
208
|
+
*/ async skipOrUpdateAlreadyStoredCheckpoints(checkpoints, latestStored) {
|
|
209
|
+
let i = 0;
|
|
210
|
+
for(; i < checkpoints.length && checkpoints[i].checkpoint.number <= latestStored; i++){
|
|
211
|
+
const incoming = checkpoints[i];
|
|
212
|
+
const stored = await this.getCheckpointData(incoming.checkpoint.number);
|
|
213
|
+
if (!stored) {
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
// Verify the checkpoint content matches (archive root)
|
|
217
|
+
if (!stored.archive.root.equals(incoming.checkpoint.archive.root)) {
|
|
218
|
+
throw new Error(`Checkpoint ${incoming.checkpoint.number} already exists in store but with a different archive root. ` + `Stored: ${stored.archive.root}, incoming: ${incoming.checkpoint.archive.root}`);
|
|
219
|
+
}
|
|
220
|
+
// Update L1 metadata and attestations for the already-stored checkpoint
|
|
221
|
+
this.#log.warn(`Checkpoint ${incoming.checkpoint.number} already stored, updating L1 info ` + `(L1 block ${stored.l1.blockNumber} -> ${incoming.l1.blockNumber})`);
|
|
222
|
+
await this.#checkpoints.set(incoming.checkpoint.number, {
|
|
223
|
+
header: incoming.checkpoint.header.toBuffer(),
|
|
224
|
+
archive: incoming.checkpoint.archive.toBuffer(),
|
|
225
|
+
checkpointOutHash: incoming.checkpoint.getCheckpointOutHash().toBuffer(),
|
|
226
|
+
l1: incoming.l1.toBuffer(),
|
|
227
|
+
attestations: incoming.attestations.map((a)=>a.toBuffer()),
|
|
228
|
+
checkpointNumber: incoming.checkpoint.number,
|
|
229
|
+
startBlock: incoming.checkpoint.blocks[0].number,
|
|
230
|
+
blockCount: incoming.checkpoint.blocks.length,
|
|
231
|
+
feeAssetPriceModifier: incoming.checkpoint.feeAssetPriceModifier.toString()
|
|
232
|
+
});
|
|
233
|
+
// Update the sync point to reflect the new L1 block
|
|
234
|
+
await this.advanceSynchedL1BlockNumber(incoming.l1.blockNumber);
|
|
235
|
+
}
|
|
236
|
+
return checkpoints.slice(i);
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Gets the last block of the checkpoint before the given one.
|
|
240
|
+
* Returns undefined if there is no previous checkpoint (i.e. genesis).
|
|
241
|
+
*/ async getPreviousCheckpointBlock(checkpointNumber) {
|
|
242
|
+
const previousCheckpointNumber = CheckpointNumber(checkpointNumber - 1);
|
|
243
|
+
if (previousCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
// Check across both proposed and mined checkpoints
|
|
247
|
+
const predecessor = await this.getProposedCheckpointByNumber(previousCheckpointNumber) ?? await this.getCheckpointData(previousCheckpointNumber);
|
|
248
|
+
if (!predecessor) {
|
|
249
|
+
throw new CheckpointNotFoundError(previousCheckpointNumber);
|
|
250
|
+
}
|
|
251
|
+
const previousBlockNumber = BlockNumber(predecessor.startBlock + predecessor.blockCount - 1);
|
|
252
|
+
const previousBlock = await this.getBlock({
|
|
253
|
+
number: previousBlockNumber
|
|
254
|
+
});
|
|
255
|
+
if (previousBlock === undefined) {
|
|
256
|
+
throw new BlockNotFoundError(previousBlockNumber);
|
|
257
|
+
}
|
|
258
|
+
return previousBlock;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Validates that blocks are sequential, have correct indexes, and chain via archive roots.
|
|
262
|
+
* This is the same validation used for both confirmed checkpoints (addCheckpoints) and
|
|
263
|
+
* proposed checkpoints (addProposedCheckpoint).
|
|
264
|
+
*/ validateCheckpointBlocks(blocks, previousBlock) {
|
|
265
|
+
for (const block of blocks){
|
|
266
|
+
if (previousBlock) {
|
|
267
|
+
if (previousBlock.number !== block.number - 1) {
|
|
268
|
+
throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
|
|
269
|
+
}
|
|
270
|
+
if (previousBlock.checkpointNumber === block.checkpointNumber) {
|
|
271
|
+
if (previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1) {
|
|
272
|
+
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
|
|
273
|
+
}
|
|
274
|
+
} else if (block.indexWithinCheckpoint !== 0) {
|
|
275
|
+
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
|
|
276
|
+
}
|
|
277
|
+
if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
|
|
278
|
+
throw new BlockArchiveNotConsistentError(block.number, previousBlock.number, block.header.lastArchive.root, previousBlock.archive.root);
|
|
279
|
+
}
|
|
280
|
+
} else {
|
|
281
|
+
if (block.indexWithinCheckpoint !== 0) {
|
|
282
|
+
throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
|
|
283
|
+
}
|
|
284
|
+
if (block.number !== INITIAL_L2_BLOCK_NUM) {
|
|
285
|
+
throw new BlockNumberNotSequentialError(block.number, undefined);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
previousBlock = block;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
async addBlockToDatabase(block, checkpointNumber, indexWithinCheckpoint) {
|
|
292
|
+
const blockHash = await block.hash();
|
|
293
|
+
await this.#blocks.set(block.number, {
|
|
294
|
+
header: block.header.toBuffer(),
|
|
295
|
+
blockHash: blockHash.toBuffer(),
|
|
296
|
+
archive: block.archive.toBuffer(),
|
|
297
|
+
checkpointNumber,
|
|
298
|
+
indexWithinCheckpoint
|
|
299
|
+
});
|
|
300
|
+
for(let i = 0; i < block.body.txEffects.length; i++){
|
|
301
|
+
const txEffect = {
|
|
302
|
+
data: block.body.txEffects[i],
|
|
303
|
+
l2BlockNumber: block.number,
|
|
304
|
+
l2BlockHash: blockHash,
|
|
305
|
+
txIndexInBlock: i
|
|
306
|
+
};
|
|
307
|
+
await this.#txEffects.set(txEffect.data.txHash.toString(), serializeIndexedTxEffect(txEffect));
|
|
308
|
+
}
|
|
309
|
+
await this.#blockTxs.set(blockHash.toString(), Buffer.concat(block.body.txEffects.map((tx)=>tx.txHash.toBuffer())));
|
|
310
|
+
// Update indices for block hash and archive
|
|
311
|
+
await this.#blockHashIndex.set(blockHash.toString(), block.number);
|
|
312
|
+
await this.#blockArchiveIndex.set(block.archive.root.toString(), block.number);
|
|
313
|
+
}
|
|
314
|
+
/** Deletes a block and all associated data (tx effects, indices). */ async deleteBlock(block) {
|
|
315
|
+
// Delete the block from the main blocks map
|
|
316
|
+
await this.#blocks.delete(block.number);
|
|
317
|
+
// Delete all tx effects for this block
|
|
318
|
+
await Promise.all(block.body.txEffects.map((tx)=>this.#txEffects.delete(tx.txHash.toString())));
|
|
319
|
+
// Delete block txs mapping
|
|
320
|
+
const blockHash = (await block.hash()).toString();
|
|
321
|
+
await this.#blockTxs.delete(blockHash);
|
|
322
|
+
// Clean up indices
|
|
323
|
+
await this.#blockHashIndex.delete(blockHash);
|
|
324
|
+
await this.#blockArchiveIndex.delete(block.archive.root.toString());
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Removes all checkpoints with checkpoint number > checkpointNumber.
|
|
328
|
+
* Also removes ALL blocks (both checkpointed and uncheckpointed) after the last block of the given checkpoint.
|
|
329
|
+
* @param checkpointNumber - Remove all checkpoints strictly after this one.
|
|
330
|
+
*/ async removeCheckpointsAfter(checkpointNumber) {
|
|
331
|
+
return await this.db.transactionAsync(async ()=>{
|
|
332
|
+
const latestCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
333
|
+
if (checkpointNumber >= latestCheckpointNumber) {
|
|
334
|
+
this.#log.warn(`No checkpoints to remove after ${checkpointNumber} (latest is ${latestCheckpointNumber})`);
|
|
335
|
+
return {
|
|
336
|
+
blocksRemoved: undefined
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
// If the proven checkpoint is beyond the target, update it
|
|
340
|
+
const proven = await this.getProvenCheckpointNumber();
|
|
341
|
+
if (proven > checkpointNumber) {
|
|
342
|
+
this.#log.warn(`Updating proven checkpoint ${proven} to last valid checkpoint ${checkpointNumber}`);
|
|
343
|
+
await this.setProvenCheckpointNumber(checkpointNumber);
|
|
344
|
+
}
|
|
345
|
+
// Find the last block number to keep (last block of the given checkpoint, or 0 if no checkpoint)
|
|
346
|
+
let lastBlockToKeep;
|
|
347
|
+
if (checkpointNumber <= 0) {
|
|
348
|
+
lastBlockToKeep = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
349
|
+
} else {
|
|
350
|
+
const targetCheckpoint = await this.#checkpoints.getAsync(checkpointNumber);
|
|
351
|
+
if (!targetCheckpoint) {
|
|
352
|
+
throw new Error(`Target checkpoint ${checkpointNumber} not found in store`);
|
|
353
|
+
}
|
|
354
|
+
lastBlockToKeep = BlockNumber(targetCheckpoint.startBlock + targetCheckpoint.blockCount - 1);
|
|
355
|
+
}
|
|
356
|
+
// Remove all blocks after lastBlockToKeep (both checkpointed and uncheckpointed)
|
|
357
|
+
const blocksRemoved = await this.removeBlocksAfter(lastBlockToKeep);
|
|
358
|
+
// Remove all checkpoints after the target
|
|
359
|
+
for(let c = latestCheckpointNumber; c > checkpointNumber; c = CheckpointNumber(c - 1)){
|
|
360
|
+
const checkpointStorage = await this.#checkpoints.getAsync(c);
|
|
361
|
+
if (checkpointStorage) {
|
|
362
|
+
const slotNumber = CheckpointHeader.fromBuffer(checkpointStorage.header).slotNumber;
|
|
363
|
+
await this.#slotToCheckpoint.delete(slotNumber);
|
|
364
|
+
}
|
|
365
|
+
await this.#checkpoints.delete(c);
|
|
366
|
+
this.#log.debug(`Removed checkpoint ${c}`);
|
|
367
|
+
}
|
|
368
|
+
// Evict all pending checkpoints > checkpointNumber (their base chain no longer exists)
|
|
369
|
+
await this.evictProposedCheckpointsFrom(CheckpointNumber(checkpointNumber + 1));
|
|
370
|
+
return {
|
|
371
|
+
blocksRemoved
|
|
372
|
+
};
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
async getCheckpointData(checkpointNumber) {
|
|
376
|
+
const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
|
|
377
|
+
if (!checkpointStorage) {
|
|
378
|
+
return undefined;
|
|
379
|
+
}
|
|
380
|
+
return this.checkpointDataFromCheckpointStorage(checkpointStorage);
|
|
381
|
+
}
|
|
382
|
+
async getRangeOfCheckpoints(from, limit) {
|
|
383
|
+
const checkpoints = [];
|
|
384
|
+
for(let checkpointNumber = from; checkpointNumber < from + limit; checkpointNumber++){
|
|
385
|
+
const checkpoint = await this.#checkpoints.getAsync(checkpointNumber);
|
|
386
|
+
if (!checkpoint) {
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
checkpoints.push(this.checkpointDataFromCheckpointStorage(checkpoint));
|
|
390
|
+
}
|
|
391
|
+
return checkpoints;
|
|
392
|
+
}
|
|
393
|
+
/** Returns checkpoint data for all checkpoints whose slot falls within the given range (inclusive). */ async getCheckpointDataForSlotRange(startSlot, endSlot) {
|
|
394
|
+
const result = [];
|
|
395
|
+
for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync({
|
|
396
|
+
start: startSlot,
|
|
397
|
+
end: endSlot + 1
|
|
398
|
+
})){
|
|
399
|
+
const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
|
|
400
|
+
if (checkpointStorage) {
|
|
401
|
+
result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage));
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return result;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Returns the checkpoint numbers for all checkpoints whose slot falls within the given range (inclusive).
|
|
408
|
+
* Lighter than {@link getCheckpointDataForSlotRange} when callers only need to identify which
|
|
409
|
+
* checkpoints fall in the range and will fetch full data for at most a few of them.
|
|
410
|
+
*/ async getCheckpointNumbersForSlotRange(startSlot, endSlot) {
|
|
411
|
+
const result = [];
|
|
412
|
+
for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync({
|
|
413
|
+
start: startSlot,
|
|
414
|
+
end: endSlot + 1
|
|
415
|
+
})){
|
|
416
|
+
result.push(CheckpointNumber(checkpointNumber));
|
|
417
|
+
}
|
|
418
|
+
return result;
|
|
419
|
+
}
|
|
420
|
+
checkpointDataFromCheckpointStorage(checkpointStorage) {
|
|
421
|
+
return {
|
|
422
|
+
header: CheckpointHeader.fromBuffer(checkpointStorage.header),
|
|
423
|
+
archive: AppendOnlyTreeSnapshot.fromBuffer(checkpointStorage.archive),
|
|
424
|
+
checkpointOutHash: Fr.fromBuffer(checkpointStorage.checkpointOutHash),
|
|
425
|
+
checkpointNumber: CheckpointNumber(checkpointStorage.checkpointNumber),
|
|
426
|
+
startBlock: BlockNumber(checkpointStorage.startBlock),
|
|
427
|
+
blockCount: checkpointStorage.blockCount,
|
|
428
|
+
feeAssetPriceModifier: BigInt(checkpointStorage.feeAssetPriceModifier),
|
|
429
|
+
l1: L1PublishedData.fromBuffer(checkpointStorage.l1),
|
|
430
|
+
attestations: checkpointStorage.attestations.map((buf)=>CommitteeAttestation.fromBuffer(buf))
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
async getBlocksForCheckpoint(checkpointNumber) {
|
|
434
|
+
const checkpoint = await this.#checkpoints.getAsync(checkpointNumber);
|
|
435
|
+
if (!checkpoint) {
|
|
436
|
+
return undefined;
|
|
437
|
+
}
|
|
438
|
+
const blocksForCheckpoint = await toArray(this.#blocks.entriesAsync({
|
|
439
|
+
start: checkpoint.startBlock,
|
|
440
|
+
end: checkpoint.startBlock + checkpoint.blockCount
|
|
441
|
+
}));
|
|
442
|
+
const converted = await Promise.all(blocksForCheckpoint.map((x)=>this.getBlockFromBlockStorage(x[0], x[1])));
|
|
443
|
+
return converted.filter(isDefined);
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Gets all blocks that have the given slot number.
|
|
447
|
+
* Iterates backwards through blocks for efficiency since we usually query for the last slot.
|
|
448
|
+
* @param slotNumber - The slot number to search for.
|
|
449
|
+
* @returns All blocks with the given slot number, in ascending block number order.
|
|
450
|
+
*/ async getBlocksForSlot(slotNumber) {
|
|
451
|
+
const blocks = [];
|
|
452
|
+
// Iterate backwards through all blocks and filter by slot number
|
|
453
|
+
// This is more efficient since we usually query for the most recent slot
|
|
454
|
+
for await (const [blockNumber, blockStorage] of this.#blocks.entriesAsync({
|
|
455
|
+
reverse: true
|
|
456
|
+
})){
|
|
457
|
+
const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
|
|
458
|
+
const blockSlot = block?.header.globalVariables.slotNumber;
|
|
459
|
+
if (block && blockSlot === slotNumber) {
|
|
460
|
+
blocks.push(block);
|
|
461
|
+
} else if (blockSlot && blockSlot < slotNumber) {
|
|
462
|
+
break; // Blocks are stored in slot ascending order, so we can stop searching
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
// Reverse to return blocks in ascending order (block number order)
|
|
466
|
+
return blocks.reverse();
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Removes all blocks with block number > blockNumber.
|
|
470
|
+
* Does not remove any associated checkpoints.
|
|
471
|
+
* @param blockNumber - The block number to remove after.
|
|
472
|
+
* @returns The removed blocks (for event emission).
|
|
473
|
+
*/ async removeBlocksAfter(blockNumber) {
|
|
474
|
+
return await this.db.transactionAsync(async ()=>{
|
|
475
|
+
const removedBlocks = [];
|
|
476
|
+
// Get the latest block number to determine the range
|
|
477
|
+
const latestBlockNumber = await this.getLatestL2BlockNumber();
|
|
478
|
+
// Iterate from blockNumber + 1 to latestBlockNumber
|
|
479
|
+
for(let bn = blockNumber + 1; bn <= latestBlockNumber; bn++){
|
|
480
|
+
const block = await this.getBlock({
|
|
481
|
+
number: BlockNumber(bn)
|
|
482
|
+
});
|
|
483
|
+
if (block === undefined) {
|
|
484
|
+
this.#log.warn(`Cannot remove block ${bn} from the store since we don't have it`);
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
removedBlocks.push(block);
|
|
488
|
+
await this.deleteBlock(block);
|
|
489
|
+
this.#log.debug(`Removed block ${bn} ${(await block.hash()).toString()}`);
|
|
490
|
+
}
|
|
491
|
+
return removedBlocks;
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
async getProvenBlockNumber() {
|
|
495
|
+
const provenCheckpointNumber = await this.getProvenCheckpointNumber();
|
|
496
|
+
if (provenCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
|
|
497
|
+
return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
498
|
+
}
|
|
499
|
+
const checkpointStorage = await this.#checkpoints.getAsync(provenCheckpointNumber);
|
|
500
|
+
if (!checkpointStorage) {
|
|
501
|
+
throw new CheckpointNotFoundError(provenCheckpointNumber);
|
|
502
|
+
} else {
|
|
503
|
+
return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
async getLatestCheckpointNumber() {
|
|
507
|
+
const [latestCheckpointNumber] = await toArray(this.#checkpoints.keysAsync({
|
|
508
|
+
reverse: true,
|
|
509
|
+
limit: 1
|
|
510
|
+
}));
|
|
511
|
+
if (latestCheckpointNumber === undefined) {
|
|
512
|
+
return CheckpointNumber(INITIAL_CHECKPOINT_NUMBER - 1);
|
|
513
|
+
}
|
|
514
|
+
return CheckpointNumber(latestCheckpointNumber);
|
|
515
|
+
}
|
|
516
|
+
async hasProposedCheckpoint() {
|
|
517
|
+
const [key] = await toArray(this.#proposedCheckpoints.keysAsync({
|
|
518
|
+
limit: 1
|
|
519
|
+
}));
|
|
520
|
+
return key !== undefined;
|
|
521
|
+
}
|
|
522
|
+
/** Deletes all pending proposed checkpoints from storage. */ async deleteProposedCheckpoints() {
|
|
523
|
+
for await (const key of this.#proposedCheckpoints.keysAsync()){
|
|
524
|
+
await this.#proposedCheckpoints.delete(key);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Promotes a specific pending checkpoint to a confirmed checkpoint entry.
|
|
529
|
+
* This persists the checkpoint to the store, removes only that pending entry, and updates the L1 sync point.
|
|
530
|
+
* Remaining pending entries (e.g. N+1, N+2) are left intact — they chain off the just-promoted one.
|
|
531
|
+
* @param checkpointNumber - The checkpoint number to promote.
|
|
532
|
+
* @param l1 - L1 published data for the checkpoint.
|
|
533
|
+
* @param attestations - Committee attestations.
|
|
534
|
+
* @param expectedArchiveRoot - Archive root guard against races.
|
|
535
|
+
*/ async promoteProposedToCheckpointed(checkpointNumber, l1, attestations, expectedArchiveRoot) {
|
|
536
|
+
return await this.db.transactionAsync(async ()=>{
|
|
537
|
+
const proposed = await this.getProposedCheckpointByNumber(checkpointNumber);
|
|
538
|
+
if (!proposed) {
|
|
539
|
+
throw new NoProposedCheckpointToPromoteError();
|
|
540
|
+
}
|
|
541
|
+
if (!proposed.archive.root.equals(expectedArchiveRoot)) {
|
|
542
|
+
throw new ProposedCheckpointArchiveRootMismatchError(expectedArchiveRoot, proposed.archive.root);
|
|
543
|
+
}
|
|
544
|
+
// Verify sequentiality: promoted checkpoint must follow the latest confirmed one
|
|
545
|
+
const latestCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
546
|
+
if (latestCheckpointNumber !== proposed.checkpointNumber - 1) {
|
|
547
|
+
throw new ProposedCheckpointPromotionNotSequentialError(proposed.checkpointNumber, latestCheckpointNumber);
|
|
548
|
+
}
|
|
549
|
+
// Write the checkpoint entry
|
|
550
|
+
await this.#checkpoints.set(proposed.checkpointNumber, {
|
|
551
|
+
header: proposed.header.toBuffer(),
|
|
552
|
+
archive: proposed.archive.toBuffer(),
|
|
553
|
+
checkpointOutHash: proposed.checkpointOutHash.toBuffer(),
|
|
554
|
+
l1: l1.toBuffer(),
|
|
555
|
+
attestations: attestations.map((attestation)=>attestation.toBuffer()),
|
|
556
|
+
checkpointNumber: proposed.checkpointNumber,
|
|
557
|
+
startBlock: proposed.startBlock,
|
|
558
|
+
blockCount: proposed.blockCount,
|
|
559
|
+
feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString()
|
|
560
|
+
});
|
|
561
|
+
// Update the slot-to-checkpoint index
|
|
562
|
+
await this.#slotToCheckpoint.set(proposed.header.slotNumber, proposed.checkpointNumber);
|
|
563
|
+
// Remove only this pending entry — remaining entries N+1, N+2, ... stay valid
|
|
564
|
+
await this.#proposedCheckpoints.delete(proposed.checkpointNumber);
|
|
565
|
+
// Drop any rejected entry for this archive root: a checkpoint that was previously rejected
|
|
566
|
+
// (e.g. invalid attestations) is now being promoted as valid, so its descendants are allowed.
|
|
567
|
+
await this.removeRejectedCheckpointByArchiveRoot(proposed.archive.root);
|
|
568
|
+
// Update the last synced L1 block
|
|
569
|
+
await this.advanceSynchedL1BlockNumber(l1.blockNumber);
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Returns the latest pending checkpoint (highest-numbered entry), or undefined if none.
|
|
574
|
+
* No fallback to confirmed.
|
|
575
|
+
*/ async getLastProposedCheckpoint() {
|
|
576
|
+
const [key] = await toArray(this.#proposedCheckpoints.keysAsync({
|
|
577
|
+
reverse: true,
|
|
578
|
+
limit: 1
|
|
579
|
+
}));
|
|
580
|
+
if (key === undefined) {
|
|
581
|
+
return undefined;
|
|
582
|
+
}
|
|
583
|
+
const stored = await this.#proposedCheckpoints.getAsync(key);
|
|
584
|
+
return stored ? this.convertToProposedCheckpointData(stored) : undefined;
|
|
585
|
+
}
|
|
586
|
+
/** Returns the pending checkpoint for a specific checkpoint number, or undefined if not found. */ async getProposedCheckpointByNumber(n) {
|
|
587
|
+
const stored = await this.#proposedCheckpoints.getAsync(n);
|
|
588
|
+
return stored ? this.convertToProposedCheckpointData(stored) : undefined;
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Returns the pending checkpoint whose header slot matches the given slot, or undefined if not found.
|
|
592
|
+
* Iterates `#proposedCheckpoints` rather than reading an index because the map carries 0–1 entries
|
|
593
|
+
* in normal operation (bounded by the proposer pipelining window). Returns the first match.
|
|
594
|
+
*/ async getProposedCheckpointBySlot(slot) {
|
|
595
|
+
for await (const [, stored] of this.#proposedCheckpoints.entriesAsync()){
|
|
596
|
+
const header = CheckpointHeader.fromBuffer(stored.header);
|
|
597
|
+
if (header.slotNumber === slot) {
|
|
598
|
+
return this.convertToProposedCheckpointData(stored);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
return undefined;
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Evicts all pending checkpoints with checkpoint number >= fromNumber.
|
|
605
|
+
* Used for divergent-mined-checkpoint cleanup: when L1 mines checkpoint N with a different archive,
|
|
606
|
+
* all pending >= N must be evicted since they chain off the now-invalid pending N.
|
|
607
|
+
*/ async evictProposedCheckpointsFrom(fromNumber) {
|
|
608
|
+
const keysToDelete = [];
|
|
609
|
+
for await (const key of this.#proposedCheckpoints.keysAsync()){
|
|
610
|
+
if (key >= fromNumber) {
|
|
611
|
+
keysToDelete.push(key);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
for (const key of keysToDelete){
|
|
615
|
+
await this.#proposedCheckpoints.delete(key);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Gets the checkpoint at the proposed tip:
|
|
620
|
+
* - latest pending checkpoint if any exist
|
|
621
|
+
* - fallsback to latest confirmed checkpoint otherwise
|
|
622
|
+
*/ async getLastCheckpoint() {
|
|
623
|
+
const latest = await this.getLastProposedCheckpoint();
|
|
624
|
+
if (!latest) {
|
|
625
|
+
return this.getCheckpointData(await this.getLatestCheckpointNumber());
|
|
626
|
+
}
|
|
627
|
+
return latest;
|
|
628
|
+
}
|
|
629
|
+
convertToProposedCheckpointData(stored) {
|
|
630
|
+
return {
|
|
631
|
+
checkpointNumber: CheckpointNumber(stored.checkpointNumber),
|
|
632
|
+
header: CheckpointHeader.fromBuffer(stored.header),
|
|
633
|
+
archive: AppendOnlyTreeSnapshot.fromBuffer(stored.archive),
|
|
634
|
+
checkpointOutHash: Fr.fromBuffer(stored.checkpointOutHash),
|
|
635
|
+
startBlock: BlockNumber(stored.startBlock),
|
|
636
|
+
blockCount: stored.blockCount,
|
|
637
|
+
totalManaUsed: BigInt(stored.totalManaUsed),
|
|
638
|
+
feeAssetPriceModifier: BigInt(stored.feeAssetPriceModifier)
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Attempts to get the proposedCheckpoint's number, if there is not one, then fallback to the latest confirmed checkpoint number.
|
|
643
|
+
* @returns CheckpointNumber
|
|
644
|
+
*/ async getProposedCheckpointNumber() {
|
|
645
|
+
const proposed = await this.getLastCheckpoint();
|
|
646
|
+
if (!proposed) {
|
|
647
|
+
return await this.getLatestCheckpointNumber();
|
|
648
|
+
}
|
|
649
|
+
return CheckpointNumber(proposed.checkpointNumber);
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* Attempts to get the proposedCheckpoint's block number, if there is not one, then fallback to the checkpointed block number
|
|
653
|
+
* @returns BlockNumber
|
|
654
|
+
*/ async getProposedCheckpointL2BlockNumber() {
|
|
655
|
+
const proposed = await this.getLastCheckpoint();
|
|
656
|
+
if (!proposed) {
|
|
657
|
+
return await this.getCheckpointedL2BlockNumber();
|
|
658
|
+
}
|
|
659
|
+
return BlockNumber(proposed.startBlock + proposed.blockCount - 1);
|
|
660
|
+
}
|
|
661
|
+
/** Returns the checkpoint number that contains the given slot (or undefined if not found). */ async getCheckpointNumberBySlot(slot) {
|
|
662
|
+
const checkpointNumber = await this.#slotToCheckpoint.getAsync(slot);
|
|
663
|
+
return checkpointNumber === undefined ? undefined : CheckpointNumber(checkpointNumber);
|
|
664
|
+
}
|
|
665
|
+
/** Gets a single L2 block matching the given resolved query. */ async getBlock(query) {
|
|
666
|
+
const blockNumber = await this.getBlockNumber(query);
|
|
667
|
+
if (blockNumber === undefined) {
|
|
668
|
+
return undefined;
|
|
669
|
+
}
|
|
670
|
+
const blockStorage = await this.#blocks.getAsync(blockNumber);
|
|
671
|
+
if (!blockStorage) {
|
|
672
|
+
return undefined;
|
|
673
|
+
}
|
|
674
|
+
return this.getBlockFromBlockStorage(blockNumber, blockStorage);
|
|
675
|
+
}
|
|
676
|
+
/** Gets a collection of L2 blocks for a resolved range. */ getBlocks(query) {
|
|
677
|
+
return toArray(this.iterateBlocks(query));
|
|
678
|
+
}
|
|
679
|
+
/** Gets single block metadata matching the given resolved query. */ async getBlockData(query) {
|
|
680
|
+
const blockNumber = await this.getBlockNumber(query);
|
|
681
|
+
if (blockNumber === undefined) {
|
|
682
|
+
return undefined;
|
|
683
|
+
}
|
|
684
|
+
const blockStorage = await this.#blocks.getAsync(blockNumber);
|
|
685
|
+
if (!blockStorage || !blockStorage.header) {
|
|
686
|
+
return undefined;
|
|
687
|
+
}
|
|
688
|
+
return this.getBlockDataFromBlockStorage(blockStorage);
|
|
689
|
+
}
|
|
690
|
+
/** Gets a collection of block metadata entries for a resolved range. */ getBlocksData(query) {
|
|
691
|
+
return toArray(this.iterateBlocksData(query));
|
|
692
|
+
}
|
|
693
|
+
/** Async iterator over L2 blocks for a resolved range. */ async *iterateBlocks(query) {
|
|
694
|
+
const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
|
|
695
|
+
for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)){
|
|
696
|
+
if (cap !== undefined && blockNumber > cap) {
|
|
697
|
+
break;
|
|
698
|
+
}
|
|
699
|
+
const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
|
|
700
|
+
if (block) {
|
|
701
|
+
yield block;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
/** Async iterator over block metadata for a resolved range. */ async *iterateBlocksData(query) {
|
|
706
|
+
const cap = query.onlyCheckpointed ? await this.getCheckpointedL2BlockNumber() : undefined;
|
|
707
|
+
for await (const [blockNumber, blockStorage] of this.getBlockStorages(query.from, query.limit)){
|
|
708
|
+
if (cap !== undefined && blockNumber > cap) {
|
|
709
|
+
break;
|
|
710
|
+
}
|
|
711
|
+
yield this.getBlockDataFromBlockStorage(blockStorage);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
async *getBlockStorages(start, limit) {
|
|
715
|
+
let expectedBlockNumber = start;
|
|
716
|
+
for await (const [blockNumber, blockStorage] of this.#blocks.entriesAsync(this.#computeBlockRange(start, limit))){
|
|
717
|
+
if (blockNumber !== expectedBlockNumber) {
|
|
718
|
+
throw new Error(`Block number mismatch when iterating blocks from archive (expected ${expectedBlockNumber} but got ${blockNumber})`);
|
|
719
|
+
}
|
|
720
|
+
expectedBlockNumber++;
|
|
721
|
+
yield [
|
|
722
|
+
blockNumber,
|
|
723
|
+
blockStorage
|
|
724
|
+
];
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
/** Resolves a ResolvedBlockQuery discriminant to a block number, or undefined if not found. */ async getBlockNumber(query) {
|
|
728
|
+
let blockNumber;
|
|
729
|
+
if ('number' in query) {
|
|
730
|
+
blockNumber = query.number;
|
|
731
|
+
} else if ('hash' in query) {
|
|
732
|
+
const n = await this.#blockHashIndex.getAsync(query.hash.toString());
|
|
733
|
+
blockNumber = n !== undefined ? BlockNumber(n) : undefined;
|
|
734
|
+
} else {
|
|
735
|
+
const n = await this.#blockArchiveIndex.getAsync(query.archive.toString());
|
|
736
|
+
blockNumber = n !== undefined ? BlockNumber(n) : undefined;
|
|
737
|
+
}
|
|
738
|
+
if (blockNumber === undefined) {
|
|
739
|
+
return undefined;
|
|
740
|
+
}
|
|
741
|
+
return blockNumber;
|
|
742
|
+
}
|
|
743
|
+
getBlockDataFromBlockStorage(blockStorage) {
|
|
744
|
+
return {
|
|
745
|
+
header: BlockHeader.fromBuffer(blockStorage.header),
|
|
746
|
+
archive: AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),
|
|
747
|
+
blockHash: BlockHash.fromBuffer(blockStorage.blockHash),
|
|
748
|
+
checkpointNumber: CheckpointNumber(blockStorage.checkpointNumber),
|
|
749
|
+
indexWithinCheckpoint: IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint)
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
async getBlockFromBlockStorage(blockNumber, blockStorage) {
|
|
753
|
+
const { header, archive, blockHash, checkpointNumber, indexWithinCheckpoint } = this.getBlockDataFromBlockStorage(blockStorage);
|
|
754
|
+
header.setHash(blockHash);
|
|
755
|
+
const blockHashString = bufferToHex(blockStorage.blockHash);
|
|
756
|
+
const blockTxsBuffer = await this.#blockTxs.getAsync(blockHashString);
|
|
757
|
+
if (blockTxsBuffer === undefined) {
|
|
758
|
+
this.#log.warn(`Could not find body for block ${header.globalVariables.blockNumber} ${blockHash}`);
|
|
759
|
+
return undefined;
|
|
760
|
+
}
|
|
761
|
+
const txEffects = [];
|
|
762
|
+
const reader = BufferReader.asReader(blockTxsBuffer);
|
|
763
|
+
while(!reader.isEmpty()){
|
|
764
|
+
const txHash = reader.readObject(TxHash);
|
|
765
|
+
const txEffect = await this.#txEffects.getAsync(txHash.toString());
|
|
766
|
+
if (txEffect === undefined) {
|
|
767
|
+
this.#log.warn(`Could not find tx effect for tx ${txHash} in block ${blockNumber}`);
|
|
768
|
+
return undefined;
|
|
769
|
+
}
|
|
770
|
+
txEffects.push(deserializeIndexedTxEffect(txEffect).data);
|
|
771
|
+
}
|
|
772
|
+
const body = new Body(txEffects);
|
|
773
|
+
const block = new L2Block(archive, header, body, checkpointNumber, indexWithinCheckpoint);
|
|
774
|
+
if (block.number !== blockNumber) {
|
|
775
|
+
throw new Error(`Block number mismatch when retrieving block from archive (expected ${blockNumber} but got ${block.number} with hash ${blockHashString})`);
|
|
776
|
+
}
|
|
777
|
+
return block;
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Gets a tx effect.
|
|
781
|
+
* @param txHash - The hash of the tx corresponding to the tx effect.
|
|
782
|
+
* @returns The requested tx effect with block info (or undefined if not found).
|
|
783
|
+
*/ async getTxEffect(txHash) {
|
|
784
|
+
const buffer = await this.#txEffects.getAsync(txHash.toString());
|
|
785
|
+
if (!buffer) {
|
|
786
|
+
return undefined;
|
|
787
|
+
}
|
|
788
|
+
return deserializeIndexedTxEffect(buffer);
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Gets a receipt of a settled tx.
|
|
792
|
+
* @param txHash - The hash of a tx we try to get the receipt for.
|
|
793
|
+
* @returns The requested tx receipt (or undefined if not found).
|
|
794
|
+
*/ async getSettledTxReceipt(txHash, l1Constants) {
|
|
795
|
+
const txEffect = await this.getTxEffect(txHash);
|
|
796
|
+
if (!txEffect) {
|
|
797
|
+
return undefined;
|
|
798
|
+
}
|
|
799
|
+
const blockNumber = BlockNumber(txEffect.l2BlockNumber);
|
|
800
|
+
// Use existing archiver methods to determine finalization level
|
|
801
|
+
const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber, blockData] = await Promise.all([
|
|
802
|
+
this.getProvenBlockNumber(),
|
|
803
|
+
this.getCheckpointedL2BlockNumber(),
|
|
804
|
+
this.getFinalizedL2BlockNumber(),
|
|
805
|
+
this.getBlockData({
|
|
806
|
+
number: blockNumber
|
|
807
|
+
})
|
|
808
|
+
]);
|
|
809
|
+
let status;
|
|
810
|
+
if (blockNumber <= finalizedBlockNumber) {
|
|
811
|
+
status = TxStatus.FINALIZED;
|
|
812
|
+
} else if (blockNumber <= provenBlockNumber) {
|
|
813
|
+
status = TxStatus.PROVEN;
|
|
814
|
+
} else if (blockNumber <= checkpointedBlockNumber) {
|
|
815
|
+
status = TxStatus.CHECKPOINTED;
|
|
816
|
+
} else {
|
|
817
|
+
status = TxStatus.PROPOSED;
|
|
818
|
+
}
|
|
819
|
+
const epochNumber = blockData && l1Constants ? getEpochAtSlot(blockData.header.globalVariables.slotNumber, l1Constants) : undefined;
|
|
820
|
+
return new TxReceipt(txHash, status, TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode), undefined, txEffect.data.transactionFee.toBigInt(), txEffect.l2BlockHash, blockNumber, epochNumber);
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Looks up which block included the requested tx effect.
|
|
824
|
+
* @param txHash - The txHash of the tx.
|
|
825
|
+
* @returns The block number and index of the tx.
|
|
826
|
+
*/ async getTxLocation(txHash) {
|
|
827
|
+
const txEffect = await this.#txEffects.getAsync(txHash.toString());
|
|
828
|
+
if (!txEffect) {
|
|
829
|
+
return undefined;
|
|
830
|
+
}
|
|
831
|
+
// Read only the IndexedTxEffect header (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4)`); the
|
|
832
|
+
// large tail (the full TxEffect with logs etc.) is irrelevant here.
|
|
833
|
+
const view = Buffer.from(txEffect.buffer, txEffect.byteOffset, txEffect.byteLength);
|
|
834
|
+
const l2BlockNumber = view.readUInt32BE(32);
|
|
835
|
+
const txIndexInBlock = view.readUInt32BE(36);
|
|
836
|
+
return [
|
|
837
|
+
l2BlockNumber,
|
|
838
|
+
txIndexInBlock
|
|
839
|
+
];
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Batched, partial deserializer that fetches `noteHashes` and `nullifiers` (all of them) for the given
|
|
843
|
+
* txs. For each input txHash, returns a `[noteHashes, nullifiers]` tuple. Returns `[[], []]` for any
|
|
844
|
+
* unknown txHash. Preserves input order. Used by the log read path when `includeEffects` is set to
|
|
845
|
+
* attach effect data on demand without paying for a full {@link TxEffect} deserialization.
|
|
846
|
+
*
|
|
847
|
+
* The on-disk `IndexedTxEffect` layout starts with a fixed-length header
|
|
848
|
+
* (`blockHash(32) + l2BlockNumber(4) + txIndexInBlock(4) + revertCode(1) + txHash(32) + transactionFee(32)` =
|
|
849
|
+
* 105 bytes), followed by `noteHashes` and `nullifiers` (both u8-length-prefixed `Fr` vectors). We
|
|
850
|
+
* skip the header, then read the two vectors, and stop — the large tail (`l2ToL1Msgs`,
|
|
851
|
+
* `publicDataWrites`, `privateLogs`, `publicLogs`, `contractClassLogs`) is never touched.
|
|
852
|
+
*/ getNoteHashesAndNullifiers(txHashes) {
|
|
853
|
+
return Promise.all(txHashes.map(async (txHash)=>{
|
|
854
|
+
const buffer = await this.#txEffects.getAsync(txHash.toString());
|
|
855
|
+
if (!buffer) {
|
|
856
|
+
return [
|
|
857
|
+
[],
|
|
858
|
+
[]
|
|
859
|
+
];
|
|
860
|
+
}
|
|
861
|
+
const reader = BufferReader.asReader(buffer);
|
|
862
|
+
// Skip the fixed-length header: blockHash + l2BlockNumber + txIndexInBlock + revertCode + txHash + transactionFee.
|
|
863
|
+
reader.readBytes(32 + 4 + 4 + 1 + 32 + 32);
|
|
864
|
+
const noteHashes = reader.readVectorUint8Prefix(Fr);
|
|
865
|
+
const nullifiers = reader.readVectorUint8Prefix(Fr);
|
|
866
|
+
return [
|
|
867
|
+
noteHashes,
|
|
868
|
+
nullifiers
|
|
869
|
+
];
|
|
870
|
+
}));
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Looks up which block deployed a particular contract.
|
|
874
|
+
* @param contractAddress - The address of the contract to look up.
|
|
875
|
+
* @returns The block number and index of the contract.
|
|
876
|
+
*/ getContractLocation(contractAddress) {
|
|
877
|
+
return this.#contractIndex.getAsync(contractAddress.toString());
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Gets the number of the latest L2 block checkpointed.
|
|
881
|
+
* @returns The number of the latest L2 block checkpointed.
|
|
882
|
+
*/ async getCheckpointedL2BlockNumber() {
|
|
883
|
+
const latestCheckpointNumber = await this.getLatestCheckpointNumber();
|
|
884
|
+
const checkpoint = await this.getCheckpointData(latestCheckpointNumber);
|
|
885
|
+
if (!checkpoint) {
|
|
886
|
+
return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
887
|
+
}
|
|
888
|
+
return BlockNumber(checkpoint.startBlock + checkpoint.blockCount - 1);
|
|
889
|
+
}
|
|
890
|
+
async getLatestL2BlockNumber() {
|
|
891
|
+
const [lastBlockNumber] = await toArray(this.#blocks.keysAsync({
|
|
892
|
+
reverse: true,
|
|
893
|
+
limit: 1
|
|
894
|
+
}));
|
|
895
|
+
return typeof lastBlockNumber === 'number' ? BlockNumber(lastBlockNumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Resolves all five L2 chain tips (proposed, proposedCheckpoint, checkpointed, proven, finalized)
|
|
899
|
+
* in a single read-only transaction so the snapshot is internally consistent. Each underlying
|
|
900
|
+
* record is read at most once: latest block, latest confirmed checkpoint, and latest pending
|
|
901
|
+
* checkpoint are each loaded directly (no separate "find the number, then look up data" hop),
|
|
902
|
+
* the proven/finalized checkpoint singletons are read once and their storage entries are
|
|
903
|
+
* reused if they coincide with the latest checkpoint, and per-tip block hashes are deduped
|
|
904
|
+
* when two tips land on the same block (e.g. finalized == proven, or proposedCheckpoint falls
|
|
905
|
+
* back to checkpointed when no pending checkpoint exists).
|
|
906
|
+
*
|
|
907
|
+
* The result is guaranteed to satisfy `finalized <= proven <= checkpointed <= proposed` (by
|
|
908
|
+
* block number). Genesis is represented by `(INITIAL_L2_BLOCK_NUM - 1)` and the supplied
|
|
909
|
+
* `genesisBlockHash`, paired with the synthetic genesis checkpoint id.
|
|
910
|
+
*
|
|
911
|
+
* @param genesisBlockHash - Block hash to report for the synthetic pre-initial block (used when
|
|
912
|
+
* a tip is still at genesis).
|
|
913
|
+
*/ async getL2TipsData(genesisBlockHash) {
|
|
914
|
+
return await this.db.transactionAsync(async ()=>{
|
|
915
|
+
// Define genesis tips
|
|
916
|
+
const genesisBlockNumber = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
|
|
917
|
+
const genesisCheckpointNumber = CheckpointNumber(INITIAL_CHECKPOINT_NUMBER - 1);
|
|
918
|
+
const genesisBlockId = {
|
|
919
|
+
number: genesisBlockNumber,
|
|
920
|
+
hash: genesisBlockHash.toString()
|
|
921
|
+
};
|
|
922
|
+
const genesisCheckpointId = {
|
|
923
|
+
number: genesisCheckpointNumber,
|
|
924
|
+
hash: GENESIS_CHECKPOINT_HEADER_HASH.toString()
|
|
925
|
+
};
|
|
926
|
+
const genesisTip = {
|
|
927
|
+
block: genesisBlockId,
|
|
928
|
+
checkpoint: genesisCheckpointId
|
|
929
|
+
};
|
|
930
|
+
// Load latest block and checkpoint entries
|
|
931
|
+
const [latestBlockEntry] = await toArray(this.#blocks.entriesAsync({
|
|
932
|
+
reverse: true,
|
|
933
|
+
limit: 1
|
|
934
|
+
}));
|
|
935
|
+
const [proposedCheckpointEntry] = await toArray(this.#proposedCheckpoints.entriesAsync({
|
|
936
|
+
reverse: true,
|
|
937
|
+
limit: 1
|
|
938
|
+
}));
|
|
939
|
+
const [latestCheckpointEntry] = await toArray(this.#checkpoints.entriesAsync({
|
|
940
|
+
reverse: true,
|
|
941
|
+
limit: 1
|
|
942
|
+
}));
|
|
943
|
+
const latestCheckpointNumber = latestCheckpointEntry ? CheckpointNumber(latestCheckpointEntry[0]) : genesisCheckpointNumber;
|
|
944
|
+
// Load proven and finalized checkpoint number pointers
|
|
945
|
+
const [provenRaw, finalizedRaw] = await Promise.all([
|
|
946
|
+
this.#lastProvenCheckpoint.getAsync(),
|
|
947
|
+
this.#lastFinalizedCheckpoint.getAsync()
|
|
948
|
+
]);
|
|
949
|
+
// Clamp to enforce finalized <= proven <= checkpointed.
|
|
950
|
+
const provenCheckpointNumber = CheckpointNumber(Math.min(provenRaw ?? 0, latestCheckpointNumber));
|
|
951
|
+
const finalizedCheckpointNumber = CheckpointNumber(Math.min(finalizedRaw ?? 0, provenCheckpointNumber));
|
|
952
|
+
// Avoid loading the same checkpoint more than once
|
|
953
|
+
const checkpointStorageCache = new Map();
|
|
954
|
+
if (latestCheckpointEntry) {
|
|
955
|
+
checkpointStorageCache.set(CheckpointNumber(latestCheckpointEntry[0]), latestCheckpointEntry[1]);
|
|
956
|
+
}
|
|
957
|
+
const loadCheckpointStorage = async (n)=>{
|
|
958
|
+
if (n === 0) {
|
|
959
|
+
return undefined;
|
|
960
|
+
}
|
|
961
|
+
if (!checkpointStorageCache.has(n)) {
|
|
962
|
+
const checkpointStorage = await this.#checkpoints.getAsync(n);
|
|
963
|
+
if (!checkpointStorage) {
|
|
964
|
+
throw new CheckpointNotFoundError(n);
|
|
965
|
+
}
|
|
966
|
+
checkpointStorageCache.set(n, checkpointStorage);
|
|
967
|
+
}
|
|
968
|
+
return checkpointStorageCache.get(n);
|
|
969
|
+
};
|
|
970
|
+
// Load proven and finalized checkpoint storage entries
|
|
971
|
+
const provenCheckpoint = await loadCheckpointStorage(provenCheckpointNumber);
|
|
972
|
+
const finalizedCheckpoint = await loadCheckpointStorage(finalizedCheckpointNumber);
|
|
973
|
+
// Avoid loading the same block hash multiple times when tips land on the same block
|
|
974
|
+
const blockHashCache = new Map();
|
|
975
|
+
blockHashCache.set(genesisBlockNumber, genesisBlockHash.toString());
|
|
976
|
+
if (latestBlockEntry) {
|
|
977
|
+
blockHashCache.set(latestBlockEntry[0], BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString());
|
|
978
|
+
}
|
|
979
|
+
const loadBlockHash = async (n)=>{
|
|
980
|
+
if (!blockHashCache.has(n)) {
|
|
981
|
+
const blockStorage = await this.#blocks.getAsync(n);
|
|
982
|
+
if (!blockStorage) {
|
|
983
|
+
throw new BlockNotFoundError(n);
|
|
984
|
+
}
|
|
985
|
+
const blockHash = BlockHash.fromBuffer(blockStorage.blockHash).toString();
|
|
986
|
+
blockHashCache.set(n, blockHash);
|
|
987
|
+
}
|
|
988
|
+
return blockHashCache.get(n);
|
|
989
|
+
};
|
|
990
|
+
// Build proposed chain tip (this one has block only, no checkpoint)
|
|
991
|
+
const proposedBlockId = latestBlockEntry === undefined ? genesisBlockId : {
|
|
992
|
+
number: BlockNumber(latestBlockEntry[0]),
|
|
993
|
+
hash: BlockHash.fromBuffer(latestBlockEntry[1].blockHash).toString()
|
|
994
|
+
};
|
|
995
|
+
// Build other tips from checkpoint data, reading corresponding block data from the cache
|
|
996
|
+
const buildTipFromCheckpoint = async (stored)=>{
|
|
997
|
+
if (!stored) {
|
|
998
|
+
return genesisTip;
|
|
999
|
+
}
|
|
1000
|
+
const blockNumber = BlockNumber(stored.startBlock + stored.blockCount - 1);
|
|
1001
|
+
const blockHash = await loadBlockHash(blockNumber);
|
|
1002
|
+
const header = CheckpointHeader.fromBuffer(stored.header);
|
|
1003
|
+
return {
|
|
1004
|
+
block: {
|
|
1005
|
+
number: blockNumber,
|
|
1006
|
+
hash: blockHash
|
|
1007
|
+
},
|
|
1008
|
+
checkpoint: {
|
|
1009
|
+
number: CheckpointNumber(stored.checkpointNumber),
|
|
1010
|
+
hash: header.hash().toString()
|
|
1011
|
+
}
|
|
1012
|
+
};
|
|
1013
|
+
};
|
|
1014
|
+
const checkpointedTip = await buildTipFromCheckpoint(latestCheckpointEntry?.[1]);
|
|
1015
|
+
const provenTip = await buildTipFromCheckpoint(provenCheckpoint);
|
|
1016
|
+
const finalizedTip = await buildTipFromCheckpoint(finalizedCheckpoint);
|
|
1017
|
+
// Proposed checkpoint falls back to the checkpoint tip if it's not set. And if local storage is
|
|
1018
|
+
// inconsistent and the proposed checkpoint is behind the checkpointed tip, we patch that and
|
|
1019
|
+
// report the checkpointed tip as the proposed checkpoint to maintain the invariant.
|
|
1020
|
+
const proposedCheckpointTip = proposedCheckpointEntry === undefined || proposedCheckpointEntry[0] <= latestCheckpointNumber ? checkpointedTip : await buildTipFromCheckpoint(proposedCheckpointEntry[1]);
|
|
1021
|
+
// A checkpointed block past the latest stored block would mean a checkpoint
|
|
1022
|
+
// references blocks that aren't in blocks.
|
|
1023
|
+
if (proposedBlockId.number < checkpointedTip.block.number) {
|
|
1024
|
+
throw new Error(`Inconsistent block store: latest block ${proposedBlockId.number} is behind checkpointed block ${checkpointedTip.block.number}`);
|
|
1025
|
+
}
|
|
1026
|
+
// Assert that checkpoint numbers are increasing
|
|
1027
|
+
if (finalizedTip.checkpoint.number > provenTip.checkpoint.number || provenTip.checkpoint.number > checkpointedTip.checkpoint.number || checkpointedTip.checkpoint.number > proposedCheckpointTip.checkpoint.number) {
|
|
1028
|
+
throw new Error(`Inconsistent checkpoint numbers in chain tips: finalized=${finalizedTip.checkpoint.number} proven=${provenTip.checkpoint.number} checkpointed=${checkpointedTip.checkpoint.number} proposed=${proposedCheckpointTip.checkpoint.number}`);
|
|
1029
|
+
}
|
|
1030
|
+
// Assert block numbers are increasing
|
|
1031
|
+
if (finalizedTip.block.number > provenTip.block.number || provenTip.block.number > checkpointedTip.block.number || checkpointedTip.block.number > proposedCheckpointTip.block.number || proposedCheckpointTip.block.number > proposedBlockId.number) {
|
|
1032
|
+
throw new Error(`Inconsistent block numbers in chain tips: finalized=${finalizedTip.block.number} proven=${provenTip.block.number} checkpointed=${checkpointedTip.block.number} proposedCheckpoint=${proposedCheckpointTip.block.number} proposed=${proposedBlockId.number}`);
|
|
1033
|
+
}
|
|
1034
|
+
return {
|
|
1035
|
+
proposed: proposedBlockId,
|
|
1036
|
+
proposedCheckpoint: proposedCheckpointTip,
|
|
1037
|
+
checkpointed: checkpointedTip,
|
|
1038
|
+
proven: provenTip,
|
|
1039
|
+
finalized: finalizedTip
|
|
1040
|
+
};
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* Gets the most recent L1 block processed.
|
|
1045
|
+
* @returns The L1 block that published the latest L2 block
|
|
1046
|
+
*/ getSynchedL1BlockNumber() {
|
|
1047
|
+
return this.#lastSynchedL1Block.getAsync();
|
|
1048
|
+
}
|
|
1049
|
+
setSynchedL1BlockNumber(l1BlockNumber) {
|
|
1050
|
+
return this.#lastSynchedL1Block.set(l1BlockNumber);
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Adds a proposed checkpoint to the pending queue.
|
|
1054
|
+
* Accepts proposed.checkpointNumber === latestTip + 1, where latestTip is the highest of
|
|
1055
|
+
* confirmed and the highest pending checkpoint number.
|
|
1056
|
+
* Computes archive and checkpointOutHash from the stored blocks.
|
|
1057
|
+
*/ async addProposedCheckpoint(proposed) {
|
|
1058
|
+
return await this.db.transactionAsync(async ()=>{
|
|
1059
|
+
const confirmed = await this.getLatestCheckpointNumber();
|
|
1060
|
+
const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({
|
|
1061
|
+
reverse: true,
|
|
1062
|
+
limit: 1
|
|
1063
|
+
}));
|
|
1064
|
+
const latestTip = CheckpointNumber(latestPendingKey !== undefined ? Math.max(latestPendingKey, confirmed) : confirmed);
|
|
1065
|
+
if (proposed.checkpointNumber !== latestTip + 1) {
|
|
1066
|
+
throw new ProposedCheckpointNotSequentialError(proposed.checkpointNumber, latestTip);
|
|
1067
|
+
}
|
|
1068
|
+
// Ensure the predecessor block (from pending or confirmed chain) exists
|
|
1069
|
+
const previousBlock = await this.getPreviousCheckpointBlock(proposed.checkpointNumber);
|
|
1070
|
+
const blocks = [];
|
|
1071
|
+
for(let i = 0; i < proposed.blockCount; i++){
|
|
1072
|
+
const block = await this.getBlock({
|
|
1073
|
+
number: BlockNumber(proposed.startBlock + i)
|
|
1074
|
+
});
|
|
1075
|
+
if (!block) {
|
|
1076
|
+
throw new BlockNotFoundError(proposed.startBlock + i);
|
|
1077
|
+
}
|
|
1078
|
+
blocks.push(block);
|
|
1079
|
+
}
|
|
1080
|
+
this.validateCheckpointBlocks(blocks, previousBlock);
|
|
1081
|
+
const archive = blocks[blocks.length - 1].archive;
|
|
1082
|
+
const checkpointOutHash = Checkpoint.getCheckpointOutHash(blocks);
|
|
1083
|
+
await this.#proposedCheckpoints.set(proposed.checkpointNumber, {
|
|
1084
|
+
header: proposed.header.toBuffer(),
|
|
1085
|
+
archive: archive.toBuffer(),
|
|
1086
|
+
checkpointOutHash: checkpointOutHash.toBuffer(),
|
|
1087
|
+
checkpointNumber: proposed.checkpointNumber,
|
|
1088
|
+
startBlock: proposed.startBlock,
|
|
1089
|
+
blockCount: proposed.blockCount,
|
|
1090
|
+
totalManaUsed: proposed.totalManaUsed.toString(),
|
|
1091
|
+
feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString()
|
|
1092
|
+
});
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
async getProvenCheckpointNumber() {
|
|
1096
|
+
return await this.db.transactionAsync(async ()=>{
|
|
1097
|
+
const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
|
|
1098
|
+
this.getLatestCheckpointNumber(),
|
|
1099
|
+
this.#lastProvenCheckpoint.getAsync()
|
|
1100
|
+
]);
|
|
1101
|
+
return (provenCheckpointNumber ?? 0) > latestCheckpointNumber ? latestCheckpointNumber : CheckpointNumber(provenCheckpointNumber ?? 0);
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
async setProvenCheckpointNumber(checkpointNumber) {
|
|
1105
|
+
const result = await this.#lastProvenCheckpoint.set(checkpointNumber);
|
|
1106
|
+
return result;
|
|
1107
|
+
}
|
|
1108
|
+
async getFinalizedCheckpointNumber() {
|
|
1109
|
+
return await this.db.transactionAsync(async ()=>{
|
|
1110
|
+
const [provenCheckpointNumber, finalizedCheckpointNumber] = await Promise.all([
|
|
1111
|
+
this.getProvenCheckpointNumber(),
|
|
1112
|
+
this.#lastFinalizedCheckpoint.getAsync()
|
|
1113
|
+
]);
|
|
1114
|
+
return (finalizedCheckpointNumber ?? 0) > provenCheckpointNumber ? provenCheckpointNumber : CheckpointNumber(finalizedCheckpointNumber ?? 0);
|
|
1115
|
+
});
|
|
1116
|
+
}
|
|
1117
|
+
setFinalizedCheckpointNumber(checkpointNumber) {
|
|
1118
|
+
return this.#lastFinalizedCheckpoint.set(checkpointNumber);
|
|
1119
|
+
}
|
|
1120
|
+
#computeBlockRange(start, limit) {
|
|
1121
|
+
if (limit < 1) {
|
|
1122
|
+
throw new Error(`Invalid limit: ${limit}`);
|
|
1123
|
+
}
|
|
1124
|
+
if (start < INITIAL_L2_BLOCK_NUM) {
|
|
1125
|
+
throw new Error(`Invalid start: ${start}`);
|
|
1126
|
+
}
|
|
1127
|
+
return {
|
|
1128
|
+
start,
|
|
1129
|
+
limit
|
|
1130
|
+
};
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* Gets the pending chain validation status.
|
|
1134
|
+
* @returns The validation status or undefined if not set.
|
|
1135
|
+
*/ async getPendingChainValidationStatus() {
|
|
1136
|
+
const buffer = await this.#pendingChainValidationStatus.getAsync();
|
|
1137
|
+
if (!buffer) {
|
|
1138
|
+
return undefined;
|
|
1139
|
+
}
|
|
1140
|
+
return deserializeValidateCheckpointResult(buffer);
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Sets the pending chain validation status.
|
|
1144
|
+
* @param status - The validation status to store.
|
|
1145
|
+
*/ async setPendingChainValidationStatus(status) {
|
|
1146
|
+
if (status) {
|
|
1147
|
+
const buffer = serializeValidateCheckpointResult(status);
|
|
1148
|
+
await this.#pendingChainValidationStatus.set(buffer);
|
|
1149
|
+
} else {
|
|
1150
|
+
await this.#pendingChainValidationStatus.delete();
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
/** Records a rejected-checkpoint entry, keyed by its own archive root. */ async addRejectedCheckpoint(entry) {
|
|
1154
|
+
const archiveRootHex = entry.archiveRoot.toString();
|
|
1155
|
+
await this.#rejectedCheckpoints.set(archiveRootHex, {
|
|
1156
|
+
checkpointNumber: entry.checkpointNumber,
|
|
1157
|
+
archiveRoot: entry.archiveRoot.toBuffer(),
|
|
1158
|
+
parentArchiveRoot: entry.parentArchiveRoot.toBuffer(),
|
|
1159
|
+
slotNumber: entry.slotNumber,
|
|
1160
|
+
l1: entry.l1.toBuffer(),
|
|
1161
|
+
reason: entry.reason
|
|
1162
|
+
});
|
|
1163
|
+
await this.#rejectedCheckpointsByNumber.set(entry.checkpointNumber, archiveRootHex);
|
|
1164
|
+
await this.advanceSynchedL1BlockNumber(entry.l1.blockNumber);
|
|
1165
|
+
}
|
|
1166
|
+
/** Returns the rejected-checkpoint entry with the given archive root, or undefined if not present. */ async getRejectedCheckpointByArchiveRoot(archiveRoot) {
|
|
1167
|
+
const stored = await this.#rejectedCheckpoints.getAsync(archiveRoot.toString());
|
|
1168
|
+
return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
|
|
1169
|
+
}
|
|
1170
|
+
/** Returns the rejected-checkpoint entry recorded for the given checkpoint number, or undefined if none. */ async getRejectedCheckpointByNumber(checkpointNumber) {
|
|
1171
|
+
const archiveRootHex = await this.#rejectedCheckpointsByNumber.getAsync(checkpointNumber);
|
|
1172
|
+
if (archiveRootHex === undefined) {
|
|
1173
|
+
return undefined;
|
|
1174
|
+
}
|
|
1175
|
+
const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
|
|
1176
|
+
return stored ? this.rejectedCheckpointFromStorage(stored) : undefined;
|
|
1177
|
+
}
|
|
1178
|
+
/** Returns the highest checkpoint number recorded across all rejected entries, or `INITIAL_CHECKPOINT_NUMBER - 1` if none. */ async getLatestRejectedCheckpointNumber() {
|
|
1179
|
+
const [latest] = await toArray(this.#rejectedCheckpointsByNumber.keysAsync({
|
|
1180
|
+
reverse: true,
|
|
1181
|
+
limit: 1
|
|
1182
|
+
}));
|
|
1183
|
+
return CheckpointNumber(latest ?? INITIAL_CHECKPOINT_NUMBER - 1);
|
|
1184
|
+
}
|
|
1185
|
+
/** Removes a rejected-checkpoint entry by its archive root (used when an entry no longer matches L1). */ async removeRejectedCheckpointByArchiveRoot(archiveRoot) {
|
|
1186
|
+
const archiveRootHex = archiveRoot.toString();
|
|
1187
|
+
const stored = await this.#rejectedCheckpoints.getAsync(archiveRootHex);
|
|
1188
|
+
await this.#rejectedCheckpoints.delete(archiveRootHex);
|
|
1189
|
+
if (stored) {
|
|
1190
|
+
// Only clear the by-number index if it still points at this archive root, so a distinct
|
|
1191
|
+
// entry that shares the checkpoint number (e.g. an L1 reorg replacement) is not dropped.
|
|
1192
|
+
const indexed = await this.#rejectedCheckpointsByNumber.getAsync(stored.checkpointNumber);
|
|
1193
|
+
if (indexed === archiveRootHex) {
|
|
1194
|
+
await this.#rejectedCheckpointsByNumber.delete(stored.checkpointNumber);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* Advances the stored last-synched L1 block number to `l1BlockNumber` only if it is strictly
|
|
1200
|
+
* greater than the current value. Use this whenever ingesting checkpoint-shaped data so the
|
|
1201
|
+
* sync pointer never walks backwards on out-of-order writes (e.g. an invalid checkpoint
|
|
1202
|
+
* advance followed by a valid-checkpoint commit landing at an earlier L1 block).
|
|
1203
|
+
*/ async advanceSynchedL1BlockNumber(l1BlockNumber) {
|
|
1204
|
+
const current = await this.#lastSynchedL1Block.getAsync();
|
|
1205
|
+
if (current === undefined || l1BlockNumber > current) {
|
|
1206
|
+
await this.#lastSynchedL1Block.set(l1BlockNumber);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
rejectedCheckpointFromStorage(stored) {
|
|
1210
|
+
return {
|
|
1211
|
+
checkpointNumber: CheckpointNumber(stored.checkpointNumber),
|
|
1212
|
+
archiveRoot: Fr.fromBuffer(stored.archiveRoot),
|
|
1213
|
+
parentArchiveRoot: Fr.fromBuffer(stored.parentArchiveRoot),
|
|
1214
|
+
slotNumber: SlotNumber(stored.slotNumber),
|
|
1215
|
+
l1: L1PublishedData.fromBuffer(stored.l1),
|
|
1216
|
+
reason: stored.reason
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
}
|