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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +164 -22
  2. package/dest/archiver.d.ts +194 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +949 -0
  5. package/dest/config.d.ts +34 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +95 -0
  8. package/dest/errors.d.ts +87 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +129 -0
  11. package/dest/factory.d.ts +16 -10
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +117 -20
  14. package/dest/index.d.ts +19 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +17 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +152 -0
  23. package/dest/l1/calldata_retriever.d.ts +143 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +413 -0
  26. package/dest/l1/data_retrieval.d.ts +102 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +85 -165
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +149 -0
  35. package/dest/l1/trace_tx.d.ts +43 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_historical_logs.d.ts +23 -0
  42. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  43. package/dest/l1/validate_historical_logs.js +108 -0
  44. package/dest/l1/validate_trace.d.ts +32 -0
  45. package/dest/l1/validate_trace.d.ts.map +1 -0
  46. package/dest/l1/validate_trace.js +154 -0
  47. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  48. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  49. package/dest/modules/contract_data_source_adapter.js +32 -0
  50. package/dest/modules/data_source_base.d.ts +112 -0
  51. package/dest/modules/data_source_base.d.ts.map +1 -0
  52. package/dest/modules/data_source_base.js +322 -0
  53. package/dest/modules/data_store_updater.d.ts +105 -0
  54. package/dest/modules/data_store_updater.d.ts.map +1 -0
  55. package/dest/modules/data_store_updater.js +393 -0
  56. package/dest/modules/instrumentation.d.ts +63 -0
  57. package/dest/modules/instrumentation.d.ts.map +1 -0
  58. package/dest/modules/instrumentation.js +166 -0
  59. package/dest/modules/l1_synchronizer.d.ts +77 -0
  60. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  61. package/dest/modules/l1_synchronizer.js +1381 -0
  62. package/dest/modules/outbox_trees_resolver.d.ts +62 -0
  63. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  64. package/dest/modules/outbox_trees_resolver.js +162 -0
  65. package/dest/modules/validation.d.ts +40 -0
  66. package/dest/modules/validation.d.ts.map +1 -0
  67. package/dest/{archiver → modules}/validation.js +41 -17
  68. package/dest/store/block_store.d.ts +303 -0
  69. package/dest/store/block_store.d.ts.map +1 -0
  70. package/dest/store/block_store.js +1206 -0
  71. package/dest/store/contract_class_store.d.ts +31 -0
  72. package/dest/store/contract_class_store.d.ts.map +1 -0
  73. package/dest/store/contract_class_store.js +98 -0
  74. package/dest/store/contract_instance_store.d.ts +51 -0
  75. package/dest/store/contract_instance_store.d.ts.map +1 -0
  76. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +55 -3
  77. package/dest/store/data_stores.d.ts +68 -0
  78. package/dest/store/data_stores.d.ts.map +1 -0
  79. package/dest/store/data_stores.js +54 -0
  80. package/dest/store/function_names_cache.d.ts +17 -0
  81. package/dest/store/function_names_cache.d.ts.map +1 -0
  82. package/dest/store/function_names_cache.js +30 -0
  83. package/dest/store/l2_tips_cache.d.ts +25 -0
  84. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  85. package/dest/store/l2_tips_cache.js +26 -0
  86. package/dest/store/log_store.d.ts +59 -0
  87. package/dest/store/log_store.d.ts.map +1 -0
  88. package/dest/store/log_store.js +310 -0
  89. package/dest/store/log_store_codec.d.ts +78 -0
  90. package/dest/store/log_store_codec.d.ts.map +1 -0
  91. package/dest/store/log_store_codec.js +110 -0
  92. package/dest/store/message_store.d.ts +50 -0
  93. package/dest/store/message_store.d.ts.map +1 -0
  94. package/dest/{archiver/kv_archiver_store → store}/message_store.js +66 -23
  95. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  96. package/dest/structs/data_retrieval.d.ts.map +1 -0
  97. package/dest/structs/inbox_message.d.ts +15 -0
  98. package/dest/structs/inbox_message.d.ts.map +1 -0
  99. package/dest/{archiver/structs → structs}/inbox_message.js +6 -6
  100. package/dest/structs/published.d.ts +2 -0
  101. package/dest/structs/published.d.ts.map +1 -0
  102. package/dest/test/fake_l1_state.d.ts +214 -0
  103. package/dest/test/fake_l1_state.d.ts.map +1 -0
  104. package/dest/test/fake_l1_state.js +517 -0
  105. package/dest/test/index.d.ts +2 -1
  106. package/dest/test/index.d.ts.map +1 -1
  107. package/dest/test/index.js +4 -1
  108. package/dest/test/mock_archiver.d.ts +5 -6
  109. package/dest/test/mock_archiver.d.ts.map +1 -1
  110. package/dest/test/mock_archiver.js +8 -12
  111. package/dest/test/mock_l1_to_l2_message_source.d.ts +6 -7
  112. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  113. package/dest/test/mock_l1_to_l2_message_source.js +19 -14
  114. package/dest/test/mock_l2_block_source.d.ts +68 -40
  115. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  116. package/dest/test/mock_l2_block_source.js +347 -145
  117. package/dest/test/mock_structs.d.ts +83 -4
  118. package/dest/test/mock_structs.d.ts.map +1 -1
  119. package/dest/test/mock_structs.js +157 -12
  120. package/dest/test/noop_l1_archiver.d.ts +34 -0
  121. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  122. package/dest/test/noop_l1_archiver.js +88 -0
  123. package/package.json +18 -18
  124. package/src/archiver.ts +785 -0
  125. package/src/config.ts +125 -0
  126. package/src/errors.ts +203 -0
  127. package/src/factory.ts +185 -22
  128. package/src/index.ts +27 -3
  129. package/src/interfaces.ts +9 -0
  130. package/src/l1/README.md +55 -0
  131. package/src/l1/bin/retrieve-calldata.ts +194 -0
  132. package/src/l1/calldata_retriever.ts +529 -0
  133. package/src/{archiver → l1}/data_retrieval.ts +157 -243
  134. package/src/l1/debug_tx.ts +99 -0
  135. package/src/l1/spire_proposer.ts +152 -0
  136. package/src/l1/trace_tx.ts +128 -0
  137. package/src/l1/types.ts +13 -0
  138. package/src/l1/validate_historical_logs.ts +140 -0
  139. package/src/l1/validate_trace.ts +229 -0
  140. package/src/modules/contract_data_source_adapter.ts +46 -0
  141. package/src/modules/data_source_base.ts +466 -0
  142. package/src/modules/data_store_updater.ts +519 -0
  143. package/src/modules/instrumentation.ts +217 -0
  144. package/src/modules/l1_synchronizer.ts +1320 -0
  145. package/src/modules/outbox_trees_resolver.ts +199 -0
  146. package/src/modules/validation.ts +186 -0
  147. package/src/store/block_store.ts +1551 -0
  148. package/src/store/contract_class_store.ts +126 -0
  149. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +70 -7
  150. package/src/store/data_stores.ts +104 -0
  151. package/src/store/function_names_cache.ts +37 -0
  152. package/src/store/l2_tips_cache.ts +35 -0
  153. package/src/store/log_store.ts +380 -0
  154. package/src/store/log_store_codec.ts +143 -0
  155. package/src/{archiver/kv_archiver_store → store}/message_store.ts +81 -28
  156. package/src/{archiver/structs → structs}/inbox_message.ts +8 -9
  157. package/src/{archiver/structs → structs}/published.ts +0 -1
  158. package/src/test/fake_l1_state.ts +770 -0
  159. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  160. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  161. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  162. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  163. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  164. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  165. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  166. package/src/test/index.ts +4 -0
  167. package/src/test/mock_archiver.ts +10 -14
  168. package/src/test/mock_l1_to_l2_message_source.ts +16 -15
  169. package/src/test/mock_l2_block_source.ts +416 -161
  170. package/src/test/mock_structs.ts +292 -14
  171. package/src/test/noop_l1_archiver.ts +158 -0
  172. package/dest/archiver/archiver.d.ts +0 -290
  173. package/dest/archiver/archiver.d.ts.map +0 -1
  174. package/dest/archiver/archiver.js +0 -1434
  175. package/dest/archiver/archiver_store.d.ts +0 -256
  176. package/dest/archiver/archiver_store.d.ts.map +0 -1
  177. package/dest/archiver/archiver_store.js +0 -4
  178. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  179. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  180. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  181. package/dest/archiver/config.d.ts +0 -21
  182. package/dest/archiver/config.d.ts.map +0 -1
  183. package/dest/archiver/config.js +0 -55
  184. package/dest/archiver/data_retrieval.d.ts +0 -80
  185. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  186. package/dest/archiver/errors.d.ts +0 -12
  187. package/dest/archiver/errors.d.ts.map +0 -1
  188. package/dest/archiver/errors.js +0 -17
  189. package/dest/archiver/index.d.ts +0 -7
  190. package/dest/archiver/index.d.ts.map +0 -1
  191. package/dest/archiver/index.js +0 -4
  192. package/dest/archiver/instrumentation.d.ts +0 -35
  193. package/dest/archiver/instrumentation.d.ts.map +0 -1
  194. package/dest/archiver/instrumentation.js +0 -140
  195. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -125
  196. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  197. package/dest/archiver/kv_archiver_store/block_store.js +0 -371
  198. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  199. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  200. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  201. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  202. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  203. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -169
  204. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  205. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  206. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  207. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  208. package/dest/archiver/kv_archiver_store/log_store.js +0 -337
  209. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  210. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  211. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  212. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  213. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  214. package/dest/archiver/structs/published.d.ts +0 -3
  215. package/dest/archiver/structs/published.d.ts.map +0 -1
  216. package/dest/archiver/validation.d.ts +0 -17
  217. package/dest/archiver/validation.d.ts.map +0 -1
  218. package/dest/rpc/index.d.ts +0 -9
  219. package/dest/rpc/index.d.ts.map +0 -1
  220. package/dest/rpc/index.js +0 -15
  221. package/src/archiver/archiver.ts +0 -1880
  222. package/src/archiver/archiver_store.ts +0 -310
  223. package/src/archiver/archiver_store_test_suite.ts +0 -1295
  224. package/src/archiver/config.ts +0 -79
  225. package/src/archiver/errors.ts +0 -26
  226. package/src/archiver/index.ts +0 -6
  227. package/src/archiver/instrumentation.ts +0 -187
  228. package/src/archiver/kv_archiver_store/block_store.ts +0 -482
  229. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  230. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -423
  231. package/src/archiver/kv_archiver_store/log_store.ts +0 -407
  232. package/src/archiver/validation.ts +0 -124
  233. package/src/rpc/index.ts +0 -16
  234. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  235. /package/dest/{archiver/structs → structs}/published.js +0 -0
  236. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,519 @@
1
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import { filterAsync } from '@aztec/foundation/collection';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+ import { ContractClassPublishedEvent } from '@aztec/protocol-contracts/class-registry';
5
+ import {
6
+ ContractInstancePublishedEvent,
7
+ ContractInstanceUpdatedEvent,
8
+ } from '@aztec/protocol-contracts/instance-registry';
9
+ import type { CommitteeAttestation, L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
10
+ import {
11
+ type L1PublishedData,
12
+ type ProposedCheckpointInput,
13
+ type PublishedCheckpoint,
14
+ validateCheckpoint,
15
+ } from '@aztec/stdlib/checkpoint';
16
+ import {
17
+ type ContractClassPublicWithCommitment,
18
+ computeContractAddressFromInstance,
19
+ computeContractClassId,
20
+ } from '@aztec/stdlib/contract';
21
+ import type { ContractClassLog, PrivateLog, PublicLog } from '@aztec/stdlib/logs';
22
+ import type { UInt64 } from '@aztec/stdlib/types';
23
+
24
+ import type { ArchiverDataStores } from '../store/data_stores.js';
25
+ import type { L2TipsCache } from '../store/l2_tips_cache.js';
26
+
27
+ /** Operation type for contract data updates. */
28
+ enum Operation {
29
+ Store,
30
+ Delete,
31
+ }
32
+
33
+ /** Result of adding checkpoints with information about any pruned blocks. */
34
+ type ReconcileCheckpointsResult = {
35
+ /** Blocks that were pruned due to conflict with L1 checkpoints. */
36
+ prunedBlocks: L2Block[] | undefined;
37
+ /** Last block number that was already inserted locally, or undefined if none. */
38
+ lastAlreadyInsertedBlockNumber: BlockNumber | undefined;
39
+ };
40
+
41
+ /** Archiver helper module to handle updates to the data store. */
42
+ export class ArchiverDataStoreUpdater {
43
+ private readonly log = createLogger('archiver:store_updater');
44
+
45
+ constructor(
46
+ private stores: ArchiverDataStores,
47
+ private l2TipsCache?: L2TipsCache,
48
+ private opts: { rollupManaLimit?: number } = {},
49
+ ) {}
50
+
51
+ /**
52
+ * Adds a proposed block to the store with contract class/instance extraction from logs.
53
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
54
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the block logs.
55
+ *
56
+ * @param block - The proposed L2 block to add.
57
+ * @param pendingChainValidationStatus - Optional validation status to set.
58
+ * @returns True if the operation is successful.
59
+ */
60
+ public async addProposedBlock(
61
+ block: L2Block,
62
+ pendingChainValidationStatus?: ValidateCheckpointResult,
63
+ ): Promise<boolean> {
64
+ const result = await this.stores.db.transactionAsync(async () => {
65
+ await this.stores.blocks.addProposedBlock(block);
66
+
67
+ const opResults = await Promise.all([
68
+ // Update the pending chain validation status if provided
69
+ pendingChainValidationStatus &&
70
+ this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),
71
+ // Add any logs emitted during the retrieved block
72
+ this.stores.logs.addLogs([block]),
73
+ // Unroll all logs emitted during the retrieved block and extract any contract classes and instances from it
74
+ this.addContractDataToDb(block),
75
+ ]);
76
+
77
+ return opResults.every(Boolean);
78
+ });
79
+ await this.l2TipsCache?.refresh();
80
+ return result;
81
+ }
82
+
83
+ /**
84
+ * Reconciles local blocks with incoming checkpoints from L1.
85
+ * Adds new checkpoints to the store with contract class/instance extraction from logs.
86
+ * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
87
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the checkpoint block logs.
88
+ * If `promoteProposed` is supplied, the proposed-checkpoint promotion runs inside the same transaction
89
+ * as the added checkpoints so both updates are applied atomically.
90
+ *
91
+ * @param checkpoints - The published checkpoints to add (excluding any being promoted from proposed).
92
+ * @param pendingChainValidationStatus - Optional validation status to set.
93
+ * @param promoteProposed - Optional promotion of the current proposed checkpoint (fast path when blocks are already local).
94
+ * @returns Result with information about any pruned blocks.
95
+ */
96
+ public async addCheckpoints(
97
+ checkpoints: PublishedCheckpoint[],
98
+ pendingChainValidationStatus?: ValidateCheckpointResult,
99
+ promoteProposed?: {
100
+ l1: L1PublishedData;
101
+ attestations: CommitteeAttestation[];
102
+ checkpoint: PublishedCheckpoint;
103
+ },
104
+ evictProposedFrom?: CheckpointNumber,
105
+ ): Promise<ReconcileCheckpointsResult> {
106
+ for (const checkpoint of checkpoints) {
107
+ validateCheckpoint(checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
108
+ }
109
+ if (promoteProposed) {
110
+ validateCheckpoint(promoteProposed.checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
111
+ }
112
+
113
+ const result = await this.stores.db.transactionAsync(async () => {
114
+ // Before adding checkpoints, check for conflicts with local blocks if any
115
+ const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
116
+
117
+ const insertedCheckpoints = await this.stores.blocks.addCheckpoints(checkpoints);
118
+
119
+ // Skip blocks already inserted via addProposedBlock() and blocks of already-stored checkpoints
120
+ // re-included by an L1 reorg: their logs/contract data were extracted when first inserted.
121
+ const newBlocks = insertedCheckpoints
122
+ .flatMap((ch: PublishedCheckpoint) => ch.checkpoint.blocks)
123
+ .filter(b => lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
124
+
125
+ await Promise.all([
126
+ // Update the pending chain validation status if provided
127
+ pendingChainValidationStatus &&
128
+ this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),
129
+ // Add any logs emitted during the retrieved blocks
130
+ this.stores.logs.addLogs(newBlocks),
131
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
132
+ ...newBlocks.map(block => this.addContractDataToDb(block)),
133
+ // Promote the proposed checkpoint if requested (uses explicit checkpoint number)
134
+ promoteProposed
135
+ ? this.stores.blocks.promoteProposedToCheckpointed(
136
+ promoteProposed.checkpoint.checkpoint.number,
137
+ promoteProposed.l1,
138
+ promoteProposed.attestations,
139
+ promoteProposed.checkpoint.checkpoint.archive.root,
140
+ )
141
+ : undefined,
142
+ // Evict pending checkpoints that diverged from what L1 mined
143
+ evictProposedFrom !== undefined
144
+ ? this.stores.blocks.evictProposedCheckpointsFrom(evictProposedFrom)
145
+ : undefined,
146
+ ]);
147
+
148
+ return { prunedBlocks, lastAlreadyInsertedBlockNumber };
149
+ });
150
+ await this.l2TipsCache?.refresh();
151
+ return result;
152
+ }
153
+
154
+ public async addProposedCheckpoint(proposedCheckpoint: ProposedCheckpointInput) {
155
+ const result = await this.stores.db.transactionAsync(async () => {
156
+ await this.stores.blocks.addProposedCheckpoint(proposedCheckpoint);
157
+ });
158
+ await this.l2TipsCache?.refresh();
159
+ return result;
160
+ }
161
+
162
+ /**
163
+ * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
164
+ * Conflict detection is keyed on `blockNumber`: when a local proposed block and an L1
165
+ * checkpointed block share a block number but live at different slots (e.g. a different proposer
166
+ * mined the same block number one slot earlier), we still treat them as a conflict and prune.
167
+ * The trailing per-checkpoint prune that handles "local has extra trailing blocks within the
168
+ * same slot as the published checkpoint" remains scoped by slot to preserve pipelining: local
169
+ * blocks that live at a later slot than the checkpoint being processed represent speculation
170
+ * atop the just-confirmed tip (and may be referenced by a pending proposed checkpoint), so we
171
+ * leave them in place. This method handles multiple checkpoints but returns after pruning the
172
+ * first conflict found. This is correct because pruning from the first conflict point removes
173
+ * all subsequent blocks, and when checkpoints are added afterward, they include all the correct
174
+ * blocks.
175
+ */
176
+ private async pruneMismatchingLocalBlocks(checkpoints: PublishedCheckpoint[]): Promise<ReconcileCheckpointsResult> {
177
+ const [lastCheckpointedBlockNumber, lastBlockNumber] = await Promise.all([
178
+ this.stores.blocks.getCheckpointedL2BlockNumber(),
179
+ this.stores.blocks.getLatestL2BlockNumber(),
180
+ ]);
181
+
182
+ // Exit early if there are no local uncheckpointed blocks
183
+ if (lastBlockNumber === lastCheckpointedBlockNumber) {
184
+ return { prunedBlocks: undefined, lastAlreadyInsertedBlockNumber: undefined };
185
+ }
186
+
187
+ // Get all uncheckpointed local blocks
188
+ const uncheckpointedLocalBlocks = await this.stores.blocks.getBlocksData({
189
+ from: BlockNumber.add(lastCheckpointedBlockNumber, 1),
190
+ limit: lastBlockNumber - lastCheckpointedBlockNumber,
191
+ });
192
+
193
+ let lastAlreadyInsertedBlockNumber: BlockNumber | undefined;
194
+
195
+ for (const publishedCheckpoint of checkpoints) {
196
+ const checkpointBlocks = publishedCheckpoint.checkpoint.blocks;
197
+ const slot = publishedCheckpoint.checkpoint.slot;
198
+
199
+ if (checkpointBlocks.length === 0) {
200
+ this.log.warn(`Checkpoint ${publishedCheckpoint.checkpoint.number} for slot ${slot} has no blocks`);
201
+ continue;
202
+ }
203
+
204
+ // Find the first checkpoint block that conflicts with an existing local block and prune local afterwards.
205
+ // Conflict detection joins on block number only — same block number at a different slot is still a conflict.
206
+ for (const checkpointBlock of checkpointBlocks) {
207
+ const blockNumber = checkpointBlock.number;
208
+ const existingBlock = uncheckpointedLocalBlocks.find(b => b.header.getBlockNumber() === blockNumber);
209
+ const blockInfos = {
210
+ existingBlock: existingBlock?.header.toInspect(),
211
+ checkpointBlock: checkpointBlock.toBlockInfo(),
212
+ };
213
+
214
+ if (!existingBlock) {
215
+ this.log.verbose(`No local block found for checkpointed block number ${blockNumber}`, blockInfos);
216
+ } else if (existingBlock.archive.root.equals(checkpointBlock.archive.root)) {
217
+ this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
218
+ lastAlreadyInsertedBlockNumber = blockNumber;
219
+ } else {
220
+ this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
221
+ const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
222
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
223
+ return { prunedBlocks, lastAlreadyInsertedBlockNumber };
224
+ }
225
+ }
226
+
227
+ // If the sequencer locally proposed extra blocks within this checkpoint's slot (e.g. local has
228
+ // [N, N+1] but L1 confirmed just [N]), prune the extras. Scoped to the checkpoint's slot so we
229
+ // do not throw away speculative blocks at later slots that belong to a pending proposed checkpoint.
230
+ const lastCheckpointBlockNumber = checkpointBlocks.at(-1)!.number;
231
+ const localBlocksInSlot = uncheckpointedLocalBlocks.filter(b => b.header.getSlot() === slot);
232
+ const lastLocalBlockNumber = localBlocksInSlot.at(-1)?.header.getBlockNumber();
233
+
234
+ if (lastLocalBlockNumber !== undefined && lastLocalBlockNumber > lastCheckpointBlockNumber) {
235
+ this.log.warn(
236
+ `Local chain for slot ${slot} ends at block ${lastLocalBlockNumber} but checkpoint ends at ${lastCheckpointBlockNumber}. Pruning blocks after block ${lastCheckpointBlockNumber}.`,
237
+ );
238
+ const prunedBlocks = await this.removeBlocksAfter(lastCheckpointBlockNumber);
239
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
240
+ return { prunedBlocks, lastAlreadyInsertedBlockNumber };
241
+ }
242
+ }
243
+
244
+ return { prunedBlocks: undefined, lastAlreadyInsertedBlockNumber };
245
+ }
246
+
247
+ /**
248
+ * Removes all uncheckpointed blocks strictly after the specified block number and cleans up associated contract data.
249
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
250
+ * Verifies that each block being removed is not part of a stored checkpoint.
251
+ *
252
+ * @param blockNumber - Remove all blocks with number greater than this.
253
+ * @returns The removed blocks.
254
+ * @throws Error if any block to be removed is checkpointed.
255
+ */
256
+ public async removeUncheckpointedBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
257
+ const result = await this.stores.db.transactionAsync(async () => {
258
+ // Verify we're only removing uncheckpointed blocks
259
+ const lastCheckpointedBlockNumber = await this.stores.blocks.getCheckpointedL2BlockNumber();
260
+ if (blockNumber < lastCheckpointedBlockNumber) {
261
+ throw new Error(
262
+ `Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`,
263
+ );
264
+ }
265
+
266
+ const prunedBlocks = await this.removeBlocksAfter(blockNumber);
267
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
268
+
269
+ return prunedBlocks;
270
+ });
271
+ await this.l2TipsCache?.refresh();
272
+ return result;
273
+ }
274
+
275
+ /**
276
+ * Removes all blocks without a proposed checkpoint strictly after the specified block number and cleans up associated contract data.
277
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
278
+ * Verifies that each block being removed is not part of a stored checkpoint (proposed or not).
279
+ * This differs from `removeUncheckpointedBlocksAfter` in that it also checks proposed checkpoints.
280
+ *
281
+ * @param blockNumber - Remove all blocks with number greater than this.
282
+ * @returns The removed blocks.
283
+ * @throws Error if any block to be removed is checkpointed.
284
+ */
285
+ public async removeBlocksWithoutProposedCheckpointAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
286
+ const result = await this.stores.db.transactionAsync(async () => {
287
+ // Verify we're only removing uncheckpointed blocks
288
+ const lastCheckpointedBlockNumber = await this.stores.blocks.getProposedCheckpointL2BlockNumber();
289
+ if (blockNumber < lastCheckpointedBlockNumber) {
290
+ throw new Error(
291
+ `Cannot remove blocks after ${blockNumber} because proposed checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`,
292
+ );
293
+ }
294
+
295
+ return await this.removeBlocksAfter(blockNumber);
296
+ });
297
+ await this.l2TipsCache?.refresh();
298
+ return result;
299
+ }
300
+
301
+ /**
302
+ * Evicts pending proposed checkpoints that referenced any of the just-pruned blocks. Pruned
303
+ * blocks invalidate all proposed checkpoints from the lowest pruned block's checkpoint number
304
+ * onwards: those checkpoints either reference the pruned blocks directly or chain off them.
305
+ */
306
+ private async evictProposedCheckpointsForPrunedBlocks(prunedBlocks: L2Block[]): Promise<void> {
307
+ if (prunedBlocks.length === 0) {
308
+ return;
309
+ }
310
+ const fromCheckpointNumber = prunedBlocks[0].checkpointNumber;
311
+ await this.stores.blocks.evictProposedCheckpointsFrom(fromCheckpointNumber);
312
+ }
313
+
314
+ /**
315
+ * Removes all blocks strictly after the given block number along with any logs and contract data.
316
+ * Does not remove their checkpoints.
317
+ */
318
+ private async removeBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
319
+ // First get the blocks to be removed so we can clean up contract data
320
+ const removedBlocks = await this.stores.blocks.removeBlocksAfter(blockNumber);
321
+
322
+ // Clean up contract data and logs for the removed blocks
323
+ await Promise.all([
324
+ this.stores.logs.deleteLogs(removedBlocks),
325
+ ...removedBlocks.map(block => this.removeContractDataFromDb(block)),
326
+ ]);
327
+
328
+ return removedBlocks;
329
+ }
330
+
331
+ /**
332
+ * Removes all checkpoints after the given checkpoint number.
333
+ * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
334
+ * that was stored for the removed checkpoints. Also removes ALL blocks (both checkpointed
335
+ * and uncheckpointed) after the last block of the given checkpoint.
336
+ *
337
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
338
+ * @returns True if the operation is successful.
339
+ */
340
+ public async removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
341
+ const result = await this.stores.db.transactionAsync(async () => {
342
+ const { blocksRemoved = [] } = await this.stores.blocks.removeCheckpointsAfter(checkpointNumber);
343
+
344
+ const opResults = await Promise.all([
345
+ // Prune rolls back to the last proven block, which is by definition valid
346
+ this.stores.blocks.setPendingChainValidationStatus({ valid: true }),
347
+ // Remove contract data for all blocks being removed
348
+ ...blocksRemoved.map(block => this.removeContractDataFromDb(block)),
349
+ this.stores.logs.deleteLogs(blocksRemoved),
350
+ ]);
351
+
352
+ return opResults.every(Boolean);
353
+ });
354
+ await this.l2TipsCache?.refresh();
355
+ return result;
356
+ }
357
+
358
+ /**
359
+ * Updates the proven checkpoint number and refreshes the L2 tips cache.
360
+ * @param checkpointNumber - The checkpoint number to set as proven.
361
+ */
362
+ public async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
363
+ await this.stores.db.transactionAsync(async () => {
364
+ await this.stores.blocks.setProvenCheckpointNumber(checkpointNumber);
365
+ });
366
+ await this.l2TipsCache?.refresh();
367
+ }
368
+
369
+ /**
370
+ * Updates the finalized checkpoint number and refreshes the L2 tips cache.
371
+ * @param checkpointNumber - The checkpoint number to set as finalized.
372
+ */
373
+ public async setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
374
+ await this.stores.db.transactionAsync(async () => {
375
+ await this.stores.blocks.setFinalizedCheckpointNumber(checkpointNumber);
376
+ });
377
+ await this.l2TipsCache?.refresh();
378
+ }
379
+
380
+ /** Extracts and stores contract data from a single block. */
381
+ private addContractDataToDb(block: L2Block): Promise<boolean> {
382
+ return this.updateContractDataOnDb(block, Operation.Store);
383
+ }
384
+
385
+ /** Removes contract data associated with a block. */
386
+ private removeContractDataFromDb(block: L2Block): Promise<boolean> {
387
+ return this.updateContractDataOnDb(block, Operation.Delete);
388
+ }
389
+
390
+ /** Adds or remove contract data associated with a block. */
391
+ private async updateContractDataOnDb(block: L2Block, operation: Operation): Promise<boolean> {
392
+ const contractClassLogs = block.body.txEffects.flatMap(txEffect => txEffect.contractClassLogs);
393
+ const privateLogs = block.body.txEffects.flatMap(txEffect => txEffect.privateLogs);
394
+ const publicLogs = block.body.txEffects.flatMap(txEffect => txEffect.publicLogs);
395
+
396
+ return (
397
+ await Promise.all([
398
+ this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
399
+ this.updateDeployedContractInstances(privateLogs, block.number, operation),
400
+ this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
401
+ ])
402
+ ).every(Boolean);
403
+ }
404
+
405
+ /**
406
+ * Extracts and stores contract classes out of ContractClassPublished events emitted by the class registry contract.
407
+ */
408
+ private async updatePublishedContractClasses(
409
+ allLogs: ContractClassLog[],
410
+ blockNum: BlockNumber,
411
+ operation: Operation,
412
+ ): Promise<boolean> {
413
+ const contractClassPublishedEvents = allLogs
414
+ .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
415
+ .map(log => ContractClassPublishedEvent.fromLog(log));
416
+
417
+ if (operation == Operation.Delete) {
418
+ const contractClasses = contractClassPublishedEvents.map(e => e.toContractClassPublic());
419
+ if (contractClasses.length > 0) {
420
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
421
+ return await this.stores.contractClasses.deleteContractClasses(contractClasses, blockNum);
422
+ }
423
+ return true;
424
+ }
425
+
426
+ // Compute bytecode commitments and validate class IDs in a single pass.
427
+ const contractClasses: ContractClassPublicWithCommitment[] = [];
428
+ for (const event of contractClassPublishedEvents) {
429
+ const contractClass = await event.toContractClassPublicWithBytecodeCommitment();
430
+ const computedClassId = await computeContractClassId({
431
+ artifactHash: contractClass.artifactHash,
432
+ privateFunctionsRoot: contractClass.privateFunctionsRoot,
433
+ publicBytecodeCommitment: contractClass.publicBytecodeCommitment,
434
+ });
435
+ if (!computedClassId.equals(contractClass.id)) {
436
+ this.log.warn(
437
+ `Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`,
438
+ { blockNum, contractClassId: event.contractClassId.toString() },
439
+ );
440
+ continue;
441
+ }
442
+ contractClasses.push(contractClass);
443
+ }
444
+
445
+ if (contractClasses.length > 0) {
446
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
447
+ return await this.stores.contractClasses.addContractClasses(contractClasses, blockNum);
448
+ }
449
+ return true;
450
+ }
451
+
452
+ /**
453
+ * Extracts and stores contract instances out of ContractInstancePublished events emitted by the canonical deployer contract.
454
+ */
455
+ private async updateDeployedContractInstances(
456
+ allLogs: PrivateLog[],
457
+ blockNum: BlockNumber,
458
+ operation: Operation,
459
+ ): Promise<boolean> {
460
+ const allInstances = allLogs
461
+ .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
462
+ .map(log => ContractInstancePublishedEvent.fromLog(log))
463
+ .map(e => e.toContractInstance());
464
+
465
+ // Verify that each instance's address matches the one derived from its fields if we're adding
466
+ const contractInstances =
467
+ operation === Operation.Delete
468
+ ? allInstances
469
+ : await filterAsync(allInstances, async instance => {
470
+ const computedAddress = await computeContractAddressFromInstance(instance);
471
+ if (!computedAddress.equals(instance.address)) {
472
+ this.log.warn(
473
+ `Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`,
474
+ { instanceAddress: instance.address.toString(), computedAddress: computedAddress.toString(), blockNum },
475
+ );
476
+ return false;
477
+ }
478
+ return true;
479
+ });
480
+
481
+ if (contractInstances.length > 0) {
482
+ contractInstances.forEach(c =>
483
+ this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`),
484
+ );
485
+ if (operation == Operation.Store) {
486
+ return await this.stores.contractInstances.addContractInstances(contractInstances, blockNum);
487
+ } else if (operation == Operation.Delete) {
488
+ return await this.stores.contractInstances.deleteContractInstances(contractInstances);
489
+ }
490
+ }
491
+ return true;
492
+ }
493
+
494
+ /**
495
+ * Extracts and stores contract instance updates out of ContractInstanceUpdated events.
496
+ */
497
+ private async updateUpdatedContractInstances(
498
+ allLogs: PublicLog[],
499
+ timestamp: UInt64,
500
+ operation: Operation,
501
+ ): Promise<boolean> {
502
+ const contractUpdates = allLogs
503
+ .filter(log => ContractInstanceUpdatedEvent.isContractInstanceUpdatedEvent(log))
504
+ .map(log => ContractInstanceUpdatedEvent.fromLog(log))
505
+ .map(e => e.toContractInstanceUpdate());
506
+
507
+ if (contractUpdates.length > 0) {
508
+ contractUpdates.forEach(c =>
509
+ this.log.verbose(`${Operation[operation]} contract instance update at ${c.address.toString()}`),
510
+ );
511
+ if (operation == Operation.Store) {
512
+ return await this.stores.contractInstances.addContractInstanceUpdates(contractUpdates, timestamp);
513
+ } else if (operation == Operation.Delete) {
514
+ return await this.stores.contractInstances.deleteContractInstanceUpdates(contractUpdates, timestamp);
515
+ }
516
+ }
517
+ return true;
518
+ }
519
+ }