@aztec/pxe 4.1.2 → 4.2.0-aztecnr-rc.2

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 (109) hide show
  1. package/dest/config/package_info.js +1 -1
  2. package/dest/contract_function_simulator/contract_function_simulator.d.ts +9 -3
  3. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  4. package/dest/contract_function_simulator/contract_function_simulator.js +26 -4
  5. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts +5 -5
  6. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts.map +1 -1
  7. package/dest/contract_function_simulator/execution_tagging_index_cache.js +17 -9
  8. package/dest/contract_function_simulator/index.d.ts +2 -1
  9. package/dest/contract_function_simulator/index.d.ts.map +1 -1
  10. package/dest/contract_function_simulator/index.js +1 -0
  11. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts +3 -5
  12. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts.map +1 -1
  13. package/dest/contract_function_simulator/noir-structs/event_validation_request.js +7 -9
  14. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts +1 -1
  15. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts.map +1 -1
  16. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.js +1 -3
  17. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts +3 -6
  18. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts.map +1 -1
  19. package/dest/contract_function_simulator/noir-structs/note_validation_request.js +5 -10
  20. package/dest/contract_function_simulator/oracle/interfaces.d.ts +45 -44
  21. package/dest/contract_function_simulator/oracle/interfaces.d.ts.map +1 -1
  22. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts +9 -0
  23. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts.map +1 -0
  24. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.js +41 -0
  25. package/dest/contract_function_simulator/oracle/oracle.d.ts +64 -44
  26. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  27. package/dest/contract_function_simulator/oracle/oracle.js +187 -97
  28. package/dest/contract_function_simulator/oracle/private_execution.js +5 -3
  29. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +22 -47
  30. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  31. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +32 -72
  32. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +54 -38
  33. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  34. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +173 -80
  35. package/dest/contract_logging.d.ts +9 -4
  36. package/dest/contract_logging.d.ts.map +1 -1
  37. package/dest/contract_logging.js +21 -6
  38. package/dest/contract_sync/contract_sync_service.d.ts +7 -4
  39. package/dest/contract_sync/contract_sync_service.d.ts.map +1 -1
  40. package/dest/contract_sync/contract_sync_service.js +59 -32
  41. package/dest/contract_sync/helpers.d.ts +2 -2
  42. package/dest/contract_sync/helpers.d.ts.map +1 -1
  43. package/dest/contract_sync/helpers.js +7 -2
  44. package/dest/events/event_service.d.ts +3 -2
  45. package/dest/events/event_service.d.ts.map +1 -1
  46. package/dest/events/event_service.js +16 -4
  47. package/dest/logs/log_service.d.ts +3 -4
  48. package/dest/logs/log_service.d.ts.map +1 -1
  49. package/dest/logs/log_service.js +16 -25
  50. package/dest/messages/message_context_service.d.ts +17 -0
  51. package/dest/messages/message_context_service.d.ts.map +1 -0
  52. package/dest/messages/message_context_service.js +36 -0
  53. package/dest/notes/note_service.d.ts +2 -2
  54. package/dest/notes/note_service.d.ts.map +1 -1
  55. package/dest/notes/note_service.js +14 -5
  56. package/dest/oracle_version.d.ts +2 -2
  57. package/dest/oracle_version.js +3 -3
  58. package/dest/pxe.d.ts +6 -3
  59. package/dest/pxe.d.ts.map +1 -1
  60. package/dest/pxe.js +39 -22
  61. package/dest/storage/capsule_store/capsule_store.d.ts +9 -9
  62. package/dest/storage/capsule_store/capsule_store.d.ts.map +1 -1
  63. package/dest/storage/capsule_store/capsule_store.js +33 -28
  64. package/dest/storage/metadata.d.ts +1 -1
  65. package/dest/storage/metadata.js +1 -1
  66. package/dest/storage/tagging_store/sender_tagging_store.d.ts +26 -25
  67. package/dest/storage/tagging_store/sender_tagging_store.d.ts.map +1 -1
  68. package/dest/storage/tagging_store/sender_tagging_store.js +141 -115
  69. package/dest/tagging/index.d.ts +2 -2
  70. package/dest/tagging/index.d.ts.map +1 -1
  71. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +1 -1
  72. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  73. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +10 -1
  74. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +4 -3
  75. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +1 -1
  76. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +20 -10
  77. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +2 -1
  78. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  79. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +24 -11
  80. package/package.json +16 -16
  81. package/src/config/package_info.ts +1 -1
  82. package/src/contract_function_simulator/contract_function_simulator.ts +37 -5
  83. package/src/contract_function_simulator/execution_tagging_index_cache.ts +16 -11
  84. package/src/contract_function_simulator/index.ts +1 -0
  85. package/src/contract_function_simulator/noir-structs/event_validation_request.ts +8 -8
  86. package/src/contract_function_simulator/noir-structs/log_retrieval_response.ts +1 -4
  87. package/src/contract_function_simulator/noir-structs/note_validation_request.ts +3 -9
  88. package/src/contract_function_simulator/oracle/interfaces.ts +59 -53
  89. package/src/contract_function_simulator/oracle/legacy_oracle_mappings.ts +107 -0
  90. package/src/contract_function_simulator/oracle/oracle.ts +223 -139
  91. package/src/contract_function_simulator/oracle/private_execution.ts +4 -4
  92. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +34 -91
  93. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +279 -93
  94. package/src/contract_logging.ts +18 -5
  95. package/src/contract_sync/contract_sync_service.ts +89 -49
  96. package/src/contract_sync/helpers.ts +3 -2
  97. package/src/events/event_service.ts +17 -4
  98. package/src/logs/log_service.ts +40 -44
  99. package/src/messages/message_context_service.ts +44 -0
  100. package/src/notes/note_service.ts +16 -5
  101. package/src/oracle_version.ts +3 -3
  102. package/src/pxe.ts +57 -20
  103. package/src/storage/capsule_store/capsule_store.ts +34 -26
  104. package/src/storage/metadata.ts +1 -1
  105. package/src/storage/tagging_store/sender_tagging_store.ts +182 -135
  106. package/src/tagging/index.ts +1 -1
  107. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +19 -1
  108. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +26 -11
  109. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +19 -9
@@ -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';
@@ -14,16 +15,18 @@ import { siloNullifier } from '@aztec/stdlib/hash';
14
15
  import type { AztecNode } from '@aztec/stdlib/interfaces/server';
15
16
  import type { KeyValidationRequest } from '@aztec/stdlib/kernel';
16
17
  import { type PublicKeys, computeAddressSecret } from '@aztec/stdlib/keys';
17
- import { deriveEcdhSharedSecret } from '@aztec/stdlib/logs';
18
+ import { MessageContext, deriveAppSiloedSharedSecret } 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
- import { createContractLogger, logContractMessage } from '../../contract_logging.js';
25
+ import { createContractLogger, logContractMessage, stripAztecnrLogPrefix } 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';
@@ -58,6 +61,8 @@ export type UtilityExecutionOracleArgs = {
58
61
  senderAddressBookStore: SenderAddressBookStore;
59
62
  capsuleStore: CapsuleStore;
60
63
  privateEventStore: PrivateEventStore;
64
+ messageContextService: MessageContextService;
65
+ contractSyncService: ContractSyncService;
61
66
  jobId: string;
62
67
  log?: ReturnType<typeof createLogger>;
63
68
  scopes: AccessScopes;
@@ -71,6 +76,8 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
71
76
  isUtility = true as const;
72
77
 
73
78
  private contractLogger: Logger | undefined;
79
+ private aztecnrLogger: Logger | undefined;
80
+ private offchainEffects: OffchainEffect[] = [];
74
81
 
75
82
  protected readonly contractAddress: AztecAddress;
76
83
  protected readonly authWitnesses: AuthWitness[];
@@ -85,8 +92,10 @@ 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
- protected log: ReturnType<typeof createLogger>;
98
+ protected logger: ReturnType<typeof createLogger>;
90
99
  protected readonly scopes: AccessScopes;
91
100
 
92
101
  constructor(args: UtilityExecutionOracleArgs) {
@@ -103,22 +112,49 @@ 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
- this.log = args.log ?? createLogger('simulator:client_view_context');
118
+ this.logger = args.log ?? createLogger('simulator:client_view_context');
108
119
  this.scopes = args.scopes;
109
120
  }
110
121
 
111
- public utilityAssertCompatibleOracleVersion(version: number): void {
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
+ const hint =
132
+ version > ORACLE_VERSION
133
+ ? 'The contract was compiled with a newer version of Aztec.nr than your private environment supports. Upgrade your private environment to a compatible version.'
134
+ : 'The contract was compiled with an older version of Aztec.nr than your private environment supports. Recompile the contract with a compatible version of Aztec.nr.';
135
+ throw new Error(
136
+ `Incompatible private environment version: ${hint} See https://docs.aztec.network/errors/8 (expected oracle version ${LEGACY_ORACLE_VERSION} or ${ORACLE_VERSION}, got ${version})`,
137
+ );
138
+ }
139
+ return;
140
+ }
141
+
112
142
  if (version !== ORACLE_VERSION) {
113
- throw new Error(`Incompatible oracle version. Expected version ${ORACLE_VERSION}, got ${version}.`);
143
+ const hint =
144
+ version > ORACLE_VERSION
145
+ ? 'The contract was compiled with a newer version of Aztec.nr than your private environment supports. Upgrade your private environment to a compatible version.'
146
+ : 'The contract was compiled with an older version of Aztec.nr than your private environment supports. Recompile the contract with a compatible version of Aztec.nr.';
147
+ throw new Error(
148
+ `Incompatible private environment version: ${hint} See https://docs.aztec.network/errors/8 (expected oracle version ${ORACLE_VERSION}, got ${version})`,
149
+ );
114
150
  }
115
151
  }
116
152
 
117
- public utilityGetRandomField(): Fr {
153
+ public getRandomField(): Fr {
118
154
  return Fr.random();
119
155
  }
120
156
 
121
- public utilityGetUtilityContext(): UtilityContext {
157
+ public getUtilityContext(): UtilityContext {
122
158
  return new UtilityContext(this.anchorBlockHeader, this.contractAddress);
123
159
  }
124
160
 
@@ -129,7 +165,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
129
165
  * @throws If the keys are not registered in the key store.
130
166
  * @throws If scopes are defined and the account is not in the scopes.
131
167
  */
132
- public async utilityGetKeyValidationRequest(pkMHash: Fr): Promise<KeyValidationRequest> {
168
+ public async getKeyValidationRequest(pkMHash: Fr): Promise<KeyValidationRequest> {
133
169
  // If scopes are defined, check that the key belongs to an account in the scopes.
134
170
  if (this.scopes !== 'ALL_SCOPES' && this.scopes.length > 0) {
135
171
  let hasAccess = false;
@@ -147,16 +183,18 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
147
183
 
148
184
  /**
149
185
  * 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.
186
+ * @param blockHash - The hash of a block that contains the note hash tree root in which to find the
187
+ * membership witness.
152
188
  * @param noteHash - The note hash to find in the note hash tree.
153
189
  * @returns The membership witness containing the leaf index and sibling path
154
190
  */
155
- public utilityGetNoteHashMembershipWitness(
156
- anchorBlockHash: BlockHash,
191
+ public getNoteHashMembershipWitness(
192
+ blockHash: BlockHash,
157
193
  noteHash: Fr,
158
194
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
159
- return this.aztecNode.getNoteHashMembershipWitness(anchorBlockHash, noteHash);
195
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
196
+ this.aztecNode.getNoteHashMembershipWitness(blockHash, noteHash),
197
+ );
160
198
  }
161
199
 
162
200
  /**
@@ -165,16 +203,21 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
165
203
  * Block hashes are the leaves of the archive tree. Each time a new block is added to the chain,
166
204
  * its block hash is appended as a new leaf to the archive tree.
167
205
  *
168
- * @param anchorBlockHash - The hash of a block that contains the archive tree root in which to find the membership
206
+ * @param referenceBlockHash - The hash of a block that contains the archive tree root in which to find the membership
169
207
  * witness.
170
208
  * @param blockHash - The block hash to find in the archive tree.
171
209
  * @returns The membership witness containing the leaf index and sibling path
172
210
  */
173
- public utilityGetBlockHashMembershipWitness(
174
- anchorBlockHash: BlockHash,
211
+ public getBlockHashMembershipWitness(
212
+ referenceBlockHash: BlockHash,
175
213
  blockHash: BlockHash,
176
214
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
177
- return this.aztecNode.getBlockHashMembershipWitness(anchorBlockHash, blockHash);
215
+ // Note that we validate that the reference block hash is at or before the anchor block - we don't test the block
216
+ // hash at all. If the block hash did not exist by the reference block hash, then the node will not return the
217
+ // membership witness as there is none.
218
+ return this.#queryWithBlockHashNotAfterAnchor(referenceBlockHash, () =>
219
+ this.aztecNode.getBlockHashMembershipWitness(referenceBlockHash, blockHash),
220
+ );
178
221
  }
179
222
 
180
223
  /**
@@ -183,11 +226,13 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
183
226
  * @param nullifier - Nullifier we try to find witness for.
184
227
  * @returns The nullifier membership witness (if found).
185
228
  */
186
- public utilityGetNullifierMembershipWitness(
229
+ public getNullifierMembershipWitness(
187
230
  blockHash: BlockHash,
188
231
  nullifier: Fr,
189
232
  ): Promise<NullifierMembershipWitness | undefined> {
190
- return this.aztecNode.getNullifierMembershipWitness(blockHash, nullifier);
233
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
234
+ this.aztecNode.getNullifierMembershipWitness(blockHash, nullifier),
235
+ );
191
236
  }
192
237
 
193
238
  /**
@@ -199,11 +244,13 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
199
244
  * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
200
245
  * we are trying to prove non-inclusion for.
201
246
  */
202
- public utilityGetLowNullifierMembershipWitness(
247
+ public getLowNullifierMembershipWitness(
203
248
  blockHash: BlockHash,
204
249
  nullifier: Fr,
205
250
  ): Promise<NullifierMembershipWitness | undefined> {
206
- return this.aztecNode.getLowNullifierMembershipWitness(blockHash, nullifier);
251
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
252
+ this.aztecNode.getLowNullifierMembershipWitness(blockHash, nullifier),
253
+ );
207
254
  }
208
255
 
209
256
  /**
@@ -212,8 +259,10 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
212
259
  * @param leafSlot - The slot of the public data tree to get the witness for.
213
260
  * @returns - The witness
214
261
  */
215
- public utilityGetPublicDataWitness(blockHash: BlockHash, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
216
- return this.aztecNode.getPublicDataWitness(blockHash, leafSlot);
262
+ public getPublicDataWitness(blockHash: BlockHash, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
263
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
264
+ this.aztecNode.getPublicDataWitness(blockHash, leafSlot),
265
+ );
217
266
  }
218
267
 
219
268
  /**
@@ -221,7 +270,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
221
270
  * @param blockNumber - The number of a block of which to get the block header.
222
271
  * @returns Block extracted from a block with block number `blockNumber`.
223
272
  */
224
- public async utilityGetBlockHeader(blockNumber: BlockNumber): Promise<BlockHeader | undefined> {
273
+ public async getBlockHeader(blockNumber: BlockNumber): Promise<BlockHeader | undefined> {
225
274
  const anchorBlockNumber = this.anchorBlockHeader.getBlockNumber();
226
275
  if (blockNumber > anchorBlockNumber) {
227
276
  throw new Error(`Block number ${blockNumber} is higher than current block ${anchorBlockNumber}`);
@@ -236,7 +285,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
236
285
  * @param account - The account address.
237
286
  * @returns The public keys and partial address, or `undefined` if the account is not registered.
238
287
  */
239
- public async utilityTryGetPublicKeysAndPartialAddress(
288
+ public async getPublicKeysAndPartialAddress(
240
289
  account: AztecAddress,
241
290
  ): Promise<{ publicKeys: PublicKeys; partialAddress: PartialAddress } | undefined> {
242
291
  const completeAddress = await this.addressStore.getCompleteAddress(account);
@@ -262,11 +311,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
262
311
  * @param address - Address.
263
312
  * @returns A contract instance.
264
313
  */
265
- public utilityGetContractInstance(address: AztecAddress): Promise<ContractInstance> {
266
- return this.getContractInstance(address);
267
- }
268
-
269
- protected async getContractInstance(address: AztecAddress): Promise<ContractInstance> {
314
+ public async getContractInstance(address: AztecAddress): Promise<ContractInstance> {
270
315
  const instance = await this.contractStore.getContractInstance(address);
271
316
  if (!instance) {
272
317
  throw new Error(`No contract instance found for address ${address.toString()}`);
@@ -280,7 +325,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
280
325
  * @param messageHash - Hash of the message to authenticate.
281
326
  * @returns Authentication witness for the requested message hash.
282
327
  */
283
- public utilityGetAuthWitness(messageHash: Fr): Promise<Fr[] | undefined> {
328
+ public getAuthWitness(messageHash: Fr): Promise<Fr[] | undefined> {
284
329
  return Promise.resolve(this.authWitnesses.find(w => w.requestHash.equals(messageHash))?.witness);
285
330
  }
286
331
 
@@ -306,7 +351,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
306
351
  * @param status - The status of notes to fetch.
307
352
  * @returns Array of note data.
308
353
  */
309
- public async utilityGetNotes(
354
+ public async getNotes(
310
355
  owner: AztecAddress | undefined,
311
356
  storageSlot: Fr,
312
357
  numSelects: number,
@@ -346,7 +391,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
346
391
  * @param innerNullifier - The inner nullifier.
347
392
  * @returns A boolean indicating whether the nullifier exists in the tree or not.
348
393
  */
349
- public async utilityCheckNullifierExists(innerNullifier: Fr) {
394
+ public async doesNullifierExist(innerNullifier: Fr) {
350
395
  const [nullifier, anchorBlockHash] = await Promise.all([
351
396
  siloNullifier(this.contractAddress, innerNullifier!),
352
397
  this.anchorBlockHeader.hash(),
@@ -358,19 +403,20 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
358
403
  }
359
404
 
360
405
  /**
361
- * Fetches a message from the executionStore, given its key.
406
+ * Returns the membership witness of an un-nullified L1 to L2 message.
362
407
  * @param contractAddress - Address of a contract by which the message was emitted.
363
408
  * @param messageHash - Hash of the message.
364
409
  * @param secret - Secret used to compute a nullifier.
365
410
  * @dev Contract address and secret are only used to compute the nullifier to get non-nullified messages
366
411
  * @returns The l1 to l2 membership witness (index of message in the tree and sibling path).
367
412
  */
368
- public async utilityGetL1ToL2MembershipWitness(contractAddress: AztecAddress, messageHash: Fr, secret: Fr) {
413
+ public async getL1ToL2MembershipWitness(contractAddress: AztecAddress, messageHash: Fr, secret: Fr) {
369
414
  const [messageIndex, siblingPath] = await getNonNullifiedL1ToL2MessageWitness(
370
415
  this.aztecNode,
371
416
  contractAddress,
372
417
  messageHash,
373
418
  secret,
419
+ await this.anchorBlockHeader.hash(),
374
420
  );
375
421
 
376
422
  return new MessageLoadOracleInputs(messageIndex, siblingPath);
@@ -383,29 +429,31 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
383
429
  * @param startStorageSlot - The starting storage slot.
384
430
  * @param numberOfElements - Number of elements to read from the starting storage slot.
385
431
  */
386
- public async utilityStorageRead(
432
+ public getFromPublicStorage(
387
433
  blockHash: BlockHash,
388
434
  contractAddress: AztecAddress,
389
435
  startStorageSlot: Fr,
390
436
  numberOfElements: number,
391
437
  ) {
392
- const slots = Array(numberOfElements)
393
- .fill(0)
394
- .map((_, i) => new Fr(startStorageSlot.value + BigInt(i)));
438
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, async () => {
439
+ const slots = Array(numberOfElements)
440
+ .fill(0)
441
+ .map((_, i) => new Fr(startStorageSlot.value + BigInt(i)));
395
442
 
396
- const values = await Promise.all(
397
- slots.map(storageSlot => this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)),
398
- );
443
+ const values = await Promise.all(
444
+ slots.map(storageSlot => this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)),
445
+ );
399
446
 
400
- this.log.debug(
401
- `Oracle storage read: slots=[${slots.map(slot => slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`,
402
- );
447
+ this.logger.debug(
448
+ `Oracle storage read: slots=[${slots.map(slot => slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`,
449
+ );
403
450
 
404
- return values;
451
+ return values;
452
+ });
405
453
  }
406
454
 
407
455
  /**
408
- * Returns a per-contract logger whose output is prefixed with `contract_log::<name>(<addrAbbrev>)`.
456
+ * Returns a per-contract logger whose output is prefixed with `contract:<name>(<addrAbbrev>)`.
409
457
  */
410
458
  async #getContractLogger(): Promise<Logger> {
411
459
  if (!this.contractLogger) {
@@ -414,21 +462,42 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
414
462
  this.contractLogger = await createContractLogger(
415
463
  this.contractAddress,
416
464
  addr => this.contractStore.getDebugContractName(addr),
465
+ 'user',
417
466
  { instanceId: this.jobId },
418
467
  );
419
468
  }
420
469
  return this.contractLogger;
421
470
  }
422
471
 
423
- public async utilityLog(level: number, message: string, fields: Fr[]): Promise<void> {
472
+ /**
473
+ * Returns a per-contract logger whose output is prefixed with `aztecnr:<name>(<addrAbbrev>)`.
474
+ */
475
+ async #getAztecnrLogger(): Promise<Logger> {
476
+ if (!this.aztecnrLogger) {
477
+ // Purpose of instanceId is to distinguish logs from different instances of the same component. It makes sense
478
+ // to re-use jobId as instanceId here as executions of different PXE jobs are isolated.
479
+ this.aztecnrLogger = await createContractLogger(
480
+ this.contractAddress,
481
+ addr => this.contractStore.getDebugContractName(addr),
482
+ 'aztecnr',
483
+ { instanceId: this.jobId },
484
+ );
485
+ }
486
+ return this.aztecnrLogger;
487
+ }
488
+
489
+ public async log(level: number, message: string, fields: Fr[]): Promise<void> {
424
490
  if (!LogLevels[level]) {
425
491
  throw new Error(`Invalid log level: ${level}`);
426
492
  }
427
- const logger = await this.#getContractLogger();
428
- logContractMessage(logger, LogLevels[level], message, fields);
493
+
494
+ const { kind, message: strippedMessage } = stripAztecnrLogPrefix(message);
495
+
496
+ const logger = kind == 'aztecnr' ? await this.#getAztecnrLogger() : await this.#getContractLogger();
497
+ logContractMessage(logger, LogLevels[level], strippedMessage, fields);
429
498
  }
430
499
 
431
- public async utilityFetchTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr) {
500
+ public async getPendingTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr, scope: AztecAddress) {
432
501
  const logService = new LogService(
433
502
  this.aztecNode,
434
503
  this.anchorBlockHeader,
@@ -438,10 +507,10 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
438
507
  this.senderAddressBookStore,
439
508
  this.addressStore,
440
509
  this.jobId,
441
- this.log.getBindings(),
510
+ this.logger.getBindings(),
442
511
  );
443
512
 
444
- await logService.fetchTaggedLogs(this.contractAddress, pendingTaggedLogArrayBaseSlot, this.scopes);
513
+ await logService.fetchTaggedLogs(this.contractAddress, pendingTaggedLogArrayBaseSlot, scope);
445
514
  }
446
515
 
447
516
  /**
@@ -454,10 +523,13 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
454
523
  * @param noteValidationRequestsArrayBaseSlot - The base slot of capsule array containing note validation requests.
455
524
  * @param eventValidationRequestsArrayBaseSlot - The base slot of capsule array containing event validation requests.
456
525
  */
457
- public async utilityValidateAndStoreEnqueuedNotesAndEvents(
526
+ public async validateAndStoreEnqueuedNotesAndEvents(
458
527
  contractAddress: AztecAddress,
459
528
  noteValidationRequestsArrayBaseSlot: Fr,
460
529
  eventValidationRequestsArrayBaseSlot: Fr,
530
+ maxNotePackedLen: number,
531
+ maxEventSerializedLen: number,
532
+ scope: AztecAddress,
461
533
  ) {
462
534
  // TODO(#10727): allow other contracts to store notes
463
535
  if (!this.contractAddress.equals(contractAddress)) {
@@ -467,12 +539,12 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
467
539
  // We read all note and event validation requests and process them all concurrently. This makes the process much
468
540
  // faster as we don't need to wait for the network round-trip.
469
541
  const noteValidationRequests = (
470
- await this.capsuleStore.readCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, this.jobId)
471
- ).map(NoteValidationRequest.fromFields);
542
+ await this.capsuleStore.readCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, this.jobId, scope)
543
+ ).map(fields => NoteValidationRequest.fromFields(fields, maxNotePackedLen));
472
544
 
473
545
  const eventValidationRequests = (
474
- await this.capsuleStore.readCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, this.jobId)
475
- ).map(EventValidationRequest.fromFields);
546
+ await this.capsuleStore.readCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, this.jobId, scope)
547
+ ).map(fields => EventValidationRequest.fromFields(fields, maxEventSerializedLen));
476
548
 
477
549
  const noteService = new NoteService(this.noteStore, this.aztecNode, this.anchorBlockHeader, this.jobId);
478
550
  const noteStorePromises = noteValidationRequests.map(request =>
@@ -486,7 +558,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
486
558
  request.noteHash,
487
559
  request.nullifier,
488
560
  request.txHash,
489
- request.recipient,
561
+ scope,
490
562
  ),
491
563
  );
492
564
 
@@ -499,21 +571,34 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
499
571
  request.serializedEvent,
500
572
  request.eventCommitment,
501
573
  request.txHash,
502
- request.recipient,
574
+ scope,
503
575
  ),
504
576
  );
505
577
 
506
578
  await Promise.all([...noteStorePromises, ...eventStorePromises]);
507
579
 
508
580
  // Requests are cleared once we're done.
509
- await this.capsuleStore.setCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, [], this.jobId);
510
- await this.capsuleStore.setCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, [], this.jobId);
581
+ await this.capsuleStore.setCapsuleArray(
582
+ contractAddress,
583
+ noteValidationRequestsArrayBaseSlot,
584
+ [],
585
+ this.jobId,
586
+ scope,
587
+ );
588
+ await this.capsuleStore.setCapsuleArray(
589
+ contractAddress,
590
+ eventValidationRequestsArrayBaseSlot,
591
+ [],
592
+ this.jobId,
593
+ scope,
594
+ );
511
595
  }
512
596
 
513
- public async utilityBulkRetrieveLogs(
597
+ public async getLogsByTag(
514
598
  contractAddress: AztecAddress,
515
599
  logRetrievalRequestsArrayBaseSlot: Fr,
516
600
  logRetrievalResponsesArrayBaseSlot: Fr,
601
+ scope: AztecAddress,
517
602
  ) {
518
603
  // TODO(#10727): allow other contracts to process partial notes
519
604
  if (!this.contractAddress.equals(contractAddress)) {
@@ -523,7 +608,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
523
608
  // We read all log retrieval requests and process them all concurrently. This makes the process much faster as we
524
609
  // don't need to wait for the network round-trip.
525
610
  const logRetrievalRequests = (
526
- await this.capsuleStore.readCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, this.jobId)
611
+ await this.capsuleStore.readCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, this.jobId, scope)
527
612
  ).map(LogRetrievalRequest.fromFields);
528
613
 
529
614
  const logService = new LogService(
@@ -535,13 +620,13 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
535
620
  this.senderAddressBookStore,
536
621
  this.addressStore,
537
622
  this.jobId,
538
- this.log.getBindings(),
623
+ this.logger.getBindings(),
539
624
  );
540
625
 
541
- const maybeLogRetrievalResponses = await logService.bulkRetrieveLogs(logRetrievalRequests);
626
+ const maybeLogRetrievalResponses = await logService.fetchLogsByTag(logRetrievalRequests);
542
627
 
543
628
  // Requests are cleared once we're done.
544
- await this.capsuleStore.setCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, [], this.jobId);
629
+ await this.capsuleStore.setCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, [], this.jobId, scope);
545
630
 
546
631
  // The responses are stored as Option<LogRetrievalResponse> in a second CapsuleArray.
547
632
  await this.capsuleStore.setCapsuleArray(
@@ -549,75 +634,176 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
549
634
  logRetrievalResponsesArrayBaseSlot,
550
635
  maybeLogRetrievalResponses.map(LogRetrievalResponse.toSerializedOption),
551
636
  this.jobId,
637
+ scope,
552
638
  );
553
639
  }
554
640
 
555
- public utilityStoreCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[]): Promise<void> {
641
+ public async getMessageContextsByTxHash(
642
+ contractAddress: AztecAddress,
643
+ messageContextRequestsArrayBaseSlot: Fr,
644
+ messageContextResponsesArrayBaseSlot: Fr,
645
+ scope: AztecAddress,
646
+ ) {
647
+ try {
648
+ if (!this.contractAddress.equals(contractAddress)) {
649
+ throw new Error(`Got a message context request from ${contractAddress}, expected ${this.contractAddress}`);
650
+ }
651
+
652
+ // TODO(@mverzilli): this is a prime example of where using a volatile array would make much more sense, we don't
653
+ // need scopes here, we just need a bit of shared memory to cross boundaries between Noir and TS.
654
+ // At the same time, we don't want to allow any global scope access other than where backwards compatibility
655
+ // forces us to. Hence we need the scope here to be artificial.
656
+ const requestCapsules = await this.capsuleStore.readCapsuleArray(
657
+ contractAddress,
658
+ messageContextRequestsArrayBaseSlot,
659
+ this.jobId,
660
+ scope,
661
+ );
662
+
663
+ const txHashes = requestCapsules.map((fields, i) => {
664
+ if (fields.length !== 1) {
665
+ throw new Error(
666
+ `Malformed message context request at index ${i}: expected 1 field (tx hash), got ${fields.length}`,
667
+ );
668
+ }
669
+ return fields[0];
670
+ });
671
+
672
+ const maybeMessageContexts = await this.messageContextService.getMessageContextsByTxHash(
673
+ txHashes,
674
+ this.anchorBlockHeader.getBlockNumber(),
675
+ );
676
+
677
+ // Leave response in response capsule array.
678
+ await this.capsuleStore.setCapsuleArray(
679
+ contractAddress,
680
+ messageContextResponsesArrayBaseSlot,
681
+ maybeMessageContexts.map(MessageContext.toSerializedOption),
682
+ this.jobId,
683
+ scope,
684
+ );
685
+ } finally {
686
+ await this.capsuleStore.setCapsuleArray(
687
+ contractAddress,
688
+ messageContextRequestsArrayBaseSlot,
689
+ [],
690
+ this.jobId,
691
+ scope,
692
+ );
693
+ }
694
+ }
695
+
696
+ public setCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[], scope: AztecAddress): void {
556
697
  if (!contractAddress.equals(this.contractAddress)) {
557
698
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
558
699
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
559
700
  }
560
- this.capsuleStore.storeCapsule(this.contractAddress, slot, capsule, this.jobId);
561
- return Promise.resolve();
701
+ this.capsuleStore.setCapsule(contractAddress, slot, capsule, this.jobId, scope);
562
702
  }
563
703
 
564
- public async utilityLoadCapsule(contractAddress: AztecAddress, slot: Fr): Promise<Fr[] | null> {
704
+ public async getCapsule(contractAddress: AztecAddress, slot: Fr, scope: AztecAddress): Promise<Fr[] | null> {
565
705
  if (!contractAddress.equals(this.contractAddress)) {
566
706
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
567
707
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
568
708
  }
569
- return (
570
- // TODO(#12425): On the following line, the pertinent capsule gets overshadowed by the transient one. Tackle this.
571
- this.capsules.find(c => c.contractAddress.equals(contractAddress) && c.storageSlot.equals(slot))?.data ??
572
- (await this.capsuleStore.loadCapsule(this.contractAddress, slot, this.jobId))
573
- );
709
+ const maybeTransientCapsule = this.capsules.find(
710
+ c =>
711
+ c.contractAddress.equals(contractAddress) &&
712
+ c.storageSlot.equals(slot) &&
713
+ (c.scope ?? AztecAddress.ZERO).equals(scope),
714
+ )?.data;
715
+
716
+ // TODO(#12425): On the following line, the pertinent capsule gets overshadowed by the transient one. Tackle this.
717
+ return maybeTransientCapsule ?? (await this.capsuleStore.getCapsule(contractAddress, slot, this.jobId, scope));
574
718
  }
575
719
 
576
- public utilityDeleteCapsule(contractAddress: AztecAddress, slot: Fr): Promise<void> {
720
+ public deleteCapsule(contractAddress: AztecAddress, slot: Fr, scope: AztecAddress): void {
577
721
  if (!contractAddress.equals(this.contractAddress)) {
578
722
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
579
723
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
580
724
  }
581
- this.capsuleStore.deleteCapsule(this.contractAddress, slot, this.jobId);
582
- return Promise.resolve();
725
+ this.capsuleStore.deleteCapsule(contractAddress, slot, this.jobId, scope);
583
726
  }
584
727
 
585
- public utilityCopyCapsule(
728
+ public copyCapsule(
586
729
  contractAddress: AztecAddress,
587
730
  srcSlot: Fr,
588
731
  dstSlot: Fr,
589
732
  numEntries: number,
733
+ scope: AztecAddress,
590
734
  ): Promise<void> {
591
735
  if (!contractAddress.equals(this.contractAddress)) {
592
736
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
593
737
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
594
738
  }
595
- return this.capsuleStore.copyCapsule(this.contractAddress, srcSlot, dstSlot, numEntries, this.jobId);
739
+ return this.capsuleStore.copyCapsule(contractAddress, srcSlot, dstSlot, numEntries, this.jobId, scope);
740
+ }
741
+
742
+ /**
743
+ * Clears cached sync state for a contract for a set of scopes, forcing re-sync on the next query so that newly
744
+ * stored notes or events are discovered.
745
+ */
746
+ public setContractSyncCacheInvalid(contractAddress: AztecAddress, scopes: AztecAddress[]): void {
747
+ if (!contractAddress.equals(this.contractAddress)) {
748
+ throw new Error(`Contract ${this.contractAddress} cannot invalidate sync cache of ${contractAddress}`);
749
+ }
750
+ this.contractSyncService.invalidateContractForScopes(contractAddress, scopes);
596
751
  }
597
752
 
598
753
  // TODO(#11849): consider replacing this oracle with a pure Noir implementation of aes decryption.
599
- public utilityAes128Decrypt(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise<Buffer> {
754
+ public decryptAes128(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise<Buffer> {
600
755
  const aes128 = new Aes128();
601
756
  return aes128.decryptBufferCBC(ciphertext, iv, symKey);
602
757
  }
603
758
 
604
759
  /**
605
- * Retrieves the shared secret for a given address and ephemeral public key.
760
+ * Retrieves the app-siloed shared secret for a given address and ephemeral public key.
606
761
  * @param address - The address to get the secret for.
607
762
  * @param ephPk - The ephemeral public key to get the secret for.
608
- * @returns The secret for the given address.
763
+ * @param contractAddress - The contract address for app-siloing (validated against execution context).
764
+ * @returns The app-siloed shared secret as a Field.
609
765
  */
610
- public utilityGetSharedSecret(address: AztecAddress, ephPk: Point): Promise<Point> {
611
- return this.getSharedSecret(address, ephPk);
612
- }
613
-
614
- protected async getSharedSecret(address: AztecAddress, ephPk: Point): Promise<Point> {
615
- // TODO(#12656): return an app-siloed secret
766
+ public async getSharedSecret(address: AztecAddress, ephPk: Point, contractAddress: AztecAddress): Promise<Fr> {
767
+ if (!contractAddress.equals(this.contractAddress)) {
768
+ throw new Error(
769
+ `getSharedSecret called with contract address ${contractAddress}, expected ${this.contractAddress}`,
770
+ );
771
+ }
616
772
  const recipientCompleteAddress = await this.getCompleteAddressOrFail(address);
617
773
  const ivskM = await this.keyStore.getMasterSecretKey(
618
774
  recipientCompleteAddress.publicKeys.masterIncomingViewingPublicKey,
619
775
  );
620
776
  const addressSecret = await computeAddressSecret(await recipientCompleteAddress.getPreaddress(), ivskM);
621
- return deriveEcdhSharedSecret(addressSecret, ephPk);
777
+ return deriveAppSiloedSharedSecret(addressSecret, ephPk, this.contractAddress);
778
+ }
779
+
780
+ public emitOffchainEffect(data: Fr[]): Promise<void> {
781
+ this.offchainEffects.push({ data, contractAddress: this.contractAddress });
782
+ return Promise.resolve();
783
+ }
784
+
785
+ /** Returns offchain effects collected during execution. */
786
+ public getOffchainEffects(): OffchainEffect[] {
787
+ return this.offchainEffects;
788
+ }
789
+
790
+ /** Runs a query concurrently with a validation that the block hash is not ahead of the anchor block. */
791
+ async #queryWithBlockHashNotAfterAnchor<T>(blockHash: BlockHash, query: () => Promise<T>): Promise<T> {
792
+ const [response] = await Promise.all([
793
+ query(),
794
+ (async () => {
795
+ const header = await this.aztecNode.getBlockHeader(blockHash);
796
+ if (!header) {
797
+ throw new Error(`Could not find block header for block hash ${blockHash}`);
798
+ }
799
+
800
+ if (header.getBlockNumber() > this.anchorBlockHeader.getBlockNumber()) {
801
+ throw new Error(
802
+ `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()}).`,
803
+ );
804
+ }
805
+ })(),
806
+ ]);
807
+ return response;
622
808
  }
623
809
  }