@aztec/archiver 0.0.1-commit.fcb71a6 → 0.0.1-commit.ff7989d6c

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 (200) hide show
  1. package/README.md +156 -22
  2. package/dest/archiver.d.ts +139 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +699 -0
  5. package/dest/{archiver/config.d.ts → config.d.ts} +9 -1
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +11 -2
  8. package/dest/errors.d.ts +41 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/{archiver/errors.js → errors.js} +8 -0
  11. package/dest/factory.d.ts +9 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +94 -11
  14. package/dest/index.d.ts +11 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +9 -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 +17 -18
  23. package/dest/{archiver/l1 → l1}/calldata_retriever.d.ts +9 -3
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/{archiver/l1 → l1}/calldata_retriever.js +19 -6
  26. package/dest/l1/data_retrieval.d.ts +89 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver/l1 → l1}/data_retrieval.js +39 -57
  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 +1 -1
  32. package/dest/l1/spire_proposer.d.ts.map +1 -0
  33. package/dest/{archiver/l1 → l1}/trace_tx.d.ts +1 -1
  34. package/dest/l1/trace_tx.d.ts.map +1 -0
  35. package/dest/l1/types.d.ts +12 -0
  36. package/dest/l1/types.d.ts.map +1 -0
  37. package/dest/{archiver/l1 → l1}/validate_trace.d.ts +6 -3
  38. package/dest/l1/validate_trace.d.ts.map +1 -0
  39. package/dest/{archiver/l1 → l1}/validate_trace.js +14 -10
  40. package/dest/modules/data_source_base.d.ts +89 -0
  41. package/dest/modules/data_source_base.d.ts.map +1 -0
  42. package/dest/modules/data_source_base.js +216 -0
  43. package/dest/modules/data_store_updater.d.ts +80 -0
  44. package/dest/modules/data_store_updater.d.ts.map +1 -0
  45. package/dest/modules/data_store_updater.js +323 -0
  46. package/dest/modules/instrumentation.d.ts +39 -0
  47. package/dest/modules/instrumentation.d.ts.map +1 -0
  48. package/dest/{archiver → modules}/instrumentation.js +33 -67
  49. package/dest/modules/l1_synchronizer.d.ts +76 -0
  50. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  51. package/dest/modules/l1_synchronizer.js +1112 -0
  52. package/dest/modules/validation.d.ts +17 -0
  53. package/dest/modules/validation.d.ts.map +1 -0
  54. package/dest/{archiver → modules}/validation.js +7 -1
  55. package/dest/store/block_store.d.ts +196 -0
  56. package/dest/store/block_store.d.ts.map +1 -0
  57. package/dest/{archiver/kv_archiver_store → store}/block_store.js +228 -62
  58. package/dest/store/contract_class_store.d.ts +18 -0
  59. package/dest/store/contract_class_store.d.ts.map +1 -0
  60. package/dest/{archiver/kv_archiver_store → store}/contract_class_store.js +12 -8
  61. package/dest/store/contract_instance_store.d.ts +24 -0
  62. package/dest/store/contract_instance_store.d.ts.map +1 -0
  63. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +1 -1
  64. package/dest/store/kv_archiver_store.d.ts +354 -0
  65. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  66. package/dest/store/kv_archiver_store.js +464 -0
  67. package/dest/store/l2_tips_cache.d.ts +19 -0
  68. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  69. package/dest/store/l2_tips_cache.js +89 -0
  70. package/dest/store/log_store.d.ts +54 -0
  71. package/dest/store/log_store.d.ts.map +1 -0
  72. package/dest/{archiver/kv_archiver_store → store}/log_store.js +146 -91
  73. package/dest/{archiver/kv_archiver_store → store}/message_store.d.ts +1 -1
  74. package/dest/store/message_store.d.ts.map +1 -0
  75. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  76. package/dest/structs/data_retrieval.d.ts.map +1 -0
  77. package/dest/structs/inbox_message.d.ts +15 -0
  78. package/dest/structs/inbox_message.d.ts.map +1 -0
  79. package/dest/{archiver/structs → structs}/published.d.ts +1 -1
  80. package/dest/structs/published.d.ts.map +1 -0
  81. package/dest/test/fake_l1_state.d.ts +193 -0
  82. package/dest/test/fake_l1_state.d.ts.map +1 -0
  83. package/dest/test/fake_l1_state.js +389 -0
  84. package/dest/test/index.d.ts +2 -1
  85. package/dest/test/index.d.ts.map +1 -1
  86. package/dest/test/index.js +4 -1
  87. package/dest/test/mock_archiver.d.ts +2 -2
  88. package/dest/test/mock_archiver.d.ts.map +1 -1
  89. package/dest/test/mock_archiver.js +3 -3
  90. package/dest/test/mock_l1_to_l2_message_source.d.ts +2 -2
  91. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  92. package/dest/test/mock_l1_to_l2_message_source.js +12 -3
  93. package/dest/test/mock_l2_block_source.d.ts +39 -17
  94. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  95. package/dest/test/mock_l2_block_source.js +232 -83
  96. package/dest/test/mock_structs.d.ts +78 -3
  97. package/dest/test/mock_structs.d.ts.map +1 -1
  98. package/dest/test/mock_structs.js +140 -7
  99. package/dest/test/noop_l1_archiver.d.ts +23 -0
  100. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  101. package/dest/test/noop_l1_archiver.js +68 -0
  102. package/package.json +16 -17
  103. package/src/archiver.ts +443 -0
  104. package/src/{archiver/config.ts → config.ts} +13 -2
  105. package/src/{archiver/errors.ts → errors.ts} +12 -0
  106. package/src/factory.ts +140 -11
  107. package/src/index.ts +11 -3
  108. package/src/interfaces.ts +9 -0
  109. package/src/{archiver/l1 → l1}/bin/retrieve-calldata.ts +16 -17
  110. package/src/{archiver/l1 → l1}/calldata_retriever.ts +28 -6
  111. package/src/{archiver/l1 → l1}/data_retrieval.ts +60 -74
  112. package/src/{archiver/l1 → l1}/validate_trace.ts +25 -7
  113. package/src/modules/data_source_base.ts +328 -0
  114. package/src/modules/data_store_updater.ts +448 -0
  115. package/src/{archiver → modules}/instrumentation.ts +33 -70
  116. package/src/modules/l1_synchronizer.ts +932 -0
  117. package/src/{archiver → modules}/validation.ts +11 -6
  118. package/src/{archiver/kv_archiver_store → store}/block_store.ts +293 -100
  119. package/src/{archiver/kv_archiver_store → store}/contract_class_store.ts +12 -8
  120. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +1 -1
  121. package/src/{archiver/kv_archiver_store → store}/kv_archiver_store.ts +273 -40
  122. package/src/store/l2_tips_cache.ts +89 -0
  123. package/src/{archiver/kv_archiver_store → store}/log_store.ts +242 -121
  124. package/src/test/fake_l1_state.ts +607 -0
  125. package/src/test/index.ts +4 -0
  126. package/src/test/mock_archiver.ts +4 -3
  127. package/src/test/mock_l1_to_l2_message_source.ts +10 -4
  128. package/src/test/mock_l2_block_source.ts +276 -90
  129. package/src/test/mock_structs.ts +269 -8
  130. package/src/test/noop_l1_archiver.ts +109 -0
  131. package/dest/archiver/archiver.d.ts +0 -304
  132. package/dest/archiver/archiver.d.ts.map +0 -1
  133. package/dest/archiver/archiver.js +0 -1645
  134. package/dest/archiver/archiver_store.d.ts +0 -308
  135. package/dest/archiver/archiver_store.d.ts.map +0 -1
  136. package/dest/archiver/archiver_store.js +0 -4
  137. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  138. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  139. package/dest/archiver/archiver_store_test_suite.js +0 -2770
  140. package/dest/archiver/config.d.ts.map +0 -1
  141. package/dest/archiver/errors.d.ts +0 -36
  142. package/dest/archiver/errors.d.ts.map +0 -1
  143. package/dest/archiver/index.d.ts +0 -7
  144. package/dest/archiver/index.d.ts.map +0 -1
  145. package/dest/archiver/index.js +0 -4
  146. package/dest/archiver/instrumentation.d.ts +0 -37
  147. package/dest/archiver/instrumentation.d.ts.map +0 -1
  148. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -157
  149. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  150. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  151. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  152. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  153. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  154. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -158
  155. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  156. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -313
  157. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -45
  158. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  159. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  160. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +0 -1
  161. package/dest/archiver/l1/calldata_retriever.d.ts.map +0 -1
  162. package/dest/archiver/l1/data_retrieval.d.ts +0 -90
  163. package/dest/archiver/l1/data_retrieval.d.ts.map +0 -1
  164. package/dest/archiver/l1/debug_tx.d.ts.map +0 -1
  165. package/dest/archiver/l1/spire_proposer.d.ts.map +0 -1
  166. package/dest/archiver/l1/trace_tx.d.ts.map +0 -1
  167. package/dest/archiver/l1/types.d.ts +0 -12
  168. package/dest/archiver/l1/types.d.ts.map +0 -1
  169. package/dest/archiver/l1/validate_trace.d.ts.map +0 -1
  170. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  171. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  172. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  173. package/dest/archiver/structs/published.d.ts.map +0 -1
  174. package/dest/archiver/validation.d.ts +0 -17
  175. package/dest/archiver/validation.d.ts.map +0 -1
  176. package/dest/rpc/index.d.ts +0 -9
  177. package/dest/rpc/index.d.ts.map +0 -1
  178. package/dest/rpc/index.js +0 -15
  179. package/src/archiver/archiver.ts +0 -2157
  180. package/src/archiver/archiver_store.ts +0 -372
  181. package/src/archiver/archiver_store_test_suite.ts +0 -2843
  182. package/src/archiver/index.ts +0 -6
  183. package/src/rpc/index.ts +0 -16
  184. /package/dest/{archiver/l1 → l1}/debug_tx.js +0 -0
  185. /package/dest/{archiver/l1 → l1}/spire_proposer.js +0 -0
  186. /package/dest/{archiver/l1 → l1}/trace_tx.js +0 -0
  187. /package/dest/{archiver/l1 → l1}/types.js +0 -0
  188. /package/dest/{archiver/kv_archiver_store → store}/message_store.js +0 -0
  189. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  190. /package/dest/{archiver/structs → structs}/inbox_message.js +0 -0
  191. /package/dest/{archiver/structs → structs}/published.js +0 -0
  192. /package/src/{archiver/l1 → l1}/README.md +0 -0
  193. /package/src/{archiver/l1 → l1}/debug_tx.ts +0 -0
  194. /package/src/{archiver/l1 → l1}/spire_proposer.ts +0 -0
  195. /package/src/{archiver/l1 → l1}/trace_tx.ts +0 -0
  196. /package/src/{archiver/l1 → l1}/types.ts +0 -0
  197. /package/src/{archiver/kv_archiver_store → store}/message_store.ts +0 -0
  198. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
  199. /package/src/{archiver/structs → structs}/inbox_message.ts +0 -0
  200. /package/src/{archiver/structs → structs}/published.ts +0 -0
@@ -0,0 +1,448 @@
1
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+ import {
5
+ ContractClassPublishedEvent,
6
+ PrivateFunctionBroadcastedEvent,
7
+ UtilityFunctionBroadcastedEvent,
8
+ } from '@aztec/protocol-contracts/class-registry';
9
+ import {
10
+ ContractInstancePublishedEvent,
11
+ ContractInstanceUpdatedEvent,
12
+ } from '@aztec/protocol-contracts/instance-registry';
13
+ import type { L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
14
+ import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
15
+ import {
16
+ type ExecutablePrivateFunctionWithMembershipProof,
17
+ type UtilityFunctionWithMembershipProof,
18
+ computePublicBytecodeCommitment,
19
+ isValidPrivateFunctionMembershipProof,
20
+ isValidUtilityFunctionMembershipProof,
21
+ } from '@aztec/stdlib/contract';
22
+ import type { ContractClassLog, PrivateLog, PublicLog } from '@aztec/stdlib/logs';
23
+ import type { UInt64 } from '@aztec/stdlib/types';
24
+
25
+ import groupBy from 'lodash.groupby';
26
+
27
+ import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
28
+ import type { L2TipsCache } from '../store/l2_tips_cache.js';
29
+
30
+ /** Operation type for contract data updates. */
31
+ enum Operation {
32
+ Store,
33
+ Delete,
34
+ }
35
+
36
+ /** Result of adding checkpoints with information about any pruned blocks. */
37
+ type ReconcileCheckpointsResult = {
38
+ /** Blocks that were pruned due to conflict with L1 checkpoints. */
39
+ prunedBlocks: L2Block[] | undefined;
40
+ /** Last block number that was already inserted locally, or undefined if none. */
41
+ lastAlreadyInsertedBlockNumber: BlockNumber | undefined;
42
+ };
43
+
44
+ /** Archiver helper module to handle updates to the data store. */
45
+ export class ArchiverDataStoreUpdater {
46
+ private readonly log = createLogger('archiver:store_updater');
47
+
48
+ constructor(
49
+ private store: KVArchiverDataStore,
50
+ private l2TipsCache?: L2TipsCache,
51
+ ) {}
52
+
53
+ /**
54
+ * Adds proposed blocks to the store with contract class/instance extraction from logs.
55
+ * These are uncheckpointed blocks that have been proposed by the sequencer but not yet included in a checkpoint on L1.
56
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
57
+ * and individually broadcasted functions from the block logs.
58
+ *
59
+ * @param blocks - The proposed L2 blocks to add.
60
+ * @param pendingChainValidationStatus - Optional validation status to set.
61
+ * @returns True if the operation is successful.
62
+ */
63
+ public async addProposedBlocks(
64
+ blocks: L2Block[],
65
+ pendingChainValidationStatus?: ValidateCheckpointResult,
66
+ ): Promise<boolean> {
67
+ const result = await this.store.transactionAsync(async () => {
68
+ await this.store.addProposedBlocks(blocks);
69
+
70
+ const opResults = await Promise.all([
71
+ // Update the pending chain validation status if provided
72
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
73
+ // Add any logs emitted during the retrieved blocks
74
+ this.store.addLogs(blocks),
75
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
76
+ ...blocks.map(block => this.addContractDataToDb(block)),
77
+ ]);
78
+
79
+ await this.l2TipsCache?.refresh();
80
+ return opResults.every(Boolean);
81
+ });
82
+ return result;
83
+ }
84
+
85
+ /**
86
+ * Reconciles local blocks with incoming checkpoints from L1.
87
+ * Adds new checkpoints to the store with contract class/instance extraction from logs.
88
+ * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
89
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
90
+ * and individually broadcasted functions from the checkpoint block logs.
91
+ *
92
+ * @param checkpoints - The published checkpoints to add.
93
+ * @param pendingChainValidationStatus - Optional validation status to set.
94
+ * @returns Result with information about any pruned blocks.
95
+ */
96
+ public async addCheckpoints(
97
+ checkpoints: PublishedCheckpoint[],
98
+ pendingChainValidationStatus?: ValidateCheckpointResult,
99
+ ): Promise<ReconcileCheckpointsResult> {
100
+ const result = await this.store.transactionAsync(async () => {
101
+ // Before adding checkpoints, check for conflicts with local blocks if any
102
+ const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
103
+
104
+ await this.store.addCheckpoints(checkpoints);
105
+
106
+ // Filter out blocks that were already inserted via addProposedBlocks() to avoid duplicating logs/contract data
107
+ const newBlocks = checkpoints
108
+ .flatMap((ch: PublishedCheckpoint) => ch.checkpoint.blocks)
109
+ .filter(b => lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
110
+
111
+ await Promise.all([
112
+ // Update the pending chain validation status if provided
113
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
114
+ // Add any logs emitted during the retrieved blocks
115
+ this.store.addLogs(newBlocks),
116
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
117
+ ...newBlocks.map(block => this.addContractDataToDb(block)),
118
+ ]);
119
+
120
+ await this.l2TipsCache?.refresh();
121
+ return { prunedBlocks, lastAlreadyInsertedBlockNumber };
122
+ });
123
+ return result;
124
+ }
125
+
126
+ /**
127
+ * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
128
+ * This method handles multiple checkpoints but returns after pruning the first conflict found.
129
+ * This is correct because pruning from the first conflict point removes all subsequent blocks,
130
+ * and when checkpoints are added afterward, they include all the correct blocks.
131
+ */
132
+ private async pruneMismatchingLocalBlocks(checkpoints: PublishedCheckpoint[]): Promise<ReconcileCheckpointsResult> {
133
+ const [lastCheckpointedBlockNumber, lastBlockNumber] = await Promise.all([
134
+ this.store.getCheckpointedL2BlockNumber(),
135
+ this.store.getLatestBlockNumber(),
136
+ ]);
137
+
138
+ // Exit early if there are no local uncheckpointed blocks
139
+ if (lastBlockNumber === lastCheckpointedBlockNumber) {
140
+ return { prunedBlocks: undefined, lastAlreadyInsertedBlockNumber: undefined };
141
+ }
142
+
143
+ // Get all uncheckpointed local blocks
144
+ const uncheckpointedLocalBlocks = await this.store.getBlocks(
145
+ BlockNumber.add(lastCheckpointedBlockNumber, 1),
146
+ lastBlockNumber - lastCheckpointedBlockNumber,
147
+ );
148
+
149
+ let lastAlreadyInsertedBlockNumber: BlockNumber | undefined;
150
+
151
+ for (const publishedCheckpoint of checkpoints) {
152
+ const checkpointBlocks = publishedCheckpoint.checkpoint.blocks;
153
+ const slot = publishedCheckpoint.checkpoint.slot;
154
+ const localBlocksInSlot = uncheckpointedLocalBlocks.filter(b => b.slot === slot);
155
+
156
+ if (checkpointBlocks.length === 0) {
157
+ this.log.warn(`Checkpoint ${publishedCheckpoint.checkpoint.number} for slot ${slot} has no blocks`);
158
+ continue;
159
+ }
160
+
161
+ // Find the first checkpoint block that conflicts with an existing local block and prune local afterwards
162
+ for (const checkpointBlock of checkpointBlocks) {
163
+ const blockNumber = checkpointBlock.number;
164
+ const existingBlock = localBlocksInSlot.find(b => b.number === blockNumber);
165
+ const blockInfos = {
166
+ existingBlock: existingBlock?.toBlockInfo(),
167
+ checkpointBlock: checkpointBlock.toBlockInfo(),
168
+ };
169
+
170
+ if (!existingBlock) {
171
+ this.log.verbose(`No local block found for checkpointed block number ${blockNumber}`, blockInfos);
172
+ } else if (existingBlock.archive.root.equals(checkpointBlock.archive.root)) {
173
+ this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
174
+ lastAlreadyInsertedBlockNumber = blockNumber;
175
+ } else {
176
+ this.log.warn(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
177
+ const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
178
+ return { prunedBlocks, lastAlreadyInsertedBlockNumber };
179
+ }
180
+ }
181
+
182
+ // If local has more blocks than the checkpoint (e.g., local has [2,3,4] but checkpoint has [2,3]),
183
+ // we need to prune the extra local blocks so they match what was checkpointed
184
+ const lastCheckpointBlockNumber = checkpointBlocks.at(-1)!.number;
185
+ const lastLocalBlockNumber = localBlocksInSlot.at(-1)?.number;
186
+
187
+ if (lastLocalBlockNumber !== undefined && lastLocalBlockNumber > lastCheckpointBlockNumber) {
188
+ this.log.warn(
189
+ `Local chain for slot ${slot} ends at block ${lastLocalBlockNumber} but checkpoint ends at ${lastCheckpointBlockNumber}. Pruning blocks after block ${lastCheckpointBlockNumber}.`,
190
+ );
191
+ const prunedBlocks = await this.removeBlocksAfter(lastCheckpointBlockNumber);
192
+ return { prunedBlocks, lastAlreadyInsertedBlockNumber };
193
+ }
194
+ }
195
+
196
+ return { prunedBlocks: undefined, lastAlreadyInsertedBlockNumber };
197
+ }
198
+
199
+ /**
200
+ * Removes all uncheckpointed blocks strictly after the specified block number and cleans up associated contract data.
201
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
202
+ * Verifies that each block being removed is not part of a stored checkpoint.
203
+ *
204
+ * @param blockNumber - Remove all blocks with number greater than this.
205
+ * @returns The removed blocks.
206
+ * @throws Error if any block to be removed is checkpointed.
207
+ */
208
+ public async removeUncheckpointedBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
209
+ const result = await this.store.transactionAsync(async () => {
210
+ // Verify we're only removing uncheckpointed blocks
211
+ const lastCheckpointedBlockNumber = await this.store.getCheckpointedL2BlockNumber();
212
+ if (blockNumber < lastCheckpointedBlockNumber) {
213
+ throw new Error(
214
+ `Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`,
215
+ );
216
+ }
217
+
218
+ const result = await this.removeBlocksAfter(blockNumber);
219
+ await this.l2TipsCache?.refresh();
220
+ return result;
221
+ });
222
+ return result;
223
+ }
224
+
225
+ /**
226
+ * Removes all blocks strictly after the given block number along with any logs and contract data.
227
+ * Does not remove their checkpoints.
228
+ */
229
+ private async removeBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
230
+ // First get the blocks to be removed so we can clean up contract data
231
+ const removedBlocks = await this.store.removeBlocksAfter(blockNumber);
232
+
233
+ // Clean up contract data and logs for the removed blocks
234
+ await Promise.all([
235
+ this.store.deleteLogs(removedBlocks),
236
+ ...removedBlocks.map(block => this.removeContractDataFromDb(block)),
237
+ ]);
238
+
239
+ return removedBlocks;
240
+ }
241
+
242
+ /**
243
+ * Removes all checkpoints after the given checkpoint number.
244
+ * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
245
+ * that was stored for the removed checkpoints. Also removes ALL blocks (both checkpointed
246
+ * and uncheckpointed) after the last block of the given checkpoint.
247
+ *
248
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
249
+ * @returns True if the operation is successful.
250
+ */
251
+ public async removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
252
+ return await this.store.transactionAsync(async () => {
253
+ const { blocksRemoved = [] } = await this.store.removeCheckpointsAfter(checkpointNumber);
254
+
255
+ const opResults = await Promise.all([
256
+ // Prune rolls back to the last proven block, which is by definition valid
257
+ this.store.setPendingChainValidationStatus({ valid: true }),
258
+ // Remove contract data for all blocks being removed
259
+ ...blocksRemoved.map(block => this.removeContractDataFromDb(block)),
260
+ this.store.deleteLogs(blocksRemoved),
261
+ ]);
262
+
263
+ await this.l2TipsCache?.refresh();
264
+ return opResults.every(Boolean);
265
+ });
266
+ }
267
+
268
+ /**
269
+ * Updates the proven checkpoint number and refreshes the L2 tips cache.
270
+ * @param checkpointNumber - The checkpoint number to set as proven.
271
+ */
272
+ public async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
273
+ await this.store.transactionAsync(async () => {
274
+ await this.store.setProvenCheckpointNumber(checkpointNumber);
275
+ await this.l2TipsCache?.refresh();
276
+ });
277
+ }
278
+
279
+ /** Extracts and stores contract data from a single block. */
280
+ private addContractDataToDb(block: L2Block): Promise<boolean> {
281
+ return this.updateContractDataOnDb(block, Operation.Store);
282
+ }
283
+
284
+ /** Removes contract data associated with a block. */
285
+ private removeContractDataFromDb(block: L2Block): Promise<boolean> {
286
+ return this.updateContractDataOnDb(block, Operation.Delete);
287
+ }
288
+
289
+ /** Adds or remove contract data associated with a block. */
290
+ private async updateContractDataOnDb(block: L2Block, operation: Operation): Promise<boolean> {
291
+ const contractClassLogs = block.body.txEffects.flatMap(txEffect => txEffect.contractClassLogs);
292
+ const privateLogs = block.body.txEffects.flatMap(txEffect => txEffect.privateLogs);
293
+ const publicLogs = block.body.txEffects.flatMap(txEffect => txEffect.publicLogs);
294
+
295
+ return (
296
+ await Promise.all([
297
+ this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
298
+ this.updateDeployedContractInstances(privateLogs, block.number, operation),
299
+ this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
300
+ operation === Operation.Store
301
+ ? this.storeBroadcastedIndividualFunctions(contractClassLogs, block.number)
302
+ : Promise.resolve(true),
303
+ ])
304
+ ).every(Boolean);
305
+ }
306
+
307
+ /**
308
+ * Extracts and stores contract classes out of ContractClassPublished events emitted by the class registry contract.
309
+ */
310
+ private async updatePublishedContractClasses(
311
+ allLogs: ContractClassLog[],
312
+ blockNum: BlockNumber,
313
+ operation: Operation,
314
+ ): Promise<boolean> {
315
+ const contractClassPublishedEvents = allLogs
316
+ .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
317
+ .map(log => ContractClassPublishedEvent.fromLog(log));
318
+
319
+ const contractClasses = await Promise.all(contractClassPublishedEvents.map(e => e.toContractClassPublic()));
320
+ if (contractClasses.length > 0) {
321
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
322
+ if (operation == Operation.Store) {
323
+ // TODO: Will probably want to create some worker threads to compute these bytecode commitments as they are expensive
324
+ const commitments = await Promise.all(
325
+ contractClasses.map(c => computePublicBytecodeCommitment(c.packedBytecode)),
326
+ );
327
+ return await this.store.addContractClasses(contractClasses, commitments, blockNum);
328
+ } else if (operation == Operation.Delete) {
329
+ return await this.store.deleteContractClasses(contractClasses, blockNum);
330
+ }
331
+ }
332
+ return true;
333
+ }
334
+
335
+ /**
336
+ * Extracts and stores contract instances out of ContractInstancePublished events emitted by the canonical deployer contract.
337
+ */
338
+ private async updateDeployedContractInstances(
339
+ allLogs: PrivateLog[],
340
+ blockNum: BlockNumber,
341
+ operation: Operation,
342
+ ): Promise<boolean> {
343
+ const contractInstances = allLogs
344
+ .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
345
+ .map(log => ContractInstancePublishedEvent.fromLog(log))
346
+ .map(e => e.toContractInstance());
347
+ if (contractInstances.length > 0) {
348
+ contractInstances.forEach(c =>
349
+ this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`),
350
+ );
351
+ if (operation == Operation.Store) {
352
+ return await this.store.addContractInstances(contractInstances, blockNum);
353
+ } else if (operation == Operation.Delete) {
354
+ return await this.store.deleteContractInstances(contractInstances, blockNum);
355
+ }
356
+ }
357
+ return true;
358
+ }
359
+
360
+ /**
361
+ * Extracts and stores contract instance updates out of ContractInstanceUpdated events.
362
+ */
363
+ private async updateUpdatedContractInstances(
364
+ allLogs: PublicLog[],
365
+ timestamp: UInt64,
366
+ operation: Operation,
367
+ ): Promise<boolean> {
368
+ const contractUpdates = allLogs
369
+ .filter(log => ContractInstanceUpdatedEvent.isContractInstanceUpdatedEvent(log))
370
+ .map(log => ContractInstanceUpdatedEvent.fromLog(log))
371
+ .map(e => e.toContractInstanceUpdate());
372
+
373
+ if (contractUpdates.length > 0) {
374
+ contractUpdates.forEach(c =>
375
+ this.log.verbose(`${Operation[operation]} contract instance update at ${c.address.toString()}`),
376
+ );
377
+ if (operation == Operation.Store) {
378
+ return await this.store.addContractInstanceUpdates(contractUpdates, timestamp);
379
+ } else if (operation == Operation.Delete) {
380
+ return await this.store.deleteContractInstanceUpdates(contractUpdates, timestamp);
381
+ }
382
+ }
383
+ return true;
384
+ }
385
+
386
+ /**
387
+ * Stores the functions that were broadcasted individually.
388
+ *
389
+ * @dev Beware that there is not a delete variant of this, since they are added to contract classes
390
+ * and will be deleted as part of the class if needed.
391
+ */
392
+ private async storeBroadcastedIndividualFunctions(
393
+ allLogs: ContractClassLog[],
394
+ _blockNum: BlockNumber,
395
+ ): Promise<boolean> {
396
+ // Filter out private and utility function broadcast events
397
+ const privateFnEvents = allLogs
398
+ .filter(log => PrivateFunctionBroadcastedEvent.isPrivateFunctionBroadcastedEvent(log))
399
+ .map(log => PrivateFunctionBroadcastedEvent.fromLog(log));
400
+ const utilityFnEvents = allLogs
401
+ .filter(log => UtilityFunctionBroadcastedEvent.isUtilityFunctionBroadcastedEvent(log))
402
+ .map(log => UtilityFunctionBroadcastedEvent.fromLog(log));
403
+
404
+ // Group all events by contract class id
405
+ for (const [classIdString, classEvents] of Object.entries(
406
+ groupBy([...privateFnEvents, ...utilityFnEvents], e => e.contractClassId.toString()),
407
+ )) {
408
+ const contractClassId = Fr.fromHexString(classIdString);
409
+ const contractClass = await this.store.getContractClass(contractClassId);
410
+ if (!contractClass) {
411
+ this.log.warn(`Skipping broadcasted functions as contract class ${contractClassId.toString()} was not found`);
412
+ continue;
413
+ }
414
+
415
+ // Split private and utility functions, and filter out invalid ones
416
+ const allFns = classEvents.map(e => e.toFunctionWithMembershipProof());
417
+ const privateFns = allFns.filter(
418
+ (fn): fn is ExecutablePrivateFunctionWithMembershipProof => 'utilityFunctionsTreeRoot' in fn,
419
+ );
420
+ const utilityFns = allFns.filter(
421
+ (fn): fn is UtilityFunctionWithMembershipProof => 'privateFunctionsArtifactTreeRoot' in fn,
422
+ );
423
+
424
+ const privateFunctionsWithValidity = await Promise.all(
425
+ privateFns.map(async fn => ({ fn, valid: await isValidPrivateFunctionMembershipProof(fn, contractClass) })),
426
+ );
427
+ const validPrivateFns = privateFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
428
+ const utilityFunctionsWithValidity = await Promise.all(
429
+ utilityFns.map(async fn => ({
430
+ fn,
431
+ valid: await isValidUtilityFunctionMembershipProof(fn, contractClass),
432
+ })),
433
+ );
434
+ const validUtilityFns = utilityFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
435
+ const validFnCount = validPrivateFns.length + validUtilityFns.length;
436
+ if (validFnCount !== allFns.length) {
437
+ this.log.warn(`Skipping ${allFns.length - validFnCount} invalid functions`);
438
+ }
439
+
440
+ // Store the functions in the contract class in a single operation
441
+ if (validFnCount > 0) {
442
+ this.log.verbose(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`);
443
+ }
444
+ return await this.store.addFunctions(contractClassId, validPrivateFns, validUtilityFns);
445
+ }
446
+ return true;
447
+ }
448
+ }
@@ -1,5 +1,6 @@
1
1
  import { createLogger } from '@aztec/foundation/log';
2
- import type { L2BlockNew } from '@aztec/stdlib/block';
2
+ import type { L2Block } from '@aztec/stdlib/block';
3
+ import type { CheckpointData } from '@aztec/stdlib/checkpoint';
3
4
  import {
4
5
  Attributes,
5
6
  type Gauge,
@@ -10,13 +11,14 @@ import {
10
11
  type TelemetryClient,
11
12
  type Tracer,
12
13
  type UpDownCounter,
13
- ValueType,
14
+ createUpDownCounterWithDefault,
14
15
  } from '@aztec/telemetry-client';
15
16
 
16
17
  export class ArchiverInstrumentation {
17
18
  public readonly tracer: Tracer;
18
19
 
19
20
  private blockHeight: Gauge;
21
+ private checkpointHeight: Gauge;
20
22
  private txCount: UpDownCounter;
21
23
  private l1BlockHeight: Gauge;
22
24
  private proofsSubmittedDelay: Histogram;
@@ -45,81 +47,43 @@ export class ArchiverInstrumentation {
45
47
  this.tracer = telemetry.getTracer('Archiver');
46
48
  const meter = telemetry.getMeter('Archiver');
47
49
 
48
- this.blockHeight = meter.createGauge(Metrics.ARCHIVER_BLOCK_HEIGHT, {
49
- description: 'The height of the latest block processed by the archiver',
50
- valueType: ValueType.INT,
51
- });
50
+ this.blockHeight = meter.createGauge(Metrics.ARCHIVER_BLOCK_HEIGHT);
52
51
 
53
- this.l1BlockHeight = meter.createGauge(Metrics.ARCHIVER_L1_BLOCK_HEIGHT, {
54
- description: 'The height of the latest L1 block processed by the archiver',
55
- valueType: ValueType.INT,
56
- });
52
+ this.checkpointHeight = meter.createGauge(Metrics.ARCHIVER_CHECKPOINT_HEIGHT);
57
53
 
58
- this.txCount = meter.createUpDownCounter(Metrics.ARCHIVER_TOTAL_TXS, {
59
- description: 'The total number of transactions',
60
- valueType: ValueType.INT,
61
- });
54
+ this.l1BlockHeight = meter.createGauge(Metrics.ARCHIVER_L1_BLOCK_HEIGHT);
62
55
 
63
- this.proofsSubmittedCount = meter.createUpDownCounter(Metrics.ARCHIVER_ROLLUP_PROOF_COUNT, {
64
- description: 'Number of proofs submitted',
65
- valueType: ValueType.INT,
66
- });
56
+ this.txCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_TOTAL_TXS);
67
57
 
68
- this.proofsSubmittedDelay = meter.createHistogram(Metrics.ARCHIVER_ROLLUP_PROOF_DELAY, {
69
- unit: 'ms',
70
- description: 'Time after a block is submitted until its proof is published',
71
- valueType: ValueType.INT,
58
+ this.proofsSubmittedCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_ROLLUP_PROOF_COUNT, {
59
+ [Attributes.PROOF_TIMED_OUT]: [true, false],
72
60
  });
73
61
 
74
- this.syncDurationPerBlock = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_BLOCK, {
75
- unit: 'ms',
76
- description: 'Duration to sync a block',
77
- valueType: ValueType.INT,
78
- });
62
+ this.proofsSubmittedDelay = meter.createHistogram(Metrics.ARCHIVER_ROLLUP_PROOF_DELAY);
79
63
 
80
- this.syncBlockCount = meter.createUpDownCounter(Metrics.ARCHIVER_SYNC_BLOCK_COUNT, {
81
- description: 'Number of blocks synced from L1',
82
- valueType: ValueType.INT,
83
- });
64
+ this.syncDurationPerBlock = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_BLOCK);
84
65
 
85
- this.manaPerBlock = meter.createHistogram(Metrics.ARCHIVER_MANA_PER_BLOCK, {
86
- description: 'The mana consumed by blocks',
87
- valueType: ValueType.DOUBLE,
88
- unit: 'Mmana',
89
- });
66
+ this.syncBlockCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_BLOCK_COUNT);
90
67
 
91
- this.txsPerBlock = meter.createHistogram(Metrics.ARCHIVER_TXS_PER_BLOCK, {
92
- description: 'The block tx count',
93
- valueType: ValueType.INT,
94
- unit: 'tx',
95
- });
68
+ this.manaPerBlock = meter.createHistogram(Metrics.ARCHIVER_MANA_PER_BLOCK);
96
69
 
97
- this.syncDurationPerMessage = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_MESSAGE, {
98
- unit: 'ms',
99
- description: 'Duration to sync a message',
100
- valueType: ValueType.INT,
101
- });
70
+ this.txsPerBlock = meter.createHistogram(Metrics.ARCHIVER_TXS_PER_BLOCK);
102
71
 
103
- this.syncMessageCount = meter.createUpDownCounter(Metrics.ARCHIVER_SYNC_MESSAGE_COUNT, {
104
- description: 'Number of L1 to L2 messages synced',
105
- valueType: ValueType.INT,
106
- });
72
+ this.syncDurationPerMessage = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_MESSAGE);
107
73
 
108
- this.pruneDuration = meter.createHistogram(Metrics.ARCHIVER_PRUNE_DURATION, {
109
- unit: 'ms',
110
- description: 'Duration to sync a message',
111
- valueType: ValueType.INT,
112
- });
74
+ this.syncMessageCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_MESSAGE_COUNT);
113
75
 
114
- this.pruneCount = meter.createUpDownCounter(Metrics.ARCHIVER_PRUNE_COUNT, {
115
- description: 'Number of prunes detected',
116
- valueType: ValueType.INT,
117
- });
76
+ this.pruneDuration = meter.createHistogram(Metrics.ARCHIVER_PRUNE_DURATION);
118
77
 
119
- this.blockProposalTxTargetCount = meter.createUpDownCounter(Metrics.ARCHIVER_BLOCK_PROPOSAL_TX_TARGET_COUNT, {
120
- description: 'Number of block proposals by tx target',
121
- valueType: ValueType.INT,
122
- });
78
+ this.pruneCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_PRUNE_COUNT);
79
+
80
+ this.blockProposalTxTargetCount = createUpDownCounterWithDefault(
81
+ meter,
82
+ Metrics.ARCHIVER_BLOCK_PROPOSAL_TX_TARGET_COUNT,
83
+ {
84
+ [Attributes.L1_BLOCK_PROPOSAL_USED_TRACE]: [true, false],
85
+ },
86
+ );
123
87
 
124
88
  this.dbMetrics = new LmdbMetrics(
125
89
  meter,
@@ -133,10 +97,6 @@ export class ArchiverInstrumentation {
133
97
  public static async new(telemetry: TelemetryClient, lmdbStats?: LmdbStatsCallback) {
134
98
  const instance = new ArchiverInstrumentation(telemetry, lmdbStats);
135
99
 
136
- instance.syncBlockCount.add(0);
137
- instance.syncMessageCount.add(0);
138
- instance.pruneCount.add(0);
139
-
140
100
  await instance.telemetry.flush();
141
101
 
142
102
  return instance;
@@ -146,9 +106,10 @@ export class ArchiverInstrumentation {
146
106
  return this.telemetry.isEnabled();
147
107
  }
148
108
 
149
- public processNewBlocks(syncTimePerBlock: number, blocks: L2BlockNew[]) {
109
+ public processNewBlocks(syncTimePerBlock: number, blocks: L2Block[]) {
150
110
  this.syncDurationPerBlock.record(Math.ceil(syncTimePerBlock));
151
111
  this.blockHeight.record(Math.max(...blocks.map(b => b.number)));
112
+ this.checkpointHeight.record(Math.max(...blocks.map(b => b.checkpointNumber)));
152
113
  this.syncBlockCount.add(blocks.length);
153
114
 
154
115
  for (const block of blocks) {
@@ -171,8 +132,10 @@ export class ArchiverInstrumentation {
171
132
  this.pruneDuration.record(Math.ceil(duration));
172
133
  }
173
134
 
174
- public updateLastProvenBlock(blockNumber: number) {
175
- this.blockHeight.record(blockNumber, { [Attributes.STATUS]: 'proven' });
135
+ public updateLastProvenCheckpoint(checkpoint: CheckpointData) {
136
+ const lastBlockNumberInCheckpoint = checkpoint.startBlock + checkpoint.blockCount - 1;
137
+ this.blockHeight.record(lastBlockNumberInCheckpoint, { [Attributes.STATUS]: 'proven' });
138
+ this.checkpointHeight.record(checkpoint.checkpointNumber, { [Attributes.STATUS]: 'proven' });
176
139
  }
177
140
 
178
141
  public processProofsVerified(logs: { proverId: string; l2BlockNumber: bigint; delay: bigint }[]) {