@aztec/pxe 0.0.1-commit.343b43af6 → 0.0.1-commit.35158ae7e

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 (75) hide show
  1. package/dest/contract_function_simulator/contract_function_simulator.d.ts +9 -3
  2. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  3. package/dest/contract_function_simulator/contract_function_simulator.js +25 -3
  4. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts +5 -5
  5. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts.map +1 -1
  6. package/dest/contract_function_simulator/execution_tagging_index_cache.js +17 -9
  7. package/dest/contract_function_simulator/index.d.ts +2 -1
  8. package/dest/contract_function_simulator/index.d.ts.map +1 -1
  9. package/dest/contract_function_simulator/index.js +1 -0
  10. package/dest/contract_function_simulator/noir-structs/message_tx_context.d.ts +16 -0
  11. package/dest/contract_function_simulator/noir-structs/message_tx_context.d.ts.map +1 -0
  12. package/dest/contract_function_simulator/noir-structs/message_tx_context.js +57 -0
  13. package/dest/contract_function_simulator/oracle/interfaces.d.ts +4 -2
  14. package/dest/contract_function_simulator/oracle/interfaces.d.ts.map +1 -1
  15. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts +9 -0
  16. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts.map +1 -0
  17. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.js +42 -0
  18. package/dest/contract_function_simulator/oracle/oracle.d.ts +4 -2
  19. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  20. package/dest/contract_function_simulator/oracle/oracle.js +36 -5
  21. package/dest/contract_function_simulator/oracle/private_execution.js +4 -2
  22. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +4 -15
  23. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  24. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +4 -17
  25. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +24 -8
  26. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  27. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +94 -17
  28. package/dest/contract_sync/contract_sync_service.d.ts +5 -3
  29. package/dest/contract_sync/contract_sync_service.d.ts.map +1 -1
  30. package/dest/contract_sync/contract_sync_service.js +47 -30
  31. package/dest/messages/message_context_service.d.ts +17 -0
  32. package/dest/messages/message_context_service.d.ts.map +1 -0
  33. package/dest/messages/message_context_service.js +36 -0
  34. package/dest/oracle_version.d.ts +2 -2
  35. package/dest/oracle_version.js +2 -2
  36. package/dest/pxe.d.ts +6 -3
  37. package/dest/pxe.d.ts.map +1 -1
  38. package/dest/pxe.js +33 -19
  39. package/dest/storage/metadata.d.ts +1 -1
  40. package/dest/storage/metadata.js +1 -1
  41. package/dest/storage/tagging_store/sender_tagging_store.d.ts +26 -25
  42. package/dest/storage/tagging_store/sender_tagging_store.d.ts.map +1 -1
  43. package/dest/storage/tagging_store/sender_tagging_store.js +141 -115
  44. package/dest/tagging/index.d.ts +2 -2
  45. package/dest/tagging/index.d.ts.map +1 -1
  46. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +1 -1
  47. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  48. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +10 -1
  49. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +4 -3
  50. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +1 -1
  51. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +20 -10
  52. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +2 -1
  53. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  54. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +24 -11
  55. package/package.json +16 -16
  56. package/src/contract_function_simulator/contract_function_simulator.ts +36 -4
  57. package/src/contract_function_simulator/execution_tagging_index_cache.ts +16 -11
  58. package/src/contract_function_simulator/index.ts +1 -0
  59. package/src/contract_function_simulator/noir-structs/message_tx_context.ts +55 -0
  60. package/src/contract_function_simulator/oracle/interfaces.ts +7 -1
  61. package/src/contract_function_simulator/oracle/legacy_oracle_mappings.ts +135 -0
  62. package/src/contract_function_simulator/oracle/oracle.ts +43 -5
  63. package/src/contract_function_simulator/oracle/private_execution.ts +3 -3
  64. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +5 -21
  65. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +147 -23
  66. package/src/contract_sync/contract_sync_service.ts +67 -38
  67. package/src/messages/message_context_service.ts +45 -0
  68. package/src/oracle_version.ts +2 -2
  69. package/src/pxe.ts +51 -18
  70. package/src/storage/metadata.ts +1 -1
  71. package/src/storage/tagging_store/sender_tagging_store.ts +182 -135
  72. package/src/tagging/index.ts +1 -1
  73. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +19 -1
  74. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +26 -11
  75. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +19 -9
@@ -0,0 +1,135 @@
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
+ import type { ACIRCallback, ACVMField } from '@aztec/simulator/client';
3
+
4
+ import type { Oracle } from './oracle.js';
5
+
6
+ /**
7
+ * Builds legacy oracle name callbacks for pinned protocol contracts whose artifacts are committed and cannot be
8
+ * changed.
9
+ * TODO(F-416): Remove these aliases on v5 when protocol contracts are redeployed.
10
+ */
11
+ export function buildLegacyOracleCallbacks(oracle: Oracle): ACIRCallback {
12
+ return {
13
+ // Simple prefix renames (privateXxx/utilityXxx → aztec_prv_/aztec_utl_)
14
+ utilityLog: (
15
+ level: ACVMField[],
16
+ message: ACVMField[],
17
+ _ignoredFieldsSize: ACVMField[],
18
+ fields: ACVMField[],
19
+ ): Promise<ACVMField[]> => oracle.aztec_utl_log(level, message, _ignoredFieldsSize, fields),
20
+ utilityAssertCompatibleOracleVersion: (version: ACVMField[]): Promise<ACVMField[]> =>
21
+ oracle.aztec_utl_assertCompatibleOracleVersion(version),
22
+ utilityLoadCapsule: (
23
+ contractAddress: ACVMField[],
24
+ slot: ACVMField[],
25
+ tSize: ACVMField[],
26
+ ): Promise<(ACVMField | ACVMField[])[]> => oracle.aztec_utl_loadCapsule(contractAddress, slot, tSize),
27
+ privateStoreInExecutionCache: (values: ACVMField[], hash: ACVMField[]): Promise<ACVMField[]> =>
28
+ oracle.aztec_prv_storeInExecutionCache(values, hash),
29
+ privateLoadFromExecutionCache: (returnsHash: ACVMField[]): Promise<ACVMField[][]> =>
30
+ oracle.aztec_prv_loadFromExecutionCache(returnsHash),
31
+ privateCallPrivateFunction: (
32
+ contractAddress: ACVMField[],
33
+ functionSelector: ACVMField[],
34
+ argsHash: ACVMField[],
35
+ sideEffectCounter: ACVMField[],
36
+ isStaticCall: ACVMField[],
37
+ ): Promise<ACVMField[][]> =>
38
+ oracle.aztec_prv_callPrivateFunction(
39
+ contractAddress,
40
+ functionSelector,
41
+ argsHash,
42
+ sideEffectCounter,
43
+ isStaticCall,
44
+ ),
45
+ privateIsNullifierPending: (innerNullifier: ACVMField[], contractAddress: ACVMField[]): Promise<ACVMField[]> =>
46
+ oracle.aztec_prv_isNullifierPending(innerNullifier, contractAddress),
47
+ privateNotifyCreatedNullifier: (innerNullifier: ACVMField[]): Promise<ACVMField[]> =>
48
+ oracle.aztec_prv_notifyCreatedNullifier(innerNullifier),
49
+ privateNotifyCreatedContractClassLog: (
50
+ contractAddress: ACVMField[],
51
+ message: ACVMField[],
52
+ length: ACVMField[],
53
+ counter: ACVMField[],
54
+ ): Promise<ACVMField[]> =>
55
+ oracle.aztec_prv_notifyCreatedContractClassLog(contractAddress, message, length, counter),
56
+ utilityGetUtilityContext: (): Promise<(ACVMField | ACVMField[])[]> => oracle.aztec_utl_getUtilityContext(),
57
+ utilityStorageRead: (
58
+ blockHash: ACVMField[],
59
+ contractAddress: ACVMField[],
60
+ startStorageSlot: ACVMField[],
61
+ numberOfElements: ACVMField[],
62
+ ): Promise<ACVMField[][]> =>
63
+ oracle.aztec_utl_storageRead(blockHash, contractAddress, startStorageSlot, numberOfElements),
64
+ utilityStoreCapsule: (
65
+ contractAddress: ACVMField[],
66
+ slot: ACVMField[],
67
+ capsule: ACVMField[],
68
+ ): Promise<ACVMField[]> => oracle.aztec_utl_storeCapsule(contractAddress, slot, capsule),
69
+ utilityCopyCapsule: (
70
+ contractAddress: ACVMField[],
71
+ srcSlot: ACVMField[],
72
+ dstSlot: ACVMField[],
73
+ numEntries: ACVMField[],
74
+ ): Promise<ACVMField[]> => oracle.aztec_utl_copyCapsule(contractAddress, srcSlot, dstSlot, numEntries),
75
+ utilityDeleteCapsule: (contractAddress: ACVMField[], slot: ACVMField[]): Promise<ACVMField[]> =>
76
+ oracle.aztec_utl_deleteCapsule(contractAddress, slot),
77
+ utilityGetSharedSecret: (
78
+ address: ACVMField[],
79
+ ephPKField0: ACVMField[],
80
+ ephPKField1: ACVMField[],
81
+ ephPKField2: ACVMField[],
82
+ ): Promise<ACVMField[]> => oracle.aztec_utl_getSharedSecret(address, ephPKField0, ephPKField1, ephPKField2),
83
+ utilityFetchTaggedLogs: (pendingTaggedLogArrayBaseSlot: ACVMField[]): Promise<ACVMField[]> =>
84
+ oracle.aztec_utl_fetchTaggedLogs(pendingTaggedLogArrayBaseSlot),
85
+ utilityBulkRetrieveLogs: (
86
+ contractAddress: ACVMField[],
87
+ logRetrievalRequestsArrayBaseSlot: ACVMField[],
88
+ logRetrievalResponsesArrayBaseSlot: ACVMField[],
89
+ ): Promise<ACVMField[]> =>
90
+ oracle.aztec_utl_bulkRetrieveLogs(
91
+ contractAddress,
92
+ logRetrievalRequestsArrayBaseSlot,
93
+ logRetrievalResponsesArrayBaseSlot,
94
+ ),
95
+ utilityGetL1ToL2MembershipWitness: (
96
+ contractAddress: ACVMField[],
97
+ messageHash: ACVMField[],
98
+ secret: ACVMField[],
99
+ ): Promise<(ACVMField | ACVMField[])[]> =>
100
+ oracle.aztec_utl_getL1ToL2MembershipWitness(contractAddress, messageHash, secret),
101
+ utilityEmitOffchainEffect: (data: ACVMField[]): Promise<ACVMField[]> => oracle.aztec_utl_emitOffchainEffect(data),
102
+ // Adapter: old 3-param signature → new 5-param with injected constants.
103
+ // Values derived from: MAX_MESSAGE_CONTENT_LEN(11) - RESERVED_FIELDS (3 for notes, 1 for events).
104
+ utilityValidateAndStoreEnqueuedNotesAndEvents: (
105
+ contractAddress: ACVMField[],
106
+ noteValidationRequestsArrayBaseSlot: ACVMField[],
107
+ eventValidationRequestsArrayBaseSlot: ACVMField[],
108
+ ): Promise<ACVMField[]> =>
109
+ oracle.aztec_utl_validateAndStoreEnqueuedNotesAndEvents(
110
+ contractAddress,
111
+ noteValidationRequestsArrayBaseSlot,
112
+ eventValidationRequestsArrayBaseSlot,
113
+ [new Fr(8).toString()],
114
+ [new Fr(10).toString()],
115
+ ),
116
+ // Renames (same signature, different oracle name)
117
+ privateNotifySetMinRevertibleSideEffectCounter: (counter: ACVMField[]): Promise<ACVMField[]> =>
118
+ oracle.aztec_prv_notifyRevertiblePhaseStart(counter),
119
+ privateIsSideEffectCounterRevertible: (sideEffectCounter: ACVMField[]): Promise<ACVMField[]> =>
120
+ oracle.aztec_prv_inRevertiblePhase(sideEffectCounter),
121
+ // Signature changes: old 4-param oracles → new 1-param validatePublicCalldata
122
+ privateNotifyEnqueuedPublicFunctionCall: (
123
+ _contractAddress: ACVMField[],
124
+ calldataHash: ACVMField[],
125
+ _sideEffectCounter: ACVMField[],
126
+ _isStaticCall: ACVMField[],
127
+ ): Promise<ACVMField[]> => oracle.aztec_prv_validatePublicCalldata(calldataHash),
128
+ privateNotifySetPublicTeardownFunctionCall: (
129
+ _contractAddress: ACVMField[],
130
+ calldataHash: ACVMField[],
131
+ _sideEffectCounter: ACVMField[],
132
+ _isStaticCall: ACVMField[],
133
+ ): Promise<ACVMField[]> => oracle.aztec_prv_validatePublicCalldata(calldataHash),
134
+ };
135
+ }
@@ -16,6 +16,7 @@ import { BlockHash } from '@aztec/stdlib/block';
16
16
  import { ContractClassLog, ContractClassLogFields } from '@aztec/stdlib/logs';
17
17
 
18
18
  import type { IMiscOracle, IPrivateExecutionOracle, IUtilityExecutionOracle } from './interfaces.js';
19
+ import { buildLegacyOracleCallbacks } from './legacy_oracle_mappings.js';
19
20
  import { packAsHintedNote } from './note_packing_utils.js';
20
21
 
21
22
  export class UnavailableOracleError extends Error {
@@ -85,11 +86,13 @@ export class Oracle {
85
86
  });
86
87
 
87
88
  // Build callback object and return it
88
- return oracleNames.reduce((acc, name) => {
89
+ const callback = oracleNames.reduce((acc, name) => {
89
90
  const method = this[name as keyof Omit<Oracle, (typeof excludedProps)[number]>];
90
91
  acc[name] = method.bind(this);
91
92
  return acc;
92
93
  }, {} as ACIRCallback);
94
+
95
+ return { ...callback, ...buildLegacyOracleCallbacks(this) };
93
96
  }
94
97
 
95
98
  // eslint-disable-next-line camelcase
@@ -526,6 +529,20 @@ export class Oracle {
526
529
  return [];
527
530
  }
528
531
 
532
+ // eslint-disable-next-line camelcase
533
+ async aztec_utl_utilityResolveMessageContexts(
534
+ [contractAddress]: ACVMField[],
535
+ [messageContextRequestsArrayBaseSlot]: ACVMField[],
536
+ [messageContextResponsesArrayBaseSlot]: ACVMField[],
537
+ ): Promise<ACVMField[]> {
538
+ await this.handlerAsUtility().utilityResolveMessageContexts(
539
+ AztecAddress.fromString(contractAddress),
540
+ Fr.fromString(messageContextRequestsArrayBaseSlot),
541
+ Fr.fromString(messageContextResponsesArrayBaseSlot),
542
+ );
543
+ return [];
544
+ }
545
+
529
546
  // eslint-disable-next-line camelcase
530
547
  async aztec_utl_storeCapsule(
531
548
  [contractAddress]: ACVMField[],
@@ -588,7 +605,7 @@ export class Oracle {
588
605
  }
589
606
 
590
607
  // eslint-disable-next-line camelcase
591
- async aztec_utl_aes128Decrypt(
608
+ async aztec_utl_tryAes128Decrypt(
592
609
  ciphertextBVecStorage: ACVMField[],
593
610
  [ciphertextLength]: ACVMField[],
594
611
  iv: ACVMField[],
@@ -598,8 +615,15 @@ export class Oracle {
598
615
  const ivBuffer = fromUintArray(iv, 8);
599
616
  const symKeyBuffer = fromUintArray(symKey, 8);
600
617
 
601
- const plaintext = await this.handlerAsUtility().aes128Decrypt(ciphertext, ivBuffer, symKeyBuffer);
602
- return bufferToBoundedVec(plaintext, ciphertextBVecStorage.length);
618
+ // Noir Option<BoundedVec> is encoded as [is_some: Field, storage: Field[], length: Field].
619
+ try {
620
+ const plaintext = await this.handlerAsUtility().aes128Decrypt(ciphertext, ivBuffer, symKeyBuffer);
621
+ const [storage, length] = bufferToBoundedVec(plaintext, ciphertextBVecStorage.length);
622
+ return [toACVMField(1), storage, length];
623
+ } catch {
624
+ const zeroStorage = Array(ciphertextBVecStorage.length).fill(toACVMField(0));
625
+ return [toACVMField(0), zeroStorage, toACVMField(0)];
626
+ }
603
627
  }
604
628
 
605
629
  // eslint-disable-next-line camelcase
@@ -616,9 +640,23 @@ export class Oracle {
616
640
  return secret.toFields().map(toACVMField);
617
641
  }
618
642
 
643
+ // eslint-disable-next-line camelcase
644
+ aztec_utl_invalidateContractSyncCache(
645
+ [contractAddress]: ACVMField[],
646
+ scopes: ACVMField[],
647
+ [scopeCount]: ACVMField[],
648
+ ): Promise<ACVMField[]> {
649
+ const scopeAddresses = scopes.slice(0, +scopeCount).map(s => AztecAddress.fromField(Fr.fromString(s)));
650
+ this.handlerAsUtility().invalidateContractSyncCache(
651
+ AztecAddress.fromField(Fr.fromString(contractAddress)),
652
+ scopeAddresses,
653
+ );
654
+ return Promise.resolve([]);
655
+ }
656
+
619
657
  // eslint-disable-next-line camelcase
620
658
  async aztec_utl_emitOffchainEffect(data: ACVMField[]) {
621
- await this.handlerAsPrivate().emitOffchainEffect(data.map(Fr.fromString));
659
+ await this.handlerAsUtility().emitOffchainEffect(data.map(Fr.fromString));
622
660
  return [];
623
661
  }
624
662
 
@@ -81,7 +81,7 @@ export async function executePrivateFunction(
81
81
  const newNotes = privateExecutionOracle.getNewNotes();
82
82
  const noteHashNullifierCounterMap = privateExecutionOracle.getNoteHashNullifierCounterMap();
83
83
  const offchainEffects = privateExecutionOracle.getOffchainEffects();
84
- const preTags = privateExecutionOracle.getUsedPreTags();
84
+ const taggingIndexRanges = privateExecutionOracle.getUsedTaggingIndexRanges();
85
85
  const nestedExecutionResults = privateExecutionOracle.getNestedExecutionResults();
86
86
 
87
87
  let timerSubtractionList = nestedExecutionResults;
@@ -103,8 +103,8 @@ export async function executePrivateFunction(
103
103
  newNotes,
104
104
  noteHashNullifierCounterMap,
105
105
  rawReturnValues,
106
- offchainEffects,
107
- preTags,
106
+ offchainEffects.map(e => ({ data: e.data })),
107
+ taggingIndexRanges,
108
108
  nestedExecutionResults,
109
109
  contractClassLogs,
110
110
  {
@@ -14,7 +14,7 @@ import {
14
14
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
15
15
  import { siloNullifier } from '@aztec/stdlib/hash';
16
16
  import { PrivateContextInputs } from '@aztec/stdlib/kernel';
17
- import { type ContractClassLog, ExtendedDirectionalAppTaggingSecret, type PreTag } from '@aztec/stdlib/logs';
17
+ import { type ContractClassLog, ExtendedDirectionalAppTaggingSecret, type TaggingIndexRange } from '@aztec/stdlib/logs';
18
18
  import { Tag } from '@aztec/stdlib/logs';
19
19
  import { Note, type NoteStatus } from '@aztec/stdlib/note';
20
20
  import {
@@ -26,7 +26,6 @@ import {
26
26
  } from '@aztec/stdlib/tx';
27
27
 
28
28
  import type { AccessScopes } from '../../access_scopes.js';
29
- import type { ContractSyncService } from '../../contract_sync/contract_sync_service.js';
30
29
  import { NoteService } from '../../notes/note_service.js';
31
30
  import type { SenderTaggingStore } from '../../storage/tagging_store/sender_tagging_store.js';
32
31
  import { syncSenderTaggingIndexes } from '../../tagging/index.js';
@@ -49,7 +48,6 @@ export type PrivateExecutionOracleArgs = Omit<UtilityExecutionOracleArgs, 'contr
49
48
  noteCache: ExecutionNoteCache;
50
49
  taggingIndexCache: ExecutionTaggingIndexCache;
51
50
  senderTaggingStore: SenderTaggingStore;
52
- contractSyncService: ContractSyncService;
53
51
  totalPublicCalldataCount?: number;
54
52
  sideEffectCounter?: number;
55
53
  senderForTags?: AztecAddress;
@@ -73,7 +71,6 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP
73
71
  private newNotes: NoteAndSlot[] = [];
74
72
  private noteHashNullifierCounterMap: Map<number, number> = new Map();
75
73
  private contractClassLogs: CountedContractClassLog[] = [];
76
- private offchainEffects: { data: Fr[] }[] = [];
77
74
  private nestedExecutionResults: PrivateCallExecutionResult[] = [];
78
75
 
79
76
  private readonly argsHash: Fr;
@@ -84,7 +81,6 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP
84
81
  private readonly noteCache: ExecutionNoteCache;
85
82
  private readonly taggingIndexCache: ExecutionTaggingIndexCache;
86
83
  private readonly senderTaggingStore: SenderTaggingStore;
87
- private readonly contractSyncService: ContractSyncService;
88
84
  private totalPublicCalldataCount: number;
89
85
  protected sideEffectCounter: number;
90
86
  private senderForTags?: AztecAddress;
@@ -104,7 +100,6 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP
104
100
  this.noteCache = args.noteCache;
105
101
  this.taggingIndexCache = args.taggingIndexCache;
106
102
  this.senderTaggingStore = args.senderTaggingStore;
107
- this.contractSyncService = args.contractSyncService;
108
103
  this.totalPublicCalldataCount = args.totalPublicCalldataCount ?? 0;
109
104
  this.sideEffectCounter = args.sideEffectCounter ?? 0;
110
105
  this.senderForTags = args.senderForTags;
@@ -159,17 +154,10 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP
159
154
  }
160
155
 
161
156
  /**
162
- * Return the offchain effects emitted during this execution.
157
+ * Returns the tagging index ranges that were used in this execution (and that need to be stored in the db).
163
158
  */
164
- public getOffchainEffects() {
165
- return this.offchainEffects;
166
- }
167
-
168
- /**
169
- * Returns the pre-tags that were used in this execution (and that need to be stored in the db).
170
- */
171
- public getUsedPreTags(): PreTag[] {
172
- return this.taggingIndexCache.getUsedPreTags();
159
+ public getUsedTaggingIndexRanges(): TaggingIndexRange[] {
160
+ return this.taggingIndexCache.getUsedTaggingIndexRanges();
173
161
  }
174
162
 
175
163
  /**
@@ -569,6 +557,7 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP
569
557
  senderAddressBookStore: this.senderAddressBookStore,
570
558
  capsuleStore: this.capsuleStore,
571
559
  privateEventStore: this.privateEventStore,
560
+ messageContextService: this.messageContextService,
572
561
  contractSyncService: this.contractSyncService,
573
562
  jobId: this.jobId,
574
563
  totalPublicCalldataCount: this.totalPublicCalldataCount,
@@ -653,9 +642,4 @@ export class PrivateExecutionOracle extends UtilityExecutionOracle implements IP
653
642
  public getDebugFunctionName() {
654
643
  return this.contractStore.getDebugFunctionName(this.contractAddress, this.callContext.functionSelector);
655
644
  }
656
-
657
- public emitOffchainEffect(data: Fr[]): Promise<void> {
658
- this.offchainEffects.push({ data });
659
- return Promise.resolve();
660
- }
661
645
  }
@@ -6,6 +6,7 @@ import { Point } from '@aztec/foundation/curves/grumpkin';
6
6
  import { LogLevels, type Logger, createLogger } from '@aztec/foundation/log';
7
7
  import type { MembershipWitness } from '@aztec/foundation/trees';
8
8
  import type { KeyStore } from '@aztec/key-store';
9
+ import { isProtocolContract } from '@aztec/protocol-contracts';
9
10
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
10
11
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
11
12
  import { BlockHash } from '@aztec/stdlib/block';
@@ -18,12 +19,14 @@ import { deriveEcdhSharedSecret } from '@aztec/stdlib/logs';
18
19
  import { getNonNullifiedL1ToL2MessageWitness } from '@aztec/stdlib/messaging';
19
20
  import type { NoteStatus } from '@aztec/stdlib/note';
20
21
  import { MerkleTreeId, type NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
21
- import type { BlockHeader, Capsule } from '@aztec/stdlib/tx';
22
+ import type { BlockHeader, Capsule, OffchainEffect } from '@aztec/stdlib/tx';
22
23
 
23
24
  import type { AccessScopes } from '../../access_scopes.js';
24
25
  import { createContractLogger, logContractMessage } from '../../contract_logging.js';
26
+ import type { ContractSyncService } from '../../contract_sync/contract_sync_service.js';
25
27
  import { EventService } from '../../events/event_service.js';
26
28
  import { LogService } from '../../logs/log_service.js';
29
+ import { MessageContextService } from '../../messages/message_context_service.js';
27
30
  import { NoteService } from '../../notes/note_service.js';
28
31
  import { ORACLE_VERSION } from '../../oracle_version.js';
29
32
  import type { AddressStore } from '../../storage/address_store/address_store.js';
@@ -36,6 +39,7 @@ import type { SenderAddressBookStore } from '../../storage/tagging_store/sender_
36
39
  import { EventValidationRequest } from '../noir-structs/event_validation_request.js';
37
40
  import { LogRetrievalRequest } from '../noir-structs/log_retrieval_request.js';
38
41
  import { LogRetrievalResponse } from '../noir-structs/log_retrieval_response.js';
42
+ import { MessageTxContext } from '../noir-structs/message_tx_context.js';
39
43
  import { NoteValidationRequest } from '../noir-structs/note_validation_request.js';
40
44
  import { UtilityContext } from '../noir-structs/utility_context.js';
41
45
  import { pickNotes } from '../pick_notes.js';
@@ -58,6 +62,8 @@ export type UtilityExecutionOracleArgs = {
58
62
  senderAddressBookStore: SenderAddressBookStore;
59
63
  capsuleStore: CapsuleStore;
60
64
  privateEventStore: PrivateEventStore;
65
+ messageContextService: MessageContextService;
66
+ contractSyncService: ContractSyncService;
61
67
  jobId: string;
62
68
  log?: ReturnType<typeof createLogger>;
63
69
  scopes: AccessScopes;
@@ -71,6 +77,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
71
77
  isUtility = true as const;
72
78
 
73
79
  private contractLogger: Logger | undefined;
80
+ private offchainEffects: OffchainEffect[] = [];
74
81
 
75
82
  protected readonly contractAddress: AztecAddress;
76
83
  protected readonly authWitnesses: AuthWitness[];
@@ -85,6 +92,8 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
85
92
  protected readonly senderAddressBookStore: SenderAddressBookStore;
86
93
  protected readonly capsuleStore: CapsuleStore;
87
94
  protected readonly privateEventStore: PrivateEventStore;
95
+ protected readonly messageContextService: MessageContextService;
96
+ protected readonly contractSyncService: ContractSyncService;
88
97
  protected readonly jobId: string;
89
98
  protected logger: ReturnType<typeof createLogger>;
90
99
  protected readonly scopes: AccessScopes;
@@ -103,12 +112,29 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
103
112
  this.senderAddressBookStore = args.senderAddressBookStore;
104
113
  this.capsuleStore = args.capsuleStore;
105
114
  this.privateEventStore = args.privateEventStore;
115
+ this.messageContextService = args.messageContextService;
116
+ this.contractSyncService = args.contractSyncService;
106
117
  this.jobId = args.jobId;
107
118
  this.logger = args.log ?? createLogger('simulator:client_view_context');
108
119
  this.scopes = args.scopes;
109
120
  }
110
121
 
111
122
  public assertCompatibleOracleVersion(version: number): void {
123
+ // TODO(F-416): Remove this hack on v5 when protocol contracts are redeployed.
124
+ // Protocol contracts/canonical contracts shipped with committed bytecode that cannot be changed. Assert they use
125
+ // the expected pinned version or the current one. We want to allow for both the pinned and the current versions
126
+ // because we want this code to work with both the pinned and unpinned version since some branches do not have the
127
+ // pinned contracts (like e.g. next)
128
+ const LEGACY_ORACLE_VERSION = 12;
129
+ if (isProtocolContract(this.contractAddress)) {
130
+ if (version !== LEGACY_ORACLE_VERSION && version !== ORACLE_VERSION) {
131
+ throw new Error(
132
+ `Expected legacy oracle version ${LEGACY_ORACLE_VERSION} or current oracle version ${ORACLE_VERSION} for alpha payload contract at ${this.contractAddress}, got ${version}.`,
133
+ );
134
+ }
135
+ return;
136
+ }
137
+
112
138
  if (version !== ORACLE_VERSION) {
113
139
  throw new Error(`Incompatible oracle version. Expected version ${ORACLE_VERSION}, got ${version}.`);
114
140
  }
@@ -147,16 +173,18 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
147
173
 
148
174
  /**
149
175
  * Fetches the index and sibling path of a leaf at a given block from the note hash tree.
150
- * @param anchorBlockHash - The hash of a block that contains the note hash tree root in which to find the membership
151
- * witness.
176
+ * @param blockHash - The hash of a block that contains the note hash tree root in which to find the
177
+ * membership witness.
152
178
  * @param noteHash - The note hash to find in the note hash tree.
153
179
  * @returns The membership witness containing the leaf index and sibling path
154
180
  */
155
181
  public getNoteHashMembershipWitness(
156
- anchorBlockHash: BlockHash,
182
+ blockHash: BlockHash,
157
183
  noteHash: Fr,
158
184
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
159
- return this.aztecNode.getNoteHashMembershipWitness(anchorBlockHash, noteHash);
185
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
186
+ this.aztecNode.getNoteHashMembershipWitness(blockHash, noteHash),
187
+ );
160
188
  }
161
189
 
162
190
  /**
@@ -165,16 +193,21 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
165
193
  * Block hashes are the leaves of the archive tree. Each time a new block is added to the chain,
166
194
  * its block hash is appended as a new leaf to the archive tree.
167
195
  *
168
- * @param anchorBlockHash - The hash of a block that contains the archive tree root in which to find the membership
196
+ * @param referenceBlockHash - The hash of a block that contains the archive tree root in which to find the membership
169
197
  * witness.
170
198
  * @param blockHash - The block hash to find in the archive tree.
171
199
  * @returns The membership witness containing the leaf index and sibling path
172
200
  */
173
201
  public getBlockHashMembershipWitness(
174
- anchorBlockHash: BlockHash,
202
+ referenceBlockHash: BlockHash,
175
203
  blockHash: BlockHash,
176
204
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
177
- return this.aztecNode.getBlockHashMembershipWitness(anchorBlockHash, blockHash);
205
+ // Note that we validate that the reference block hash is at or before the anchor block - we don't test the block
206
+ // hash at all. If the block hash did not exist by the reference block hash, then the node will not return the
207
+ // membership witness as there is none.
208
+ return this.#queryWithBlockHashNotAfterAnchor(referenceBlockHash, () =>
209
+ this.aztecNode.getBlockHashMembershipWitness(referenceBlockHash, blockHash),
210
+ );
178
211
  }
179
212
 
180
213
  /**
@@ -187,7 +220,9 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
187
220
  blockHash: BlockHash,
188
221
  nullifier: Fr,
189
222
  ): Promise<NullifierMembershipWitness | undefined> {
190
- return this.aztecNode.getNullifierMembershipWitness(blockHash, nullifier);
223
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
224
+ this.aztecNode.getNullifierMembershipWitness(blockHash, nullifier),
225
+ );
191
226
  }
192
227
 
193
228
  /**
@@ -203,7 +238,9 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
203
238
  blockHash: BlockHash,
204
239
  nullifier: Fr,
205
240
  ): Promise<NullifierMembershipWitness | undefined> {
206
- return this.aztecNode.getLowNullifierMembershipWitness(blockHash, nullifier);
241
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
242
+ this.aztecNode.getLowNullifierMembershipWitness(blockHash, nullifier),
243
+ );
207
244
  }
208
245
 
209
246
  /**
@@ -213,7 +250,9 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
213
250
  * @returns - The witness
214
251
  */
215
252
  public getPublicDataWitness(blockHash: BlockHash, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
216
- return this.aztecNode.getPublicDataWitness(blockHash, leafSlot);
253
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
254
+ this.aztecNode.getPublicDataWitness(blockHash, leafSlot),
255
+ );
217
256
  }
218
257
 
219
258
  /**
@@ -354,7 +393,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
354
393
  }
355
394
 
356
395
  /**
357
- * Fetches a message from the executionStore, given its key.
396
+ * Returns the membership witness of an un-nullified L1 to L2 message.
358
397
  * @param contractAddress - Address of a contract by which the message was emitted.
359
398
  * @param messageHash - Hash of the message.
360
399
  * @param secret - Secret used to compute a nullifier.
@@ -367,6 +406,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
367
406
  contractAddress,
368
407
  messageHash,
369
408
  secret,
409
+ await this.anchorBlockHeader.hash(),
370
410
  );
371
411
 
372
412
  return new MessageLoadOracleInputs(messageIndex, siblingPath);
@@ -379,25 +419,27 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
379
419
  * @param startStorageSlot - The starting storage slot.
380
420
  * @param numberOfElements - Number of elements to read from the starting storage slot.
381
421
  */
382
- public async storageRead(
422
+ public storageRead(
383
423
  blockHash: BlockHash,
384
424
  contractAddress: AztecAddress,
385
425
  startStorageSlot: Fr,
386
426
  numberOfElements: number,
387
427
  ) {
388
- const slots = Array(numberOfElements)
389
- .fill(0)
390
- .map((_, i) => new Fr(startStorageSlot.value + BigInt(i)));
428
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, async () => {
429
+ const slots = Array(numberOfElements)
430
+ .fill(0)
431
+ .map((_, i) => new Fr(startStorageSlot.value + BigInt(i)));
391
432
 
392
- const values = await Promise.all(
393
- slots.map(storageSlot => this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)),
394
- );
433
+ const values = await Promise.all(
434
+ slots.map(storageSlot => this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)),
435
+ );
395
436
 
396
- this.logger.debug(
397
- `Oracle storage read: slots=[${slots.map(slot => slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`,
398
- );
437
+ this.logger.debug(
438
+ `Oracle storage read: slots=[${slots.map(slot => slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`,
439
+ );
399
440
 
400
- return values;
441
+ return values;
442
+ });
401
443
  }
402
444
 
403
445
  /**
@@ -550,6 +592,47 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
550
592
  );
551
593
  }
552
594
 
595
+ public async utilityResolveMessageContexts(
596
+ contractAddress: AztecAddress,
597
+ messageContextRequestsArrayBaseSlot: Fr,
598
+ messageContextResponsesArrayBaseSlot: Fr,
599
+ ) {
600
+ try {
601
+ if (!this.contractAddress.equals(contractAddress)) {
602
+ throw new Error(`Got a message context request from ${contractAddress}, expected ${this.contractAddress}`);
603
+ }
604
+ const requestCapsules = await this.capsuleStore.readCapsuleArray(
605
+ contractAddress,
606
+ messageContextRequestsArrayBaseSlot,
607
+ this.jobId,
608
+ );
609
+
610
+ const txHashes = requestCapsules.map((fields, i) => {
611
+ if (fields.length !== 1) {
612
+ throw new Error(
613
+ `Malformed message context request at index ${i}: expected 1 field (tx hash), got ${fields.length}`,
614
+ );
615
+ }
616
+ return fields[0];
617
+ });
618
+
619
+ const maybeMessageContexts = await this.messageContextService.resolveMessageContexts(
620
+ txHashes,
621
+ this.anchorBlockHeader.getBlockNumber(),
622
+ );
623
+
624
+ // Leave response in response capsule array.
625
+ await this.capsuleStore.setCapsuleArray(
626
+ contractAddress,
627
+ messageContextResponsesArrayBaseSlot,
628
+ maybeMessageContexts.map(MessageTxContext.toSerializedOption),
629
+ this.jobId,
630
+ );
631
+ } finally {
632
+ await this.capsuleStore.setCapsuleArray(contractAddress, messageContextRequestsArrayBaseSlot, [], this.jobId);
633
+ }
634
+ }
635
+
553
636
  public storeCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[]): Promise<void> {
554
637
  if (!contractAddress.equals(this.contractAddress)) {
555
638
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
@@ -588,6 +671,17 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
588
671
  return this.capsuleStore.copyCapsule(this.contractAddress, srcSlot, dstSlot, numEntries, this.jobId);
589
672
  }
590
673
 
674
+ /**
675
+ * Clears cached sync state for a contract for a set of scopes, forcing re-sync on the next query so that newly
676
+ * stored notes or events are discovered.
677
+ */
678
+ public invalidateContractSyncCache(contractAddress: AztecAddress, scopes: AztecAddress[]): void {
679
+ if (!contractAddress.equals(this.contractAddress)) {
680
+ throw new Error(`Contract ${this.contractAddress} cannot invalidate sync cache of ${contractAddress}`);
681
+ }
682
+ this.contractSyncService.invalidateContractForScopes(contractAddress, scopes);
683
+ }
684
+
591
685
  // TODO(#11849): consider replacing this oracle with a pure Noir implementation of aes decryption.
592
686
  public aes128Decrypt(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise<Buffer> {
593
687
  const aes128 = new Aes128();
@@ -609,4 +703,34 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
609
703
  const addressSecret = await computeAddressSecret(await recipientCompleteAddress.getPreaddress(), ivskM);
610
704
  return deriveEcdhSharedSecret(addressSecret, ephPk);
611
705
  }
706
+
707
+ public emitOffchainEffect(data: Fr[]): Promise<void> {
708
+ this.offchainEffects.push({ data, contractAddress: this.contractAddress });
709
+ return Promise.resolve();
710
+ }
711
+
712
+ /** Returns offchain effects collected during execution. */
713
+ public getOffchainEffects(): OffchainEffect[] {
714
+ return this.offchainEffects;
715
+ }
716
+
717
+ /** Runs a query concurrently with a validation that the block hash is not ahead of the anchor block. */
718
+ async #queryWithBlockHashNotAfterAnchor<T>(blockHash: BlockHash, query: () => Promise<T>): Promise<T> {
719
+ const [response] = await Promise.all([
720
+ query(),
721
+ (async () => {
722
+ const header = await this.aztecNode.getBlockHeader(blockHash);
723
+ if (!header) {
724
+ throw new Error(`Could not find block header for block hash ${blockHash}`);
725
+ }
726
+
727
+ if (header.getBlockNumber() > this.anchorBlockHeader.getBlockNumber()) {
728
+ throw new Error(
729
+ `Made a node query with a reference block hash ${blockHash} with block number ${header.getBlockNumber()}, which is ahead of the anchor block number ${this.anchorBlockHeader.getBlockNumber()} (from anchor block hash ${await this.anchorBlockHeader.hash()}).`,
730
+ );
731
+ }
732
+ })(),
733
+ ]);
734
+ return response;
735
+ }
612
736
  }