@aztec/pxe 0.0.1-commit.e558bd1c → 0.0.1-commit.e588bc7e5

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