@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,518 @@
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
+ await this.stores.blocks.addCheckpoints(checkpoints);
118
+
119
+ // Filter out blocks that were already inserted via addProposedBlock() to avoid duplicating logs/contract data
120
+ const newBlocks = checkpoints
121
+ .flatMap((ch: PublishedCheckpoint) => ch.checkpoint.blocks)
122
+ .filter(b => lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
123
+
124
+ await Promise.all([
125
+ // Update the pending chain validation status if provided
126
+ pendingChainValidationStatus &&
127
+ this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),
128
+ // Add any logs emitted during the retrieved blocks
129
+ this.stores.logs.addLogs(newBlocks),
130
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
131
+ ...newBlocks.map(block => this.addContractDataToDb(block)),
132
+ // Promote the proposed checkpoint if requested (uses explicit checkpoint number)
133
+ promoteProposed
134
+ ? this.stores.blocks.promoteProposedToCheckpointed(
135
+ promoteProposed.checkpoint.checkpoint.number,
136
+ promoteProposed.l1,
137
+ promoteProposed.attestations,
138
+ promoteProposed.checkpoint.checkpoint.archive.root,
139
+ )
140
+ : undefined,
141
+ // Evict pending checkpoints that diverged from what L1 mined
142
+ evictProposedFrom !== undefined
143
+ ? this.stores.blocks.evictProposedCheckpointsFrom(evictProposedFrom)
144
+ : undefined,
145
+ ]);
146
+
147
+ return { prunedBlocks, lastAlreadyInsertedBlockNumber };
148
+ });
149
+ await this.l2TipsCache?.refresh();
150
+ return result;
151
+ }
152
+
153
+ public async addProposedCheckpoint(proposedCheckpoint: ProposedCheckpointInput) {
154
+ const result = await this.stores.db.transactionAsync(async () => {
155
+ await this.stores.blocks.addProposedCheckpoint(proposedCheckpoint);
156
+ });
157
+ await this.l2TipsCache?.refresh();
158
+ return result;
159
+ }
160
+
161
+ /**
162
+ * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
163
+ * Conflict detection is keyed on `blockNumber`: when a local proposed block and an L1
164
+ * checkpointed block share a block number but live at different slots (e.g. a different proposer
165
+ * mined the same block number one slot earlier), we still treat them as a conflict and prune.
166
+ * The trailing per-checkpoint prune that handles "local has extra trailing blocks within the
167
+ * same slot as the published checkpoint" remains scoped by slot to preserve pipelining: local
168
+ * blocks that live at a later slot than the checkpoint being processed represent speculation
169
+ * atop the just-confirmed tip (and may be referenced by a pending proposed checkpoint), so we
170
+ * leave them in place. This method handles multiple checkpoints but returns after pruning the
171
+ * first conflict found. This is correct because pruning from the first conflict point removes
172
+ * all subsequent blocks, and when checkpoints are added afterward, they include all the correct
173
+ * blocks.
174
+ */
175
+ private async pruneMismatchingLocalBlocks(checkpoints: PublishedCheckpoint[]): Promise<ReconcileCheckpointsResult> {
176
+ const [lastCheckpointedBlockNumber, lastBlockNumber] = await Promise.all([
177
+ this.stores.blocks.getCheckpointedL2BlockNumber(),
178
+ this.stores.blocks.getLatestL2BlockNumber(),
179
+ ]);
180
+
181
+ // Exit early if there are no local uncheckpointed blocks
182
+ if (lastBlockNumber === lastCheckpointedBlockNumber) {
183
+ return { prunedBlocks: undefined, lastAlreadyInsertedBlockNumber: undefined };
184
+ }
185
+
186
+ // Get all uncheckpointed local blocks
187
+ const uncheckpointedLocalBlocks = await this.stores.blocks.getBlocksData({
188
+ from: BlockNumber.add(lastCheckpointedBlockNumber, 1),
189
+ limit: lastBlockNumber - lastCheckpointedBlockNumber,
190
+ });
191
+
192
+ let lastAlreadyInsertedBlockNumber: BlockNumber | undefined;
193
+
194
+ for (const publishedCheckpoint of checkpoints) {
195
+ const checkpointBlocks = publishedCheckpoint.checkpoint.blocks;
196
+ const slot = publishedCheckpoint.checkpoint.slot;
197
+
198
+ if (checkpointBlocks.length === 0) {
199
+ this.log.warn(`Checkpoint ${publishedCheckpoint.checkpoint.number} for slot ${slot} has no blocks`);
200
+ continue;
201
+ }
202
+
203
+ // Find the first checkpoint block that conflicts with an existing local block and prune local afterwards.
204
+ // Conflict detection joins on block number only — same block number at a different slot is still a conflict.
205
+ for (const checkpointBlock of checkpointBlocks) {
206
+ const blockNumber = checkpointBlock.number;
207
+ const existingBlock = uncheckpointedLocalBlocks.find(b => b.header.getBlockNumber() === blockNumber);
208
+ const blockInfos = {
209
+ existingBlock: existingBlock?.header.toInspect(),
210
+ checkpointBlock: checkpointBlock.toBlockInfo(),
211
+ };
212
+
213
+ if (!existingBlock) {
214
+ this.log.verbose(`No local block found for checkpointed block number ${blockNumber}`, blockInfos);
215
+ } else if (existingBlock.archive.root.equals(checkpointBlock.archive.root)) {
216
+ this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
217
+ lastAlreadyInsertedBlockNumber = blockNumber;
218
+ } else {
219
+ this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
220
+ const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
221
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
222
+ return { prunedBlocks, lastAlreadyInsertedBlockNumber };
223
+ }
224
+ }
225
+
226
+ // If the sequencer locally proposed extra blocks within this checkpoint's slot (e.g. local has
227
+ // [N, N+1] but L1 confirmed just [N]), prune the extras. Scoped to the checkpoint's slot so we
228
+ // do not throw away speculative blocks at later slots that belong to a pending proposed checkpoint.
229
+ const lastCheckpointBlockNumber = checkpointBlocks.at(-1)!.number;
230
+ const localBlocksInSlot = uncheckpointedLocalBlocks.filter(b => b.header.getSlot() === slot);
231
+ const lastLocalBlockNumber = localBlocksInSlot.at(-1)?.header.getBlockNumber();
232
+
233
+ if (lastLocalBlockNumber !== undefined && lastLocalBlockNumber > lastCheckpointBlockNumber) {
234
+ this.log.warn(
235
+ `Local chain for slot ${slot} ends at block ${lastLocalBlockNumber} but checkpoint ends at ${lastCheckpointBlockNumber}. Pruning blocks after block ${lastCheckpointBlockNumber}.`,
236
+ );
237
+ const prunedBlocks = await this.removeBlocksAfter(lastCheckpointBlockNumber);
238
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
239
+ return { prunedBlocks, lastAlreadyInsertedBlockNumber };
240
+ }
241
+ }
242
+
243
+ return { prunedBlocks: undefined, lastAlreadyInsertedBlockNumber };
244
+ }
245
+
246
+ /**
247
+ * Removes all uncheckpointed blocks strictly after the specified block number and cleans up associated contract data.
248
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
249
+ * Verifies that each block being removed is not part of a stored checkpoint.
250
+ *
251
+ * @param blockNumber - Remove all blocks with number greater than this.
252
+ * @returns The removed blocks.
253
+ * @throws Error if any block to be removed is checkpointed.
254
+ */
255
+ public async removeUncheckpointedBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
256
+ const result = await this.stores.db.transactionAsync(async () => {
257
+ // Verify we're only removing uncheckpointed blocks
258
+ const lastCheckpointedBlockNumber = await this.stores.blocks.getCheckpointedL2BlockNumber();
259
+ if (blockNumber < lastCheckpointedBlockNumber) {
260
+ throw new Error(
261
+ `Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`,
262
+ );
263
+ }
264
+
265
+ const prunedBlocks = await this.removeBlocksAfter(blockNumber);
266
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
267
+
268
+ return prunedBlocks;
269
+ });
270
+ await this.l2TipsCache?.refresh();
271
+ return result;
272
+ }
273
+
274
+ /**
275
+ * Removes all blocks without a proposed checkpoint strictly after the specified block number and cleans up associated contract data.
276
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
277
+ * Verifies that each block being removed is not part of a stored checkpoint (proposed or not).
278
+ * This differs from `removeUncheckpointedBlocksAfter` in that it also checks proposed checkpoints.
279
+ *
280
+ * @param blockNumber - Remove all blocks with number greater than this.
281
+ * @returns The removed blocks.
282
+ * @throws Error if any block to be removed is checkpointed.
283
+ */
284
+ public async removeBlocksWithoutProposedCheckpointAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
285
+ const result = await this.stores.db.transactionAsync(async () => {
286
+ // Verify we're only removing uncheckpointed blocks
287
+ const lastCheckpointedBlockNumber = await this.stores.blocks.getProposedCheckpointL2BlockNumber();
288
+ if (blockNumber < lastCheckpointedBlockNumber) {
289
+ throw new Error(
290
+ `Cannot remove blocks after ${blockNumber} because proposed checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`,
291
+ );
292
+ }
293
+
294
+ return await this.removeBlocksAfter(blockNumber);
295
+ });
296
+ await this.l2TipsCache?.refresh();
297
+ return result;
298
+ }
299
+
300
+ /**
301
+ * Evicts pending proposed checkpoints that referenced any of the just-pruned blocks. Pruned
302
+ * blocks invalidate all proposed checkpoints from the lowest pruned block's checkpoint number
303
+ * onwards: those checkpoints either reference the pruned blocks directly or chain off them.
304
+ */
305
+ private async evictProposedCheckpointsForPrunedBlocks(prunedBlocks: L2Block[]): Promise<void> {
306
+ if (prunedBlocks.length === 0) {
307
+ return;
308
+ }
309
+ const fromCheckpointNumber = prunedBlocks[0].checkpointNumber;
310
+ await this.stores.blocks.evictProposedCheckpointsFrom(fromCheckpointNumber);
311
+ }
312
+
313
+ /**
314
+ * Removes all blocks strictly after the given block number along with any logs and contract data.
315
+ * Does not remove their checkpoints.
316
+ */
317
+ private async removeBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
318
+ // First get the blocks to be removed so we can clean up contract data
319
+ const removedBlocks = await this.stores.blocks.removeBlocksAfter(blockNumber);
320
+
321
+ // Clean up contract data and logs for the removed blocks
322
+ await Promise.all([
323
+ this.stores.logs.deleteLogs(removedBlocks),
324
+ ...removedBlocks.map(block => this.removeContractDataFromDb(block)),
325
+ ]);
326
+
327
+ return removedBlocks;
328
+ }
329
+
330
+ /**
331
+ * Removes all checkpoints after the given checkpoint number.
332
+ * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
333
+ * that was stored for the removed checkpoints. Also removes ALL blocks (both checkpointed
334
+ * and uncheckpointed) after the last block of the given checkpoint.
335
+ *
336
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
337
+ * @returns True if the operation is successful.
338
+ */
339
+ public async removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
340
+ const result = await this.stores.db.transactionAsync(async () => {
341
+ const { blocksRemoved = [] } = await this.stores.blocks.removeCheckpointsAfter(checkpointNumber);
342
+
343
+ const opResults = await Promise.all([
344
+ // Prune rolls back to the last proven block, which is by definition valid
345
+ this.stores.blocks.setPendingChainValidationStatus({ valid: true }),
346
+ // Remove contract data for all blocks being removed
347
+ ...blocksRemoved.map(block => this.removeContractDataFromDb(block)),
348
+ this.stores.logs.deleteLogs(blocksRemoved),
349
+ ]);
350
+
351
+ return opResults.every(Boolean);
352
+ });
353
+ await this.l2TipsCache?.refresh();
354
+ return result;
355
+ }
356
+
357
+ /**
358
+ * Updates the proven checkpoint number and refreshes the L2 tips cache.
359
+ * @param checkpointNumber - The checkpoint number to set as proven.
360
+ */
361
+ public async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
362
+ await this.stores.db.transactionAsync(async () => {
363
+ await this.stores.blocks.setProvenCheckpointNumber(checkpointNumber);
364
+ });
365
+ await this.l2TipsCache?.refresh();
366
+ }
367
+
368
+ /**
369
+ * Updates the finalized checkpoint number and refreshes the L2 tips cache.
370
+ * @param checkpointNumber - The checkpoint number to set as finalized.
371
+ */
372
+ public async setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
373
+ await this.stores.db.transactionAsync(async () => {
374
+ await this.stores.blocks.setFinalizedCheckpointNumber(checkpointNumber);
375
+ });
376
+ await this.l2TipsCache?.refresh();
377
+ }
378
+
379
+ /** Extracts and stores contract data from a single block. */
380
+ private addContractDataToDb(block: L2Block): Promise<boolean> {
381
+ return this.updateContractDataOnDb(block, Operation.Store);
382
+ }
383
+
384
+ /** Removes contract data associated with a block. */
385
+ private removeContractDataFromDb(block: L2Block): Promise<boolean> {
386
+ return this.updateContractDataOnDb(block, Operation.Delete);
387
+ }
388
+
389
+ /** Adds or remove contract data associated with a block. */
390
+ private async updateContractDataOnDb(block: L2Block, operation: Operation): Promise<boolean> {
391
+ const contractClassLogs = block.body.txEffects.flatMap(txEffect => txEffect.contractClassLogs);
392
+ const privateLogs = block.body.txEffects.flatMap(txEffect => txEffect.privateLogs);
393
+ const publicLogs = block.body.txEffects.flatMap(txEffect => txEffect.publicLogs);
394
+
395
+ return (
396
+ await Promise.all([
397
+ this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
398
+ this.updateDeployedContractInstances(privateLogs, block.number, operation),
399
+ this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
400
+ ])
401
+ ).every(Boolean);
402
+ }
403
+
404
+ /**
405
+ * Extracts and stores contract classes out of ContractClassPublished events emitted by the class registry contract.
406
+ */
407
+ private async updatePublishedContractClasses(
408
+ allLogs: ContractClassLog[],
409
+ blockNum: BlockNumber,
410
+ operation: Operation,
411
+ ): Promise<boolean> {
412
+ const contractClassPublishedEvents = allLogs
413
+ .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
414
+ .map(log => ContractClassPublishedEvent.fromLog(log));
415
+
416
+ if (operation == Operation.Delete) {
417
+ const contractClasses = contractClassPublishedEvents.map(e => e.toContractClassPublic());
418
+ if (contractClasses.length > 0) {
419
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
420
+ return await this.stores.contractClasses.deleteContractClasses(contractClasses, blockNum);
421
+ }
422
+ return true;
423
+ }
424
+
425
+ // Compute bytecode commitments and validate class IDs in a single pass.
426
+ const contractClasses: ContractClassPublicWithCommitment[] = [];
427
+ for (const event of contractClassPublishedEvents) {
428
+ const contractClass = await event.toContractClassPublicWithBytecodeCommitment();
429
+ const computedClassId = await computeContractClassId({
430
+ artifactHash: contractClass.artifactHash,
431
+ privateFunctionsRoot: contractClass.privateFunctionsRoot,
432
+ publicBytecodeCommitment: contractClass.publicBytecodeCommitment,
433
+ });
434
+ if (!computedClassId.equals(contractClass.id)) {
435
+ this.log.warn(
436
+ `Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`,
437
+ { blockNum, contractClassId: event.contractClassId.toString() },
438
+ );
439
+ continue;
440
+ }
441
+ contractClasses.push(contractClass);
442
+ }
443
+
444
+ if (contractClasses.length > 0) {
445
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
446
+ return await this.stores.contractClasses.addContractClasses(contractClasses, blockNum);
447
+ }
448
+ return true;
449
+ }
450
+
451
+ /**
452
+ * Extracts and stores contract instances out of ContractInstancePublished events emitted by the canonical deployer contract.
453
+ */
454
+ private async updateDeployedContractInstances(
455
+ allLogs: PrivateLog[],
456
+ blockNum: BlockNumber,
457
+ operation: Operation,
458
+ ): Promise<boolean> {
459
+ const allInstances = allLogs
460
+ .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
461
+ .map(log => ContractInstancePublishedEvent.fromLog(log))
462
+ .map(e => e.toContractInstance());
463
+
464
+ // Verify that each instance's address matches the one derived from its fields if we're adding
465
+ const contractInstances =
466
+ operation === Operation.Delete
467
+ ? allInstances
468
+ : await filterAsync(allInstances, async instance => {
469
+ const computedAddress = await computeContractAddressFromInstance(instance);
470
+ if (!computedAddress.equals(instance.address)) {
471
+ this.log.warn(
472
+ `Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`,
473
+ { instanceAddress: instance.address.toString(), computedAddress: computedAddress.toString(), blockNum },
474
+ );
475
+ return false;
476
+ }
477
+ return true;
478
+ });
479
+
480
+ if (contractInstances.length > 0) {
481
+ contractInstances.forEach(c =>
482
+ this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`),
483
+ );
484
+ if (operation == Operation.Store) {
485
+ return await this.stores.contractInstances.addContractInstances(contractInstances, blockNum);
486
+ } else if (operation == Operation.Delete) {
487
+ return await this.stores.contractInstances.deleteContractInstances(contractInstances);
488
+ }
489
+ }
490
+ return true;
491
+ }
492
+
493
+ /**
494
+ * Extracts and stores contract instance updates out of ContractInstanceUpdated events.
495
+ */
496
+ private async updateUpdatedContractInstances(
497
+ allLogs: PublicLog[],
498
+ timestamp: UInt64,
499
+ operation: Operation,
500
+ ): Promise<boolean> {
501
+ const contractUpdates = allLogs
502
+ .filter(log => ContractInstanceUpdatedEvent.isContractInstanceUpdatedEvent(log))
503
+ .map(log => ContractInstanceUpdatedEvent.fromLog(log))
504
+ .map(e => e.toContractInstanceUpdate());
505
+
506
+ if (contractUpdates.length > 0) {
507
+ contractUpdates.forEach(c =>
508
+ this.log.verbose(`${Operation[operation]} contract instance update at ${c.address.toString()}`),
509
+ );
510
+ if (operation == Operation.Store) {
511
+ return await this.stores.contractInstances.addContractInstanceUpdates(contractUpdates, timestamp);
512
+ } else if (operation == Operation.Delete) {
513
+ return await this.stores.contractInstances.deleteContractInstanceUpdates(contractUpdates, timestamp);
514
+ }
515
+ }
516
+ return true;
517
+ }
518
+ }