@aztec/pxe 0.0.1-commit.8afd444 → 0.0.1-commit.8f9871590

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 (108) hide show
  1. package/dest/access_scopes.d.ts +9 -0
  2. package/dest/access_scopes.d.ts.map +1 -0
  3. package/dest/access_scopes.js +6 -0
  4. package/dest/block_synchronizer/block_synchronizer.d.ts +4 -2
  5. package/dest/block_synchronizer/block_synchronizer.d.ts.map +1 -1
  6. package/dest/block_synchronizer/block_synchronizer.js +7 -1
  7. package/dest/contract_function_simulator/contract_function_simulator.d.ts +54 -28
  8. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  9. package/dest/contract_function_simulator/contract_function_simulator.js +170 -64
  10. package/dest/contract_function_simulator/oracle/interfaces.d.ts +2 -2
  11. package/dest/contract_function_simulator/oracle/interfaces.d.ts.map +1 -1
  12. package/dest/contract_function_simulator/oracle/oracle.d.ts +2 -2
  13. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  14. package/dest/contract_function_simulator/oracle/oracle.js +3 -3
  15. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +36 -35
  16. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  17. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +72 -19
  18. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +32 -11
  19. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  20. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +58 -29
  21. package/dest/contract_sync/contract_sync_service.d.ts +43 -0
  22. package/dest/contract_sync/contract_sync_service.d.ts.map +1 -0
  23. package/dest/contract_sync/contract_sync_service.js +97 -0
  24. package/dest/contract_sync/helpers.d.ts +29 -0
  25. package/dest/contract_sync/helpers.d.ts.map +1 -0
  26. package/dest/contract_sync/{index.js → helpers.js} +8 -14
  27. package/dest/debug/pxe_debug_utils.d.ts +14 -10
  28. package/dest/debug/pxe_debug_utils.d.ts.map +1 -1
  29. package/dest/debug/pxe_debug_utils.js +16 -15
  30. package/dest/entrypoints/client/bundle/index.d.ts +3 -1
  31. package/dest/entrypoints/client/bundle/index.d.ts.map +1 -1
  32. package/dest/entrypoints/client/bundle/index.js +2 -0
  33. package/dest/entrypoints/client/bundle/utils.d.ts +1 -1
  34. package/dest/entrypoints/client/bundle/utils.d.ts.map +1 -1
  35. package/dest/entrypoints/client/bundle/utils.js +9 -1
  36. package/dest/entrypoints/client/lazy/index.d.ts +3 -1
  37. package/dest/entrypoints/client/lazy/index.d.ts.map +1 -1
  38. package/dest/entrypoints/client/lazy/index.js +2 -0
  39. package/dest/entrypoints/client/lazy/utils.d.ts +1 -1
  40. package/dest/entrypoints/client/lazy/utils.d.ts.map +1 -1
  41. package/dest/entrypoints/client/lazy/utils.js +9 -1
  42. package/dest/entrypoints/server/index.d.ts +4 -2
  43. package/dest/entrypoints/server/index.d.ts.map +1 -1
  44. package/dest/entrypoints/server/index.js +3 -1
  45. package/dest/entrypoints/server/utils.js +9 -1
  46. package/dest/logs/log_service.d.ts +3 -2
  47. package/dest/logs/log_service.d.ts.map +1 -1
  48. package/dest/logs/log_service.js +5 -10
  49. package/dest/notes/note_service.d.ts +4 -3
  50. package/dest/notes/note_service.d.ts.map +1 -1
  51. package/dest/notes/note_service.js +3 -2
  52. package/dest/notes_filter.d.ts +25 -0
  53. package/dest/notes_filter.d.ts.map +1 -0
  54. package/dest/notes_filter.js +4 -0
  55. package/dest/oracle_version.d.ts +2 -2
  56. package/dest/oracle_version.js +2 -2
  57. package/dest/private_kernel/hints/compute_tx_expiration_timestamp.d.ts +4 -0
  58. package/dest/private_kernel/hints/compute_tx_expiration_timestamp.d.ts.map +1 -0
  59. package/dest/private_kernel/hints/{compute_tx_include_by_timestamp.js → compute_tx_expiration_timestamp.js} +12 -12
  60. package/dest/private_kernel/hints/index.d.ts +1 -1
  61. package/dest/private_kernel/hints/index.js +1 -1
  62. package/dest/private_kernel/private_kernel_execution_prover.js +6 -6
  63. package/dest/pxe.d.ts +69 -23
  64. package/dest/pxe.d.ts.map +1 -1
  65. package/dest/pxe.js +72 -44
  66. package/dest/storage/contract_store/contract_store.js +5 -5
  67. package/dest/storage/note_store/note_store.d.ts +3 -3
  68. package/dest/storage/note_store/note_store.d.ts.map +1 -1
  69. package/dest/storage/note_store/note_store.js +6 -4
  70. package/dest/tagging/get_all_logs_by_tags.d.ts +1 -1
  71. package/dest/tagging/get_all_logs_by_tags.d.ts.map +1 -1
  72. package/dest/tagging/get_all_logs_by_tags.js +17 -3
  73. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.js +4 -4
  74. package/dest/tagging/recipient_sync/utils/find_highest_indexes.js +2 -2
  75. package/package.json +25 -16
  76. package/src/access_scopes.ts +9 -0
  77. package/src/block_synchronizer/block_synchronizer.ts +6 -0
  78. package/src/contract_function_simulator/contract_function_simulator.ts +318 -121
  79. package/src/contract_function_simulator/oracle/interfaces.ts +1 -1
  80. package/src/contract_function_simulator/oracle/oracle.ts +3 -3
  81. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +94 -96
  82. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +100 -28
  83. package/src/contract_sync/contract_sync_service.ts +152 -0
  84. package/src/contract_sync/{index.ts → helpers.ts} +13 -34
  85. package/src/debug/pxe_debug_utils.ts +48 -18
  86. package/src/entrypoints/client/bundle/index.ts +2 -0
  87. package/src/entrypoints/client/bundle/utils.ts +9 -1
  88. package/src/entrypoints/client/lazy/index.ts +2 -0
  89. package/src/entrypoints/client/lazy/utils.ts +9 -1
  90. package/src/entrypoints/server/index.ts +3 -1
  91. package/src/entrypoints/server/utils.ts +7 -7
  92. package/src/logs/log_service.ts +7 -19
  93. package/src/notes/note_service.ts +4 -3
  94. package/src/notes_filter.ts +26 -0
  95. package/src/oracle_version.ts +2 -2
  96. package/src/private_kernel/hints/{compute_tx_include_by_timestamp.ts → compute_tx_expiration_timestamp.ts} +13 -13
  97. package/src/private_kernel/hints/index.ts +1 -1
  98. package/src/private_kernel/private_kernel_execution_prover.ts +6 -6
  99. package/src/pxe.ts +148 -90
  100. package/src/storage/contract_store/contract_store.ts +4 -4
  101. package/src/storage/note_store/note_store.ts +12 -5
  102. package/src/tagging/get_all_logs_by_tags.ts +28 -4
  103. package/src/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.ts +4 -4
  104. package/src/tagging/recipient_sync/utils/find_highest_indexes.ts +2 -2
  105. package/dest/contract_sync/index.d.ts +0 -24
  106. package/dest/contract_sync/index.d.ts.map +0 -1
  107. package/dest/private_kernel/hints/compute_tx_include_by_timestamp.d.ts +0 -4
  108. package/dest/private_kernel/hints/compute_tx_include_by_timestamp.d.ts.map +0 -1
@@ -417,7 +417,7 @@ export class Oracle {
417
417
  return Promise.resolve([]);
418
418
  }
419
419
 
420
- utilityDebugLog(
420
+ async utilityLog(
421
421
  level: ACVMField[],
422
422
  message: ACVMField[],
423
423
  _ignoredFieldsSize: ACVMField[],
@@ -426,8 +426,8 @@ export class Oracle {
426
426
  const levelFr = Fr.fromString(level[0]);
427
427
  const messageStr = message.map(acvmField => String.fromCharCode(Fr.fromString(acvmField).toNumber())).join('');
428
428
  const fieldsFr = fields.map(Fr.fromString);
429
- this.handlerAsMisc().utilityDebugLog(levelFr.toNumber(), messageStr, fieldsFr);
430
- return Promise.resolve([]);
429
+ await this.handlerAsMisc().utilityLog(levelFr.toNumber(), messageStr, fieldsFr);
430
+ return [];
431
431
  }
432
432
 
433
433
  // This function's name is directly hardcoded in `circuit_recorder.ts`. Don't forget to update it there if you
@@ -2,7 +2,6 @@ import { MAX_FR_CALLDATA_TO_ALL_ENQUEUED_CALLS, PRIVATE_CONTEXT_INPUTS_LENGTH }
2
2
  import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import { createLogger } from '@aztec/foundation/log';
4
4
  import { Timer } from '@aztec/foundation/timer';
5
- import type { KeyStore } from '@aztec/key-store';
6
5
  import { type CircuitSimulator, toACVMWitness } from '@aztec/simulator/client';
7
6
  import {
8
7
  type FunctionAbi,
@@ -12,33 +11,23 @@ import {
12
11
  type NoteSelector,
13
12
  countArgumentsSize,
14
13
  } from '@aztec/stdlib/abi';
15
- import type { AuthWitness } from '@aztec/stdlib/auth-witness';
16
14
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
17
15
  import { siloNullifier } from '@aztec/stdlib/hash';
18
- import type { AztecNode } from '@aztec/stdlib/interfaces/client';
19
16
  import { PrivateContextInputs } from '@aztec/stdlib/kernel';
20
17
  import { type ContractClassLog, DirectionalAppTaggingSecret, type PreTag } from '@aztec/stdlib/logs';
21
18
  import { Tag } from '@aztec/stdlib/logs';
22
19
  import { Note, type NoteStatus } from '@aztec/stdlib/note';
23
20
  import {
24
- type BlockHeader,
25
21
  CallContext,
26
- Capsule,
27
22
  CountedContractClassLog,
28
23
  NoteAndSlot,
29
24
  PrivateCallExecutionResult,
30
25
  type TxContext,
31
26
  } from '@aztec/stdlib/tx';
32
27
 
33
- import { ensureContractSynced } from '../../contract_sync/index.js';
28
+ import type { AccessScopes } from '../../access_scopes.js';
29
+ import type { ContractSyncService } from '../../contract_sync/contract_sync_service.js';
34
30
  import { NoteService } from '../../notes/note_service.js';
35
- import type { AddressStore } from '../../storage/address_store/address_store.js';
36
- import type { CapsuleStore } from '../../storage/capsule_store/capsule_store.js';
37
- import type { ContractStore } from '../../storage/contract_store/contract_store.js';
38
- import type { NoteStore } from '../../storage/note_store/note_store.js';
39
- import type { PrivateEventStore } from '../../storage/private_event_store/private_event_store.js';
40
- import type { RecipientTaggingStore } from '../../storage/tagging_store/recipient_tagging_store.js';
41
- import type { SenderAddressBookStore } from '../../storage/tagging_store/sender_address_book_store.js';
42
31
  import type { SenderTaggingStore } from '../../storage/tagging_store/sender_tagging_store.js';
43
32
  import { syncSenderTaggingIndexes } from '../../tagging/index.js';
44
33
  import type { ExecutionNoteCache } from '../execution_note_cache.js';
@@ -47,7 +36,25 @@ import type { HashedValuesCache } from '../hashed_values_cache.js';
47
36
  import { pickNotes } from '../pick_notes.js';
48
37
  import type { IPrivateExecutionOracle, NoteData } from './interfaces.js';
49
38
  import { executePrivateFunction } from './private_execution.js';
50
- import { UtilityExecutionOracle } from './utility_execution_oracle.js';
39
+ import { UtilityExecutionOracle, type UtilityExecutionOracleArgs } from './utility_execution_oracle.js';
40
+
41
+ /** Args for PrivateExecutionOracle constructor. */
42
+ export type PrivateExecutionOracleArgs = Omit<UtilityExecutionOracleArgs, 'contractAddress'> & {
43
+ argsHash: Fr;
44
+ txContext: TxContext;
45
+ callContext: CallContext;
46
+ /** Needed to trigger contract synchronization before nested calls */
47
+ utilityExecutor: (call: FunctionCall, scopes: AccessScopes) => Promise<void>;
48
+ executionCache: HashedValuesCache;
49
+ noteCache: ExecutionNoteCache;
50
+ taggingIndexCache: ExecutionTaggingIndexCache;
51
+ senderTaggingStore: SenderTaggingStore;
52
+ contractSyncService: ContractSyncService;
53
+ totalPublicCalldataCount?: number;
54
+ sideEffectCounter?: number;
55
+ senderForTags?: AztecAddress;
56
+ simulator?: CircuitSimulator;
57
+ };
51
58
 
52
59
  /**
53
60
  * The execution oracle for the private part of a transaction.
@@ -69,56 +76,39 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP
69
76
  private offchainEffects: { data: Fr[] }[] = [];
70
77
  private nestedExecutionResults: PrivateCallExecutionResult[] = [];
71
78
 
72
- constructor(
73
- private readonly argsHash: Fr,
74
- private readonly txContext: TxContext,
75
- private readonly callContext: CallContext,
76
- /** Header of a block whose state is used during private execution (not the block the transaction is included in). */
77
- protected override readonly anchorBlockHeader: BlockHeader,
78
- /** Needed to trigger contract synchronization before nested calls */
79
- private readonly utilityExecutor: (call: FunctionCall) => Promise<void>,
80
- /** List of transient auth witnesses to be used during this simulation */
81
- authWitnesses: AuthWitness[],
82
- capsules: Capsule[],
83
- private readonly executionCache: HashedValuesCache,
84
- private readonly noteCache: ExecutionNoteCache,
85
- private readonly taggingIndexCache: ExecutionTaggingIndexCache,
86
- contractStore: ContractStore,
87
- noteStore: NoteStore,
88
- keyStore: KeyStore,
89
- addressStore: AddressStore,
90
- aztecNode: AztecNode,
91
- private readonly senderTaggingStore: SenderTaggingStore,
92
- recipientTaggingStore: RecipientTaggingStore,
93
- senderAddressBookStore: SenderAddressBookStore,
94
- capsuleStore: CapsuleStore,
95
- privateEventStore: PrivateEventStore,
96
- jobId: string,
97
- private totalPublicCalldataCount: number = 0,
98
- protected sideEffectCounter: number = 0,
99
- log = createLogger('simulator:client_execution_context'),
100
- scopes?: AztecAddress[],
101
- private senderForTags?: AztecAddress,
102
- private simulator?: CircuitSimulator,
103
- ) {
104
- super(
105
- callContext.contractAddress,
106
- authWitnesses,
107
- capsules,
108
- anchorBlockHeader,
109
- contractStore,
110
- noteStore,
111
- keyStore,
112
- addressStore,
113
- aztecNode,
114
- recipientTaggingStore,
115
- senderAddressBookStore,
116
- capsuleStore,
117
- privateEventStore,
118
- jobId,
119
- log,
120
- scopes,
121
- );
79
+ private readonly argsHash: Fr;
80
+ private readonly txContext: TxContext;
81
+ private readonly callContext: CallContext;
82
+ private readonly utilityExecutor: (call: FunctionCall, scopes: AccessScopes) => Promise<void>;
83
+ private readonly executionCache: HashedValuesCache;
84
+ private readonly noteCache: ExecutionNoteCache;
85
+ private readonly taggingIndexCache: ExecutionTaggingIndexCache;
86
+ private readonly senderTaggingStore: SenderTaggingStore;
87
+ private readonly contractSyncService: ContractSyncService;
88
+ private totalPublicCalldataCount: number;
89
+ protected sideEffectCounter: number;
90
+ private senderForTags?: AztecAddress;
91
+ private readonly simulator?: CircuitSimulator;
92
+
93
+ constructor(args: PrivateExecutionOracleArgs) {
94
+ super({
95
+ ...args,
96
+ contractAddress: args.callContext.contractAddress,
97
+ log: args.log ?? createLogger('simulator:client_execution_context'),
98
+ });
99
+ this.argsHash = args.argsHash;
100
+ this.txContext = args.txContext;
101
+ this.callContext = args.callContext;
102
+ this.utilityExecutor = args.utilityExecutor;
103
+ this.executionCache = args.executionCache;
104
+ this.noteCache = args.noteCache;
105
+ this.taggingIndexCache = args.taggingIndexCache;
106
+ this.senderTaggingStore = args.senderTaggingStore;
107
+ this.contractSyncService = args.contractSyncService;
108
+ this.totalPublicCalldataCount = args.totalPublicCalldataCount ?? 0;
109
+ this.sideEffectCounter = args.sideEffectCounter ?? 0;
110
+ this.senderForTags = args.senderForTags;
111
+ this.simulator = args.simulator;
122
112
  }
123
113
 
124
114
  public getPrivateContextInputs(): PrivateContextInputs {
@@ -537,15 +527,22 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP
537
527
 
538
528
  isStaticCall = isStaticCall || this.callContext.isStaticCall;
539
529
 
540
- await ensureContractSynced(
530
+ // When scopes are set and the target contract is a registered account (has keys in the keyStore),
531
+ // expand scopes to include it so nested private calls can sync and read the contract's own notes.
532
+ // We only expand for registered accounts because the log service needs the recipient's keys to derive
533
+ // tagging secrets, which are only available for registered accounts.
534
+ const expandedScopes =
535
+ this.scopes !== 'ALL_SCOPES' && (await this.keyStore.hasAccount(targetContractAddress))
536
+ ? [...this.scopes, targetContractAddress]
537
+ : this.scopes;
538
+
539
+ await this.contractSyncService.ensureContractSynced(
541
540
  targetContractAddress,
542
541
  functionSelector,
543
542
  this.utilityExecutor,
544
- this.aztecNode,
545
- this.contractStore,
546
- this.noteStore,
547
543
  this.anchorBlockHeader,
548
544
  this.jobId,
545
+ expandedScopes,
549
546
  );
550
547
 
551
548
  const targetArtifact = await this.contractStore.getFunctionArtifactWithDebugMetadata(
@@ -557,40 +554,41 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP
557
554
 
558
555
  const derivedCallContext = await this.deriveCallContext(targetContractAddress, targetArtifact, isStaticCall);
559
556
 
560
- const privateExecutionOracle = new PrivateExecutionOracle(
557
+ const privateExecutionOracle = new PrivateExecutionOracle({
561
558
  argsHash,
562
- derivedTxContext,
563
- derivedCallContext,
564
- this.anchorBlockHeader,
565
- this.utilityExecutor,
566
- this.authWitnesses,
567
- this.capsules,
568
- this.executionCache,
569
- this.noteCache,
570
- this.taggingIndexCache,
571
- this.contractStore,
572
- this.noteStore,
573
- this.keyStore,
574
- this.addressStore,
575
- this.aztecNode,
576
- this.senderTaggingStore,
577
- this.recipientTaggingStore,
578
- this.senderAddressBookStore,
579
- this.capsuleStore,
580
- this.privateEventStore,
581
- this.jobId,
582
- this.totalPublicCalldataCount,
559
+ txContext: derivedTxContext,
560
+ callContext: derivedCallContext,
561
+ anchorBlockHeader: this.anchorBlockHeader,
562
+ utilityExecutor: this.utilityExecutor,
563
+ authWitnesses: this.authWitnesses,
564
+ capsules: this.capsules,
565
+ executionCache: this.executionCache,
566
+ noteCache: this.noteCache,
567
+ taggingIndexCache: this.taggingIndexCache,
568
+ contractStore: this.contractStore,
569
+ noteStore: this.noteStore,
570
+ keyStore: this.keyStore,
571
+ addressStore: this.addressStore,
572
+ aztecNode: this.aztecNode,
573
+ senderTaggingStore: this.senderTaggingStore,
574
+ recipientTaggingStore: this.recipientTaggingStore,
575
+ senderAddressBookStore: this.senderAddressBookStore,
576
+ capsuleStore: this.capsuleStore,
577
+ privateEventStore: this.privateEventStore,
578
+ contractSyncService: this.contractSyncService,
579
+ jobId: this.jobId,
580
+ totalPublicCalldataCount: this.totalPublicCalldataCount,
583
581
  sideEffectCounter,
584
- this.log,
585
- this.scopes,
586
- this.senderForTags,
587
- this.simulator,
588
- );
582
+ log: this.log,
583
+ scopes: expandedScopes,
584
+ senderForTags: this.senderForTags,
585
+ simulator: this.simulator!,
586
+ });
589
587
 
590
588
  const setupTime = simulatorSetupTimer.ms();
591
589
 
592
590
  const childExecutionResult = await executePrivateFunction(
593
- this.simulator,
591
+ this.simulator!,
594
592
  privateExecutionOracle,
595
593
  targetArtifact,
596
594
  targetContractAddress,
@@ -3,7 +3,7 @@ import type { BlockNumber } from '@aztec/foundation/branded-types';
3
3
  import { Aes128 } from '@aztec/foundation/crypto/aes128';
4
4
  import { Fr } from '@aztec/foundation/curves/bn254';
5
5
  import { Point } from '@aztec/foundation/curves/grumpkin';
6
- import { LogLevels, applyStringFormatting, createLogger } from '@aztec/foundation/log';
6
+ import { LogLevels, type Logger, applyStringFormatting, createLogger } from '@aztec/foundation/log';
7
7
  import type { MembershipWitness } from '@aztec/foundation/trees';
8
8
  import type { KeyStore } from '@aztec/key-store';
9
9
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
@@ -20,6 +20,7 @@ import type { NoteStatus } from '@aztec/stdlib/note';
20
20
  import { MerkleTreeId, type NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
21
21
  import type { BlockHeader, Capsule } from '@aztec/stdlib/tx';
22
22
 
23
+ import type { AccessScopes } from '../../access_scopes.js';
23
24
  import { EventService } from '../../events/event_service.js';
24
25
  import { LogService } from '../../logs/log_service.js';
25
26
  import { NoteService } from '../../notes/note_service.js';
@@ -40,6 +41,27 @@ import { pickNotes } from '../pick_notes.js';
40
41
  import type { IMiscOracle, IUtilityExecutionOracle, NoteData } from './interfaces.js';
41
42
  import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
42
43
 
44
+ /** Args for UtilityExecutionOracle constructor. */
45
+ export type UtilityExecutionOracleArgs = {
46
+ contractAddress: AztecAddress;
47
+ /** List of transient auth witnesses to be used during this simulation */
48
+ authWitnesses: AuthWitness[];
49
+ capsules: Capsule[]; // TODO(#12425): Rename to transientCapsules
50
+ anchorBlockHeader: BlockHeader;
51
+ contractStore: ContractStore;
52
+ noteStore: NoteStore;
53
+ keyStore: KeyStore;
54
+ addressStore: AddressStore;
55
+ aztecNode: AztecNode;
56
+ recipientTaggingStore: RecipientTaggingStore;
57
+ senderAddressBookStore: SenderAddressBookStore;
58
+ capsuleStore: CapsuleStore;
59
+ privateEventStore: PrivateEventStore;
60
+ jobId: string;
61
+ log?: ReturnType<typeof createLogger>;
62
+ scopes: AccessScopes;
63
+ };
64
+
43
65
  /**
44
66
  * The oracle for an execution of utility contract functions.
45
67
  */
@@ -47,27 +69,43 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
47
69
  isMisc = true as const;
48
70
  isUtility = true as const;
49
71
 
50
- private aztecNrDebugLog = createLogger('aztec-nr:debug_log');
51
-
52
- constructor(
53
- protected readonly contractAddress: AztecAddress,
54
- /** List of transient auth witnesses to be used during this simulation */
55
- protected readonly authWitnesses: AuthWitness[],
56
- protected readonly capsules: Capsule[], // TODO(#12425): Rename to transientCapsules
57
- protected readonly anchorBlockHeader: BlockHeader,
58
- protected readonly contractStore: ContractStore,
59
- protected readonly noteStore: NoteStore,
60
- protected readonly keyStore: KeyStore,
61
- protected readonly addressStore: AddressStore,
62
- protected readonly aztecNode: AztecNode,
63
- protected readonly recipientTaggingStore: RecipientTaggingStore,
64
- protected readonly senderAddressBookStore: SenderAddressBookStore,
65
- protected readonly capsuleStore: CapsuleStore,
66
- protected readonly privateEventStore: PrivateEventStore,
67
- protected readonly jobId: string,
68
- protected log = createLogger('simulator:client_view_context'),
69
- protected readonly scopes?: AztecAddress[],
70
- ) {}
72
+ private contractLogger: Logger | undefined;
73
+
74
+ protected readonly contractAddress: AztecAddress;
75
+ protected readonly authWitnesses: AuthWitness[];
76
+ protected readonly capsules: Capsule[];
77
+ protected readonly anchorBlockHeader: BlockHeader;
78
+ protected readonly contractStore: ContractStore;
79
+ protected readonly noteStore: NoteStore;
80
+ protected readonly keyStore: KeyStore;
81
+ protected readonly addressStore: AddressStore;
82
+ protected readonly aztecNode: AztecNode;
83
+ protected readonly recipientTaggingStore: RecipientTaggingStore;
84
+ protected readonly senderAddressBookStore: SenderAddressBookStore;
85
+ protected readonly capsuleStore: CapsuleStore;
86
+ protected readonly privateEventStore: PrivateEventStore;
87
+ protected readonly jobId: string;
88
+ protected log: ReturnType<typeof createLogger>;
89
+ protected readonly scopes: AccessScopes;
90
+
91
+ constructor(args: UtilityExecutionOracleArgs) {
92
+ this.contractAddress = args.contractAddress;
93
+ this.authWitnesses = args.authWitnesses;
94
+ this.capsules = args.capsules;
95
+ this.anchorBlockHeader = args.anchorBlockHeader;
96
+ this.contractStore = args.contractStore;
97
+ this.noteStore = args.noteStore;
98
+ this.keyStore = args.keyStore;
99
+ this.addressStore = args.addressStore;
100
+ this.aztecNode = args.aztecNode;
101
+ this.recipientTaggingStore = args.recipientTaggingStore;
102
+ this.senderAddressBookStore = args.senderAddressBookStore;
103
+ this.capsuleStore = args.capsuleStore;
104
+ this.privateEventStore = args.privateEventStore;
105
+ this.jobId = args.jobId;
106
+ this.log = args.log ?? createLogger('simulator:client_view_context');
107
+ this.scopes = args.scopes;
108
+ }
71
109
 
72
110
  public utilityAssertCompatibleOracleVersion(version: number): void {
73
111
  if (version !== ORACLE_VERSION) {
@@ -88,8 +126,21 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
88
126
  * @param pkMHash - The master public key hash.
89
127
  * @returns A Promise that resolves to nullifier keys.
90
128
  * @throws If the keys are not registered in the key store.
129
+ * @throws If scopes are defined and the account is not in the scopes.
91
130
  */
92
- public utilityGetKeyValidationRequest(pkMHash: Fr): Promise<KeyValidationRequest> {
131
+ public async utilityGetKeyValidationRequest(pkMHash: Fr): Promise<KeyValidationRequest> {
132
+ // If scopes are defined, check that the key belongs to an account in the scopes.
133
+ if (this.scopes !== 'ALL_SCOPES' && this.scopes.length > 0) {
134
+ let hasAccess = false;
135
+ for (let i = 0; i < this.scopes.length && !hasAccess; i++) {
136
+ if (await this.keyStore.accountHasKey(this.scopes[i], pkMHash)) {
137
+ hasAccess = true;
138
+ }
139
+ }
140
+ if (!hasAccess) {
141
+ throw new Error(`Key validation request denied: no scoped account has a key with hash ${pkMHash.toString()}.`);
142
+ }
143
+ }
93
144
  return this.keyStore.getKeyValidationRequest(pkMHash, this.contractAddress);
94
145
  }
95
146
 
@@ -289,8 +340,13 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
289
340
  * @returns A boolean indicating whether the nullifier exists in the tree or not.
290
341
  */
291
342
  public async utilityCheckNullifierExists(innerNullifier: Fr) {
292
- const nullifier = await siloNullifier(this.contractAddress, innerNullifier!);
293
- const [leafIndex] = await this.aztecNode.findLeavesIndexes('latest', MerkleTreeId.NULLIFIER_TREE, [nullifier]);
343
+ const [nullifier, anchorBlockHash] = await Promise.all([
344
+ siloNullifier(this.contractAddress, innerNullifier!),
345
+ this.anchorBlockHeader.hash(),
346
+ ]);
347
+ const [leafIndex] = await this.aztecNode.findLeavesIndexes(anchorBlockHash, MerkleTreeId.NULLIFIER_TREE, [
348
+ nullifier,
349
+ ]);
294
350
  return leafIndex?.data !== undefined;
295
351
  }
296
352
 
@@ -341,12 +397,28 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
341
397
  return values;
342
398
  }
343
399
 
344
- public utilityDebugLog(level: number, message: string, fields: Fr[]): void {
400
+ /**
401
+ * Returns a per-contract logger whose output is prefixed with `contract_log::<name>(<addrAbbrev>)`.
402
+ */
403
+ async #getContractLogger(): Promise<Logger> {
404
+ if (!this.contractLogger) {
405
+ const addrAbbrev = this.contractAddress.toString().slice(0, 10);
406
+ const name = await this.contractStore.getDebugContractName(this.contractAddress);
407
+ const module = name ? `contract_log::${name}(${addrAbbrev})` : `contract_log::${addrAbbrev}`;
408
+ // Purpose of instanceId is to distinguish logs from different instances of the same component. It makes sense
409
+ // to re-use jobId as instanceId here as executions of different PXE jobs are isolated.
410
+ this.contractLogger = createLogger(module, { instanceId: this.jobId });
411
+ }
412
+ return this.contractLogger;
413
+ }
414
+
415
+ public async utilityLog(level: number, message: string, fields: Fr[]): Promise<void> {
345
416
  if (!LogLevels[level]) {
346
- throw new Error(`Invalid debug log level: ${level}`);
417
+ throw new Error(`Invalid log level: ${level}`);
347
418
  }
348
419
  const levelName = LogLevels[level];
349
- this.aztecNrDebugLog[levelName](`${applyStringFormatting(message, fields)}`);
420
+ const logger = await this.#getContractLogger();
421
+ logger[levelName](`${applyStringFormatting(message, fields)}`);
350
422
  }
351
423
 
352
424
  public async utilityFetchTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr) {
@@ -0,0 +1,152 @@
1
+ import type { Logger } from '@aztec/foundation/log';
2
+ import type { FunctionCall, FunctionSelector } from '@aztec/stdlib/abi';
3
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
4
+ import type { AztecNode } from '@aztec/stdlib/interfaces/client';
5
+ import type { BlockHeader } from '@aztec/stdlib/tx';
6
+
7
+ import type { AccessScopes } from '../access_scopes.js';
8
+ import type { StagedStore } from '../job_coordinator/job_coordinator.js';
9
+ import type { ContractStore } from '../storage/contract_store/contract_store.js';
10
+ import type { NoteStore } from '../storage/note_store/note_store.js';
11
+ import { syncState, verifyCurrentClassId } from './helpers.js';
12
+
13
+ /**
14
+ * Service for syncing the private state of contracts and verifying that the PXE holds the current class artifact.
15
+ * It uses a cache to avoid redundant sync operations - the cache is wiped when the anchor block changes.
16
+ *
17
+ * TODO: The StagedStore naming is broken here. Figure out a better name.
18
+ */
19
+ export class ContractSyncService implements StagedStore {
20
+ readonly storeName = 'contract_sync';
21
+
22
+ // Tracks contracts synced since last wipe. The cache is keyed per individual scope address
23
+ // (`contractAddress:scopeAddress`), or `contractAddress:*` for undefined scopes (all accounts).
24
+ // The value is a promise that resolves when the contract is synced.
25
+ private syncedContracts: Map<string, Promise<void>> = new Map();
26
+
27
+ // Per-job overridden contract addresses - these contracts should not be synced.
28
+ private overriddenContracts: Map<string, Set<string>> = new Map();
29
+
30
+ constructor(
31
+ private aztecNode: AztecNode,
32
+ private contractStore: ContractStore,
33
+ private noteStore: NoteStore,
34
+ private log: Logger,
35
+ ) {}
36
+
37
+ /** Sets contracts that should be skipped during sync for a specific job. */
38
+ setOverriddenContracts(jobId: string, addresses: Set<string>): void {
39
+ this.overriddenContracts.set(jobId, addresses);
40
+ }
41
+
42
+ /**
43
+ * Ensures a contract's private state is synchronized and that the PXE holds the current class artifact.
44
+ * Uses a cache to avoid redundant sync operations - the cache is wiped when the anchor block changes.
45
+ * @param contractAddress - The address of the contract to sync.
46
+ * @param functionToInvokeAfterSync - The function selector that will be called after sync (used to validate it's
47
+ * not sync_state itself).
48
+ * @param utilityExecutor - Executor function for running the sync_state utility function.
49
+ * @param scopes - Access scopes to pass through to the utility executor (affects whose account's private state is discovered).
50
+ */
51
+ async ensureContractSynced(
52
+ contractAddress: AztecAddress,
53
+ functionToInvokeAfterSync: FunctionSelector | null,
54
+ utilityExecutor: (call: FunctionCall, scopes: AccessScopes) => Promise<any>,
55
+ anchorBlockHeader: BlockHeader,
56
+ jobId: string,
57
+ scopes: AccessScopes,
58
+ ): Promise<void> {
59
+ // Skip sync if this contract has an override for this job (overrides are keyed by contract address only)
60
+ const overrides = this.overriddenContracts.get(jobId);
61
+ if (overrides?.has(contractAddress.toString())) {
62
+ return;
63
+ }
64
+
65
+ // Skip sync if we already synced for "all scopes", or if we have an empty list of scopes
66
+ const allScopesKey = toKey(contractAddress, 'ALL_SCOPES');
67
+ const allScopesExisting = this.syncedContracts.get(allScopesKey);
68
+ if (allScopesExisting || (scopes !== 'ALL_SCOPES' && scopes.length == 0)) {
69
+ return;
70
+ }
71
+
72
+ const unsyncedScopes =
73
+ scopes === 'ALL_SCOPES'
74
+ ? scopes
75
+ : scopes.filter(scope => !this.syncedContracts.has(toKey(contractAddress, scope)));
76
+ const unsyncedScopesKeys = toKeys(contractAddress, unsyncedScopes);
77
+
78
+ if (unsyncedScopesKeys.length > 0) {
79
+ // Start sync and store the promise for all unsynced scopes
80
+ const promise = this.#doSync(
81
+ contractAddress,
82
+ functionToInvokeAfterSync,
83
+ utilityExecutor,
84
+ anchorBlockHeader,
85
+ jobId,
86
+ unsyncedScopes,
87
+ ).catch(err => {
88
+ // There was an error syncing the contract, so we remove it from the cache so that it can be retried.
89
+ unsyncedScopesKeys.forEach(key => this.syncedContracts.delete(key));
90
+ throw err;
91
+ });
92
+ unsyncedScopesKeys.forEach(key => this.syncedContracts.set(key, promise));
93
+ }
94
+
95
+ const promises = toKeys(contractAddress, scopes).map(key => this.syncedContracts.get(key)!);
96
+ await Promise.all(promises);
97
+ }
98
+
99
+ async #doSync(
100
+ contractAddress: AztecAddress,
101
+ functionToInvokeAfterSync: FunctionSelector | null,
102
+ utilityExecutor: (call: FunctionCall, scopes: AccessScopes) => Promise<any>,
103
+ anchorBlockHeader: BlockHeader,
104
+ jobId: string,
105
+ scopes: AccessScopes,
106
+ ): Promise<void> {
107
+ this.log.debug(`Syncing contract ${contractAddress}`);
108
+ await Promise.all([
109
+ syncState(
110
+ contractAddress,
111
+ this.contractStore,
112
+ functionToInvokeAfterSync,
113
+ utilityExecutor,
114
+ this.noteStore,
115
+ this.aztecNode,
116
+ anchorBlockHeader,
117
+ jobId,
118
+ scopes,
119
+ ),
120
+ verifyCurrentClassId(contractAddress, this.aztecNode, this.contractStore, anchorBlockHeader),
121
+ ]);
122
+ this.log.debug(`Contract ${contractAddress} synced`);
123
+ }
124
+
125
+ /** Clears sync cache. Called by BlockSynchronizer when anchor block changes. */
126
+ wipe(): void {
127
+ this.log.debug(`Wiping contract sync cache (${this.syncedContracts.size} entries)`);
128
+ this.syncedContracts.clear();
129
+ }
130
+
131
+ commit(jobId: string): Promise<void> {
132
+ // Clear overridden contracts for this job
133
+ this.overriddenContracts.delete(jobId);
134
+ return Promise.resolve();
135
+ }
136
+
137
+ discardStaged(jobId: string): Promise<void> {
138
+ // We clear the synced contracts cache here because, when the job is discarded, any associated database writes from
139
+ // the sync are also undone.
140
+ this.syncedContracts.clear();
141
+ this.overriddenContracts.delete(jobId);
142
+ return Promise.resolve();
143
+ }
144
+ }
145
+
146
+ function toKeys(contract: AztecAddress, scopes: AccessScopes) {
147
+ return scopes === 'ALL_SCOPES' ? [toKey(contract, scopes)] : scopes.map(scope => toKey(contract, scope));
148
+ }
149
+
150
+ function toKey(contract: AztecAddress, scope: AztecAddress | 'ALL_SCOPES') {
151
+ return scope === 'ALL_SCOPES' ? `${contract.toString()}:*` : `${contract.toString()}:${scope.toString()}`;
152
+ }