@aztec/archiver 0.0.1-commit.c7c42ec → 0.0.1-commit.f295ac2

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