@aztec/archiver 0.0.1-commit.fce3e4f → 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 (209) 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/config.d.ts +30 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +21 -5
  8. package/dest/errors.d.ts +41 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +62 -0
  11. package/dest/factory.d.ts +9 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +97 -13
  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/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 +148 -0
  23. package/dest/l1/calldata_retriever.d.ts +118 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +484 -0
  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}/data_retrieval.js +80 -153
  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 +157 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_trace.d.ts +32 -0
  42. package/dest/l1/validate_trace.d.ts.map +1 -0
  43. package/dest/l1/validate_trace.js +154 -0
  44. package/dest/modules/data_source_base.d.ts +89 -0
  45. package/dest/modules/data_source_base.d.ts.map +1 -0
  46. package/dest/modules/data_source_base.js +216 -0
  47. package/dest/modules/data_store_updater.d.ts +80 -0
  48. package/dest/modules/data_store_updater.d.ts.map +1 -0
  49. package/dest/modules/data_store_updater.js +323 -0
  50. package/dest/modules/instrumentation.d.ts +39 -0
  51. package/dest/modules/instrumentation.d.ts.map +1 -0
  52. package/dest/{archiver → modules}/instrumentation.js +39 -62
  53. package/dest/modules/l1_synchronizer.d.ts +76 -0
  54. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  55. package/dest/modules/l1_synchronizer.js +1112 -0
  56. package/dest/modules/validation.d.ts +17 -0
  57. package/dest/modules/validation.d.ts.map +1 -0
  58. package/dest/{archiver → modules}/validation.js +7 -1
  59. package/dest/store/block_store.d.ts +196 -0
  60. package/dest/store/block_store.d.ts.map +1 -0
  61. package/dest/store/block_store.js +773 -0
  62. package/dest/store/contract_class_store.d.ts +18 -0
  63. package/dest/store/contract_class_store.d.ts.map +1 -0
  64. package/dest/{archiver/kv_archiver_store → store}/contract_class_store.js +13 -9
  65. package/dest/store/contract_instance_store.d.ts +24 -0
  66. package/dest/store/contract_instance_store.d.ts.map +1 -0
  67. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +1 -1
  68. package/dest/store/kv_archiver_store.d.ts +354 -0
  69. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  70. package/dest/store/kv_archiver_store.js +464 -0
  71. package/dest/store/l2_tips_cache.d.ts +19 -0
  72. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  73. package/dest/store/l2_tips_cache.js +89 -0
  74. package/dest/store/log_store.d.ts +54 -0
  75. package/dest/store/log_store.d.ts.map +1 -0
  76. package/dest/store/log_store.js +456 -0
  77. package/dest/store/message_store.d.ts +40 -0
  78. package/dest/store/message_store.d.ts.map +1 -0
  79. package/dest/{archiver/kv_archiver_store → store}/message_store.js +15 -14
  80. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  81. package/dest/structs/data_retrieval.d.ts.map +1 -0
  82. package/dest/structs/inbox_message.d.ts +15 -0
  83. package/dest/structs/inbox_message.d.ts.map +1 -0
  84. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  85. package/dest/structs/published.d.ts +2 -0
  86. package/dest/structs/published.d.ts.map +1 -0
  87. package/dest/test/fake_l1_state.d.ts +193 -0
  88. package/dest/test/fake_l1_state.d.ts.map +1 -0
  89. package/dest/test/fake_l1_state.js +389 -0
  90. package/dest/test/index.d.ts +2 -1
  91. package/dest/test/index.d.ts.map +1 -1
  92. package/dest/test/index.js +4 -1
  93. package/dest/test/mock_archiver.d.ts +16 -8
  94. package/dest/test/mock_archiver.d.ts.map +1 -1
  95. package/dest/test/mock_archiver.js +19 -14
  96. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  97. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  98. package/dest/test/mock_l1_to_l2_message_source.js +21 -11
  99. package/dest/test/mock_l2_block_source.d.ts +51 -18
  100. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  101. package/dest/test/mock_l2_block_source.js +245 -82
  102. package/dest/test/mock_structs.d.ts +80 -4
  103. package/dest/test/mock_structs.d.ts.map +1 -1
  104. package/dest/test/mock_structs.js +145 -11
  105. package/dest/test/noop_l1_archiver.d.ts +23 -0
  106. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  107. package/dest/test/noop_l1_archiver.js +68 -0
  108. package/package.json +20 -20
  109. package/src/archiver.ts +443 -0
  110. package/src/{archiver/config.ts → config.ts} +28 -12
  111. package/src/errors.ts +102 -0
  112. package/src/factory.ts +143 -13
  113. package/src/index.ts +11 -3
  114. package/src/interfaces.ts +9 -0
  115. package/src/l1/README.md +98 -0
  116. package/src/l1/bin/retrieve-calldata.ts +181 -0
  117. package/src/l1/calldata_retriever.ts +663 -0
  118. package/src/{archiver → l1}/data_retrieval.ts +146 -224
  119. package/src/l1/debug_tx.ts +99 -0
  120. package/src/l1/spire_proposer.ts +160 -0
  121. package/src/l1/trace_tx.ts +128 -0
  122. package/src/l1/types.ts +13 -0
  123. package/src/l1/validate_trace.ts +229 -0
  124. package/src/modules/data_source_base.ts +328 -0
  125. package/src/modules/data_store_updater.ts +448 -0
  126. package/src/{archiver → modules}/instrumentation.ts +43 -66
  127. package/src/modules/l1_synchronizer.ts +932 -0
  128. package/src/{archiver → modules}/validation.ts +11 -6
  129. package/src/store/block_store.ts +1015 -0
  130. package/src/{archiver/kv_archiver_store → store}/contract_class_store.ts +13 -9
  131. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +2 -2
  132. package/src/store/kv_archiver_store.ts +671 -0
  133. package/src/store/l2_tips_cache.ts +89 -0
  134. package/src/store/log_store.ts +637 -0
  135. package/src/{archiver/kv_archiver_store → store}/message_store.ts +21 -18
  136. package/src/{archiver/structs → structs}/inbox_message.ts +8 -8
  137. package/src/{archiver/structs → structs}/published.ts +0 -1
  138. package/src/test/fake_l1_state.ts +607 -0
  139. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  140. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  141. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  142. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  143. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  144. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  145. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  146. package/src/test/index.ts +4 -0
  147. package/src/test/mock_archiver.ts +23 -16
  148. package/src/test/mock_l1_to_l2_message_source.ts +18 -11
  149. package/src/test/mock_l2_block_source.ts +296 -90
  150. package/src/test/mock_structs.ts +275 -13
  151. package/src/test/noop_l1_archiver.ts +109 -0
  152. package/dest/archiver/archiver.d.ts +0 -287
  153. package/dest/archiver/archiver.d.ts.map +0 -1
  154. package/dest/archiver/archiver.js +0 -1408
  155. package/dest/archiver/archiver_store.d.ts +0 -255
  156. package/dest/archiver/archiver_store.d.ts.map +0 -1
  157. package/dest/archiver/archiver_store.js +0 -4
  158. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  159. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  160. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  161. package/dest/archiver/config.d.ts +0 -21
  162. package/dest/archiver/config.d.ts.map +0 -1
  163. package/dest/archiver/data_retrieval.d.ts +0 -79
  164. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  165. package/dest/archiver/errors.d.ts +0 -12
  166. package/dest/archiver/errors.d.ts.map +0 -1
  167. package/dest/archiver/errors.js +0 -17
  168. package/dest/archiver/index.d.ts +0 -7
  169. package/dest/archiver/index.d.ts.map +0 -1
  170. package/dest/archiver/index.js +0 -4
  171. package/dest/archiver/instrumentation.d.ts +0 -35
  172. package/dest/archiver/instrumentation.d.ts.map +0 -1
  173. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  174. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  175. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  176. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  177. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  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 -168
  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 -296
  183. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  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 -336
  186. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  187. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  188. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  189. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  190. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  191. package/dest/archiver/structs/published.d.ts +0 -3
  192. package/dest/archiver/structs/published.d.ts.map +0 -1
  193. package/dest/archiver/validation.d.ts +0 -17
  194. package/dest/archiver/validation.d.ts.map +0 -1
  195. package/dest/rpc/index.d.ts +0 -9
  196. package/dest/rpc/index.d.ts.map +0 -1
  197. package/dest/rpc/index.js +0 -15
  198. package/src/archiver/archiver.ts +0 -1858
  199. package/src/archiver/archiver_store.ts +0 -305
  200. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  201. package/src/archiver/errors.ts +0 -26
  202. package/src/archiver/index.ts +0 -6
  203. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  204. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  205. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  206. package/src/rpc/index.ts +0 -16
  207. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  208. /package/dest/{archiver/structs → structs}/published.js +0 -0
  209. /package/src/{archiver/structs → structs}/data_retrieval.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;
@@ -34,6 +36,8 @@ export class ArchiverInstrumentation {
34
36
  private syncDurationPerMessage: Histogram;
35
37
  private syncMessageCount: UpDownCounter;
36
38
 
39
+ private blockProposalTxTargetCount: UpDownCounter;
40
+
37
41
  private log = createLogger('archiver:instrumentation');
38
42
 
39
43
  private constructor(
@@ -43,76 +47,43 @@ export class ArchiverInstrumentation {
43
47
  this.tracer = telemetry.getTracer('Archiver');
44
48
  const meter = telemetry.getMeter('Archiver');
45
49
 
46
- this.blockHeight = meter.createGauge(Metrics.ARCHIVER_BLOCK_HEIGHT, {
47
- description: 'The height of the latest block processed by the archiver',
48
- valueType: ValueType.INT,
49
- });
50
+ this.blockHeight = meter.createGauge(Metrics.ARCHIVER_BLOCK_HEIGHT);
50
51
 
51
- this.l1BlockHeight = meter.createGauge(Metrics.ARCHIVER_L1_BLOCK_HEIGHT, {
52
- description: 'The height of the latest L1 block processed by the archiver',
53
- valueType: ValueType.INT,
54
- });
52
+ this.checkpointHeight = meter.createGauge(Metrics.ARCHIVER_CHECKPOINT_HEIGHT);
55
53
 
56
- this.txCount = meter.createUpDownCounter(Metrics.ARCHIVER_TOTAL_TXS, {
57
- description: 'The total number of transactions',
58
- valueType: ValueType.INT,
59
- });
54
+ this.l1BlockHeight = meter.createGauge(Metrics.ARCHIVER_L1_BLOCK_HEIGHT);
60
55
 
61
- this.proofsSubmittedCount = meter.createUpDownCounter(Metrics.ARCHIVER_ROLLUP_PROOF_COUNT, {
62
- description: 'Number of proofs submitted',
63
- valueType: ValueType.INT,
64
- });
56
+ this.txCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_TOTAL_TXS);
65
57
 
66
- this.proofsSubmittedDelay = meter.createHistogram(Metrics.ARCHIVER_ROLLUP_PROOF_DELAY, {
67
- unit: 'ms',
68
- description: 'Time after a block is submitted until its proof is published',
69
- valueType: ValueType.INT,
58
+ this.proofsSubmittedCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_ROLLUP_PROOF_COUNT, {
59
+ [Attributes.PROOF_TIMED_OUT]: [true, false],
70
60
  });
71
61
 
72
- this.syncDurationPerBlock = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_BLOCK, {
73
- unit: 'ms',
74
- description: 'Duration to sync a block',
75
- valueType: ValueType.INT,
76
- });
62
+ this.proofsSubmittedDelay = meter.createHistogram(Metrics.ARCHIVER_ROLLUP_PROOF_DELAY);
77
63
 
78
- this.syncBlockCount = meter.createUpDownCounter(Metrics.ARCHIVER_SYNC_BLOCK_COUNT, {
79
- description: 'Number of blocks synced from L1',
80
- valueType: ValueType.INT,
81
- });
64
+ this.syncDurationPerBlock = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_BLOCK);
82
65
 
83
- this.manaPerBlock = meter.createHistogram(Metrics.ARCHIVER_MANA_PER_BLOCK, {
84
- description: 'The mana consumed by blocks',
85
- valueType: ValueType.DOUBLE,
86
- unit: 'Mmana',
87
- });
66
+ this.syncBlockCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_BLOCK_COUNT);
88
67
 
89
- this.txsPerBlock = meter.createHistogram(Metrics.ARCHIVER_TXS_PER_BLOCK, {
90
- description: 'The block tx count',
91
- valueType: ValueType.INT,
92
- unit: 'tx',
93
- });
68
+ this.manaPerBlock = meter.createHistogram(Metrics.ARCHIVER_MANA_PER_BLOCK);
94
69
 
95
- this.syncDurationPerMessage = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_MESSAGE, {
96
- unit: 'ms',
97
- description: 'Duration to sync a message',
98
- valueType: ValueType.INT,
99
- });
70
+ this.txsPerBlock = meter.createHistogram(Metrics.ARCHIVER_TXS_PER_BLOCK);
100
71
 
101
- this.syncMessageCount = meter.createUpDownCounter(Metrics.ARCHIVER_SYNC_MESSAGE_COUNT, {
102
- description: 'Number of L1 to L2 messages synced',
103
- valueType: ValueType.INT,
104
- });
72
+ this.syncDurationPerMessage = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_MESSAGE);
105
73
 
106
- this.pruneDuration = meter.createHistogram(Metrics.ARCHIVER_PRUNE_DURATION, {
107
- unit: 'ms',
108
- description: 'Duration to sync a message',
109
- valueType: ValueType.INT,
110
- });
74
+ this.syncMessageCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_MESSAGE_COUNT);
111
75
 
112
- this.pruneCount = meter.createUpDownCounter(Metrics.ARCHIVER_PRUNE_COUNT, {
113
- description: 'Number of prunes detected',
114
- valueType: ValueType.INT,
115
- });
76
+ this.pruneDuration = meter.createHistogram(Metrics.ARCHIVER_PRUNE_DURATION);
77
+
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
+ );
116
87
 
117
88
  this.dbMetrics = new LmdbMetrics(
118
89
  meter,
@@ -126,10 +97,6 @@ export class ArchiverInstrumentation {
126
97
  public static async new(telemetry: TelemetryClient, lmdbStats?: LmdbStatsCallback) {
127
98
  const instance = new ArchiverInstrumentation(telemetry, lmdbStats);
128
99
 
129
- instance.syncBlockCount.add(0);
130
- instance.syncMessageCount.add(0);
131
- instance.pruneCount.add(0);
132
-
133
100
  await instance.telemetry.flush();
134
101
 
135
102
  return instance;
@@ -139,9 +106,10 @@ export class ArchiverInstrumentation {
139
106
  return this.telemetry.isEnabled();
140
107
  }
141
108
 
142
- public processNewBlocks(syncTimePerBlock: number, blocks: L2BlockNew[]) {
109
+ public processNewBlocks(syncTimePerBlock: number, blocks: L2Block[]) {
143
110
  this.syncDurationPerBlock.record(Math.ceil(syncTimePerBlock));
144
111
  this.blockHeight.record(Math.max(...blocks.map(b => b.number)));
112
+ this.checkpointHeight.record(Math.max(...blocks.map(b => b.checkpointNumber)));
145
113
  this.syncBlockCount.add(blocks.length);
146
114
 
147
115
  for (const block of blocks) {
@@ -164,8 +132,10 @@ export class ArchiverInstrumentation {
164
132
  this.pruneDuration.record(Math.ceil(duration));
165
133
  }
166
134
 
167
- public updateLastProvenBlock(blockNumber: number) {
168
- 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' });
169
139
  }
170
140
 
171
141
  public processProofsVerified(logs: { proverId: string; l2BlockNumber: bigint; delay: bigint }[]) {
@@ -184,4 +154,11 @@ export class ArchiverInstrumentation {
184
154
  public updateL1BlockHeight(blockNumber: bigint) {
185
155
  this.l1BlockHeight.record(Number(blockNumber));
186
156
  }
157
+
158
+ public recordBlockProposalTxTarget(target: string, usedTrace: boolean) {
159
+ this.blockProposalTxTargetCount.add(1, {
160
+ [Attributes.L1_BLOCK_PROPOSAL_TX_TARGET]: target.toLowerCase(),
161
+ [Attributes.L1_BLOCK_PROPOSAL_USED_TRACE]: usedTrace,
162
+ });
163
+ }
187
164
  }