@aztec/pxe 0.0.1-commit.fffb133c → 0.0.1-dev

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 (309) hide show
  1. package/dest/bin/check_oracle_version.js +5 -5
  2. package/dest/block_synchronizer/block_synchronizer.d.ts +10 -4
  3. package/dest/block_synchronizer/block_synchronizer.d.ts.map +1 -1
  4. package/dest/block_synchronizer/block_synchronizer.js +30 -6
  5. package/dest/config/package_info.js +1 -1
  6. package/dest/contract_function_simulator/contract_function_simulator.d.ts +66 -31
  7. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  8. package/dest/contract_function_simulator/contract_function_simulator.js +214 -75
  9. package/dest/contract_function_simulator/ephemeral_array_service.d.ts +28 -0
  10. package/dest/contract_function_simulator/ephemeral_array_service.d.ts.map +1 -0
  11. package/dest/contract_function_simulator/ephemeral_array_service.js +78 -0
  12. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts +7 -7
  13. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts.map +1 -1
  14. package/dest/contract_function_simulator/execution_tagging_index_cache.js +19 -11
  15. package/dest/contract_function_simulator/index.d.ts +2 -1
  16. package/dest/contract_function_simulator/index.d.ts.map +1 -1
  17. package/dest/contract_function_simulator/index.js +1 -0
  18. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts +4 -6
  19. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts.map +1 -1
  20. package/dest/contract_function_simulator/noir-structs/event_validation_request.js +8 -10
  21. package/dest/contract_function_simulator/noir-structs/log_retrieval_request.d.ts +1 -1
  22. package/dest/contract_function_simulator/noir-structs/log_retrieval_request.js +1 -1
  23. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts +2 -2
  24. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts.map +1 -1
  25. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.js +2 -4
  26. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts +4 -7
  27. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts.map +1 -1
  28. package/dest/contract_function_simulator/noir-structs/note_validation_request.js +6 -11
  29. package/dest/contract_function_simulator/oracle/interfaces.d.ts +66 -47
  30. package/dest/contract_function_simulator/oracle/interfaces.d.ts.map +1 -1
  31. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts +9 -0
  32. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts.map +1 -0
  33. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.js +47 -0
  34. package/dest/contract_function_simulator/oracle/oracle.d.ts +78 -44
  35. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  36. package/dest/contract_function_simulator/oracle/oracle.js +363 -114
  37. package/dest/contract_function_simulator/oracle/private_execution.js +5 -3
  38. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +56 -86
  39. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  40. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +123 -98
  41. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +145 -70
  42. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  43. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +435 -145
  44. package/dest/contract_function_simulator/pick_notes.d.ts +1 -1
  45. package/dest/contract_function_simulator/pick_notes.d.ts.map +1 -1
  46. package/dest/contract_function_simulator/pick_notes.js +20 -3
  47. package/dest/contract_function_simulator/proxied_contract_data_source.d.ts +1 -1
  48. package/dest/contract_function_simulator/proxied_contract_data_source.d.ts.map +1 -1
  49. package/dest/contract_function_simulator/proxied_contract_data_source.js +3 -0
  50. package/dest/contract_logging.d.ts +27 -0
  51. package/dest/contract_logging.d.ts.map +1 -0
  52. package/dest/contract_logging.js +38 -0
  53. package/dest/contract_sync/contract_sync_service.d.ts +45 -0
  54. package/dest/contract_sync/contract_sync_service.d.ts.map +1 -0
  55. package/dest/contract_sync/contract_sync_service.js +150 -0
  56. package/dest/contract_sync/helpers.d.ts +27 -0
  57. package/dest/contract_sync/helpers.d.ts.map +1 -0
  58. package/dest/contract_sync/{index.js → helpers.js} +16 -17
  59. package/dest/debug/pxe_debug_utils.d.ts +24 -10
  60. package/dest/debug/pxe_debug_utils.d.ts.map +1 -1
  61. package/dest/debug/pxe_debug_utils.js +28 -18
  62. package/dest/entrypoints/client/bundle/index.d.ts +3 -1
  63. package/dest/entrypoints/client/bundle/index.d.ts.map +1 -1
  64. package/dest/entrypoints/client/bundle/index.js +2 -0
  65. package/dest/entrypoints/client/bundle/utils.d.ts +2 -2
  66. package/dest/entrypoints/client/bundle/utils.d.ts.map +1 -1
  67. package/dest/entrypoints/client/bundle/utils.js +24 -9
  68. package/dest/entrypoints/client/lazy/index.d.ts +3 -1
  69. package/dest/entrypoints/client/lazy/index.d.ts.map +1 -1
  70. package/dest/entrypoints/client/lazy/index.js +2 -0
  71. package/dest/entrypoints/client/lazy/utils.d.ts +3 -3
  72. package/dest/entrypoints/client/lazy/utils.d.ts.map +1 -1
  73. package/dest/entrypoints/client/lazy/utils.js +25 -10
  74. package/dest/entrypoints/pxe_creation_options.d.ts +8 -2
  75. package/dest/entrypoints/pxe_creation_options.d.ts.map +1 -1
  76. package/dest/entrypoints/pxe_creation_options.js +3 -1
  77. package/dest/entrypoints/server/index.d.ts +5 -3
  78. package/dest/entrypoints/server/index.d.ts.map +1 -1
  79. package/dest/entrypoints/server/index.js +4 -2
  80. package/dest/entrypoints/server/utils.d.ts +2 -2
  81. package/dest/entrypoints/server/utils.d.ts.map +1 -1
  82. package/dest/entrypoints/server/utils.js +31 -11
  83. package/dest/events/event_service.d.ts +16 -8
  84. package/dest/events/event_service.d.ts.map +1 -1
  85. package/dest/events/event_service.js +46 -14
  86. package/dest/events/private_event_filter_validator.d.ts +3 -2
  87. package/dest/events/private_event_filter_validator.d.ts.map +1 -1
  88. package/dest/events/private_event_filter_validator.js +15 -0
  89. package/dest/hooks/authorize_utility_call.d.ts +37 -0
  90. package/dest/hooks/authorize_utility_call.d.ts.map +1 -0
  91. package/dest/hooks/authorize_utility_call.js +4 -0
  92. package/dest/hooks/execution_hooks.d.ts +42 -0
  93. package/dest/hooks/execution_hooks.d.ts.map +1 -0
  94. package/dest/hooks/execution_hooks.js +9 -0
  95. package/dest/hooks/index.d.ts +4 -0
  96. package/dest/hooks/index.d.ts.map +1 -0
  97. package/dest/hooks/index.js +1 -0
  98. package/dest/job_coordinator/job_coordinator.d.ts +3 -2
  99. package/dest/job_coordinator/job_coordinator.d.ts.map +1 -1
  100. package/dest/job_coordinator/job_coordinator.js +3 -2
  101. package/dest/logs/log_service.d.ts +10 -9
  102. package/dest/logs/log_service.d.ts.map +1 -1
  103. package/dest/logs/log_service.js +50 -85
  104. package/dest/messages/message_context_service.d.ts +17 -0
  105. package/dest/messages/message_context_service.d.ts.map +1 -0
  106. package/dest/messages/message_context_service.js +38 -0
  107. package/dest/notes/note_service.d.ts +29 -8
  108. package/dest/notes/note_service.d.ts.map +1 -1
  109. package/dest/notes/note_service.js +89 -65
  110. package/dest/notes_filter.d.ts +24 -0
  111. package/dest/notes_filter.d.ts.map +1 -0
  112. package/dest/notes_filter.js +4 -0
  113. package/dest/oracle_version.d.ts +4 -3
  114. package/dest/oracle_version.d.ts.map +1 -1
  115. package/dest/oracle_version.js +20 -10
  116. package/dest/private_kernel/hints/compute_tx_expiration_timestamp.d.ts +4 -0
  117. package/dest/private_kernel/hints/compute_tx_expiration_timestamp.d.ts.map +1 -0
  118. package/dest/private_kernel/hints/{compute_tx_include_by_timestamp.js → compute_tx_expiration_timestamp.js} +12 -12
  119. package/dest/private_kernel/hints/index.d.ts +1 -1
  120. package/dest/private_kernel/hints/index.js +1 -1
  121. package/dest/private_kernel/hints/private_kernel_reset_private_inputs_builder.d.ts +4 -3
  122. package/dest/private_kernel/hints/private_kernel_reset_private_inputs_builder.d.ts.map +1 -1
  123. package/dest/private_kernel/hints/private_kernel_reset_private_inputs_builder.js +129 -68
  124. package/dest/private_kernel/hints/test_utils.d.ts +122 -0
  125. package/dest/private_kernel/hints/test_utils.d.ts.map +1 -0
  126. package/dest/private_kernel/hints/test_utils.js +203 -0
  127. package/dest/private_kernel/private_kernel_execution_prover.d.ts +4 -2
  128. package/dest/private_kernel/private_kernel_execution_prover.d.ts.map +1 -1
  129. package/dest/private_kernel/private_kernel_execution_prover.js +38 -19
  130. package/dest/private_kernel/private_kernel_oracle.d.ts +10 -6
  131. package/dest/private_kernel/private_kernel_oracle.d.ts.map +1 -1
  132. package/dest/private_kernel/private_kernel_oracle.js +26 -20
  133. package/dest/pxe.d.ts +87 -23
  134. package/dest/pxe.d.ts.map +1 -1
  135. package/dest/pxe.js +178 -119
  136. package/dest/storage/address_store/address_store.d.ts +1 -1
  137. package/dest/storage/address_store/address_store.d.ts.map +1 -1
  138. package/dest/storage/address_store/address_store.js +12 -11
  139. package/dest/storage/anchor_block_store/anchor_block_store.d.ts +9 -1
  140. package/dest/storage/anchor_block_store/anchor_block_store.d.ts.map +1 -1
  141. package/dest/storage/anchor_block_store/anchor_block_store.js +9 -2
  142. package/dest/storage/backwards_compatibility_tests/kv_store_snapshot.d.ts +42 -0
  143. package/dest/storage/backwards_compatibility_tests/kv_store_snapshot.d.ts.map +1 -0
  144. package/dest/storage/backwards_compatibility_tests/kv_store_snapshot.js +93 -0
  145. package/dest/storage/backwards_compatibility_tests/schema_tests.d.ts +15 -0
  146. package/dest/storage/backwards_compatibility_tests/schema_tests.d.ts.map +1 -0
  147. package/dest/storage/backwards_compatibility_tests/schema_tests.js +588 -0
  148. package/dest/storage/backwards_compatibility_tests/store_spy.d.ts +19 -0
  149. package/dest/storage/backwards_compatibility_tests/store_spy.d.ts.map +1 -0
  150. package/dest/storage/backwards_compatibility_tests/store_spy.js +63 -0
  151. package/dest/storage/capsule_store/capsule_service.d.ts +21 -0
  152. package/dest/storage/capsule_store/capsule_service.d.ts.map +1 -0
  153. package/dest/storage/capsule_store/capsule_service.js +50 -0
  154. package/dest/storage/capsule_store/capsule_store.d.ts +9 -9
  155. package/dest/storage/capsule_store/capsule_store.d.ts.map +1 -1
  156. package/dest/storage/capsule_store/capsule_store.js +42 -36
  157. package/dest/storage/capsule_store/index.d.ts +2 -1
  158. package/dest/storage/capsule_store/index.d.ts.map +1 -1
  159. package/dest/storage/capsule_store/index.js +1 -0
  160. package/dest/storage/contract_store/contract_store.d.ts +42 -15
  161. package/dest/storage/contract_store/contract_store.d.ts.map +1 -1
  162. package/dest/storage/contract_store/contract_store.js +160 -73
  163. package/dest/storage/metadata.d.ts +1 -1
  164. package/dest/storage/metadata.js +1 -1
  165. package/dest/storage/note_store/note_store.d.ts +13 -3
  166. package/dest/storage/note_store/note_store.d.ts.map +1 -1
  167. package/dest/storage/note_store/note_store.js +147 -107
  168. package/dest/storage/open_pxe_stores.d.ts +31 -0
  169. package/dest/storage/open_pxe_stores.d.ts.map +1 -0
  170. package/dest/storage/open_pxe_stores.js +26 -0
  171. package/dest/storage/private_event_store/private_event_store.d.ts +1 -1
  172. package/dest/storage/private_event_store/private_event_store.d.ts.map +1 -1
  173. package/dest/storage/private_event_store/private_event_store.js +87 -61
  174. package/dest/storage/private_event_store/stored_private_event.d.ts +4 -4
  175. package/dest/storage/private_event_store/stored_private_event.d.ts.map +1 -1
  176. package/dest/storage/private_event_store/stored_private_event.js +2 -2
  177. package/dest/storage/tagging_store/recipient_tagging_store.d.ts +6 -6
  178. package/dest/storage/tagging_store/recipient_tagging_store.d.ts.map +1 -1
  179. package/dest/storage/tagging_store/recipient_tagging_store.js +31 -19
  180. package/dest/storage/tagging_store/sender_address_book_store.d.ts +1 -1
  181. package/dest/storage/tagging_store/sender_address_book_store.d.ts.map +1 -1
  182. package/dest/storage/tagging_store/sender_address_book_store.js +20 -14
  183. package/dest/storage/tagging_store/sender_tagging_store.d.ts +29 -28
  184. package/dest/storage/tagging_store/sender_tagging_store.d.ts.map +1 -1
  185. package/dest/storage/tagging_store/sender_tagging_store.js +233 -137
  186. package/dest/tagging/get_all_logs_by_tags.d.ts +4 -4
  187. package/dest/tagging/get_all_logs_by_tags.d.ts.map +1 -1
  188. package/dest/tagging/get_all_logs_by_tags.js +20 -3
  189. package/dest/tagging/index.d.ts +6 -5
  190. package/dest/tagging/index.d.ts.map +1 -1
  191. package/dest/tagging/index.js +4 -3
  192. package/dest/tagging/persist_sender_tagging_index_ranges.d.ts +29 -0
  193. package/dest/tagging/persist_sender_tagging_index_ranges.d.ts.map +1 -0
  194. package/dest/tagging/persist_sender_tagging_index_ranges.js +42 -0
  195. package/dest/tagging/recipient_sync/sync_tagged_private_logs.d.ts +56 -0
  196. package/dest/tagging/recipient_sync/sync_tagged_private_logs.d.ts.map +1 -0
  197. package/dest/tagging/recipient_sync/sync_tagged_private_logs.js +158 -0
  198. package/dest/tagging/recipient_sync/utils/find_highest_indexes.js +2 -2
  199. package/dest/tagging/reconcile_tagging_index_ranges.d.ts +36 -0
  200. package/dest/tagging/reconcile_tagging_index_ranges.d.ts.map +1 -0
  201. package/dest/tagging/reconcile_tagging_index_ranges.js +74 -0
  202. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +5 -9
  203. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  204. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +30 -13
  205. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +13 -7
  206. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +1 -1
  207. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +41 -10
  208. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +6 -8
  209. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  210. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +36 -24
  211. package/package.json +26 -16
  212. package/src/bin/check_oracle_version.ts +5 -5
  213. package/src/block_synchronizer/block_synchronizer.ts +45 -21
  214. package/src/config/package_info.ts +1 -1
  215. package/src/contract_function_simulator/contract_function_simulator.ts +389 -134
  216. package/src/contract_function_simulator/ephemeral_array_service.ts +110 -0
  217. package/src/contract_function_simulator/execution_tagging_index_cache.ts +19 -14
  218. package/src/contract_function_simulator/index.ts +1 -0
  219. package/src/contract_function_simulator/noir-structs/event_validation_request.ts +9 -9
  220. package/src/contract_function_simulator/noir-structs/log_retrieval_request.ts +1 -1
  221. package/src/contract_function_simulator/noir-structs/log_retrieval_response.ts +2 -5
  222. package/src/contract_function_simulator/noir-structs/note_validation_request.ts +4 -10
  223. package/src/contract_function_simulator/oracle/interfaces.ts +101 -62
  224. package/src/contract_function_simulator/oracle/legacy_oracle_mappings.ts +104 -0
  225. package/src/contract_function_simulator/oracle/oracle.ts +464 -151
  226. package/src/contract_function_simulator/oracle/private_execution.ts +4 -4
  227. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +152 -191
  228. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +709 -200
  229. package/src/contract_function_simulator/pick_notes.ts +22 -3
  230. package/src/contract_function_simulator/proxied_contract_data_source.ts +8 -1
  231. package/src/contract_logging.ts +52 -0
  232. package/src/contract_sync/contract_sync_service.ts +208 -0
  233. package/src/contract_sync/{index.ts → helpers.ts} +17 -29
  234. package/src/debug/pxe_debug_utils.ts +63 -19
  235. package/src/entrypoints/client/bundle/index.ts +2 -0
  236. package/src/entrypoints/client/bundle/utils.ts +19 -18
  237. package/src/entrypoints/client/lazy/index.ts +2 -0
  238. package/src/entrypoints/client/lazy/utils.ts +20 -18
  239. package/src/entrypoints/pxe_creation_options.ts +13 -1
  240. package/src/entrypoints/server/index.ts +4 -2
  241. package/src/entrypoints/server/utils.ts +25 -29
  242. package/src/events/event_service.ts +70 -24
  243. package/src/events/private_event_filter_validator.ts +21 -1
  244. package/src/hooks/authorize_utility_call.ts +40 -0
  245. package/src/hooks/execution_hooks.ts +48 -0
  246. package/src/hooks/index.ts +7 -0
  247. package/src/job_coordinator/job_coordinator.ts +4 -3
  248. package/src/logs/log_service.ts +88 -141
  249. package/src/messages/message_context_service.ts +45 -0
  250. package/src/notes/note_service.ts +124 -91
  251. package/src/notes_filter.ts +24 -0
  252. package/src/oracle_version.ts +20 -10
  253. package/src/private_kernel/hints/{compute_tx_include_by_timestamp.ts → compute_tx_expiration_timestamp.ts} +13 -13
  254. package/src/private_kernel/hints/index.ts +1 -1
  255. package/src/private_kernel/hints/private_kernel_reset_private_inputs_builder.ts +164 -117
  256. package/src/private_kernel/hints/test_utils.ts +325 -0
  257. package/src/private_kernel/private_kernel_execution_prover.ts +53 -22
  258. package/src/private_kernel/private_kernel_oracle.ts +36 -26
  259. package/src/pxe.ts +351 -168
  260. package/src/storage/address_store/address_store.ts +15 -15
  261. package/src/storage/anchor_block_store/anchor_block_store.ts +9 -1
  262. package/src/storage/backwards_compatibility_tests/__snapshots__/AddressStore.json +22 -0
  263. package/src/storage/backwards_compatibility_tests/__snapshots__/AnchorBlockStore.json +3 -0
  264. package/src/storage/backwards_compatibility_tests/__snapshots__/CapsuleStore.json +16 -0
  265. package/src/storage/backwards_compatibility_tests/__snapshots__/ContractStore.json +28 -0
  266. package/src/storage/backwards_compatibility_tests/__snapshots__/KeyStore.json +52 -0
  267. package/src/storage/backwards_compatibility_tests/__snapshots__/L2TipsKVStore.json +42 -0
  268. package/src/storage/backwards_compatibility_tests/__snapshots__/NoteStore.json +36 -0
  269. package/src/storage/backwards_compatibility_tests/__snapshots__/PrivateEventStore.json +44 -0
  270. package/src/storage/backwards_compatibility_tests/__snapshots__/RecipientTaggingStore.json +18 -0
  271. package/src/storage/backwards_compatibility_tests/__snapshots__/SenderAddressBookStore.json +16 -0
  272. package/src/storage/backwards_compatibility_tests/__snapshots__/SenderTaggingStore.json +22 -0
  273. package/src/storage/backwards_compatibility_tests/__snapshots__/opened_stores.json +97 -0
  274. package/src/storage/backwards_compatibility_tests/kv_store_snapshot.ts +122 -0
  275. package/src/storage/backwards_compatibility_tests/schema_tests.ts +707 -0
  276. package/src/storage/backwards_compatibility_tests/store_spy.ts +73 -0
  277. package/src/storage/capsule_store/capsule_service.ts +90 -0
  278. package/src/storage/capsule_store/capsule_store.ts +52 -34
  279. package/src/storage/capsule_store/index.ts +1 -0
  280. package/src/storage/contract_store/contract_store.ts +193 -81
  281. package/src/storage/metadata.ts +1 -1
  282. package/src/storage/note_store/note_store.ts +166 -132
  283. package/src/storage/open_pxe_stores.ts +47 -0
  284. package/src/storage/private_event_store/private_event_store.ts +106 -81
  285. package/src/storage/private_event_store/stored_private_event.ts +3 -3
  286. package/src/storage/tagging_store/recipient_tagging_store.ts +38 -24
  287. package/src/storage/tagging_store/sender_address_book_store.ts +20 -14
  288. package/src/storage/tagging_store/sender_tagging_store.ts +287 -156
  289. package/src/tagging/get_all_logs_by_tags.ts +35 -7
  290. package/src/tagging/index.ts +5 -4
  291. package/src/tagging/persist_sender_tagging_index_ranges.ts +57 -0
  292. package/src/tagging/recipient_sync/sync_tagged_private_logs.ts +236 -0
  293. package/src/tagging/recipient_sync/utils/find_highest_indexes.ts +2 -2
  294. package/src/tagging/reconcile_tagging_index_ranges.ts +102 -0
  295. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +54 -18
  296. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +44 -14
  297. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +30 -29
  298. package/dest/contract_sync/index.d.ts +0 -23
  299. package/dest/contract_sync/index.d.ts.map +0 -1
  300. package/dest/private_kernel/hints/compute_tx_include_by_timestamp.d.ts +0 -4
  301. package/dest/private_kernel/hints/compute_tx_include_by_timestamp.d.ts.map +0 -1
  302. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.d.ts +0 -15
  303. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.d.ts.map +0 -1
  304. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.js +0 -99
  305. package/dest/tagging/recipient_sync/utils/load_logs_for_range.d.ts +0 -15
  306. package/dest/tagging/recipient_sync/utils/load_logs_for_range.d.ts.map +0 -1
  307. package/dest/tagging/recipient_sync/utils/load_logs_for_range.js +0 -32
  308. package/src/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.ts +0 -143
  309. package/src/tagging/recipient_sync/utils/load_logs_for_range.ts +0 -49
@@ -1,37 +1,52 @@
1
1
  import type { ARCHIVE_HEIGHT, NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
2
2
  import type { BlockNumber } from '@aztec/foundation/branded-types';
3
+ import { uniqueBy } from '@aztec/foundation/collection';
3
4
  import { Aes128 } from '@aztec/foundation/crypto/aes128';
4
5
  import { Fr } from '@aztec/foundation/curves/bn254';
5
6
  import { Point } from '@aztec/foundation/curves/grumpkin';
6
- import { LogLevels, applyStringFormatting, createLogger } from '@aztec/foundation/log';
7
+ import { LogLevels, type Logger, createLogger } from '@aztec/foundation/log';
7
8
  import type { MembershipWitness } from '@aztec/foundation/trees';
8
9
  import type { KeyStore } from '@aztec/key-store';
10
+ import { isProtocolContract } from '@aztec/protocol-contracts';
11
+ import {
12
+ type CircuitSimulator,
13
+ ExecutionError,
14
+ extractCallStack,
15
+ resolveAssertionMessageFromError,
16
+ toACVMWitness,
17
+ witnessMapToFields,
18
+ } from '@aztec/simulator/client';
19
+ import { type FunctionCall, FunctionSelector } from '@aztec/stdlib/abi';
9
20
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
10
21
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
11
- import { L2BlockHash } from '@aztec/stdlib/block';
12
- import type { CompleteAddress, ContractInstance } from '@aztec/stdlib/contract';
22
+ import { BlockHash, type L2TipsProvider } from '@aztec/stdlib/block';
23
+ import type { CompleteAddress, ContractInstance, PartialAddress } from '@aztec/stdlib/contract';
13
24
  import { siloNullifier } from '@aztec/stdlib/hash';
14
25
  import type { AztecNode } from '@aztec/stdlib/interfaces/server';
15
26
  import type { KeyValidationRequest } from '@aztec/stdlib/kernel';
16
- import { computeAddressSecret } from '@aztec/stdlib/keys';
17
- import { deriveEcdhSharedSecret } from '@aztec/stdlib/logs';
27
+ import { type PublicKeys, computeAddressSecret } from '@aztec/stdlib/keys';
28
+ import { MessageContext, deriveAppSiloedSharedSecret } from '@aztec/stdlib/logs';
18
29
  import { getNonNullifiedL1ToL2MessageWitness } from '@aztec/stdlib/messaging';
19
30
  import type { NoteStatus } from '@aztec/stdlib/note';
20
31
  import { MerkleTreeId, type NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
21
- import type { BlockHeader, Capsule } from '@aztec/stdlib/tx';
32
+ import type { BlockHeader, Capsule, IndexedTxEffect, OffchainEffect, TxEffect, TxHash } from '@aztec/stdlib/tx';
22
33
 
34
+ import { createContractLogger, logContractMessage, stripAztecnrLogPrefix } from '../../contract_logging.js';
35
+ import type { ContractSyncService } from '../../contract_sync/contract_sync_service.js';
23
36
  import { EventService } from '../../events/event_service.js';
37
+ import type { ExecutionHooks } from '../../hooks/index.js';
24
38
  import { LogService } from '../../logs/log_service.js';
39
+ import { MessageContextService } from '../../messages/message_context_service.js';
25
40
  import { NoteService } from '../../notes/note_service.js';
26
- import { ORACLE_VERSION } from '../../oracle_version.js';
41
+ import { ORACLE_VERSION_MAJOR } from '../../oracle_version.js';
27
42
  import type { AddressStore } from '../../storage/address_store/address_store.js';
28
- import type { AnchorBlockStore } from '../../storage/anchor_block_store/anchor_block_store.js';
29
- import type { CapsuleStore } from '../../storage/capsule_store/capsule_store.js';
43
+ import type { CapsuleService } from '../../storage/capsule_store/capsule_service.js';
30
44
  import type { ContractStore } from '../../storage/contract_store/contract_store.js';
31
45
  import type { NoteStore } from '../../storage/note_store/note_store.js';
32
46
  import type { PrivateEventStore } from '../../storage/private_event_store/private_event_store.js';
33
47
  import type { RecipientTaggingStore } from '../../storage/tagging_store/recipient_tagging_store.js';
34
48
  import type { SenderAddressBookStore } from '../../storage/tagging_store/sender_address_book_store.js';
49
+ import { EphemeralArrayService } from '../ephemeral_array_service.js';
35
50
  import { EventValidationRequest } from '../noir-structs/event_validation_request.js';
36
51
  import { LogRetrievalRequest } from '../noir-structs/log_retrieval_request.js';
37
52
  import { LogRetrievalResponse } from '../noir-structs/log_retrieval_response.js';
@@ -40,6 +55,35 @@ import { UtilityContext } from '../noir-structs/utility_context.js';
40
55
  import { pickNotes } from '../pick_notes.js';
41
56
  import type { IMiscOracle, IUtilityExecutionOracle, NoteData } from './interfaces.js';
42
57
  import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
58
+ import { Oracle } from './oracle.js';
59
+
60
+ /** Args for UtilityExecutionOracle constructor. */
61
+ export type UtilityExecutionOracleArgs = {
62
+ contractAddress: AztecAddress;
63
+ /** List of transient auth witnesses to be used during this simulation */
64
+ authWitnesses: AuthWitness[];
65
+ capsules: Capsule[]; // TODO(#12425): Rename to transientCapsules
66
+ anchorBlockHeader: BlockHeader;
67
+ contractStore: ContractStore;
68
+ noteStore: NoteStore;
69
+ keyStore: KeyStore;
70
+ addressStore: AddressStore;
71
+ aztecNode: AztecNode;
72
+ recipientTaggingStore: RecipientTaggingStore;
73
+ senderAddressBookStore: SenderAddressBookStore;
74
+ capsuleService: CapsuleService;
75
+ privateEventStore: PrivateEventStore;
76
+ messageContextService: MessageContextService;
77
+ contractSyncService: ContractSyncService;
78
+ l2TipsStore: L2TipsProvider;
79
+ jobId: string;
80
+ log?: ReturnType<typeof createLogger>;
81
+ scopes: AztecAddress[];
82
+ simulator: CircuitSimulator;
83
+ hooks?: ExecutionHooks;
84
+ /** Needed to trigger contract synchronization before nested cross-contract calls. */
85
+ utilityExecutor: (call: FunctionCall, scopes: AztecAddress[]) => Promise<void>;
86
+ };
43
87
 
44
88
  /**
45
89
  * The oracle for an execution of utility contract functions.
@@ -48,40 +92,107 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
48
92
  isMisc = true as const;
49
93
  isUtility = true as const;
50
94
 
51
- private aztecNrDebugLog = createLogger('aztec-nr:debug_log');
52
-
53
- constructor(
54
- protected readonly contractAddress: AztecAddress,
55
- /** List of transient auth witnesses to be used during this simulation */
56
- protected readonly authWitnesses: AuthWitness[],
57
- protected readonly capsules: Capsule[], // TODO(#12425): Rename to transientCapsules
58
- protected readonly anchorBlockHeader: BlockHeader,
59
- protected readonly contractStore: ContractStore,
60
- protected readonly noteStore: NoteStore,
61
- protected readonly keyStore: KeyStore,
62
- protected readonly addressStore: AddressStore,
63
- protected readonly aztecNode: AztecNode,
64
- protected readonly anchorBlockStore: AnchorBlockStore,
65
- protected readonly recipientTaggingStore: RecipientTaggingStore,
66
- protected readonly senderAddressBookStore: SenderAddressBookStore,
67
- protected readonly capsuleStore: CapsuleStore,
68
- protected readonly privateEventStore: PrivateEventStore,
69
- protected readonly jobId: string,
70
- protected log = createLogger('simulator:client_view_context'),
71
- protected readonly scopes?: AztecAddress[],
72
- ) {}
73
-
74
- public utilityAssertCompatibleOracleVersion(version: number): void {
75
- if (version !== ORACLE_VERSION) {
76
- throw new Error(`Incompatible oracle version. Expected version ${ORACLE_VERSION}, got ${version}.`);
95
+ private contractLogger: Logger | undefined;
96
+ private aztecnrLogger: Logger | undefined;
97
+ private offchainEffects: OffchainEffect[] = [];
98
+ private readonly ephemeralArrayService = new EphemeralArrayService();
99
+
100
+ // We store oracle version to be able to show a nice error message when an oracle handler is missing.
101
+ private contractOracleVersion: { major: number; minor: number } | undefined;
102
+
103
+ protected readonly contractAddress: AztecAddress;
104
+ protected readonly authWitnesses: AuthWitness[];
105
+ protected readonly capsules: Capsule[];
106
+ protected readonly anchorBlockHeader: BlockHeader;
107
+ protected readonly contractStore: ContractStore;
108
+ protected readonly noteStore: NoteStore;
109
+ protected readonly keyStore: KeyStore;
110
+ protected readonly addressStore: AddressStore;
111
+ protected readonly aztecNode: AztecNode;
112
+ protected readonly recipientTaggingStore: RecipientTaggingStore;
113
+ protected readonly senderAddressBookStore: SenderAddressBookStore;
114
+ protected readonly capsuleService: CapsuleService;
115
+ protected readonly privateEventStore: PrivateEventStore;
116
+ protected readonly messageContextService: MessageContextService;
117
+ protected readonly contractSyncService: ContractSyncService;
118
+ protected readonly l2TipsStore: L2TipsProvider;
119
+ protected readonly jobId: string;
120
+ protected logger: ReturnType<typeof createLogger>;
121
+ protected readonly scopes: AztecAddress[];
122
+ protected readonly simulator: CircuitSimulator;
123
+ protected readonly hooks: ExecutionHooks | undefined;
124
+ protected readonly utilityExecutor: (call: FunctionCall, scopes: AztecAddress[]) => Promise<void>;
125
+
126
+ constructor(args: UtilityExecutionOracleArgs) {
127
+ this.contractAddress = args.contractAddress;
128
+ this.authWitnesses = args.authWitnesses;
129
+ this.capsules = args.capsules;
130
+ this.anchorBlockHeader = args.anchorBlockHeader;
131
+ this.contractStore = args.contractStore;
132
+ this.noteStore = args.noteStore;
133
+ this.keyStore = args.keyStore;
134
+ this.addressStore = args.addressStore;
135
+ this.aztecNode = args.aztecNode;
136
+ this.recipientTaggingStore = args.recipientTaggingStore;
137
+ this.senderAddressBookStore = args.senderAddressBookStore;
138
+ this.capsuleService = args.capsuleService;
139
+ this.privateEventStore = args.privateEventStore;
140
+ this.messageContextService = args.messageContextService;
141
+ this.contractSyncService = args.contractSyncService;
142
+ this.l2TipsStore = args.l2TipsStore;
143
+ this.jobId = args.jobId;
144
+ this.logger = args.log ?? createLogger('simulator:client_view_context');
145
+ this.scopes = args.scopes;
146
+ this.simulator = args.simulator;
147
+ this.hooks = args.hooks;
148
+ this.utilityExecutor = args.utilityExecutor;
149
+ }
150
+
151
+ public assertCompatibleOracleVersion(major: number, minor: number): void {
152
+ // TODO(F-416): Remove this hack on v5 when protocol contracts are redeployed.
153
+ // Protocol contracts/canonical contracts shipped with committed bytecode that cannot be changed. Assert they use
154
+ // the expected pinned version or the current one. We want to allow for both the pinned and the current versions
155
+ // because we want this code to work with both the pinned and unpinned version since some branches do not have the
156
+ // pinned contracts (like e.g. next)
157
+ const LEGACY_ORACLE_VERSION = 12;
158
+ if (isProtocolContract(this.contractAddress)) {
159
+ if (major !== LEGACY_ORACLE_VERSION && major !== ORACLE_VERSION_MAJOR) {
160
+ const hint =
161
+ major > ORACLE_VERSION_MAJOR
162
+ ? 'The contract was compiled with a newer version of Aztec.nr than your private environment supports. Upgrade your private environment to a compatible version.'
163
+ : '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.';
164
+ throw new Error(
165
+ `Incompatible private environment version: ${hint} See https://docs.aztec.network/errors/8 (expected oracle major version ${LEGACY_ORACLE_VERSION} or ${ORACLE_VERSION_MAJOR}, got ${major})`,
166
+ );
167
+ }
168
+ this.contractOracleVersion = { major, minor };
169
+ return;
77
170
  }
171
+
172
+ if (major !== ORACLE_VERSION_MAJOR) {
173
+ const hint =
174
+ major > ORACLE_VERSION_MAJOR
175
+ ? 'The contract was compiled with a newer version of Aztec.nr than your private environment supports. Upgrade your private environment to a compatible version.'
176
+ : '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.';
177
+ throw new Error(
178
+ `Incompatible private environment version: ${hint} See https://docs.aztec.network/errors/8 (expected oracle major version ${ORACLE_VERSION_MAJOR}, got ${major})`,
179
+ );
180
+ }
181
+
182
+ // Major matches - store both major and minor for later diagnostics (e.g. when an oracle is not found)
183
+ this.contractOracleVersion = { major, minor };
184
+ }
185
+
186
+ // Prefixed with "nonOracleFunction" as it is not used as an oracle handler.
187
+ public nonOracleFunctionGetContractOracleVersion(): { major: number; minor: number } | undefined {
188
+ return this.contractOracleVersion;
78
189
  }
79
190
 
80
- public utilityGetRandomField(): Fr {
191
+ public getRandomField(): Fr {
81
192
  return Fr.random();
82
193
  }
83
194
 
84
- public utilityGetUtilityContext(): UtilityContext {
195
+ public getUtilityContext(): UtilityContext {
85
196
  return new UtilityContext(this.anchorBlockHeader, this.contractAddress);
86
197
  }
87
198
 
@@ -90,35 +201,58 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
90
201
  * @param pkMHash - The master public key hash.
91
202
  * @returns A Promise that resolves to nullifier keys.
92
203
  * @throws If the keys are not registered in the key store.
204
+ * @throws If scopes are defined and the account is not in the scopes.
93
205
  */
94
- public utilityGetKeyValidationRequest(pkMHash: Fr): Promise<KeyValidationRequest> {
206
+ public async getKeyValidationRequest(pkMHash: Fr): Promise<KeyValidationRequest> {
207
+ let hasAccess = false;
208
+ for (let i = 0; i < this.scopes.length && !hasAccess; i++) {
209
+ if (await this.keyStore.accountHasKey(this.scopes[i], pkMHash)) {
210
+ hasAccess = true;
211
+ }
212
+ }
213
+ if (!hasAccess) {
214
+ throw new Error(`Key validation request denied: no scoped account has a key with hash ${pkMHash.toString()}.`);
215
+ }
95
216
  return this.keyStore.getKeyValidationRequest(pkMHash, this.contractAddress);
96
217
  }
97
218
 
98
219
  /**
99
220
  * Fetches the index and sibling path of a leaf at a given block from the note hash tree.
100
- * @param blockHash - The block hash at which to get the membership witness.
101
- * @param leafValue - The leaf value
221
+ * @param blockHash - The hash of a block that contains the note hash tree root in which to find the
222
+ * membership witness.
223
+ * @param noteHash - The note hash to find in the note hash tree.
102
224
  * @returns The membership witness containing the leaf index and sibling path
103
225
  */
104
- public utilityGetNoteHashMembershipWitness(
105
- blockHash: L2BlockHash,
106
- leafValue: Fr,
226
+ public getNoteHashMembershipWitness(
227
+ blockHash: BlockHash,
228
+ noteHash: Fr,
107
229
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
108
- return this.aztecNode.getNoteHashMembershipWitness(blockHash, leafValue);
230
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
231
+ this.aztecNode.getNoteHashMembershipWitness(blockHash, noteHash),
232
+ );
109
233
  }
110
234
 
111
235
  /**
112
- * Fetches the index and sibling path of a leaf at a given block from the archive tree.
113
- * @param blockHash - The block hash at which to get the membership witness.
114
- * @param leafValue - The leaf value
236
+ * Fetches the index and sibling path of a block hash in the archive tree.
237
+ *
238
+ * Block hashes are the leaves of the archive tree. Each time a new block is added to the chain,
239
+ * its block hash is appended as a new leaf to the archive tree.
240
+ *
241
+ * @param referenceBlockHash - The hash of a block that contains the archive tree root in which to find the membership
242
+ * witness.
243
+ * @param blockHash - The block hash to find in the archive tree.
115
244
  * @returns The membership witness containing the leaf index and sibling path
116
245
  */
117
- public utilityGetArchiveMembershipWitness(
118
- blockHash: L2BlockHash,
119
- leafValue: Fr,
246
+ public getBlockHashMembershipWitness(
247
+ referenceBlockHash: BlockHash,
248
+ blockHash: BlockHash,
120
249
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
121
- return this.aztecNode.getArchiveMembershipWitness(blockHash, leafValue);
250
+ // Note that we validate that the reference block hash is at or before the anchor block - we don't test the block
251
+ // hash at all. If the block hash did not exist by the reference block hash, then the node will not return the
252
+ // membership witness as there is none.
253
+ return this.#queryWithBlockHashNotAfterAnchor(referenceBlockHash, () =>
254
+ this.aztecNode.getBlockHashMembershipWitness(referenceBlockHash, blockHash),
255
+ );
122
256
  }
123
257
 
124
258
  /**
@@ -127,11 +261,13 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
127
261
  * @param nullifier - Nullifier we try to find witness for.
128
262
  * @returns The nullifier membership witness (if found).
129
263
  */
130
- public utilityGetNullifierMembershipWitness(
131
- blockHash: L2BlockHash,
264
+ public getNullifierMembershipWitness(
265
+ blockHash: BlockHash,
132
266
  nullifier: Fr,
133
267
  ): Promise<NullifierMembershipWitness | undefined> {
134
- return this.aztecNode.getNullifierMembershipWitness(blockHash, nullifier);
268
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
269
+ this.aztecNode.getNullifierMembershipWitness(blockHash, nullifier),
270
+ );
135
271
  }
136
272
 
137
273
  /**
@@ -143,11 +279,13 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
143
279
  * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
144
280
  * we are trying to prove non-inclusion for.
145
281
  */
146
- public utilityGetLowNullifierMembershipWitness(
147
- blockHash: L2BlockHash,
282
+ public getLowNullifierMembershipWitness(
283
+ blockHash: BlockHash,
148
284
  nullifier: Fr,
149
285
  ): Promise<NullifierMembershipWitness | undefined> {
150
- return this.aztecNode.getLowNullifierMembershipWitness(blockHash, nullifier);
286
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
287
+ this.aztecNode.getLowNullifierMembershipWitness(blockHash, nullifier),
288
+ );
151
289
  }
152
290
 
153
291
  /**
@@ -156,8 +294,10 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
156
294
  * @param leafSlot - The slot of the public data tree to get the witness for.
157
295
  * @returns - The witness
158
296
  */
159
- public utilityGetPublicDataWitness(blockHash: L2BlockHash, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
160
- return this.aztecNode.getPublicDataWitness(blockHash, leafSlot);
297
+ public getPublicDataWitness(blockHash: BlockHash, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
298
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, () =>
299
+ this.aztecNode.getPublicDataWitness(blockHash, leafSlot),
300
+ );
161
301
  }
162
302
 
163
303
  /**
@@ -165,27 +305,37 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
165
305
  * @param blockNumber - The number of a block of which to get the block header.
166
306
  * @returns Block extracted from a block with block number `blockNumber`.
167
307
  */
168
- public async utilityGetBlockHeader(blockNumber: BlockNumber): Promise<BlockHeader | undefined> {
169
- const anchorBlockNumber = (await this.anchorBlockStore.getBlockHeader()).getBlockNumber();
308
+ public async getBlockHeader(blockNumber: BlockNumber): Promise<BlockHeader | undefined> {
309
+ const anchorBlockNumber = this.anchorBlockHeader.getBlockNumber();
170
310
  if (blockNumber > anchorBlockNumber) {
171
311
  throw new Error(`Block number ${blockNumber} is higher than current block ${anchorBlockNumber}`);
172
312
  }
173
313
 
314
+ // Most contracts query state at the "current" block, which is the anchor. Skip the RPC when we can.
315
+ if (blockNumber === anchorBlockNumber) {
316
+ return this.anchorBlockHeader;
317
+ }
318
+
174
319
  const block = await this.aztecNode.getBlock(blockNumber);
175
320
  return block?.header;
176
321
  }
177
322
 
178
323
  /**
179
- * Retrieve the complete address associated to a given address.
324
+ * Retrieve the public keys and partial address associated to a given address.
180
325
  * @param account - The account address.
181
- * @returns A complete address associated with the input address.
182
- * @throws An error if the account is not registered in the database.
326
+ * @returns The public keys and partial address, or `undefined` if the account is not registered.
183
327
  */
184
- public utilityGetPublicKeysAndPartialAddress(account: AztecAddress): Promise<CompleteAddress> {
185
- return this.getCompleteAddress(account);
328
+ public async getPublicKeysAndPartialAddress(
329
+ account: AztecAddress,
330
+ ): Promise<{ publicKeys: PublicKeys; partialAddress: PartialAddress } | undefined> {
331
+ const completeAddress = await this.addressStore.getCompleteAddress(account);
332
+ if (!completeAddress) {
333
+ return undefined;
334
+ }
335
+ return { publicKeys: completeAddress.publicKeys, partialAddress: completeAddress.partialAddress };
186
336
  }
187
337
 
188
- protected async getCompleteAddress(account: AztecAddress): Promise<CompleteAddress> {
338
+ protected async getCompleteAddressOrFail(account: AztecAddress): Promise<CompleteAddress> {
189
339
  const completeAddress = await this.addressStore.getCompleteAddress(account);
190
340
  if (!completeAddress) {
191
341
  throw new Error(
@@ -201,11 +351,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
201
351
  * @param address - Address.
202
352
  * @returns A contract instance.
203
353
  */
204
- public utilityGetContractInstance(address: AztecAddress): Promise<ContractInstance> {
205
- return this.getContractInstance(address);
206
- }
207
-
208
- protected async getContractInstance(address: AztecAddress): Promise<ContractInstance> {
354
+ public async getContractInstance(address: AztecAddress): Promise<ContractInstance> {
209
355
  const instance = await this.contractStore.getContractInstance(address);
210
356
  if (!instance) {
211
357
  throw new Error(`No contract instance found for address ${address.toString()}`);
@@ -214,12 +360,11 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
214
360
  }
215
361
 
216
362
  /**
217
- * Returns an auth witness for the given message hash. Checks on the list of transient witnesses
218
- * for this transaction first, and falls back to the local database if not found.
363
+ * Returns an auth witness for the given message hash from the list of transient witnesses for this transaction.
219
364
  * @param messageHash - Hash of the message to authenticate.
220
- * @returns Authentication witness for the requested message hash.
365
+ * @returns Authentication witness for the requested message hash, or undefined if not found.
221
366
  */
222
- public utilityGetAuthWitness(messageHash: Fr): Promise<Fr[] | undefined> {
367
+ public getAuthWitness(messageHash: Fr): Promise<Fr[] | undefined> {
223
368
  return Promise.resolve(this.authWitnesses.find(w => w.requestHash.equals(messageHash))?.witness);
224
369
  }
225
370
 
@@ -245,7 +390,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
245
390
  * @param status - The status of notes to fetch.
246
391
  * @returns Array of note data.
247
392
  */
248
- public async utilityGetNotes(
393
+ public async getNotes(
249
394
  owner: AztecAddress | undefined,
250
395
  storageSlot: Fr,
251
396
  numSelects: number,
@@ -262,7 +407,7 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
262
407
  offset: number,
263
408
  status: NoteStatus,
264
409
  ): Promise<NoteData[]> {
265
- const noteService = new NoteService(this.noteStore, this.aztecNode, this.anchorBlockStore, this.jobId);
410
+ const noteService = new NoteService(this.noteStore, this.aztecNode, this.anchorBlockHeader, this.jobId);
266
411
 
267
412
  const dbNotes = await noteService.getNotes(this.contractAddress, owner, storageSlot, status, this.scopes);
268
413
  return pickNotes<NoteData>(dbNotes, {
@@ -285,26 +430,32 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
285
430
  * @param innerNullifier - The inner nullifier.
286
431
  * @returns A boolean indicating whether the nullifier exists in the tree or not.
287
432
  */
288
- public async utilityCheckNullifierExists(innerNullifier: Fr) {
289
- const nullifier = await siloNullifier(this.contractAddress, innerNullifier!);
290
- const [leafIndex] = await this.aztecNode.findLeavesIndexes('latest', MerkleTreeId.NULLIFIER_TREE, [nullifier]);
433
+ public async doesNullifierExist(innerNullifier: Fr) {
434
+ const [nullifier, anchorBlockHash] = await Promise.all([
435
+ siloNullifier(this.contractAddress, innerNullifier!),
436
+ this.anchorBlockHeader.hash(),
437
+ ]);
438
+ const [leafIndex] = await this.aztecNode.findLeavesIndexes(anchorBlockHash, MerkleTreeId.NULLIFIER_TREE, [
439
+ nullifier,
440
+ ]);
291
441
  return leafIndex?.data !== undefined;
292
442
  }
293
443
 
294
444
  /**
295
- * Fetches a message from the executionStore, given its key.
445
+ * Returns the membership witness of an un-nullified L1 to L2 message.
296
446
  * @param contractAddress - Address of a contract by which the message was emitted.
297
447
  * @param messageHash - Hash of the message.
298
448
  * @param secret - Secret used to compute a nullifier.
299
449
  * @dev Contract address and secret are only used to compute the nullifier to get non-nullified messages
300
450
  * @returns The l1 to l2 membership witness (index of message in the tree and sibling path).
301
451
  */
302
- public async utilityGetL1ToL2MembershipWitness(contractAddress: AztecAddress, messageHash: Fr, secret: Fr) {
452
+ public async getL1ToL2MembershipWitness(contractAddress: AztecAddress, messageHash: Fr, secret: Fr) {
303
453
  const [messageIndex, siblingPath] = await getNonNullifiedL1ToL2MessageWitness(
304
454
  this.aztecNode,
305
455
  contractAddress,
306
456
  messageHash,
307
457
  secret,
458
+ await this.anchorBlockHeader.hash(),
308
459
  );
309
460
 
310
461
  return new MessageLoadOracleInputs(messageIndex, siblingPath);
@@ -317,129 +468,210 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
317
468
  * @param startStorageSlot - The starting storage slot.
318
469
  * @param numberOfElements - Number of elements to read from the starting storage slot.
319
470
  */
320
- public async utilityStorageRead(
321
- blockHash: L2BlockHash,
471
+ public getFromPublicStorage(
472
+ blockHash: BlockHash,
322
473
  contractAddress: AztecAddress,
323
474
  startStorageSlot: Fr,
324
475
  numberOfElements: number,
325
476
  ) {
326
- const slots = Array(numberOfElements)
327
- .fill(0)
328
- .map((_, i) => new Fr(startStorageSlot.value + BigInt(i)));
477
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, async () => {
478
+ const slots = Array(numberOfElements)
479
+ .fill(0)
480
+ .map((_, i) => new Fr(startStorageSlot.value + BigInt(i)));
329
481
 
330
- const values = await Promise.all(
331
- slots.map(storageSlot => this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)),
332
- );
482
+ const values = await Promise.all(
483
+ slots.map(storageSlot => this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)),
484
+ );
333
485
 
334
- this.log.debug(
335
- `Oracle storage read: slots=[${slots.map(slot => slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`,
336
- );
486
+ this.logger.debug(
487
+ `Oracle storage read: slots=[${slots.map(slot => slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`,
488
+ );
337
489
 
338
- return values;
490
+ return values;
491
+ });
492
+ }
493
+
494
+ /**
495
+ * Returns a per-contract logger whose output is prefixed with `contract:<name>(<addrAbbrev>)`.
496
+ */
497
+ async #getContractLogger(): Promise<Logger> {
498
+ if (!this.contractLogger) {
499
+ // Purpose of instanceId is to distinguish logs from different instances of the same component. It makes sense
500
+ // to re-use jobId as instanceId here as executions of different PXE jobs are isolated.
501
+ this.contractLogger = await createContractLogger(
502
+ this.contractAddress,
503
+ addr => this.contractStore.getDebugContractName(addr),
504
+ 'user',
505
+ { instanceId: this.jobId },
506
+ );
507
+ }
508
+ return this.contractLogger;
509
+ }
510
+
511
+ /**
512
+ * Returns a per-contract logger whose output is prefixed with `aztecnr:<name>(<addrAbbrev>)`.
513
+ */
514
+ async #getAztecnrLogger(): Promise<Logger> {
515
+ if (!this.aztecnrLogger) {
516
+ // Purpose of instanceId is to distinguish logs from different instances of the same component. It makes sense
517
+ // to re-use jobId as instanceId here as executions of different PXE jobs are isolated.
518
+ this.aztecnrLogger = await createContractLogger(
519
+ this.contractAddress,
520
+ addr => this.contractStore.getDebugContractName(addr),
521
+ 'aztecnr',
522
+ { instanceId: this.jobId },
523
+ );
524
+ }
525
+ return this.aztecnrLogger;
339
526
  }
340
527
 
341
- public utilityDebugLog(level: number, message: string, fields: Fr[]): void {
528
+ public async log(level: number, message: string, fields: Fr[]): Promise<void> {
342
529
  if (!LogLevels[level]) {
343
- throw new Error(`Invalid debug log level: ${level}`);
530
+ throw new Error(`Invalid log level: ${level}`);
344
531
  }
345
- const levelName = LogLevels[level];
346
- this.aztecNrDebugLog[levelName](`${applyStringFormatting(message, fields)}`);
532
+
533
+ const { kind, message: strippedMessage } = stripAztecnrLogPrefix(message);
534
+
535
+ const logger = kind == 'aztecnr' ? await this.#getAztecnrLogger() : await this.#getContractLogger();
536
+ logContractMessage(logger, LogLevels[level], strippedMessage, fields);
537
+ }
538
+
539
+ // Deprecated, only kept for backwards compatibility until Alpha v5 rolls out.
540
+ public async getPendingTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr, scope: AztecAddress) {
541
+ const logService = this.#createLogService();
542
+ const logs = await logService.fetchTaggedLogs(this.contractAddress, scope);
543
+ await this.capsuleService.appendToCapsuleArray(
544
+ this.contractAddress,
545
+ pendingTaggedLogArrayBaseSlot,
546
+ logs.map(log => log.toFields()),
547
+ this.jobId,
548
+ scope,
549
+ );
550
+ }
551
+
552
+ /** Fetches pending tagged logs into a freshly allocated ephemeral array and returns its base slot. */
553
+ public async getPendingTaggedLogsV2(scope: AztecAddress): Promise<Fr> {
554
+ const logService = this.#createLogService();
555
+ const logs = await logService.fetchTaggedLogs(this.contractAddress, scope);
556
+ return this.ephemeralArrayService.newArray(logs.map(log => log.toFields()));
347
557
  }
348
558
 
349
- public async utilityFetchTaggedLogs(pendingTaggedLogArrayBaseSlot: Fr) {
350
- const logService = new LogService(
559
+ #createLogService(): LogService {
560
+ return new LogService(
351
561
  this.aztecNode,
352
- this.anchorBlockStore,
562
+ this.anchorBlockHeader,
563
+ this.l2TipsStore,
353
564
  this.keyStore,
354
- this.capsuleStore,
355
565
  this.recipientTaggingStore,
356
566
  this.senderAddressBookStore,
357
567
  this.addressStore,
358
568
  this.jobId,
569
+ this.logger.getBindings(),
359
570
  );
360
-
361
- const noteService = new NoteService(this.noteStore, this.aztecNode, this.anchorBlockStore, this.jobId);
362
-
363
- // It is acceptable to run the following operations in parallel for several reasons:
364
- // 1. syncTaggedLogs does not write to the note store — it only stores the pending tagged logs in a capsule array,
365
- // which is then processed in Noir after this handler returns.
366
- // 2. Even if syncTaggedLogs did write to the note store, it would not cause inconsistent state.
367
- await Promise.all([
368
- logService.syncTaggedLogs(this.contractAddress, pendingTaggedLogArrayBaseSlot, this.scopes),
369
- noteService.syncNoteNullifiers(this.contractAddress),
370
- ]);
371
571
  }
372
572
 
373
573
  /**
374
- * Validates all note and event validation requests enqueued via `enqueue_note_for_validation` and
375
- * `enqueue_event_for_validation`, inserting them into the note database and event store respectively, making them
376
- * queryable via `get_notes` and `getPrivateEvents`.
574
+ * Legacy: validates note/event requests stored in capsule arrays.
377
575
  *
378
- * This automatically clears both validation request queues, so no further work needs to be done by the caller.
379
- * @param contractAddress - The address of the contract that the logs are tagged for.
380
- * @param noteValidationRequestsArrayBaseSlot - The base slot of capsule array containing note validation requests.
381
- * @param eventValidationRequestsArrayBaseSlot - The base slot of capsule array containing event validation requests.
576
+ * Deprecated, only kept for backwards compatibility until Alpha v5 rolls out.
382
577
  */
383
- public async utilityValidateAndStoreEnqueuedNotesAndEvents(
578
+ public async validateAndStoreEnqueuedNotesAndEvents(
384
579
  contractAddress: AztecAddress,
385
580
  noteValidationRequestsArrayBaseSlot: Fr,
386
581
  eventValidationRequestsArrayBaseSlot: Fr,
582
+ maxNotePackedLen: number,
583
+ maxEventSerializedLen: number,
584
+ scope: AztecAddress,
387
585
  ) {
388
586
  // TODO(#10727): allow other contracts to store notes
389
587
  if (!this.contractAddress.equals(contractAddress)) {
390
588
  throw new Error(`Got a note validation request from ${contractAddress}, expected ${this.contractAddress}`);
391
589
  }
392
590
 
393
- // We read all note and event validation requests and process them all concurrently. This makes the process much
394
- // faster as we don't need to wait for the network round-trip.
395
591
  const noteValidationRequests = (
396
- await this.capsuleStore.readCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, this.jobId)
397
- ).map(NoteValidationRequest.fromFields);
592
+ await this.capsuleService.readCapsuleArray(
593
+ contractAddress,
594
+ noteValidationRequestsArrayBaseSlot,
595
+ this.jobId,
596
+ scope,
597
+ )
598
+ ).map(fields => NoteValidationRequest.fromFields(fields, maxNotePackedLen));
398
599
 
399
600
  const eventValidationRequests = (
400
- await this.capsuleStore.readCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, this.jobId)
401
- ).map(EventValidationRequest.fromFields);
402
-
403
- const noteService = new NoteService(this.noteStore, this.aztecNode, this.anchorBlockStore, this.jobId);
404
- const noteStorePromises = noteValidationRequests.map(request =>
405
- noteService.validateAndStoreNote(
406
- request.contractAddress,
407
- request.owner,
408
- request.storageSlot,
409
- request.randomness,
410
- request.noteNonce,
411
- request.content,
412
- request.noteHash,
413
- request.nullifier,
414
- request.txHash,
415
- request.recipient,
416
- ),
417
- );
601
+ await this.capsuleService.readCapsuleArray(
602
+ contractAddress,
603
+ eventValidationRequestsArrayBaseSlot,
604
+ this.jobId,
605
+ scope,
606
+ )
607
+ ).map(fields => EventValidationRequest.fromFields(fields, maxEventSerializedLen));
608
+
609
+ await this.#processValidationRequests(noteValidationRequests, eventValidationRequests, scope);
418
610
 
419
- const eventService = new EventService(this.anchorBlockStore, this.aztecNode, this.privateEventStore, this.jobId);
420
- const eventStorePromises = eventValidationRequests.map(request =>
421
- eventService.validateAndStoreEvent(
422
- request.contractAddress,
423
- request.eventTypeId,
424
- request.randomness,
425
- request.serializedEvent,
426
- request.eventCommitment,
427
- request.txHash,
428
- request.recipient,
429
- ),
611
+ await this.capsuleService.setCapsuleArray(
612
+ contractAddress,
613
+ noteValidationRequestsArrayBaseSlot,
614
+ [],
615
+ this.jobId,
616
+ scope,
617
+ );
618
+ await this.capsuleService.setCapsuleArray(
619
+ contractAddress,
620
+ eventValidationRequestsArrayBaseSlot,
621
+ [],
622
+ this.jobId,
623
+ scope,
430
624
  );
625
+ }
431
626
 
432
- await Promise.all([...noteStorePromises, ...eventStorePromises]);
627
+ public async validateAndStoreEnqueuedNotesAndEventsV2(
628
+ noteValidationRequestsArrayBaseSlot: Fr,
629
+ eventValidationRequestsArrayBaseSlot: Fr,
630
+ maxNotePackedLen: number,
631
+ maxEventSerializedLen: number,
632
+ scope: AztecAddress,
633
+ ) {
634
+ const noteValidationRequests = this.ephemeralArrayService
635
+ .readArrayAt(noteValidationRequestsArrayBaseSlot)
636
+ .map(fields => NoteValidationRequest.fromFields(fields, maxNotePackedLen));
433
637
 
434
- // Requests are cleared once we're done.
435
- await this.capsuleStore.setCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, [], this.jobId);
436
- await this.capsuleStore.setCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, [], this.jobId);
638
+ const eventValidationRequests = this.ephemeralArrayService
639
+ .readArrayAt(eventValidationRequestsArrayBaseSlot)
640
+ .map(fields => EventValidationRequest.fromFields(fields, maxEventSerializedLen));
641
+
642
+ await this.#processValidationRequests(noteValidationRequests, eventValidationRequests, scope);
437
643
  }
438
644
 
439
- public async utilityBulkRetrieveLogs(
645
+ /**
646
+ * Dispatches note and event validation requests to the service layer.
647
+ *
648
+ * This function is an auxiliary to support legacy (capsule backed) and new (ephemeral array backed) versions of the
649
+ * `validateAndStoreEnqueuedNotesAndEvents` oracle.
650
+ */
651
+ async #processValidationRequests(
652
+ noteValidationRequests: NoteValidationRequest[],
653
+ eventValidationRequests: EventValidationRequest[],
654
+ scope: AztecAddress,
655
+ ) {
656
+ const txEffects = await this.#fetchTxEffects([
657
+ ...noteValidationRequests.map(r => r.txHash),
658
+ ...eventValidationRequests.map(r => r.txHash),
659
+ ]);
660
+
661
+ const noteService = new NoteService(this.noteStore, this.aztecNode, this.anchorBlockHeader, this.jobId);
662
+ const eventService = new EventService(this.anchorBlockHeader, this.aztecNode, this.privateEventStore, this.jobId);
663
+
664
+ await Promise.all([
665
+ noteService.validateAndStoreNotes(noteValidationRequests, scope, txEffects),
666
+ eventService.validateAndStoreEvents(eventValidationRequests, scope, txEffects),
667
+ ]);
668
+ }
669
+
670
+ public async getLogsByTag(
440
671
  contractAddress: AztecAddress,
441
672
  logRetrievalRequestsArrayBaseSlot: Fr,
442
673
  logRetrievalResponsesArrayBaseSlot: Fr,
674
+ scope: AztecAddress,
443
675
  ) {
444
676
  // TODO(#10727): allow other contracts to process partial notes
445
677
  if (!this.contractAddress.equals(contractAddress)) {
@@ -449,100 +681,377 @@ export class UtilityExecutionOracle implements IMiscOracle, IUtilityExecutionOra
449
681
  // We read all log retrieval requests and process them all concurrently. This makes the process much faster as we
450
682
  // don't need to wait for the network round-trip.
451
683
  const logRetrievalRequests = (
452
- await this.capsuleStore.readCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, this.jobId)
684
+ await this.capsuleService.readCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, this.jobId, scope)
453
685
  ).map(LogRetrievalRequest.fromFields);
454
686
 
455
- const logService = new LogService(
456
- this.aztecNode,
457
- this.anchorBlockStore,
458
- this.keyStore,
459
- this.capsuleStore,
460
- this.recipientTaggingStore,
461
- this.senderAddressBookStore,
462
- this.addressStore,
463
- this.jobId,
464
- );
465
-
466
- const maybeLogRetrievalResponses = await logService.bulkRetrieveLogs(logRetrievalRequests);
687
+ const logService = this.#createLogService();
688
+ const maybeLogRetrievalResponses = await logService.fetchLogsByTag(contractAddress, logRetrievalRequests);
467
689
 
468
690
  // Requests are cleared once we're done.
469
- await this.capsuleStore.setCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, [], this.jobId);
691
+ await this.capsuleService.setCapsuleArray(
692
+ contractAddress,
693
+ logRetrievalRequestsArrayBaseSlot,
694
+ [],
695
+ this.jobId,
696
+ scope,
697
+ );
470
698
 
471
699
  // The responses are stored as Option<LogRetrievalResponse> in a second CapsuleArray.
472
- await this.capsuleStore.setCapsuleArray(
700
+ await this.capsuleService.setCapsuleArray(
473
701
  contractAddress,
474
702
  logRetrievalResponsesArrayBaseSlot,
475
703
  maybeLogRetrievalResponses.map(LogRetrievalResponse.toSerializedOption),
476
704
  this.jobId,
705
+ scope,
477
706
  );
478
707
  }
479
708
 
480
- public utilityStoreCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[]): Promise<void> {
709
+ public async getLogsByTagV2(requestArrayBaseSlot: Fr): Promise<Fr> {
710
+ const logRetrievalRequests = this.ephemeralArrayService
711
+ .readArrayAt(requestArrayBaseSlot)
712
+ .map(LogRetrievalRequest.fromFields);
713
+ const logService = this.#createLogService();
714
+
715
+ const maybeLogRetrievalResponses = await logService.fetchLogsByTag(this.contractAddress, logRetrievalRequests);
716
+
717
+ return this.ephemeralArrayService.newArray(maybeLogRetrievalResponses.map(LogRetrievalResponse.toSerializedOption));
718
+ }
719
+
720
+ // Deprecated, only kept for backwards compatibility until Alpha v5 rolls out.
721
+ public async getMessageContextsByTxHash(
722
+ contractAddress: AztecAddress,
723
+ messageContextRequestsArrayBaseSlot: Fr,
724
+ messageContextResponsesArrayBaseSlot: Fr,
725
+ scope: AztecAddress,
726
+ ) {
727
+ try {
728
+ if (!this.contractAddress.equals(contractAddress)) {
729
+ throw new Error(`Got a message context request from ${contractAddress}, expected ${this.contractAddress}`);
730
+ }
731
+
732
+ // TODO(@mverzilli): this is a prime example of where using an ephemeral array would make much more sense, we don't
733
+ // need scopes here, we just need a bit of shared memory to cross boundaries between Noir and TS.
734
+ // At the same time, we don't want to allow any global scope access other than where backwards compatibility
735
+ // forces us to. Hence we need the scope here to be artificial.
736
+ const requestCapsules = await this.capsuleService.readCapsuleArray(
737
+ contractAddress,
738
+ messageContextRequestsArrayBaseSlot,
739
+ this.jobId,
740
+ scope,
741
+ );
742
+
743
+ const txHashes = requestCapsules.map((fields, i) => {
744
+ if (fields.length !== 1) {
745
+ throw new Error(
746
+ `Malformed message context request at index ${i}: expected 1 field (tx hash), got ${fields.length}`,
747
+ );
748
+ }
749
+ return fields[0];
750
+ });
751
+
752
+ const maybeMessageContexts = await this.messageContextService.getMessageContextsByTxHash(
753
+ txHashes,
754
+ this.anchorBlockHeader.getBlockNumber(),
755
+ );
756
+
757
+ // Leave response in response capsule array.
758
+ await this.capsuleService.setCapsuleArray(
759
+ contractAddress,
760
+ messageContextResponsesArrayBaseSlot,
761
+ maybeMessageContexts.map(MessageContext.toSerializedOption),
762
+ this.jobId,
763
+ scope,
764
+ );
765
+ } finally {
766
+ await this.capsuleService.setCapsuleArray(
767
+ contractAddress,
768
+ messageContextRequestsArrayBaseSlot,
769
+ [],
770
+ this.jobId,
771
+ scope,
772
+ );
773
+ }
774
+ }
775
+
776
+ /** Reads tx hash requests from an ephemeral array, resolves their contexts, and returns the response slot. */
777
+ public async getMessageContextsByTxHashV2(requestArrayBaseSlot: Fr): Promise<Fr> {
778
+ const requestFields = this.ephemeralArrayService.readArrayAt(requestArrayBaseSlot);
779
+
780
+ const txHashes = requestFields.map((fields, i) => {
781
+ if (fields.length !== 1) {
782
+ throw new Error(
783
+ `Malformed message context request at index ${i}: expected 1 field (tx hash), got ${fields.length}`,
784
+ );
785
+ }
786
+ return fields[0];
787
+ });
788
+
789
+ const maybeMessageContexts = await this.messageContextService.getMessageContextsByTxHash(
790
+ txHashes,
791
+ this.anchorBlockHeader.getBlockNumber(),
792
+ );
793
+
794
+ return this.ephemeralArrayService.newArray(maybeMessageContexts.map(MessageContext.toSerializedOption));
795
+ }
796
+
797
+ /**
798
+ * Fetches the effects of a transaction by its hash. Returns null if the tx is not found or is beyond the anchor
799
+ * block.
800
+ */
801
+ public async getTxEffect(txHash: TxHash): Promise<TxEffect | null> {
802
+ if (txHash.hash.isZero()) {
803
+ throw new Error('Invalid tx hash passed into aztec_utl_getTxEffect oracle handler');
804
+ }
805
+
806
+ const txEffect = await this.aztecNode.getTxEffect(txHash);
807
+ if (!txEffect || txEffect.l2BlockNumber > this.anchorBlockHeader.getBlockNumber()) {
808
+ return null;
809
+ }
810
+
811
+ return txEffect.data;
812
+ }
813
+
814
+ public setCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[], scope: AztecAddress): void {
481
815
  if (!contractAddress.equals(this.contractAddress)) {
482
816
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
483
817
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
484
818
  }
485
- this.capsuleStore.storeCapsule(this.contractAddress, slot, capsule, this.jobId);
486
- return Promise.resolve();
819
+ this.capsuleService.setCapsule(contractAddress, slot, capsule, this.jobId, scope);
487
820
  }
488
821
 
489
- public async utilityLoadCapsule(contractAddress: AztecAddress, slot: Fr): Promise<Fr[] | null> {
822
+ public getCapsule(contractAddress: AztecAddress, slot: Fr, scope: AztecAddress): Promise<Fr[] | null> {
490
823
  if (!contractAddress.equals(this.contractAddress)) {
491
824
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
492
825
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
493
826
  }
494
- return (
495
- // TODO(#12425): On the following line, the pertinent capsule gets overshadowed by the transient one. Tackle this.
496
- this.capsules.find(c => c.contractAddress.equals(contractAddress) && c.storageSlot.equals(slot))?.data ??
497
- (await this.capsuleStore.loadCapsule(this.contractAddress, slot, this.jobId))
498
- );
827
+ return this.capsuleService.getCapsule(contractAddress, slot, this.jobId, scope, this.capsules);
499
828
  }
500
829
 
501
- public utilityDeleteCapsule(contractAddress: AztecAddress, slot: Fr): Promise<void> {
830
+ public deleteCapsule(contractAddress: AztecAddress, slot: Fr, scope: AztecAddress): void {
502
831
  if (!contractAddress.equals(this.contractAddress)) {
503
832
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
504
833
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
505
834
  }
506
- this.capsuleStore.deleteCapsule(this.contractAddress, slot, this.jobId);
507
- return Promise.resolve();
835
+ this.capsuleService.deleteCapsule(contractAddress, slot, this.jobId, scope);
508
836
  }
509
837
 
510
- public utilityCopyCapsule(
838
+ public copyCapsule(
511
839
  contractAddress: AztecAddress,
512
840
  srcSlot: Fr,
513
841
  dstSlot: Fr,
514
842
  numEntries: number,
843
+ scope: AztecAddress,
515
844
  ): Promise<void> {
516
845
  if (!contractAddress.equals(this.contractAddress)) {
517
846
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
518
847
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
519
848
  }
520
- return this.capsuleStore.copyCapsule(this.contractAddress, srcSlot, dstSlot, numEntries, this.jobId);
849
+ return this.capsuleService.copyCapsule(contractAddress, srcSlot, dstSlot, numEntries, this.jobId, scope);
850
+ }
851
+
852
+ /**
853
+ * Clears cached sync state for a contract for a set of scopes, forcing re-sync on the next query so that newly
854
+ * stored notes or events are discovered.
855
+ */
856
+ public setContractSyncCacheInvalid(contractAddress: AztecAddress, scopes: AztecAddress[]): void {
857
+ if (!contractAddress.equals(this.contractAddress)) {
858
+ throw new Error(`Contract ${this.contractAddress} cannot invalidate sync cache of ${contractAddress}`);
859
+ }
860
+ this.contractSyncService.invalidateContractForScopes(contractAddress, scopes);
521
861
  }
522
862
 
523
863
  // TODO(#11849): consider replacing this oracle with a pure Noir implementation of aes decryption.
524
- public utilityAes128Decrypt(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise<Buffer> {
864
+ public decryptAes128(ciphertext: Buffer, iv: Buffer, symKey: Buffer): Promise<Buffer> {
525
865
  const aes128 = new Aes128();
526
866
  return aes128.decryptBufferCBC(ciphertext, iv, symKey);
527
867
  }
528
868
 
529
869
  /**
530
- * Retrieves the shared secret for a given address and ephemeral public key.
870
+ * Retrieves the app-siloed shared secret for a given address and ephemeral public key.
531
871
  * @param address - The address to get the secret for.
532
872
  * @param ephPk - The ephemeral public key to get the secret for.
533
- * @returns The secret for the given address.
873
+ * @param contractAddress - The contract address for app-siloing (validated against execution context).
874
+ * @returns The app-siloed shared secret as a Field.
534
875
  */
535
- public utilityGetSharedSecret(address: AztecAddress, ephPk: Point): Promise<Point> {
536
- return this.getSharedSecret(address, ephPk);
537
- }
538
-
539
- protected async getSharedSecret(address: AztecAddress, ephPk: Point): Promise<Point> {
540
- // TODO(#12656): return an app-siloed secret
541
- const recipientCompleteAddress = await this.getCompleteAddress(address);
876
+ public async getSharedSecret(address: AztecAddress, ephPk: Point, contractAddress: AztecAddress): Promise<Fr> {
877
+ if (!contractAddress.equals(this.contractAddress)) {
878
+ throw new Error(
879
+ `getSharedSecret called with contract address ${contractAddress}, expected ${this.contractAddress}`,
880
+ );
881
+ }
882
+ const recipientCompleteAddress = await this.getCompleteAddressOrFail(address);
542
883
  const ivskM = await this.keyStore.getMasterSecretKey(
543
884
  recipientCompleteAddress.publicKeys.masterIncomingViewingPublicKey,
544
885
  );
545
886
  const addressSecret = await computeAddressSecret(await recipientCompleteAddress.getPreaddress(), ivskM);
546
- return deriveEcdhSharedSecret(addressSecret, ephPk);
887
+ return deriveAppSiloedSharedSecret(addressSecret, ephPk, this.contractAddress);
888
+ }
889
+
890
+ public pushEphemeral(slot: Fr, elements: Fr[]): number {
891
+ return this.ephemeralArrayService.push(slot, elements);
892
+ }
893
+
894
+ public popEphemeral(slot: Fr): Fr[] {
895
+ return this.ephemeralArrayService.pop(slot);
896
+ }
897
+
898
+ public getEphemeral(slot: Fr, index: number): Fr[] {
899
+ return this.ephemeralArrayService.get(slot, index);
900
+ }
901
+
902
+ public setEphemeral(slot: Fr, index: number, elements: Fr[]): void {
903
+ this.ephemeralArrayService.set(slot, index, elements);
904
+ }
905
+
906
+ public getEphemeralLen(slot: Fr): number {
907
+ return this.ephemeralArrayService.len(slot);
908
+ }
909
+
910
+ public removeEphemeral(slot: Fr, index: number): void {
911
+ this.ephemeralArrayService.remove(slot, index);
912
+ }
913
+
914
+ public clearEphemeral(slot: Fr): void {
915
+ this.ephemeralArrayService.clear(slot);
916
+ }
917
+
918
+ public emitOffchainEffect(data: Fr[]): Promise<void> {
919
+ this.offchainEffects.push({ data, contractAddress: this.contractAddress });
920
+ return Promise.resolve();
921
+ }
922
+
923
+ /** Executes another utility function from within this one and returns its serialized return values. */
924
+ public async callUtilityFunction(
925
+ targetContractAddress: AztecAddress,
926
+ functionSelector: FunctionSelector,
927
+ args: Fr[],
928
+ ): Promise<Fr[]> {
929
+ const targetArtifact = await this.contractStore.getFunctionArtifactWithDebugMetadata(
930
+ targetContractAddress,
931
+ functionSelector,
932
+ );
933
+
934
+ if (!targetContractAddress.equals(this.contractAddress)) {
935
+ const request = {
936
+ caller: this.contractAddress,
937
+ target: targetContractAddress,
938
+ functionSelector,
939
+ functionName: targetArtifact.name,
940
+ args,
941
+ callerContext: ('isPrivate' in this ? 'private' : 'utility') as 'private' | 'utility',
942
+ };
943
+
944
+ const response = this.hooks
945
+ ? await this.hooks.authorizeUtilityCall(request)
946
+ : { authorized: false, reason: 'No execution hooks configured' };
947
+
948
+ if (!response.authorized) {
949
+ const reason = response.reason ? `: ${response.reason}` : '';
950
+ throw new Error(
951
+ `Cross-contract utility call denied${reason}. ${this.contractAddress} attempted to call ` +
952
+ `${targetContractAddress}:${functionSelector} (${targetArtifact.name}). ` +
953
+ `See https://docs.aztec.network/errors/11`,
954
+ );
955
+ }
956
+
957
+ await this.contractSyncService.ensureContractSynced(
958
+ targetContractAddress,
959
+ functionSelector,
960
+ this.utilityExecutor,
961
+ this.anchorBlockHeader,
962
+ this.jobId,
963
+ this.scopes,
964
+ );
965
+ }
966
+
967
+ this.logger.debug(
968
+ `Calling nested utility function ${targetContractAddress}:${functionSelector} from ${this.contractAddress}`,
969
+ );
970
+
971
+ const nestedOracle = new UtilityExecutionOracle({
972
+ contractAddress: targetContractAddress,
973
+ authWitnesses: this.authWitnesses,
974
+ capsules: this.capsules,
975
+ anchorBlockHeader: this.anchorBlockHeader,
976
+ contractStore: this.contractStore,
977
+ noteStore: this.noteStore,
978
+ keyStore: this.keyStore,
979
+ addressStore: this.addressStore,
980
+ aztecNode: this.aztecNode,
981
+ recipientTaggingStore: this.recipientTaggingStore,
982
+ senderAddressBookStore: this.senderAddressBookStore,
983
+ capsuleService: this.capsuleService,
984
+ privateEventStore: this.privateEventStore,
985
+ messageContextService: this.messageContextService,
986
+ contractSyncService: this.contractSyncService,
987
+ l2TipsStore: this.l2TipsStore,
988
+ jobId: this.jobId,
989
+ scopes: this.scopes,
990
+ simulator: this.simulator,
991
+ hooks: this.hooks,
992
+ utilityExecutor: this.utilityExecutor,
993
+ log: this.logger,
994
+ });
995
+
996
+ const initialWitness = toACVMWitness(0, args);
997
+ const acvmCallback = new Oracle(nestedOracle);
998
+ const acirExecutionResult = await this.simulator
999
+ .executeUserCircuit(initialWitness, targetArtifact, acvmCallback.toACIRCallback())
1000
+ .catch((err: Error) => {
1001
+ err.message = resolveAssertionMessageFromError(err, targetArtifact);
1002
+ throw new ExecutionError(
1003
+ err.message,
1004
+ { contractAddress: targetContractAddress, functionSelector },
1005
+ extractCallStack(err, targetArtifact.debug),
1006
+ { cause: err },
1007
+ );
1008
+ });
1009
+
1010
+ return witnessMapToFields(acirExecutionResult.returnWitness);
1011
+ }
1012
+
1013
+ /** Returns offchain effects collected during execution. */
1014
+ public getOffchainEffects(): OffchainEffect[] {
1015
+ return this.offchainEffects;
1016
+ }
1017
+
1018
+ /**
1019
+ * Fetches tx effects for the given hashes in parallel, deduplicating repeated hashes so each tx is only requested
1020
+ * once. Returns a map keyed by `TxHash.toString()`; hashes for which the node has no tx effect are omitted.
1021
+ */
1022
+ async #fetchTxEffects(txHashes: TxHash[]): Promise<Map<string, IndexedTxEffect>> {
1023
+ const uniqueTxHashes = uniqueBy(txHashes, h => h.toString());
1024
+ const fetched = await Promise.all(uniqueTxHashes.map(h => this.aztecNode.getTxEffect(h)));
1025
+ return new Map(
1026
+ uniqueTxHashes
1027
+ .map((h, i): [string, IndexedTxEffect | undefined] => [h.toString(), fetched[i]])
1028
+ .filter((entry): entry is [string, IndexedTxEffect] => entry[1] !== undefined),
1029
+ );
1030
+ }
1031
+
1032
+ /** Runs a query concurrently with a validation that the block hash is not ahead of the anchor block. */
1033
+ async #queryWithBlockHashNotAfterAnchor<T>(blockHash: BlockHash, query: () => Promise<T>): Promise<T> {
1034
+ // Most contracts query state at the "current" block, which is the anchor. Skip the validation when we can.
1035
+ const anchorHash = await this.anchorBlockHeader.hash();
1036
+ if (blockHash.equals(anchorHash)) {
1037
+ return query();
1038
+ }
1039
+
1040
+ const [response] = await Promise.all([
1041
+ query(),
1042
+ (async () => {
1043
+ const header = await this.aztecNode.getBlockHeader(blockHash);
1044
+ if (!header) {
1045
+ throw new Error(`Could not find block header for block hash ${blockHash}`);
1046
+ }
1047
+
1048
+ if (header.getBlockNumber() > this.anchorBlockHeader.getBlockNumber()) {
1049
+ throw new Error(
1050
+ `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 ${anchorHash}).`,
1051
+ );
1052
+ }
1053
+ })(),
1054
+ ]);
1055
+ return response;
547
1056
  }
548
1057
  }