@aztec/archiver 0.0.1-commit.d431d1c → 0.0.1-commit.d939eb5aa

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 (116) hide show
  1. package/README.md +21 -6
  2. package/dest/archiver.d.ts +17 -12
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +108 -127
  5. package/dest/config.d.ts +3 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +3 -2
  8. package/dest/errors.d.ts +39 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +52 -15
  11. package/dest/factory.d.ts +4 -2
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +29 -23
  14. package/dest/index.d.ts +2 -1
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +1 -0
  17. package/dest/l1/bin/retrieve-calldata.js +35 -32
  18. package/dest/l1/calldata_retriever.d.ts +73 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +191 -259
  21. package/dest/l1/data_retrieval.d.ts +11 -11
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +38 -37
  24. package/dest/l1/spire_proposer.d.ts +5 -5
  25. package/dest/l1/spire_proposer.d.ts.map +1 -1
  26. package/dest/l1/spire_proposer.js +9 -17
  27. package/dest/l1/validate_trace.d.ts +6 -3
  28. package/dest/l1/validate_trace.d.ts.map +1 -1
  29. package/dest/l1/validate_trace.js +13 -9
  30. package/dest/modules/data_source_base.d.ts +29 -23
  31. package/dest/modules/data_source_base.d.ts.map +1 -1
  32. package/dest/modules/data_source_base.js +55 -124
  33. package/dest/modules/data_store_updater.d.ts +43 -26
  34. package/dest/modules/data_store_updater.d.ts.map +1 -1
  35. package/dest/modules/data_store_updater.js +158 -129
  36. package/dest/modules/instrumentation.d.ts +19 -4
  37. package/dest/modules/instrumentation.d.ts.map +1 -1
  38. package/dest/modules/instrumentation.js +53 -18
  39. package/dest/modules/l1_synchronizer.d.ts +7 -9
  40. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  41. package/dest/modules/l1_synchronizer.js +186 -145
  42. package/dest/modules/validation.d.ts +1 -1
  43. package/dest/modules/validation.d.ts.map +1 -1
  44. package/dest/modules/validation.js +2 -2
  45. package/dest/store/block_store.d.ts +86 -34
  46. package/dest/store/block_store.d.ts.map +1 -1
  47. package/dest/store/block_store.js +414 -152
  48. package/dest/store/contract_class_store.d.ts +2 -3
  49. package/dest/store/contract_class_store.d.ts.map +1 -1
  50. package/dest/store/contract_class_store.js +16 -72
  51. package/dest/store/contract_instance_store.d.ts +1 -1
  52. package/dest/store/contract_instance_store.d.ts.map +1 -1
  53. package/dest/store/contract_instance_store.js +6 -2
  54. package/dest/store/kv_archiver_store.d.ts +80 -39
  55. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  56. package/dest/store/kv_archiver_store.js +86 -35
  57. package/dest/store/l2_tips_cache.d.ts +20 -0
  58. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  59. package/dest/store/l2_tips_cache.js +109 -0
  60. package/dest/store/log_store.d.ts +9 -6
  61. package/dest/store/log_store.d.ts.map +1 -1
  62. package/dest/store/log_store.js +151 -56
  63. package/dest/store/message_store.d.ts +5 -1
  64. package/dest/store/message_store.d.ts.map +1 -1
  65. package/dest/store/message_store.js +21 -9
  66. package/dest/test/fake_l1_state.d.ts +24 -4
  67. package/dest/test/fake_l1_state.d.ts.map +1 -1
  68. package/dest/test/fake_l1_state.js +133 -26
  69. package/dest/test/index.js +3 -1
  70. package/dest/test/mock_archiver.d.ts +1 -1
  71. package/dest/test/mock_archiver.d.ts.map +1 -1
  72. package/dest/test/mock_archiver.js +3 -2
  73. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  74. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  75. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  76. package/dest/test/mock_l2_block_source.d.ts +44 -23
  77. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  78. package/dest/test/mock_l2_block_source.js +185 -115
  79. package/dest/test/mock_structs.d.ts +6 -2
  80. package/dest/test/mock_structs.d.ts.map +1 -1
  81. package/dest/test/mock_structs.js +24 -10
  82. package/dest/test/noop_l1_archiver.d.ts +26 -0
  83. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  84. package/dest/test/noop_l1_archiver.js +71 -0
  85. package/package.json +14 -13
  86. package/src/archiver.ts +144 -159
  87. package/src/config.ts +9 -2
  88. package/src/errors.ts +82 -26
  89. package/src/factory.ts +46 -22
  90. package/src/index.ts +1 -0
  91. package/src/l1/README.md +25 -68
  92. package/src/l1/bin/retrieve-calldata.ts +45 -33
  93. package/src/l1/calldata_retriever.ts +250 -379
  94. package/src/l1/data_retrieval.ts +35 -41
  95. package/src/l1/spire_proposer.ts +7 -15
  96. package/src/l1/validate_trace.ts +24 -6
  97. package/src/modules/data_source_base.ts +98 -169
  98. package/src/modules/data_store_updater.ts +178 -160
  99. package/src/modules/instrumentation.ts +64 -20
  100. package/src/modules/l1_synchronizer.ts +212 -182
  101. package/src/modules/validation.ts +2 -2
  102. package/src/store/block_store.ts +533 -207
  103. package/src/store/contract_class_store.ts +16 -110
  104. package/src/store/contract_instance_store.ts +8 -5
  105. package/src/store/kv_archiver_store.ts +141 -59
  106. package/src/store/l2_tips_cache.ts +134 -0
  107. package/src/store/log_store.ts +232 -74
  108. package/src/store/message_store.ts +27 -10
  109. package/src/structs/inbox_message.ts +1 -1
  110. package/src/test/fake_l1_state.ts +180 -32
  111. package/src/test/index.ts +3 -0
  112. package/src/test/mock_archiver.ts +3 -2
  113. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  114. package/src/test/mock_l2_block_source.ts +247 -130
  115. package/src/test/mock_structs.ts +45 -15
  116. package/src/test/noop_l1_archiver.ts +114 -0
@@ -1,30 +1,23 @@
1
- import { BlockNumber, type CheckpointNumber } from '@aztec/foundation/branded-types';
2
- import { Fr } from '@aztec/foundation/curves/bn254';
1
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import { filterAsync } from '@aztec/foundation/collection';
3
3
  import { createLogger } from '@aztec/foundation/log';
4
- import {
5
- ContractClassPublishedEvent,
6
- PrivateFunctionBroadcastedEvent,
7
- UtilityFunctionBroadcastedEvent,
8
- } from '@aztec/protocol-contracts/class-registry';
4
+ import { ContractClassPublishedEvent } from '@aztec/protocol-contracts/class-registry';
9
5
  import {
10
6
  ContractInstancePublishedEvent,
11
7
  ContractInstanceUpdatedEvent,
12
8
  } from '@aztec/protocol-contracts/instance-registry';
13
- import type { L2BlockNew, ValidateCheckpointResult } from '@aztec/stdlib/block';
14
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
9
+ import type { L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
10
+ import { type ProposedCheckpointInput, type PublishedCheckpoint, validateCheckpoint } from '@aztec/stdlib/checkpoint';
15
11
  import {
16
- type ExecutablePrivateFunctionWithMembershipProof,
17
- type UtilityFunctionWithMembershipProof,
18
- computePublicBytecodeCommitment,
19
- isValidPrivateFunctionMembershipProof,
20
- isValidUtilityFunctionMembershipProof,
12
+ type ContractClassPublicWithCommitment,
13
+ computeContractAddressFromInstance,
14
+ computeContractClassId,
21
15
  } from '@aztec/stdlib/contract';
22
16
  import type { ContractClassLog, PrivateLog, PublicLog } from '@aztec/stdlib/logs';
23
17
  import type { UInt64 } from '@aztec/stdlib/types';
24
18
 
25
- import groupBy from 'lodash.groupby';
26
-
27
19
  import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
20
+ import type { L2TipsCache } from '../store/l2_tips_cache.js';
28
21
 
29
22
  /** Operation type for contract data updates. */
30
23
  enum Operation {
@@ -35,7 +28,7 @@ enum Operation {
35
28
  /** Result of adding checkpoints with information about any pruned blocks. */
36
29
  type ReconcileCheckpointsResult = {
37
30
  /** Blocks that were pruned due to conflict with L1 checkpoints. */
38
- prunedBlocks: L2BlockNew[] | undefined;
31
+ prunedBlocks: L2Block[] | undefined;
39
32
  /** Last block number that was already inserted locally, or undefined if none. */
40
33
  lastAlreadyInsertedBlockNumber: BlockNumber | undefined;
41
34
  };
@@ -44,56 +37,68 @@ type ReconcileCheckpointsResult = {
44
37
  export class ArchiverDataStoreUpdater {
45
38
  private readonly log = createLogger('archiver:store_updater');
46
39
 
47
- constructor(private store: KVArchiverDataStore) {}
40
+ constructor(
41
+ private store: KVArchiverDataStore,
42
+ private l2TipsCache?: L2TipsCache,
43
+ private opts: { rollupManaLimit?: number } = {},
44
+ ) {}
48
45
 
49
46
  /**
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.
47
+ * Adds a proposed block to the store with contract class/instance extraction from logs.
48
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
49
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the block logs.
53
50
  *
54
- * @param blocks - The L2 blocks to add.
51
+ * @param block - The proposed L2 block to add.
55
52
  * @param pendingChainValidationStatus - Optional validation status to set.
56
53
  * @returns True if the operation is successful.
57
54
  */
58
- public addBlocks(blocks: L2BlockNew[], pendingChainValidationStatus?: ValidateCheckpointResult): Promise<boolean> {
59
- return this.store.transactionAsync(async () => {
60
- await this.store.addBlocks(blocks);
55
+ public async addProposedBlock(
56
+ block: L2Block,
57
+ pendingChainValidationStatus?: ValidateCheckpointResult,
58
+ ): Promise<boolean> {
59
+ const result = await this.store.transactionAsync(async () => {
60
+ await this.store.addProposedBlock(block);
61
61
 
62
62
  const opResults = await Promise.all([
63
63
  // Update the pending chain validation status if provided
64
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)),
65
+ // Add any logs emitted during the retrieved block
66
+ this.store.addLogs([block]),
67
+ // Unroll all logs emitted during the retrieved block and extract any contract classes and instances from it
68
+ this.addContractDataToDb(block),
69
69
  ]);
70
70
 
71
+ await this.l2TipsCache?.refresh();
71
72
  return opResults.every(Boolean);
72
73
  });
74
+ return result;
73
75
  }
74
76
 
75
77
  /**
76
78
  * Reconciles local blocks with incoming checkpoints from L1.
77
- * Adds checkpoints to the store with contract class/instance extraction from logs.
79
+ * Adds new checkpoints to the store with contract class/instance extraction from logs.
78
80
  * 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
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the checkpoint block logs.
81
82
  *
82
83
  * @param checkpoints - The published checkpoints to add.
83
84
  * @param pendingChainValidationStatus - Optional validation status to set.
84
85
  * @returns Result with information about any pruned blocks.
85
86
  */
86
- public setNewCheckpointData(
87
+ public async addCheckpoints(
87
88
  checkpoints: PublishedCheckpoint[],
88
89
  pendingChainValidationStatus?: ValidateCheckpointResult,
89
90
  ): Promise<ReconcileCheckpointsResult> {
90
- return this.store.transactionAsync(async () => {
91
+ for (const checkpoint of checkpoints) {
92
+ validateCheckpoint(checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
93
+ }
94
+
95
+ const result = await this.store.transactionAsync(async () => {
91
96
  // Before adding checkpoints, check for conflicts with local blocks if any
92
97
  const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
93
98
 
94
99
  await this.store.addCheckpoints(checkpoints);
95
100
 
96
- // Filter out blocks that were already inserted via addBlocks() to avoid duplicating logs/contract data
101
+ // Filter out blocks that were already inserted via addProposedBlock() to avoid duplicating logs/contract data
97
102
  const newBlocks = checkpoints
98
103
  .flatMap((ch: PublishedCheckpoint) => ch.checkpoint.blocks)
99
104
  .filter(b => lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
@@ -104,11 +109,22 @@ export class ArchiverDataStoreUpdater {
104
109
  // Add any logs emitted during the retrieved blocks
105
110
  this.store.addLogs(newBlocks),
106
111
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
107
- ...newBlocks.map(block => this.addBlockDataToDB(block)),
112
+ ...newBlocks.map(block => this.addContractDataToDb(block)),
108
113
  ]);
109
114
 
115
+ await this.l2TipsCache?.refresh();
110
116
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
111
117
  });
118
+ return result;
119
+ }
120
+
121
+ public async setProposedCheckpoint(proposedCheckpoint: ProposedCheckpointInput) {
122
+ const result = await this.store.transactionAsync(async () => {
123
+ await this.store.setProposedCheckpoint(proposedCheckpoint);
124
+ await this.l2TipsCache?.refresh();
125
+ });
126
+
127
+ return result;
112
128
  }
113
129
 
114
130
  /**
@@ -161,7 +177,7 @@ export class ArchiverDataStoreUpdater {
161
177
  this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
162
178
  lastAlreadyInsertedBlockNumber = blockNumber;
163
179
  } else {
164
- this.log.warn(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
180
+ this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
165
181
  const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
166
182
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
167
183
  }
@@ -185,80 +201,112 @@ export class ArchiverDataStoreUpdater {
185
201
  }
186
202
 
187
203
  /**
188
- * Removes all blocks strictly after the specified block number and cleans up associated contract data.
204
+ * Removes all uncheckpointed blocks strictly after the specified block number and cleans up associated contract data.
189
205
  * This handles removal of provisionally added blocks along with their contract classes/instances.
206
+ * Verifies that each block being removed is not part of a stored checkpoint.
190
207
  *
191
208
  * @param blockNumber - Remove all blocks with number greater than this.
192
209
  * @returns The removed blocks.
210
+ * @throws Error if any block to be removed is checkpointed.
193
211
  */
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);
212
+ public async removeUncheckpointedBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
213
+ const result = await this.store.transactionAsync(async () => {
214
+ // Verify we're only removing uncheckpointed blocks
215
+ const lastCheckpointedBlockNumber = await this.store.getCheckpointedL2BlockNumber();
216
+ if (blockNumber < lastCheckpointedBlockNumber) {
217
+ throw new Error(
218
+ `Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`,
219
+ );
220
+ }
198
221
 
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
- ]);
222
+ const result = await this.removeBlocksAfter(blockNumber);
223
+
224
+ // Clear the proposed checkpoint if it exists, since its blocks have been pruned
225
+ await this.store.deleteProposedCheckpoint();
204
226
 
205
- return removedBlocks;
227
+ await this.l2TipsCache?.refresh();
228
+ return result;
206
229
  });
230
+ return result;
207
231
  }
208
232
 
209
233
  /**
210
- * Unwinds checkpoints from the store with reverse contract extraction.
234
+ * Removes all blocks strictly after the given block number along with any logs and contract data.
235
+ * Does not remove their checkpoints.
236
+ */
237
+ private async removeBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
238
+ // First get the blocks to be removed so we can clean up contract data
239
+ const removedBlocks = await this.store.removeBlocksAfter(blockNumber);
240
+
241
+ // Clean up contract data and logs for the removed blocks
242
+ await Promise.all([
243
+ this.store.deleteLogs(removedBlocks),
244
+ ...removedBlocks.map(block => this.removeContractDataFromDb(block)),
245
+ ]);
246
+
247
+ return removedBlocks;
248
+ }
249
+
250
+ /**
251
+ * Removes all checkpoints after the given checkpoint number.
211
252
  * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
212
- * that was stored for the unwound checkpoints.
253
+ * that was stored for the removed checkpoints. Also removes ALL blocks (both checkpointed
254
+ * and uncheckpointed) after the last block of the given checkpoint.
213
255
  *
214
- * @param from - The checkpoint number to unwind from (must be the current tip).
215
- * @param checkpointsToUnwind - The number of checkpoints to unwind.
256
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
216
257
  * @returns True if the operation is successful.
217
258
  */
218
- public async unwindCheckpoints(from: CheckpointNumber, checkpointsToUnwind: number): Promise<boolean> {
219
- if (checkpointsToUnwind <= 0) {
220
- throw new Error(`Cannot unwind ${checkpointsToUnwind} blocks`);
221
- }
259
+ public async removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
260
+ return await this.store.transactionAsync(async () => {
261
+ const { blocksRemoved = [] } = await this.store.removeCheckpointsAfter(checkpointNumber);
222
262
 
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
- }
263
+ const opResults = await Promise.all([
264
+ // Prune rolls back to the last proven block, which is by definition valid
265
+ this.store.setPendingChainValidationStatus({ valid: true }),
266
+ // Remove contract data for all blocks being removed
267
+ ...blocksRemoved.map(block => this.removeContractDataFromDb(block)),
268
+ this.store.deleteLogs(blocksRemoved),
269
+ ]);
227
270
 
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
- }
271
+ await this.l2TipsCache?.refresh();
272
+ return opResults.every(Boolean);
273
+ });
274
+ }
237
275
 
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
- ]);
276
+ /**
277
+ * Updates the proven checkpoint number and refreshes the L2 tips cache.
278
+ * @param checkpointNumber - The checkpoint number to set as proven.
279
+ */
280
+ public async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
281
+ await this.store.transactionAsync(async () => {
282
+ await this.store.setProvenCheckpointNumber(checkpointNumber);
283
+ await this.l2TipsCache?.refresh();
284
+ });
285
+ }
246
286
 
247
- return opResults.every(Boolean);
287
+ /**
288
+ * Updates the finalized checkpoint number and refreshes the L2 tips cache.
289
+ * @param checkpointNumber - The checkpoint number to set as finalized.
290
+ */
291
+ public async setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
292
+ await this.store.transactionAsync(async () => {
293
+ await this.store.setFinalizedCheckpointNumber(checkpointNumber);
294
+ await this.l2TipsCache?.refresh();
295
+ });
248
296
  }
249
297
 
250
298
  /** Extracts and stores contract data from a single block. */
251
- private addBlockDataToDB(block: L2BlockNew): Promise<boolean> {
252
- return this.editContractBlockData(block, Operation.Store);
299
+ private addContractDataToDb(block: L2Block): Promise<boolean> {
300
+ return this.updateContractDataOnDb(block, Operation.Store);
253
301
  }
254
302
 
255
303
  /** Removes contract data associated with a block. */
256
- private removeBlockDataFromDB(block: L2BlockNew): Promise<boolean> {
257
- return this.editContractBlockData(block, Operation.Delete);
304
+ private removeContractDataFromDb(block: L2Block): Promise<boolean> {
305
+ return this.updateContractDataOnDb(block, Operation.Delete);
258
306
  }
259
307
 
260
308
  /** Adds or remove contract data associated with a block. */
261
- private async editContractBlockData(block: L2BlockNew, operation: Operation): Promise<boolean> {
309
+ private async updateContractDataOnDb(block: L2Block, operation: Operation): Promise<boolean> {
262
310
  const contractClassLogs = block.body.txEffects.flatMap(txEffect => txEffect.contractClassLogs);
263
311
  const privateLogs = block.body.txEffects.flatMap(txEffect => txEffect.privateLogs);
264
312
  const publicLogs = block.body.txEffects.flatMap(txEffect => txEffect.publicLogs);
@@ -268,9 +316,6 @@ export class ArchiverDataStoreUpdater {
268
316
  this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
269
317
  this.updateDeployedContractInstances(privateLogs, block.number, operation),
270
318
  this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
271
- operation === Operation.Store
272
- ? this.storeBroadcastedIndividualFunctions(contractClassLogs, block.number)
273
- : Promise.resolve(true),
274
319
  ])
275
320
  ).every(Boolean);
276
321
  }
@@ -287,18 +332,37 @@ export class ArchiverDataStoreUpdater {
287
332
  .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
288
333
  .map(log => ContractClassPublishedEvent.fromLog(log));
289
334
 
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) {
335
+ if (operation == Operation.Delete) {
336
+ const contractClasses = contractClassPublishedEvents.map(e => e.toContractClassPublic());
337
+ if (contractClasses.length > 0) {
338
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
300
339
  return await this.store.deleteContractClasses(contractClasses, blockNum);
301
340
  }
341
+ return true;
342
+ }
343
+
344
+ // Compute bytecode commitments and validate class IDs in a single pass.
345
+ const contractClasses: ContractClassPublicWithCommitment[] = [];
346
+ for (const event of contractClassPublishedEvents) {
347
+ const contractClass = await event.toContractClassPublicWithBytecodeCommitment();
348
+ const computedClassId = await computeContractClassId({
349
+ artifactHash: contractClass.artifactHash,
350
+ privateFunctionsRoot: contractClass.privateFunctionsRoot,
351
+ publicBytecodeCommitment: contractClass.publicBytecodeCommitment,
352
+ });
353
+ if (!computedClassId.equals(contractClass.id)) {
354
+ this.log.warn(
355
+ `Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`,
356
+ { blockNum, contractClassId: event.contractClassId.toString() },
357
+ );
358
+ continue;
359
+ }
360
+ contractClasses.push(contractClass);
361
+ }
362
+
363
+ if (contractClasses.length > 0) {
364
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
365
+ return await this.store.addContractClasses(contractClasses, blockNum);
302
366
  }
303
367
  return true;
304
368
  }
@@ -311,10 +375,27 @@ export class ArchiverDataStoreUpdater {
311
375
  blockNum: BlockNumber,
312
376
  operation: Operation,
313
377
  ): Promise<boolean> {
314
- const contractInstances = allLogs
378
+ const allInstances = allLogs
315
379
  .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
316
380
  .map(log => ContractInstancePublishedEvent.fromLog(log))
317
381
  .map(e => e.toContractInstance());
382
+
383
+ // Verify that each instance's address matches the one derived from its fields if we're adding
384
+ const contractInstances =
385
+ operation === Operation.Delete
386
+ ? allInstances
387
+ : await filterAsync(allInstances, async instance => {
388
+ const computedAddress = await computeContractAddressFromInstance(instance);
389
+ if (!computedAddress.equals(instance.address)) {
390
+ this.log.warn(
391
+ `Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`,
392
+ { instanceAddress: instance.address.toString(), computedAddress: computedAddress.toString(), blockNum },
393
+ );
394
+ return false;
395
+ }
396
+ return true;
397
+ });
398
+
318
399
  if (contractInstances.length > 0) {
319
400
  contractInstances.forEach(c =>
320
401
  this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`),
@@ -353,67 +434,4 @@ export class ArchiverDataStoreUpdater {
353
434
  }
354
435
  return true;
355
436
  }
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
437
  }
@@ -1,5 +1,9 @@
1
+ import type { SlotNumber } from '@aztec/foundation/branded-types';
1
2
  import { createLogger } from '@aztec/foundation/log';
2
- import type { L2BlockNew } from '@aztec/stdlib/block';
3
+ import type { L2Block } from '@aztec/stdlib/block';
4
+ import type { CheckpointData } from '@aztec/stdlib/checkpoint';
5
+ import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
6
+ import { getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
3
7
  import {
4
8
  Attributes,
5
9
  type Gauge,
@@ -10,12 +14,14 @@ import {
10
14
  type TelemetryClient,
11
15
  type Tracer,
12
16
  type UpDownCounter,
17
+ createUpDownCounterWithDefault,
13
18
  } from '@aztec/telemetry-client';
14
19
 
15
20
  export class ArchiverInstrumentation {
16
21
  public readonly tracer: Tracer;
17
22
 
18
23
  private blockHeight: Gauge;
24
+ private checkpointHeight: Gauge;
19
25
  private txCount: UpDownCounter;
20
26
  private l1BlockHeight: Gauge;
21
27
  private proofsSubmittedDelay: Histogram;
@@ -26,6 +32,7 @@ export class ArchiverInstrumentation {
26
32
  private pruneCount: UpDownCounter;
27
33
 
28
34
  private syncDurationPerBlock: Histogram;
35
+ private syncDurationPerCheckpoint: Histogram;
29
36
  private syncBlockCount: UpDownCounter;
30
37
  private manaPerBlock: Histogram;
31
38
  private txsPerBlock: Histogram;
@@ -35,6 +42,8 @@ export class ArchiverInstrumentation {
35
42
 
36
43
  private blockProposalTxTargetCount: UpDownCounter;
37
44
 
45
+ private checkpointL1InclusionDelay: Histogram;
46
+
38
47
  private log = createLogger('archiver:instrumentation');
39
48
 
40
49
  private constructor(
@@ -46,17 +55,23 @@ export class ArchiverInstrumentation {
46
55
 
47
56
  this.blockHeight = meter.createGauge(Metrics.ARCHIVER_BLOCK_HEIGHT);
48
57
 
58
+ this.checkpointHeight = meter.createGauge(Metrics.ARCHIVER_CHECKPOINT_HEIGHT);
59
+
49
60
  this.l1BlockHeight = meter.createGauge(Metrics.ARCHIVER_L1_BLOCK_HEIGHT);
50
61
 
51
- this.txCount = meter.createUpDownCounter(Metrics.ARCHIVER_TOTAL_TXS);
62
+ this.txCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_TOTAL_TXS);
52
63
 
53
- this.proofsSubmittedCount = meter.createUpDownCounter(Metrics.ARCHIVER_ROLLUP_PROOF_COUNT);
64
+ this.proofsSubmittedCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_ROLLUP_PROOF_COUNT, {
65
+ [Attributes.PROOF_TIMED_OUT]: [true, false],
66
+ });
54
67
 
55
68
  this.proofsSubmittedDelay = meter.createHistogram(Metrics.ARCHIVER_ROLLUP_PROOF_DELAY);
56
69
 
57
70
  this.syncDurationPerBlock = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_BLOCK);
58
71
 
59
- this.syncBlockCount = meter.createUpDownCounter(Metrics.ARCHIVER_SYNC_BLOCK_COUNT);
72
+ this.syncDurationPerCheckpoint = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_CHECKPOINT);
73
+
74
+ this.syncBlockCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_BLOCK_COUNT);
60
75
 
61
76
  this.manaPerBlock = meter.createHistogram(Metrics.ARCHIVER_MANA_PER_BLOCK);
62
77
 
@@ -64,13 +79,21 @@ export class ArchiverInstrumentation {
64
79
 
65
80
  this.syncDurationPerMessage = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_MESSAGE);
66
81
 
67
- this.syncMessageCount = meter.createUpDownCounter(Metrics.ARCHIVER_SYNC_MESSAGE_COUNT);
82
+ this.syncMessageCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_MESSAGE_COUNT);
68
83
 
69
84
  this.pruneDuration = meter.createHistogram(Metrics.ARCHIVER_PRUNE_DURATION);
70
85
 
71
- this.pruneCount = meter.createUpDownCounter(Metrics.ARCHIVER_PRUNE_COUNT);
86
+ this.pruneCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_PRUNE_COUNT);
87
+
88
+ this.blockProposalTxTargetCount = createUpDownCounterWithDefault(
89
+ meter,
90
+ Metrics.ARCHIVER_BLOCK_PROPOSAL_TX_TARGET_COUNT,
91
+ {
92
+ [Attributes.L1_BLOCK_PROPOSAL_USED_TRACE]: [true, false],
93
+ },
94
+ );
72
95
 
73
- this.blockProposalTxTargetCount = meter.createUpDownCounter(Metrics.ARCHIVER_BLOCK_PROPOSAL_TX_TARGET_COUNT);
96
+ this.checkpointL1InclusionDelay = meter.createHistogram(Metrics.ARCHIVER_CHECKPOINT_L1_INCLUSION_DELAY);
74
97
 
75
98
  this.dbMetrics = new LmdbMetrics(
76
99
  meter,
@@ -84,10 +107,6 @@ export class ArchiverInstrumentation {
84
107
  public static async new(telemetry: TelemetryClient, lmdbStats?: LmdbStatsCallback) {
85
108
  const instance = new ArchiverInstrumentation(telemetry, lmdbStats);
86
109
 
87
- instance.syncBlockCount.add(0);
88
- instance.syncMessageCount.add(0);
89
- instance.pruneCount.add(0);
90
-
91
110
  await instance.telemetry.flush();
92
111
 
93
112
  return instance;
@@ -97,16 +116,26 @@ export class ArchiverInstrumentation {
97
116
  return this.telemetry.isEnabled();
98
117
  }
99
118
 
100
- public processNewBlocks(syncTimePerBlock: number, blocks: L2BlockNew[]) {
119
+ public processNewProposedBlock(syncTimePerBlock: number, block: L2Block) {
120
+ const attrs = { [Attributes.STATUS]: 'proposed' };
121
+ this.blockHeight.record(block.number, attrs);
101
122
  this.syncDurationPerBlock.record(Math.ceil(syncTimePerBlock));
102
- this.blockHeight.record(Math.max(...blocks.map(b => b.number)));
103
- this.syncBlockCount.add(blocks.length);
104
123
 
105
- for (const block of blocks) {
106
- this.txCount.add(block.body.txEffects.length);
107
- this.txsPerBlock.record(block.body.txEffects.length);
108
- this.manaPerBlock.record(block.header.totalManaUsed.toNumber() / 1e6);
124
+ // Per block metrics
125
+ this.txCount.add(block.body.txEffects.length);
126
+ this.txsPerBlock.record(block.body.txEffects.length);
127
+ this.manaPerBlock.record(block.header.totalManaUsed.toNumber() / 1e6);
128
+ }
129
+
130
+ public processNewCheckpointedBlocks(syncTimePerCheckpoint: number, blocks: L2Block[]) {
131
+ if (blocks.length === 0) {
132
+ return;
109
133
  }
134
+
135
+ this.syncDurationPerCheckpoint.record(Math.ceil(syncTimePerCheckpoint));
136
+ this.blockHeight.record(Math.max(...blocks.map(b => b.number)));
137
+ this.checkpointHeight.record(Math.max(...blocks.map(b => b.checkpointNumber)));
138
+ this.syncBlockCount.add(blocks.length);
110
139
  }
111
140
 
112
141
  public processNewMessages(count: number, syncPerMessageMs: number) {
@@ -122,8 +151,10 @@ export class ArchiverInstrumentation {
122
151
  this.pruneDuration.record(Math.ceil(duration));
123
152
  }
124
153
 
125
- public updateLastProvenBlock(blockNumber: number) {
126
- this.blockHeight.record(blockNumber, { [Attributes.STATUS]: 'proven' });
154
+ public updateLastProvenCheckpoint(checkpoint: CheckpointData) {
155
+ const lastBlockNumberInCheckpoint = checkpoint.startBlock + checkpoint.blockCount - 1;
156
+ this.blockHeight.record(lastBlockNumberInCheckpoint, { [Attributes.STATUS]: 'proven' });
157
+ this.checkpointHeight.record(checkpoint.checkpointNumber, { [Attributes.STATUS]: 'proven' });
127
158
  }
128
159
 
129
160
  public processProofsVerified(logs: { proverId: string; l2BlockNumber: bigint; delay: bigint }[]) {
@@ -149,4 +180,17 @@ export class ArchiverInstrumentation {
149
180
  [Attributes.L1_BLOCK_PROPOSAL_USED_TRACE]: usedTrace,
150
181
  });
151
182
  }
183
+
184
+ /**
185
+ * Records L1 inclusion timing for a checkpoint observed on L1 (seconds into the L2 slot).
186
+ */
187
+ public processCheckpointL1Timing(data: {
188
+ slotNumber: SlotNumber;
189
+ l1Timestamp: bigint;
190
+ l1Constants: Pick<L1RollupConstants, 'l1GenesisTime' | 'slotDuration'>;
191
+ }): void {
192
+ const slotStartTs = getTimestampForSlot(data.slotNumber, data.l1Constants);
193
+ const inclusionDelaySeconds = Number(data.l1Timestamp - slotStartTs);
194
+ this.checkpointL1InclusionDelay.record(inclusionDelaySeconds);
195
+ }
152
196
  }