@aztec/archiver 0.0.1-commit.d1f2d6c → 0.0.1-commit.d20b825a7

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 (120) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +16 -10
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +110 -122
  5. package/dest/config.d.ts +5 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +15 -3
  8. package/dest/errors.d.ts +55 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +74 -15
  11. package/dest/factory.d.ts +5 -4
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +34 -29
  14. package/dest/index.d.ts +4 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +3 -1
  17. package/dest/l1/bin/retrieve-calldata.js +36 -33
  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 +26 -17
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +43 -48
  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_historical_logs.d.ts +23 -0
  28. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  29. package/dest/l1/validate_historical_logs.js +108 -0
  30. package/dest/l1/validate_trace.d.ts +6 -3
  31. package/dest/l1/validate_trace.d.ts.map +1 -1
  32. package/dest/l1/validate_trace.js +13 -9
  33. package/dest/modules/data_source_base.d.ts +17 -10
  34. package/dest/modules/data_source_base.d.ts.map +1 -1
  35. package/dest/modules/data_source_base.js +39 -77
  36. package/dest/modules/data_store_updater.d.ts +50 -26
  37. package/dest/modules/data_store_updater.d.ts.map +1 -1
  38. package/dest/modules/data_store_updater.js +169 -130
  39. package/dest/modules/instrumentation.d.ts +21 -3
  40. package/dest/modules/instrumentation.d.ts.map +1 -1
  41. package/dest/modules/instrumentation.js +58 -18
  42. package/dest/modules/l1_synchronizer.d.ts +10 -9
  43. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  44. package/dest/modules/l1_synchronizer.js +285 -157
  45. package/dest/modules/validation.d.ts +1 -1
  46. package/dest/modules/validation.d.ts.map +1 -1
  47. package/dest/modules/validation.js +2 -2
  48. package/dest/store/block_store.d.ts +85 -36
  49. package/dest/store/block_store.d.ts.map +1 -1
  50. package/dest/store/block_store.js +433 -162
  51. package/dest/store/contract_class_store.d.ts +2 -3
  52. package/dest/store/contract_class_store.d.ts.map +1 -1
  53. package/dest/store/contract_class_store.js +16 -72
  54. package/dest/store/contract_instance_store.d.ts +1 -1
  55. package/dest/store/contract_instance_store.d.ts.map +1 -1
  56. package/dest/store/contract_instance_store.js +6 -2
  57. package/dest/store/kv_archiver_store.d.ts +76 -32
  58. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  59. package/dest/store/kv_archiver_store.js +92 -37
  60. package/dest/store/l2_tips_cache.d.ts +20 -0
  61. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  62. package/dest/store/l2_tips_cache.js +109 -0
  63. package/dest/store/log_store.d.ts +6 -3
  64. package/dest/store/log_store.d.ts.map +1 -1
  65. package/dest/store/log_store.js +151 -56
  66. package/dest/store/message_store.d.ts +5 -1
  67. package/dest/store/message_store.d.ts.map +1 -1
  68. package/dest/store/message_store.js +21 -9
  69. package/dest/test/fake_l1_state.d.ts +24 -1
  70. package/dest/test/fake_l1_state.d.ts.map +1 -1
  71. package/dest/test/fake_l1_state.js +145 -28
  72. package/dest/test/index.js +3 -1
  73. package/dest/test/mock_archiver.d.ts +1 -1
  74. package/dest/test/mock_archiver.d.ts.map +1 -1
  75. package/dest/test/mock_archiver.js +3 -2
  76. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  77. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  78. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  79. package/dest/test/mock_l2_block_source.d.ts +31 -10
  80. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  81. package/dest/test/mock_l2_block_source.js +163 -92
  82. package/dest/test/mock_structs.d.ts +6 -2
  83. package/dest/test/mock_structs.d.ts.map +1 -1
  84. package/dest/test/mock_structs.js +20 -6
  85. package/dest/test/noop_l1_archiver.d.ts +26 -0
  86. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  87. package/dest/test/noop_l1_archiver.js +74 -0
  88. package/package.json +14 -13
  89. package/src/archiver.ts +150 -146
  90. package/src/config.ts +22 -2
  91. package/src/errors.ts +116 -26
  92. package/src/factory.ts +49 -26
  93. package/src/index.ts +3 -1
  94. package/src/l1/README.md +25 -68
  95. package/src/l1/bin/retrieve-calldata.ts +46 -39
  96. package/src/l1/calldata_retriever.ts +250 -379
  97. package/src/l1/data_retrieval.ts +59 -70
  98. package/src/l1/spire_proposer.ts +7 -15
  99. package/src/l1/validate_historical_logs.ts +140 -0
  100. package/src/l1/validate_trace.ts +24 -6
  101. package/src/modules/data_source_base.ts +81 -101
  102. package/src/modules/data_store_updater.ts +202 -160
  103. package/src/modules/instrumentation.ts +71 -19
  104. package/src/modules/l1_synchronizer.ts +365 -197
  105. package/src/modules/validation.ts +2 -2
  106. package/src/store/block_store.ts +546 -206
  107. package/src/store/contract_class_store.ts +16 -110
  108. package/src/store/contract_instance_store.ts +8 -5
  109. package/src/store/kv_archiver_store.ts +143 -53
  110. package/src/store/l2_tips_cache.ts +134 -0
  111. package/src/store/log_store.ts +225 -67
  112. package/src/store/message_store.ts +27 -10
  113. package/src/structs/inbox_message.ts +1 -1
  114. package/src/test/fake_l1_state.ts +193 -32
  115. package/src/test/index.ts +3 -0
  116. package/src/test/mock_archiver.ts +3 -2
  117. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  118. package/src/test/mock_l2_block_source.ts +217 -90
  119. package/src/test/mock_structs.ts +42 -12
  120. package/src/test/noop_l1_archiver.ts +117 -0
@@ -1,30 +1,28 @@
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 { L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
14
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
9
+ import type { CommitteeAttestation, L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
10
+ import {
11
+ type L1PublishedData,
12
+ type ProposedCheckpointInput,
13
+ type PublishedCheckpoint,
14
+ validateCheckpoint,
15
+ } from '@aztec/stdlib/checkpoint';
15
16
  import {
16
- type ExecutablePrivateFunctionWithMembershipProof,
17
- type UtilityFunctionWithMembershipProof,
18
- computePublicBytecodeCommitment,
19
- isValidPrivateFunctionMembershipProof,
20
- isValidUtilityFunctionMembershipProof,
17
+ type ContractClassPublicWithCommitment,
18
+ computeContractAddressFromInstance,
19
+ computeContractClassId,
21
20
  } from '@aztec/stdlib/contract';
22
21
  import type { ContractClassLog, PrivateLog, PublicLog } from '@aztec/stdlib/logs';
23
22
  import type { UInt64 } from '@aztec/stdlib/types';
24
23
 
25
- import groupBy from 'lodash.groupby';
26
-
27
24
  import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
25
+ import type { L2TipsCache } from '../store/l2_tips_cache.js';
28
26
 
29
27
  /** Operation type for contract data updates. */
30
28
  enum Operation {
@@ -44,56 +42,79 @@ type ReconcileCheckpointsResult = {
44
42
  export class ArchiverDataStoreUpdater {
45
43
  private readonly log = createLogger('archiver:store_updater');
46
44
 
47
- constructor(private store: KVArchiverDataStore) {}
45
+ constructor(
46
+ private store: KVArchiverDataStore,
47
+ private l2TipsCache?: L2TipsCache,
48
+ private opts: { rollupManaLimit?: number } = {},
49
+ ) {}
48
50
 
49
51
  /**
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.
52
+ * Adds a proposed block to the store with contract class/instance extraction from logs.
53
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
54
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the block logs.
53
55
  *
54
- * @param blocks - The L2 blocks to add.
56
+ * @param block - The proposed L2 block to add.
55
57
  * @param pendingChainValidationStatus - Optional validation status to set.
56
58
  * @returns True if the operation is successful.
57
59
  */
58
- public addBlocks(blocks: L2Block[], pendingChainValidationStatus?: ValidateCheckpointResult): Promise<boolean> {
59
- return this.store.transactionAsync(async () => {
60
- await this.store.addBlocks(blocks);
60
+ public async addProposedBlock(
61
+ block: L2Block,
62
+ pendingChainValidationStatus?: ValidateCheckpointResult,
63
+ ): Promise<boolean> {
64
+ const result = await this.store.transactionAsync(async () => {
65
+ await this.store.addProposedBlock(block);
61
66
 
62
67
  const opResults = await Promise.all([
63
68
  // Update the pending chain validation status if provided
64
69
  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)),
70
+ // Add any logs emitted during the retrieved block
71
+ this.store.addLogs([block]),
72
+ // Unroll all logs emitted during the retrieved block and extract any contract classes and instances from it
73
+ this.addContractDataToDb(block),
69
74
  ]);
70
75
 
76
+ await this.l2TipsCache?.refresh();
71
77
  return opResults.every(Boolean);
72
78
  });
79
+ return result;
73
80
  }
74
81
 
75
82
  /**
76
83
  * Reconciles local blocks with incoming checkpoints from L1.
77
- * Adds checkpoints to the store with contract class/instance extraction from logs.
84
+ * Adds new checkpoints to the store with contract class/instance extraction from logs.
78
85
  * 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.
86
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the checkpoint block logs.
87
+ * If `promoteProposed` is supplied, the proposed-checkpoint promotion runs inside the same transaction
88
+ * as the added checkpoints so both updates are applied atomically.
81
89
  *
82
- * @param checkpoints - The published checkpoints to add.
90
+ * @param checkpoints - The published checkpoints to add (excluding any being promoted from proposed).
83
91
  * @param pendingChainValidationStatus - Optional validation status to set.
92
+ * @param promoteProposed - Optional promotion of the current proposed checkpoint (fast path when blocks are already local).
84
93
  * @returns Result with information about any pruned blocks.
85
94
  */
86
- public setNewCheckpointData(
95
+ public async addCheckpoints(
87
96
  checkpoints: PublishedCheckpoint[],
88
97
  pendingChainValidationStatus?: ValidateCheckpointResult,
98
+ promoteProposed?: {
99
+ l1: L1PublishedData;
100
+ attestations: CommitteeAttestation[];
101
+ checkpoint: PublishedCheckpoint;
102
+ },
89
103
  ): Promise<ReconcileCheckpointsResult> {
90
- return this.store.transactionAsync(async () => {
104
+ for (const checkpoint of checkpoints) {
105
+ validateCheckpoint(checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
106
+ }
107
+ if (promoteProposed) {
108
+ validateCheckpoint(promoteProposed.checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
109
+ }
110
+
111
+ const result = await this.store.transactionAsync(async () => {
91
112
  // Before adding checkpoints, check for conflicts with local blocks if any
92
113
  const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
93
114
 
94
115
  await this.store.addCheckpoints(checkpoints);
95
116
 
96
- // Filter out blocks that were already inserted via addBlocks() to avoid duplicating logs/contract data
117
+ // Filter out blocks that were already inserted via addProposedBlock() to avoid duplicating logs/contract data
97
118
  const newBlocks = checkpoints
98
119
  .flatMap((ch: PublishedCheckpoint) => ch.checkpoint.blocks)
99
120
  .filter(b => lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
@@ -104,11 +125,30 @@ export class ArchiverDataStoreUpdater {
104
125
  // Add any logs emitted during the retrieved blocks
105
126
  this.store.addLogs(newBlocks),
106
127
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
107
- ...newBlocks.map(block => this.addBlockDataToDB(block)),
128
+ ...newBlocks.map(block => this.addContractDataToDb(block)),
129
+ // Promote the proposed checkpoint if requested
130
+ promoteProposed
131
+ ? this.store.promoteProposedToCheckpointed(
132
+ promoteProposed.l1,
133
+ promoteProposed.attestations,
134
+ promoteProposed.checkpoint.checkpoint.archive.root,
135
+ )
136
+ : undefined,
108
137
  ]);
109
138
 
139
+ await this.l2TipsCache?.refresh();
110
140
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
111
141
  });
142
+ return result;
143
+ }
144
+
145
+ public async setProposedCheckpoint(proposedCheckpoint: ProposedCheckpointInput) {
146
+ const result = await this.store.transactionAsync(async () => {
147
+ await this.store.setProposedCheckpoint(proposedCheckpoint);
148
+ await this.l2TipsCache?.refresh();
149
+ });
150
+
151
+ return result;
112
152
  }
113
153
 
114
154
  /**
@@ -161,7 +201,7 @@ export class ArchiverDataStoreUpdater {
161
201
  this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
162
202
  lastAlreadyInsertedBlockNumber = blockNumber;
163
203
  } else {
164
- this.log.warn(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
204
+ this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
165
205
  const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
166
206
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
167
207
  }
@@ -185,80 +225,112 @@ export class ArchiverDataStoreUpdater {
185
225
  }
186
226
 
187
227
  /**
188
- * Removes all blocks strictly after the specified block number and cleans up associated contract data.
228
+ * Removes all uncheckpointed blocks strictly after the specified block number and cleans up associated contract data.
189
229
  * This handles removal of provisionally added blocks along with their contract classes/instances.
230
+ * Verifies that each block being removed is not part of a stored checkpoint.
190
231
  *
191
232
  * @param blockNumber - Remove all blocks with number greater than this.
192
233
  * @returns The removed blocks.
234
+ * @throws Error if any block to be removed is checkpointed.
193
235
  */
194
- public removeBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
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);
236
+ public async removeUncheckpointedBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
237
+ const result = await this.store.transactionAsync(async () => {
238
+ // Verify we're only removing uncheckpointed blocks
239
+ const lastCheckpointedBlockNumber = await this.store.getCheckpointedL2BlockNumber();
240
+ if (blockNumber < lastCheckpointedBlockNumber) {
241
+ throw new Error(
242
+ `Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`,
243
+ );
244
+ }
198
245
 
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
- ]);
246
+ const result = await this.removeBlocksAfter(blockNumber);
204
247
 
205
- return removedBlocks;
248
+ // Clear the proposed checkpoint if it exists, since its blocks have been pruned
249
+ await this.store.deleteProposedCheckpoint();
250
+
251
+ await this.l2TipsCache?.refresh();
252
+ return result;
206
253
  });
254
+ return result;
255
+ }
256
+
257
+ /**
258
+ * Removes all blocks strictly after the given block number along with any logs and contract data.
259
+ * Does not remove their checkpoints.
260
+ */
261
+ private async removeBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
262
+ // First get the blocks to be removed so we can clean up contract data
263
+ const removedBlocks = await this.store.removeBlocksAfter(blockNumber);
264
+
265
+ // Clean up contract data and logs for the removed blocks
266
+ await Promise.all([
267
+ this.store.deleteLogs(removedBlocks),
268
+ ...removedBlocks.map(block => this.removeContractDataFromDb(block)),
269
+ ]);
270
+
271
+ return removedBlocks;
207
272
  }
208
273
 
209
274
  /**
210
- * Unwinds checkpoints from the store with reverse contract extraction.
275
+ * Removes all checkpoints after the given checkpoint number.
211
276
  * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
212
- * that was stored for the unwound checkpoints.
277
+ * that was stored for the removed checkpoints. Also removes ALL blocks (both checkpointed
278
+ * and uncheckpointed) after the last block of the given checkpoint.
213
279
  *
214
- * @param from - The checkpoint number to unwind from (must be the current tip).
215
- * @param checkpointsToUnwind - The number of checkpoints to unwind.
280
+ * @param checkpointNumber - Remove all checkpoints strictly after this one.
216
281
  * @returns True if the operation is successful.
217
282
  */
218
- public async unwindCheckpoints(from: CheckpointNumber, checkpointsToUnwind: number): Promise<boolean> {
219
- if (checkpointsToUnwind <= 0) {
220
- throw new Error(`Cannot unwind ${checkpointsToUnwind} blocks`);
221
- }
283
+ public async removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
284
+ return await this.store.transactionAsync(async () => {
285
+ const { blocksRemoved = [] } = await this.store.removeCheckpointsAfter(checkpointNumber);
222
286
 
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
- }
287
+ const opResults = await Promise.all([
288
+ // Prune rolls back to the last proven block, which is by definition valid
289
+ this.store.setPendingChainValidationStatus({ valid: true }),
290
+ // Remove contract data for all blocks being removed
291
+ ...blocksRemoved.map(block => this.removeContractDataFromDb(block)),
292
+ this.store.deleteLogs(blocksRemoved),
293
+ ]);
227
294
 
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
- }
295
+ await this.l2TipsCache?.refresh();
296
+ return opResults.every(Boolean);
297
+ });
298
+ }
237
299
 
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
- ]);
300
+ /**
301
+ * Updates the proven checkpoint number and refreshes the L2 tips cache.
302
+ * @param checkpointNumber - The checkpoint number to set as proven.
303
+ */
304
+ public async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
305
+ await this.store.transactionAsync(async () => {
306
+ await this.store.setProvenCheckpointNumber(checkpointNumber);
307
+ await this.l2TipsCache?.refresh();
308
+ });
309
+ }
246
310
 
247
- return opResults.every(Boolean);
311
+ /**
312
+ * Updates the finalized checkpoint number and refreshes the L2 tips cache.
313
+ * @param checkpointNumber - The checkpoint number to set as finalized.
314
+ */
315
+ public async setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
316
+ await this.store.transactionAsync(async () => {
317
+ await this.store.setFinalizedCheckpointNumber(checkpointNumber);
318
+ await this.l2TipsCache?.refresh();
319
+ });
248
320
  }
249
321
 
250
322
  /** Extracts and stores contract data from a single block. */
251
- private addBlockDataToDB(block: L2Block): Promise<boolean> {
252
- return this.editContractBlockData(block, Operation.Store);
323
+ private addContractDataToDb(block: L2Block): Promise<boolean> {
324
+ return this.updateContractDataOnDb(block, Operation.Store);
253
325
  }
254
326
 
255
327
  /** Removes contract data associated with a block. */
256
- private removeBlockDataFromDB(block: L2Block): Promise<boolean> {
257
- return this.editContractBlockData(block, Operation.Delete);
328
+ private removeContractDataFromDb(block: L2Block): Promise<boolean> {
329
+ return this.updateContractDataOnDb(block, Operation.Delete);
258
330
  }
259
331
 
260
332
  /** Adds or remove contract data associated with a block. */
261
- private async editContractBlockData(block: L2Block, operation: Operation): Promise<boolean> {
333
+ private async updateContractDataOnDb(block: L2Block, operation: Operation): Promise<boolean> {
262
334
  const contractClassLogs = block.body.txEffects.flatMap(txEffect => txEffect.contractClassLogs);
263
335
  const privateLogs = block.body.txEffects.flatMap(txEffect => txEffect.privateLogs);
264
336
  const publicLogs = block.body.txEffects.flatMap(txEffect => txEffect.publicLogs);
@@ -268,9 +340,6 @@ export class ArchiverDataStoreUpdater {
268
340
  this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
269
341
  this.updateDeployedContractInstances(privateLogs, block.number, operation),
270
342
  this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
271
- operation === Operation.Store
272
- ? this.storeBroadcastedIndividualFunctions(contractClassLogs, block.number)
273
- : Promise.resolve(true),
274
343
  ])
275
344
  ).every(Boolean);
276
345
  }
@@ -287,18 +356,37 @@ export class ArchiverDataStoreUpdater {
287
356
  .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
288
357
  .map(log => ContractClassPublishedEvent.fromLog(log));
289
358
 
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) {
359
+ if (operation == Operation.Delete) {
360
+ const contractClasses = contractClassPublishedEvents.map(e => e.toContractClassPublic());
361
+ if (contractClasses.length > 0) {
362
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
300
363
  return await this.store.deleteContractClasses(contractClasses, blockNum);
301
364
  }
365
+ return true;
366
+ }
367
+
368
+ // Compute bytecode commitments and validate class IDs in a single pass.
369
+ const contractClasses: ContractClassPublicWithCommitment[] = [];
370
+ for (const event of contractClassPublishedEvents) {
371
+ const contractClass = await event.toContractClassPublicWithBytecodeCommitment();
372
+ const computedClassId = await computeContractClassId({
373
+ artifactHash: contractClass.artifactHash,
374
+ privateFunctionsRoot: contractClass.privateFunctionsRoot,
375
+ publicBytecodeCommitment: contractClass.publicBytecodeCommitment,
376
+ });
377
+ if (!computedClassId.equals(contractClass.id)) {
378
+ this.log.warn(
379
+ `Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`,
380
+ { blockNum, contractClassId: event.contractClassId.toString() },
381
+ );
382
+ continue;
383
+ }
384
+ contractClasses.push(contractClass);
385
+ }
386
+
387
+ if (contractClasses.length > 0) {
388
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
389
+ return await this.store.addContractClasses(contractClasses, blockNum);
302
390
  }
303
391
  return true;
304
392
  }
@@ -311,10 +399,27 @@ export class ArchiverDataStoreUpdater {
311
399
  blockNum: BlockNumber,
312
400
  operation: Operation,
313
401
  ): Promise<boolean> {
314
- const contractInstances = allLogs
402
+ const allInstances = allLogs
315
403
  .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
316
404
  .map(log => ContractInstancePublishedEvent.fromLog(log))
317
405
  .map(e => e.toContractInstance());
406
+
407
+ // Verify that each instance's address matches the one derived from its fields if we're adding
408
+ const contractInstances =
409
+ operation === Operation.Delete
410
+ ? allInstances
411
+ : await filterAsync(allInstances, async instance => {
412
+ const computedAddress = await computeContractAddressFromInstance(instance);
413
+ if (!computedAddress.equals(instance.address)) {
414
+ this.log.warn(
415
+ `Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`,
416
+ { instanceAddress: instance.address.toString(), computedAddress: computedAddress.toString(), blockNum },
417
+ );
418
+ return false;
419
+ }
420
+ return true;
421
+ });
422
+
318
423
  if (contractInstances.length > 0) {
319
424
  contractInstances.forEach(c =>
320
425
  this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`),
@@ -353,67 +458,4 @@ export class ArchiverDataStoreUpdater {
353
458
  }
354
459
  return true;
355
460
  }
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
461
  }