@aztec/archiver 0.0.1-commit.10bd49492 → 0.0.1-commit.11bf3dd6e

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 (91) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +6 -5
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +32 -15
  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 +28 -2
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +36 -2
  11. package/dest/factory.d.ts +2 -2
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +16 -13
  14. package/dest/l1/calldata_retriever.d.ts +1 -1
  15. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  16. package/dest/l1/calldata_retriever.js +2 -1
  17. package/dest/l1/data_retrieval.d.ts +3 -3
  18. package/dest/l1/data_retrieval.d.ts.map +1 -1
  19. package/dest/l1/data_retrieval.js +14 -15
  20. package/dest/modules/data_source_base.d.ts +6 -4
  21. package/dest/modules/data_source_base.d.ts.map +1 -1
  22. package/dest/modules/data_source_base.js +10 -4
  23. package/dest/modules/data_store_updater.d.ts +5 -7
  24. package/dest/modules/data_store_updater.d.ts.map +1 -1
  25. package/dest/modules/data_store_updater.js +56 -65
  26. package/dest/modules/instrumentation.d.ts +4 -2
  27. package/dest/modules/instrumentation.d.ts.map +1 -1
  28. package/dest/modules/instrumentation.js +17 -6
  29. package/dest/modules/l1_synchronizer.d.ts +3 -2
  30. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  31. package/dest/modules/l1_synchronizer.js +139 -128
  32. package/dest/modules/validation.d.ts +1 -1
  33. package/dest/modules/validation.d.ts.map +1 -1
  34. package/dest/modules/validation.js +2 -2
  35. package/dest/store/block_store.d.ts +39 -4
  36. package/dest/store/block_store.d.ts.map +1 -1
  37. package/dest/store/block_store.js +232 -63
  38. package/dest/store/contract_class_store.d.ts +2 -3
  39. package/dest/store/contract_class_store.d.ts.map +1 -1
  40. package/dest/store/contract_class_store.js +7 -67
  41. package/dest/store/contract_instance_store.d.ts +1 -1
  42. package/dest/store/contract_instance_store.d.ts.map +1 -1
  43. package/dest/store/contract_instance_store.js +6 -2
  44. package/dest/store/kv_archiver_store.d.ts +30 -16
  45. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  46. package/dest/store/kv_archiver_store.js +36 -18
  47. package/dest/store/l2_tips_cache.d.ts +2 -1
  48. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  49. package/dest/store/l2_tips_cache.js +27 -7
  50. package/dest/store/log_store.d.ts +6 -3
  51. package/dest/store/log_store.d.ts.map +1 -1
  52. package/dest/store/log_store.js +95 -20
  53. package/dest/store/message_store.d.ts +5 -1
  54. package/dest/store/message_store.d.ts.map +1 -1
  55. package/dest/store/message_store.js +20 -8
  56. package/dest/test/fake_l1_state.d.ts +9 -1
  57. package/dest/test/fake_l1_state.d.ts.map +1 -1
  58. package/dest/test/fake_l1_state.js +49 -6
  59. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  60. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  61. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  62. package/dest/test/mock_l2_block_source.d.ts +7 -2
  63. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  64. package/dest/test/mock_l2_block_source.js +28 -3
  65. package/dest/test/noop_l1_archiver.d.ts +1 -1
  66. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  67. package/dest/test/noop_l1_archiver.js +0 -1
  68. package/package.json +13 -13
  69. package/src/archiver.ts +43 -20
  70. package/src/config.ts +9 -2
  71. package/src/errors.ts +60 -2
  72. package/src/factory.ts +17 -10
  73. package/src/l1/calldata_retriever.ts +2 -1
  74. package/src/l1/data_retrieval.ts +8 -12
  75. package/src/modules/data_source_base.ts +23 -4
  76. package/src/modules/data_store_updater.ts +68 -95
  77. package/src/modules/instrumentation.ts +19 -7
  78. package/src/modules/l1_synchronizer.ts +159 -160
  79. package/src/modules/validation.ts +2 -2
  80. package/src/store/block_store.ts +301 -74
  81. package/src/store/contract_class_store.ts +8 -106
  82. package/src/store/contract_instance_store.ts +8 -5
  83. package/src/store/kv_archiver_store.ts +56 -32
  84. package/src/store/l2_tips_cache.ts +58 -13
  85. package/src/store/log_store.ts +128 -32
  86. package/src/store/message_store.ts +26 -9
  87. package/src/structs/inbox_message.ts +1 -1
  88. package/src/test/fake_l1_state.ts +68 -9
  89. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  90. package/src/test/mock_l2_block_source.ts +37 -2
  91. package/src/test/noop_l1_archiver.ts +0 -1
@@ -1,29 +1,21 @@
1
1
  import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
- import { Fr } from '@aztec/foundation/curves/bn254';
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
9
  import type { L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
14
- import { type PublishedCheckpoint, validateCheckpoint } from '@aztec/stdlib/checkpoint';
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';
28
20
  import type { L2TipsCache } from '../store/l2_tips_cache.js';
29
21
 
@@ -54,8 +46,7 @@ export class ArchiverDataStoreUpdater {
54
46
  /**
55
47
  * Adds a proposed block to the store with contract class/instance extraction from logs.
56
48
  * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
57
- * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
58
- * and individually broadcasted functions from the block logs.
49
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the block logs.
59
50
  *
60
51
  * @param block - The proposed L2 block to add.
61
52
  * @param pendingChainValidationStatus - Optional validation status to set.
@@ -87,8 +78,7 @@ export class ArchiverDataStoreUpdater {
87
78
  * Reconciles local blocks with incoming checkpoints from L1.
88
79
  * Adds new checkpoints to the store with contract class/instance extraction from logs.
89
80
  * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
90
- * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
91
- * and individually broadcasted functions from the checkpoint block logs.
81
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the checkpoint block logs.
92
82
  *
93
83
  * @param checkpoints - The published checkpoints to add.
94
84
  * @param pendingChainValidationStatus - Optional validation status to set.
@@ -128,6 +118,15 @@ export class ArchiverDataStoreUpdater {
128
118
  return result;
129
119
  }
130
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;
128
+ }
129
+
131
130
  /**
132
131
  * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
133
132
  * This method handles multiple checkpoints but returns after pruning the first conflict found.
@@ -221,6 +220,10 @@ export class ArchiverDataStoreUpdater {
221
220
  }
222
221
 
223
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();
226
+
224
227
  await this.l2TipsCache?.refresh();
225
228
  return result;
226
229
  });
@@ -313,9 +316,6 @@ export class ArchiverDataStoreUpdater {
313
316
  this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
314
317
  this.updateDeployedContractInstances(privateLogs, block.number, operation),
315
318
  this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
316
- operation === Operation.Store
317
- ? this.storeBroadcastedIndividualFunctions(contractClassLogs, block.number)
318
- : Promise.resolve(true),
319
319
  ])
320
320
  ).every(Boolean);
321
321
  }
@@ -332,18 +332,37 @@ export class ArchiverDataStoreUpdater {
332
332
  .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
333
333
  .map(log => ContractClassPublishedEvent.fromLog(log));
334
334
 
335
- const contractClasses = await Promise.all(contractClassPublishedEvents.map(e => e.toContractClassPublic()));
336
- if (contractClasses.length > 0) {
337
- contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
338
- if (operation == Operation.Store) {
339
- // TODO: Will probably want to create some worker threads to compute these bytecode commitments as they are expensive
340
- const commitments = await Promise.all(
341
- contractClasses.map(c => computePublicBytecodeCommitment(c.packedBytecode)),
342
- );
343
- return await this.store.addContractClasses(contractClasses, commitments, blockNum);
344
- } 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()}`));
345
339
  return await this.store.deleteContractClasses(contractClasses, blockNum);
346
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);
347
366
  }
348
367
  return true;
349
368
  }
@@ -356,10 +375,27 @@ export class ArchiverDataStoreUpdater {
356
375
  blockNum: BlockNumber,
357
376
  operation: Operation,
358
377
  ): Promise<boolean> {
359
- const contractInstances = allLogs
378
+ const allInstances = allLogs
360
379
  .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
361
380
  .map(log => ContractInstancePublishedEvent.fromLog(log))
362
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
+
363
399
  if (contractInstances.length > 0) {
364
400
  contractInstances.forEach(c =>
365
401
  this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`),
@@ -398,67 +434,4 @@ export class ArchiverDataStoreUpdater {
398
434
  }
399
435
  return true;
400
436
  }
401
-
402
- /**
403
- * Stores the functions that were broadcasted individually.
404
- *
405
- * @dev Beware that there is not a delete variant of this, since they are added to contract classes
406
- * and will be deleted as part of the class if needed.
407
- */
408
- private async storeBroadcastedIndividualFunctions(
409
- allLogs: ContractClassLog[],
410
- _blockNum: BlockNumber,
411
- ): Promise<boolean> {
412
- // Filter out private and utility function broadcast events
413
- const privateFnEvents = allLogs
414
- .filter(log => PrivateFunctionBroadcastedEvent.isPrivateFunctionBroadcastedEvent(log))
415
- .map(log => PrivateFunctionBroadcastedEvent.fromLog(log));
416
- const utilityFnEvents = allLogs
417
- .filter(log => UtilityFunctionBroadcastedEvent.isUtilityFunctionBroadcastedEvent(log))
418
- .map(log => UtilityFunctionBroadcastedEvent.fromLog(log));
419
-
420
- // Group all events by contract class id
421
- for (const [classIdString, classEvents] of Object.entries(
422
- groupBy([...privateFnEvents, ...utilityFnEvents], e => e.contractClassId.toString()),
423
- )) {
424
- const contractClassId = Fr.fromHexString(classIdString);
425
- const contractClass = await this.store.getContractClass(contractClassId);
426
- if (!contractClass) {
427
- this.log.warn(`Skipping broadcasted functions as contract class ${contractClassId.toString()} was not found`);
428
- continue;
429
- }
430
-
431
- // Split private and utility functions, and filter out invalid ones
432
- const allFns = classEvents.map(e => e.toFunctionWithMembershipProof());
433
- const privateFns = allFns.filter(
434
- (fn): fn is ExecutablePrivateFunctionWithMembershipProof => 'utilityFunctionsTreeRoot' in fn,
435
- );
436
- const utilityFns = allFns.filter(
437
- (fn): fn is UtilityFunctionWithMembershipProof => 'privateFunctionsArtifactTreeRoot' in fn,
438
- );
439
-
440
- const privateFunctionsWithValidity = await Promise.all(
441
- privateFns.map(async fn => ({ fn, valid: await isValidPrivateFunctionMembershipProof(fn, contractClass) })),
442
- );
443
- const validPrivateFns = privateFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
444
- const utilityFunctionsWithValidity = await Promise.all(
445
- utilityFns.map(async fn => ({
446
- fn,
447
- valid: await isValidUtilityFunctionMembershipProof(fn, contractClass),
448
- })),
449
- );
450
- const validUtilityFns = utilityFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
451
- const validFnCount = validPrivateFns.length + validUtilityFns.length;
452
- if (validFnCount !== allFns.length) {
453
- this.log.warn(`Skipping ${allFns.length - validFnCount} invalid functions`);
454
- }
455
-
456
- // Store the functions in the contract class in a single operation
457
- if (validFnCount > 0) {
458
- this.log.verbose(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`);
459
- }
460
- return await this.store.addFunctions(contractClassId, validPrivateFns, validUtilityFns);
461
- }
462
- return true;
463
- }
464
437
  }
@@ -32,6 +32,7 @@ export class ArchiverInstrumentation {
32
32
  private pruneCount: UpDownCounter;
33
33
 
34
34
  private syncDurationPerBlock: Histogram;
35
+ private syncDurationPerCheckpoint: Histogram;
35
36
  private syncBlockCount: UpDownCounter;
36
37
  private manaPerBlock: Histogram;
37
38
  private txsPerBlock: Histogram;
@@ -68,6 +69,8 @@ export class ArchiverInstrumentation {
68
69
 
69
70
  this.syncDurationPerBlock = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_BLOCK);
70
71
 
72
+ this.syncDurationPerCheckpoint = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_CHECKPOINT);
73
+
71
74
  this.syncBlockCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_BLOCK_COUNT);
72
75
 
73
76
  this.manaPerBlock = meter.createHistogram(Metrics.ARCHIVER_MANA_PER_BLOCK);
@@ -113,17 +116,26 @@ export class ArchiverInstrumentation {
113
116
  return this.telemetry.isEnabled();
114
117
  }
115
118
 
116
- public processNewBlocks(syncTimePerBlock: number, blocks: L2Block[]) {
119
+ public processNewProposedBlock(syncTimePerBlock: number, block: L2Block) {
120
+ const attrs = { [Attributes.STATUS]: 'proposed' };
121
+ this.blockHeight.record(block.number, attrs);
117
122
  this.syncDurationPerBlock.record(Math.ceil(syncTimePerBlock));
123
+
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;
133
+ }
134
+
135
+ this.syncDurationPerCheckpoint.record(Math.ceil(syncTimePerCheckpoint));
118
136
  this.blockHeight.record(Math.max(...blocks.map(b => b.number)));
119
137
  this.checkpointHeight.record(Math.max(...blocks.map(b => b.checkpointNumber)));
120
138
  this.syncBlockCount.add(blocks.length);
121
-
122
- for (const block of blocks) {
123
- this.txCount.add(block.body.txEffects.length);
124
- this.txsPerBlock.record(block.body.txEffects.length);
125
- this.manaPerBlock.record(block.header.totalManaUsed.toNumber() / 1e6);
126
- }
127
139
  }
128
140
 
129
141
  public processNewMessages(count: number, syncPerMessageMs: number) {