@aztec/pxe 0.0.1-commit.f504929 → 0.0.1-commit.f5d02921e

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 (123) hide show
  1. package/dest/block_synchronizer/block_synchronizer.d.ts +1 -1
  2. package/dest/block_synchronizer/block_synchronizer.d.ts.map +1 -1
  3. package/dest/block_synchronizer/block_synchronizer.js +6 -0
  4. package/dest/config/index.d.ts +2 -2
  5. package/dest/config/index.d.ts.map +1 -1
  6. package/dest/config/index.js +1 -1
  7. package/dest/contract_function_simulator/contract_function_simulator.d.ts +9 -3
  8. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  9. package/dest/contract_function_simulator/contract_function_simulator.js +29 -6
  10. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts +5 -5
  11. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts.map +1 -1
  12. package/dest/contract_function_simulator/execution_tagging_index_cache.js +17 -9
  13. package/dest/contract_function_simulator/index.d.ts +2 -1
  14. package/dest/contract_function_simulator/index.d.ts.map +1 -1
  15. package/dest/contract_function_simulator/index.js +1 -0
  16. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts +3 -5
  17. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts.map +1 -1
  18. package/dest/contract_function_simulator/noir-structs/event_validation_request.js +7 -9
  19. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts +1 -1
  20. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts.map +1 -1
  21. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.js +1 -3
  22. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts +3 -6
  23. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts.map +1 -1
  24. package/dest/contract_function_simulator/noir-structs/note_validation_request.js +5 -10
  25. package/dest/contract_function_simulator/oracle/interfaces.d.ts +26 -21
  26. package/dest/contract_function_simulator/oracle/interfaces.d.ts.map +1 -1
  27. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts +9 -0
  28. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts.map +1 -0
  29. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.js +38 -0
  30. package/dest/contract_function_simulator/oracle/oracle.d.ts +39 -19
  31. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  32. package/dest/contract_function_simulator/oracle/oracle.js +91 -44
  33. package/dest/contract_function_simulator/oracle/private_execution.js +5 -3
  34. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +11 -36
  35. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  36. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +12 -44
  37. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +50 -28
  38. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  39. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +167 -64
  40. package/dest/contract_logging.d.ts +9 -4
  41. package/dest/contract_logging.d.ts.map +1 -1
  42. package/dest/contract_logging.js +21 -6
  43. package/dest/contract_sync/contract_sync_service.d.ts +7 -4
  44. package/dest/contract_sync/contract_sync_service.d.ts.map +1 -1
  45. package/dest/contract_sync/contract_sync_service.js +59 -32
  46. package/dest/contract_sync/helpers.d.ts +2 -2
  47. package/dest/contract_sync/helpers.d.ts.map +1 -1
  48. package/dest/contract_sync/helpers.js +7 -2
  49. package/dest/events/event_service.d.ts +3 -2
  50. package/dest/events/event_service.d.ts.map +1 -1
  51. package/dest/events/event_service.js +16 -4
  52. package/dest/logs/log_service.d.ts +6 -7
  53. package/dest/logs/log_service.d.ts.map +1 -1
  54. package/dest/logs/log_service.js +24 -28
  55. package/dest/messages/message_context_service.d.ts +17 -0
  56. package/dest/messages/message_context_service.d.ts.map +1 -0
  57. package/dest/messages/message_context_service.js +36 -0
  58. package/dest/notes/note_service.d.ts +2 -2
  59. package/dest/notes/note_service.d.ts.map +1 -1
  60. package/dest/notes/note_service.js +14 -5
  61. package/dest/oracle_version.d.ts +2 -2
  62. package/dest/oracle_version.js +2 -2
  63. package/dest/pxe.d.ts +6 -3
  64. package/dest/pxe.d.ts.map +1 -1
  65. package/dest/pxe.js +37 -21
  66. package/dest/storage/capsule_store/capsule_service.d.ts +22 -0
  67. package/dest/storage/capsule_store/capsule_service.d.ts.map +1 -0
  68. package/dest/storage/capsule_store/capsule_service.js +50 -0
  69. package/dest/storage/capsule_store/capsule_store.d.ts +9 -9
  70. package/dest/storage/capsule_store/capsule_store.d.ts.map +1 -1
  71. package/dest/storage/capsule_store/capsule_store.js +33 -28
  72. package/dest/storage/capsule_store/index.d.ts +2 -1
  73. package/dest/storage/capsule_store/index.d.ts.map +1 -1
  74. package/dest/storage/capsule_store/index.js +1 -0
  75. package/dest/storage/metadata.d.ts +1 -1
  76. package/dest/storage/metadata.js +1 -1
  77. package/dest/storage/tagging_store/sender_tagging_store.d.ts +26 -25
  78. package/dest/storage/tagging_store/sender_tagging_store.d.ts.map +1 -1
  79. package/dest/storage/tagging_store/sender_tagging_store.js +141 -115
  80. package/dest/tagging/index.d.ts +2 -2
  81. package/dest/tagging/index.d.ts.map +1 -1
  82. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +1 -1
  83. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  84. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +10 -1
  85. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +4 -3
  86. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +1 -1
  87. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +20 -10
  88. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +2 -1
  89. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  90. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +24 -11
  91. package/package.json +16 -16
  92. package/src/block_synchronizer/block_synchronizer.ts +6 -0
  93. package/src/config/index.ts +1 -1
  94. package/src/contract_function_simulator/contract_function_simulator.ts +40 -7
  95. package/src/contract_function_simulator/execution_tagging_index_cache.ts +16 -11
  96. package/src/contract_function_simulator/index.ts +1 -0
  97. package/src/contract_function_simulator/noir-structs/event_validation_request.ts +8 -8
  98. package/src/contract_function_simulator/noir-structs/log_retrieval_response.ts +1 -4
  99. package/src/contract_function_simulator/noir-structs/note_validation_request.ts +3 -9
  100. package/src/contract_function_simulator/oracle/interfaces.ts +38 -29
  101. package/src/contract_function_simulator/oracle/legacy_oracle_mappings.ts +98 -0
  102. package/src/contract_function_simulator/oracle/oracle.ts +120 -64
  103. package/src/contract_function_simulator/oracle/private_execution.ts +4 -4
  104. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +14 -62
  105. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +290 -77
  106. package/src/contract_logging.ts +18 -5
  107. package/src/contract_sync/contract_sync_service.ts +89 -49
  108. package/src/contract_sync/helpers.ts +3 -2
  109. package/src/events/event_service.ts +17 -4
  110. package/src/logs/log_service.ts +51 -46
  111. package/src/messages/message_context_service.ts +44 -0
  112. package/src/notes/note_service.ts +16 -5
  113. package/src/oracle_version.ts +2 -2
  114. package/src/pxe.ts +55 -19
  115. package/src/storage/capsule_store/capsule_service.ts +91 -0
  116. package/src/storage/capsule_store/capsule_store.ts +34 -26
  117. package/src/storage/capsule_store/index.ts +1 -0
  118. package/src/storage/metadata.ts +1 -1
  119. package/src/storage/tagging_store/sender_tagging_store.ts +182 -135
  120. package/src/tagging/index.ts +1 -1
  121. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +19 -1
  122. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +26 -11
  123. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +19 -9
@@ -6,28 +6,31 @@ 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';
12
- import type { CompleteAddress, ContractInstance } from '@aztec/stdlib/contract';
13
+ import type { CompleteAddress, ContractInstance, PartialAddress } from '@aztec/stdlib/contract';
13
14
  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
- import { computeAddressSecret } from '@aztec/stdlib/keys';
17
- import { deriveEcdhSharedSecret } from '@aztec/stdlib/logs';
17
+ import { type PublicKeys, computeAddressSecret } from '@aztec/stdlib/keys';
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';
30
- import type { CapsuleStore } from '../../storage/capsule_store/capsule_store.js';
33
+ import type { CapsuleService } from '../../storage/capsule_store/capsule_service.js';
31
34
  import type { ContractStore } from '../../storage/contract_store/contract_store.js';
32
35
  import type { NoteStore } from '../../storage/note_store/note_store.js';
33
36
  import type { PrivateEventStore } from '../../storage/private_event_store/private_event_store.js';
@@ -56,8 +59,10 @@ export type UtilityExecutionOracleArgs = {
56
59
  aztecNode: AztecNode;
57
60
  recipientTaggingStore: RecipientTaggingStore;
58
61
  senderAddressBookStore: SenderAddressBookStore;
59
- capsuleStore: CapsuleStore;
62
+ capsuleService: CapsuleService;
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[];
@@ -83,8 +90,10 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
83
90
  protected readonly aztecNode: AztecNode;
84
91
  protected readonly recipientTaggingStore: RecipientTaggingStore;
85
92
  protected readonly senderAddressBookStore: SenderAddressBookStore;
86
- protected readonly capsuleStore: CapsuleStore;
93
+ protected readonly capsuleService: CapsuleService;
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;
@@ -101,16 +110,43 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
101
110
  this.aztecNode = args.aztecNode;
102
111
  this.recipientTaggingStore = args.recipientTaggingStore;
103
112
  this.senderAddressBookStore = args.senderAddressBookStore;
104
- this.capsuleStore = args.capsuleStore;
113
+ this.capsuleService = args.capsuleService;
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
+ 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
 
@@ -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
191
  public getNoteHashMembershipWitness(
156
- anchorBlockHash: BlockHash,
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
211
  public getBlockHashMembershipWitness(
174
- anchorBlockHash: BlockHash,
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
  /**
@@ -187,7 +230,9 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
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
  /**
@@ -203,7 +248,9 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
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
  /**
@@ -213,7 +260,9 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
213
260
  * @returns - The witness
214
261
  */
215
262
  public getPublicDataWitness(blockHash: BlockHash, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
216
- return this.aztecNode.getPublicDataWitness(blockHash, leafSlot);
263
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
264
+ this.aztecNode.getPublicDataWitness(blockHash, leafSlot),
265
+ );
217
266
  }
218
267
 
219
268
  /**
@@ -232,12 +281,18 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
232
281
  }
233
282
 
234
283
  /**
235
- * Retrieve the complete address associated to a given address.
284
+ * Retrieve the public keys and partial address associated to a given address.
236
285
  * @param account - The account address.
237
- * @returns A complete address associated with the input address, or `undefined` if not registered.
286
+ * @returns The public keys and partial address, or `undefined` if the account is not registered.
238
287
  */
239
- public tryGetPublicKeysAndPartialAddress(account: AztecAddress): Promise<CompleteAddress | undefined> {
240
- return this.addressStore.getCompleteAddress(account);
288
+ public async getPublicKeysAndPartialAddress(
289
+ account: AztecAddress,
290
+ ): Promise<{ publicKeys: PublicKeys; partialAddress: PartialAddress } | undefined> {
291
+ const completeAddress = await this.addressStore.getCompleteAddress(account);
292
+ if (!completeAddress) {
293
+ return undefined;
294
+ }
295
+ return { publicKeys: completeAddress.publicKeys, partialAddress: completeAddress.partialAddress };
241
296
  }
242
297
 
243
298
  protected async getCompleteAddressOrFail(account: AztecAddress): Promise<CompleteAddress> {
@@ -336,7 +391,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
336
391
  * @param innerNullifier - The inner nullifier.
337
392
  * @returns A boolean indicating whether the nullifier exists in the tree or not.
338
393
  */
339
- public async checkNullifierExists(innerNullifier: Fr) {
394
+ public async doesNullifierExist(innerNullifier: Fr) {
340
395
  const [nullifier, anchorBlockHash] = await Promise.all([
341
396
  siloNullifier(this.contractAddress, innerNullifier!),
342
397
  this.anchorBlockHeader.hash(),
@@ -348,7 +403,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
348
403
  }
349
404
 
350
405
  /**
351
- * Fetches a message from the executionStore, given its key.
406
+ * Returns the membership witness of an un-nullified L1 to L2 message.
352
407
  * @param contractAddress - Address of a contract by which the message was emitted.
353
408
  * @param messageHash - Hash of the message.
354
409
  * @param secret - Secret used to compute a nullifier.
@@ -361,6 +416,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
361
416
  contractAddress,
362
417
  messageHash,
363
418
  secret,
419
+ await this.anchorBlockHeader.hash(),
364
420
  );
365
421
 
366
422
  return new MessageLoadOracleInputs(messageIndex, siblingPath);
@@ -373,29 +429,31 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
373
429
  * @param startStorageSlot - The starting storage slot.
374
430
  * @param numberOfElements - Number of elements to read from the starting storage slot.
375
431
  */
376
- public async storageRead(
432
+ public getFromPublicStorage(
377
433
  blockHash: BlockHash,
378
434
  contractAddress: AztecAddress,
379
435
  startStorageSlot: Fr,
380
436
  numberOfElements: number,
381
437
  ) {
382
- const slots = Array(numberOfElements)
383
- .fill(0)
384
- .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)));
385
442
 
386
- const values = await Promise.all(
387
- slots.map(storageSlot => this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)),
388
- );
443
+ const values = await Promise.all(
444
+ slots.map(storageSlot => this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)),
445
+ );
389
446
 
390
- this.logger.debug(
391
- `Oracle storage read: slots=[${slots.map(slot => slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`,
392
- );
447
+ this.logger.debug(
448
+ `Oracle storage read: slots=[${slots.map(slot => slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`,
449
+ );
393
450
 
394
- return values;
451
+ return values;
452
+ });
395
453
  }
396
454
 
397
455
  /**
398
- * 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>)`.
399
457
  */
400
458
  async #getContractLogger(): Promise<Logger> {
401
459
  if (!this.contractLogger) {
@@ -404,26 +462,47 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
404
462
  this.contractLogger = await createContractLogger(
405
463
  this.contractAddress,
406
464
  addr => this.contractStore.getDebugContractName(addr),
465
+ 'user',
407
466
  { instanceId: this.jobId },
408
467
  );
409
468
  }
410
469
  return this.contractLogger;
411
470
  }
412
471
 
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
+
413
489
  public async log(level: number, message: string, fields: Fr[]): Promise<void> {
414
490
  if (!LogLevels[level]) {
415
491
  throw new Error(`Invalid log level: ${level}`);
416
492
  }
417
- const logger = await this.#getContractLogger();
418
- 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);
419
498
  }
420
499
 
421
- public async fetchTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr) {
500
+ public async getPendingTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr, scope: AztecAddress) {
422
501
  const logService = new LogService(
423
502
  this.aztecNode,
424
503
  this.anchorBlockHeader,
425
504
  this.keyStore,
426
- this.capsuleStore,
505
+ this.capsuleService,
427
506
  this.recipientTaggingStore,
428
507
  this.senderAddressBookStore,
429
508
  this.addressStore,
@@ -431,7 +510,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
431
510
  this.logger.getBindings(),
432
511
  );
433
512
 
434
- await logService.fetchTaggedLogs(this.contractAddress, pendingTaggedLogArrayBaseSlot, this.scopes);
513
+ await logService.fetchTaggedLogs(this.contractAddress, pendingTaggedLogArrayBaseSlot, scope);
435
514
  }
436
515
 
437
516
  /**
@@ -448,6 +527,9 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
448
527
  contractAddress: AztecAddress,
449
528
  noteValidationRequestsArrayBaseSlot: Fr,
450
529
  eventValidationRequestsArrayBaseSlot: Fr,
530
+ maxNotePackedLen: number,
531
+ maxEventSerializedLen: number,
532
+ scope: AztecAddress,
451
533
  ) {
452
534
  // TODO(#10727): allow other contracts to store notes
453
535
  if (!this.contractAddress.equals(contractAddress)) {
@@ -457,12 +539,22 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
457
539
  // We read all note and event validation requests and process them all concurrently. This makes the process much
458
540
  // faster as we don't need to wait for the network round-trip.
459
541
  const noteValidationRequests = (
460
- await this.capsuleStore.readCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, this.jobId)
461
- ).map(NoteValidationRequest.fromFields);
542
+ await this.capsuleService.readCapsuleArray(
543
+ contractAddress,
544
+ noteValidationRequestsArrayBaseSlot,
545
+ this.jobId,
546
+ scope,
547
+ )
548
+ ).map(fields => NoteValidationRequest.fromFields(fields, maxNotePackedLen));
462
549
 
463
550
  const eventValidationRequests = (
464
- await this.capsuleStore.readCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, this.jobId)
465
- ).map(EventValidationRequest.fromFields);
551
+ await this.capsuleService.readCapsuleArray(
552
+ contractAddress,
553
+ eventValidationRequestsArrayBaseSlot,
554
+ this.jobId,
555
+ scope,
556
+ )
557
+ ).map(fields => EventValidationRequest.fromFields(fields, maxEventSerializedLen));
466
558
 
467
559
  const noteService = new NoteService(this.noteStore, this.aztecNode, this.anchorBlockHeader, this.jobId);
468
560
  const noteStorePromises = noteValidationRequests.map(request =>
@@ -476,7 +568,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
476
568
  request.noteHash,
477
569
  request.nullifier,
478
570
  request.txHash,
479
- request.recipient,
571
+ scope,
480
572
  ),
481
573
  );
482
574
 
@@ -489,21 +581,34 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
489
581
  request.serializedEvent,
490
582
  request.eventCommitment,
491
583
  request.txHash,
492
- request.recipient,
584
+ scope,
493
585
  ),
494
586
  );
495
587
 
496
588
  await Promise.all([...noteStorePromises, ...eventStorePromises]);
497
589
 
498
590
  // Requests are cleared once we're done.
499
- await this.capsuleStore.setCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, [], this.jobId);
500
- await this.capsuleStore.setCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, [], this.jobId);
591
+ await this.capsuleService.setCapsuleArray(
592
+ contractAddress,
593
+ noteValidationRequestsArrayBaseSlot,
594
+ [],
595
+ this.jobId,
596
+ scope,
597
+ );
598
+ await this.capsuleService.setCapsuleArray(
599
+ contractAddress,
600
+ eventValidationRequestsArrayBaseSlot,
601
+ [],
602
+ this.jobId,
603
+ scope,
604
+ );
501
605
  }
502
606
 
503
- public async bulkRetrieveLogs(
607
+ public async getLogsByTag(
504
608
  contractAddress: AztecAddress,
505
609
  logRetrievalRequestsArrayBaseSlot: Fr,
506
610
  logRetrievalResponsesArrayBaseSlot: Fr,
611
+ scope: AztecAddress,
507
612
  ) {
508
613
  // TODO(#10727): allow other contracts to process partial notes
509
614
  if (!this.contractAddress.equals(contractAddress)) {
@@ -513,14 +618,14 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
513
618
  // We read all log retrieval requests and process them all concurrently. This makes the process much faster as we
514
619
  // don't need to wait for the network round-trip.
515
620
  const logRetrievalRequests = (
516
- await this.capsuleStore.readCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, this.jobId)
621
+ await this.capsuleService.readCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, this.jobId, scope)
517
622
  ).map(LogRetrievalRequest.fromFields);
518
623
 
519
624
  const logService = new LogService(
520
625
  this.aztecNode,
521
626
  this.anchorBlockHeader,
522
627
  this.keyStore,
523
- this.capsuleStore,
628
+ this.capsuleService,
524
629
  this.recipientTaggingStore,
525
630
  this.senderAddressBookStore,
526
631
  this.addressStore,
@@ -528,77 +633,185 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
528
633
  this.logger.getBindings(),
529
634
  );
530
635
 
531
- const maybeLogRetrievalResponses = await logService.bulkRetrieveLogs(logRetrievalRequests);
636
+ const maybeLogRetrievalResponses = await logService.fetchLogsByTag(contractAddress, logRetrievalRequests);
532
637
 
533
638
  // Requests are cleared once we're done.
534
- await this.capsuleStore.setCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, [], this.jobId);
639
+ await this.capsuleService.setCapsuleArray(
640
+ contractAddress,
641
+ logRetrievalRequestsArrayBaseSlot,
642
+ [],
643
+ this.jobId,
644
+ scope,
645
+ );
535
646
 
536
647
  // The responses are stored as Option<LogRetrievalResponse> in a second CapsuleArray.
537
- await this.capsuleStore.setCapsuleArray(
648
+ await this.capsuleService.setCapsuleArray(
538
649
  contractAddress,
539
650
  logRetrievalResponsesArrayBaseSlot,
540
651
  maybeLogRetrievalResponses.map(LogRetrievalResponse.toSerializedOption),
541
652
  this.jobId,
653
+ scope,
542
654
  );
543
655
  }
544
656
 
545
- public storeCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[]): Promise<void> {
657
+ public async getMessageContextsByTxHash(
658
+ contractAddress: AztecAddress,
659
+ messageContextRequestsArrayBaseSlot: Fr,
660
+ messageContextResponsesArrayBaseSlot: Fr,
661
+ scope: AztecAddress,
662
+ ) {
663
+ try {
664
+ if (!this.contractAddress.equals(contractAddress)) {
665
+ throw new Error(`Got a message context request from ${contractAddress}, expected ${this.contractAddress}`);
666
+ }
667
+
668
+ // TODO(@mverzilli): this is a prime example of where using a volatile array would make much more sense, we don't
669
+ // need scopes here, we just need a bit of shared memory to cross boundaries between Noir and TS.
670
+ // At the same time, we don't want to allow any global scope access other than where backwards compatibility
671
+ // forces us to. Hence we need the scope here to be artificial.
672
+ const requestCapsules = await this.capsuleService.readCapsuleArray(
673
+ contractAddress,
674
+ messageContextRequestsArrayBaseSlot,
675
+ this.jobId,
676
+ scope,
677
+ );
678
+
679
+ const txHashes = requestCapsules.map((fields, i) => {
680
+ if (fields.length !== 1) {
681
+ throw new Error(
682
+ `Malformed message context request at index ${i}: expected 1 field (tx hash), got ${fields.length}`,
683
+ );
684
+ }
685
+ return fields[0];
686
+ });
687
+
688
+ const maybeMessageContexts = await this.messageContextService.getMessageContextsByTxHash(
689
+ txHashes,
690
+ this.anchorBlockHeader.getBlockNumber(),
691
+ );
692
+
693
+ // Leave response in response capsule array.
694
+ await this.capsuleService.setCapsuleArray(
695
+ contractAddress,
696
+ messageContextResponsesArrayBaseSlot,
697
+ maybeMessageContexts.map(MessageContext.toSerializedOption),
698
+ this.jobId,
699
+ scope,
700
+ );
701
+ } finally {
702
+ await this.capsuleService.setCapsuleArray(
703
+ contractAddress,
704
+ messageContextRequestsArrayBaseSlot,
705
+ [],
706
+ this.jobId,
707
+ scope,
708
+ );
709
+ }
710
+ }
711
+
712
+ public setCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[], scope: AztecAddress): void {
546
713
  if (!contractAddress.equals(this.contractAddress)) {
547
714
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
548
715
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
549
716
  }
550
- this.capsuleStore.storeCapsule(this.contractAddress, slot, capsule, this.jobId);
551
- return Promise.resolve();
717
+ this.capsuleService.setCapsule(contractAddress, slot, capsule, this.jobId, scope);
552
718
  }
553
719
 
554
- public async loadCapsule(contractAddress: AztecAddress, slot: Fr): Promise<Fr[] | null> {
720
+ public getCapsule(contractAddress: AztecAddress, slot: Fr, scope: AztecAddress): Promise<Fr[] | null> {
555
721
  if (!contractAddress.equals(this.contractAddress)) {
556
722
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
557
723
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
558
724
  }
559
- return (
560
- // TODO(#12425): On the following line, the pertinent capsule gets overshadowed by the transient one. Tackle this.
561
- this.capsules.find(c => c.contractAddress.equals(contractAddress) && c.storageSlot.equals(slot))?.data ??
562
- (await this.capsuleStore.loadCapsule(this.contractAddress, slot, this.jobId))
563
- );
725
+ return this.capsuleService.getCapsule(contractAddress, slot, this.jobId, scope, this.capsules);
564
726
  }
565
727
 
566
- public deleteCapsule(contractAddress: AztecAddress, slot: Fr): Promise<void> {
728
+ public deleteCapsule(contractAddress: AztecAddress, slot: Fr, scope: AztecAddress): void {
567
729
  if (!contractAddress.equals(this.contractAddress)) {
568
730
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
569
731
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
570
732
  }
571
- this.capsuleStore.deleteCapsule(this.contractAddress, slot, this.jobId);
572
- return Promise.resolve();
733
+ this.capsuleService.deleteCapsule(contractAddress, slot, this.jobId, scope);
573
734
  }
574
735
 
575
- public copyCapsule(contractAddress: AztecAddress, srcSlot: Fr, dstSlot: Fr, numEntries: number): Promise<void> {
736
+ public copyCapsule(
737
+ contractAddress: AztecAddress,
738
+ srcSlot: Fr,
739
+ dstSlot: Fr,
740
+ numEntries: number,
741
+ scope: AztecAddress,
742
+ ): Promise<void> {
576
743
  if (!contractAddress.equals(this.contractAddress)) {
577
744
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
578
745
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
579
746
  }
580
- return this.capsuleStore.copyCapsule(this.contractAddress, srcSlot, dstSlot, numEntries, this.jobId);
747
+ return this.capsuleService.copyCapsule(contractAddress, srcSlot, dstSlot, numEntries, this.jobId, scope);
748
+ }
749
+
750
+ /**
751
+ * Clears cached sync state for a contract for a set of scopes, forcing re-sync on the next query so that newly
752
+ * stored notes or events are discovered.
753
+ */
754
+ public setContractSyncCacheInvalid(contractAddress: AztecAddress, scopes: AztecAddress[]): void {
755
+ if (!contractAddress.equals(this.contractAddress)) {
756
+ throw new Error(`Contract ${this.contractAddress} cannot invalidate sync cache of ${contractAddress}`);
757
+ }
758
+ this.contractSyncService.invalidateContractForScopes(contractAddress, scopes);
581
759
  }
582
760
 
583
761
  // TODO(#11849): consider replacing this oracle with a pure Noir implementation of aes decryption.
584
- public aes128Decrypt(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise<Buffer> {
762
+ public decryptAes128(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise<Buffer> {
585
763
  const aes128 = new Aes128();
586
764
  return aes128.decryptBufferCBC(ciphertext, iv, symKey);
587
765
  }
588
766
 
589
767
  /**
590
- * Retrieves the shared secret for a given address and ephemeral public key.
768
+ * Retrieves the app-siloed shared secret for a given address and ephemeral public key.
591
769
  * @param address - The address to get the secret for.
592
770
  * @param ephPk - The ephemeral public key to get the secret for.
593
- * @returns The secret for the given address.
771
+ * @param contractAddress - The contract address for app-siloing (validated against execution context).
772
+ * @returns The app-siloed shared secret as a Field.
594
773
  */
595
- public async getSharedSecret(address: AztecAddress, ephPk: Point): Promise<Point> {
596
- // TODO(#12656): return an app-siloed secret
774
+ public async getSharedSecret(address: AztecAddress, ephPk: Point, contractAddress: AztecAddress): Promise<Fr> {
775
+ if (!contractAddress.equals(this.contractAddress)) {
776
+ throw new Error(
777
+ `getSharedSecret called with contract address ${contractAddress}, expected ${this.contractAddress}`,
778
+ );
779
+ }
597
780
  const recipientCompleteAddress = await this.getCompleteAddressOrFail(address);
598
781
  const ivskM = await this.keyStore.getMasterSecretKey(
599
782
  recipientCompleteAddress.publicKeys.masterIncomingViewingPublicKey,
600
783
  );
601
784
  const addressSecret = await computeAddressSecret(await recipientCompleteAddress.getPreaddress(), ivskM);
602
- return deriveEcdhSharedSecret(addressSecret, ephPk);
785
+ return deriveAppSiloedSharedSecret(addressSecret, ephPk, this.contractAddress);
786
+ }
787
+
788
+ public emitOffchainEffect(data: Fr[]): Promise<void> {
789
+ this.offchainEffects.push({ data, contractAddress: this.contractAddress });
790
+ return Promise.resolve();
791
+ }
792
+
793
+ /** Returns offchain effects collected during execution. */
794
+ public getOffchainEffects(): OffchainEffect[] {
795
+ return this.offchainEffects;
796
+ }
797
+
798
+ /** Runs a query concurrently with a validation that the block hash is not ahead of the anchor block. */
799
+ async #queryWithBlockHashNotAfterAnchor<T>(blockHash: BlockHash, query: () => Promise<T>): Promise<T> {
800
+ const [response] = await Promise.all([
801
+ query(),
802
+ (async () => {
803
+ const header = await this.aztecNode.getBlockHeader(blockHash);
804
+ if (!header) {
805
+ throw new Error(`Could not find block header for block hash ${blockHash}`);
806
+ }
807
+
808
+ if (header.getBlockNumber() > this.anchorBlockHeader.getBlockNumber()) {
809
+ throw new Error(
810
+ `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()}).`,
811
+ );
812
+ }
813
+ })(),
814
+ ]);
815
+ return response;
603
816
  }
604
817
  }