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

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