@aztec/archiver 0.0.1-commit.5daedc8 → 0.0.1-commit.6201a7b05

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 (218) hide show
  1. package/README.md +162 -22
  2. package/dest/archiver.d.ts +147 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +788 -0
  5. package/dest/config.d.ts +32 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +83 -0
  8. package/dest/errors.d.ts +92 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +136 -0
  11. package/dest/factory.d.ts +8 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +100 -15
  14. package/dest/index.d.ts +12 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +10 -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 +136 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +408 -0
  26. package/dest/l1/data_retrieval.d.ts +97 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +86 -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 +97 -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/data_source_base.d.ts +95 -0
  48. package/dest/modules/data_source_base.d.ts.map +1 -0
  49. package/dest/modules/data_source_base.js +234 -0
  50. package/dest/modules/data_store_updater.d.ts +93 -0
  51. package/dest/modules/data_store_updater.d.ts.map +1 -0
  52. package/dest/modules/data_store_updater.js +345 -0
  53. package/dest/modules/instrumentation.d.ts +55 -0
  54. package/dest/modules/instrumentation.d.ts.map +1 -0
  55. package/dest/modules/instrumentation.js +143 -0
  56. package/dest/modules/l1_synchronizer.d.ts +77 -0
  57. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  58. package/dest/modules/l1_synchronizer.js +1265 -0
  59. package/dest/modules/validation.d.ts +18 -0
  60. package/dest/modules/validation.d.ts.map +1 -0
  61. package/dest/{archiver → modules}/validation.js +13 -7
  62. package/dest/store/block_store.d.ts +262 -0
  63. package/dest/store/block_store.d.ts.map +1 -0
  64. package/dest/store/block_store.js +1048 -0
  65. package/dest/store/contract_class_store.d.ts +17 -0
  66. package/dest/store/contract_class_store.d.ts.map +1 -0
  67. package/dest/store/contract_class_store.js +64 -0
  68. package/dest/store/contract_instance_store.d.ts +24 -0
  69. package/dest/store/contract_instance_store.d.ts.map +1 -0
  70. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +7 -3
  71. package/dest/store/kv_archiver_store.d.ts +401 -0
  72. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  73. package/dest/store/kv_archiver_store.js +525 -0
  74. package/dest/store/l2_tips_cache.d.ts +20 -0
  75. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  76. package/dest/store/l2_tips_cache.js +109 -0
  77. package/dest/store/log_store.d.ts +57 -0
  78. package/dest/store/log_store.d.ts.map +1 -0
  79. package/dest/store/log_store.js +531 -0
  80. package/dest/store/message_store.d.ts +44 -0
  81. package/dest/store/message_store.d.ts.map +1 -0
  82. package/dest/{archiver/kv_archiver_store → store}/message_store.js +36 -23
  83. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  84. package/dest/structs/data_retrieval.d.ts.map +1 -0
  85. package/dest/structs/inbox_message.d.ts +15 -0
  86. package/dest/structs/inbox_message.d.ts.map +1 -0
  87. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  88. package/dest/structs/published.d.ts +2 -0
  89. package/dest/structs/published.d.ts.map +1 -0
  90. package/dest/test/fake_l1_state.d.ts +214 -0
  91. package/dest/test/fake_l1_state.d.ts.map +1 -0
  92. package/dest/test/fake_l1_state.js +517 -0
  93. package/dest/test/index.d.ts +2 -1
  94. package/dest/test/index.d.ts.map +1 -1
  95. package/dest/test/index.js +4 -1
  96. package/dest/test/mock_archiver.d.ts +16 -8
  97. package/dest/test/mock_archiver.d.ts.map +1 -1
  98. package/dest/test/mock_archiver.js +19 -14
  99. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  100. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  101. package/dest/test/mock_l1_to_l2_message_source.js +23 -12
  102. package/dest/test/mock_l2_block_source.d.ts +68 -20
  103. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  104. package/dest/test/mock_l2_block_source.js +298 -85
  105. package/dest/test/mock_structs.d.ts +83 -4
  106. package/dest/test/mock_structs.d.ts.map +1 -1
  107. package/dest/test/mock_structs.js +157 -11
  108. package/dest/test/noop_l1_archiver.d.ts +26 -0
  109. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  110. package/dest/test/noop_l1_archiver.js +74 -0
  111. package/package.json +20 -20
  112. package/src/archiver.ts +566 -0
  113. package/src/{archiver/config.ts → config.ts} +51 -14
  114. package/src/errors.ts +213 -0
  115. package/src/factory.ts +155 -17
  116. package/src/index.ts +12 -3
  117. package/src/interfaces.ts +9 -0
  118. package/src/l1/README.md +55 -0
  119. package/src/l1/bin/retrieve-calldata.ts +194 -0
  120. package/src/l1/calldata_retriever.ts +523 -0
  121. package/src/{archiver → l1}/data_retrieval.ts +155 -247
  122. package/src/l1/debug_tx.ts +99 -0
  123. package/src/l1/spire_proposer.ts +152 -0
  124. package/src/l1/trace_tx.ts +128 -0
  125. package/src/l1/types.ts +13 -0
  126. package/src/l1/validate_historical_logs.ts +140 -0
  127. package/src/l1/validate_trace.ts +229 -0
  128. package/src/modules/data_source_base.ts +364 -0
  129. package/src/modules/data_store_updater.ts +465 -0
  130. package/src/modules/instrumentation.ts +204 -0
  131. package/src/modules/l1_synchronizer.ts +1126 -0
  132. package/src/{archiver → modules}/validation.ts +21 -15
  133. package/src/store/block_store.ts +1361 -0
  134. package/src/store/contract_class_store.ts +82 -0
  135. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +10 -7
  136. package/src/store/kv_archiver_store.ts +765 -0
  137. package/src/store/l2_tips_cache.ts +134 -0
  138. package/src/store/log_store.ts +733 -0
  139. package/src/{archiver/kv_archiver_store → store}/message_store.ts +48 -28
  140. package/src/{archiver/structs → structs}/inbox_message.ts +7 -7
  141. package/src/{archiver/structs → structs}/published.ts +0 -1
  142. package/src/test/fake_l1_state.ts +770 -0
  143. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  144. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  145. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  146. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  147. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  148. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  149. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  150. package/src/test/index.ts +4 -0
  151. package/src/test/mock_archiver.ts +23 -16
  152. package/src/test/mock_l1_to_l2_message_source.ts +19 -11
  153. package/src/test/mock_l2_block_source.ts +367 -93
  154. package/src/test/mock_structs.ts +289 -13
  155. package/src/test/noop_l1_archiver.ts +117 -0
  156. package/dest/archiver/archiver.d.ts +0 -287
  157. package/dest/archiver/archiver.d.ts.map +0 -1
  158. package/dest/archiver/archiver.js +0 -1408
  159. package/dest/archiver/archiver_store.d.ts +0 -255
  160. package/dest/archiver/archiver_store.d.ts.map +0 -1
  161. package/dest/archiver/archiver_store.js +0 -4
  162. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  163. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  164. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  165. package/dest/archiver/config.d.ts +0 -21
  166. package/dest/archiver/config.d.ts.map +0 -1
  167. package/dest/archiver/config.js +0 -55
  168. package/dest/archiver/data_retrieval.d.ts +0 -79
  169. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  170. package/dest/archiver/errors.d.ts +0 -12
  171. package/dest/archiver/errors.d.ts.map +0 -1
  172. package/dest/archiver/errors.js +0 -17
  173. package/dest/archiver/index.d.ts +0 -7
  174. package/dest/archiver/index.d.ts.map +0 -1
  175. package/dest/archiver/index.js +0 -4
  176. package/dest/archiver/instrumentation.d.ts +0 -35
  177. package/dest/archiver/instrumentation.d.ts.map +0 -1
  178. package/dest/archiver/instrumentation.js +0 -140
  179. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  180. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  181. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  182. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  183. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  184. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  185. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  186. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  187. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  188. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  189. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  190. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  191. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  192. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  193. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  194. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  195. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  196. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  197. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  198. package/dest/archiver/structs/published.d.ts +0 -3
  199. package/dest/archiver/structs/published.d.ts.map +0 -1
  200. package/dest/archiver/validation.d.ts +0 -17
  201. package/dest/archiver/validation.d.ts.map +0 -1
  202. package/dest/rpc/index.d.ts +0 -9
  203. package/dest/rpc/index.d.ts.map +0 -1
  204. package/dest/rpc/index.js +0 -15
  205. package/src/archiver/archiver.ts +0 -1858
  206. package/src/archiver/archiver_store.ts +0 -305
  207. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  208. package/src/archiver/errors.ts +0 -26
  209. package/src/archiver/index.ts +0 -6
  210. package/src/archiver/instrumentation.ts +0 -187
  211. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  212. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  213. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  214. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  215. package/src/rpc/index.ts +0 -16
  216. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  217. /package/dest/{archiver/structs → structs}/published.js +0 -0
  218. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,1361 @@
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 type { AztecAsyncKVStore, AztecAsyncMap, AztecAsyncSingleton, Range } from '@aztec/kv-store';
10
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
11
+ import {
12
+ type BlockData,
13
+ type BlockDataWithCheckpointContext,
14
+ BlockHash,
15
+ Body,
16
+ CheckpointedL2Block,
17
+ CommitteeAttestation,
18
+ L2Block,
19
+ type ValidateCheckpointResult,
20
+ deserializeValidateCheckpointResult,
21
+ serializeValidateCheckpointResult,
22
+ } from '@aztec/stdlib/block';
23
+ import {
24
+ Checkpoint,
25
+ type CheckpointData,
26
+ type CommonCheckpointData,
27
+ L1PublishedData,
28
+ type ProposedCheckpointData,
29
+ type ProposedCheckpointInput,
30
+ PublishedCheckpoint,
31
+ } from '@aztec/stdlib/checkpoint';
32
+ import { type L1RollupConstants, getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
33
+ import { CheckpointHeader } from '@aztec/stdlib/rollup';
34
+ import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
35
+ import {
36
+ BlockHeader,
37
+ type IndexedTxEffect,
38
+ TxEffect,
39
+ TxHash,
40
+ TxReceipt,
41
+ TxStatus,
42
+ deserializeIndexedTxEffect,
43
+ serializeIndexedTxEffect,
44
+ } from '@aztec/stdlib/tx';
45
+
46
+ import {
47
+ BlockAlreadyCheckpointedError,
48
+ BlockArchiveNotConsistentError,
49
+ BlockCheckpointNumberNotSequentialError,
50
+ BlockIndexNotSequentialError,
51
+ BlockNotFoundError,
52
+ BlockNumberNotSequentialError,
53
+ CannotOverwriteCheckpointedBlockError,
54
+ CheckpointNotFoundError,
55
+ CheckpointNumberNotSequentialError,
56
+ InitialCheckpointNumberNotSequentialError,
57
+ NoProposedCheckpointToPromoteError,
58
+ ProposedCheckpointArchiveRootMismatchError,
59
+ ProposedCheckpointNotSequentialError,
60
+ ProposedCheckpointPromotionNotSequentialError,
61
+ } from '../errors.js';
62
+
63
+ export { TxReceipt, type TxEffect, type TxHash } from '@aztec/stdlib/tx';
64
+
65
+ type BlockIndexValue = [blockNumber: number, index: number];
66
+
67
+ type BlockStorage = {
68
+ header: Buffer;
69
+ blockHash: Buffer;
70
+ archive: Buffer;
71
+ checkpointNumber: number;
72
+ indexWithinCheckpoint: number;
73
+ };
74
+
75
+ /** Checkpoint Storage shared between Checkpoints + Proposed Checkpoints */
76
+ type CommonCheckpointStorage = {
77
+ header: Buffer;
78
+ archive: Buffer;
79
+ checkpointOutHash: Buffer;
80
+ checkpointNumber: number;
81
+ startBlock: number;
82
+ blockCount: number;
83
+ };
84
+
85
+ type CheckpointStorage = CommonCheckpointStorage & {
86
+ l1: Buffer;
87
+ attestations: Buffer[];
88
+ feeAssetPriceModifier: string;
89
+ };
90
+
91
+ /** Storage format for a proposed checkpoint (attested but not yet L1-confirmed). */
92
+ type ProposedCheckpointStorage = CommonCheckpointStorage & {
93
+ totalManaUsed: string;
94
+ feeAssetPriceModifier: string;
95
+ };
96
+
97
+ export type RemoveCheckpointsResult = { blocksRemoved: L2Block[] | undefined };
98
+
99
+ /**
100
+ * LMDB-based block storage for the archiver.
101
+ */
102
+ export class BlockStore {
103
+ /** Map block number to block data */
104
+ #blocks: AztecAsyncMap<number, BlockStorage>;
105
+
106
+ /** Map keyed by checkpoint number holding proposed (locally-validated, not yet L1-confirmed) checkpoints. */
107
+ #proposedCheckpoints: AztecAsyncMap<number, ProposedCheckpointStorage>;
108
+
109
+ /** Map checkpoint number to checkpoint data for mined checkpoints only */
110
+ #checkpoints: AztecAsyncMap<number, CheckpointStorage>;
111
+
112
+ /** Map slot number to checkpoint number, for looking up checkpoints by slot range. */
113
+ #slotToCheckpoint: AztecAsyncMap<number, number>;
114
+
115
+ /** Map block hash to list of tx hashes */
116
+ #blockTxs: AztecAsyncMap<string, Buffer>;
117
+
118
+ /** Tx hash to serialized IndexedTxEffect */
119
+ #txEffects: AztecAsyncMap<string, Buffer>;
120
+
121
+ /** Stores L1 block number in which the last processed L2 block was included */
122
+ #lastSynchedL1Block: AztecAsyncSingleton<bigint>;
123
+
124
+ /** Stores last proven checkpoint */
125
+ #lastProvenCheckpoint: AztecAsyncSingleton<number>;
126
+
127
+ /** Stores last finalized checkpoint (proven at or before the finalized L1 block) */
128
+ #lastFinalizedCheckpoint: AztecAsyncSingleton<number>;
129
+
130
+ /** Stores the pending chain validation status */
131
+ #pendingChainValidationStatus: AztecAsyncSingleton<Buffer>;
132
+
133
+ /** Index mapping a contract's address (as a string) to its location in a block */
134
+ #contractIndex: AztecAsyncMap<string, BlockIndexValue>;
135
+
136
+ /** Index mapping block hash to block number */
137
+ #blockHashIndex: AztecAsyncMap<string, number>;
138
+
139
+ /** Index mapping block archive to block number */
140
+ #blockArchiveIndex: AztecAsyncMap<string, number>;
141
+
142
+ #log = createLogger('archiver:block_store');
143
+
144
+ constructor(private db: AztecAsyncKVStore) {
145
+ this.#blocks = db.openMap('archiver_blocks');
146
+ this.#blockTxs = db.openMap('archiver_block_txs');
147
+ this.#txEffects = db.openMap('archiver_tx_effects');
148
+ this.#contractIndex = db.openMap('archiver_contract_index');
149
+ this.#blockHashIndex = db.openMap('archiver_block_hash_index');
150
+ this.#blockArchiveIndex = db.openMap('archiver_block_archive_index');
151
+ this.#lastSynchedL1Block = db.openSingleton('archiver_last_synched_l1_block');
152
+ this.#lastProvenCheckpoint = db.openSingleton('archiver_last_proven_l2_checkpoint');
153
+ this.#lastFinalizedCheckpoint = db.openSingleton('archiver_last_finalized_l2_checkpoint');
154
+ this.#pendingChainValidationStatus = db.openSingleton('archiver_pending_chain_validation_status');
155
+ this.#checkpoints = db.openMap('archiver_checkpoints');
156
+ this.#slotToCheckpoint = db.openMap('archiver_slot_to_checkpoint');
157
+ this.#proposedCheckpoints = db.openMap('archiver_proposed_checkpoints');
158
+ }
159
+
160
+ /**
161
+ * Returns the finalized L2 block number. An L2 block is finalized when it was proven
162
+ * in an L1 block that has itself been finalized on Ethereum.
163
+ * @returns The finalized block number.
164
+ */
165
+ async getFinalizedL2BlockNumber(): Promise<BlockNumber> {
166
+ const finalizedCheckpointNumber = await this.getFinalizedCheckpointNumber();
167
+ if (finalizedCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
168
+ return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
169
+ }
170
+ const checkpointStorage = await this.#checkpoints.getAsync(finalizedCheckpointNumber);
171
+ if (!checkpointStorage) {
172
+ throw new CheckpointNotFoundError(finalizedCheckpointNumber);
173
+ }
174
+ return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
175
+ }
176
+
177
+ /**
178
+ * Append a new proposed block to the store.
179
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
180
+ * For checkpointed blocks (already published to L1), use addCheckpoints() instead.
181
+ * @param block - The proposed L2 block to be added to the store.
182
+ * @returns True if the operation is successful.
183
+ */
184
+ async addProposedBlock(block: L2Block, opts: { force?: boolean } = {}): Promise<boolean> {
185
+ return await this.db.transactionAsync(async () => {
186
+ const blockNumber = block.number;
187
+ const blockCheckpointNumber = block.checkpointNumber;
188
+ const blockIndex = block.indexWithinCheckpoint;
189
+ const blockLastArchive = block.header.lastArchive.root;
190
+
191
+ // Extract the latest block and checkpoint numbers
192
+ const previousBlockNumber = await this.getLatestL2BlockNumber();
193
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
194
+
195
+ // Verify we're not overwriting checkpointed blocks
196
+ const lastCheckpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
197
+ if (!opts.force && blockNumber <= lastCheckpointedBlockNumber) {
198
+ // Check if the proposed block matches the already-checkpointed one
199
+ const existingBlock = await this.getBlock(BlockNumber(blockNumber));
200
+ if (existingBlock && existingBlock.archive.root.equals(block.archive.root)) {
201
+ throw new BlockAlreadyCheckpointedError(blockNumber);
202
+ }
203
+ throw new CannotOverwriteCheckpointedBlockError(blockNumber, lastCheckpointedBlockNumber);
204
+ }
205
+
206
+ // Check that the block number is the expected one
207
+ if (!opts.force && previousBlockNumber !== blockNumber - 1) {
208
+ throw new BlockNumberNotSequentialError(blockNumber, previousBlockNumber);
209
+ }
210
+
211
+ // Accept the block if either the confirmed checkpoint or a pending checkpoint matches
212
+ // the expected predecessor. We look for a pending entry at exactly blockCheckpointNumber - 1.
213
+ const expectedCheckpointNumber = blockCheckpointNumber - 1;
214
+ const hasPendingAtExpected = await this.#proposedCheckpoints.hasAsync(expectedCheckpointNumber);
215
+ if (!opts.force && latestCheckpointNumber !== expectedCheckpointNumber && !hasPendingAtExpected) {
216
+ const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
217
+ const previous = CheckpointNumber(Math.max(latestCheckpointNumber, latestPendingKey ?? 0));
218
+ throw new BlockCheckpointNumberNotSequentialError(blockNumber, blockCheckpointNumber, previous);
219
+ }
220
+
221
+ // Extract the previous block if there is one and see if it is for the same checkpoint or not
222
+ const previousBlockResult = await this.getBlock(previousBlockNumber);
223
+
224
+ let expectedBlockIndex = 0;
225
+ let previousBlockIndex: number | undefined = undefined;
226
+ if (previousBlockResult !== undefined) {
227
+ if (previousBlockResult.checkpointNumber === blockCheckpointNumber) {
228
+ // The previous block is for the same checkpoint, therefore our index should follow it
229
+ previousBlockIndex = previousBlockResult.indexWithinCheckpoint;
230
+ expectedBlockIndex = previousBlockIndex + 1;
231
+ }
232
+ if (!previousBlockResult.archive.root.equals(blockLastArchive)) {
233
+ throw new BlockArchiveNotConsistentError(
234
+ blockNumber,
235
+ previousBlockResult.number,
236
+ blockLastArchive,
237
+ previousBlockResult.archive.root,
238
+ );
239
+ }
240
+ }
241
+
242
+ // Now check that the block has the expected index value
243
+ if (!opts.force && expectedBlockIndex !== blockIndex) {
244
+ throw new BlockIndexNotSequentialError(blockIndex, previousBlockIndex);
245
+ }
246
+
247
+ await this.addBlockToDatabase(block, block.checkpointNumber, block.indexWithinCheckpoint);
248
+
249
+ return true;
250
+ });
251
+ }
252
+
253
+ /**
254
+ * Append new checkpoints to the store's list.
255
+ * @param checkpoints - The L2 checkpoints to be added to the store.
256
+ * @returns True if the operation is successful.
257
+ */
258
+ async addCheckpoints(checkpoints: PublishedCheckpoint[], opts: { force?: boolean } = {}): Promise<boolean> {
259
+ if (checkpoints.length === 0) {
260
+ return true;
261
+ }
262
+
263
+ return await this.db.transactionAsync(async () => {
264
+ const firstCheckpointNumber = checkpoints[0].checkpoint.number;
265
+ const previousCheckpointNumber = await this.getLatestCheckpointNumber();
266
+
267
+ // Handle already-stored checkpoints at the start of the batch.
268
+ // This can happen after an L1 reorg re-includes a checkpoint in a different L1 block.
269
+ // We accept them if archives match (same content) and update their L1 metadata.
270
+ if (!opts.force && firstCheckpointNumber <= previousCheckpointNumber) {
271
+ checkpoints = await this.skipOrUpdateAlreadyStoredCheckpoints(checkpoints, previousCheckpointNumber);
272
+ if (checkpoints.length === 0) {
273
+ return true;
274
+ }
275
+ // Re-check sequentiality after skipping
276
+ const newFirstNumber = checkpoints[0].checkpoint.number;
277
+ if (previousCheckpointNumber !== newFirstNumber - 1) {
278
+ throw new InitialCheckpointNumberNotSequentialError(newFirstNumber, previousCheckpointNumber);
279
+ }
280
+ } else if (previousCheckpointNumber !== firstCheckpointNumber - 1 && !opts.force) {
281
+ throw new InitialCheckpointNumberNotSequentialError(firstCheckpointNumber, previousCheckpointNumber);
282
+ }
283
+
284
+ // Get the last block of the previous checkpoint for archive chaining
285
+ let previousBlock = await this.getPreviousCheckpointBlock(checkpoints[0].checkpoint.number);
286
+
287
+ // Iterate over checkpoints array and insert them, checking that the block numbers are sequential.
288
+ let previousCheckpoint: PublishedCheckpoint | undefined = undefined;
289
+ for (const checkpoint of checkpoints) {
290
+ if (
291
+ !opts.force &&
292
+ previousCheckpoint &&
293
+ previousCheckpoint.checkpoint.number + 1 !== checkpoint.checkpoint.number
294
+ ) {
295
+ throw new CheckpointNumberNotSequentialError(
296
+ checkpoint.checkpoint.number,
297
+ previousCheckpoint.checkpoint.number,
298
+ );
299
+ }
300
+ previousCheckpoint = checkpoint;
301
+
302
+ // Validate block sequencing, indexes, and archive chaining
303
+ this.validateCheckpointBlocks(checkpoint.checkpoint.blocks, previousBlock);
304
+
305
+ // Store every block in the database (may already exist, but L1 data is authoritative)
306
+ for (let i = 0; i < checkpoint.checkpoint.blocks.length; i++) {
307
+ await this.addBlockToDatabase(checkpoint.checkpoint.blocks[i], checkpoint.checkpoint.number, i);
308
+ }
309
+ previousBlock = checkpoint.checkpoint.blocks.at(-1);
310
+
311
+ // Store the checkpoint in the database
312
+ await this.#checkpoints.set(checkpoint.checkpoint.number, {
313
+ header: checkpoint.checkpoint.header.toBuffer(),
314
+ archive: checkpoint.checkpoint.archive.toBuffer(),
315
+ checkpointOutHash: checkpoint.checkpoint.getCheckpointOutHash().toBuffer(),
316
+ l1: checkpoint.l1.toBuffer(),
317
+ attestations: checkpoint.attestations.map(attestation => attestation.toBuffer()),
318
+ checkpointNumber: checkpoint.checkpoint.number,
319
+ startBlock: checkpoint.checkpoint.blocks[0].number,
320
+ blockCount: checkpoint.checkpoint.blocks.length,
321
+ feeAssetPriceModifier: checkpoint.checkpoint.feeAssetPriceModifier.toString(),
322
+ });
323
+
324
+ // Update slot-to-checkpoint index
325
+ await this.#slotToCheckpoint.set(checkpoint.checkpoint.header.slotNumber, checkpoint.checkpoint.number);
326
+
327
+ // Remove proposed checkpoint if it exists, since L1 is authoritative
328
+ await this.#proposedCheckpoints.delete(checkpoint.checkpoint.number);
329
+ }
330
+
331
+ await this.#lastSynchedL1Block.set(checkpoints[checkpoints.length - 1].l1.blockNumber);
332
+ return true;
333
+ });
334
+ }
335
+
336
+ /**
337
+ * Handles checkpoints at the start of a batch that are already stored (e.g. due to L1 reorg).
338
+ * Verifies the archive root matches, updates L1 metadata, and returns only the new checkpoints.
339
+ */
340
+ private async skipOrUpdateAlreadyStoredCheckpoints(
341
+ checkpoints: PublishedCheckpoint[],
342
+ latestStored: CheckpointNumber,
343
+ ): Promise<PublishedCheckpoint[]> {
344
+ let i = 0;
345
+ for (; i < checkpoints.length && checkpoints[i].checkpoint.number <= latestStored; i++) {
346
+ const incoming = checkpoints[i];
347
+ const stored = await this.getCheckpointData(incoming.checkpoint.number);
348
+ if (!stored) {
349
+ // Should not happen if latestStored is correct, but be safe
350
+ break;
351
+ }
352
+ // Verify the checkpoint content matches (archive root)
353
+ if (!stored.archive.root.equals(incoming.checkpoint.archive.root)) {
354
+ throw new Error(
355
+ `Checkpoint ${incoming.checkpoint.number} already exists in store but with a different archive root. ` +
356
+ `Stored: ${stored.archive.root}, incoming: ${incoming.checkpoint.archive.root}`,
357
+ );
358
+ }
359
+ // Update L1 metadata and attestations for the already-stored checkpoint
360
+ this.#log.warn(
361
+ `Checkpoint ${incoming.checkpoint.number} already stored, updating L1 info ` +
362
+ `(L1 block ${stored.l1.blockNumber} -> ${incoming.l1.blockNumber})`,
363
+ );
364
+ await this.#checkpoints.set(incoming.checkpoint.number, {
365
+ header: incoming.checkpoint.header.toBuffer(),
366
+ archive: incoming.checkpoint.archive.toBuffer(),
367
+ checkpointOutHash: incoming.checkpoint.getCheckpointOutHash().toBuffer(),
368
+ l1: incoming.l1.toBuffer(),
369
+ attestations: incoming.attestations.map(a => a.toBuffer()),
370
+ checkpointNumber: incoming.checkpoint.number,
371
+ startBlock: incoming.checkpoint.blocks[0].number,
372
+ blockCount: incoming.checkpoint.blocks.length,
373
+ feeAssetPriceModifier: incoming.checkpoint.feeAssetPriceModifier.toString(),
374
+ });
375
+ // Update the sync point to reflect the new L1 block
376
+ await this.#lastSynchedL1Block.set(incoming.l1.blockNumber);
377
+ }
378
+ return checkpoints.slice(i);
379
+ }
380
+
381
+ /**
382
+ * Gets the last block of the checkpoint before the given one.
383
+ * Returns undefined if there is no previous checkpoint (i.e. genesis).
384
+ */
385
+ private async getPreviousCheckpointBlock(checkpointNumber: CheckpointNumber): Promise<L2Block | undefined> {
386
+ const previousCheckpointNumber = CheckpointNumber(checkpointNumber - 1);
387
+ if (previousCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
388
+ return undefined;
389
+ }
390
+
391
+ // Check across both proposed and mined checkpoints
392
+ const predecessor =
393
+ (await this.getProposedCheckpointByNumber(previousCheckpointNumber)) ??
394
+ (await this.getCheckpointData(previousCheckpointNumber));
395
+
396
+ if (!predecessor) {
397
+ throw new CheckpointNotFoundError(previousCheckpointNumber);
398
+ }
399
+
400
+ const previousBlockNumber = BlockNumber(predecessor.startBlock + predecessor.blockCount - 1);
401
+ const previousBlock = await this.getBlock(previousBlockNumber);
402
+ if (previousBlock === undefined) {
403
+ throw new BlockNotFoundError(previousBlockNumber);
404
+ }
405
+ return previousBlock;
406
+ }
407
+
408
+ /**
409
+ * Validates that blocks are sequential, have correct indexes, and chain via archive roots.
410
+ * This is the same validation used for both confirmed checkpoints (addCheckpoints) and
411
+ * proposed checkpoints (addProposedCheckpoint).
412
+ */
413
+ private validateCheckpointBlocks(blocks: L2Block[], previousBlock: L2Block | undefined): void {
414
+ for (const block of blocks) {
415
+ if (previousBlock) {
416
+ if (previousBlock.number !== block.number - 1) {
417
+ throw new BlockNumberNotSequentialError(block.number, previousBlock.number);
418
+ }
419
+ if (previousBlock.checkpointNumber === block.checkpointNumber) {
420
+ if (previousBlock.indexWithinCheckpoint !== block.indexWithinCheckpoint - 1) {
421
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
422
+ }
423
+ } else if (block.indexWithinCheckpoint !== 0) {
424
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, previousBlock.indexWithinCheckpoint);
425
+ }
426
+ if (!previousBlock.archive.root.equals(block.header.lastArchive.root)) {
427
+ throw new BlockArchiveNotConsistentError(
428
+ block.number,
429
+ previousBlock.number,
430
+ block.header.lastArchive.root,
431
+ previousBlock.archive.root,
432
+ );
433
+ }
434
+ } else {
435
+ if (block.indexWithinCheckpoint !== 0) {
436
+ throw new BlockIndexNotSequentialError(block.indexWithinCheckpoint, undefined);
437
+ }
438
+ if (block.number !== INITIAL_L2_BLOCK_NUM) {
439
+ throw new BlockNumberNotSequentialError(block.number, undefined);
440
+ }
441
+ }
442
+ previousBlock = block;
443
+ }
444
+ }
445
+
446
+ private async addBlockToDatabase(block: L2Block, checkpointNumber: number, indexWithinCheckpoint: number) {
447
+ const blockHash = await block.hash();
448
+
449
+ await this.#blocks.set(block.number, {
450
+ header: block.header.toBuffer(),
451
+ blockHash: blockHash.toBuffer(),
452
+ archive: block.archive.toBuffer(),
453
+ checkpointNumber,
454
+ indexWithinCheckpoint,
455
+ });
456
+
457
+ for (let i = 0; i < block.body.txEffects.length; i++) {
458
+ const txEffect: IndexedTxEffect = {
459
+ data: block.body.txEffects[i],
460
+ l2BlockNumber: block.number,
461
+ l2BlockHash: blockHash,
462
+ txIndexInBlock: i,
463
+ };
464
+ await this.#txEffects.set(txEffect.data.txHash.toString(), serializeIndexedTxEffect(txEffect));
465
+ }
466
+
467
+ await this.#blockTxs.set(blockHash.toString(), Buffer.concat(block.body.txEffects.map(tx => tx.txHash.toBuffer())));
468
+
469
+ // Update indices for block hash and archive
470
+ await this.#blockHashIndex.set(blockHash.toString(), block.number);
471
+ await this.#blockArchiveIndex.set(block.archive.root.toString(), block.number);
472
+ }
473
+
474
+ /** Deletes a block and all associated data (tx effects, indices). */
475
+ private async deleteBlock(block: L2Block): Promise<void> {
476
+ // Delete the block from the main blocks map
477
+ await this.#blocks.delete(block.number);
478
+
479
+ // Delete all tx effects for this block
480
+ await Promise.all(block.body.txEffects.map(tx => this.#txEffects.delete(tx.txHash.toString())));
481
+
482
+ // Delete block txs mapping
483
+ const blockHash = (await block.hash()).toString();
484
+ await this.#blockTxs.delete(blockHash);
485
+
486
+ // Clean up indices
487
+ await this.#blockHashIndex.delete(blockHash);
488
+ await this.#blockArchiveIndex.delete(block.archive.root.toString());
489
+ }
490
+
491
+ /**
492
+ * Removes all checkpoints with checkpoint number > checkpointNumber.
493
+ * Also removes ALL blocks (both checkpointed and uncheckpointed) after the last block of the given checkpoint.
494
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
495
+ */
496
+ async removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<RemoveCheckpointsResult> {
497
+ return await this.db.transactionAsync(async () => {
498
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
499
+
500
+ if (checkpointNumber >= latestCheckpointNumber) {
501
+ this.#log.warn(`No checkpoints to remove after ${checkpointNumber} (latest is ${latestCheckpointNumber})`);
502
+ return { blocksRemoved: undefined };
503
+ }
504
+
505
+ // If the proven checkpoint is beyond the target, update it
506
+ const proven = await this.getProvenCheckpointNumber();
507
+ if (proven > checkpointNumber) {
508
+ this.#log.warn(`Updating proven checkpoint ${proven} to last valid checkpoint ${checkpointNumber}`);
509
+ await this.setProvenCheckpointNumber(checkpointNumber);
510
+ }
511
+
512
+ // Find the last block number to keep (last block of the given checkpoint, or 0 if no checkpoint)
513
+ let lastBlockToKeep: BlockNumber;
514
+ if (checkpointNumber <= 0) {
515
+ lastBlockToKeep = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
516
+ } else {
517
+ const targetCheckpoint = await this.#checkpoints.getAsync(checkpointNumber);
518
+ if (!targetCheckpoint) {
519
+ throw new Error(`Target checkpoint ${checkpointNumber} not found in store`);
520
+ }
521
+ lastBlockToKeep = BlockNumber(targetCheckpoint.startBlock + targetCheckpoint.blockCount - 1);
522
+ }
523
+
524
+ // Remove all blocks after lastBlockToKeep (both checkpointed and uncheckpointed)
525
+ const blocksRemoved = await this.removeBlocksAfter(lastBlockToKeep);
526
+
527
+ // Remove all checkpoints after the target
528
+ for (let c = latestCheckpointNumber; c > checkpointNumber; c = CheckpointNumber(c - 1)) {
529
+ const checkpointStorage = await this.#checkpoints.getAsync(c);
530
+ if (checkpointStorage) {
531
+ const slotNumber = CheckpointHeader.fromBuffer(checkpointStorage.header).slotNumber;
532
+ await this.#slotToCheckpoint.delete(slotNumber);
533
+ }
534
+ await this.#checkpoints.delete(c);
535
+ this.#log.debug(`Removed checkpoint ${c}`);
536
+ }
537
+
538
+ // Evict all pending checkpoints > checkpointNumber (their base chain no longer exists)
539
+ await this.evictProposedCheckpointsFrom(CheckpointNumber(checkpointNumber + 1));
540
+
541
+ return { blocksRemoved };
542
+ });
543
+ }
544
+
545
+ async getCheckpointData(checkpointNumber: CheckpointNumber): Promise<CheckpointData | undefined> {
546
+ const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
547
+ if (!checkpointStorage) {
548
+ return undefined;
549
+ }
550
+ return this.checkpointDataFromCheckpointStorage(checkpointStorage);
551
+ }
552
+
553
+ async getRangeOfCheckpoints(from: CheckpointNumber, limit: number): Promise<CheckpointData[]> {
554
+ const checkpoints: CheckpointData[] = [];
555
+ for (let checkpointNumber = from; checkpointNumber < from + limit; checkpointNumber++) {
556
+ const checkpoint = await this.#checkpoints.getAsync(checkpointNumber);
557
+ if (!checkpoint) {
558
+ break;
559
+ }
560
+ checkpoints.push(this.checkpointDataFromCheckpointStorage(checkpoint));
561
+ }
562
+ return checkpoints;
563
+ }
564
+
565
+ /** Returns checkpoint data for all checkpoints whose slot falls within the given range (inclusive). */
566
+ async getCheckpointDataForSlotRange(startSlot: SlotNumber, endSlot: SlotNumber): Promise<CheckpointData[]> {
567
+ const result: CheckpointData[] = [];
568
+ for await (const [, checkpointNumber] of this.#slotToCheckpoint.entriesAsync({
569
+ start: startSlot,
570
+ end: endSlot + 1,
571
+ })) {
572
+ const checkpointStorage = await this.#checkpoints.getAsync(checkpointNumber);
573
+ if (checkpointStorage) {
574
+ result.push(this.checkpointDataFromCheckpointStorage(checkpointStorage));
575
+ }
576
+ }
577
+ return result;
578
+ }
579
+
580
+ private checkpointDataFromCheckpointStorage(checkpointStorage: CheckpointStorage): CheckpointData {
581
+ return {
582
+ header: CheckpointHeader.fromBuffer(checkpointStorage.header),
583
+ archive: AppendOnlyTreeSnapshot.fromBuffer(checkpointStorage.archive),
584
+ checkpointOutHash: Fr.fromBuffer(checkpointStorage.checkpointOutHash),
585
+ checkpointNumber: CheckpointNumber(checkpointStorage.checkpointNumber),
586
+ startBlock: BlockNumber(checkpointStorage.startBlock),
587
+ blockCount: checkpointStorage.blockCount,
588
+ feeAssetPriceModifier: BigInt(checkpointStorage.feeAssetPriceModifier),
589
+ l1: L1PublishedData.fromBuffer(checkpointStorage.l1),
590
+ attestations: checkpointStorage.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
591
+ };
592
+ }
593
+
594
+ async getBlocksForCheckpoint(checkpointNumber: CheckpointNumber): Promise<L2Block[] | undefined> {
595
+ const checkpoint = await this.#checkpoints.getAsync(checkpointNumber);
596
+ if (!checkpoint) {
597
+ return undefined;
598
+ }
599
+
600
+ const blocksForCheckpoint = await toArray(
601
+ this.#blocks.entriesAsync({
602
+ start: checkpoint.startBlock,
603
+ end: checkpoint.startBlock + checkpoint.blockCount,
604
+ }),
605
+ );
606
+
607
+ const converted = await Promise.all(blocksForCheckpoint.map(x => this.getBlockFromBlockStorage(x[0], x[1])));
608
+ return converted.filter(isDefined);
609
+ }
610
+
611
+ /**
612
+ * Gets all blocks that have the given slot number.
613
+ * Iterates backwards through blocks for efficiency since we usually query for the last slot.
614
+ * @param slotNumber - The slot number to search for.
615
+ * @returns All blocks with the given slot number, in ascending block number order.
616
+ */
617
+ async getBlocksForSlot(slotNumber: SlotNumber): Promise<L2Block[]> {
618
+ const blocks: L2Block[] = [];
619
+
620
+ // Iterate backwards through all blocks and filter by slot number
621
+ // This is more efficient since we usually query for the most recent slot
622
+ for await (const [blockNumber, blockStorage] of this.#blocks.entriesAsync({ reverse: true })) {
623
+ const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
624
+ const blockSlot = block?.header.globalVariables.slotNumber;
625
+ if (block && blockSlot === slotNumber) {
626
+ blocks.push(block);
627
+ } else if (blockSlot && blockSlot < slotNumber) {
628
+ break; // Blocks are stored in slot ascending order, so we can stop searching
629
+ }
630
+ }
631
+
632
+ // Reverse to return blocks in ascending order (block number order)
633
+ return blocks.reverse();
634
+ }
635
+
636
+ /**
637
+ * Removes all blocks with block number > blockNumber.
638
+ * Does not remove any associated checkpoints.
639
+ * @param blockNumber - The block number to remove after.
640
+ * @returns The removed blocks (for event emission).
641
+ */
642
+ async removeBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
643
+ return await this.db.transactionAsync(async () => {
644
+ const removedBlocks: L2Block[] = [];
645
+
646
+ // Get the latest block number to determine the range
647
+ const latestBlockNumber = await this.getLatestL2BlockNumber();
648
+
649
+ // Iterate from blockNumber + 1 to latestBlockNumber
650
+ for (let bn = blockNumber + 1; bn <= latestBlockNumber; bn++) {
651
+ const block = await this.getBlock(BlockNumber(bn));
652
+
653
+ if (block === undefined) {
654
+ this.#log.warn(`Cannot remove block ${bn} from the store since we don't have it`);
655
+ continue;
656
+ }
657
+
658
+ removedBlocks.push(block);
659
+ await this.deleteBlock(block);
660
+ this.#log.debug(`Removed block ${bn} ${(await block.hash()).toString()}`);
661
+ }
662
+
663
+ return removedBlocks;
664
+ });
665
+ }
666
+
667
+ async getProvenBlockNumber(): Promise<BlockNumber> {
668
+ const provenCheckpointNumber = await this.getProvenCheckpointNumber();
669
+ if (provenCheckpointNumber === INITIAL_CHECKPOINT_NUMBER - 1) {
670
+ return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
671
+ }
672
+ const checkpointStorage = await this.#checkpoints.getAsync(provenCheckpointNumber);
673
+ if (!checkpointStorage) {
674
+ throw new CheckpointNotFoundError(provenCheckpointNumber);
675
+ } else {
676
+ return BlockNumber(checkpointStorage.startBlock + checkpointStorage.blockCount - 1);
677
+ }
678
+ }
679
+
680
+ async getLatestCheckpointNumber(): Promise<CheckpointNumber> {
681
+ const [latestCheckpointNumber] = await toArray(this.#checkpoints.keysAsync({ reverse: true, limit: 1 }));
682
+ if (latestCheckpointNumber === undefined) {
683
+ return CheckpointNumber(INITIAL_CHECKPOINT_NUMBER - 1);
684
+ }
685
+ return CheckpointNumber(latestCheckpointNumber);
686
+ }
687
+
688
+ async hasProposedCheckpoint(): Promise<boolean> {
689
+ const [key] = await toArray(this.#proposedCheckpoints.keysAsync({ limit: 1 }));
690
+ return key !== undefined;
691
+ }
692
+
693
+ /** Deletes all pending proposed checkpoints from storage. */
694
+ async deleteProposedCheckpoints(): Promise<void> {
695
+ for await (const key of this.#proposedCheckpoints.keysAsync()) {
696
+ await this.#proposedCheckpoints.delete(key);
697
+ }
698
+ }
699
+
700
+ /**
701
+ * Promotes a specific pending checkpoint to a confirmed checkpoint entry.
702
+ * This persists the checkpoint to the store, removes only that pending entry, and updates the L1 sync point.
703
+ * Remaining pending entries (e.g. N+1, N+2) are left intact — they chain off the just-promoted one.
704
+ * @param checkpointNumber - The checkpoint number to promote.
705
+ * @param l1 - L1 published data for the checkpoint.
706
+ * @param attestations - Committee attestations.
707
+ * @param expectedArchiveRoot - Archive root guard against races.
708
+ */
709
+ async promoteProposedToCheckpointed(
710
+ checkpointNumber: CheckpointNumber,
711
+ l1: L1PublishedData,
712
+ attestations: CommitteeAttestation[],
713
+ expectedArchiveRoot: Fr,
714
+ ): Promise<void> {
715
+ return await this.db.transactionAsync(async () => {
716
+ const proposed = await this.getProposedCheckpointByNumber(checkpointNumber);
717
+ if (!proposed) {
718
+ throw new NoProposedCheckpointToPromoteError();
719
+ }
720
+ if (!proposed.archive.root.equals(expectedArchiveRoot)) {
721
+ throw new ProposedCheckpointArchiveRootMismatchError(expectedArchiveRoot, proposed.archive.root);
722
+ }
723
+
724
+ // Verify sequentiality: promoted checkpoint must follow the latest confirmed one
725
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
726
+ if (latestCheckpointNumber !== proposed.checkpointNumber - 1) {
727
+ throw new ProposedCheckpointPromotionNotSequentialError(proposed.checkpointNumber, latestCheckpointNumber);
728
+ }
729
+
730
+ // Write the checkpoint entry
731
+ await this.#checkpoints.set(proposed.checkpointNumber, {
732
+ header: proposed.header.toBuffer(),
733
+ archive: proposed.archive.toBuffer(),
734
+ checkpointOutHash: proposed.checkpointOutHash.toBuffer(),
735
+ l1: l1.toBuffer(),
736
+ attestations: attestations.map(attestation => attestation.toBuffer()),
737
+ checkpointNumber: proposed.checkpointNumber,
738
+ startBlock: proposed.startBlock,
739
+ blockCount: proposed.blockCount,
740
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
741
+ });
742
+
743
+ // Update the slot-to-checkpoint index
744
+ await this.#slotToCheckpoint.set(proposed.header.slotNumber, proposed.checkpointNumber);
745
+
746
+ // Remove only this pending entry — remaining entries N+1, N+2, ... stay valid
747
+ await this.#proposedCheckpoints.delete(proposed.checkpointNumber);
748
+
749
+ // Update the last synced L1 block
750
+ await this.#lastSynchedL1Block.set(l1.blockNumber);
751
+ });
752
+ }
753
+
754
+ /**
755
+ * Returns the latest pending checkpoint (highest-numbered entry), or undefined if none.
756
+ * No fallback to confirmed.
757
+ */
758
+ async getLastProposedCheckpoint(): Promise<ProposedCheckpointData | undefined> {
759
+ const [key] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
760
+ if (key === undefined) {
761
+ return undefined;
762
+ }
763
+ const stored = await this.#proposedCheckpoints.getAsync(key);
764
+ return stored ? this.convertToProposedCheckpointData(stored) : undefined;
765
+ }
766
+
767
+ /** Returns the pending checkpoint for a specific checkpoint number, or undefined if not found. */
768
+ async getProposedCheckpointByNumber(n: CheckpointNumber): Promise<ProposedCheckpointData | undefined> {
769
+ const stored = await this.#proposedCheckpoints.getAsync(n);
770
+ return stored ? this.convertToProposedCheckpointData(stored) : undefined;
771
+ }
772
+
773
+ /** Returns all pending checkpoints in ascending checkpoint-number order. */
774
+ async getProposedCheckpoints(): Promise<ProposedCheckpointData[]> {
775
+ const results: ProposedCheckpointData[] = [];
776
+ for await (const [, stored] of this.#proposedCheckpoints.entriesAsync()) {
777
+ results.push(this.convertToProposedCheckpointData(stored));
778
+ }
779
+ return results;
780
+ }
781
+
782
+ /**
783
+ * Evicts all pending checkpoints with checkpoint number >= fromNumber.
784
+ * Used for divergent-mined-checkpoint cleanup: when L1 mines checkpoint N with a different archive,
785
+ * all pending >= N must be evicted since they chain off the now-invalid pending N.
786
+ */
787
+ async evictProposedCheckpointsFrom(fromNumber: CheckpointNumber): Promise<void> {
788
+ const keysToDelete: number[] = [];
789
+ for await (const key of this.#proposedCheckpoints.keysAsync()) {
790
+ if (key >= fromNumber) {
791
+ keysToDelete.push(key);
792
+ }
793
+ }
794
+ for (const key of keysToDelete) {
795
+ await this.#proposedCheckpoints.delete(key);
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Gets the checkpoint at the proposed tip:
801
+ * - latest pending checkpoint if any exist
802
+ * - fallsback to latest confirmed checkpoint otherwise
803
+ */
804
+ async getLastCheckpoint(): Promise<CommonCheckpointData | undefined> {
805
+ const latest = await this.getLastProposedCheckpoint();
806
+ if (!latest) {
807
+ return this.getCheckpointData(await this.getLatestCheckpointNumber());
808
+ }
809
+ return latest;
810
+ }
811
+
812
+ private convertToProposedCheckpointData(stored: ProposedCheckpointStorage): ProposedCheckpointData {
813
+ return {
814
+ checkpointNumber: CheckpointNumber(stored.checkpointNumber),
815
+ header: CheckpointHeader.fromBuffer(stored.header),
816
+ archive: AppendOnlyTreeSnapshot.fromBuffer(stored.archive),
817
+ checkpointOutHash: Fr.fromBuffer(stored.checkpointOutHash),
818
+ startBlock: BlockNumber(stored.startBlock),
819
+ blockCount: stored.blockCount,
820
+ totalManaUsed: BigInt(stored.totalManaUsed),
821
+ feeAssetPriceModifier: BigInt(stored.feeAssetPriceModifier),
822
+ };
823
+ }
824
+
825
+ /**
826
+ * Attempts to get the proposedCheckpoint's number, if there is not one, then fallback to the latest confirmed checkpoint number.
827
+ * @returns CheckpointNumber
828
+ */
829
+ async getProposedCheckpointNumber(): Promise<CheckpointNumber> {
830
+ const proposed = await this.getLastCheckpoint();
831
+ if (!proposed) {
832
+ return await this.getLatestCheckpointNumber();
833
+ }
834
+ return CheckpointNumber(proposed.checkpointNumber);
835
+ }
836
+
837
+ /**
838
+ * Attempts to get the proposedCheckpoint's block number, if there is not one, then fallback to the checkpointed block number
839
+ * @returns BlockNumber
840
+ */
841
+ async getProposedCheckpointL2BlockNumber(): Promise<BlockNumber> {
842
+ const proposed = await this.getLastCheckpoint();
843
+ if (!proposed) {
844
+ return await this.getCheckpointedL2BlockNumber();
845
+ }
846
+ return BlockNumber(proposed.startBlock + proposed.blockCount - 1);
847
+ }
848
+
849
+ async getCheckpointedBlock(number: BlockNumber): Promise<CheckpointedL2Block | undefined> {
850
+ const blockStorage = await this.#blocks.getAsync(number);
851
+ if (!blockStorage) {
852
+ return undefined;
853
+ }
854
+ const checkpoint = await this.#checkpoints.getAsync(blockStorage.checkpointNumber);
855
+ if (!checkpoint) {
856
+ return undefined;
857
+ }
858
+ const block = await this.getBlockFromBlockStorage(number, blockStorage);
859
+ if (!block) {
860
+ return undefined;
861
+ }
862
+ return new CheckpointedL2Block(
863
+ CheckpointNumber(checkpoint.checkpointNumber),
864
+ block,
865
+ L1PublishedData.fromBuffer(checkpoint.l1),
866
+ checkpoint.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
867
+ );
868
+ }
869
+
870
+ /**
871
+ * Gets up to `limit` amount of Checkpointed L2 blocks starting from `from`.
872
+ * @param start - Number of the first block to return (inclusive).
873
+ * @param limit - The number of blocks to return.
874
+ * @returns The requested L2 blocks
875
+ */
876
+ async *getCheckpointedBlocks(start: BlockNumber, limit: number): AsyncIterableIterator<CheckpointedL2Block> {
877
+ const checkpointCache = new Map<CheckpointNumber, CheckpointStorage>();
878
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)) {
879
+ const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
880
+ if (block) {
881
+ const checkpoint =
882
+ checkpointCache.get(CheckpointNumber(blockStorage.checkpointNumber)) ??
883
+ (await this.#checkpoints.getAsync(blockStorage.checkpointNumber));
884
+ if (checkpoint) {
885
+ checkpointCache.set(CheckpointNumber(blockStorage.checkpointNumber), checkpoint);
886
+ const checkpointedBlock = new CheckpointedL2Block(
887
+ CheckpointNumber(checkpoint.checkpointNumber),
888
+ block,
889
+ L1PublishedData.fromBuffer(checkpoint.l1),
890
+ checkpoint.attestations.map(buf => CommitteeAttestation.fromBuffer(buf)),
891
+ );
892
+ yield checkpointedBlock;
893
+ }
894
+ }
895
+ }
896
+ }
897
+
898
+ async getCheckpointedBlockByHash(blockHash: BlockHash): Promise<CheckpointedL2Block | undefined> {
899
+ const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
900
+ if (blockNumber === undefined) {
901
+ return undefined;
902
+ }
903
+ return this.getCheckpointedBlock(BlockNumber(blockNumber));
904
+ }
905
+
906
+ async getCheckpointedBlockByArchive(archive: Fr): Promise<CheckpointedL2Block | undefined> {
907
+ const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
908
+ if (blockNumber === undefined) {
909
+ return undefined;
910
+ }
911
+ return this.getCheckpointedBlock(BlockNumber(blockNumber));
912
+ }
913
+
914
+ /**
915
+ * Gets up to `limit` amount of L2 blocks starting from `from`.
916
+ * @param start - Number of the first block to return (inclusive).
917
+ * @param limit - The number of blocks to return.
918
+ * @returns The requested L2 blocks
919
+ */
920
+ async *getBlocks(start: BlockNumber, limit: number): AsyncIterableIterator<L2Block> {
921
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)) {
922
+ const block = await this.getBlockFromBlockStorage(blockNumber, blockStorage);
923
+ if (block) {
924
+ yield block;
925
+ }
926
+ }
927
+ }
928
+
929
+ /**
930
+ * Gets block metadata (without tx data) by block number.
931
+ * @param blockNumber - The number of the block to return.
932
+ * @returns The requested block data.
933
+ */
934
+ async getBlockData(blockNumber: BlockNumber): Promise<BlockData | undefined> {
935
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
936
+ if (!blockStorage || !blockStorage.header) {
937
+ return undefined;
938
+ }
939
+ return this.getBlockDataFromBlockStorage(blockStorage);
940
+ }
941
+
942
+ /**
943
+ * Gets block metadata plus checkpoint-derived context (L1 publish info, attestations) without
944
+ * deserializing tx bodies. When the block's containing checkpoint has not yet been L1-confirmed,
945
+ * `checkpoint` and `l1` are `undefined` and `attestations` is empty.
946
+ */
947
+ async getBlockDataWithCheckpointContext(
948
+ blockNumber: BlockNumber,
949
+ ): Promise<BlockDataWithCheckpointContext | undefined> {
950
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
951
+ if (!blockStorage || !blockStorage.header) {
952
+ return undefined;
953
+ }
954
+ const data = this.getBlockDataFromBlockStorage(blockStorage);
955
+ const checkpointStorage = await this.#checkpoints.getAsync(blockStorage.checkpointNumber);
956
+ if (!checkpointStorage) {
957
+ return { data, checkpoint: undefined, l1: undefined, attestations: [] };
958
+ }
959
+ const checkpoint = this.checkpointDataFromCheckpointStorage(checkpointStorage);
960
+ return { data, checkpoint, l1: checkpoint.l1, attestations: checkpoint.attestations };
961
+ }
962
+
963
+ /** Returns the checkpoint number that contains the given slot (or undefined if not found). */
964
+ async getCheckpointNumberBySlot(slot: SlotNumber): Promise<CheckpointNumber | undefined> {
965
+ const checkpointNumber = await this.#slotToCheckpoint.getAsync(slot);
966
+ return checkpointNumber === undefined ? undefined : CheckpointNumber(checkpointNumber);
967
+ }
968
+
969
+ /**
970
+ * Gets block metadata (without tx data) by archive root.
971
+ * @param archive - The archive root of the block to return.
972
+ * @returns The requested block data.
973
+ */
974
+ async getBlockDataByArchive(archive: Fr): Promise<BlockData | undefined> {
975
+ const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
976
+ if (blockNumber === undefined) {
977
+ return undefined;
978
+ }
979
+ return this.getBlockData(BlockNumber(blockNumber));
980
+ }
981
+
982
+ /**
983
+ * Gets an L2 block.
984
+ * @param blockNumber - The number of the block to return.
985
+ * @returns The requested L2 block.
986
+ */
987
+ async getBlock(blockNumber: BlockNumber): Promise<L2Block | undefined> {
988
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
989
+ if (!blockStorage || !blockStorage.header) {
990
+ return Promise.resolve(undefined);
991
+ }
992
+ return this.getBlockFromBlockStorage(blockNumber, blockStorage);
993
+ }
994
+
995
+ /**
996
+ * Gets an L2 block by its hash.
997
+ * @param blockHash - The hash of the block to return.
998
+ * @returns The requested L2 block.
999
+ */
1000
+ async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
1001
+ const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
1002
+ if (blockNumber === undefined) {
1003
+ return undefined;
1004
+ }
1005
+ return this.getBlock(BlockNumber(blockNumber));
1006
+ }
1007
+
1008
+ /**
1009
+ * Gets an L2 block by its archive root.
1010
+ * @param archive - The archive root of the block to return.
1011
+ * @returns The requested L2 block.
1012
+ */
1013
+ async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
1014
+ const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
1015
+ if (blockNumber === undefined) {
1016
+ return undefined;
1017
+ }
1018
+ return this.getBlock(BlockNumber(blockNumber));
1019
+ }
1020
+
1021
+ /**
1022
+ * Gets a block header by its hash.
1023
+ * @param blockHash - The hash of the block to return.
1024
+ * @returns The requested block header.
1025
+ */
1026
+ async getBlockHeaderByHash(blockHash: BlockHash): Promise<BlockHeader | undefined> {
1027
+ const blockNumber = await this.#blockHashIndex.getAsync(blockHash.toString());
1028
+ if (blockNumber === undefined) {
1029
+ return undefined;
1030
+ }
1031
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
1032
+ if (!blockStorage || !blockStorage.header) {
1033
+ return undefined;
1034
+ }
1035
+ return BlockHeader.fromBuffer(blockStorage.header);
1036
+ }
1037
+
1038
+ /**
1039
+ * Gets a block header by its archive root.
1040
+ * @param archive - The archive root of the block to return.
1041
+ * @returns The requested block header.
1042
+ */
1043
+ async getBlockHeaderByArchive(archive: Fr): Promise<BlockHeader | undefined> {
1044
+ const blockNumber = await this.#blockArchiveIndex.getAsync(archive.toString());
1045
+ if (blockNumber === undefined) {
1046
+ return undefined;
1047
+ }
1048
+ const blockStorage = await this.#blocks.getAsync(blockNumber);
1049
+ if (!blockStorage || !blockStorage.header) {
1050
+ return undefined;
1051
+ }
1052
+ return BlockHeader.fromBuffer(blockStorage.header);
1053
+ }
1054
+
1055
+ /**
1056
+ * Gets the headers for a sequence of L2 blocks.
1057
+ * @param start - Number of the first block to return (inclusive).
1058
+ * @param limit - The number of blocks to return.
1059
+ * @returns The requested L2 block headers
1060
+ */
1061
+ async *getBlockHeaders(start: BlockNumber, limit: number): AsyncIterableIterator<BlockHeader> {
1062
+ for await (const [blockNumber, blockStorage] of this.getBlockStorages(start, limit)) {
1063
+ const header = BlockHeader.fromBuffer(blockStorage.header);
1064
+ if (header.getBlockNumber() !== blockNumber) {
1065
+ throw new Error(
1066
+ `Block number mismatch when retrieving block header from archive (expected ${blockNumber} but got ${header.getBlockNumber()})`,
1067
+ );
1068
+ }
1069
+ yield header;
1070
+ }
1071
+ }
1072
+
1073
+ private async *getBlockStorages(start: BlockNumber, limit: number) {
1074
+ let expectedBlockNumber = start;
1075
+ for await (const [blockNumber, blockStorage] of this.#blocks.entriesAsync(this.#computeBlockRange(start, limit))) {
1076
+ if (blockNumber !== expectedBlockNumber) {
1077
+ throw new Error(
1078
+ `Block number mismatch when iterating blocks from archive (expected ${expectedBlockNumber} but got ${blockNumber})`,
1079
+ );
1080
+ }
1081
+ expectedBlockNumber++;
1082
+ yield [blockNumber, blockStorage] as const;
1083
+ }
1084
+ }
1085
+
1086
+ private getBlockDataFromBlockStorage(blockStorage: BlockStorage): BlockData {
1087
+ return {
1088
+ header: BlockHeader.fromBuffer(blockStorage.header),
1089
+ archive: AppendOnlyTreeSnapshot.fromBuffer(blockStorage.archive),
1090
+ blockHash: BlockHash.fromBuffer(blockStorage.blockHash),
1091
+ checkpointNumber: CheckpointNumber(blockStorage.checkpointNumber),
1092
+ indexWithinCheckpoint: IndexWithinCheckpoint(blockStorage.indexWithinCheckpoint),
1093
+ };
1094
+ }
1095
+
1096
+ private async getBlockFromBlockStorage(
1097
+ blockNumber: number,
1098
+ blockStorage: BlockStorage,
1099
+ ): Promise<L2Block | undefined> {
1100
+ const { header, archive, blockHash, checkpointNumber, indexWithinCheckpoint } =
1101
+ this.getBlockDataFromBlockStorage(blockStorage);
1102
+ header.setHash(blockHash);
1103
+ const blockHashString = bufferToHex(blockStorage.blockHash);
1104
+ const blockTxsBuffer = await this.#blockTxs.getAsync(blockHashString);
1105
+ if (blockTxsBuffer === undefined) {
1106
+ this.#log.warn(`Could not find body for block ${header.globalVariables.blockNumber} ${blockHash}`);
1107
+ return undefined;
1108
+ }
1109
+
1110
+ const txEffects: TxEffect[] = [];
1111
+ const reader = BufferReader.asReader(blockTxsBuffer);
1112
+ while (!reader.isEmpty()) {
1113
+ const txHash = reader.readObject(TxHash);
1114
+ const txEffect = await this.#txEffects.getAsync(txHash.toString());
1115
+ if (txEffect === undefined) {
1116
+ this.#log.warn(`Could not find tx effect for tx ${txHash} in block ${blockNumber}`);
1117
+ return undefined;
1118
+ }
1119
+ txEffects.push(deserializeIndexedTxEffect(txEffect).data);
1120
+ }
1121
+ const body = new Body(txEffects);
1122
+ const block = new L2Block(archive, header, body, checkpointNumber, indexWithinCheckpoint);
1123
+
1124
+ if (block.number !== blockNumber) {
1125
+ throw new Error(
1126
+ `Block number mismatch when retrieving block from archive (expected ${blockNumber} but got ${
1127
+ block.number
1128
+ } with hash ${blockHashString})`,
1129
+ );
1130
+ }
1131
+ return block;
1132
+ }
1133
+
1134
+ /**
1135
+ * Gets a tx effect.
1136
+ * @param txHash - The hash of the tx corresponding to the tx effect.
1137
+ * @returns The requested tx effect with block info (or undefined if not found).
1138
+ */
1139
+ async getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
1140
+ const buffer = await this.#txEffects.getAsync(txHash.toString());
1141
+ if (!buffer) {
1142
+ return undefined;
1143
+ }
1144
+ return deserializeIndexedTxEffect(buffer);
1145
+ }
1146
+
1147
+ /**
1148
+ * Gets a receipt of a settled tx.
1149
+ * @param txHash - The hash of a tx we try to get the receipt for.
1150
+ * @returns The requested tx receipt (or undefined if not found).
1151
+ */
1152
+ async getSettledTxReceipt(
1153
+ txHash: TxHash,
1154
+ l1Constants?: Pick<L1RollupConstants, 'epochDuration'>,
1155
+ ): Promise<TxReceipt | undefined> {
1156
+ const txEffect = await this.getTxEffect(txHash);
1157
+ if (!txEffect) {
1158
+ return undefined;
1159
+ }
1160
+
1161
+ const blockNumber = BlockNumber(txEffect.l2BlockNumber);
1162
+
1163
+ // Use existing archiver methods to determine finalization level
1164
+ const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber, blockData] = await Promise.all([
1165
+ this.getProvenBlockNumber(),
1166
+ this.getCheckpointedL2BlockNumber(),
1167
+ this.getFinalizedL2BlockNumber(),
1168
+ this.getBlockData(blockNumber),
1169
+ ]);
1170
+
1171
+ let status: TxStatus;
1172
+ if (blockNumber <= finalizedBlockNumber) {
1173
+ status = TxStatus.FINALIZED;
1174
+ } else if (blockNumber <= provenBlockNumber) {
1175
+ status = TxStatus.PROVEN;
1176
+ } else if (blockNumber <= checkpointedBlockNumber) {
1177
+ status = TxStatus.CHECKPOINTED;
1178
+ } else {
1179
+ status = TxStatus.PROPOSED;
1180
+ }
1181
+
1182
+ const epochNumber =
1183
+ blockData && l1Constants ? getEpochAtSlot(blockData.header.globalVariables.slotNumber, l1Constants) : undefined;
1184
+
1185
+ return new TxReceipt(
1186
+ txHash,
1187
+ status,
1188
+ TxReceipt.executionResultFromRevertCode(txEffect.data.revertCode),
1189
+ undefined,
1190
+ txEffect.data.transactionFee.toBigInt(),
1191
+ txEffect.l2BlockHash,
1192
+ blockNumber,
1193
+ epochNumber,
1194
+ );
1195
+ }
1196
+
1197
+ /**
1198
+ * Looks up which block included the requested tx effect.
1199
+ * @param txHash - The txHash of the tx.
1200
+ * @returns The block number and index of the tx.
1201
+ */
1202
+ public async getTxLocation(txHash: TxHash): Promise<[blockNumber: number, txIndex: number] | undefined> {
1203
+ const txEffect = await this.#txEffects.getAsync(txHash.toString());
1204
+ if (!txEffect) {
1205
+ return undefined;
1206
+ }
1207
+ const { l2BlockNumber, txIndexInBlock } = deserializeIndexedTxEffect(txEffect);
1208
+ return [l2BlockNumber, txIndexInBlock];
1209
+ }
1210
+
1211
+ /**
1212
+ * Looks up which block deployed a particular contract.
1213
+ * @param contractAddress - The address of the contract to look up.
1214
+ * @returns The block number and index of the contract.
1215
+ */
1216
+ getContractLocation(contractAddress: AztecAddress): Promise<[blockNumber: number, index: number] | undefined> {
1217
+ return this.#contractIndex.getAsync(contractAddress.toString());
1218
+ }
1219
+
1220
+ /**
1221
+ * Gets the number of the latest L2 block checkpointed.
1222
+ * @returns The number of the latest L2 block checkpointed.
1223
+ */
1224
+ async getCheckpointedL2BlockNumber(): Promise<BlockNumber> {
1225
+ const latestCheckpointNumber = await this.getLatestCheckpointNumber();
1226
+ const checkpoint = await this.getCheckpointData(latestCheckpointNumber);
1227
+ if (!checkpoint) {
1228
+ return BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
1229
+ }
1230
+ return BlockNumber(checkpoint.startBlock + checkpoint.blockCount - 1);
1231
+ }
1232
+
1233
+ async getLatestL2BlockNumber(): Promise<BlockNumber> {
1234
+ const [lastBlockNumber] = await toArray(this.#blocks.keysAsync({ reverse: true, limit: 1 }));
1235
+ return typeof lastBlockNumber === 'number' ? BlockNumber(lastBlockNumber) : BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
1236
+ }
1237
+
1238
+ /**
1239
+ * Gets the most recent L1 block processed.
1240
+ * @returns The L1 block that published the latest L2 block
1241
+ */
1242
+ getSynchedL1BlockNumber(): Promise<bigint | undefined> {
1243
+ return this.#lastSynchedL1Block.getAsync();
1244
+ }
1245
+
1246
+ setSynchedL1BlockNumber(l1BlockNumber: bigint) {
1247
+ return this.#lastSynchedL1Block.set(l1BlockNumber);
1248
+ }
1249
+
1250
+ /**
1251
+ * Adds a proposed checkpoint to the pending queue.
1252
+ * Accepts proposed.checkpointNumber === latestTip + 1, where latestTip is the highest of
1253
+ * confirmed and the highest pending checkpoint number.
1254
+ * Computes archive and checkpointOutHash from the stored blocks.
1255
+ */
1256
+ async addProposedCheckpoint(proposed: ProposedCheckpointInput) {
1257
+ return await this.db.transactionAsync(async () => {
1258
+ const confirmed = await this.getLatestCheckpointNumber();
1259
+ const [latestPendingKey] = await toArray(this.#proposedCheckpoints.keysAsync({ reverse: true, limit: 1 }));
1260
+ const latestTip = CheckpointNumber(
1261
+ latestPendingKey !== undefined ? Math.max(latestPendingKey, confirmed) : confirmed,
1262
+ );
1263
+
1264
+ if (proposed.checkpointNumber !== latestTip + 1) {
1265
+ throw new ProposedCheckpointNotSequentialError(proposed.checkpointNumber, latestTip);
1266
+ }
1267
+
1268
+ // Ensure the predecessor block (from pending or confirmed chain) exists
1269
+ const previousBlock = await this.getPreviousCheckpointBlock(proposed.checkpointNumber);
1270
+ const blocks: L2Block[] = [];
1271
+ for (let i = 0; i < proposed.blockCount; i++) {
1272
+ const block = await this.getBlock(BlockNumber(proposed.startBlock + i));
1273
+ if (!block) {
1274
+ throw new BlockNotFoundError(proposed.startBlock + i);
1275
+ }
1276
+ blocks.push(block);
1277
+ }
1278
+ this.validateCheckpointBlocks(blocks, previousBlock);
1279
+
1280
+ const archive = blocks[blocks.length - 1].archive;
1281
+ const checkpointOutHash = Checkpoint.getCheckpointOutHash(blocks);
1282
+
1283
+ await this.#proposedCheckpoints.set(proposed.checkpointNumber, {
1284
+ header: proposed.header.toBuffer(),
1285
+ archive: archive.toBuffer(),
1286
+ checkpointOutHash: checkpointOutHash.toBuffer(),
1287
+ checkpointNumber: proposed.checkpointNumber,
1288
+ startBlock: proposed.startBlock,
1289
+ blockCount: proposed.blockCount,
1290
+ totalManaUsed: proposed.totalManaUsed.toString(),
1291
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
1292
+ });
1293
+ });
1294
+ }
1295
+
1296
+ async getProvenCheckpointNumber(): Promise<CheckpointNumber> {
1297
+ const [latestCheckpointNumber, provenCheckpointNumber] = await Promise.all([
1298
+ this.getLatestCheckpointNumber(),
1299
+ this.#lastProvenCheckpoint.getAsync(),
1300
+ ]);
1301
+ return (provenCheckpointNumber ?? 0) > latestCheckpointNumber
1302
+ ? latestCheckpointNumber
1303
+ : CheckpointNumber(provenCheckpointNumber ?? 0);
1304
+ }
1305
+
1306
+ async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber) {
1307
+ const result = await this.#lastProvenCheckpoint.set(checkpointNumber);
1308
+ return result;
1309
+ }
1310
+
1311
+ async getFinalizedCheckpointNumber(): Promise<CheckpointNumber> {
1312
+ const [latestCheckpointNumber, finalizedCheckpointNumber] = await Promise.all([
1313
+ this.getLatestCheckpointNumber(),
1314
+ this.#lastFinalizedCheckpoint.getAsync(),
1315
+ ]);
1316
+ return (finalizedCheckpointNumber ?? 0) > latestCheckpointNumber
1317
+ ? latestCheckpointNumber
1318
+ : CheckpointNumber(finalizedCheckpointNumber ?? 0);
1319
+ }
1320
+
1321
+ setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber) {
1322
+ return this.#lastFinalizedCheckpoint.set(checkpointNumber);
1323
+ }
1324
+
1325
+ #computeBlockRange(start: BlockNumber, limit: number): Required<Pick<Range<number>, 'start' | 'limit'>> {
1326
+ if (limit < 1) {
1327
+ throw new Error(`Invalid limit: ${limit}`);
1328
+ }
1329
+
1330
+ if (start < INITIAL_L2_BLOCK_NUM) {
1331
+ throw new Error(`Invalid start: ${start}`);
1332
+ }
1333
+
1334
+ return { start, limit };
1335
+ }
1336
+
1337
+ /**
1338
+ * Gets the pending chain validation status.
1339
+ * @returns The validation status or undefined if not set.
1340
+ */
1341
+ async getPendingChainValidationStatus(): Promise<ValidateCheckpointResult | undefined> {
1342
+ const buffer = await this.#pendingChainValidationStatus.getAsync();
1343
+ if (!buffer) {
1344
+ return undefined;
1345
+ }
1346
+ return deserializeValidateCheckpointResult(buffer);
1347
+ }
1348
+
1349
+ /**
1350
+ * Sets the pending chain validation status.
1351
+ * @param status - The validation status to store.
1352
+ */
1353
+ async setPendingChainValidationStatus(status: ValidateCheckpointResult | undefined): Promise<void> {
1354
+ if (status) {
1355
+ const buffer = serializeValidateCheckpointResult(status);
1356
+ await this.#pendingChainValidationStatus.set(buffer);
1357
+ } else {
1358
+ await this.#pendingChainValidationStatus.delete();
1359
+ }
1360
+ }
1361
+ }