@aztec/archiver 0.0.1-commit.d3ec352c → 0.0.1-commit.d58ff9d0

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