@aztec/archiver 0.0.1-commit.96bb3f7 → 0.0.1-commit.993d240

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