@aztec-labs/standard-contracts 6.0.0-nightly.20260829

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 (87) hide show
  1. package/artifacts/AuthRegistry.d.json.ts +5 -0
  2. package/artifacts/AuthRegistry.json +6588 -0
  3. package/artifacts/HandshakeRegistry.d.json.ts +5 -0
  4. package/artifacts/HandshakeRegistry.json +13319 -0
  5. package/artifacts/MultiCallEntrypoint.d.json.ts +5 -0
  6. package/artifacts/MultiCallEntrypoint.json +4383 -0
  7. package/artifacts/PublicChecks.d.json.ts +5 -0
  8. package/artifacts/PublicChecks.json +3067 -0
  9. package/dest/auth-registry/constants.d.ts +5 -0
  10. package/dest/auth-registry/constants.d.ts.map +1 -0
  11. package/dest/auth-registry/constants.js +7 -0
  12. package/dest/auth-registry/index.d.ts +6 -0
  13. package/dest/auth-registry/index.d.ts.map +1 -0
  14. package/dest/auth-registry/index.js +14 -0
  15. package/dest/auth-registry/lazy.d.ts +7 -0
  16. package/dest/auth-registry/lazy.d.ts.map +1 -0
  17. package/dest/auth-registry/lazy.js +24 -0
  18. package/dest/contract_data.d.ts +63 -0
  19. package/dest/contract_data.d.ts.map +1 -0
  20. package/dest/contract_data.js +105 -0
  21. package/dest/drift.d.ts +54 -0
  22. package/dest/drift.d.ts.map +1 -0
  23. package/dest/drift.js +167 -0
  24. package/dest/handshake-registry/constants.d.ts +11 -0
  25. package/dest/handshake-registry/constants.d.ts.map +1 -0
  26. package/dest/handshake-registry/constants.js +17 -0
  27. package/dest/handshake-registry/index.d.ts +6 -0
  28. package/dest/handshake-registry/index.d.ts.map +1 -0
  29. package/dest/handshake-registry/index.js +14 -0
  30. package/dest/handshake-registry/lazy.d.ts +7 -0
  31. package/dest/handshake-registry/lazy.d.ts.map +1 -0
  32. package/dest/handshake-registry/lazy.js +24 -0
  33. package/dest/index.d.ts +6 -0
  34. package/dest/index.d.ts.map +1 -0
  35. package/dest/index.js +5 -0
  36. package/dest/make_standard_contract.d.ts +9 -0
  37. package/dest/make_standard_contract.d.ts.map +1 -0
  38. package/dest/make_standard_contract.js +40 -0
  39. package/dest/multi-call-entrypoint/constants.d.ts +5 -0
  40. package/dest/multi-call-entrypoint/constants.d.ts.map +1 -0
  41. package/dest/multi-call-entrypoint/constants.js +7 -0
  42. package/dest/multi-call-entrypoint/index.d.ts +6 -0
  43. package/dest/multi-call-entrypoint/index.d.ts.map +1 -0
  44. package/dest/multi-call-entrypoint/index.js +14 -0
  45. package/dest/multi-call-entrypoint/lazy.d.ts +7 -0
  46. package/dest/multi-call-entrypoint/lazy.d.ts.map +1 -0
  47. package/dest/multi-call-entrypoint/lazy.js +24 -0
  48. package/dest/public-checks/constants.d.ts +5 -0
  49. package/dest/public-checks/constants.d.ts.map +1 -0
  50. package/dest/public-checks/constants.js +7 -0
  51. package/dest/public-checks/index.d.ts +6 -0
  52. package/dest/public-checks/index.d.ts.map +1 -0
  53. package/dest/public-checks/index.js +14 -0
  54. package/dest/public-checks/lazy.d.ts +7 -0
  55. package/dest/public-checks/lazy.d.ts.map +1 -0
  56. package/dest/public-checks/lazy.js +24 -0
  57. package/dest/publishable_standard_contracts.d.ts +17 -0
  58. package/dest/publishable_standard_contracts.d.ts.map +1 -0
  59. package/dest/publishable_standard_contracts.js +23 -0
  60. package/dest/scripts/cleanup_artifacts.js +16 -0
  61. package/dest/scripts/generate_data.js +136 -0
  62. package/dest/standard_contract.d.ts +15 -0
  63. package/dest/standard_contract.d.ts.map +1 -0
  64. package/dest/standard_contract.js +1 -0
  65. package/dest/standard_contract_data.d.ts +19 -0
  66. package/dest/standard_contract_data.d.ts.map +1 -0
  67. package/dest/standard_contract_data.js +85 -0
  68. package/package.json +104 -0
  69. package/src/auth-registry/constants.ts +10 -0
  70. package/src/auth-registry/index.ts +24 -0
  71. package/src/auth-registry/lazy.ts +35 -0
  72. package/src/contract_data.ts +125 -0
  73. package/src/drift.ts +200 -0
  74. package/src/handshake-registry/constants.ts +23 -0
  75. package/src/handshake-registry/index.ts +25 -0
  76. package/src/handshake-registry/lazy.ts +35 -0
  77. package/src/index.ts +5 -0
  78. package/src/make_standard_contract.ts +51 -0
  79. package/src/multi-call-entrypoint/constants.ts +10 -0
  80. package/src/multi-call-entrypoint/index.ts +24 -0
  81. package/src/multi-call-entrypoint/lazy.ts +35 -0
  82. package/src/public-checks/constants.ts +10 -0
  83. package/src/public-checks/index.ts +24 -0
  84. package/src/public-checks/lazy.ts +35 -0
  85. package/src/publishable_standard_contracts.ts +22 -0
  86. package/src/standard_contract.ts +19 -0
  87. package/src/standard_contract_data.ts +114 -0
@@ -0,0 +1,3067 @@
1
+ {
2
+ "file_map": {
3
+ "105": {
4
+ "function_locations": [
5
+ {
6
+ "name": "AztecConfig::new",
7
+ "start": 1918
8
+ },
9
+ {
10
+ "name": "AztecConfig::custom_message_handler",
11
+ "start": 2455
12
+ },
13
+ {
14
+ "name": "AztecConfig::custom_sync_state",
15
+ "start": 3150
16
+ },
17
+ {
18
+ "name": "aztec",
19
+ "start": 4051
20
+ },
21
+ {
22
+ "name": "generate_contract_interface",
23
+ "start": 7875
24
+ },
25
+ {
26
+ "name": "generate_sync_state",
27
+ "start": 9789
28
+ },
29
+ {
30
+ "name": "generate_offchain_receive",
31
+ "start": 11291
32
+ },
33
+ {
34
+ "name": "check_each_fn_macroified",
35
+ "start": 12880
36
+ }
37
+ ],
38
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/macros/aztec.nr",
39
+ "source": "mod compute_note_hash_and_nullifier;\n\nuse crate::{\n macros::{\n calls_generation::{\n external_functions::{generate_external_function_calls, generate_external_function_self_calls_structs},\n internal_functions::generate_call_internal_struct,\n },\n dispatch::generate_public_dispatch,\n emit_public_init_nullifier::generate_emit_public_init_nullifier,\n internals_functions_generation::{create_fn_abi_exports, process_functions},\n offchain_receive::{\n OFFCHAIN_RECEIVE_FN_NAME, OFFCHAIN_RECEIVE_PARAM_NAME, offchain_receive_param_type,\n OFFCHAIN_RECEIVE_RETURN_TYPE,\n },\n storage::STORAGE_LAYOUT_NAME,\n utils::{is_fn_contract_library_method, is_fn_external, is_fn_internal, is_fn_test, module_has_storage},\n },\n messages::discovery::{CustomMessageHandler, CustomSyncHandler},\n};\n\nuse compute_note_hash_and_nullifier::generate_contract_library_methods_compute_note_hash_and_nullifier;\n\n/// Configuration for the [`aztec`] macro.\n///\n/// This type lets users override different parts of the default aztec-nr contract behavior, such\n/// as message handling and state synchronization. These are advanced features that require careful\n/// understanding of the behavior of these systems.\n///\n/// ## Examples\n///\n/// ```noir\n/// #[aztec(aztec::macros::AztecConfig::new().custom_message_handler(my_handler))]\n/// contract MyContract { ... }\n/// ```\npub struct AztecConfig {\n custom_message_handler: Option<CustomMessageHandler>,\n custom_sync_state: Option<CustomSyncHandler>,\n}\n\nimpl AztecConfig {\n /// Creates a new `AztecConfig` with default values.\n ///\n /// Calling `new` is equivalent to invoking the [`aztec`] macro with no parameters. The different methods\n /// (e.g. [`AztecConfig::custom_message_handler`]) can then be used to change the default behavior.\n pub comptime fn new() -> Self {\n Self { custom_message_handler: Option::none(), custom_sync_state: Option::none() }\n }\n\n /// Sets a handler for custom messages.\n ///\n /// This enables contracts to process non-standard messages (i.e. any with a message type that is not in\n /// [`crate::messages::msg_type`]).\n ///\n /// `handler` must be a function that conforms to the\n /// [`crate::messages::discovery::CustomMessageHandler`] type signature.\n pub comptime fn custom_message_handler(&mut self, handler: CustomMessageHandler) -> Self {\n self.custom_message_handler = Option::some(handler);\n *self\n }\n\n /// Overrides the default state synchronization logic.\n ///\n /// The generated `sync_state` function will call `handler` instead of\n /// [`crate::messages::discovery::do_sync_state`]. The handler receives all of the same parameters, so it can\n /// run custom logic (e.g. fetching and decrypting custom logs) before, after, or instead of calling\n /// `do_sync_state`.\n ///\n /// `handler` must be a function that conforms to the\n /// [`crate::messages::discovery::CustomSyncHandler`] type signature.\n pub comptime fn custom_sync_state(&mut self, handler: CustomSyncHandler) -> Self {\n self.custom_sync_state = Option::some(handler);\n *self\n }\n}\n\n/// Enables aztec-nr features on a `contract`.\n///\n/// All aztec-nr contracts should have this macro invoked on them, as it is the one that processes all contract\n/// functions, notes, storage, generates interfaces for external calls, and creates the message processing\n/// boilerplate.\n///\n/// ## Examples\n///\n/// Most contracts can simply invoke the macro with no parameters, resulting in default aztec-nr behavior:\n/// ```noir\n/// #[aztec]\n/// contract MyContract { ... }\n/// ```\n///\n/// Advanced contracts can use [`AztecConfig`] to customize parts of its behavior, such as message\n/// processing.\n/// ```noir\n/// #[aztec(aztec::macros::AztecConfig::new().custom_message_handler(my_handler))]\n/// contract MyAdvancedContract { ... }\n/// ```\n#[varargs]\npub comptime fn aztec(m: Module, args: [AztecConfig]) -> Quoted {\n let num_args = args.len();\n let config = if num_args == 0 {\n AztecConfig::new()\n } else if num_args == 1 {\n args[0]\n } else {\n panic(f\"#[aztec] expects 0 or 1 arguments, got {num_args}\")\n };\n\n // Functions that don't have #[external(...)], #[contract_library_method], or #[test] are not allowed in contracts.\n check_each_fn_macroified(m);\n\n // We generate new functions prefixed with `__aztec_nr_internals__` and we replace the original functions' bodies\n // with `static_assert(false, ...)` to prevent them from being called directly from within the contract.\n let functions = process_functions(m);\n\n // We generate structs and their implementations necessary for convenient functions calls.\n let interface = generate_contract_interface(m);\n let self_call_structs = generate_external_function_self_calls_structs(m);\n let call_internal_struct = generate_call_internal_struct(m);\n\n // We generate ABI exports for all the external functions in the contract.\n let fn_abi_exports = create_fn_abi_exports(m);\n\n // We generate `_compute_note_hash`, `_compute_note_nullifier` (and the deprecated\n // `_compute_note_hash_and_nullifier` wrapper) only if they are not already implemented.\n // If they are implemented we just insert empty quotes.\n let contract_library_method_compute_note_hash_and_nullifier = if !m.functions().any(|f| {\n // Note that we don't test for `_compute_note_hash` or `_compute_note_nullifier` in order to make this simpler\n // - users must either implement all three or none.\n // Down the line we'll remove this check and use `AztecConfig`.\n f.name() == quote { _compute_note_hash_and_nullifier }\n }) {\n generate_contract_library_methods_compute_note_hash_and_nullifier()\n } else {\n quote {}\n };\n let process_custom_message_option = if config.custom_message_handler.is_some() {\n let handler = config.custom_message_handler.unwrap();\n quote { Option::some($handler) }\n } else {\n quote { Option::<aztec::messages::discovery::CustomMessageHandler>::none() }\n };\n\n let offchain_inbox_sync_option = quote {\n Option::some(aztec::messages::processing::offchain::sync_inbox)\n };\n\n if m.functions().any(|f| f.name() == quote { sync_state }) {\n panic(\n \"User-defined 'sync_state' is not allowed. Use AztecConfig::custom_sync_state() to customize sync behavior.\",\n );\n }\n\n let custom_sync_handler = if config.custom_sync_state.is_some() {\n let handler = config.custom_sync_state.unwrap();\n Option::some(quote { $handler })\n } else {\n Option::none()\n };\n\n let sync_state_fn_and_abi_export = generate_sync_state(\n process_custom_message_option,\n offchain_inbox_sync_option,\n custom_sync_handler,\n );\n\n if m.functions().any(|f| f.name() == quote { offchain_receive }) {\n panic(\n \"User-defined 'offchain_receive' is not allowed. The function is auto-injected by the #[aztec] macro. See https://docs.aztec.network/errors/7\",\n );\n }\n let offchain_receive_fn_and_abi_export = generate_offchain_receive();\n\n let (has_public_init_nullifier_fn, emit_public_init_nullifier_fn_body) = generate_emit_public_init_nullifier(m);\n let public_dispatch = generate_public_dispatch(m, has_public_init_nullifier_fn);\n\n quote {\n $interface\n $self_call_structs\n $call_internal_struct\n $functions\n $fn_abi_exports\n $contract_library_method_compute_note_hash_and_nullifier\n $public_dispatch\n $sync_state_fn_and_abi_export\n $emit_public_init_nullifier_fn_body\n $offchain_receive_fn_and_abi_export\n }\n}\n\ncomptime fn generate_contract_interface(m: Module) -> Quoted {\n let calls = generate_external_function_calls(m);\n\n let module_name = m.name();\n\n let has_storage_layout = module_has_storage(m) & STORAGE_LAYOUT_NAME.get(m).is_some();\n let storage_layout_getter = if has_storage_layout {\n let storage_layout_name = STORAGE_LAYOUT_NAME.get(m).unwrap();\n quote {\n pub fn storage_layout() -> StorageLayoutFields {\n $storage_layout_name.fields\n }\n }\n } else {\n quote {}\n };\n\n let library_storage_layout_getter = if has_storage_layout {\n quote {\n #[contract_library_method]\n $storage_layout_getter\n }\n } else {\n quote {}\n };\n\n quote {\n pub struct $module_name {\n pub target_contract: aztec::protocol::address::AztecAddress\n }\n\n impl $module_name {\n $calls\n\n pub fn at(\n addr: aztec::protocol::address::AztecAddress\n ) -> Self {\n Self { target_contract: addr }\n }\n\n pub fn interface() -> Self {\n Self { target_contract: aztec::protocol::address::AztecAddress::zero() }\n }\n\n $storage_layout_getter\n }\n\n #[contract_library_method]\n pub fn at(\n addr: aztec::protocol::address::AztecAddress\n ) -> $module_name {\n $module_name { target_contract: addr }\n }\n\n #[contract_library_method]\n pub fn interface() -> $module_name {\n $module_name { target_contract: aztec::protocol::address::AztecAddress::zero() }\n }\n\n $library_storage_layout_getter\n\n }\n}\n\n/// Generates the `sync_state` utility function that performs message discovery.\ncomptime fn generate_sync_state(\n process_custom_message_option: Quoted,\n offchain_inbox_sync_option: Quoted,\n custom_sync_handler: Option<Quoted>,\n) -> Quoted {\n let body = if custom_sync_handler.is_some() {\n let handler = custom_sync_handler.unwrap();\n quote {\n $handler(\n address,\n _compute_note_hash,\n _compute_note_nullifier,\n $process_custom_message_option,\n $offchain_inbox_sync_option,\n scope,\n );\n }\n } else {\n quote {\n aztec::messages::discovery::do_sync_state(\n address,\n _compute_note_hash,\n _compute_note_nullifier,\n $process_custom_message_option,\n $offchain_inbox_sync_option,\n scope,\n );\n }\n };\n\n quote {\n pub struct sync_state_parameters {\n pub scope: aztec::protocol::address::AztecAddress,\n }\n\n #[abi(functions)]\n pub struct sync_state_abi {\n parameters: sync_state_parameters,\n }\n\n #[aztec::macros::internals_functions_generation::abi_attributes::abi_utility]\n unconstrained fn sync_state(scope: aztec::protocol::address::AztecAddress) {\n let address = aztec::context::UtilityContext::new().this_address();\n $body\n }\n }\n}\n\n/// Generates an `offchain_receive` utility function that lets callers add messages to the offchain message inbox.\n///\n/// For more details, see `aztec::messages::processing::offchain::receive`.\ncomptime fn generate_offchain_receive() -> Quoted {\n let param_type = offchain_receive_param_type(quote { aztec });\n let parameters_struct_name = f\"{OFFCHAIN_RECEIVE_FN_NAME}_parameters\".quoted_contents();\n let abi_struct_name = f\"{OFFCHAIN_RECEIVE_FN_NAME}_abi\".quoted_contents();\n\n quote {\n pub struct $parameters_struct_name {\n pub $OFFCHAIN_RECEIVE_PARAM_NAME: $param_type,\n }\n\n #[abi(functions)]\n pub struct $abi_struct_name {\n parameters: $parameters_struct_name,\n }\n\n /// Receives offchain messages into this contract's offchain inbox for subsequent processing.\n ///\n /// Each message is routed to the inbox scoped to its `recipient` field.\n ///\n /// For more details, see `aztec::messages::processing::offchain::receive`.\n ///\n /// This function is automatically injected by the `#[aztec]` macro.\n #[aztec::macros::internals_functions_generation::abi_attributes::abi_utility]\n unconstrained fn $OFFCHAIN_RECEIVE_FN_NAME($OFFCHAIN_RECEIVE_PARAM_NAME: $param_type) -> $OFFCHAIN_RECEIVE_RETURN_TYPE {\n let address = aztec::context::UtilityContext::new().this_address();\n aztec::messages::processing::offchain::receive(address, $OFFCHAIN_RECEIVE_PARAM_NAME);\n }\n }\n}\n\n/// Checks that all functions in the module have a context macro applied.\n///\n/// Non-macroified functions are not allowed in contracts. They must all be one of\n/// [`crate::macros::functions::external`], [`crate::macros::functions::internal`] or `test`.\ncomptime fn check_each_fn_macroified(m: Module) {\n for f in m.functions() {\n let name = f.name();\n if !is_fn_external(f) & !is_fn_contract_library_method(f) & !is_fn_internal(f) & !is_fn_test(f) {\n // We don't suggest that #[contract_library_method] is allowed because we don't want to introduce another\n // concept\n panic(\n f\"Function {name} must be marked as either #[external(...)], #[internal(...)], or #[test]\",\n );\n }\n }\n}\n"
40
+ },
41
+ "110": {
42
+ "function_locations": [
43
+ {
44
+ "name": "generate_public_dispatch",
45
+ "start": 1231
46
+ },
47
+ {
48
+ "name": "signature_key",
49
+ "start": 5747
50
+ },
51
+ {
52
+ "name": "compute_unpack_prelude",
53
+ "start": 7187
54
+ },
55
+ {
56
+ "name": "inline_unpack",
57
+ "start": 8799
58
+ },
59
+ {
60
+ "name": "build_unpack_helper",
61
+ "start": 10034
62
+ },
63
+ {
64
+ "name": "get_type",
65
+ "start": 12238
66
+ }
67
+ ],
68
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/macros/dispatch.nr",
69
+ "source": "use crate::macros::internals_functions_generation::external_functions_registry::get_public_functions;\nuse crate::protocol::meta::utils::get_params_len_quote;\nuse crate::utils::cmap::CHashMap;\nuse super::functions::initialization_utils::EMIT_PUBLIC_INIT_NULLIFIER_FN_NAME;\nuse super::utils::compute_fn_selector;\n\n/// Minimum number of public functions that must share a parameter-type signature before we extract a shared\n/// unpack helper. See [compute_unpack_prelude] for the rationale behind the chosen value.\nglobal EXTRACTION_THRESHOLD: u32 = 4;\n\n/// Generates a `public_dispatch` function for an Aztec contract module `m`.\n///\n/// The generated function dispatches public calls based on selector to the appropriate contract function. If\n/// `generate_emit_public_init_nullifier` is true, it also handles dispatch to the macro-generated\n/// `__emit_public_init_nullifier` function.\n///\n/// Alongside `public_dispatch`, this also emits one `__aztec_nr_internals__unpack_arguments_<N>` helper per\n/// parameter-type signature shared by enough public functions; see [compute_unpack_prelude] for the extraction\n/// criterion.\npub comptime fn generate_public_dispatch(m: Module, generate_emit_public_init_nullifier: bool) -> Quoted {\n let functions = get_public_functions(m);\n\n let unit = get_type::<()>();\n\n // Count how many public functions share each parameter-type signature, so we can decide which signatures are\n // worth extracting into helpers.\n let signature_counts = &mut CHashMap::<Quoted, u32>::new();\n for function in functions {\n let parameters = function.parameters();\n if parameters.len() != 0 {\n let key = signature_key(parameters);\n let prior = signature_counts.get(key).unwrap_or(0);\n signature_counts.insert(key, prior + 1);\n }\n }\n\n let seen_selectors = &mut CHashMap::<Field, Quoted>::new();\n let signature_to_helper_idx = &mut CHashMap::<Quoted, u32>::new();\n // The helper function definitions, in the order they were created.\n let unpack_helpers: &mut [Quoted] = &mut @[];\n\n let mut ifs = functions.map(|function: FunctionDefinition| {\n let parameters = function.parameters();\n let return_type = function.return_type();\n\n let fn_name = function.name();\n let selector: Field = compute_fn_selector(fn_name, parameters);\n\n // Since function selectors are computed as the first 4 bytes of the hash of the function signature, it's\n // possible to have collisions. With the following check, we ensure it doesn't happen within the same contract.\n let existing_fn = seen_selectors.get(selector);\n if existing_fn.is_some() {\n let existing_fn = existing_fn.unwrap();\n panic(\n f\"Public function selector collision detected between functions '{fn_name}' and '{existing_fn}'\",\n );\n }\n seen_selectors.insert(selector, fn_name);\n\n let (unpack_prelude, call_args) = compute_unpack_prelude(\n parameters,\n signature_counts,\n signature_to_helper_idx,\n unpack_helpers,\n );\n\n // We call a function whose name is prefixed with `__aztec_nr_internals__`. This is necessary because the\n // original function is intentionally made uncallable, preventing direct invocation within the contract.\n // Instead, a new function with the same name, but prefixed by `__aztec_nr_internals__`, has been generated to\n // be called here. For more details see the `process_functions` function.\n let name = f\"__aztec_nr_internals__{fn_name}\".quoted_contents();\n let call = quote { $name($call_args) };\n\n let return_code = if return_type == unit {\n quote {\n $call;\n // Force early return.\n aztec::oracle::avm::avm_return([]);\n }\n } else {\n quote {\n let return_value = aztec::protocol::traits::Serialize::serialize($call);\n aztec::oracle::avm::avm_return(return_value.as_vector());\n }\n };\n\n let if_ = quote {\n if selector == $selector {\n $unpack_prelude\n $return_code\n }\n };\n if_\n });\n\n // If we injected the auto-generated public function to emit the public initialization nullifier, then\n // we'll also need to handle its dispatch.\n if generate_emit_public_init_nullifier {\n let name = EMIT_PUBLIC_INIT_NULLIFIER_FN_NAME;\n let init_nullifier_selector: Field = compute_fn_selector(name, @[]);\n\n ifs = ifs.push_back(\n quote {\n if selector == $init_nullifier_selector {\n $name();\n aztec::oracle::avm::avm_return([]);\n }\n },\n );\n }\n\n if ifs.len() == 0 {\n // No dispatch function if there are no public functions\n quote {}\n } else {\n let ifs = ifs.push_back(quote { panic(f\"Unknown selector {selector}\") });\n let dispatch = ifs.join(quote { });\n\n let helpers = (*unpack_helpers).join(quote { });\n\n let body = quote {\n $helpers\n\n // We mark this as public because our whole system depends on public functions having this attribute.\n #[aztec::macros::internals_functions_generation::abi_attributes::abi_public]\n pub unconstrained fn public_dispatch(selector: Field) {\n $dispatch\n }\n };\n\n body\n }\n}\n\n/// Canonical Quoted representation of a parameter list's types, used as the deduplication key for unpack helpers.\ncomptime fn signature_key(parameters: [(Quoted, Type)]) -> Quoted {\n parameters\n .map(|param: (Quoted, Type)| {\n let param_type = param.1;\n quote { $param_type }\n })\n .join(quote { , })\n}\n\n/// Builds the dispatch-arm prelude for a public function and the comma-separated arg list to pass through to the call.\n///\n/// If the function's signature reaches `EXTRACTION_THRESHOLD`, the prelude reuses (or creates) a shared\n/// `__aztec_nr_internals__unpack_arguments_<N>` helper. Otherwise the calldata read is inlined, matching the\n/// pre-extraction shape; this avoids paying the helper-call overhead on signatures that would not benefit from the\n/// shared body.\n///\n/// The real break-even depends on the size of the inlined boilerplate at each call site (which scales with the\n/// parameter types' `stream_deserialize` cost), not just the share count: a signature with one `Field` arg inlines\n/// to a few opcodes per site, while a signature like `(AztecAddress, U128, PartialUintNote)` inlines into many. For\n/// now we approximate that with a single share-count threshold, which is the simplest knob that keeps the macro\n/// readable. If we ever want to be more precise we can size each helper against its per-site savings.\ncomptime fn compute_unpack_prelude(\n parameters: [(Quoted, Type)],\n signature_counts: &mut CHashMap<Quoted, u32>,\n signature_to_helper_idx: &mut CHashMap<Quoted, u32>,\n unpack_helpers: &mut [Quoted],\n) -> (Quoted, Quoted) {\n if parameters.len() == 0 {\n (quote {}, quote {})\n } else {\n let sig_key = signature_key(parameters);\n let count = signature_counts.get(sig_key).unwrap_or(0);\n let shared = count >= EXTRACTION_THRESHOLD;\n\n let mut arg_names: [Quoted] = @[];\n for parameter_index in 0..parameters.len() {\n let arg_name = f\"arg{parameter_index}\".quoted_contents();\n arg_names = arg_names.push_back(arg_name);\n }\n let args = arg_names.join(quote { , });\n\n let prelude = if shared {\n let existing_idx = signature_to_helper_idx.get(sig_key);\n let helper_idx = if existing_idx.is_some() {\n existing_idx.unwrap()\n } else {\n let new_idx = (*unpack_helpers).len();\n signature_to_helper_idx.insert(sig_key, new_idx);\n let helper_def = build_unpack_helper(new_idx, parameters);\n *unpack_helpers = (*unpack_helpers).push_back(helper_def);\n new_idx\n };\n let helper_name = f\"__aztec_nr_internals__unpack_arguments_{helper_idx}\".quoted_contents();\n if parameters.len() == 1 {\n quote { let arg0 = $helper_name(); }\n } else {\n quote { let ($args) = $helper_name(); }\n }\n } else {\n inline_unpack(parameters)\n };\n\n (prelude, args)\n }\n}\n\n/// Inlined calldata read + per-parameter `stream_deserialize` for signatures that are not worth extracting.\ncomptime fn inline_unpack(parameters: [(Quoted, Type)]) -> Quoted {\n let params_len_quote = get_params_len_quote(parameters);\n let initial_read = quote {\n let input_calldata: [Field; $params_len_quote] = aztec::oracle::avm::calldata_copy(1, $params_len_quote);\n let mut reader = aztec::protocol::utils::reader::Reader::new(input_calldata);\n };\n\n let mut read_quotes: [Quoted] = @[];\n for parameter_index in 0..parameters.len() {\n let arg_name = f\"arg{parameter_index}\".quoted_contents();\n let param_type = parameters[parameter_index].1;\n read_quotes = read_quotes.push_back(\n quote {\n let $arg_name: $param_type = aztec::protocol::traits::Deserialize::stream_deserialize(&mut reader);\n },\n );\n }\n let reads = read_quotes.join(quote { });\n\n quote {\n $initial_read\n $reads\n }\n}\n\n/// Emits the `#[inline_never]` helper that reads calldata for one specific parameter-type signature.\n///\n/// Returns a single value when there is only one parameter, and a tuple when there are several. Marked\n/// `#[inline_never]` (and therefore `unconstrained`) so each entry point can call into the same compiled body.\ncomptime fn build_unpack_helper(idx: u32, parameters: [(Quoted, Type)]) -> Quoted {\n let helper_name = f\"__aztec_nr_internals__unpack_arguments_{idx}\".quoted_contents();\n let params_len_quote = get_params_len_quote(parameters);\n\n // The initial calldata_copy offset is 1 to skip the Field selector. The expected calldata is the serialization\n // of:\n // - FunctionSelector: the selector of the function intended to dispatch\n // - Parameters: the parameters of the function intended to dispatch\n // That is, exactly what is expected for a call to the target function, but with a selector added at the\n // beginning.\n let initial_read = quote {\n let input_calldata: [Field; $params_len_quote] = aztec::oracle::avm::calldata_copy(1, $params_len_quote);\n let mut reader = aztec::protocol::utils::reader::Reader::new(input_calldata);\n };\n\n let mut read_quotes: [Quoted] = @[];\n let mut arg_quotes: [Quoted] = @[];\n let mut type_quotes: [Quoted] = @[];\n for parameter_index in 0..parameters.len() {\n let arg_name = f\"arg{parameter_index}\".quoted_contents();\n let param_type = parameters[parameter_index].1;\n read_quotes = read_quotes.push_back(\n quote {\n let $arg_name: $param_type = aztec::protocol::traits::Deserialize::stream_deserialize(&mut reader);\n },\n );\n arg_quotes = arg_quotes.push_back(arg_name);\n type_quotes = type_quotes.push_back(quote { $param_type });\n }\n let reads = read_quotes.join(quote { });\n let return_args = arg_quotes.join(quote { , });\n\n if parameters.len() == 1 {\n let only_type = parameters[0].1;\n quote {\n #[inline_never]\n #[contract_library_method]\n unconstrained fn $helper_name() -> $only_type {\n $initial_read\n $reads\n arg0\n }\n }\n } else {\n let return_types = type_quotes.join(quote { , });\n quote {\n #[inline_never]\n #[contract_library_method]\n unconstrained fn $helper_name() -> ($return_types) {\n $initial_read\n $reads\n ($return_args)\n }\n }\n }\n}\n\ncomptime fn get_type<T>() -> Type {\n let t: T = std::mem::zeroed();\n std::meta::type_of(t)\n}\n"
70
+ },
71
+ "121": {
72
+ "function_locations": [
73
+ {
74
+ "name": "generate_public_self_creator_from_context",
75
+ "start": 916
76
+ },
77
+ {
78
+ "name": "generate_public_self_creator",
79
+ "start": 3117
80
+ },
81
+ {
82
+ "name": "generate_public_external",
83
+ "start": 4225
84
+ }
85
+ ],
86
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/macros/internals_functions_generation/external/public.nr",
87
+ "source": "use crate::macros::{\n internals_functions_generation::external::helpers::{create_authorize_once_check, get_abi_relevant_attributes},\n utils::{\n fn_has_authorize_once, fn_has_noinitcheck, is_fn_initializer, is_fn_only_self, is_fn_view,\n module_has_initializer, module_has_storage,\n },\n};\n\n/// Emits a per-contract helper that creates the `self` value from a `PublicContext` already in scope.\n///\n/// This is the shared helper used by both:\n/// - public external functions, via [`generate_public_self_creator`], which constructs a fresh `PublicContext` from\n/// `calldata_copy` and then delegates to this helper; and\n/// - public internal functions and `#[contract_library_method]` bodies, which already receive `context` as a\n/// parameter and call this helper directly to skip the `calldata_copy` step.\npub(crate) comptime fn generate_public_self_creator_from_context(m: Module) -> Quoted {\n let (storage_type, storage_init) = if module_has_storage(m) {\n (quote { Storage<aztec::context::PublicContext> }, quote { let storage = Storage::init(context); })\n } else {\n // Contract does not have Storage defined, so we set storage to the unit type `()`. ContractSelfPublic requires\n // a storage struct in its constructor. Using an Option type would lead to worse developer experience and\n // higher constraint counts so we use the unit type `()` instead.\n (quote { () }, quote { let storage = (); })\n };\n\n quote {\n #[contract_library_method]\n unconstrained fn __aztec_nr_internals__create_public_self_from_context(context: aztec::context::PublicContext) -> aztec::contract_self::ContractSelfPublic<$storage_type, CallSelf<aztec::context::PublicContext>, CallSelfStatic<aztec::context::PublicContext>, CallInternal<aztec::context::PublicContext>> {\n $storage_init\n let self_address = context.this_address();\n let call_self: CallSelf<aztec::context::PublicContext> = CallSelf { address: self_address, context };\n let call_self_static: CallSelfStatic<aztec::context::PublicContext> = CallSelfStatic { address: self_address, context };\n let internal: CallInternal<aztec::context::PublicContext> = CallInternal { context };\n aztec::contract_self::ContractSelfPublic::new(context, storage, call_self, call_self_static, internal)\n }\n }\n}\n\n/// Generates the per-contract helper that builds public `self`.\n///\n/// Each public external function calls this helper instead of inlining the construction, so the same preamble does not\n/// appear duplicated in every public function body. We let Noir's inliner decide whether to inline the helper at each\n/// call site rather than forcing it via macro expansion.\n///\n/// The helper is generic over the calldata length `N` because `PublicContext::new` takes a closure that reads `N`\n/// fields from calldata. Noir monomorphizes one copy per distinct `N`, so public functions with the same number of\n/// serialized args reuse the same compiled code.\npub(crate) comptime fn generate_public_self_creator(m: Module) -> Quoted {\n let storage_type = if module_has_storage(m) {\n quote { Storage<aztec::context::PublicContext> }\n } else {\n quote { () }\n };\n\n quote {\n #[contract_library_method]\n unconstrained fn __aztec_nr_internals__create_public_self<let N: u32>() -> aztec::contract_self::ContractSelfPublic<$storage_type, CallSelf<aztec::context::PublicContext>, CallSelfStatic<aztec::context::PublicContext>, CallInternal<aztec::context::PublicContext>> {\n // Unlike in the private case, in public the `context` does not need to receive the hash of the original\n // params.\n let context = aztec::context::PublicContext::new(|| {\n // We start from 1 because we skip the selector for the dispatch function.\n let serialized_args : [Field; N] = aztec::oracle::avm::calldata_copy(1, N);\n aztec::hash::hash_args(serialized_args)\n });\n __aztec_nr_internals__create_public_self_from_context(context)\n }\n }\n}\n\npub(crate) comptime fn generate_public_external(f: FunctionDefinition) -> Quoted {\n let module_has_initializer = module_has_initializer(f.module());\n\n // Public functions undergo a lot of transformations from their Aztec.nr form.\n let original_params = f.parameters();\n\n let args_len_quote = if original_params.len() == 0 {\n // If the function has no parameters, we set the args_len to 0.\n quote { 0 }\n } else {\n // The following will give us <type_of_struct_member_1 as Serialize>::N + <type_of_struct_member_2 as\n // Serialize>::N + ...\n original_params\n .map(|(_, param_type): (Quoted, Type)| {\n quote {\n <$param_type as $crate::protocol::traits::Serialize>::N\n }\n })\n .join(quote {+})\n };\n\n let contract_self_creation = quote {\n #[allow(unused_variables)]\n let mut self = __aztec_nr_internals__create_public_self::<$args_len_quote>();\n };\n\n let original_function_name = f.name();\n\n // Modifications introduced by the different marker attributes.\n let internal_check = if is_fn_only_self(f) {\n let assertion_message = f\"Function {original_function_name} can only be called by the same contract\";\n quote { assert(self.msg_sender() == self.address, $assertion_message); }\n } else {\n quote {}\n };\n\n let view_check = if is_fn_view(f) {\n let assertion_message = f\"Function {original_function_name} can only be called statically\".as_quoted_str();\n quote { assert(self.context.is_static_call(), $assertion_message); }\n } else {\n quote {}\n };\n\n let (assert_initializer, mark_as_initialized) = if is_fn_initializer(f) {\n (\n quote {\n aztec::macros::functions::initialization_utils::assert_initialization_matches_address_preimage_public(self.context);\n },\n quote {\n aztec::macros::functions::initialization_utils::mark_as_initialized_from_public_initializer(self.context);\n },\n )\n } else {\n (quote {}, quote {})\n };\n\n // Initialization checks are not included in contracts that don't have initializers.\n let init_check = if module_has_initializer & !fn_has_noinitcheck(f) & !is_fn_initializer(f) {\n quote { aztec::macros::functions::initialization_utils::assert_is_initialized_public(self.context); }\n } else {\n quote {}\n };\n\n // Inject the authwit check if the function is marked with #[authorize_once].\n let authorize_once_check = if fn_has_authorize_once(f) {\n create_authorize_once_check(f, false)\n } else {\n quote {}\n };\n\n let to_prepend = quote {\n $contract_self_creation\n $assert_initializer\n $init_check\n $internal_check\n $view_check\n $authorize_once_check\n };\n\n // `mark_as_initialized` is placed after the user's function body. If it ran at the beginning, the contract\n // would appear initialized while the initializer is still running, allowing contracts called by the initializer\n // to re-enter into a half-initialized contract.\n let to_append = quote {\n $mark_as_initialized\n };\n\n let fn_name = f\"__aztec_nr_internals__{original_function_name}\".quoted_contents();\n let body = f.body();\n let return_type = f.return_type();\n\n // New function parameters are the same as the original function's ones.\n let params = original_params.map(|(param_name, param_type)| quote { $param_name: $param_type }).join(quote {, });\n\n // Preserve all attributes that are relevant to the function's ABI.\n let abi_relevant_attributes = get_abi_relevant_attributes(f);\n\n // All public functions are automatically made unconstrained, even if they were not marked as such. This is because\n // instead of compiling into a circuit, they will compile to bytecode that will be later transpiled into AVM\n // bytecode.\n quote {\n #[aztec::macros::internals_functions_generation::abi_attributes::abi_public]\n $abi_relevant_attributes\n unconstrained fn $fn_name($params) -> pub $return_type {\n $to_prepend\n $body\n $to_append\n }\n }\n}\n"
88
+ },
89
+ "15": {
90
+ "function_locations": [
91
+ {
92
+ "name": "compute_decomposition",
93
+ "start": 456
94
+ },
95
+ {
96
+ "name": "decompose_hint",
97
+ "start": 818
98
+ },
99
+ {
100
+ "name": "lte_hint",
101
+ "start": 906
102
+ },
103
+ {
104
+ "name": "assert_gt_limbs",
105
+ "start": 1116
106
+ },
107
+ {
108
+ "name": "decompose",
109
+ "start": 1725
110
+ },
111
+ {
112
+ "name": "assert_gt",
113
+ "start": 2431
114
+ },
115
+ {
116
+ "name": "assert_lt",
117
+ "start": 2837
118
+ },
119
+ {
120
+ "name": "gt",
121
+ "start": 2901
122
+ },
123
+ {
124
+ "name": "lt",
125
+ "start": 3405
126
+ },
127
+ {
128
+ "name": "tests::check_decompose",
129
+ "start": 3678
130
+ },
131
+ {
132
+ "name": "tests::check_lte_hint",
133
+ "start": 3928
134
+ },
135
+ {
136
+ "name": "tests::check_gt",
137
+ "start": 4261
138
+ },
139
+ {
140
+ "name": "tests::check_plo_phi",
141
+ "start": 4591
142
+ },
143
+ {
144
+ "name": "tests::check_decompose_edge_cases",
145
+ "start": 5086
146
+ },
147
+ {
148
+ "name": "tests::check_decompose_large_values",
149
+ "start": 5446
150
+ },
151
+ {
152
+ "name": "tests::check_lt_comprehensive",
153
+ "start": 5807
154
+ }
155
+ ],
156
+ "path": "std/field/bn254.nr",
157
+ "source": "use crate::field::field_less_than;\nuse crate::runtime::is_unconstrained;\n\n// The low and high decomposition of the field modulus\npub(crate) global PLO: Field = 53438638232309528389504892708671455233;\npub(crate) global PHI: Field = 64323764613183177041862057485226039389;\n\npub(crate) global TWO_POW_128: Field = 0x100000000000000000000000000000000;\n\n// Decomposes a single field into two 16 byte fields.\nfn compute_decomposition(x: Field) -> (Field, Field) {\n // Here's we're taking advantage of truncating 128 bit limbs from the input field\n // and then subtracting them from the input such the field division is equivalent to integer division.\n let low = (x as u128) as Field;\n let high = (x - low) / TWO_POW_128;\n\n (low, high)\n}\n\npub(crate) unconstrained fn decompose_hint(x: Field) -> (Field, Field) {\n compute_decomposition(x)\n}\n\nunconstrained fn lte_hint(x: Field, y: Field) -> bool {\n if x == y {\n true\n } else {\n field_less_than(x, y)\n }\n}\n\n// Assert that (alo > blo && ahi >= bhi) || (alo <= blo && ahi > bhi)\nfn assert_gt_limbs(a: (Field, Field), b: (Field, Field)) {\n let (alo, ahi) = a;\n let (blo, bhi) = b;\n // Safety: borrow is enforced to be boolean due to its type.\n // if borrow is 0, it asserts that (alo > blo && ahi >= bhi)\n // if borrow is 1, it asserts that (alo <= blo && ahi > bhi)\n unsafe {\n let borrow = lte_hint(alo, blo);\n\n let rlo = alo - blo - 1 + (borrow as Field) * TWO_POW_128;\n let rhi = ahi - bhi - (borrow as Field);\n\n rlo.assert_max_bit_size::<128>();\n rhi.assert_max_bit_size::<128>();\n }\n}\n\n/// Decompose a single field into two 16 byte fields.\npub fn decompose(x: Field) -> (Field, Field) {\n if is_unconstrained() {\n compute_decomposition(x)\n } else {\n // Safety: decomposition is properly checked below\n unsafe {\n // Take hints of the decomposition\n let (xlo, xhi) = decompose_hint(x);\n\n // Range check the limbs\n xlo.assert_max_bit_size::<128>();\n xhi.assert_max_bit_size::<128>();\n\n // Check that the decomposition is correct\n assert_eq(x, xlo + TWO_POW_128 * xhi);\n\n // Assert that the decomposition of P is greater than the decomposition of x\n assert_gt_limbs((PLO, PHI), (xlo, xhi));\n (xlo, xhi)\n }\n }\n}\n\npub fn assert_gt(a: Field, b: Field) {\n if is_unconstrained() {\n assert(\n // Safety: already unconstrained\n unsafe { field_less_than(b, a) },\n );\n } else {\n // Decompose a and b\n let a_limbs = decompose(a);\n let b_limbs = decompose(b);\n\n // Assert that a_limbs is greater than b_limbs\n assert_gt_limbs(a_limbs, b_limbs)\n }\n}\n\npub fn assert_lt(a: Field, b: Field) {\n assert_gt(b, a);\n}\n\npub fn gt(a: Field, b: Field) -> bool {\n if is_unconstrained() {\n // Safety: unsafe in unconstrained\n unsafe {\n field_less_than(b, a)\n }\n } else if a == b {\n false\n } else {\n // Safety: Take a hint of the comparison and verify it\n unsafe {\n if field_less_than(a, b) {\n assert_gt(b, a);\n false\n } else {\n assert_gt(a, b);\n true\n }\n }\n }\n}\n\npub fn lt(a: Field, b: Field) -> bool {\n gt(b, a)\n}\n\nmod tests {\n // TODO: Allow imports from \"super\"\n use crate::field::bn254::{assert_gt, decompose, gt, lt, lte_hint, PHI, PLO, TWO_POW_128};\n use crate::internal::test_unconstrained;\n use super::assert_lt;\n\n #[test]\n fn check_decompose() {\n assert_eq(decompose(TWO_POW_128), (0, 1));\n assert_eq(decompose(TWO_POW_128 + 0x1234567890), (0x1234567890, 1));\n assert_eq(decompose(0x1234567890), (0x1234567890, 0));\n }\n\n #[test]\n unconstrained fn check_lte_hint() {\n assert(lte_hint(0, 1));\n assert(lte_hint(0, 0x100));\n assert(lte_hint(0x100, TWO_POW_128 - 1));\n assert(!lte_hint(0 - 1, 0));\n\n assert(lte_hint(0, 0));\n assert(lte_hint(0x100, 0x100));\n assert(lte_hint(0 - 1, 0 - 1));\n }\n\n #[test]\n #[test_unconstrained]\n fn check_gt() {\n assert(gt(1, 0));\n assert(gt(0x100, 0));\n assert(gt((0 - 1), (0 - 2)));\n assert(gt(TWO_POW_128, 0));\n assert(!gt(0, 0));\n assert(!gt(0, 0x100));\n assert(gt(0 - 1, 0 - 2));\n assert(!gt(0 - 2, 0 - 1));\n assert_gt(0 - 1, 0);\n }\n\n #[test]\n fn check_plo_phi() {\n assert_eq(PLO + PHI * TWO_POW_128, 0);\n let p_bytes = crate::field::modulus_le_bytes();\n let mut p_low: Field = 0;\n let mut p_high: Field = 0;\n\n let mut offset = 1;\n for i in 0..16 {\n p_low += (p_bytes[i] as Field) * offset;\n p_high += (p_bytes[i + 16] as Field) * offset;\n offset *= 256;\n }\n assert_eq(p_low, PLO);\n assert_eq(p_high, PHI);\n }\n\n #[test]\n fn check_decompose_edge_cases() {\n assert_eq(decompose(0), (0, 0));\n assert_eq(decompose(TWO_POW_128 - 1), (TWO_POW_128 - 1, 0));\n assert_eq(decompose(TWO_POW_128 + 1), (1, 1));\n assert_eq(decompose(TWO_POW_128 * 2), (0, 2));\n assert_eq(decompose(TWO_POW_128 * 2 + 0x1234567890), (0x1234567890, 2));\n }\n\n #[test]\n fn check_decompose_large_values() {\n let large_field = 0xffffffffffffffff;\n let (lo, hi) = decompose(large_field);\n assert_eq(large_field, lo + TWO_POW_128 * hi);\n\n let large_value = large_field - TWO_POW_128;\n let (lo2, hi2) = decompose(large_value);\n assert_eq(large_value, lo2 + TWO_POW_128 * hi2);\n }\n\n #[test]\n fn check_lt_comprehensive() {\n assert(lt(0, 1));\n assert_lt(0, 1);\n assert(!lt(1, 0));\n assert(!lt(0, 0));\n assert(!lt(42, 42));\n\n assert(lt(TWO_POW_128 - 1, TWO_POW_128));\n assert(!lt(TWO_POW_128, TWO_POW_128 - 1));\n }\n}\n"
158
+ },
159
+ "16": {
160
+ "function_locations": [
161
+ {
162
+ "name": "Field::assert_max_bit_size",
163
+ "start": 380
164
+ },
165
+ {
166
+ "name": "Field::to_le_bits",
167
+ "start": 1196
168
+ },
169
+ {
170
+ "name": "Field::to_be_bits",
171
+ "start": 2387
172
+ },
173
+ {
174
+ "name": "Field::to_le_bytes",
175
+ "start": 3562
176
+ },
177
+ {
178
+ "name": "Field::to_be_bytes",
179
+ "start": 5033
180
+ },
181
+ {
182
+ "name": "Field::to_le_radix",
183
+ "start": 5904
184
+ },
185
+ {
186
+ "name": "Field::to_be_radix",
187
+ "start": 6362
188
+ },
189
+ {
190
+ "name": "Field::pow_32",
191
+ "start": 7053
192
+ },
193
+ {
194
+ "name": "Field::sgn0",
195
+ "start": 7455
196
+ },
197
+ {
198
+ "name": "Field::lt",
199
+ "start": 7538
200
+ },
201
+ {
202
+ "name": "Field::from_le_bytes",
203
+ "start": 8073
204
+ },
205
+ {
206
+ "name": "Field::from_be_bytes",
207
+ "start": 8820
208
+ },
209
+ {
210
+ "name": "Field::from_le_bytes_checked",
211
+ "start": 9611
212
+ },
213
+ {
214
+ "name": "Field::from_be_bytes_checked",
215
+ "start": 10620
216
+ },
217
+ {
218
+ "name": "__assert_max_bit_size",
219
+ "start": 11202
220
+ },
221
+ {
222
+ "name": "__to_le_radix",
223
+ "start": 11330
224
+ },
225
+ {
226
+ "name": "__to_be_radix",
227
+ "start": 11458
228
+ },
229
+ {
230
+ "name": "__to_le_bits",
231
+ "start": 12179
232
+ },
233
+ {
234
+ "name": "__to_be_bits",
235
+ "start": 12897
236
+ },
237
+ {
238
+ "name": "modulus_num_bits",
239
+ "start": 12972
240
+ },
241
+ {
242
+ "name": "modulus_be_bits",
243
+ "start": 13048
244
+ },
245
+ {
246
+ "name": "modulus_le_bits",
247
+ "start": 13124
248
+ },
249
+ {
250
+ "name": "modulus_be_bytes",
251
+ "start": 13200
252
+ },
253
+ {
254
+ "name": "modulus_le_bytes",
255
+ "start": 13276
256
+ },
257
+ {
258
+ "name": "__field_less_than",
259
+ "start": 13437
260
+ },
261
+ {
262
+ "name": "field_less_than",
263
+ "start": 13513
264
+ },
265
+ {
266
+ "name": "lt_fallback",
267
+ "start": 13589
268
+ },
269
+ {
270
+ "name": "tests::test_to_be_bits",
271
+ "start": 14551
272
+ },
273
+ {
274
+ "name": "tests::test_to_le_bits",
275
+ "start": 14824
276
+ },
277
+ {
278
+ "name": "tests::test_to_be_bytes",
279
+ "start": 15099
280
+ },
281
+ {
282
+ "name": "tests::test_to_le_bytes",
283
+ "start": 15405
284
+ },
285
+ {
286
+ "name": "tests::test_to_be_radix",
287
+ "start": 15711
288
+ },
289
+ {
290
+ "name": "tests::test_to_le_radix",
291
+ "start": 16293
292
+ },
293
+ {
294
+ "name": "tests::test_to_le_radix_1",
295
+ "start": 16893
296
+ },
297
+ {
298
+ "name": "tests::test_to_le_radix_brillig_1",
299
+ "start": 17346
300
+ },
301
+ {
302
+ "name": "tests::test_to_le_radix_3",
303
+ "start": 17700
304
+ },
305
+ {
306
+ "name": "tests::test_to_le_radix_brillig_3",
307
+ "start": 18011
308
+ },
309
+ {
310
+ "name": "tests::test_to_le_radix_512",
311
+ "start": 18439
312
+ },
313
+ {
314
+ "name": "tests::not_enough_limbs_brillig",
315
+ "start": 18848
316
+ },
317
+ {
318
+ "name": "tests::not_enough_limbs",
319
+ "start": 19044
320
+ },
321
+ {
322
+ "name": "tests::non_zero_field_to_le_bytes_zero_limbs",
323
+ "start": 19274
324
+ },
325
+ {
326
+ "name": "tests::non_zero_field_to_be_bytes_zero_limbs",
327
+ "start": 19469
328
+ },
329
+ {
330
+ "name": "tests::zero_field_to_bytes_zero_limbs_unconstrained",
331
+ "start": 19600
332
+ },
333
+ {
334
+ "name": "tests::zero_field_to_bytes_zero_limbs_constrained",
335
+ "start": 19915
336
+ },
337
+ {
338
+ "name": "tests::zero_field_to_bytes_zero_limbs_comptime",
339
+ "start": 20227
340
+ },
341
+ {
342
+ "name": "tests::test_field_less_than",
343
+ "start": 20558
344
+ },
345
+ {
346
+ "name": "tests::test_large_field_values_unconstrained",
347
+ "start": 20813
348
+ },
349
+ {
350
+ "name": "tests::test_large_field_values",
351
+ "start": 21266
352
+ },
353
+ {
354
+ "name": "tests::test_decomposition_edge_cases",
355
+ "start": 21713
356
+ },
357
+ {
358
+ "name": "tests::test_pow_32",
359
+ "start": 22303
360
+ },
361
+ {
362
+ "name": "tests::test_sgn0",
363
+ "start": 22632
364
+ },
365
+ {
366
+ "name": "tests::test_bit_decomposition_overflow",
367
+ "start": 23054
368
+ },
369
+ {
370
+ "name": "tests::test_byte_decomposition_overflow",
371
+ "start": 23336
372
+ },
373
+ {
374
+ "name": "tests::test_to_from_be_bytes_bn254_edge_cases",
375
+ "start": 23553
376
+ },
377
+ {
378
+ "name": "tests::test_to_from_le_bytes_bn254_edge_cases",
379
+ "start": 25504
380
+ },
381
+ {
382
+ "name": "tests::test_from_le_bytes_checked_accepts_modulus_minus_one",
383
+ "start": 27439
384
+ },
385
+ {
386
+ "name": "tests::test_from_le_bytes_checked_rejects_modulus",
387
+ "start": 27918
388
+ },
389
+ {
390
+ "name": "tests::test_from_le_bytes_checked_rejects_modulus_plus_one",
391
+ "start": 28303
392
+ },
393
+ {
394
+ "name": "tests::test_from_be_bytes_checked_accepts_modulus_minus_one",
395
+ "start": 28758
396
+ },
397
+ {
398
+ "name": "tests::test_from_be_bytes_checked_rejects_modulus",
399
+ "start": 29247
400
+ },
401
+ {
402
+ "name": "tests::test_from_be_bytes_checked_rejects_modulus_plus_one",
403
+ "start": 29632
404
+ },
405
+ {
406
+ "name": "tests::test_from_bytes_checked_small_n",
407
+ "start": 30076
408
+ },
409
+ {
410
+ "name": "tests::from_le_bits",
411
+ "start": 30721
412
+ },
413
+ {
414
+ "name": "tests::from_be_bits",
415
+ "start": 31268
416
+ },
417
+ {
418
+ "name": "tests::test_to_from_be_bits_bn254_edge_cases",
419
+ "start": 31514
420
+ },
421
+ {
422
+ "name": "tests::test_to_from_le_bits_bn254_edge_cases",
423
+ "start": 33447
424
+ },
425
+ {
426
+ "name": "tests::max_bit_size_too_large",
427
+ "start": 35379
428
+ }
429
+ ],
430
+ "path": "std/field/mod.nr",
431
+ "source": "pub mod bn254;\nuse crate::{runtime::is_unconstrained, static_assert};\nuse bn254::lt as bn254_lt;\n\nimpl Field {\n /// Asserts that `self` can be represented in `bit_size` bits.\n ///\n /// # Failures\n /// Causes a constraint failure for `Field` values exceeding `2^{bit_size}`.\n // docs:start:assert_max_bit_size\n pub fn assert_max_bit_size<let BIT_SIZE: u32>(self) {\n // docs:end:assert_max_bit_size\n static_assert(\n BIT_SIZE < modulus_num_bits() as u32,\n \"BIT_SIZE must be less than modulus_num_bits\",\n );\n __assert_max_bit_size(self, BIT_SIZE);\n }\n\n /// Decomposes `self` into its little endian bit decomposition as a `[bool; N]` array.\n /// This array will be zero padded should not all bits be necessary to represent `self`.\n ///\n /// # Failures\n /// Causes a constraint failure for `Field` values exceeding `2^N` as the resulting array will not\n /// be able to represent the original `Field`.\n ///\n /// # Safety\n /// The bit decomposition returned is canonical and is guaranteed to not overflow the modulus.\n // docs:start:to_le_bits\n pub fn to_le_bits<let N: u32>(self: Self) -> [bool; N] {\n // docs:end:to_le_bits\n let bits = __to_le_bits(self);\n\n if !is_unconstrained() {\n // Ensure that the byte decomposition does not overflow the modulus\n let p = modulus_le_bits();\n assert(bits.len() <= p.len());\n let mut ok = bits.len() != p.len();\n for i in 0..N {\n if !ok {\n if (bits[N - 1 - i] != p[N - 1 - i]) {\n assert(p[N - 1 - i]);\n ok = true;\n }\n }\n }\n assert(ok);\n }\n bits\n }\n\n /// Decomposes `self` into its big endian bit decomposition as a `[bool; N]` array.\n /// This array will be zero padded should not all bits be necessary to represent `self`.\n ///\n /// # Failures\n /// Causes a constraint failure for `Field` values exceeding `2^N` as the resulting array will not\n /// be able to represent the original `Field`.\n ///\n /// # Safety\n /// The bit decomposition returned is canonical and is guaranteed to not overflow the modulus.\n // docs:start:to_be_bits\n pub fn to_be_bits<let N: u32>(self: Self) -> [bool; N] {\n // docs:end:to_be_bits\n let bits = __to_be_bits(self);\n\n if !is_unconstrained() {\n // Ensure that the decomposition does not overflow the modulus\n let p = modulus_be_bits();\n assert(bits.len() <= p.len());\n let mut ok = bits.len() != p.len();\n for i in 0..N {\n if !ok {\n if (bits[i] != p[i]) {\n assert(p[i]);\n ok = true;\n }\n }\n }\n assert(ok);\n }\n bits\n }\n\n /// Decomposes `self` into its little endian byte decomposition as a `[u8;N]` array\n /// This array will be zero padded should not all bytes be necessary to represent `self`.\n ///\n /// # Failures\n /// The length N of the array must be big enough to contain all the bytes of the 'self',\n /// and no more than the number of bytes required to represent the field modulus\n ///\n /// # Safety\n /// The result is ensured to be the canonical decomposition of the field element\n // docs:start:to_le_bytes\n pub fn to_le_bytes<let N: u32>(self: Self) -> [u8; N] {\n // docs:end:to_le_bytes\n static_assert(\n N <= modulus_le_bytes().len(),\n \"N must be less than or equal to modulus_le_bytes().len()\",\n );\n // Compute the byte decomposition\n let bytes = self.to_le_radix(256);\n\n if !is_unconstrained() {\n // Ensure that the byte decomposition does not overflow the modulus\n let p = modulus_le_bytes();\n assert(bytes.len() <= p.len());\n let mut ok = bytes.len() != p.len();\n for i in 0..N {\n if !ok {\n if (bytes[N - 1 - i] != p[N - 1 - i]) {\n assert(bytes[N - 1 - i] < p[N - 1 - i]);\n ok = true;\n }\n }\n }\n assert(ok);\n }\n bytes\n }\n\n /// Decomposes `self` into its big endian byte decomposition as a `[u8;N]` array of length required to represent the field modulus\n /// This array will be zero padded should not all bytes be necessary to represent `self`.\n ///\n /// # Failures\n /// The length N of the array must be big enough to contain all the bytes of the 'self',\n /// and no more than the number of bytes required to represent the field modulus\n ///\n /// # Safety\n /// The result is ensured to be the canonical decomposition of the field element\n // docs:start:to_be_bytes\n pub fn to_be_bytes<let N: u32>(self: Self) -> [u8; N] {\n // docs:end:to_be_bytes\n static_assert(\n N <= modulus_le_bytes().len(),\n \"N must be less than or equal to modulus_le_bytes().len()\",\n );\n // Compute the byte decomposition\n let bytes = self.to_be_radix(256);\n\n if !is_unconstrained() {\n // Ensure that the byte decomposition does not overflow the modulus\n let p = modulus_be_bytes();\n assert(bytes.len() <= p.len());\n let mut ok = bytes.len() != p.len();\n for i in 0..N {\n if !ok {\n if (bytes[i] != p[i]) {\n assert(bytes[i] < p[i]);\n ok = true;\n }\n }\n }\n assert(ok);\n }\n bytes\n }\n\n fn to_le_radix<let N: u32>(self: Self, radix: u32) -> [u8; N] {\n // Brillig does not need an immediate radix\n if !crate::runtime::is_unconstrained() {\n static_assert(1 < radix, \"radix must be greater than 1\");\n static_assert(radix <= 256, \"radix must be less than or equal to 256\");\n static_assert(radix & (radix - 1) == 0, \"radix must be a power of 2\");\n }\n __to_le_radix(self, radix)\n }\n\n fn to_be_radix<let N: u32>(self: Self, radix: u32) -> [u8; N] {\n // Brillig does not need an immediate radix\n if !crate::runtime::is_unconstrained() {\n static_assert(1 < radix, \"radix must be greater than 1\");\n static_assert(radix <= 256, \"radix must be less than or equal to 256\");\n static_assert(radix & (radix - 1) == 0, \"radix must be a power of 2\");\n }\n __to_be_radix(self, radix)\n }\n\n // Returns self to the power of the given exponent value.\n // Caution: we assume the exponent fits into 32 bits\n // using a bigger bit size impacts negatively the performance and should be done only if the exponent does not fit in 32 bits\n pub fn pow_32(self, exponent: Field) -> Field {\n let mut r: Field = 1;\n let b: [bool; 32] = exponent.to_le_bits();\n\n for i in 1..33 {\n r *= r;\n r = (b[32 - i] as Field) * (r * self) + (1 - b[32 - i] as Field) * r;\n }\n r\n }\n\n // Parity of (prime) Field element, i.e. sgn0(x mod p) = false if x `elem` {0, ..., p-1} is even, otherwise sgn0(x mod p) = true.\n pub fn sgn0(self) -> bool {\n (self as u8) % 2 == 1\n }\n\n pub fn lt(self, another: Field) -> bool {\n if crate::compat::is_bn254() {\n bn254_lt(self, another)\n } else {\n lt_fallback(self, another)\n }\n }\n\n /// Convert a little endian byte array to a field element.\n /// If the provided byte array overflows the field modulus then the Field will silently wrap around.\n ///\n /// # Failures\n /// `N` must be no greater than the number of bytes required to represent the field modulus\n // docs:start:from_le_bytes\n pub fn from_le_bytes<let N: u32>(bytes: [u8; N]) -> Field {\n // docs:end:from_le_bytes\n static_assert(\n N <= modulus_le_bytes().len(),\n \"N must be less than or equal to modulus_le_bytes().len()\",\n );\n let mut v = 1;\n let mut result = 0;\n\n for i in 0..N {\n result += (bytes[i] as Field) * v;\n v = v * 256;\n }\n result\n }\n\n /// Convert a big endian byte array to a field element.\n /// If the provided byte array overflows the field modulus then the Field will silently wrap around.\n ///\n /// # Failures\n /// `N` must be no greater than the number of bytes required to represent the field modulus\n // docs:start:from_be_bytes\n pub fn from_be_bytes<let N: u32>(bytes: [u8; N]) -> Field {\n // docs:end:from_be_bytes\n static_assert(\n N <= modulus_be_bytes().len(),\n \"N must be less than or equal to modulus_be_bytes().len()\",\n );\n let mut v = 1;\n let mut result = 0;\n\n for i in 0..N {\n result += (bytes[N - 1 - i] as Field) * v;\n v = v * 256;\n }\n result\n }\n\n /// Convert a little endian byte array to a field element, asserting that the input is a\n /// canonical representation (strictly less than the field modulus).\n ///\n /// # Failures\n /// Causes a constraint failure if `bytes` encodes a value greater than or equal to the\n /// field modulus.\n // docs:start:from_le_bytes_checked\n pub fn from_le_bytes_checked<let N: u32>(bytes: [u8; N]) -> Field {\n // docs:end:from_le_bytes_checked\n let p = modulus_le_bytes();\n let mut ok = N != p.len();\n for i in 0..N {\n if !ok {\n if bytes[N - 1 - i] != p[N - 1 - i] {\n assert(\n bytes[N - 1 - i] < p[N - 1 - i],\n \"input bytes are not a canonical field representation\",\n );\n ok = true;\n }\n }\n }\n assert(ok, \"input bytes are not a canonical field representation\");\n Field::from_le_bytes(bytes)\n }\n\n /// Convert a big endian byte array to a field element, asserting that the input is a\n /// canonical representation (strictly less than the field modulus).\n ///\n /// # Failures\n /// Causes a constraint failure if `bytes` encodes a value greater than or equal to the\n /// field modulus.\n // docs:start:from_be_bytes_checked\n pub fn from_be_bytes_checked<let N: u32>(bytes: [u8; N]) -> Field {\n // docs:end:from_be_bytes_checked\n let p = modulus_be_bytes();\n let mut ok = N != p.len();\n for i in 0..N {\n if !ok {\n if bytes[i] != p[i] {\n assert(bytes[i] < p[i], \"input bytes are not a canonical field representation\");\n ok = true;\n }\n }\n }\n assert(ok, \"input bytes are not a canonical field representation\");\n Field::from_be_bytes(bytes)\n }\n}\n\n#[builtin(apply_range_constraint)]\nfn __assert_max_bit_size(value: Field, bit_size: u32) {}\n\n// `_radix` must be less than 256\n#[builtin(to_le_radix)]\nfn __to_le_radix<let N: u32>(value: Field, radix: u32) -> [u8; N] {}\n\n// `_radix` must be less than 256\n#[builtin(to_be_radix)]\nfn __to_be_radix<let N: u32>(value: Field, radix: u32) -> [u8; N] {}\n\n/// Decomposes `self` into its little endian bit decomposition as a `[bool; N]` array.\n/// This array will be zero padded should not all bits be necessary to represent `self`.\n///\n/// # Failures\n/// Causes a constraint failure for `Field` values exceeding `2^N` as the resulting array will not\n/// be able to represent the original `Field`.\n///\n/// # Safety\n/// Values of `N` equal to or greater than the number of bits necessary to represent the `Field` modulus\n/// (e.g. 254 for the BN254 field) allow for multiple bit decompositions. This is due to how the `Field` will\n/// wrap around due to overflow when verifying the decomposition.\n#[builtin(to_le_bits)]\nfn __to_le_bits<let N: u32>(value: Field) -> [bool; N] {}\n\n/// Decomposes `self` into its big endian bit decomposition as a `[bool; N]` array.\n/// This array will be zero padded should not all bits be necessary to represent `self`.\n///\n/// # Failures\n/// Causes a constraint failure for `Field` values exceeding `2^N` as the resulting array will not\n/// be able to represent the original `Field`.\n///\n/// # Safety\n/// Values of `N` equal to or greater than the number of bits necessary to represent the `Field` modulus\n/// (e.g. 254 for the BN254 field) allow for multiple bit decompositions. This is due to how the `Field` will\n/// wrap around due to overflow when verifying the decomposition.\n#[builtin(to_be_bits)]\nfn __to_be_bits<let N: u32>(value: Field) -> [bool; N] {}\n\n#[builtin(modulus_num_bits)]\npub comptime fn modulus_num_bits() -> u64 {}\n\n#[builtin(modulus_be_bits)]\npub comptime fn modulus_be_bits() -> [bool] {}\n\n#[builtin(modulus_le_bits)]\npub comptime fn modulus_le_bits() -> [bool] {}\n\n#[builtin(modulus_be_bytes)]\npub comptime fn modulus_be_bytes() -> [u8] {}\n\n#[builtin(modulus_le_bytes)]\npub comptime fn modulus_le_bytes() -> [u8] {}\n\n/// An unconstrained only built in to efficiently compare fields.\n#[builtin(field_less_than)]\nunconstrained fn __field_less_than(x: Field, y: Field) -> bool {}\n\npub(crate) unconstrained fn field_less_than(x: Field, y: Field) -> bool {\n __field_less_than(x, y)\n}\n\nfn lt_fallback(x: Field, y: Field) -> bool {\n if is_unconstrained() {\n // Safety: unconstrained context\n unsafe {\n field_less_than(x, y)\n }\n } else {\n let x_bytes: [u8; 32] = x.to_le_bytes();\n let y_bytes: [u8; 32] = y.to_le_bytes();\n let mut x_is_lt = false;\n let mut done = false;\n for i in 0..32 {\n if (!done) {\n let x_byte = x_bytes[32 - 1 - i] as u8;\n let y_byte = y_bytes[32 - 1 - i] as u8;\n let bytes_match = x_byte == y_byte;\n if !bytes_match {\n x_is_lt = x_byte < y_byte;\n done = true;\n }\n }\n }\n x_is_lt\n }\n}\n\nmod tests {\n use crate::{panic::panic, runtime, static_assert};\n use super::{\n field_less_than, modulus_be_bits, modulus_be_bytes, modulus_le_bits, modulus_le_bytes,\n };\n\n #[test]\n // docs:start:to_be_bits_example\n fn test_to_be_bits() {\n let field = 2;\n let bits: [bool; 8] = field.to_be_bits();\n assert_eq(bits, [false, false, false, false, false, false, true, false]);\n }\n // docs:end:to_be_bits_example\n\n #[test]\n // docs:start:to_le_bits_example\n fn test_to_le_bits() {\n let field = 2;\n let bits: [bool; 8] = field.to_le_bits();\n assert_eq(bits, [false, true, false, false, false, false, false, false]);\n }\n // docs:end:to_le_bits_example\n\n #[test]\n // docs:start:to_be_bytes_example\n fn test_to_be_bytes() {\n let field = 2;\n let bytes: [u8; 8] = field.to_be_bytes();\n assert_eq(bytes, [0, 0, 0, 0, 0, 0, 0, 2]);\n assert_eq(Field::from_be_bytes::<8>(bytes), field);\n }\n // docs:end:to_be_bytes_example\n\n #[test]\n // docs:start:to_le_bytes_example\n fn test_to_le_bytes() {\n let field = 2;\n let bytes: [u8; 8] = field.to_le_bytes();\n assert_eq(bytes, [2, 0, 0, 0, 0, 0, 0, 0]);\n assert_eq(Field::from_le_bytes::<8>(bytes), field);\n }\n // docs:end:to_le_bytes_example\n\n #[test]\n // docs:start:to_be_radix_example\n fn test_to_be_radix() {\n // 259, in base 256, big endian, is [1, 3].\n // i.e. 3 * 256^0 + 1 * 256^1\n let field = 259;\n\n // The radix (in this example, 256) must be a power of 2.\n // The length of the returned byte array can be specified to be\n // >= the amount of space needed.\n let bytes: [u8; 8] = field.to_be_radix(256);\n assert_eq(bytes, [0, 0, 0, 0, 0, 0, 1, 3]);\n assert_eq(Field::from_be_bytes::<8>(bytes), field);\n }\n // docs:end:to_be_radix_example\n\n #[test]\n // docs:start:to_le_radix_example\n fn test_to_le_radix() {\n // 259, in base 256, little endian, is [3, 1].\n // i.e. 3 * 256^0 + 1 * 256^1\n let field = 259;\n\n // The radix (in this example, 256) must be a power of 2.\n // The length of the returned byte array can be specified to be\n // >= the amount of space needed.\n let bytes: [u8; 8] = field.to_le_radix(256);\n assert_eq(bytes, [3, 1, 0, 0, 0, 0, 0, 0]);\n assert_eq(Field::from_le_bytes::<8>(bytes), field);\n }\n // docs:end:to_le_radix_example\n\n #[test(should_fail_with = \"radix must be greater than 1\")]\n fn test_to_le_radix_1() {\n // this test should only fail in constrained mode\n if !runtime::is_unconstrained() {\n let field = 2;\n let _: [u8; 8] = field.to_le_radix(1);\n } else {\n panic(\"radix must be greater than 1\");\n }\n }\n\n // Updated test to account for Brillig restriction that radix must be greater than 2\n #[test(should_fail_with = \"radix must be greater than 1\")]\n fn test_to_le_radix_brillig_1() {\n // this test should only fail in constrained mode\n if !runtime::is_unconstrained() {\n let field = 1;\n let _: [u8; 8] = field.to_le_radix(1);\n } else {\n panic(\"radix must be greater than 1\");\n }\n }\n\n #[test(should_fail_with = \"radix must be a power of 2\")]\n fn test_to_le_radix_3() {\n // this test should only fail in constrained mode\n if !runtime::is_unconstrained() {\n let field = 2;\n let _: [u8; 8] = field.to_le_radix(3);\n } else {\n panic(\"radix must be a power of 2\");\n }\n }\n\n #[test]\n fn test_to_le_radix_brillig_3() {\n // this test should only fail in constrained mode\n if runtime::is_unconstrained() {\n let field = 1;\n let out: [u8; 8] = field.to_le_radix(3);\n let mut expected = [0; 8];\n expected[0] = 1;\n assert(out == expected, \"unexpected result\");\n }\n }\n\n #[test(should_fail_with = \"radix must be less than or equal to 256\")]\n fn test_to_le_radix_512() {\n // this test should only fail in constrained mode\n if !runtime::is_unconstrained() {\n let field = 2;\n let _: [u8; 8] = field.to_le_radix(512);\n } else {\n panic(\"radix must be less than or equal to 256\")\n }\n }\n\n #[test(should_fail_with = \"Field failed to decompose into specified 16 limbs\")]\n unconstrained fn not_enough_limbs_brillig() {\n let _: [u8; 16] = 0x100000000000000000000000000000000.to_le_bytes();\n }\n\n #[test(should_fail_with = \"Field failed to decompose into specified 16 limbs\")]\n fn not_enough_limbs() {\n let _: [u8; 16] = 0x100000000000000000000000000000000.to_le_bytes();\n }\n\n #[test(should_fail_with = \"Field failed to decompose into specified 0 limbs\")]\n unconstrained fn non_zero_field_to_le_bytes_zero_limbs() {\n let _: [u8; 0] = 5.to_le_bytes();\n }\n\n #[test(should_fail_with = \"Field failed to decompose into specified 0 limbs\")]\n unconstrained fn non_zero_field_to_be_bytes_zero_limbs() {\n let _: [u8; 0] = 5.to_be_bytes();\n }\n\n #[test]\n unconstrained fn zero_field_to_bytes_zero_limbs_unconstrained() {\n assert_eq((0 as Field).to_le_bytes::<0>().len(), 0);\n assert_eq((0 as Field).to_be_bytes::<0>().len(), 0);\n assert_eq((0 as Field).to_le_bits::<0>().len(), 0);\n assert_eq((0 as Field).to_be_bits::<0>().len(), 0);\n }\n\n #[test]\n fn zero_field_to_bytes_zero_limbs_constrained() {\n assert_eq((0 as Field).to_le_bytes::<0>().len(), 0);\n assert_eq((0 as Field).to_be_bytes::<0>().len(), 0);\n assert_eq((0 as Field).to_le_bits::<0>().len(), 0);\n assert_eq((0 as Field).to_be_bits::<0>().len(), 0);\n }\n\n #[test]\n fn zero_field_to_bytes_zero_limbs_comptime() {\n let _: [u8; 0] = comptime { (0 as Field).to_le_bytes() };\n let _: [u8; 0] = comptime { (0 as Field).to_be_bytes() };\n let _: [bool; 0] = comptime { (0 as Field).to_le_bits() };\n let _: [bool; 0] = comptime { (0 as Field).to_be_bits() };\n }\n\n #[test]\n unconstrained fn test_field_less_than() {\n assert(field_less_than(0, 1));\n assert(field_less_than(0, 0x100));\n assert(field_less_than(0x100, 0 - 1));\n assert(!field_less_than(0 - 1, 0));\n }\n\n #[test]\n unconstrained fn test_large_field_values_unconstrained() {\n let large_field = 0xffffffffffffffff;\n\n let bits: [bool; 64] = large_field.to_le_bits();\n assert_eq(bits[0], true);\n\n let bytes: [u8; 8] = large_field.to_le_bytes();\n assert_eq(Field::from_le_bytes::<8>(bytes), large_field);\n\n let radix_bytes: [u8; 8] = large_field.to_le_radix(256);\n assert_eq(Field::from_le_bytes::<8>(radix_bytes), large_field);\n }\n\n #[test]\n fn test_large_field_values() {\n let large_val = 0xffffffffffffffff;\n\n let bits: [bool; 64] = large_val.to_le_bits();\n assert_eq(bits[0], true);\n\n let bytes: [u8; 8] = large_val.to_le_bytes();\n assert_eq(Field::from_le_bytes::<8>(bytes), large_val);\n\n let radix_bytes: [u8; 8] = large_val.to_le_radix(256);\n assert_eq(Field::from_le_bytes::<8>(radix_bytes), large_val);\n }\n\n #[test]\n fn test_decomposition_edge_cases() {\n let zero_bits: [bool; 8] = 0.to_le_bits();\n assert_eq(zero_bits, [false; 8]);\n\n let zero_bytes: [u8; 8] = 0.to_le_bytes();\n assert_eq(zero_bytes, [0; 8]);\n\n let one_bits: [bool; 8] = 1.to_le_bits();\n let expected: [bool; 8] = [true, false, false, false, false, false, false, false];\n assert_eq(one_bits, expected);\n\n let pow2_bits: [bool; 8] = 4.to_le_bits();\n let expected: [bool; 8] = [false, false, true, false, false, false, false, false];\n assert_eq(pow2_bits, expected);\n }\n\n #[test]\n fn test_pow_32() {\n assert_eq(2.pow_32(3), 8);\n assert_eq(3.pow_32(2), 9);\n assert_eq(5.pow_32(0), 1);\n assert_eq(7.pow_32(1), 7);\n\n assert_eq(2.pow_32(10), 1024);\n\n assert_eq(0.pow_32(5), 0);\n assert_eq(0.pow_32(0), 1);\n\n assert_eq(1.pow_32(100), 1);\n }\n\n #[test]\n fn test_sgn0() {\n assert_eq(0.sgn0(), false);\n assert_eq(2.sgn0(), false);\n assert_eq(4.sgn0(), false);\n assert_eq(100.sgn0(), false);\n\n assert_eq(1.sgn0(), true);\n assert_eq(3.sgn0(), true);\n assert_eq(5.sgn0(), true);\n assert_eq(101.sgn0(), true);\n }\n\n #[test(should_fail_with = \"Field failed to decompose into specified 8 limbs\")]\n fn test_bit_decomposition_overflow() {\n // 8 bits can't represent large field values\n let large_val = 0x1000000000000000;\n let _: [bool; 8] = large_val.to_le_bits();\n }\n\n #[test(should_fail_with = \"Field failed to decompose into specified 4 limbs\")]\n fn test_byte_decomposition_overflow() {\n // 4 bytes can't represent large field values\n let large_val = 0x1000000000000000;\n let _: [u8; 4] = large_val.to_le_bytes();\n }\n\n #[test]\n fn test_to_from_be_bytes_bn254_edge_cases() {\n if crate::compat::is_bn254() {\n // checking that decrementing this byte produces the expected 32 BE bytes for (modulus - 1)\n let mut p_minus_1_bytes: [u8; 32] = modulus_be_bytes().as_array();\n assert(p_minus_1_bytes[32 - 1] > 0);\n p_minus_1_bytes[32 - 1] -= 1;\n\n let p_minus_1 = Field::from_be_bytes::<32>(p_minus_1_bytes);\n assert_eq(p_minus_1 + 1, 0);\n\n // checking that converting (modulus - 1) from and then to 32 BE bytes produces the same bytes\n let p_minus_1_converted_bytes: [u8; 32] = p_minus_1.to_be_bytes();\n assert_eq(p_minus_1_converted_bytes, p_minus_1_bytes);\n\n // checking that incrementing this byte produces 32 BE bytes for (modulus + 1)\n let mut p_plus_1_bytes: [u8; 32] = modulus_be_bytes().as_array();\n assert(p_plus_1_bytes[32 - 1] < 255);\n p_plus_1_bytes[32 - 1] += 1;\n\n let p_plus_1 = Field::from_be_bytes::<32>(p_plus_1_bytes);\n assert_eq(p_plus_1, 1);\n\n // checking that converting p_plus_1 to 32 BE bytes produces the same\n // byte set to 1 as p_plus_1_bytes and otherwise zeroes\n let mut p_plus_1_converted_bytes: [u8; 32] = p_plus_1.to_be_bytes();\n assert_eq(p_plus_1_converted_bytes[32 - 1], 1);\n p_plus_1_converted_bytes[32 - 1] = 0;\n assert_eq(p_plus_1_converted_bytes, [0; 32]);\n\n // checking that Field::from_be_bytes::<32> on the Field modulus produces 0\n assert_eq(modulus_be_bytes().len(), 32);\n let p = Field::from_be_bytes::<32>(modulus_be_bytes().as_array());\n assert_eq(p, 0);\n\n // checking that converting 0 to 32 BE bytes produces 32 zeroes\n let p_bytes: [u8; 32] = 0.to_be_bytes();\n assert_eq(p_bytes, [0; 32]);\n }\n }\n\n #[test]\n fn test_to_from_le_bytes_bn254_edge_cases() {\n if crate::compat::is_bn254() {\n // checking that decrementing this byte produces the expected 32 LE bytes for (modulus - 1)\n let mut p_minus_1_bytes: [u8; 32] = modulus_le_bytes().as_array();\n assert(p_minus_1_bytes[0] > 0);\n p_minus_1_bytes[0] -= 1;\n\n let p_minus_1 = Field::from_le_bytes::<32>(p_minus_1_bytes);\n assert_eq(p_minus_1 + 1, 0);\n\n // checking that converting (modulus - 1) from and then to 32 BE bytes produces the same bytes\n let p_minus_1_converted_bytes: [u8; 32] = p_minus_1.to_le_bytes();\n assert_eq(p_minus_1_converted_bytes, p_minus_1_bytes);\n\n // checking that incrementing this byte produces 32 LE bytes for (modulus + 1)\n let mut p_plus_1_bytes: [u8; 32] = modulus_le_bytes().as_array();\n assert(p_plus_1_bytes[0] < 255);\n p_plus_1_bytes[0] += 1;\n\n let p_plus_1 = Field::from_le_bytes::<32>(p_plus_1_bytes);\n assert_eq(p_plus_1, 1);\n\n // checking that converting p_plus_1 to 32 LE bytes produces the same\n // byte set to 1 as p_plus_1_bytes and otherwise zeroes\n let mut p_plus_1_converted_bytes: [u8; 32] = p_plus_1.to_le_bytes();\n assert_eq(p_plus_1_converted_bytes[0], 1);\n p_plus_1_converted_bytes[0] = 0;\n assert_eq(p_plus_1_converted_bytes, [0; 32]);\n\n // checking that Field::from_le_bytes::<32> on the Field modulus produces 0\n assert_eq(modulus_le_bytes().len(), 32);\n let p = Field::from_le_bytes::<32>(modulus_le_bytes().as_array());\n assert_eq(p, 0);\n\n // checking that converting 0 to 32 LE bytes produces 32 zeroes\n let p_bytes: [u8; 32] = 0.to_le_bytes();\n assert_eq(p_bytes, [0; 32]);\n }\n }\n\n #[test]\n fn test_from_le_bytes_checked_accepts_modulus_minus_one() {\n if crate::compat::is_bn254() {\n let mut p_minus_1_bytes: [u8; 32] = modulus_le_bytes().as_array();\n assert(p_minus_1_bytes[0] > 0);\n p_minus_1_bytes[0] -= 1;\n let p_minus_1 = Field::from_le_bytes_checked::<32>(p_minus_1_bytes);\n assert_eq(p_minus_1 + 1, 0);\n }\n }\n\n #[test(should_fail_with = \"input bytes are not a canonical field representation\")]\n fn test_from_le_bytes_checked_rejects_modulus() {\n if crate::compat::is_bn254() {\n let _ = Field::from_le_bytes_checked::<32>(modulus_le_bytes().as_array());\n } else {\n panic(\"input bytes are not a canonical field representation\");\n }\n }\n\n #[test(should_fail_with = \"input bytes are not a canonical field representation\")]\n fn test_from_le_bytes_checked_rejects_modulus_plus_one() {\n if crate::compat::is_bn254() {\n let mut p_plus_1_bytes: [u8; 32] = modulus_le_bytes().as_array();\n assert(p_plus_1_bytes[0] < 255);\n p_plus_1_bytes[0] += 1;\n let _ = Field::from_le_bytes_checked::<32>(p_plus_1_bytes);\n } else {\n panic(\"input bytes are not a canonical field representation\");\n }\n }\n\n #[test]\n fn test_from_be_bytes_checked_accepts_modulus_minus_one() {\n if crate::compat::is_bn254() {\n let mut p_minus_1_bytes: [u8; 32] = modulus_be_bytes().as_array();\n assert(p_minus_1_bytes[32 - 1] > 0);\n p_minus_1_bytes[32 - 1] -= 1;\n let p_minus_1 = Field::from_be_bytes_checked::<32>(p_minus_1_bytes);\n assert_eq(p_minus_1 + 1, 0);\n }\n }\n\n #[test(should_fail_with = \"input bytes are not a canonical field representation\")]\n fn test_from_be_bytes_checked_rejects_modulus() {\n if crate::compat::is_bn254() {\n let _ = Field::from_be_bytes_checked::<32>(modulus_be_bytes().as_array());\n } else {\n panic(\"input bytes are not a canonical field representation\");\n }\n }\n\n #[test(should_fail_with = \"input bytes are not a canonical field representation\")]\n fn test_from_be_bytes_checked_rejects_modulus_plus_one() {\n if crate::compat::is_bn254() {\n let mut p_plus_1_bytes: [u8; 32] = modulus_be_bytes().as_array();\n assert(p_plus_1_bytes[32 - 1] < 255);\n p_plus_1_bytes[32 - 1] += 1;\n let _ = Field::from_be_bytes_checked::<32>(p_plus_1_bytes);\n } else {\n panic(\"input bytes are not a canonical field representation\");\n }\n }\n\n #[test]\n fn test_from_bytes_checked_small_n() {\n // For N < modulus_bytes().len(), the input cannot overflow the modulus, so the checked\n // variants behave identically to the unchecked ones.\n let le_bytes: [u8; 8] = [3, 1, 0, 0, 0, 0, 0, 0];\n assert_eq(Field::from_le_bytes_checked::<8>(le_bytes), 259);\n let be_bytes: [u8; 8] = [0, 0, 0, 0, 0, 0, 1, 3];\n assert_eq(Field::from_be_bytes_checked::<8>(be_bytes), 259);\n }\n\n /// Convert a little endian bit array to a field element.\n /// If the provided bit array overflows the field modulus then the Field will silently wrap around.\n fn from_le_bits<let N: u32>(bits: [bool; N]) -> Field {\n static_assert(\n N <= modulus_le_bits().len(),\n \"N must be less than or equal to modulus_le_bits().len()\",\n );\n let mut v = 1;\n let mut result = 0;\n\n for i in 0..N {\n result += (bits[i] as Field) * v;\n v = v * 2;\n }\n result\n }\n\n /// Convert a big endian bit array to a field element.\n /// If the provided bit array overflows the field modulus then the Field will silently wrap around.\n fn from_be_bits<let N: u32>(bits: [bool; N]) -> Field {\n let mut v = 1;\n let mut result = 0;\n\n for i in 0..N {\n result += (bits[N - 1 - i] as Field) * v;\n v = v * 2;\n }\n result\n }\n\n #[test]\n fn test_to_from_be_bits_bn254_edge_cases() {\n if crate::compat::is_bn254() {\n // checking that decrementing this bit produces the expected 254 BE bits for (modulus - 1)\n let mut p_minus_1_bits: [bool; 254] = modulus_be_bits().as_array();\n assert(p_minus_1_bits[254 - 1]);\n p_minus_1_bits[254 - 1] = false;\n\n let p_minus_1 = from_be_bits::<254>(p_minus_1_bits);\n assert_eq(p_minus_1 + 1, 0);\n\n // checking that converting (modulus - 1) from and then to 254 BE bits produces the same bits\n let p_minus_1_converted_bits: [bool; 254] = p_minus_1.to_be_bits();\n assert_eq(p_minus_1_converted_bits, p_minus_1_bits);\n\n // checking that incrementing this bit produces 254 BE bits for (modulus + 4)\n let mut p_plus_4_bits: [bool; 254] = modulus_be_bits().as_array();\n assert(!p_plus_4_bits[254 - 3]);\n p_plus_4_bits[254 - 3] = true;\n\n let p_plus_4 = from_be_bits::<254>(p_plus_4_bits);\n assert_eq(p_plus_4, 4);\n\n // checking that converting p_plus_4 to 254 BE bits produces the same\n // bit set to 1 as p_plus_4_bits and otherwise zeroes\n let mut p_plus_4_converted_bits: [bool; 254] = p_plus_4.to_be_bits();\n assert(p_plus_4_converted_bits[254 - 3]);\n p_plus_4_converted_bits[254 - 3] = false;\n assert_eq(p_plus_4_converted_bits, [false; 254]);\n\n // checking that Field::from_be_bits::<254> on the Field modulus produces 0\n assert_eq(modulus_be_bits().len(), 254);\n let p = from_be_bits::<254>(modulus_be_bits().as_array());\n assert_eq(p, 0);\n\n // checking that converting 0 to 254 BE bits produces 254 false values\n let p_bits: [bool; 254] = 0.to_be_bits();\n assert_eq(p_bits, [false; 254]);\n }\n }\n\n #[test]\n fn test_to_from_le_bits_bn254_edge_cases() {\n if crate::compat::is_bn254() {\n // checking that decrementing this bit produces the expected 254 LE bits for (modulus - 1)\n let mut p_minus_1_bits: [bool; 254] = modulus_le_bits().as_array();\n assert(p_minus_1_bits[0]);\n p_minus_1_bits[0] = false;\n\n let p_minus_1 = from_le_bits::<254>(p_minus_1_bits);\n assert_eq(p_minus_1 + 1, 0);\n\n // checking that converting (modulus - 1) from and then to 254 BE bits produces the same bits\n let p_minus_1_converted_bits: [bool; 254] = p_minus_1.to_le_bits();\n assert_eq(p_minus_1_converted_bits, p_minus_1_bits);\n\n // checking that incrementing this bit produces 254 LE bits for (modulus + 4)\n let mut p_plus_4_bits: [bool; 254] = modulus_le_bits().as_array();\n assert(!p_plus_4_bits[2]);\n p_plus_4_bits[2] = true;\n\n let p_plus_4 = from_le_bits::<254>(p_plus_4_bits);\n assert_eq(p_plus_4, 4);\n\n // checking that converting p_plus_4 to 254 LE bits produces the same\n // bit set to 1 as p_plus_4_bits and otherwise zeroes\n let mut p_plus_4_converted_bits: [bool; 254] = p_plus_4.to_le_bits();\n assert(p_plus_4_converted_bits[2]);\n p_plus_4_converted_bits[2] = false;\n assert_eq(p_plus_4_converted_bits, [false; 254]);\n\n // checking that Field::from_le_bits::<254> on the Field modulus produces 0\n assert_eq(modulus_le_bits().len(), 254);\n let p = from_le_bits::<254>(modulus_le_bits().as_array());\n assert_eq(p, 0);\n\n // checking that converting 0 to 254 LE bits produces 254 false values\n let p_bits: [bool; 254] = 0.to_le_bits();\n assert_eq(p_bits, [false; 254]);\n }\n }\n\n #[test(should_fail_with = \"call to assert_max_bit_size\")]\n fn max_bit_size_too_large() {\n let x: Field = 0x010000;\n x.assert_max_bit_size::<16>();\n }\n\n}\n"
432
+ },
433
+ "165": {
434
+ "function_locations": [
435
+ {
436
+ "name": "receive",
437
+ "start": 2699
438
+ },
439
+ {
440
+ "name": "sync_inbox",
441
+ "start": 4202
442
+ },
443
+ {
444
+ "name": "test::setup",
445
+ "start": 6051
446
+ },
447
+ {
448
+ "name": "test::make_msg",
449
+ "start": 6381
450
+ },
451
+ {
452
+ "name": "test::advance_by",
453
+ "start": 6664
454
+ },
455
+ {
456
+ "name": "test::empty_inbox_returns_empty_result",
457
+ "start": 6855
458
+ },
459
+ {
460
+ "name": "test::multiple_messages_mixed_expiration",
461
+ "start": 7243
462
+ },
463
+ {
464
+ "name": "test::accepts_messages_within_the_tolerated_future_skew",
465
+ "start": 9172
466
+ },
467
+ {
468
+ "name": "test::rejects_batch_with_implausible_future_anchor",
469
+ "start": 10197
470
+ },
471
+ {
472
+ "name": "test::redelivery_is_idempotent",
473
+ "start": 10895
474
+ },
475
+ {
476
+ "name": "test::redelivery_after_processing_keeps_processed_guard",
477
+ "start": 11760
478
+ }
479
+ ],
480
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/messages/processing/offchain/mod.nr",
481
+ "source": "use crate::{\n context::UtilityContext,\n ephemeral::EphemeralArray,\n messages::{encoding::MESSAGE_CIPHERTEXT_LEN, processing::OffchainMessageWithTx},\n oracle::{contract_sync::set_contract_sync_cache_invalid, tx_resolution::get_resolved_txs},\n protocol::{address::AztecAddress, traits::{Deserialize, Serialize}},\n};\n\nmod reception;\nuse reception::{MAX_ANCHOR_FUTURE_SKEW, OffchainReception};\n\n/// Maximum number of offchain messages accepted by `offchain_receive` in a single call.\npub global MAX_OFFCHAIN_MESSAGES_PER_RECEIVE_CALL: u32 = 16;\n\n/// A function that manages offchain-delivered messages for processing during sync.\n///\n/// Offchain messages are messages that are not broadcasted via onchain logs. They are instead delivered to the\n/// recipient by calling the `offchain_receive` utility function (injected by the `#[aztec]` macro). Message transport\n/// is the app's responsibility. Typical examples of transport methods are: messaging apps, email, QR codes, etc.\n///\n/// Once offchain messages are delivered to the recipient's private environment via `offchain_receive`, messages are\n/// locally stored in a persistent inbox.\n///\n/// This function determines when each message in said inbox is ready for processing, when it can be safely disposed\n/// of, etc.\n///\n/// The only current implementation of an [`OffchainInboxSync`] is [`sync_inbox`], which manages an inbox with\n/// expiration and finality-based eviction and automatic transaction context resolution.\npub type OffchainInboxSync = unconstrained fn(\n/* contract_address */AztecAddress, /* scope */ AztecAddress) -> EphemeralArray<OffchainMessageWithTx>;\n\n/// Delivers offchain messages to the given contract's offchain inbox for subsequent processing.\n///\n/// Offchain messages are transaction effects that are not broadcasted via onchain logs. Instead, the sender shares the\n/// message to the recipient through an external channel (e.g. a URL accessible by the recipient). The recipient then\n/// calls this function to hand the messages to the contract so they can be processed through the same mechanisms as\n/// onchain messages.\n///\n/// Messages are processed when their originating transaction is found onchain (providing the context needed to\n/// validate resulting notes and events).\n///\n/// Messages are eventually removed from the inbox: an unprocessed message once its TTL (`anchor_block_timestamp +\n/// MAX_MSG_TTL`) elapses, and a processed message once the block its transaction was found in finalizes.\n///\n/// Processing order is not guaranteed.\npub unconstrained fn receive(\n contract_address: AztecAddress,\n messages: BoundedVec<OffchainMessage, MAX_OFFCHAIN_MESSAGES_PER_RECEIVE_CALL>,\n) {\n // Offchain reception facts are scoped to the recipient. Note that because offchain messages have no integrity or\n // authenticity checks it is not possible to verify that this is indeed the intended recipient. In this case we're\n // assuming a cooperative environment, which is on par with other offchain delivery expectations.\n //\n // The sender-supplied anchor timestamp is the one field we bound: a message claiming to originate implausibly far\n // in our future (see MAX_ANCHOR_FUTURE_SKEW) cannot be genuine, and accepting it would let a malicious anchor evade\n // the TTL-based inbox eviction. We reject such a batch by panicking instead of silently dropping the message, so\n // the calling wallet can react to it (e.g. surface the error or distrust the sender).\n let now = UtilityContext::new().timestamp();\n messages.for_each(|msg| {\n assert(\n msg.anchor_block_timestamp <= now + MAX_ANCHOR_FUTURE_SKEW,\n \"offchain message anchor timestamp is implausibly far in the future\",\n );\n });\n\n messages.for_each(|msg| OffchainReception::init(contract_address, msg));\n\n // Clear cache for message recipients so the next sync runs.\n set_contract_sync_cache_invalid(contract_address, messages.map(|msg| msg.recipient));\n}\n\n/// Returns offchain-delivered messages to process during sync.\npub unconstrained fn sync_inbox(\n contract_address: AztecAddress,\n scope: AztecAddress,\n) -> EphemeralArray<OffchainMessageWithTx> {\n let active_receptions = OffchainReception::load_all(contract_address, scope);\n\n // Ask PXE to resolve each message's originating tx. We pass the tx hashes in reception order, so the resolved txs\n // come back aligned with the reception indices and can be matched back positionally.\n let resolved_txs = get_resolved_txs(active_receptions.map(|reception: OffchainReception| {\n reception.read_message().tx_hash.unwrap_or(0)\n }));\n\n let processable_messages: EphemeralArray<OffchainMessageWithTx> = EphemeralArray::empty();\n let now = UtilityContext::new().timestamp();\n\n active_receptions.for_each(|i, reception| {\n let maybe_message = reception.step(resolved_txs.get(i), now);\n if maybe_message.is_some() {\n processable_messages.push(maybe_message.unwrap());\n }\n });\n\n processable_messages\n}\n\n/// A message delivered via the `offchain_receive` utility function.\n#[derive(Serialize, Deserialize)]\npub struct OffchainMessage {\n /// The encrypted message payload.\n pub ciphertext: BoundedVec<Field, MESSAGE_CIPHERTEXT_LEN>,\n /// The intended recipient of the message.\n pub recipient: AztecAddress,\n /// The hash of the transaction that produced this message. `Option::none` indicates a tx-less message.\n pub tx_hash: Option<Field>,\n /// Anchor block timestamp at message emission.\n pub anchor_block_timestamp: u64,\n}\n\nmod test {\n use crate::{\n oracle::random::random,\n protocol::{address::AztecAddress, constants::MAX_TX_LIFETIME},\n test::helpers::test_environment::TestEnvironment,\n };\n use super::{MAX_OFFCHAIN_MESSAGES_PER_RECEIVE_CALL, OffchainMessage, receive, sync_inbox};\n use super::reception::{MAX_ANCHOR_FUTURE_SKEW, MAX_MSG_TTL, OffchainReception};\n\n unconstrained fn setup() -> (TestEnvironment, AztecAddress) {\n let mut env = TestEnvironment::new();\n let scope = env.create_light_account();\n (env, scope)\n }\n\n /// Creates an `OffchainMessage` with dummy ciphertext and the given scope as recipient.\n fn make_msg(recipient: AztecAddress, tx_hash: Option<Field>, anchor_block_timestamp: u64) -> OffchainMessage {\n OffchainMessage { ciphertext: BoundedVec::new(), recipient, tx_hash, anchor_block_timestamp }\n }\n\n /// Advances the TXE block timestamp by `offset` seconds and returns the resulting timestamp.\n unconstrained fn advance_by(env: TestEnvironment, offset: u64) -> u64 {\n env.advance_next_block_timestamp_by(offset);\n env.mine_block();\n env.last_block_timestamp()\n }\n\n #[test]\n unconstrained fn empty_inbox_returns_empty_result() {\n let (env, scope) = setup();\n env.utility_context(|context| {\n let address = context.this_address();\n let result = sync_inbox(address, scope);\n\n assert_eq(result.len(), 0);\n assert_eq(OffchainReception::load_all(address, scope).len(), 0);\n });\n }\n\n #[test]\n unconstrained fn multiple_messages_mixed_expiration() {\n let (env, scope) = setup();\n let anchor_ts = advance_by(env, 10);\n\n let expired_a_tx_hash = random();\n let survivor_tx_hash = random();\n\n let expired_a = make_msg(scope, Option::some(expired_a_tx_hash), 0);\n let survivor = make_msg(scope, Option::some(survivor_tx_hash), anchor_ts);\n let expired_b = make_msg(scope, Option::none(), 0);\n\n env.utility_context(|context| {\n let address = context.this_address();\n let mut msgs: BoundedVec<OffchainMessage, MAX_OFFCHAIN_MESSAGES_PER_RECEIVE_CALL> = BoundedVec::new();\n // Message 0: tx-bound, anchor=0 so it expires quickly.\n msgs.push(expired_a);\n // Message 1: tx-bound, anchor_ts is recent so it survives.\n msgs.push(survivor);\n // Message 2: tx-less, anchor=0 so it also expires.\n msgs.push(expired_b);\n receive(address, msgs);\n });\n\n // Advance past MAX_MSG_TTL for anchor=0, but not for anchor_ts.\n let _now = advance_by(env, MAX_MSG_TTL);\n\n env.utility_context(|context| {\n let address = context.this_address();\n let result = sync_inbox(address, scope);\n\n assert_eq(result.len(), 0); // all contexts are None\n assert(\n !OffchainReception::is_active(address, scope, expired_a),\n \"expired tx-bound reception should be terminated\",\n );\n assert(\n !OffchainReception::is_active(address, scope, expired_b),\n \"expired tx-less reception should be terminated\",\n );\n assert(OffchainReception::is_active(address, scope, survivor), \"survivor reception should stay active\");\n assert_eq(OffchainReception::load_all(address, scope).len(), 1);\n });\n }\n\n #[test]\n unconstrained fn accepts_messages_within_the_tolerated_future_skew() {\n let (env, scope) = setup();\n let now = advance_by(env, 10);\n\n // A present-dated anchor and a 24h-future one both fall within the tolerated skew. The latter models a genuine\n // message whose sender anchored ahead of our lagging PXE, and must still be accepted.\n let present = make_msg(scope, Option::some(random()), now);\n let lagged = make_msg(scope, Option::some(random()), now + MAX_TX_LIFETIME);\n\n env.utility_context(|context| {\n let address = context.this_address();\n receive(address, BoundedVec::from_array([present, lagged]));\n\n assert(OffchainReception::is_active(address, scope, present));\n assert(OffchainReception::is_active(address, scope, lagged));\n assert_eq(OffchainReception::load_all(address, scope).len(), 2);\n });\n }\n\n #[test(should_fail_with = \"offchain message anchor timestamp is implausibly far in the future\")]\n unconstrained fn rejects_batch_with_implausible_future_anchor() {\n let (env, scope) = setup();\n let now = advance_by(env, 10);\n\n // Beyond `now + MAX_ANCHOR_FUTURE_SKEW`: our view would trail the tip by more than a tx lifetime, so this\n // cannot be genuine. Reception panics so the wallet can react rather than accept it.\n let too_future = make_msg(\n scope,\n Option::some(random()),\n now + MAX_ANCHOR_FUTURE_SKEW + 7200,\n );\n\n env.utility_context(|context| { receive(context.this_address(), BoundedVec::from_array([too_future])); });\n }\n\n // -- Idempotent re-delivery (first-write-wins fact recording) ---------\n\n #[test]\n unconstrained fn redelivery_is_idempotent() {\n let (env, scope) = setup();\n let anchor_ts = advance_by(env, 10);\n let msg = make_msg(scope, Option::some(random()), anchor_ts);\n\n // First delivery, committed as its own job.\n env.utility_context(|context| { receive(context.this_address(), BoundedVec::from_array([msg])); });\n\n // Re-delivering the same content-addressed message must not panic and must not create a second reception.\n env.utility_context(|context| {\n let address = context.this_address();\n receive(address, BoundedVec::from_array([msg]));\n\n assert(OffchainReception::is_active(address, scope, msg), \"reception should be active\");\n assert_eq(OffchainReception::load_all(address, scope).len(), 1);\n });\n }\n\n #[test]\n unconstrained fn redelivery_after_processing_keeps_processed_guard() {\n let (env, scope) = setup();\n let known_tx_hash: Field = 1;\n let anchor_ts = advance_by(env, 10);\n let msg = make_msg(scope, Option::some(known_tx_hash), anchor_ts);\n\n env.utility_context(|context| { receive(context.this_address(), BoundedVec::from_array([msg])); });\n\n let _now = advance_by(env, 100);\n\n // First sync resolves the message and marks it as processed.\n env.utility_context(|context| {\n let address = context.this_address();\n assert_eq(sync_inbox(address, scope).len(), 1);\n assert(OffchainReception::is_processed(address, scope, msg), \"should be processed\");\n });\n\n // Re-deliver the same message. The next sync recognizes it as already processed and does not re-push it.\n env.utility_context(|context| {\n let address = context.this_address();\n receive(address, BoundedVec::from_array([msg]));\n\n assert(\n OffchainReception::is_processed(address, scope, msg),\n \"re-delivery must preserve the processed guard\",\n );\n assert_eq(sync_inbox(address, scope).len(), 0);\n });\n }\n}\n"
482
+ },
483
+ "166": {
484
+ "function_locations": [
485
+ {
486
+ "name": "OffchainReception::init",
487
+ "start": 9679
488
+ },
489
+ {
490
+ "name": "OffchainReception::load_all",
491
+ "start": 10197
492
+ },
493
+ {
494
+ "name": "OffchainReception::read_message",
495
+ "start": 10546
496
+ },
497
+ {
498
+ "name": "OffchainReception::id_for",
499
+ "start": 11247
500
+ },
501
+ {
502
+ "name": "OffchainReception::is_active",
503
+ "start": 11566
504
+ },
505
+ {
506
+ "name": "OffchainReception::step",
507
+ "start": 12221
508
+ },
509
+ {
510
+ "name": "OffchainReception::is_processed",
511
+ "start": 13826
512
+ },
513
+ {
514
+ "name": "OffchainReception::mark_processed",
515
+ "start": 14394
516
+ },
517
+ {
518
+ "name": "OffchainReception::terminate",
519
+ "start": 14962
520
+ },
521
+ {
522
+ "name": "to_payload",
523
+ "start": 15336
524
+ },
525
+ {
526
+ "name": "test::setup",
527
+ "start": 15893
528
+ },
529
+ {
530
+ "name": "test::make_msg",
531
+ "start": 16223
532
+ },
533
+ {
534
+ "name": "test::resolved_tx_at_block",
535
+ "start": 16507
536
+ },
537
+ {
538
+ "name": "test::resolved_tx",
539
+ "start": 16898
540
+ },
541
+ {
542
+ "name": "test::expired_reception_is_terminated",
543
+ "start": 17015
544
+ },
545
+ {
546
+ "name": "test::unresolved_reception_stays_active",
547
+ "start": 17697
548
+ },
549
+ {
550
+ "name": "test::resolved_reception_is_ready_to_process",
551
+ "start": 18492
552
+ },
553
+ {
554
+ "name": "test::already_processed_reception_is_not_re_pushed",
555
+ "start": 19538
556
+ },
557
+ {
558
+ "name": "test::processed_reception_terminates_once_its_origin_block_finalizes",
559
+ "start": 20912
560
+ },
561
+ {
562
+ "name": "test::unfinalized_processed_reception_survives_past_the_ttl",
563
+ "start": 22137
564
+ },
565
+ {
566
+ "name": "test::expired_reception_is_still_processed_when_its_tx_resolves",
567
+ "start": 23527
568
+ }
569
+ ],
570
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/messages/processing/offchain/reception.nr",
571
+ "source": "//! The state machine of a single offchain message reception process.\n//!\n//! Offchain processing needs to handle some complexity, including the possibility of reorgs reverting message effects,\n//! and the need to reprocess messages in that case. The state chart below summarizes the current behavior.\n//!\n//! ```text\n//! offchain_receive() (process starts)\n//! |\n//! v\n//! +-----------+ tx found onchain +-----------+\n//! ---- | | --------------------------> | |\n//! tx not found | | | | | discover notes,\n//! |--> | RECEIVED | | PROCESSED | ~~> events, etc\n//! | | <-------------------------- | |\n//! | | tx block re-orged | |\n//! +-----------+ +-----------+\n//! | |\n//! | TTL expired | tx block finalized\n//! v v\n//! +---------------------------------------------------------+\n//! | TERMINATED (process ends) |\n//! +---------------------------------------------------------+\n//! ```\n//!\n//! ## States\n//!\n//! - **Received**: the message is stored but its originating transaction has not been found onchain yet (or the\n//! message is tx-less; see below). While the reception process is in this state, it keeps looking for the\n// transaction onchain.\n//! - **Processed**: the message has been handed off for processing. If there weren't reorgs, reaching this state would\n//! be equivalent to terminating the reception process. Since reorgs are a possibility, this state is not terminal\n//! until the block the originating transaction was found in finalizes.\n//! - **Terminated**: nothing else can be done with the message, either because its originating transaction never\n//! appeared within the TTL, or because the block it was processed in has finalized. This is the terminal state of\n//! this process.\n//!\n//! ## Transitions (each evaluated by [`OffchainReception::step`])\n//!\n//! - **Received -> Processed**: the originating transaction is found onchain. The message (packaged with its\n//! transaction context) is queued to have its actual contents processed (which can lead for example to the discovery\n//! of notes and events).\n//! - **Processed -> Received**: the block where the message transaction was originally found is re-orged out.\n//! - **Received -> Terminated**: the message TTL has elapsed (see below), so the originating transaction can no longer\n//! appear and the message is no longer processable.\n//! - **Processed -> Terminated**: the block the originating transaction was found in has finalized, so the effects of\n//! its processing are permanent and reorg-proof.\n//!\n//! # Message reception lifecycle and the TTL\n//!\n//! A reception expires once `now > anchor_block_timestamp + MAX_MSG_TTL`, where `MAX_MSG_TTL = MAX_TX_LIFETIME + 2h`.\n//! A transaction anchored at a given block can only be mined within\n//! [`MAX_TX_LIFETIME`](crate::protocol::constants::MAX_TX_LIFETIME) of that block, so once that\n//! window (plus a safety margin of 2 hours) has elapsed the originating transaction can no longer appear, and it is\n//! safe to stop looking for it.\n//!\n//! The TTL only matters for unprocessed messages. Already-processed message receptions complete when the block that\n//! included the originating transaction finalizes, which is exactly when the processing becomes reorg-proof.\n//!\n//! # Current limitations, future plans\n//!\n//! - Tx-less messages never reach `Processed` and are only ever removed by expiry. This will be supported in the\n//! future.\n//!\n//! # Implementation\n//!\n//! [`OffchainReception::init`] creates a [fact collection](crate::facts::FactCollection) of type\n//! `OFFCHAIN_RECEPTION_TYPE_ID`. The fact collection is identified by a hash of the `OffchainMessage` it tracks, which\n//! makes duplicate calls to `init` idempotent.\n//!\n//! Upon reception, an `OFFCHAIN_MESSAGE_RECEIVED` [non-retractable fact](crate::facts::record_non_retractable_fact) is\n//! recorded. The fact's payload is the `OffchainMessage` itself, which persists it to be subsequently processed.\n//! A fact collection with just an `OFFCHAIN_MESSAGE_RECEIVED` fact represents an active reception process in the\n//! RECEIVED state from our state chart above.\n//!\n//! The message reception state machine is driven externally, advancing one step at a time each time\n//! [`OffchainReception::step`] is invoked. [`OffchainReception::step`] implements the rest of the reception state\n//! machine described above.\n//!\n//! When stepping, if the transaction to the message is found onchain, an `OFFCHAIN_MESSAGE_PROCESSED`\n//! [retractable fact](crate::facts::record_retractable_fact) associated to the block where the transaction was found is\n//! recorded.\n//! Note that since this fact is retractable, a reorg dropping said block would result in the fact being automatically\n//! removed by PXE, effectively pushing the reception process back to `RECEIVED` state.\n//!\n//! To determine in which state of the reception process we are we just analyze the recorded facts:\n//!\n//! - If there is an `OFFCHAIN_MESSAGE_PROCESSED` fact we are in PROCESSED state. Once that fact's origin block has\n//! finalized the processing is reorg-proof, so the [fact collection](crate::facts::FactCollection) can (and should)\n//! be deleted; until then there is nothing to do.\n//! - If there is only an `OFFCHAIN_MESSAGE_RECEIVED` fact we are in RECEIVED state, so we check if the message\n//! transaction is now available onchain, and if so, exercise the RECEIVED->PROCESSED transition. Otherwise, once the\n//! TTL has elapsed the originating transaction can no longer appear and the collection can (and should) be deleted.\n//!\n//! The PROCESSED->RECEIVED transition is transparently handled by PXE: if a re-org caused the message transaction to\n//! fall off the chain, the `OFFCHAIN_MESSAGE_PROCESSED` fact disappears, taking us back to the RECEIVED state.\n\nuse crate::{\n ephemeral::EphemeralArray,\n facts::{\n delete_fact_collection, Fact, FactCollection, get_fact_collection, get_fact_collections_by_type, OriginBlock,\n record_non_retractable_fact, record_retractable_fact,\n },\n messages::processing::OffchainMessageWithTx,\n oracle::tx_resolution::ResolvedTx,\n protocol::{\n address::AztecAddress,\n constants::MAX_TX_LIFETIME,\n hash::{poseidon2_hash, sha256_to_field},\n traits::{Deserialize, Serialize},\n },\n};\nuse super::OffchainMessage;\n\n/// Maximum time-to-live for a tx-bound offchain message.\n///\n/// After `anchor_block_timestamp + MAX_MSG_TTL`, the message is evicted from the inbox.\n/// (7200 == 2 hours)\npub(crate) global MAX_MSG_TTL: u64 = MAX_TX_LIFETIME + 7200;\n\n/// Maximum amount by which a received message's `anchor_block_timestamp` may exceed our current timestamp.\n///\n/// A message's anchor is the timestamp of the block the sender anchored its originating tx to, so for a genuine\n/// message it is at or before our own anchor timestamp. Our PXE may lag the chain tip though, which can make a\n/// legitimate anchor appear to be in our future, so we tolerate a forward skew of `MAX_TX_LIFETIME` (the longest a tx\n/// can wait to be mined after its anchor) plus a 2h margin. A larger skew would mean our view trails the tip by more\n/// than a tx lifetime -- so far behind that we could not even build a tx that wouldn't be immediately expired -- so\n/// such a message cannot be genuine and is rejected on reception. Bounding the anchor this way also keeps accepted\n/// values near the present, which prevents the `anchor_block_timestamp + MAX_MSG_TTL` eviction check from overflowing.\n/// (7200 == 2 hours)\npub(crate) global MAX_ANCHOR_FUTURE_SKEW: u64 = MAX_TX_LIFETIME + 7200;\n\n/// Fact type id of the fact that stores the offchain message body inside a reception collection.\nglobal OFFCHAIN_MESSAGE_RECEIVED: Field = sha256_to_field(\"AZTEC_NR::OFFCHAIN_MESSAGE_RECEIVED\".as_bytes());\n\n/// Fact type id to mark an offchain message as processed.\n///\n/// A reception is in \"processed state\" exactly when its collection carries a fact of this type.\npub(crate) global OFFCHAIN_MESSAGE_PROCESSED: Field =\n sha256_to_field(\"AZTEC_NR::OFFCHAIN_MESSAGE_PROCESSED\".as_bytes());\n\n/// Fact-collection type id shared by every offchain message reception in the [fact store](crate::facts).\npub(crate) global OFFCHAIN_RECEPTION_TYPE_ID: Field =\n sha256_to_field(\"AZTEC_NR::OFFCHAIN_RECEPTION_TYPE_ID\".as_bytes());\n\n/// A single offchain message reception machine, backed by a [`FactCollection`](crate::facts::FactCollection).\n///\n/// Wraps the fact collection that tracks one message's progress through the reception state machine (see the\n/// [module documentation](super)); the [`OffchainMessage`] it carries is decoded on demand.\n#[derive(Deserialize, Serialize)]\npub(crate) struct OffchainReception {\n collection: FactCollection,\n}\n\nimpl OffchainReception {\n /// Initializes a new reception for a freshly received message, in the `Received` state.\n ///\n /// Re-initializing the same message is a no-op, which makes redelivery idempotent.\n pub(crate) unconstrained fn init(contract_address: AztecAddress, message: OffchainMessage) {\n record_non_retractable_fact(\n contract_address,\n message.recipient,\n OFFCHAIN_RECEPTION_TYPE_ID,\n Self::id_for(message),\n OFFCHAIN_MESSAGE_RECEIVED,\n to_payload(message),\n );\n }\n\n /// Loads every active reception for the given contract and scope, decoding each message body.\n pub(crate) unconstrained fn load_all(\n contract_address: AztecAddress,\n scope: AztecAddress,\n ) -> EphemeralArray<OffchainReception> {\n get_fact_collections_by_type(contract_address, scope, OFFCHAIN_RECEPTION_TYPE_ID)\n .map(|collection: FactCollection| OffchainReception { collection })\n }\n\n /// Reads and returns the message this reception carries, decoding it from its fact collection.\n pub(crate) unconstrained fn read_message(self) -> OffchainMessage {\n let message_fact = self.collection.facts.find(|f: Fact| f.fact_type_id == OFFCHAIN_MESSAGE_RECEIVED).unwrap();\n let n = <OffchainMessage as Deserialize>::N;\n let mut fields = [0; <OffchainMessage as Deserialize>::N];\n for i in 0..n {\n fields[i] = message_fact.payload.get(i);\n }\n Deserialize::deserialize(fields)\n }\n\n /// Computes the fact-collection id that identifies a message's reception machine in the [fact store](crate::facts).\n ///\n /// The id is a hash of the message, which makes duplicate receptions of the same message collapse onto a single\n /// reception.\n pub(crate) fn id_for(message: OffchainMessage) -> Field {\n poseidon2_hash(message.serialize())\n }\n\n /// Returns `true` if a reception for `message` is currently active for the given contract and scope.\n pub(crate) unconstrained fn is_active(\n contract_address: AztecAddress,\n scope: AztecAddress,\n message: OffchainMessage,\n ) -> bool {\n get_fact_collection(\n contract_address,\n scope,\n OFFCHAIN_RECEPTION_TYPE_ID,\n Self::id_for(message),\n )\n .is_some()\n }\n\n /// Advances this reception by one step of its state machine. See the [module documentation](super) for the\n /// states, transitions, and expiry rules.\n ///\n /// Returns `Some` with the message and its resolved context when this step determines the message is ready to be\n /// processed.\n pub(crate) unconstrained fn step(\n self,\n maybe_resolved_tx: Option<ResolvedTx>,\n now: u64,\n ) -> Option<OffchainMessageWithTx> {\n let message = self.read_message();\n let processed_fact = self.collection.facts.find(|f: Fact| f.fact_type_id == OFFCHAIN_MESSAGE_PROCESSED);\n\n if processed_fact.is_none() & maybe_resolved_tx.is_some() {\n // Received -> Processed: the originating tx is onchain.\n let resolved = maybe_resolved_tx.unwrap();\n self.mark_processed(resolved.block_number, resolved.block_hash);\n Option::some(\n OffchainMessageWithTx { message_ciphertext: message.ciphertext, resolved_tx: resolved },\n )\n } else if processed_fact.is_some() {\n if processed_fact.unwrap().origin_block.unwrap().block_state.is_finalized() {\n // Processed -> Terminated: once the marker's origin block finalizes, the processing is reorg-proof and\n // the reception is complete. Until then we wait: a reorg dropping that block removes the retractable\n // marker and PXE pushes us back to Received.\n self.terminate();\n }\n Option::none()\n } else {\n // Received -> Terminated: the TTL caps how long we keep looking for the originating tx.\n if now > message.anchor_block_timestamp + MAX_MSG_TTL {\n self.terminate();\n }\n Option::none()\n }\n }\n\n /// Returns `true` if the reception for `message` has been marked processed.\n pub(crate) unconstrained fn is_processed(\n contract_address: AztecAddress,\n scope: AztecAddress,\n message: OffchainMessage,\n ) -> bool {\n let maybe_collection = get_fact_collection(\n contract_address,\n scope,\n OFFCHAIN_RECEPTION_TYPE_ID,\n Self::id_for(message),\n );\n if maybe_collection.is_some() {\n maybe_collection.unwrap().facts.any(|f: Fact| f.fact_type_id == OFFCHAIN_MESSAGE_PROCESSED)\n } else {\n false\n }\n }\n\n /// Records the retractable processed marker for this reception, originated at the resolved block.\n unconstrained fn mark_processed(self, block_number: u32, block_hash: Field) {\n let empty_payload: EphemeralArray<Field> = EphemeralArray::empty();\n record_retractable_fact(\n self.collection.contract_address,\n self.collection.scope,\n self.collection.fact_collection_type_id,\n self.collection.fact_collection_id,\n OFFCHAIN_MESSAGE_PROCESSED,\n empty_payload,\n OriginBlock { block_number, block_hash },\n );\n }\n\n /// Terminates this reception by deleting its [fact collection](crate::facts::FactCollection).\n unconstrained fn terminate(self) {\n delete_fact_collection(\n self.collection.contract_address,\n self.collection.scope,\n self.collection.fact_collection_type_id,\n self.collection.fact_collection_id,\n );\n }\n}\n\n/// Serializes an [`OffchainMessage`] into a fact payload.\nunconstrained fn to_payload(message: OffchainMessage) -> EphemeralArray<Field> {\n let fields = message.serialize();\n let payload: EphemeralArray<Field> = EphemeralArray::empty();\n for i in 0..fields.len() {\n payload.push(fields[i]);\n }\n payload\n}\n\nmod test {\n use crate::{\n messages::processing::offchain::OffchainMessage,\n oracle::{random::random, tx_resolution::ResolvedTx},\n protocol::address::AztecAddress,\n test::helpers::test_environment::TestEnvironment,\n };\n use super::{MAX_MSG_TTL, OffchainReception};\n\n unconstrained fn setup() -> (TestEnvironment, AztecAddress) {\n let mut env = TestEnvironment::new();\n let scope = env.create_light_account();\n (env, scope)\n }\n\n /// Creates an `OffchainMessage` with dummy ciphertext and the given scope as recipient.\n fn make_msg(recipient: AztecAddress, tx_hash: Option<Field>, anchor_block_timestamp: u64) -> OffchainMessage {\n OffchainMessage { ciphertext: BoundedVec::new(), recipient, tx_hash, anchor_block_timestamp }\n }\n\n /// Builds the resolved-tx context PXE would return for `tx_hash`, found in `block_number`.\n fn resolved_tx_at_block(tx_hash: Field, block_number: u32) -> ResolvedTx {\n ResolvedTx {\n tx_hash,\n unique_note_hashes_in_tx: BoundedVec::new(),\n first_nullifier_in_tx: 0,\n block_number,\n block_hash: 0,\n }\n }\n\n /// Builds a resolved-tx context found in a low block, which TXE (proven == finalized == latest) reports as\n /// `Finalized`.\n fn resolved_tx(tx_hash: Field) -> ResolvedTx {\n resolved_tx_at_block(tx_hash, 1)\n }\n\n #[test]\n unconstrained fn expired_reception_is_terminated() {\n let (env, scope) = setup();\n let msg = make_msg(scope, Option::some(random()), 0);\n\n env.utility_context(|context| {\n let address = context.this_address();\n OffchainReception::init(address, msg);\n let reception = OffchainReception::load_all(address, scope).get(0);\n\n // Past the TTL with no resolved tx: the reception is terminated.\n assert(reception.step(Option::none(), MAX_MSG_TTL + 1).is_none());\n assert(!OffchainReception::is_active(address, scope, msg), \"expired reception should be terminated\");\n });\n }\n\n #[test]\n unconstrained fn unresolved_reception_stays_active() {\n let (env, scope) = setup();\n let msg = make_msg(scope, Option::some(random()), 0);\n\n env.utility_context(|context| {\n let address = context.this_address();\n OffchainReception::init(address, msg);\n let reception = OffchainReception::load_all(address, scope).get(0);\n\n // Within the TTL with no resolved tx: nothing to process, the reception stays.\n assert(reception.step(Option::none(), 100).is_none());\n assert(OffchainReception::is_active(address, scope, msg), \"unresolved reception should stay active\");\n assert(!OffchainReception::is_processed(address, scope, msg), \"should still be unprocessed\");\n });\n }\n\n #[test]\n unconstrained fn resolved_reception_is_ready_to_process() {\n let (env, scope) = setup();\n let tx_hash = random();\n let msg = make_msg(scope, Option::some(tx_hash), 0);\n\n env.utility_context(|context| {\n let address = context.this_address();\n OffchainReception::init(address, msg);\n let reception = OffchainReception::load_all(address, scope).get(0);\n\n // A resolved tx within the TTL: the message is handed off with its tx context attached.\n let processable = reception.step(Option::some(resolved_tx(tx_hash)), 100);\n assert(processable.is_some());\n assert_eq(processable.unwrap().resolved_tx.tx_hash, tx_hash);\n\n // It stays active for reorg safety and is now marked processed.\n assert(OffchainReception::is_active(address, scope, msg), \"processed reception should stay active\");\n assert(OffchainReception::is_processed(address, scope, msg), \"should be processed\");\n });\n }\n\n #[test]\n unconstrained fn already_processed_reception_is_not_re_pushed() {\n let (env, scope) = setup();\n let tx_hash = random();\n let msg = make_msg(scope, Option::some(tx_hash), 0);\n // A future origin block stays unfinalized, so the reception lingers in Processed across steps.\n let future_block = env.last_block_number() + 100;\n\n env.utility_context(|context| {\n let address = context.this_address();\n OffchainReception::init(address, msg);\n\n // First step processes the message.\n let reception = OffchainReception::load_all(address, scope).get(0);\n assert(reception.step(Option::some(resolved_tx_at_block(tx_hash, future_block)), 100).is_some());\n assert(OffchainReception::is_processed(address, scope, msg), \"should be processed\");\n\n // Second step (still resolved, not finalized) recognizes it as processed and does not re-push it.\n let reloaded = OffchainReception::load_all(address, scope).get(0);\n assert(\n reloaded.step(Option::some(resolved_tx_at_block(tx_hash, future_block)), 100).is_none(),\n \"already processed\",\n );\n assert(OffchainReception::is_active(address, scope, msg), \"processed reception should still be active\");\n });\n }\n\n #[test]\n unconstrained fn processed_reception_terminates_once_its_origin_block_finalizes() {\n let (env, scope) = setup();\n let tx_hash = random();\n let msg = make_msg(scope, Option::some(tx_hash), 0);\n\n env.utility_context(|context| {\n let address = context.this_address();\n OffchainReception::init(address, msg);\n\n // Process the message against a finalized block.\n let reception = OffchainReception::load_all(address, scope).get(0);\n assert(reception.step(Option::some(resolved_tx(tx_hash)), 100).is_some());\n assert(OffchainReception::is_processed(address, scope, msg), \"should be processed\");\n\n // Next step, still well within the TTL: a finalized origin block makes the processing reorg-proof, so the\n // reception terminates regardless of the TTL.\n let reloaded = OffchainReception::load_all(address, scope).get(0);\n assert(reloaded.step(Option::some(resolved_tx(tx_hash)), 100).is_none());\n assert(\n !OffchainReception::is_active(address, scope, msg),\n \"finalized processed reception should be terminated\",\n );\n });\n }\n\n #[test]\n unconstrained fn unfinalized_processed_reception_survives_past_the_ttl() {\n let (env, scope) = setup();\n let tx_hash = random();\n let msg = make_msg(scope, Option::some(tx_hash), 0);\n // A future origin block never finalizes here, so the reception must not be terminated by the TTL.\n let future_block = env.last_block_number() + 100;\n\n env.utility_context(|context| {\n let address = context.this_address();\n OffchainReception::init(address, msg);\n\n let reception = OffchainReception::load_all(address, scope).get(0);\n assert(reception.step(Option::some(resolved_tx_at_block(tx_hash, future_block)), 100).is_some());\n assert(OffchainReception::is_processed(address, scope, msg), \"should be processed\");\n\n // Past the TTL, but the origin block has not finalized: the reception stays active. The TTL no longer\n // governs an already-processed reception.\n let reloaded = OffchainReception::load_all(address, scope).get(0);\n assert(reloaded.step(Option::some(resolved_tx_at_block(tx_hash, future_block)), MAX_MSG_TTL + 1).is_none());\n assert(\n OffchainReception::is_active(address, scope, msg),\n \"unfinalized processed reception should survive past the TTL\",\n );\n });\n }\n\n #[test]\n unconstrained fn expired_reception_is_still_processed_when_its_tx_resolves() {\n let (env, scope) = setup();\n let tx_hash = random();\n let msg = make_msg(scope, Option::some(tx_hash), 0);\n\n env.utility_context(|context| {\n let address = context.this_address();\n OffchainReception::init(address, msg);\n\n // Even past the TTL, a freshly resolved tx is still handed off: expiry only caps the search for the\n // originating tx, it does not pre-empt processing once that tx is found.\n let reception = OffchainReception::load_all(address, scope).get(0);\n assert(reception.step(Option::some(resolved_tx(tx_hash)), MAX_MSG_TTL + 1).is_some());\n assert(OffchainReception::is_processed(address, scope, msg), \"should be processed\");\n assert(OffchainReception::is_active(address, scope, msg), \"just-processed reception should stay active\");\n });\n }\n}\n"
572
+ },
573
+ "17": {
574
+ "function_locations": [
575
+ {
576
+ "name": "sha256_compression",
577
+ "start": 572
578
+ },
579
+ {
580
+ "name": "keccakf1600",
581
+ "start": 707
582
+ },
583
+ {
584
+ "name": "blake2s",
585
+ "start": 852
586
+ },
587
+ {
588
+ "name": "blake3",
589
+ "start": 950
590
+ },
591
+ {
592
+ "name": "__blake3",
593
+ "start": 1437
594
+ },
595
+ {
596
+ "name": "pedersen_commitment",
597
+ "start": 1555
598
+ },
599
+ {
600
+ "name": "pedersen_commitment_with_separator",
601
+ "start": 1784
602
+ },
603
+ {
604
+ "name": "pedersen_hash",
605
+ "start": 2188
606
+ },
607
+ {
608
+ "name": "pedersen_hash_with_separator",
609
+ "start": 2345
610
+ },
611
+ {
612
+ "name": "derive_generators",
613
+ "start": 3339
614
+ },
615
+ {
616
+ "name": "__derive_generators",
617
+ "start": 3698
618
+ },
619
+ {
620
+ "name": "poseidon2_permutation",
621
+ "start": 3776
622
+ },
623
+ {
624
+ "name": "poseidon2_permutation_internal",
625
+ "start": 4132
626
+ },
627
+ {
628
+ "name": "poseidon2_config_state_size",
629
+ "start": 4225
630
+ },
631
+ {
632
+ "name": "derive_hash",
633
+ "start": 4536
634
+ },
635
+ {
636
+ "name": "Hasher::finish_ref",
637
+ "start": 5327
638
+ },
639
+ {
640
+ "name": "<impl BuildHasher for BuildHasherDefault<H>>::build_hasher",
641
+ "start": 5761
642
+ },
643
+ {
644
+ "name": "<impl Default for BuildHasherDefault<H>>::default",
645
+ "start": 5893
646
+ },
647
+ {
648
+ "name": "<impl Hash for Field>::hash",
649
+ "start": 6025
650
+ },
651
+ {
652
+ "name": "<impl Hash for u8>::hash",
653
+ "start": 6155
654
+ },
655
+ {
656
+ "name": "<impl Hash for u16>::hash",
657
+ "start": 6295
658
+ },
659
+ {
660
+ "name": "<impl Hash for u32>::hash",
661
+ "start": 6435
662
+ },
663
+ {
664
+ "name": "<impl Hash for u64>::hash",
665
+ "start": 6575
666
+ },
667
+ {
668
+ "name": "<impl Hash for u128>::hash",
669
+ "start": 6716
670
+ },
671
+ {
672
+ "name": "<impl Hash for i8>::hash",
673
+ "start": 6855
674
+ },
675
+ {
676
+ "name": "<impl Hash for i16>::hash",
677
+ "start": 7001
678
+ },
679
+ {
680
+ "name": "<impl Hash for i32>::hash",
681
+ "start": 7148
682
+ },
683
+ {
684
+ "name": "<impl Hash for i64>::hash",
685
+ "start": 7295
686
+ },
687
+ {
688
+ "name": "<impl Hash for bool>::hash",
689
+ "start": 7443
690
+ },
691
+ {
692
+ "name": "<impl Hash for ()>::hash",
693
+ "start": 7590
694
+ },
695
+ {
696
+ "name": "<impl Hash for [T; N]>::hash",
697
+ "start": 7722
698
+ },
699
+ {
700
+ "name": "<impl Hash for [T]>::hash",
701
+ "start": 7911
702
+ },
703
+ {
704
+ "name": "<impl Hash for (A,)>::hash",
705
+ "start": 8133
706
+ },
707
+ {
708
+ "name": "<impl Hash for (A, B)>::hash",
709
+ "start": 8302
710
+ },
711
+ {
712
+ "name": "<impl Hash for (A, B, C)>::hash",
713
+ "start": 8518
714
+ },
715
+ {
716
+ "name": "<impl Hash for (A, B, C, D)>::hash",
717
+ "start": 8781
718
+ },
719
+ {
720
+ "name": "<impl Hash for (A, B, C, D, E)>::hash",
721
+ "start": 9091
722
+ },
723
+ {
724
+ "name": "<impl Hash for (A, B, C, D, E, F)>::hash",
725
+ "start": 9448
726
+ },
727
+ {
728
+ "name": "<impl Hash for (A, B, C, D, E, F, G)>::hash",
729
+ "start": 9852
730
+ },
731
+ {
732
+ "name": "<impl Hash for (A, B, C, D, E, F, G, H_)>::hash",
733
+ "start": 10306
734
+ },
735
+ {
736
+ "name": "<impl Hash for (A, B, C, D, E, F, G, H_, I)>::hash",
737
+ "start": 10807
738
+ },
739
+ {
740
+ "name": "<impl Hash for (A, B, C, D, E, F, G, H_, I, J)>::hash",
741
+ "start": 11355
742
+ },
743
+ {
744
+ "name": "<impl Hash for (A, B, C, D, E, F, G, H_, I, J, K)>::hash",
745
+ "start": 11950
746
+ },
747
+ {
748
+ "name": "<impl Hash for (A, B, C, D, E, F, G, H_, I, J, K, L)>::hash",
749
+ "start": 12593
750
+ },
751
+ {
752
+ "name": "assert_pedersen",
753
+ "start": 13187
754
+ }
755
+ ],
756
+ "path": "std/hash/mod.nr",
757
+ "source": "// Exposed only for usage in `std::meta`\npub(crate) mod poseidon2;\n\nuse crate::default::Default;\nuse crate::embedded_curve_ops::{\n EmbeddedCurvePoint, EmbeddedCurveScalar, multi_scalar_mul, multi_scalar_mul_array_return,\n};\nuse crate::meta::derive_via;\nuse crate::static_assert;\n\n/// The size of the state accepted by the backend in `poseidon2_permutation`.\nglobal POSEIDON2_CONFIG_STATE_SIZE: u32 = poseidon2_config_state_size();\n\n#[foreign(sha256_compression)]\n// docs:start:sha256_compression\npub fn sha256_compression(input: [u32; 16], state: [u32; 8]) -> [u32; 8] {}\n// docs:end:sha256_compression\n\n#[foreign(keccakf1600)]\n// docs:start:keccakf1600\npub fn keccakf1600(input: [u64; 25]) -> [u64; 25] {}\n// docs:end:keccakf1600\n\n#[foreign(blake2s)]\n// docs:start:blake2s\npub fn blake2s<let N: u32>(input: [u8; N]) -> [u8; 32]\n// docs:end:blake2s\n{}\n\n// docs:start:blake3\npub fn blake3<let N: u32>(input: [u8; N]) -> [u8; 32]\n// docs:end:blake3\n{\n if crate::runtime::is_unconstrained() {\n // Temporary measure while Barretenberg is main proving system.\n // Please open an issue if you're working on another proving system and running into problems due to this.\n crate::static_assert(\n N <= 1024,\n \"Barretenberg cannot prove blake3 hashes with inputs larger than 1024 bytes\",\n );\n }\n __blake3(input)\n}\n\n#[foreign(blake3)]\nfn __blake3<let N: u32>(input: [u8; N]) -> [u8; 32] {}\n\n// docs:start:pedersen_commitment\npub fn pedersen_commitment<let N: u32>(input: [Field; N]) -> EmbeddedCurvePoint {\n // docs:end:pedersen_commitment\n pedersen_commitment_with_separator(input, 0)\n}\n\n#[inline_always]\npub fn pedersen_commitment_with_separator<let N: u32>(\n input: [Field; N],\n separator: u32,\n) -> EmbeddedCurvePoint {\n let mut points = [EmbeddedCurveScalar { lo: 0, hi: 0 }; N];\n for i in 0..N {\n points[i] = EmbeddedCurveScalar::from_field(input[i]);\n }\n let generators = derive_generators(\"DEFAULT_DOMAIN_SEPARATOR\".as_bytes(), separator);\n multi_scalar_mul(generators, points)\n}\n\n// docs:start:pedersen_hash\npub fn pedersen_hash<let N: u32>(input: [Field; N]) -> Field\n// docs:end:pedersen_hash\n{\n pedersen_hash_with_separator(input, 0)\n}\n\n#[no_predicates]\npub fn pedersen_hash_with_separator<let N: u32>(input: [Field; N], separator: u32) -> Field {\n let mut scalars: [EmbeddedCurveScalar; N + 1] = [EmbeddedCurveScalar { lo: 0, hi: 0 }; N + 1];\n let mut generators: [EmbeddedCurvePoint; N + 1] =\n [EmbeddedCurvePoint::point_at_infinity(); N + 1];\n crate::assert_constant(separator);\n let domain_generators: [EmbeddedCurvePoint; N] =\n derive_generators(\"DEFAULT_DOMAIN_SEPARATOR\".as_bytes(), separator);\n\n for i in 0..N {\n scalars[i] = EmbeddedCurveScalar::from_field(input[i]);\n generators[i] = domain_generators[i];\n }\n scalars[N] = EmbeddedCurveScalar { lo: N as Field, hi: 0 as Field };\n\n let length_generator: [EmbeddedCurvePoint; 1] =\n derive_generators(\"pedersen_hash_length\".as_bytes(), 0);\n generators[N] = length_generator[0];\n multi_scalar_mul_array_return(generators, scalars, true)[0].x\n}\n\n#[field(bn254)]\n#[inline_always]\npub fn derive_generators<let N: u32, let M: u32>(\n domain_separator_bytes: [u8; M],\n starting_index: u32,\n) -> [EmbeddedCurvePoint; N] {\n crate::assert_constant(domain_separator_bytes);\n crate::assert_constant(starting_index);\n __derive_generators(domain_separator_bytes, starting_index)\n}\n\n#[builtin(derive_pedersen_generators)]\n#[field(bn254)]\nfn __derive_generators<let N: u32, let M: u32>(\n domain_separator_bytes: [u8; M],\n starting_index: u32,\n) -> [EmbeddedCurvePoint; N] {}\n\npub fn poseidon2_permutation<let N: u32>(input: [Field; N]) -> [Field; N] {\n static_assert(\n N == POSEIDON2_CONFIG_STATE_SIZE,\n f\"the input length must equal the state size in the Poseidon2 config; expected {POSEIDON2_CONFIG_STATE_SIZE}, got {N}\",\n );\n poseidon2_permutation_internal(input)\n}\n\n#[foreign(poseidon2_permutation)]\nfn poseidon2_permutation_internal<let N: u32>(input: [Field; N]) -> [Field; N] {}\n\n#[foreign(poseidon2_config_state_size)]\ncomptime fn poseidon2_config_state_size() -> u32 {}\n\n// Generic hashing support.\n// Partially ported and impacted by rust.\n\n// Hash trait shall be implemented per type.\n#[derive_via(derive_hash)]\npub trait Hash {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher;\n}\n\n// docs:start:derive_hash\ncomptime fn derive_hash(s: TypeDefinition) -> Quoted {\n let name = quote { $crate::hash::Hash };\n let signature = quote { fn hash<H>(_self: Self, _state: &mut H) where H: $crate::hash::Hasher };\n let for_each_field = |name| quote { _self.$name.hash(_state); };\n crate::meta::make_trait_impl(\n s,\n name,\n signature,\n for_each_field,\n quote {},\n |fields| fields,\n )\n}\n// docs:end:derive_hash\n\n// Hasher trait shall be implemented by algorithms to provide hash-agnostic means.\n// TODO: consider making the types generic here ([u8], [Field], etc.)\npub trait Hasher {\n fn finish(self) -> Field;\n\n /// Returns the hash value without consuming the hasher.\n /// Override this for more efficient implementations that avoid copying.\n /// TODO: deprecate finish() and replace it\n fn finish_ref(&self) -> Field {\n (*self).finish()\n }\n\n fn write(&mut self, input: Field);\n}\n\n// BuildHasher is a factory trait, responsible for production of specific Hasher.\npub trait BuildHasher {\n type H: Hasher;\n\n fn build_hasher(self) -> H;\n}\n\npub struct BuildHasherDefault<H>;\n\nimpl<H> BuildHasher for BuildHasherDefault<H>\nwhere\n H: Hasher + Default,\n{\n type H = H;\n\n fn build_hasher(_self: Self) -> H {\n H::default()\n }\n}\n\nimpl<H> Default for BuildHasherDefault<H>\nwhere\n H: Hasher + Default,\n{\n fn default() -> Self {\n BuildHasherDefault {}\n }\n}\n\nimpl Hash for Field {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self);\n }\n}\n\nimpl Hash for u8 {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as Field);\n }\n}\n\nimpl Hash for u16 {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as Field);\n }\n}\n\nimpl Hash for u32 {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as Field);\n }\n}\n\nimpl Hash for u64 {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as Field);\n }\n}\n\nimpl Hash for u128 {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as Field);\n }\n}\n\nimpl Hash for i8 {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as u8 as Field);\n }\n}\n\nimpl Hash for i16 {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as u16 as Field);\n }\n}\n\nimpl Hash for i32 {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as u32 as Field);\n }\n}\n\nimpl Hash for i64 {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as u64 as Field);\n }\n}\n\nimpl Hash for bool {\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n H::write(state, self as Field);\n }\n}\n\nimpl Hash for () {\n fn hash<H>(_self: Self, _state: &mut H)\n where\n H: Hasher,\n {}\n}\n\nimpl<T, let N: u32> Hash for [T; N]\nwhere\n T: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n for elem in self {\n elem.hash(state);\n }\n }\n}\n\nimpl<T> Hash for [T]\nwhere\n T: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.len().hash(state);\n for elem in self {\n elem.hash(state);\n }\n }\n}\n\nimpl<A> Hash for (A,)\nwhere\n A: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n }\n}\n\nimpl<A, B> Hash for (A, B)\nwhere\n A: Hash,\n B: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n }\n}\n\nimpl<A, B, C> Hash for (A, B, C)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n }\n}\n\nimpl<A, B, C, D> Hash for (A, B, C, D)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n D: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n self.3.hash(state);\n }\n}\n\nimpl<A, B, C, D, E> Hash for (A, B, C, D, E)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n D: Hash,\n E: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n self.3.hash(state);\n self.4.hash(state);\n }\n}\n\nimpl<A, B, C, D, E, F> Hash for (A, B, C, D, E, F)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n D: Hash,\n E: Hash,\n F: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n self.3.hash(state);\n self.4.hash(state);\n self.5.hash(state);\n }\n}\n\nimpl<A, B, C, D, E, F, G> Hash for (A, B, C, D, E, F, G)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n D: Hash,\n E: Hash,\n F: Hash,\n G: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n self.3.hash(state);\n self.4.hash(state);\n self.5.hash(state);\n self.6.hash(state);\n }\n}\n\nimpl<A, B, C, D, E, F, G, H_> Hash for (A, B, C, D, E, F, G, H_)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n D: Hash,\n E: Hash,\n F: Hash,\n G: Hash,\n H_: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n self.3.hash(state);\n self.4.hash(state);\n self.5.hash(state);\n self.6.hash(state);\n self.7.hash(state);\n }\n}\n\nimpl<A, B, C, D, E, F, G, H_, I> Hash for (A, B, C, D, E, F, G, H_, I)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n D: Hash,\n E: Hash,\n F: Hash,\n G: Hash,\n H_: Hash,\n I: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n self.3.hash(state);\n self.4.hash(state);\n self.5.hash(state);\n self.6.hash(state);\n self.7.hash(state);\n self.8.hash(state);\n }\n}\n\nimpl<A, B, C, D, E, F, G, H_, I, J> Hash for (A, B, C, D, E, F, G, H_, I, J)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n D: Hash,\n E: Hash,\n F: Hash,\n G: Hash,\n H_: Hash,\n I: Hash,\n J: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n self.3.hash(state);\n self.4.hash(state);\n self.5.hash(state);\n self.6.hash(state);\n self.7.hash(state);\n self.8.hash(state);\n self.9.hash(state);\n }\n}\n\nimpl<A, B, C, D, E, F, G, H_, I, J, K> Hash for (A, B, C, D, E, F, G, H_, I, J, K)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n D: Hash,\n E: Hash,\n F: Hash,\n G: Hash,\n H_: Hash,\n I: Hash,\n J: Hash,\n K: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n self.3.hash(state);\n self.4.hash(state);\n self.5.hash(state);\n self.6.hash(state);\n self.7.hash(state);\n self.8.hash(state);\n self.9.hash(state);\n self.10.hash(state);\n }\n}\n\nimpl<A, B, C, D, E, F, G, H_, I, J, K, L> Hash for (A, B, C, D, E, F, G, H_, I, J, K, L)\nwhere\n A: Hash,\n B: Hash,\n C: Hash,\n D: Hash,\n E: Hash,\n F: Hash,\n G: Hash,\n H_: Hash,\n I: Hash,\n J: Hash,\n K: Hash,\n L: Hash,\n{\n fn hash<H>(self, state: &mut H)\n where\n H: Hasher,\n {\n self.0.hash(state);\n self.1.hash(state);\n self.2.hash(state);\n self.3.hash(state);\n self.4.hash(state);\n self.5.hash(state);\n self.6.hash(state);\n self.7.hash(state);\n self.8.hash(state);\n self.9.hash(state);\n self.10.hash(state);\n self.11.hash(state);\n }\n}\n\n// Some test vectors for Pedersen hash and Pedersen Commitment.\n// They have been generated using the same functions so the tests are for now useless\n// but they will be useful when we switch to Noir implementation.\n#[test]\nfn assert_pedersen() {\n assert_eq(\n pedersen_hash_with_separator([1], 1),\n 0x1b3f4b1a83092a13d8d1a59f7acb62aba15e7002f4440f2275edb99ebbc2305f,\n );\n assert_eq(\n pedersen_commitment_with_separator([1], 1),\n EmbeddedCurvePoint {\n x: 0x054aa86a73cb8a34525e5bbed6e43ba1198e860f5f3950268f71df4591bde402,\n y: 0x209dcfbf2cfb57f9f6046f44d71ac6faf87254afc7407c04eb621a6287cac126,\n },\n );\n\n assert_eq(\n pedersen_hash_with_separator([1, 2], 2),\n 0x26691c129448e9ace0c66d11f0a16d9014a9e8498ee78f4d69f0083168188255,\n );\n assert_eq(\n pedersen_commitment_with_separator([1, 2], 2),\n EmbeddedCurvePoint {\n x: 0x2e2b3b191e49541fe468ec6877721d445dcaffe41728df0a0eafeb15e87b0753,\n y: 0x2ff4482400ad3a6228be17a2af33e2bcdf41be04795f9782bd96efe7e24f8778,\n },\n );\n assert_eq(\n pedersen_hash_with_separator([1, 2, 3], 3),\n 0x0bc694b7a1f8d10d2d8987d07433f26bd616a2d351bc79a3c540d85b6206dbe4,\n );\n assert_eq(\n pedersen_commitment_with_separator([1, 2, 3], 3),\n EmbeddedCurvePoint {\n x: 0x1fee4e8cf8d2f527caa2684236b07c4b1bad7342c01b0f75e9a877a71827dc85,\n y: 0x2f9fedb9a090697ab69bf04c8bc15f7385b3e4b68c849c1536e5ae15ff138fd1,\n },\n );\n assert_eq(\n pedersen_hash_with_separator([1, 2, 3, 4], 4),\n 0xdae10fb32a8408521803905981a2b300d6a35e40e798743e9322b223a5eddc,\n );\n assert_eq(\n pedersen_commitment_with_separator([1, 2, 3, 4], 4),\n EmbeddedCurvePoint {\n x: 0x07ae3e202811e1fca39c2d81eabe6f79183978e6f12be0d3b8eda095b79bdbc9,\n y: 0x0afc6f892593db6fbba60f2da558517e279e0ae04f95758587760ba193145014,\n },\n );\n assert_eq(\n pedersen_hash_with_separator([1, 2, 3, 4, 5], 5),\n 0xfc375b062c4f4f0150f7100dfb8d9b72a6d28582dd9512390b0497cdad9c22,\n );\n assert_eq(\n pedersen_commitment_with_separator([1, 2, 3, 4, 5], 5),\n EmbeddedCurvePoint {\n x: 0x1754b12bd475a6984a1094b5109eeca9838f4f81ac89c5f0a41dbce53189bb29,\n y: 0x2da030e3cfcdc7ddad80eaf2599df6692cae0717d4e9f7bfbee8d073d5d278f7,\n },\n );\n assert_eq(\n pedersen_hash_with_separator([1, 2, 3, 4, 5, 6], 6),\n 0x1696ed13dc2730062a98ac9d8f9de0661bb98829c7582f699d0273b18c86a572,\n );\n assert_eq(\n pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6], 6),\n EmbeddedCurvePoint {\n x: 0x190f6c0e97ad83e1e28da22a98aae156da083c5a4100e929b77e750d3106a697,\n y: 0x1f4b60f34ef91221a0b49756fa0705da93311a61af73d37a0c458877706616fb,\n },\n );\n assert_eq(\n pedersen_hash_with_separator([1, 2, 3, 4, 5, 6, 7], 7),\n 0x128c0ff144fc66b6cb60eeac8a38e23da52992fc427b92397a7dffd71c45ede3,\n );\n assert_eq(\n pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6, 7], 7),\n EmbeddedCurvePoint {\n x: 0x015441e9d29491b06563fac16fc76abf7a9534c715421d0de85d20dbe2965939,\n y: 0x1d2575b0276f4e9087e6e07c2cb75aa1baafad127af4be5918ef8a2ef2fea8fc,\n },\n );\n assert_eq(\n pedersen_hash_with_separator([1, 2, 3, 4, 5, 6, 7, 8], 8),\n 0x2f960e117482044dfc99d12fece2ef6862fba9242be4846c7c9a3e854325a55c,\n );\n assert_eq(\n pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6, 7, 8], 8),\n EmbeddedCurvePoint {\n x: 0x1657737676968887fceb6dd516382ea13b3a2c557f509811cd86d5d1199bc443,\n y: 0x1f39f0cb569040105fa1e2f156521e8b8e08261e635a2b210bdc94e8d6d65f77,\n },\n );\n assert_eq(\n pedersen_hash_with_separator([1, 2, 3, 4, 5, 6, 7, 8, 9], 9),\n 0x0c96db0790602dcb166cc4699e2d306c479a76926b81c2cb2aaa92d249ec7be7,\n );\n assert_eq(\n pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6, 7, 8, 9], 9),\n EmbeddedCurvePoint {\n x: 0x0a3ceae42d14914a432aa60ec7fded4af7dad7dd4acdbf2908452675ec67e06d,\n y: 0xfc19761eaaf621ad4aec9a8b2e84a4eceffdba78f60f8b9391b0bd9345a2f2,\n },\n );\n assert_eq(\n pedersen_hash_with_separator([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10),\n 0x2cd37505871bc460a62ea1e63c7fe51149df5d0801302cf1cbc48beb8dff7e94,\n );\n assert_eq(\n pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10),\n EmbeddedCurvePoint {\n x: 0x2fb3f8b3d41ddde007c8c3c62550f9a9380ee546fcc639ffbb3fd30c8d8de30c,\n y: 0x300783be23c446b11a4c0fabf6c91af148937cea15fcf5fb054abf7f752ee245,\n },\n );\n}\n"
758
+ },
759
+ "188": {
760
+ "function_locations": [
761
+ {
762
+ "name": "address",
763
+ "start": 272
764
+ },
765
+ {
766
+ "name": "sender",
767
+ "start": 343
768
+ },
769
+ {
770
+ "name": "transaction_fee",
771
+ "start": 415
772
+ },
773
+ {
774
+ "name": "chain_id",
775
+ "start": 489
776
+ },
777
+ {
778
+ "name": "version",
779
+ "start": 555
780
+ },
781
+ {
782
+ "name": "block_number",
783
+ "start": 623
784
+ },
785
+ {
786
+ "name": "timestamp",
787
+ "start": 693
788
+ },
789
+ {
790
+ "name": "min_fee_per_l2_gas",
791
+ "start": 770
792
+ },
793
+ {
794
+ "name": "min_fee_per_da_gas",
795
+ "start": 856
796
+ },
797
+ {
798
+ "name": "l2_gas_left",
799
+ "start": 934
800
+ },
801
+ {
802
+ "name": "da_gas_left",
803
+ "start": 1005
804
+ },
805
+ {
806
+ "name": "is_static_call",
807
+ "start": 1080
808
+ },
809
+ {
810
+ "name": "note_hash_exists",
811
+ "start": 1193
812
+ },
813
+ {
814
+ "name": "emit_note_hash",
815
+ "start": 1302
816
+ },
817
+ {
818
+ "name": "nullifier_exists",
819
+ "start": 1414
820
+ },
821
+ {
822
+ "name": "emit_nullifier",
823
+ "start": 1518
824
+ },
825
+ {
826
+ "name": "emit_public_log",
827
+ "start": 1614
828
+ },
829
+ {
830
+ "name": "l1_to_l2_msg_exists",
831
+ "start": 1741
832
+ },
833
+ {
834
+ "name": "send_l2_to_l1_msg",
835
+ "start": 1880
836
+ },
837
+ {
838
+ "name": "call",
839
+ "start": 2080
840
+ },
841
+ {
842
+ "name": "call_static",
843
+ "start": 2310
844
+ },
845
+ {
846
+ "name": "calldata_copy",
847
+ "start": 2486
848
+ },
849
+ {
850
+ "name": "success_copy",
851
+ "start": 2669
852
+ },
853
+ {
854
+ "name": "returndata_size",
855
+ "start": 2746
856
+ },
857
+ {
858
+ "name": "returndata_copy",
859
+ "start": 2859
860
+ },
861
+ {
862
+ "name": "avm_return",
863
+ "start": 3044
864
+ },
865
+ {
866
+ "name": "revert",
867
+ "start": 3421
868
+ },
869
+ {
870
+ "name": "storage_read",
871
+ "start": 3545
872
+ },
873
+ {
874
+ "name": "storage_write",
875
+ "start": 3676
876
+ },
877
+ {
878
+ "name": "address_opcode",
879
+ "start": 3807
880
+ },
881
+ {
882
+ "name": "sender_opcode",
883
+ "start": 3888
884
+ },
885
+ {
886
+ "name": "transaction_fee_opcode",
887
+ "start": 3979
888
+ },
889
+ {
890
+ "name": "chain_id_opcode",
891
+ "start": 4056
892
+ },
893
+ {
894
+ "name": "version_opcode",
895
+ "start": 4132
896
+ },
897
+ {
898
+ "name": "block_number_opcode",
899
+ "start": 4215
900
+ },
901
+ {
902
+ "name": "timestamp_opcode",
903
+ "start": 4293
904
+ },
905
+ {
906
+ "name": "min_fee_per_l2_gas_opcode",
907
+ "start": 4386
908
+ },
909
+ {
910
+ "name": "min_fee_per_da_gas_opcode",
911
+ "start": 4479
912
+ },
913
+ {
914
+ "name": "l2_gas_left_opcode",
915
+ "start": 4559
916
+ },
917
+ {
918
+ "name": "da_gas_left_opcode",
919
+ "start": 4639
920
+ },
921
+ {
922
+ "name": "is_static_call_opcode",
923
+ "start": 4726
924
+ },
925
+ {
926
+ "name": "note_hash_exists_opcode",
927
+ "start": 4850
928
+ },
929
+ {
930
+ "name": "emit_note_hash_opcode",
931
+ "start": 4945
932
+ },
933
+ {
934
+ "name": "nullifier_exists_opcode",
935
+ "start": 5060
936
+ },
937
+ {
938
+ "name": "emit_nullifier_opcode",
939
+ "start": 5156
940
+ },
941
+ {
942
+ "name": "emit_public_log_opcode",
943
+ "start": 5253
944
+ },
945
+ {
946
+ "name": "l1_to_l2_msg_exists_opcode",
947
+ "start": 5384
948
+ },
949
+ {
950
+ "name": "send_l2_to_l1_msg_opcode",
951
+ "start": 5504
952
+ },
953
+ {
954
+ "name": "calldata_copy_opcode",
955
+ "start": 5637
956
+ },
957
+ {
958
+ "name": "returndata_size_opcode",
959
+ "start": 5726
960
+ },
961
+ {
962
+ "name": "returndata_copy_opcode",
963
+ "start": 5848
964
+ },
965
+ {
966
+ "name": "return_opcode",
967
+ "start": 5932
968
+ },
969
+ {
970
+ "name": "revert_opcode",
971
+ "start": 6016
972
+ },
973
+ {
974
+ "name": "call_opcode",
975
+ "start": 6463
976
+ },
977
+ {
978
+ "name": "call_static_opcode",
979
+ "start": 6923
980
+ },
981
+ {
982
+ "name": "success_copy_opcode",
983
+ "start": 7007
984
+ },
985
+ {
986
+ "name": "storage_read_opcode",
987
+ "start": 7136
988
+ },
989
+ {
990
+ "name": "storage_write_opcode",
991
+ "start": 7247
992
+ }
993
+ ],
994
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/oracle/avm.nr",
995
+ "source": "//! AVM oracles.\n//!\n//! There are only available during public execution. Calling any of them from a private or utility function will\n//! result in runtime errors.\n\nuse crate::protocol::address::{AztecAddress, EthAddress};\n\npub unconstrained fn address() -> AztecAddress {\n address_opcode()\n}\npub unconstrained fn sender() -> AztecAddress {\n sender_opcode()\n}\npub unconstrained fn transaction_fee() -> Field {\n transaction_fee_opcode()\n}\npub unconstrained fn chain_id() -> Field {\n chain_id_opcode()\n}\npub unconstrained fn version() -> Field {\n version_opcode()\n}\npub unconstrained fn block_number() -> u32 {\n block_number_opcode()\n}\npub unconstrained fn timestamp() -> u64 {\n timestamp_opcode()\n}\npub unconstrained fn min_fee_per_l2_gas() -> u128 {\n min_fee_per_l2_gas_opcode()\n}\npub unconstrained fn min_fee_per_da_gas() -> u128 {\n min_fee_per_da_gas_opcode()\n}\npub unconstrained fn l2_gas_left() -> u32 {\n l2_gas_left_opcode()\n}\npub unconstrained fn da_gas_left() -> u32 {\n da_gas_left_opcode()\n}\npub unconstrained fn is_static_call() -> bool {\n is_static_call_opcode()\n}\npub unconstrained fn note_hash_exists(note_hash: Field, leaf_index: u64) -> bool {\n note_hash_exists_opcode(note_hash, leaf_index)\n}\npub unconstrained fn emit_note_hash(note_hash: Field) {\n emit_note_hash_opcode(note_hash)\n}\npub unconstrained fn nullifier_exists(siloed_nullifier: Field) -> bool {\n nullifier_exists_opcode(siloed_nullifier)\n}\npub unconstrained fn emit_nullifier(nullifier: Field) {\n emit_nullifier_opcode(nullifier)\n}\npub unconstrained fn emit_public_log(message: [Field]) {\n emit_public_log_opcode(message)\n}\npub unconstrained fn l1_to_l2_msg_exists(msg_hash: Field, msg_leaf_index: u64) -> bool {\n l1_to_l2_msg_exists_opcode(msg_hash, msg_leaf_index)\n}\npub unconstrained fn send_l2_to_l1_msg(recipient: EthAddress, content: Field) {\n send_l2_to_l1_msg_opcode(recipient, content)\n}\n\npub unconstrained fn call<let N: u32>(\n l2_gas_allocation: u32,\n da_gas_allocation: u32,\n address: AztecAddress,\n args: [Field; N],\n) {\n call_opcode(l2_gas_allocation, da_gas_allocation, address, N, args)\n}\n\npub unconstrained fn call_static<let N: u32>(\n l2_gas_allocation: u32,\n da_gas_allocation: u32,\n address: AztecAddress,\n args: [Field; N],\n) {\n call_static_opcode(l2_gas_allocation, da_gas_allocation, address, N, args)\n}\n\npub unconstrained fn calldata_copy<let N: u32>(cdoffset: u32, copy_size: u32) -> [Field; N] {\n calldata_copy_opcode(cdoffset, copy_size)\n}\n\n/// `success_copy` is placed immediately after the CALL opcode to get the success value\npub unconstrained fn success_copy() -> bool {\n success_copy_opcode()\n}\n\npub unconstrained fn returndata_size() -> u32 {\n returndata_size_opcode()\n}\n\npub unconstrained fn returndata_copy(rdoffset: u32, copy_size: u32) -> [Field] {\n returndata_copy_opcode(rdoffset, copy_size)\n}\n\n/// The additional prefix is to avoid clashing with the `return` Noir keyword.\npub unconstrained fn avm_return(returndata: [Field]) {\n return_opcode(returndata)\n}\n\n/// This opcode reverts using the exact data given. In general it should only be used to do rethrows, where the revert\n/// data is the same as the original revert data. For normal reverts, use Noir's `assert` which, on top of reverting,\n/// will also add an error selector to the revert data.\npub unconstrained fn revert(revertdata: [Field]) {\n revert_opcode(revertdata)\n}\n\npub unconstrained fn storage_read(storage_slot: Field, contract_address: Field) -> Field {\n storage_read_opcode(storage_slot, contract_address)\n}\n\npub unconstrained fn storage_write(storage_slot: Field, value: Field) {\n storage_write_opcode(storage_slot, value);\n}\n\n#[oracle(aztec_avm_address)]\nunconstrained fn address_opcode() -> AztecAddress {}\n\n#[oracle(aztec_avm_sender)]\nunconstrained fn sender_opcode() -> AztecAddress {}\n\n#[oracle(aztec_avm_transactionFee)]\nunconstrained fn transaction_fee_opcode() -> Field {}\n\n#[oracle(aztec_avm_chainId)]\nunconstrained fn chain_id_opcode() -> Field {}\n\n#[oracle(aztec_avm_version)]\nunconstrained fn version_opcode() -> Field {}\n\n#[oracle(aztec_avm_blockNumber)]\nunconstrained fn block_number_opcode() -> u32 {}\n\n#[oracle(aztec_avm_timestamp)]\nunconstrained fn timestamp_opcode() -> u64 {}\n\n#[oracle(aztec_avm_minFeePerL2Gas)]\nunconstrained fn min_fee_per_l2_gas_opcode() -> u128 {}\n\n#[oracle(aztec_avm_minFeePerDaGas)]\nunconstrained fn min_fee_per_da_gas_opcode() -> u128 {}\n\n#[oracle(aztec_avm_l2GasLeft)]\nunconstrained fn l2_gas_left_opcode() -> u32 {}\n\n#[oracle(aztec_avm_daGasLeft)]\nunconstrained fn da_gas_left_opcode() -> u32 {}\n\n#[oracle(aztec_avm_isStaticCall)]\nunconstrained fn is_static_call_opcode() -> bool {}\n\n#[oracle(aztec_avm_noteHashExists)]\nunconstrained fn note_hash_exists_opcode(note_hash: Field, leaf_index: u64) -> bool {}\n\n#[oracle(aztec_avm_emitNoteHash)]\nunconstrained fn emit_note_hash_opcode(note_hash: Field) {}\n\n#[oracle(aztec_avm_nullifierExists)]\nunconstrained fn nullifier_exists_opcode(siloed_nullifier: Field) -> bool {}\n\n#[oracle(aztec_avm_emitNullifier)]\nunconstrained fn emit_nullifier_opcode(nullifier: Field) {}\n\n#[oracle(aztec_avm_emitPublicLog)]\nunconstrained fn emit_public_log_opcode(message: [Field]) {}\n\n#[oracle(aztec_avm_l1ToL2MsgExists)]\nunconstrained fn l1_to_l2_msg_exists_opcode(msg_hash: Field, msg_leaf_index: u64) -> bool {}\n\n#[oracle(aztec_avm_sendL2ToL1Msg)]\nunconstrained fn send_l2_to_l1_msg_opcode(recipient: EthAddress, content: Field) {}\n\n#[oracle(aztec_avm_calldataCopy)]\nunconstrained fn calldata_copy_opcode<let N: u32>(cdoffset: u32, copy_size: u32) -> [Field; N] {}\n\n#[oracle(aztec_avm_returndataSize)]\nunconstrained fn returndata_size_opcode() -> u32 {}\n\n#[oracle(aztec_avm_returndataCopy)]\nunconstrained fn returndata_copy_opcode(rdoffset: u32, copy_size: u32) -> [Field] {}\n\n#[oracle(aztec_avm_return)]\nunconstrained fn return_opcode(returndata: [Field]) {}\n\n#[oracle(aztec_avm_revert)]\nunconstrained fn revert_opcode(revertdata: [Field]) {}\n\n// While the length parameter might seem unnecessary given that we have N we keep it around because at the AVM bytecode\n// level, we want to support non-comptime-known lengths for such opcodes, even if Noir code will not generally take\n// that route.\n#[oracle(aztec_avm_call)]\nunconstrained fn call_opcode<let N: u32>(\n l2_gas_allocation: u32,\n da_gas_allocation: u32,\n address: AztecAddress,\n length: u32,\n args: [Field; N],\n) {}\n\n// While the length parameter might seem unnecessary given that we have N we keep it around because at the AVM bytecode\n// level, we want to support non-comptime-known lengths for such opcodes, even if Noir code will not generally take\n// that route.\n#[oracle(aztec_avm_staticCall)]\nunconstrained fn call_static_opcode<let N: u32>(\n l2_gas_allocation: u32,\n da_gas_allocation: u32,\n address: AztecAddress,\n length: u32,\n args: [Field; N],\n) {}\n\n#[oracle(aztec_avm_successCopy)]\nunconstrained fn success_copy_opcode() -> bool {}\n\n#[oracle(aztec_avm_storageRead)]\nunconstrained fn storage_read_opcode(storage_slot: Field, contract_address: Field) -> Field {}\n\n#[oracle(aztec_avm_storageWrite)]\nunconstrained fn storage_write_opcode(storage_slot: Field, value: Field) {}\n"
996
+ },
997
+ "193": {
998
+ "function_locations": [
999
+ {
1000
+ "name": "set_contract_sync_cache_invalid_oracle",
1001
+ "start": 242
1002
+ },
1003
+ {
1004
+ "name": "set_contract_sync_cache_invalid",
1005
+ "start": 700
1006
+ }
1007
+ ],
1008
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/oracle/contract_sync.nr",
1009
+ "source": "use crate::protocol::address::AztecAddress;\n\n#[oracle(aztec_utl_setContractSyncCacheInvalid)]\nunconstrained fn set_contract_sync_cache_invalid_oracle<let N: u32>(\n contract_address: AztecAddress,\n scopes: BoundedVec<AztecAddress, N>,\n) {}\n\n/// Forces the PXE to re-sync the given contract for a set of scopes on the next query.\n///\n/// Call this after writing data (e.g. offchain messages) that the contract's `sync_state` function needs to discover.\n/// Without invalidation, the sync cache would skip re-running `sync_state` until the next block.\npub unconstrained fn set_contract_sync_cache_invalid<let N: u32>(\n contract_address: AztecAddress,\n scopes: BoundedVec<AztecAddress, N>,\n) {\n set_contract_sync_cache_invalid_oracle(contract_address, scopes);\n}\n"
1010
+ },
1011
+ "195": {
1012
+ "function_locations": [
1013
+ {
1014
+ "name": "get_utility_context_oracle",
1015
+ "start": 582
1016
+ },
1017
+ {
1018
+ "name": "get_utility_context",
1019
+ "start": 786
1020
+ }
1021
+ ],
1022
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/oracle/execution.nr",
1023
+ "source": "use crate::context::UtilityContext;\nuse crate::protocol::{abis::block_header::BlockHeader, address::AztecAddress};\n\n/// Wire shape of [`get_utility_context_oracle`]'s response. [`UtilityContext`] is built from it rather than returned\n/// directly so its fields stay private to its module.\n#[derive(Eq)]\npub(crate) struct UtilityContextData {\n pub(crate) block_header: BlockHeader,\n pub(crate) contract_address: AztecAddress,\n pub(crate) msg_sender: AztecAddress,\n}\n\n#[oracle(aztec_utl_getUtilityContext)]\nunconstrained fn get_utility_context_oracle() -> UtilityContextData {}\n\n/// Returns a utility context built from the global variables of anchor block and the contract address of the function\n/// being executed.\npub unconstrained fn get_utility_context() -> UtilityContext {\n UtilityContext::from(get_utility_context_oracle())\n}\n"
1024
+ },
1025
+ "212": {
1026
+ "function_locations": [
1027
+ {
1028
+ "name": "random",
1029
+ "start": 468
1030
+ },
1031
+ {
1032
+ "name": "rand_oracle",
1033
+ "start": 568
1034
+ }
1035
+ ],
1036
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/oracle/random.nr",
1037
+ "source": "/// Returns an unconstrained random value. Note that it is not possible to constrain this value to prove that it is\n/// truly random: we assume that the oracle is cooperating and returning random values. In some applications this\n/// behavior might not be acceptable and other techniques might be more suitable, such as producing pseudo-random\n/// values by hashing values outside of user control (like block hashes) or secrets.\npub unconstrained fn random() -> Field {\n rand_oracle()\n}\n\n#[oracle(aztec_misc_getRandomField)]\nunconstrained fn rand_oracle() -> Field {}\n"
1038
+ },
1039
+ "276": {
1040
+ "function_locations": [
1041
+ {
1042
+ "name": "UnconstrainedArray<T, Oracle>::at",
1043
+ "start": 3001
1044
+ },
1045
+ {
1046
+ "name": "UnconstrainedArray<T, Oracle>::empty_at",
1047
+ "start": 3363
1048
+ },
1049
+ {
1050
+ "name": "UnconstrainedArray<T, Oracle>::empty",
1051
+ "start": 3834
1052
+ },
1053
+ {
1054
+ "name": "UnconstrainedArray<T, Oracle>::len",
1055
+ "start": 3972
1056
+ },
1057
+ {
1058
+ "name": "UnconstrainedArray<T, Oracle>::push",
1059
+ "start": 4149
1060
+ },
1061
+ {
1062
+ "name": "UnconstrainedArray<T, Oracle>::pop",
1063
+ "start": 4444
1064
+ },
1065
+ {
1066
+ "name": "UnconstrainedArray<T, Oracle>::get",
1067
+ "start": 4757
1068
+ },
1069
+ {
1070
+ "name": "UnconstrainedArray<T, Oracle>::set",
1071
+ "start": 5081
1072
+ },
1073
+ {
1074
+ "name": "UnconstrainedArray<T, Oracle>::remove",
1075
+ "start": 5395
1076
+ },
1077
+ {
1078
+ "name": "UnconstrainedArray<T, Oracle>::clear",
1079
+ "start": 5573
1080
+ },
1081
+ {
1082
+ "name": "UnconstrainedArray<T, Oracle>::for_each",
1083
+ "start": 6201
1084
+ },
1085
+ {
1086
+ "name": "UnconstrainedArray<T, Oracle>::map",
1087
+ "start": 6555
1088
+ },
1089
+ {
1090
+ "name": "UnconstrainedArray<T, Oracle>::filter",
1091
+ "start": 6975
1092
+ },
1093
+ {
1094
+ "name": "UnconstrainedArray<T, Oracle>::any",
1095
+ "start": 7435
1096
+ },
1097
+ {
1098
+ "name": "UnconstrainedArray<T, Oracle>::all",
1099
+ "start": 7720
1100
+ },
1101
+ {
1102
+ "name": "UnconstrainedArray<T, Oracle>::find",
1103
+ "start": 7995
1104
+ }
1105
+ ],
1106
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/unconstrained_array/mod.nr",
1107
+ "source": "pub(crate) mod test_helpers;\npub(crate) mod test_suite;\n\nuse crate::oracle::random::random;\nuse crate::protocol::traits::{Deserialize, Serialize};\n\n/// Oracle backend for an [`UnconstrainedArray`]: the set of PXE-side operations that implement its storage.\n///\n/// Each implementor routes these operations to a distinct family of oracles, and the oracle family determines the\n/// array's lifetime and visibility (e.g. [`EphemeralArray`](crate::ephemeral::EphemeralArray) arrays live for one\n/// contract call frame, while [`TransientArray`](crate::transient::TransientArray) arrays are shared across all frames\n/// of the same contract within one top-level PXE call).\npub(crate) trait ArrayOracles {\n /// Returns the number of elements in the array at `slot`.\n unconstrained fn len_oracle(slot: Field) -> u32;\n\n /// Appends a serialized element to the array at `slot` and returns the new length.\n unconstrained fn push_oracle<let N: u32>(slot: Field, values: [Field; N]) -> u32;\n\n /// Removes and returns the last serialized element of the array at `slot`. Implementors must panic if the\n /// array is empty.\n unconstrained fn pop_oracle<let N: u32>(slot: Field) -> [Field; N];\n\n /// Returns the serialized element at the given index of the array at `slot`. Implementors must panic if `index`\n /// is out of bounds.\n unconstrained fn get_oracle<let N: u32>(slot: Field, index: u32) -> [Field; N];\n\n /// Overwrites the serialized element at the given index of the array at `slot`. Implementors must panic if\n /// `index` is out of bounds.\n unconstrained fn set_oracle<let N: u32>(slot: Field, index: u32, values: [Field; N]);\n\n /// Removes the element at the given index of the array at `slot`, shifting subsequent elements backward.\n /// Implementors must panic if `index` is out of bounds.\n unconstrained fn remove_oracle(slot: Field, index: u32);\n\n /// Removes all elements from the array at `slot`.\n unconstrained fn clear_oracle(slot: Field);\n}\n\n/// A dynamically sized array backed by PXE-side in-memory storage via an [`ArrayOracles`] backend.\n///\n/// Arrays are identified by a slot, and each logical operation (push, pop, get, etc.) is a single oracle call. The\n/// `Oracle` backend determines the array's lifetime and visibility; contracts should not use this type directly but\n/// rather one of its aliases: [`EphemeralArray`](crate::ephemeral::EphemeralArray) (scoped to a single contract call\n/// frame) or [`TransientArray`](crate::transient::TransientArray) (shared across all frames of the same contract\n/// within one top-level PXE call).\npub struct UnconstrainedArray<T, Oracle> {\n pub(crate) slot: Field,\n}\n\nimpl<T, Oracle> UnconstrainedArray<T, Oracle>\nwhere\n Oracle: ArrayOracles,\n{\n /// Returns a handle to the array at the given slot, which may already contain data (e.g. populated by an oracle\n /// or by an earlier frame, depending on the backend's visibility).\n pub unconstrained fn at(slot: Field) -> Self {\n Self { slot }\n }\n\n /// Returns an empty array at the given slot, clearing any pre-existing data.\n ///\n /// For backends whose arrays are visible beyond a single call frame (e.g. transient arrays), this wipes data\n /// other frames of the same contract may have written at the slot.\n pub unconstrained fn empty_at(slot: Field) -> Self {\n Self::at(slot).clear()\n }\n\n /// Returns an empty array at a fresh, randomly allocated slot.\n ///\n /// Use this when the caller does not need a specific slot: the random slot is isolated from every other array of\n /// the same backend with overwhelming probability. Prefer [`UnconstrainedArray::empty_at`] when the slot must be a\n /// known value (e.g. one shared with an oracle or another call frame).\n pub unconstrained fn empty() -> Self {\n Self::at(random())\n }\n\n /// Returns the number of elements stored in the array.\n pub unconstrained fn len(self) -> u32 {\n Oracle::len_oracle(self.slot)\n }\n\n /// Stores a value at the end of the array.\n pub unconstrained fn push(self, value: T)\n where\n T: Serialize,\n {\n let serialized = value.serialize();\n let _ = Oracle::push_oracle(self.slot, serialized);\n }\n\n /// Removes and returns the last element. Implementors are required to panic if the array is empty.\n pub unconstrained fn pop(self) -> T\n where\n T: Deserialize,\n {\n let serialized = Oracle::pop_oracle(self.slot);\n Deserialize::deserialize(serialized)\n }\n\n /// Retrieves the value stored at `index`. Implementors are required to panic if the index is out of bounds.\n pub unconstrained fn get(self, index: u32) -> T\n where\n T: Deserialize,\n {\n let serialized = Oracle::get_oracle(self.slot, index);\n Deserialize::deserialize(serialized)\n }\n\n /// Overwrites the value stored at `index`. Implementors are required to panic if the index is out of bounds.\n pub unconstrained fn set(self, index: u32, value: T)\n where\n T: Serialize,\n {\n let serialized = value.serialize();\n Oracle::set_oracle(self.slot, index, serialized);\n }\n\n /// Removes the element at `index`, shifting subsequent elements backward. Implementors are required to panic if\n /// the index is out of bounds.\n pub unconstrained fn remove(self, index: u32) {\n Oracle::remove_oracle(self.slot, index);\n }\n\n /// Removes all elements from the array and returns self for chaining.\n pub unconstrained fn clear(self) -> Self {\n Oracle::clear_oracle(self.slot);\n self\n }\n\n /// Calls a function on each element of the array.\n ///\n /// The function `f` is called once with each array value and its corresponding index, in order (from the first\n /// element to the last).\n ///\n /// Structurally mutating the array from inside the callback (e.g. via `push`, `pop`, `remove` or `clear`) is\n /// **not** supported: it can cause elements to be skipped, visited more than once, or read out of bounds.\n pub unconstrained fn for_each<Env>(self, f: unconstrained fn[Env](u32, T) -> ())\n where\n T: Deserialize,\n {\n let n = self.len();\n for i in 0..n {\n f(i, self.get(i));\n }\n }\n\n /// Applies `f` to every element and collects the results into a fresh array.\n pub unconstrained fn map<U, Env>(self, f: unconstrained fn[Env](T) -> U) -> UnconstrainedArray<U, Oracle>\n where\n T: Deserialize,\n U: Serialize,\n {\n let dest: UnconstrainedArray<U, Oracle> = UnconstrainedArray::empty();\n let n = self.len();\n for i in 0..n {\n dest.push(f(self.get(i)));\n }\n dest\n }\n\n /// Collects every element satisfying the predicate `f` into a fresh array.\n pub unconstrained fn filter<Env>(self, f: unconstrained fn[Env](T) -> bool) -> Self\n where\n T: Serialize + Deserialize,\n {\n let dest: Self = UnconstrainedArray::empty();\n let n = self.len();\n for i in 0..n {\n let value = self.get(i);\n if f(value) {\n dest.push(value);\n }\n }\n dest\n }\n\n /// Returns `true` if at least one element satisfies the predicate `f`.\n pub unconstrained fn any<Env>(self, f: unconstrained fn[Env](T) -> bool) -> bool\n where\n T: Serialize + Deserialize,\n {\n self.filter(f).len() != 0\n }\n\n /// Returns `true` if every element satisfies the predicate `f` (vacuously `true` for an empty array).\n pub unconstrained fn all<Env>(self, f: unconstrained fn[Env](T) -> bool) -> bool\n where\n T: Serialize + Deserialize,\n {\n self.filter(f).len() == self.len()\n }\n\n /// Returns the first element satisfying the predicate `f`, or `Option::none` if none do.\n pub unconstrained fn find<Env>(self, f: unconstrained fn[Env](T) -> bool) -> Option<T>\n where\n T: Deserialize,\n {\n let n = self.len();\n let mut result: Option<T> = Option::none();\n let mut i = 0;\n while (i < n) & result.is_none() {\n let value = self.get(i);\n if f(value) {\n result = Option::some(value);\n }\n i += 1;\n }\n result\n }\n}\n"
1108
+ },
1109
+ "285": {
1110
+ "function_locations": [
1111
+ {
1112
+ "name": "compare",
1113
+ "start": 293
1114
+ },
1115
+ {
1116
+ "name": "test::test_compare",
1117
+ "start": 987
1118
+ }
1119
+ ],
1120
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/utils/comparison.nr",
1121
+ "source": "struct ComparatorEnum {\n pub EQ: u8,\n pub NEQ: u8,\n pub LT: u8,\n pub LTE: u8,\n pub GT: u8,\n pub GTE: u8,\n}\n\npub global Comparator: ComparatorEnum = ComparatorEnum { EQ: 1, NEQ: 2, LT: 3, LTE: 4, GT: 5, GTE: 6 };\n\npub fn compare(lhs: Field, operation: u8, rhs: Field) -> bool {\n // Values are computed ahead of time because circuits evaluate all branches\n let is_equal = lhs == rhs;\n let is_lt = lhs.lt(rhs);\n\n if (operation == Comparator.EQ) {\n is_equal\n } else if (operation == Comparator.NEQ) {\n !is_equal\n } else if (operation == Comparator.LT) {\n is_lt\n } else if (operation == Comparator.LTE) {\n is_lt | is_equal\n } else if (operation == Comparator.GT) {\n !is_lt & !is_equal\n } else if (operation == Comparator.GTE) {\n !is_lt\n } else {\n panic(f\"Invalid operation\")\n }\n}\n\nmod test {\n use super::Comparator;\n use super::compare;\n\n #[test]\n unconstrained fn test_compare() {\n let lhs = 10;\n let rhs = 10;\n assert(compare(lhs, Comparator.EQ, rhs), \"Expected lhs to be equal to rhs\");\n\n let lhs = 10;\n let rhs = 11;\n assert(compare(lhs, Comparator.NEQ, rhs), \"Expected lhs to be not equal to rhs\");\n\n let lhs = 10;\n let rhs = 11;\n assert(compare(lhs, Comparator.LT, rhs), \"Expected lhs to be less than rhs\");\n\n let lhs = 10;\n let rhs = 10;\n assert(compare(lhs, Comparator.LTE, rhs), \"Expected lhs to be less than or equal to rhs\");\n\n let lhs = 11;\n let rhs = 10;\n assert(compare(lhs, Comparator.GT, rhs), \"Expected lhs to be greater than rhs\");\n\n let lhs = 10;\n let rhs = 10;\n assert(compare(lhs, Comparator.GTE, rhs), \"Expected lhs to be greater than or equal to rhs\");\n\n let lhs = 11;\n let rhs = 10;\n assert(compare(lhs, Comparator.GTE, rhs), \"Expected lhs to be greater than or equal to rhs\");\n\n let lhs = 10;\n let rhs = 11;\n assert(!compare(lhs, Comparator.EQ, rhs), \"Expected lhs to be not equal to rhs\");\n\n let lhs = 10;\n let rhs = 10;\n assert(!compare(lhs, Comparator.NEQ, rhs), \"Expected lhs to not be not equal to rhs\");\n\n let lhs = 11;\n let rhs = 10;\n assert(!compare(lhs, Comparator.LT, rhs), \"Expected lhs to not be less than rhs\");\n\n let lhs = 11;\n let rhs = 10;\n assert(!compare(lhs, Comparator.LTE, rhs), \"Expected lhs to not be less than or equal to rhs\");\n\n let lhs = 10;\n let rhs = 10;\n assert(!compare(lhs, Comparator.GT, rhs), \"Expected lhs to not be greater than rhs\");\n\n let lhs = 10;\n let rhs = 11;\n assert(!compare(lhs, Comparator.GTE, rhs), \"Expected lhs to not be greater than or equal to rhs\");\n\n let lhs = 10;\n let rhs = 11;\n assert(!compare(lhs, Comparator.GTE, rhs), \"Expected lhs to not be greater than or equal to rhs\");\n }\n}\n"
1122
+ },
1123
+ "300": {
1124
+ "function_locations": [
1125
+ {
1126
+ "name": "Poseidon2::hash",
1127
+ "start": 333
1128
+ },
1129
+ {
1130
+ "name": "Poseidon2::new",
1131
+ "start": 442
1132
+ },
1133
+ {
1134
+ "name": "Poseidon2::perform_duplex",
1135
+ "start": 649
1136
+ },
1137
+ {
1138
+ "name": "Poseidon2::absorb",
1139
+ "start": 923
1140
+ },
1141
+ {
1142
+ "name": "Poseidon2::squeeze",
1143
+ "start": 1453
1144
+ },
1145
+ {
1146
+ "name": "Poseidon2::hash_internal",
1147
+ "start": 1814
1148
+ },
1149
+ {
1150
+ "name": "<impl Hasher for Poseidon2Hasher>::finish",
1151
+ "start": 4105
1152
+ },
1153
+ {
1154
+ "name": "<impl Hasher for Poseidon2Hasher>::write",
1155
+ "start": 4426
1156
+ },
1157
+ {
1158
+ "name": "<impl Default for Poseidon2Hasher>::default",
1159
+ "start": 4549
1160
+ }
1161
+ ],
1162
+ "path": "/Users/maximvezenov/nargo/github.com/noir-lang/poseidon/v0.3.0/src/poseidon2.nr",
1163
+ "source": "use std::default::Default;\nuse std::hash::Hasher;\n\nglobal RATE: u32 = 3;\n\npub struct Poseidon2 {\n cache: [Field; 3],\n state: [Field; 4],\n cache_size: u32,\n squeeze_mode: bool, // 0 => absorb, 1 => squeeze\n}\n\nimpl Poseidon2 {\n #[no_predicates]\n pub fn hash<let N: u32>(input: [Field; N], message_size: u32) -> Field {\n Poseidon2::hash_internal(input, message_size)\n }\n\n pub(crate) fn new(iv: Field) -> Poseidon2 {\n let mut result =\n Poseidon2 { cache: [0; 3], state: [0; 4], cache_size: 0, squeeze_mode: false };\n result.state[RATE] = iv;\n result\n }\n\n fn perform_duplex(&mut self) {\n // add the cache into sponge state\n self.state[0] += self.cache[0];\n self.state[1] += self.cache[1];\n self.state[2] += self.cache[2];\n self.state = crate::poseidon2_permutation(self.state);\n }\n\n fn absorb(&mut self, input: Field) {\n assert(!self.squeeze_mode);\n if self.cache_size == RATE {\n // If we're absorbing, and the cache is full, apply the sponge permutation to compress the cache\n self.perform_duplex();\n self.cache[0] = input;\n self.cache_size = 1;\n } else {\n // If we're absorbing, and the cache is not full, add the input into the cache\n self.cache[self.cache_size] = input;\n self.cache_size += 1;\n }\n }\n\n fn squeeze(&mut self) -> Field {\n assert(!self.squeeze_mode);\n // If we're in absorb mode, apply sponge permutation to compress the cache.\n self.perform_duplex();\n self.squeeze_mode = true;\n\n // Pop one item off the top of the permutation and return it.\n self.state[0]\n }\n\n fn hash_internal<let N: u32>(input: [Field; N], in_len: u32) -> Field {\n let two_pow_64 = 18446744073709551616;\n let iv: Field = (in_len as Field) * two_pow_64;\n let mut state = [0; 4];\n state[RATE] = iv;\n\n if std::runtime::is_unconstrained() {\n for i in 0..(in_len / RATE) {\n state[0] += input[i * RATE];\n state[1] += input[i * RATE + 1];\n state[2] += input[i * RATE + 2];\n state = crate::poseidon2_permutation(state);\n }\n\n // handle remaining elements after last full RATE-sized chunk\n let num_extra_fields = in_len % RATE;\n if num_extra_fields != 0 {\n let remainder_start = in_len - num_extra_fields;\n state[0] += input[remainder_start];\n if num_extra_fields > 1 {\n state[1] += input[remainder_start + 1];\n }\n }\n } else {\n let mut states: [[Field; 4]; N / RATE + 1] = [[0; 4]; N / RATE + 1];\n states[0] = state;\n\n // process all full RATE-sized chunks, storing state after each permutation\n for chunk_idx in 0..(N / RATE) {\n for i in 0..RATE {\n state[i] += input[chunk_idx * RATE + i];\n }\n state = crate::poseidon2_permutation(state);\n states[chunk_idx + 1] = state;\n }\n\n // get state at the last full block before in_len\n let first_partially_filled_chunk = in_len / RATE;\n state = states[first_partially_filled_chunk];\n\n // handle remaining elements after last full RATE-sized chunk\n let remainder_start = (in_len / RATE) * RATE;\n for j in 0..RATE {\n let idx = remainder_start + j;\n if idx < in_len {\n state[j] += input[idx];\n }\n }\n }\n\n // always run final permutation unless we just completed a full chunk\n // still need to permute once if in_len is 0\n if (in_len == 0) | (in_len % RATE != 0) {\n state = crate::poseidon2_permutation(state);\n };\n\n state[0]\n }\n}\n\npub struct Poseidon2Hasher {\n _state: [Field],\n}\n\nimpl Hasher for Poseidon2Hasher {\n fn finish(self) -> Field {\n let iv: Field = (self._state.len() as Field) * 18446744073709551616; // iv = (self._state.len() << 64)\n let mut sponge = Poseidon2::new(iv);\n for i in 0..self._state.len() {\n sponge.absorb(self._state[i]);\n }\n sponge.squeeze()\n }\n\n fn write(&mut self, input: Field) {\n self._state = self._state.push_back(input);\n }\n}\n\nimpl Default for Poseidon2Hasher {\n fn default() -> Self {\n Poseidon2Hasher { _state: @[] }\n }\n}\n"
1164
+ },
1165
+ "389": {
1166
+ "function_locations": [
1167
+ {
1168
+ "name": "sha256_to_field",
1169
+ "start": 1253
1170
+ },
1171
+ {
1172
+ "name": "private_functions_root_from_siblings",
1173
+ "start": 1605
1174
+ },
1175
+ {
1176
+ "name": "compute_siloed_note_hash",
1177
+ "start": 2202
1178
+ },
1179
+ {
1180
+ "name": "compute_unique_note_hash",
1181
+ "start": 5031
1182
+ },
1183
+ {
1184
+ "name": "compute_note_hash_nonce",
1185
+ "start": 5247
1186
+ },
1187
+ {
1188
+ "name": "compute_note_nonce_and_unique_note_hash",
1189
+ "start": 5663
1190
+ },
1191
+ {
1192
+ "name": "compute_siloed_nullifier",
1193
+ "start": 5899
1194
+ },
1195
+ {
1196
+ "name": "create_protocol_nullifier",
1197
+ "start": 6116
1198
+ },
1199
+ {
1200
+ "name": "compute_log_tag",
1201
+ "start": 6480
1202
+ },
1203
+ {
1204
+ "name": "compute_siloed_private_log_first_field",
1205
+ "start": 6651
1206
+ },
1207
+ {
1208
+ "name": "compute_siloed_private_log",
1209
+ "start": 6882
1210
+ },
1211
+ {
1212
+ "name": "compute_contract_class_log_hash",
1213
+ "start": 7142
1214
+ },
1215
+ {
1216
+ "name": "compute_app_siloed_secret_key",
1217
+ "start": 7333
1218
+ },
1219
+ {
1220
+ "name": "compute_l2_to_l1_message_hash",
1221
+ "start": 7628
1222
+ },
1223
+ {
1224
+ "name": "accumulate_sha256",
1225
+ "start": 8709
1226
+ },
1227
+ {
1228
+ "name": "poseidon2_hash",
1229
+ "start": 9037
1230
+ },
1231
+ {
1232
+ "name": "poseidon2_hash_with_separator",
1233
+ "start": 9228
1234
+ },
1235
+ {
1236
+ "name": "poseidon2_hash_subarray",
1237
+ "start": 9714
1238
+ },
1239
+ {
1240
+ "name": "poseidon2_hash_with_separator_bounded_vec",
1241
+ "start": 10126
1242
+ },
1243
+ {
1244
+ "name": "poseidon2_hash_bytes",
1245
+ "start": 10487
1246
+ },
1247
+ {
1248
+ "name": "subarray_hash_matches_fixed",
1249
+ "start": 11063
1250
+ },
1251
+ {
1252
+ "name": "subarray_hash_matches_variable",
1253
+ "start": 11462
1254
+ },
1255
+ {
1256
+ "name": "smoke_sha256_to_field",
1257
+ "start": 11878
1258
+ },
1259
+ {
1260
+ "name": "unique_siloed_note_hash_matches_typescript",
1261
+ "start": 13280
1262
+ },
1263
+ {
1264
+ "name": "siloed_nullifier_matches_typescript",
1265
+ "start": 14502
1266
+ },
1267
+ {
1268
+ "name": "siloed_private_log_first_field_matches_typescript",
1269
+ "start": 14882
1270
+ },
1271
+ {
1272
+ "name": "empty_l2_to_l1_message_hash_matches_typescript",
1273
+ "start": 15292
1274
+ },
1275
+ {
1276
+ "name": "l2_to_l1_message_hash_matches_typescript",
1277
+ "start": 15743
1278
+ },
1279
+ {
1280
+ "name": "poseidon2_hash_with_separator_bounded_vec_matches_non_bounded_vec_version",
1281
+ "start": 16359
1282
+ }
1283
+ ],
1284
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/fnd/noir-protocol-circuits/crates/types/src/hash.nr",
1285
+ "source": "mod poseidon2_chunks;\n\nuse crate::{\n abis::{\n contract_class_function_leaf_preimage::ContractClassFunctionLeafPreimage,\n function_selector::FunctionSelector, nullifier::Nullifier, private_log::PrivateLog,\n transaction::tx_request::TxRequest,\n },\n address::{AztecAddress, EthAddress},\n constants::{\n CONTRACT_CLASS_LOG_SIZE_IN_FIELDS, DOM_SEP__NOTE_HASH_NONCE,\n DOM_SEP__PRIVATE_LOG_FIRST_FIELD, DOM_SEP__SILOED_NOTE_HASH, DOM_SEP__SILOED_NULLIFIER,\n DOM_SEP__UNIQUE_NOTE_HASH, FUNCTION_TREE_HEIGHT, NULL_MSG_SENDER_CONTRACT_ADDRESS,\n TWO_POW_64,\n },\n merkle_tree::root_from_sibling_path,\n messaging::l2_to_l1_message::L2ToL1Message,\n poseidon2::Poseidon2Sponge,\n side_effect::{Counted, Scoped},\n traits::{FromField, Hash, ToField},\n utils::field::{field_from_bytes, field_from_bytes_32_trunc},\n};\n\npub use poseidon2_chunks::poseidon2_absorb_in_chunks_existing_sponge;\nuse poseidon2_chunks::poseidon2_absorb_in_chunks;\nuse std::embedded_curve_ops::EmbeddedCurveScalar;\n\n// TODO: refactor these into their own files: sha256, poseidon2, some protocol-specific hash computations, some merkle computations.\n\npub fn sha256_to_field<let N: u32>(bytes_to_hash: [u8; N]) -> Field {\n let sha256_hashed = sha256::digest(bytes_to_hash);\n let hash_in_a_field = field_from_bytes_32_trunc(sha256_hashed);\n\n hash_in_a_field\n}\n\npub fn private_functions_root_from_siblings(\n selector: FunctionSelector,\n vk_hash: Field,\n function_leaf_index: Field,\n function_leaf_sibling_path: [Field; FUNCTION_TREE_HEIGHT],\n) -> Field {\n let function_leaf_preimage = ContractClassFunctionLeafPreimage { selector, vk_hash };\n let function_leaf = function_leaf_preimage.hash();\n root_from_sibling_path(\n function_leaf,\n function_leaf_index,\n function_leaf_sibling_path,\n )\n}\n\n/// Siloing in the context of Aztec refers to the process of hashing a note hash with a contract address (this way\n/// the note hash is scoped to a specific contract). This is used to prevent intermingling of notes between contracts.\npub fn compute_siloed_note_hash(contract_address: AztecAddress, note_hash: Field) -> Field {\n poseidon2_hash_with_separator(\n [contract_address.to_field(), note_hash],\n DOM_SEP__SILOED_NOTE_HASH,\n )\n}\n\n/// Computes unique, siloed note hashes from siloed note hashes.\n///\n/// The protocol injects uniqueness into every note_hash, so that every single note_hash in the\n/// tree is unique. This prevents faerie gold attacks, where a malicious sender could create\n/// two identical note_hashes for a recipient (meaning only one would be nullifiable in future).\n///\n/// Most privacy protocols will inject the note's leaf_index (its position in the Note Hashes Tree)\n/// into the note, but this requires the creator of a note to wait until their tx is included in\n/// a block to know the note's final note hash (the unique, siloed note hash), because inserting\n/// leaves into trees is the job of a block producer.\n///\n/// We took a different approach so that the creator of a note will know each note's unique, siloed\n/// note hash before broadcasting their tx to the network.\n/// (There was also a historical requirement relating to \"chained transactions\" -- a feature that\n/// Aztec Connect had to enable notes to be spent from distinct txs earlier in the same block,\n/// and hence before an archive block root had been established for that block -- but that feature\n/// was abandoned for the Aztec Network for having too many bad tradeoffs).\n///\n/// (\n/// Edit: it is no longer true that all final note_hashes will be known by the creator of a tx\n/// before they send it to the network. If a tx makes public function calls, then _revertible_\n/// note_hashes that are created in private will not be made unique in private by the Reset circuit,\n/// but will instead be made unique by the AVM, because the `note_index_in_tx` will not be known\n/// until the AVM has executed the public functions of the tx. (See an explanation in\n/// reset_output_composer.nr for why).\n/// For some such txs, the `note_index_in_tx` might still be predictable through simulation, but\n/// for txs whose public functions create a varying number of non-revertible notes (determined at\n/// runtime), the `note_index_in_tx` will not be deterministically derivable before submitting the\n/// tx to the network.\n/// )\n///\n/// We use the `first_nullifier` of a tx as a seed of uniqueness. We have a guarantee that there will\n/// always be at least one nullifier per tx, because the init circuit will create one if one isn't\n/// created naturally by any functions of the tx. (Search \"protocol_nullifier\").\n/// We combine the `first_nullifier` with the note's index (its position within this tx's new\n/// note_hashes array) (`note_index_in_tx`) to get a truly unique value to inject into a note, which\n/// we call a `note_nonce`.\npub fn compute_unique_note_hash(note_nonce: Field, siloed_note_hash: Field) -> Field {\n let inputs = [note_nonce, siloed_note_hash];\n poseidon2_hash_with_separator(inputs, DOM_SEP__UNIQUE_NOTE_HASH)\n}\n\npub fn compute_note_hash_nonce(first_nullifier_in_tx: Field, note_index_in_tx: u32) -> Field {\n // Hashing the first nullifier with note index in tx is guaranteed to be unique (because all nullifiers are also\n // unique).\n poseidon2_hash_with_separator(\n [first_nullifier_in_tx, note_index_in_tx as Field],\n DOM_SEP__NOTE_HASH_NONCE,\n )\n}\n\npub fn compute_note_nonce_and_unique_note_hash(\n siloed_note_hash: Field,\n first_nullifier: Field,\n note_index_in_tx: u32,\n) -> Field {\n let note_nonce = compute_note_hash_nonce(first_nullifier, note_index_in_tx);\n compute_unique_note_hash(note_nonce, siloed_note_hash)\n}\n\npub fn compute_siloed_nullifier(contract_address: AztecAddress, nullifier: Field) -> Field {\n poseidon2_hash_with_separator(\n [contract_address.to_field(), nullifier],\n DOM_SEP__SILOED_NULLIFIER,\n )\n}\n\npub fn create_protocol_nullifier(tx_request: TxRequest) -> Scoped<Counted<Nullifier>> {\n // The protocol nullifier is ascribed a special side-effect counter of 1. No other side-effect\n // can have counter 1 (see `validate_as_first_call` for that assertion).\n Nullifier { value: tx_request.hash(), note_hash: 0 }.count(1).scope(\n NULL_MSG_SENDER_CONTRACT_ADDRESS,\n )\n}\n\npub fn compute_log_tag(raw_tag: Field, dom_sep: u32) -> Field {\n poseidon2_hash_with_separator([raw_tag], dom_sep)\n}\n\npub fn compute_siloed_private_log_first_field(\n contract_address: AztecAddress,\n field: Field,\n) -> Field {\n poseidon2_hash_with_separator(\n [contract_address.to_field(), field],\n DOM_SEP__PRIVATE_LOG_FIRST_FIELD,\n )\n}\n\npub fn compute_siloed_private_log(contract_address: AztecAddress, log: PrivateLog) -> PrivateLog {\n let mut fields = log.fields;\n fields[0] = compute_siloed_private_log_first_field(contract_address, fields[0]);\n PrivateLog::new(fields, log.length)\n}\n\npub fn compute_contract_class_log_hash(log: [Field; CONTRACT_CLASS_LOG_SIZE_IN_FIELDS]) -> Field {\n poseidon2_hash(log)\n}\n\npub fn compute_app_siloed_secret_key(\n master_secret_key: EmbeddedCurveScalar,\n app_address: AztecAddress,\n key_type_domain_separator: Field,\n) -> Field {\n poseidon2_hash_with_separator(\n [master_secret_key.hi, master_secret_key.lo, app_address.to_field()],\n key_type_domain_separator,\n )\n}\n\npub fn compute_l2_to_l1_message_hash(\n message: Scoped<L2ToL1Message>,\n rollup_version_id: Field,\n chain_id: Field,\n) -> Field {\n let contract_address_bytes: [u8; 32] = message.contract_address.to_field().to_be_bytes();\n let recipient_bytes: [u8; 20] = message.inner.recipient.to_be_bytes();\n let content_bytes: [u8; 32] = message.inner.content.to_be_bytes();\n let rollup_version_id_bytes: [u8; 32] = rollup_version_id.to_be_bytes();\n let chain_id_bytes: [u8; 32] = chain_id.to_be_bytes();\n\n let mut bytes: [u8; 148] = std::mem::zeroed();\n for i in 0..32 {\n bytes[i] = contract_address_bytes[i];\n bytes[i + 32] = rollup_version_id_bytes[i];\n // 64 - 84 are for recipient.\n bytes[i + 84] = chain_id_bytes[i];\n bytes[i + 116] = content_bytes[i];\n }\n\n for i in 0..20 {\n bytes[64 + i] = recipient_bytes[i];\n }\n\n sha256_to_field(bytes)\n}\n\n// TODO: consider a variant that enables domain separation with a u32 (we seem to have standardised u32s for domain separators)\n/// Computes sha256 hash of 2 input fields.\n///\n/// @returns A truncated field (i.e., the first byte is always 0).\npub fn accumulate_sha256(v0: Field, v1: Field) -> Field {\n // Concatenate two fields into 32 x 2 = 64 bytes\n let v0_as_bytes: [u8; 32] = v0.to_be_bytes();\n let v1_as_bytes: [u8; 32] = v1.to_be_bytes();\n let hash_input_flattened = v0_as_bytes.concat(v1_as_bytes);\n\n sha256_to_field(hash_input_flattened)\n}\n\npub fn poseidon2_hash<let N: u32>(inputs: [Field; N]) -> Field {\n poseidon::poseidon2::Poseidon2::hash(inputs, N)\n}\n\n#[no_predicates]\npub fn poseidon2_hash_with_separator<let N: u32, T>(inputs: [Field; N], separator: T) -> Field\nwhere\n T: ToField,\n{\n let inputs_with_separator = [separator.to_field()].concat(inputs);\n poseidon2_hash(inputs_with_separator)\n}\n\n/// Computes a Poseidon2 hash over a dynamic-length subarray of the given input.\n/// Only the first `in_len` fields of `input` are absorbed; any remaining fields are ignored.\n/// The caller is responsible for ensuring that the input is padded with zeros if required.\n#[no_predicates]\npub fn poseidon2_hash_subarray<let N: u32>(input: [Field; N], in_len: u32) -> Field {\n let mut sponge = poseidon2_absorb_in_chunks(input, in_len);\n sponge.squeeze()\n}\n\n// This function is unconstrained because it is intended to be used in unconstrained context only as\n// in constrained contexts it would be too inefficient.\npub unconstrained fn poseidon2_hash_with_separator_bounded_vec<let N: u32, T>(\n inputs: BoundedVec<Field, N>,\n separator: T,\n) -> Field\nwhere\n T: ToField,\n{\n let in_len = inputs.len() + 1;\n let iv: Field = (in_len as Field) * TWO_POW_64;\n let mut sponge = Poseidon2Sponge::new(iv);\n sponge.absorb(separator.to_field());\n\n for i in 0..inputs.len() {\n sponge.absorb(inputs.get(i));\n }\n\n sponge.squeeze()\n}\n\n#[no_predicates]\npub fn poseidon2_hash_bytes<let N: u32>(inputs: [u8; N]) -> Field {\n let mut fields = [0; (N + 30) / 31];\n let mut field_index = 0;\n let mut current_field = [0; 31];\n for i in 0..inputs.len() {\n let index = i % 31;\n current_field[index] = inputs[i];\n if index == 30 {\n fields[field_index] = field_from_bytes(current_field, false);\n current_field = [0; 31];\n field_index += 1;\n }\n }\n if field_index != fields.len() {\n fields[field_index] = field_from_bytes(current_field, false);\n }\n poseidon2_hash(fields)\n}\n\n#[test]\nfn subarray_hash_matches_fixed() {\n let values_to_hash = [3; 17];\n let padded = values_to_hash.concat([0; 11]);\n let subarray_hash = poseidon2_hash_subarray(padded, values_to_hash.len());\n\n // Hash the entire values_to_hash.\n let fixed_len_hash = poseidon::poseidon2::Poseidon2::hash(values_to_hash, values_to_hash.len());\n\n assert_eq(subarray_hash, fixed_len_hash);\n}\n\n#[test]\nfn subarray_hash_matches_variable() {\n let values_to_hash = [3; 17];\n let padded = values_to_hash.concat([0; 11]);\n let subarray_hash = poseidon2_hash_subarray(padded, values_to_hash.len());\n\n // Hash up to values_to_hash.len() fields of the padded array.\n let variable_len_hash = poseidon::poseidon2::Poseidon2::hash(padded, values_to_hash.len());\n\n assert_eq(subarray_hash, variable_len_hash);\n}\n\n#[test]\nfn smoke_sha256_to_field() {\n let full_buffer = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,\n 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,\n 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,\n 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130,\n 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,\n 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,\n ];\n let result = sha256_to_field(full_buffer);\n\n assert(result == 0x448ebbc9e1a31220a2f3830c18eef61b9bd070e5084b7fa2a359fe729184c7);\n\n // to show correctness of the current ver (truncate one byte) vs old ver (mod full bytes):\n let result_bytes = sha256::digest(full_buffer);\n let truncated_field = crate::utils::field::field_from_bytes_32_trunc(result_bytes);\n assert(truncated_field == result);\n let mod_res = result + (result_bytes[31] as Field);\n assert(mod_res == 0x448ebbc9e1a31220a2f3830c18eef61b9bd070e5084b7fa2a359fe729184e0);\n}\n\n#[test]\nfn unique_siloed_note_hash_matches_typescript() {\n let inner_note_hash = 1;\n let contract_address = AztecAddress::from_field(2);\n let first_nullifier = 3;\n let note_index_in_tx = 4;\n\n let siloed_note_hash = compute_siloed_note_hash(contract_address, inner_note_hash);\n let siloed_note_hash_from_ts =\n 0x1986a4bea3eddb1fff917d629a13e10f63f514f401bdd61838c6b475db949169;\n assert_eq(siloed_note_hash, siloed_note_hash_from_ts);\n\n let nonce: Field = compute_note_hash_nonce(first_nullifier, note_index_in_tx);\n let note_hash_nonce_from_ts =\n 0x28e7799791bf066a57bb51fdd0fbcaf3f0926414314c7db515ea343f44f5d58b;\n assert_eq(nonce, note_hash_nonce_from_ts);\n\n let unique_siloed_note_hash_from_nonce = compute_unique_note_hash(nonce, siloed_note_hash);\n let unique_siloed_note_hash = compute_note_nonce_and_unique_note_hash(\n siloed_note_hash,\n first_nullifier,\n note_index_in_tx,\n );\n assert_eq(unique_siloed_note_hash_from_nonce, unique_siloed_note_hash);\n\n let unique_siloed_note_hash_from_ts =\n 0x29949aef207b715303b24639737c17fbfeb375c1d965ecfa85c7e4f0febb7d16;\n assert_eq(unique_siloed_note_hash, unique_siloed_note_hash_from_ts);\n}\n\n#[test]\nfn siloed_nullifier_matches_typescript() {\n let contract_address = AztecAddress::from_field(123);\n let nullifier = 456;\n\n let res = compute_siloed_nullifier(contract_address, nullifier);\n\n let siloed_nullifier_from_ts =\n 0x169b50336c1f29afdb8a03d955a81e485f5ac7d5f0b8065673d1e407e5877813;\n\n assert_eq(res, siloed_nullifier_from_ts);\n}\n\n#[test]\nfn siloed_private_log_first_field_matches_typescript() {\n let contract_address = AztecAddress::from_field(123);\n let field = 456;\n let res = compute_siloed_private_log_first_field(contract_address, field);\n\n let siloed_private_log_first_field_from_ts =\n 0x29480984f7b9257fded523d50addbcfc8d1d33adcf2db73ef3390a8fd5cdffaa;\n\n assert_eq(res, siloed_private_log_first_field_from_ts);\n}\n\n#[test]\nfn empty_l2_to_l1_message_hash_matches_typescript() {\n // All zeroes\n let res = compute_l2_to_l1_message_hash(\n L2ToL1Message { recipient: EthAddress::zero(), content: 0 }.scope(AztecAddress::from_field(\n 0,\n )),\n 0,\n 0,\n );\n\n let empty_l2_to_l1_msg_hash_from_ts =\n 0x003b18c58c739716e76429634a61375c45b3b5cd470c22ab6d3e14cee23dd992;\n\n assert_eq(res, empty_l2_to_l1_msg_hash_from_ts);\n}\n\n#[test]\nfn l2_to_l1_message_hash_matches_typescript() {\n let message = L2ToL1Message { recipient: EthAddress::from_field(1), content: 2 }.scope(\n AztecAddress::from_field(3),\n );\n let version = 4;\n let chainId = 5;\n\n let hash = compute_l2_to_l1_message_hash(message, version, chainId);\n\n // The following value was generated by `yarn-project/stdlib/src/hash/hash.test.ts`\n let l2_to_l1_message_hash_from_ts =\n 0x0081edf209e087ad31b3fd24263698723d57190bd1d6e9fe056fc0c0a68ee661;\n\n assert_eq(hash, l2_to_l1_message_hash_from_ts);\n}\n\n#[test]\nunconstrained fn poseidon2_hash_with_separator_bounded_vec_matches_non_bounded_vec_version() {\n let inputs = BoundedVec::<Field, 4>::from_array([1, 2, 3]);\n let separator = 42;\n\n // Hash using bounded vec version\n let bounded_result = poseidon2_hash_with_separator_bounded_vec(inputs, separator);\n\n // Hash using regular version\n let regular_result = poseidon2_hash_with_separator([1, 2, 3], separator);\n\n // Results should match\n assert_eq(bounded_result, regular_result);\n}\n"
1286
+ },
1287
+ "44": {
1288
+ "function_locations": [
1289
+ {
1290
+ "name": "panic",
1291
+ "start": 196
1292
+ },
1293
+ {
1294
+ "name": "tests::panics",
1295
+ "start": 469
1296
+ }
1297
+ ],
1298
+ "path": "std/panic.nr",
1299
+ "source": "/// Halt the program at runtime with the given error message.\n///\n/// The provided error message must be either a `str` or a `fmtstr`.\npub fn panic<T, U>(message: T) -> U\nwhere\n T: StringLike,\n{\n assert(false, message);\n crate::mem::zeroed()\n}\n\ntrait StringLike {}\n\nimpl<let N: u32> StringLike for str<N> {}\nimpl<let N: u32, T> StringLike for fmtstr<N, T> {}\n\nmod tests {\n use crate::prelude::panic;\n\n #[test(should_fail_with = \"OH NO\")]\n fn panics() {\n panic(\"OH NO\");\n }\n}\n"
1300
+ },
1301
+ "443": {
1302
+ "function_locations": [
1303
+ {
1304
+ "name": "Reader<N>::new",
1305
+ "start": 144
1306
+ },
1307
+ {
1308
+ "name": "Reader<N>::read",
1309
+ "start": 222
1310
+ },
1311
+ {
1312
+ "name": "Reader<N>::read_u32",
1313
+ "start": 355
1314
+ },
1315
+ {
1316
+ "name": "Reader<N>::read_u64",
1317
+ "start": 429
1318
+ },
1319
+ {
1320
+ "name": "Reader<N>::read_bool",
1321
+ "start": 505
1322
+ },
1323
+ {
1324
+ "name": "Reader<N>::read_array",
1325
+ "start": 598
1326
+ },
1327
+ {
1328
+ "name": "Reader<N>::read_struct",
1329
+ "start": 855
1330
+ },
1331
+ {
1332
+ "name": "Reader<N>::read_struct_array",
1333
+ "start": 1094
1334
+ },
1335
+ {
1336
+ "name": "Reader<N>::peek_offset",
1337
+ "start": 1263
1338
+ },
1339
+ {
1340
+ "name": "Reader<N>::advance_offset",
1341
+ "start": 1362
1342
+ },
1343
+ {
1344
+ "name": "Reader<N>::finish",
1345
+ "start": 1426
1346
+ }
1347
+ ],
1348
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/fnd/noir-protocol-circuits/crates/serde/src/reader.nr",
1349
+ "source": "pub struct Reader<let N: u32> {\n data: [Field; N],\n offset: u32,\n}\n\nimpl<let N: u32> Reader<N> {\n pub fn new(data: [Field; N]) -> Self {\n Self { data, offset: 0 }\n }\n\n pub fn read(&mut self) -> Field {\n let result = self.data[self.offset];\n self.offset += 1;\n result\n }\n\n pub fn read_u32(&mut self) -> u32 {\n self.read() as u32\n }\n\n pub fn read_u64(&mut self) -> u64 {\n self.read() as u64\n }\n\n pub fn read_bool(&mut self) -> bool {\n self.read() != 0\n }\n\n pub fn read_array<let K: u32>(&mut self) -> [Field; K] {\n let mut result = [0; K];\n for i in 0..K {\n result[i] = self.data[self.offset + i];\n }\n self.offset += K;\n result\n }\n\n pub fn read_struct<T, let K: u32>(&mut self, deserialise: fn([Field; K]) -> T) -> T {\n let result = deserialise(self.read_array());\n result\n }\n\n pub fn read_struct_array<T, let K: u32, let C: u32>(\n &mut self,\n deserialise: fn([Field; K]) -> T,\n mut result: [T; C],\n ) -> [T; C] {\n for i in 0..C {\n result[i] = self.read_struct(deserialise);\n }\n result\n }\n\n pub fn peek_offset(&mut self, offset: u32) -> Field {\n self.data[self.offset + offset]\n }\n\n pub fn advance_offset(&mut self, offset: u32) {\n self.offset += offset;\n }\n\n pub fn finish(self) {\n assert_eq(self.offset, self.data.len(), \"Reader did not read all data\");\n }\n}\n"
1350
+ },
1351
+ "444": {
1352
+ "function_locations": [
1353
+ {
1354
+ "name": "derive_serialize",
1355
+ "start": 3018
1356
+ },
1357
+ {
1358
+ "name": "derive_deserialize",
1359
+ "start": 7208
1360
+ },
1361
+ {
1362
+ "name": "get_params_len_quote",
1363
+ "start": 10934
1364
+ },
1365
+ {
1366
+ "name": "get_generics_declarations",
1367
+ "start": 11393
1368
+ },
1369
+ {
1370
+ "name": "get_where_trait_clause",
1371
+ "start": 12477
1372
+ }
1373
+ ],
1374
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/fnd/noir-protocol-circuits/crates/serde/src/serialization.nr",
1375
+ "source": "use crate::{reader::Reader, writer::Writer};\n\n/// Trait for serializing Noir types into arrays of Fields.\n///\n/// An implementation of the Serialize trait has to follow Noir's intrinsic serialization (each member of a struct\n/// converted directly into one or more Fields without any packing or compression). This trait (and Deserialize) are\n/// typically used to communicate between Noir and TypeScript (via oracles and function arguments).\n///\n/// # On Following Noir's Intrinsic Serialization\n/// When calling a Noir function from TypeScript (TS), first the function arguments are serialized into an array\n/// of fields. This array is then included in the initial witness. Noir's intrinsic serialization is then used\n/// to deserialize the arguments from the witness. When the same Noir function is called from Noir this Serialize trait\n/// is used instead of the serialization in TS. For this reason we need to have a match between TS serialization,\n/// Noir's intrinsic serialization and the implementation of this trait. If there is a mismatch, the function calls\n/// fail with an arguments hash mismatch error message.\n///\n/// # Associated Constants\n/// * `N` - The length of the output Field array, known at compile time\n///\n/// # Example\n/// ```\n/// impl<let N: u32> Serialize for str<N> {\n/// let N: u32 = N;\n///\n/// fn serialize(self) -> [Field; Self::N] {\n/// let mut writer: Writer<Self::N> = Writer::new();\n/// self.stream_serialize(&mut writer);\n/// writer.finish()\n/// }\n///\n/// fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n/// let bytes = self.as_bytes();\n/// for i in 0..bytes.len() {\n/// writer.write(bytes[i] as Field);\n/// }\n/// }\n/// }\n/// ```\n#[derive_via(derive_serialize)]\npub trait Serialize {\n let N: u32;\n\n fn serialize(self) -> [Field; Self::N];\n\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>);\n}\n\n/// Generates a `Serialize` trait implementation for a struct type.\n///\n/// # Parameters\n/// - `s`: The struct type definition to generate the implementation for\n///\n/// # Returns\n/// A quoted code block containing the trait implementation\n///\n/// # Example\n/// For a struct defined as:\n/// ```\n/// struct Log<N> {\n/// fields: [Field; N],\n/// length: u32\n/// }\n/// ```\n///\n/// This function generates code equivalent to:\n/// ```\n/// impl<let N: u32> Serialize for Log<N> {\n/// let N: u32 = <[Field; N] as Serialize>::N + <u32 as Serialize>::N;\n///\n/// fn serialize(self) -> [Field; Self::N] {\n/// let mut writer: Writer<Self::N> = Writer::new();\n/// self.stream_serialize(&mut writer);\n/// writer.finish()\n/// }\n///\n/// #[inline_always]\n/// fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n/// Serialize::stream_serialize(self.fields, writer);\n/// Serialize::stream_serialize(self.length, writer);\n/// }\n/// }\n/// ```\npub comptime fn derive_serialize(s: TypeDefinition) -> Quoted {\n let typ = s.as_type();\n let nested_struct = typ.as_data_type().unwrap();\n\n // We care only about the name and type so we drop the last item of the tuple\n let params = nested_struct.0.fields(nested_struct.1).map(|(name, typ, _)| (name, typ));\n\n // Generates the generic parameter declarations (to be placed after the `impl` keyword) and the `where` clause\n // for the `Serialize` trait.\n let generics_declarations = get_generics_declarations(s);\n let where_serialize_clause = get_where_trait_clause(s, quote { Serialize });\n\n let params_len_quote = get_params_len_quote(params);\n\n let function_body = params\n .map(|(name, _typ): (Quoted, Type)| {\n quote {\n $crate::serialization::Serialize::stream_serialize(self.$name, writer);\n }\n })\n .join(quote {});\n\n quote {\n impl$generics_declarations $crate::serialization::Serialize for $typ\n $where_serialize_clause\n {\n let N: u32 = $params_len_quote;\n\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: $crate::writer::Writer<Self::N> = $crate::writer::Writer::new();\n $crate::serialization::Serialize::stream_serialize(self, &mut writer);\n writer.finish()\n }\n\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut $crate::writer::Writer<K>) {\n $function_body\n }\n }\n }\n}\n\n/// Trait for deserializing Noir types from arrays of Fields.\n///\n/// An implementation of the Deserialize trait has to follow Noir's intrinsic serialization (each member of a struct\n/// converted directly into one or more Fields without any packing or compression). This trait is typically used when\n/// deserializing return values from function calls in Noir. Since the same function could be called from TypeScript\n/// (TS), in which case the TS deserialization would get used, we need to have a match between the 2.\n///\n/// # Associated Constants\n/// * `N` - The length of the input Field array, known at compile time\n///\n/// # Example\n/// ```\n/// impl<let M: u32> Deserialize for str<M> {\n/// let N: u32 = M;\n///\n/// fn deserialize(fields: [Field; Self::N]) -> Self {\n/// let mut reader = Reader::new(fields);\n/// let result = Self::stream_deserialize(&mut reader);\n/// reader.finish();\n/// result\n/// }\n///\n/// fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n/// let mut bytes = [0 as u8; M];\n/// for i in 0..M {\n/// bytes[i] = reader.read() as u8;\n/// }\n/// str::<M>::from(bytes)\n/// }\n/// }\n/// ```\n#[derive_via(derive_deserialize)]\npub trait Deserialize {\n let N: u32;\n\n fn deserialize(fields: [Field; Self::N]) -> Self;\n\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self;\n}\n\n/// Generates a `Deserialize` trait implementation for a given struct `s`.\n///\n/// # Arguments\n/// * `s` - The struct type definition to generate the implementation for\n///\n/// # Returns\n/// A `Quoted` block containing the generated trait implementation\n///\n/// # Requirements\n/// Each struct member type must implement the `Deserialize` trait (it gets used in the generated code).\n///\n/// # Example\n/// For a struct like:\n/// ```\n/// struct MyStruct {\n/// x: AztecAddress,\n/// y: Field,\n/// }\n/// ```\n///\n/// This generates:\n/// ```\n/// impl Deserialize for MyStruct {\n/// let N: u32 = <AztecAddress as Deserialize>::N + <Field as Deserialize>::N;\n///\n/// fn deserialize(fields: [Field; Self::N]) -> Self {\n/// let mut reader = Reader::new(fields);\n/// let result = Self::stream_deserialize(&mut reader);\n/// reader.finish();\n/// result\n/// }\n///\n/// #[inline_always]\n/// fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n/// let x = <AztecAddress as Deserialize>::stream_deserialize(reader);\n/// let y = <Field as Deserialize>::stream_deserialize(reader);\n/// Self { x, y }\n/// }\n/// }\n/// ```\npub comptime fn derive_deserialize(s: TypeDefinition) -> Quoted {\n let typ = s.as_type();\n let nested_struct = typ.as_data_type().unwrap();\n let params = nested_struct.0.fields(nested_struct.1);\n\n // Generates the generic parameter declarations (to be placed after the `impl` keyword) and the `where` clause\n // for the `Deserialize` trait.\n let generics_declarations = get_generics_declarations(s);\n let where_deserialize_clause = get_where_trait_clause(s, quote { Deserialize });\n\n // The following will give us:\n // <type_of_struct_member_1 as Deserialize>::N + <type_of_struct_member_2 as Deserialize>::N + ...\n // (or 0 if the struct has no members)\n let right_hand_side_of_definition_of_n = if params.len() > 0 {\n params\n .map(|(_, param_type, _): (Quoted, Type, Quoted)| {\n quote {\n <$param_type as $crate::serialization::Deserialize>::N\n }\n })\n .join(quote {+})\n } else {\n quote { 0 }\n };\n\n // For structs containing a single member, we can enhance performance by directly deserializing the input array,\n // bypassing the need for loop-based array construction. While this optimization yields significant benefits in\n // Brillig where the loops are expected to not be optimized, it is not relevant in ACIR where the loops are\n // expected to be optimized away.\n let function_body = if params.len() > 1 {\n // This generates deserialization code for each struct member and concatenates them together.\n let deserialization_of_struct_members = params\n .map(|(param_name, param_type, _): (Quoted, Type, Quoted)| {\n quote {\n let $param_name = <$param_type as Deserialize>::stream_deserialize(reader);\n }\n })\n .join(quote {});\n\n // We join the struct member names with a comma to be used in the `Self { ... }` syntax\n // This will give us e.g. `a, b, c` for a struct with three fields named `a`, `b`, and `c`.\n let struct_members = params\n .map(|(param_name, _, _): (Quoted, Type, Quoted)| quote { $param_name })\n .join(quote {,});\n\n quote {\n $deserialization_of_struct_members\n\n Self { $struct_members }\n }\n } else if params.len() == 1 {\n let param_name = params[0].0;\n quote {\n Self { $param_name: $crate::serialization::Deserialize::stream_deserialize(reader) }\n }\n } else {\n quote {\n Self {}\n }\n };\n\n quote {\n impl$generics_declarations $crate::serialization::Deserialize for $typ\n $where_deserialize_clause\n {\n let N: u32 = $right_hand_side_of_definition_of_n;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = $crate::reader::Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut $crate::reader::Reader<K>) -> Self {\n $function_body\n }\n }\n }\n}\n\n/// Generates a quoted expression that computes the total serialized length of function parameters.\n///\n/// # Parameters\n/// * `params` - An array of tuples where each tuple contains a quoted parameter name and its Type. The type needs\n/// to implement the Serialize trait.\n///\n/// # Returns\n/// A quoted expression that evaluates to:\n/// * `0` if there are no parameters\n/// * `(<type1 as Serialize>::N + <type2 as Serialize>::N + ...)` for one or more parameters\ncomptime fn get_params_len_quote(params: [(Quoted, Type)]) -> Quoted {\n if params.len() == 0 {\n quote { 0 }\n } else {\n let params_quote_without_parentheses = params\n .map(|(_, param_type): (Quoted, Type)| {\n quote {\n <$param_type as $crate::serialization::Serialize>::N\n }\n })\n .join(quote {+});\n quote { ($params_quote_without_parentheses) }\n }\n}\n\ncomptime fn get_generics_declarations(s: TypeDefinition) -> Quoted {\n let generics = s.generics();\n\n if generics.len() > 0 {\n let generics_declarations_items = generics\n .map(|(name, maybe_integer_typ)| {\n // The second item in the generics tuple is an Option of an integer type that is Some only if\n // the generic is numeric.\n if maybe_integer_typ.is_some() {\n // The generic is numeric, so we return a quote defined as e.g. \"let N: u32\"\n let integer_type = maybe_integer_typ.unwrap();\n quote {let $name: $integer_type}\n } else {\n // The generic is not numeric, so we return a quote containing the name of the generic (e.g. \"T\")\n quote { $name }\n }\n })\n .join(quote {,});\n quote {<$generics_declarations_items>}\n } else {\n // The struct doesn't have any generics defined, so we just return an empty quote.\n quote {}\n }\n}\n\ncomptime fn get_where_trait_clause(s: TypeDefinition, trait_name: Quoted) -> Quoted {\n let generics = s.generics();\n\n // The second item in the generics tuple is an Option of an integer type that is Some only if the generic is\n // numeric.\n let non_numeric_generics =\n generics.filter(|(_, maybe_integer_typ)| maybe_integer_typ.is_none());\n\n if non_numeric_generics.len() > 0 {\n let non_numeric_generics_declarations =\n non_numeric_generics.map(|(name, _)| quote {$name: $trait_name}).join(quote {,});\n quote {where $non_numeric_generics_declarations}\n } else {\n // There are no non-numeric generics, so we return an empty quote.\n quote {}\n }\n}\n"
1376
+ },
1377
+ "446": {
1378
+ "function_locations": [
1379
+ {
1380
+ "name": "<impl Serialize for bool>::serialize",
1381
+ "start": 693
1382
+ },
1383
+ {
1384
+ "name": "<impl Serialize for bool>::stream_serialize",
1385
+ "start": 914
1386
+ },
1387
+ {
1388
+ "name": "<impl Deserialize for bool>::deserialize",
1389
+ "start": 1082
1390
+ },
1391
+ {
1392
+ "name": "<impl Deserialize for bool>::stream_deserialize",
1393
+ "start": 1328
1394
+ },
1395
+ {
1396
+ "name": "<impl Serialize for u8>::serialize",
1397
+ "start": 1470
1398
+ },
1399
+ {
1400
+ "name": "<impl Serialize for u8>::stream_serialize",
1401
+ "start": 1691
1402
+ },
1403
+ {
1404
+ "name": "<impl Deserialize for u8>::deserialize",
1405
+ "start": 1855
1406
+ },
1407
+ {
1408
+ "name": "<impl Deserialize for u8>::stream_deserialize",
1409
+ "start": 2101
1410
+ },
1411
+ {
1412
+ "name": "<impl Serialize for u16>::serialize",
1413
+ "start": 2246
1414
+ },
1415
+ {
1416
+ "name": "<impl Serialize for u16>::stream_serialize",
1417
+ "start": 2467
1418
+ },
1419
+ {
1420
+ "name": "<impl Deserialize for u16>::deserialize",
1421
+ "start": 2633
1422
+ },
1423
+ {
1424
+ "name": "<impl Deserialize for u16>::stream_deserialize",
1425
+ "start": 2879
1426
+ },
1427
+ {
1428
+ "name": "<impl Serialize for u32>::serialize",
1429
+ "start": 3025
1430
+ },
1431
+ {
1432
+ "name": "<impl Serialize for u32>::stream_serialize",
1433
+ "start": 3246
1434
+ },
1435
+ {
1436
+ "name": "<impl Deserialize for u32>::deserialize",
1437
+ "start": 3412
1438
+ },
1439
+ {
1440
+ "name": "<impl Deserialize for u32>::stream_deserialize",
1441
+ "start": 3658
1442
+ },
1443
+ {
1444
+ "name": "<impl Serialize for u64>::serialize",
1445
+ "start": 3804
1446
+ },
1447
+ {
1448
+ "name": "<impl Serialize for u64>::stream_serialize",
1449
+ "start": 4025
1450
+ },
1451
+ {
1452
+ "name": "<impl Deserialize for u64>::deserialize",
1453
+ "start": 4191
1454
+ },
1455
+ {
1456
+ "name": "<impl Deserialize for u64>::stream_deserialize",
1457
+ "start": 4437
1458
+ },
1459
+ {
1460
+ "name": "<impl Serialize for u128>::serialize",
1461
+ "start": 4585
1462
+ },
1463
+ {
1464
+ "name": "<impl Serialize for u128>::stream_serialize",
1465
+ "start": 4806
1466
+ },
1467
+ {
1468
+ "name": "<impl Deserialize for u128>::deserialize",
1469
+ "start": 4974
1470
+ },
1471
+ {
1472
+ "name": "<impl Deserialize for u128>::stream_deserialize",
1473
+ "start": 5220
1474
+ },
1475
+ {
1476
+ "name": "<impl Serialize for Field>::serialize",
1477
+ "start": 5371
1478
+ },
1479
+ {
1480
+ "name": "<impl Serialize for Field>::stream_serialize",
1481
+ "start": 5592
1482
+ },
1483
+ {
1484
+ "name": "<impl Deserialize for Field>::deserialize",
1485
+ "start": 5753
1486
+ },
1487
+ {
1488
+ "name": "<impl Deserialize for Field>::stream_deserialize",
1489
+ "start": 5999
1490
+ },
1491
+ {
1492
+ "name": "<impl Serialize for i8>::serialize",
1493
+ "start": 6136
1494
+ },
1495
+ {
1496
+ "name": "<impl Serialize for i8>::stream_serialize",
1497
+ "start": 6357
1498
+ },
1499
+ {
1500
+ "name": "<impl Deserialize for i8>::deserialize",
1501
+ "start": 6527
1502
+ },
1503
+ {
1504
+ "name": "<impl Deserialize for i8>::stream_deserialize",
1505
+ "start": 6773
1506
+ },
1507
+ {
1508
+ "name": "<impl Serialize for i16>::serialize",
1509
+ "start": 6924
1510
+ },
1511
+ {
1512
+ "name": "<impl Serialize for i16>::stream_serialize",
1513
+ "start": 7145
1514
+ },
1515
+ {
1516
+ "name": "<impl Deserialize for i16>::deserialize",
1517
+ "start": 7318
1518
+ },
1519
+ {
1520
+ "name": "<impl Deserialize for i16>::stream_deserialize",
1521
+ "start": 7564
1522
+ },
1523
+ {
1524
+ "name": "<impl Serialize for i32>::serialize",
1525
+ "start": 7717
1526
+ },
1527
+ {
1528
+ "name": "<impl Serialize for i32>::stream_serialize",
1529
+ "start": 7938
1530
+ },
1531
+ {
1532
+ "name": "<impl Deserialize for i32>::deserialize",
1533
+ "start": 8111
1534
+ },
1535
+ {
1536
+ "name": "<impl Deserialize for i32>::stream_deserialize",
1537
+ "start": 8357
1538
+ },
1539
+ {
1540
+ "name": "<impl Serialize for i64>::serialize",
1541
+ "start": 8510
1542
+ },
1543
+ {
1544
+ "name": "<impl Serialize for i64>::stream_serialize",
1545
+ "start": 8731
1546
+ },
1547
+ {
1548
+ "name": "<impl Deserialize for i64>::deserialize",
1549
+ "start": 8904
1550
+ },
1551
+ {
1552
+ "name": "<impl Deserialize for i64>::stream_deserialize",
1553
+ "start": 9150
1554
+ },
1555
+ {
1556
+ "name": "<impl Serialize for [T; M]>::serialize",
1557
+ "start": 9350
1558
+ },
1559
+ {
1560
+ "name": "<impl Serialize for [T; M]>::stream_serialize",
1561
+ "start": 9571
1562
+ },
1563
+ {
1564
+ "name": "<impl Deserialize for [T; M]>::deserialize",
1565
+ "start": 9831
1566
+ },
1567
+ {
1568
+ "name": "<impl Deserialize for [T; M]>::stream_deserialize",
1569
+ "start": 10077
1570
+ },
1571
+ {
1572
+ "name": "<impl Serialize for Option<T>>::serialize",
1573
+ "start": 10389
1574
+ },
1575
+ {
1576
+ "name": "<impl Serialize for Option<T>>::stream_serialize",
1577
+ "start": 10610
1578
+ },
1579
+ {
1580
+ "name": "<impl Deserialize for Option<T>>::deserialize",
1581
+ "start": 10997
1582
+ },
1583
+ {
1584
+ "name": "<impl Deserialize for Option<T>>::stream_deserialize",
1585
+ "start": 11243
1586
+ },
1587
+ {
1588
+ "name": "<impl Serialize for EmbeddedCurveScalar>::serialize",
1589
+ "start": 11621
1590
+ },
1591
+ {
1592
+ "name": "<impl Serialize for EmbeddedCurveScalar>::stream_serialize",
1593
+ "start": 11744
1594
+ },
1595
+ {
1596
+ "name": "<impl Deserialize for EmbeddedCurveScalar>::deserialize",
1597
+ "start": 11944
1598
+ },
1599
+ {
1600
+ "name": "<impl Deserialize for EmbeddedCurveScalar>::stream_deserialize",
1601
+ "start": 12090
1602
+ },
1603
+ {
1604
+ "name": "<impl Serialize for EmbeddedCurvePoint>::serialize",
1605
+ "start": 12297
1606
+ },
1607
+ {
1608
+ "name": "<impl Serialize for EmbeddedCurvePoint>::stream_serialize",
1609
+ "start": 12397
1610
+ },
1611
+ {
1612
+ "name": "<impl Deserialize for EmbeddedCurvePoint>::deserialize",
1613
+ "start": 12593
1614
+ },
1615
+ {
1616
+ "name": "<impl Deserialize for EmbeddedCurvePoint>::stream_deserialize",
1617
+ "start": 12737
1618
+ },
1619
+ {
1620
+ "name": "<impl Deserialize for str<M>>::deserialize",
1621
+ "start": 12916
1622
+ },
1623
+ {
1624
+ "name": "<impl Deserialize for str<M>>::stream_deserialize",
1625
+ "start": 13162
1626
+ },
1627
+ {
1628
+ "name": "<impl Serialize for str<M>>::serialize",
1629
+ "start": 13395
1630
+ },
1631
+ {
1632
+ "name": "<impl Serialize for str<M>>::stream_serialize",
1633
+ "start": 13616
1634
+ },
1635
+ {
1636
+ "name": "<impl Deserialize for BoundedVec<T, M>>::deserialize",
1637
+ "start": 13997
1638
+ },
1639
+ {
1640
+ "name": "<impl Deserialize for BoundedVec<T, M>>::stream_deserialize",
1641
+ "start": 14243
1642
+ },
1643
+ {
1644
+ "name": "<impl Deserialize for ()>::deserialize",
1645
+ "start": 15299
1646
+ },
1647
+ {
1648
+ "name": "<impl Deserialize for ()>::stream_deserialize",
1649
+ "start": 15546
1650
+ },
1651
+ {
1652
+ "name": "<impl Serialize for BoundedVec<T, M>>::serialize",
1653
+ "start": 15911
1654
+ },
1655
+ {
1656
+ "name": "<impl Serialize for BoundedVec<T, M>>::stream_serialize",
1657
+ "start": 16132
1658
+ },
1659
+ {
1660
+ "name": "make_slice",
1661
+ "start": 16617
1662
+ },
1663
+ {
1664
+ "name": "impl_serialize_for_tuple",
1665
+ "start": 16867
1666
+ },
1667
+ {
1668
+ "name": "<impl Serialize for (T1,)>::serialize",
1669
+ "start": 20178
1670
+ },
1671
+ {
1672
+ "name": "<impl Serialize for (T1,)>::stream_serialize",
1673
+ "start": 20429
1674
+ },
1675
+ {
1676
+ "name": "<impl Deserialize for (T1,)>::deserialize",
1677
+ "start": 20636
1678
+ },
1679
+ {
1680
+ "name": "<impl Deserialize for (T1,)>::stream_deserialize",
1681
+ "start": 20897
1682
+ },
1683
+ {
1684
+ "name": "bounded_vec_serialization",
1685
+ "start": 21246
1686
+ }
1687
+ ],
1688
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/fnd/noir-protocol-circuits/crates/serde/src/type_impls.nr",
1689
+ "source": "use crate::{reader::Reader, serialization::{Deserialize, Serialize}, writer::Writer};\nuse std::embedded_curve_ops::EmbeddedCurvePoint;\nuse std::embedded_curve_ops::EmbeddedCurveScalar;\n\nglobal BOOL_SERIALIZED_LEN: u32 = 1;\nglobal U8_SERIALIZED_LEN: u32 = 1;\nglobal U16_SERIALIZED_LEN: u32 = 1;\nglobal U32_SERIALIZED_LEN: u32 = 1;\nglobal U64_SERIALIZED_LEN: u32 = 1;\nglobal U128_SERIALIZED_LEN: u32 = 1;\nglobal FIELD_SERIALIZED_LEN: u32 = 1;\nglobal I8_SERIALIZED_LEN: u32 = 1;\nglobal I16_SERIALIZED_LEN: u32 = 1;\nglobal I32_SERIALIZED_LEN: u32 = 1;\nglobal I64_SERIALIZED_LEN: u32 = 1;\n\nimpl Serialize for bool {\n let N: u32 = BOOL_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as Field);\n }\n}\n\nimpl Deserialize for bool {\n let N: u32 = BOOL_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> bool {\n reader.read() != 0\n }\n}\n\nimpl Serialize for u8 {\n let N: u32 = U8_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as Field);\n }\n}\n\nimpl Deserialize for u8 {\n let N: u32 = U8_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read() as u8\n }\n}\n\nimpl Serialize for u16 {\n let N: u32 = U16_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as Field);\n }\n}\n\nimpl Deserialize for u16 {\n let N: u32 = U16_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read() as u16\n }\n}\n\nimpl Serialize for u32 {\n let N: u32 = U32_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as Field);\n }\n}\n\nimpl Deserialize for u32 {\n let N: u32 = U32_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read() as u32\n }\n}\n\nimpl Serialize for u64 {\n let N: u32 = U64_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as Field);\n }\n}\n\nimpl Deserialize for u64 {\n let N: u32 = U64_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read() as u64\n }\n}\n\nimpl Serialize for u128 {\n let N: u32 = U128_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as Field);\n }\n}\n\nimpl Deserialize for u128 {\n let N: u32 = U128_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read() as u128\n }\n}\n\nimpl Serialize for Field {\n let N: u32 = FIELD_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self);\n }\n}\n\nimpl Deserialize for Field {\n let N: u32 = FIELD_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read()\n }\n}\n\nimpl Serialize for i8 {\n let N: u32 = I8_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as u8 as Field);\n }\n}\n\nimpl Deserialize for i8 {\n let N: u32 = I8_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read() as u8 as i8\n }\n}\n\nimpl Serialize for i16 {\n let N: u32 = I16_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as u16 as Field);\n }\n}\n\nimpl Deserialize for i16 {\n let N: u32 = I16_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read() as u16 as i16\n }\n}\n\nimpl Serialize for i32 {\n let N: u32 = I32_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as u32 as Field);\n }\n}\n\nimpl Deserialize for i32 {\n let N: u32 = I32_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read() as u32 as i32\n }\n}\n\nimpl Serialize for i64 {\n let N: u32 = I64_SERIALIZED_LEN;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self as u64 as Field);\n }\n}\n\nimpl Deserialize for i64 {\n let N: u32 = I64_SERIALIZED_LEN;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n reader.read() as u64 as i64\n }\n}\n\nimpl<T, let M: u32> Serialize for [T; M]\nwhere\n T: Serialize,\n{\n let N: u32 = <T as Serialize>::N * M;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n for i in 0..M {\n self[i].stream_serialize(writer);\n }\n }\n}\n\nimpl<T, let M: u32> Deserialize for [T; M]\nwhere\n T: Deserialize,\n{\n let N: u32 = <T as Deserialize>::N * M;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n let mut result: [T; M] = std::mem::zeroed();\n for i in 0..M {\n result[i] = T::stream_deserialize(reader);\n }\n result\n }\n}\n\nimpl<T> Serialize for Option<T>\nwhere\n T: Serialize,\n{\n let N: u32 = <T as Serialize>::N + 1;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write_bool(self.is_some());\n if self.is_some() {\n self.unwrap_unchecked().stream_serialize(writer);\n } else {\n writer.advance_offset(<T as Serialize>::N);\n }\n }\n}\n\nimpl<T> Deserialize for Option<T>\nwhere\n T: Deserialize,\n{\n let N: u32 = <T as Deserialize>::N + 1;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n if reader.read_bool() {\n Option::some(<T as Deserialize>::stream_deserialize(reader))\n } else {\n reader.advance_offset(<T as Deserialize>::N);\n Option::none()\n }\n }\n}\n\nglobal SCALAR_SIZE: u32 = 2;\n\nimpl Serialize for EmbeddedCurveScalar {\n\n let N: u32 = SCALAR_SIZE;\n\n fn serialize(self) -> [Field; SCALAR_SIZE] {\n [self.lo, self.hi]\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self.lo);\n writer.write(self.hi);\n }\n}\n\nimpl Deserialize for EmbeddedCurveScalar {\n let N: u32 = SCALAR_SIZE;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n Self { lo: fields[0], hi: fields[1] }\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n Self { lo: reader.read(), hi: reader.read() }\n }\n}\n\nglobal POINT_SIZE: u32 = 2;\n\nimpl Serialize for EmbeddedCurvePoint {\n let N: u32 = POINT_SIZE;\n\n fn serialize(self) -> [Field; Self::N] {\n [self.x, self.y]\n }\n\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self.x);\n writer.write(self.y);\n }\n}\n\nimpl Deserialize for EmbeddedCurvePoint {\n let N: u32 = POINT_SIZE;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n Self { x: fields[0], y: fields[1] }\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n Self { x: reader.read(), y: reader.read() }\n }\n}\n\nimpl<let M: u32> Deserialize for str<M> {\n let N: u32 = M;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n let u8_arr = <[u8; Self::N] as Deserialize>::stream_deserialize(reader);\n str::<Self::N>::from(u8_arr)\n }\n}\n\nimpl<let M: u32> Serialize for str<M> {\n let N: u32 = M;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n self.as_bytes().stream_serialize(writer);\n }\n}\n\n// Note: Not deriving this because it's not supported to call derive_serialize on a \"remote\" struct (and it will never\n// be supported).\nimpl<T, let M: u32> Deserialize for BoundedVec<T, M>\nwhere\n T: Deserialize,\n{\n let N: u32 = <T as Deserialize>::N * M + 1;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n let mut new_bounded_vec: BoundedVec<T, M> = BoundedVec::new();\n let payload_len = Self::N - 1;\n\n // Length is stored in the last field as we need to match intrinsic Noir serialization and the `len` struct\n // field is after `storage` struct field (see `bounded_vec.nr` in noir-stdlib)\n let len = reader.peek_offset(payload_len) as u32;\n\n for i in 0..M {\n if i < len {\n new_bounded_vec.push(<T as Deserialize>::stream_deserialize(reader));\n }\n }\n\n // +1 for the length of the BoundedVec\n reader.advance_offset((M - len) * <T as Deserialize>::N + 1);\n\n new_bounded_vec\n }\n}\n\n// This may cause issues if used as program input, because noir disallows empty arrays for program input.\n// I think this is okay because I don't foresee a unit type being used as input. But leaving this comment as a hint\n// if someone does run into this in the future.\nimpl Deserialize for () {\n let N: u32 = 0;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(_reader: &mut Reader<K>) -> Self {\n ()\n }\n}\n\n// Note: Not deriving this because it's not supported to call derive_serialize on a \"remote\" struct (and it will never\n// be supported).\nimpl<T, let M: u32> Serialize for BoundedVec<T, M>\nwhere\n T: Serialize,\n{\n let N: u32 = <T as Serialize>::N * M + 1; // +1 for the length of the BoundedVec\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: Writer<Self::N> = Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n self.storage().stream_serialize(writer);\n // Length is stored in the last field as we need to match intrinsic Noir serialization and the `len` struct\n // field is after `storage` struct field (see `bounded_vec.nr` in noir-stdlib)\n writer.write_u32(self.len() as u32);\n }\n}\n\n// Create a slice of the given length with each element made from `f(i)` where `i` is the current index\ncomptime fn make_slice<Env, T>(length: u32, f: fn[Env](u32) -> T) -> [T] {\n let mut slice = @[];\n for i in 0..length {\n slice = slice.push_back(f(i));\n }\n slice\n}\n\n// Implements Serialize and Deserialize for an arbitrary tuple type\ncomptime fn impl_serialize_for_tuple(_m: Module, length: u32) -> Quoted {\n // `T0`, `T1`, `T2`\n let type_names = make_slice(length, |i| f\"T{i}\".quoted_contents());\n\n // `result0`, `result1`, `result2`\n let result_names = make_slice(length, |i| f\"result{i}\".quoted_contents());\n\n // `T0, T1, T2`\n let field_generics = type_names.join(quote [,]);\n\n // `<T0 as Serialize>::N + <T1 as Serialize>::N + <T2 as Serialize>::N`\n let full_size_serialize = type_names\n .map(|type_name| quote {\n <$type_name as Serialize>::N\n })\n .join(quote [+]);\n\n // `<T0 as Deserialize>::N + <T1 as Deserialize>::N + <T2 as Deserialize>::N`\n let full_size_deserialize = type_names\n .map(|type_name| quote {\n <$type_name as Deserialize>::N\n })\n .join(quote [+]);\n\n // `T0: Serialize, T1: Serialize, T2: Serialize,`\n let serialize_constraints = type_names\n .map(|field_name| quote {\n $field_name: Serialize,\n })\n .join(quote []);\n\n // `T0: Deserialize, T1: Deserialize, T2: Deserialize,`\n let deserialize_constraints = type_names\n .map(|field_name| quote {\n $field_name: Deserialize,\n })\n .join(quote []);\n\n // Statements to serialize each field\n let serialized_fields = type_names\n .mapi(|i, _type_name| quote {\n $crate::serialization::Serialize::stream_serialize(self.$i, writer);\n })\n .join(quote []);\n\n // Statements to deserialize each field\n let deserialized_fields = type_names\n .mapi(|i, type_name| {\n let result_name = result_names[i];\n quote {\n let $result_name = <$type_name as $crate::serialization::Deserialize>::stream_deserialize(reader);\n }\n })\n .join(quote []);\n let deserialize_results = result_names.join(quote [,]);\n\n quote {\n impl<$field_generics> Serialize for ($field_generics) where $serialize_constraints {\n let N: u32 = $full_size_serialize;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: $crate::writer::Writer<Self::N> = $crate::writer::Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut $crate::writer::Writer<K>) {\n\n $serialized_fields\n }\n }\n\n impl<$field_generics> Deserialize for ($field_generics) where $deserialize_constraints {\n let N: u32 = $full_size_deserialize;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = $crate::reader::Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n \n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut $crate::reader::Reader<K>) -> Self {\n $deserialized_fields\n ($deserialize_results)\n }\n }\n }\n}\n\n// Keeping these manual impls. They are more efficient since they do not\n// require copying sub-arrays from any serialized arrays.\nimpl<T1> Serialize for (T1,)\nwhere\n T1: Serialize,\n{\n let N: u32 = <T1 as Serialize>::N;\n\n fn serialize(self) -> [Field; Self::N] {\n let mut writer: crate::writer::Writer<Self::N> = crate::writer::Writer::new();\n self.stream_serialize(&mut writer);\n writer.finish()\n }\n\n #[inline_always]\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n self.0.stream_serialize(writer);\n }\n}\n\nimpl<T1> Deserialize for (T1,)\nwhere\n T1: Deserialize,\n{\n let N: u32 = <T1 as Deserialize>::N;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n let mut reader = crate::reader::Reader::new(fields);\n let result = Self::stream_deserialize(&mut reader);\n reader.finish();\n result\n }\n\n #[inline_always]\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n (<T1 as Deserialize>::stream_deserialize(reader),)\n }\n}\n\n#[impl_serialize_for_tuple(2)]\n#[impl_serialize_for_tuple(3)]\n#[impl_serialize_for_tuple(4)]\n#[impl_serialize_for_tuple(5)]\n#[impl_serialize_for_tuple(6)]\nmod impls {\n use crate::serialization::{Deserialize, Serialize};\n}\n\n#[test]\nunconstrained fn bounded_vec_serialization() {\n // Test empty BoundedVec\n let empty_vec: BoundedVec<Field, 3> = BoundedVec::from_array([]);\n let serialized = empty_vec.serialize();\n let deserialized = BoundedVec::<Field, 3>::deserialize(serialized);\n assert_eq(empty_vec, deserialized);\n assert_eq(deserialized.len(), 0);\n\n // Test partially filled BoundedVec\n let partial_vec: BoundedVec<[u32; 2], 3> = BoundedVec::from_array([[1, 2]]);\n let serialized = partial_vec.serialize();\n let deserialized = BoundedVec::<[u32; 2], 3>::deserialize(serialized);\n assert_eq(partial_vec, deserialized);\n assert_eq(deserialized.len(), 1);\n assert_eq(deserialized.get(0), [1, 2]);\n\n // Test full BoundedVec\n let full_vec: BoundedVec<[u32; 2], 3> = BoundedVec::from_array([[1, 2], [3, 4], [5, 6]]);\n let serialized = full_vec.serialize();\n let deserialized = BoundedVec::<[u32; 2], 3>::deserialize(serialized);\n assert_eq(full_vec, deserialized);\n assert_eq(deserialized.len(), 3);\n assert_eq(deserialized.get(0), [1, 2]);\n assert_eq(deserialized.get(1), [3, 4]);\n assert_eq(deserialized.get(2), [5, 6]);\n}\n"
1690
+ },
1691
+ "447": {
1692
+ "function_locations": [
1693
+ {
1694
+ "name": "Writer<N>::new",
1695
+ "start": 128
1696
+ },
1697
+ {
1698
+ "name": "Writer<N>::write",
1699
+ "start": 220
1700
+ },
1701
+ {
1702
+ "name": "Writer<N>::write_u32",
1703
+ "start": 339
1704
+ },
1705
+ {
1706
+ "name": "Writer<N>::write_u64",
1707
+ "start": 428
1708
+ },
1709
+ {
1710
+ "name": "Writer<N>::write_bool",
1711
+ "start": 519
1712
+ },
1713
+ {
1714
+ "name": "Writer<N>::write_array",
1715
+ "start": 629
1716
+ },
1717
+ {
1718
+ "name": "Writer<N>::write_struct",
1719
+ "start": 841
1720
+ },
1721
+ {
1722
+ "name": "Writer<N>::write_struct_array",
1723
+ "start": 1040
1724
+ },
1725
+ {
1726
+ "name": "Writer<N>::advance_offset",
1727
+ "start": 1185
1728
+ },
1729
+ {
1730
+ "name": "Writer<N>::finish",
1731
+ "start": 1263
1732
+ }
1733
+ ],
1734
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/fnd/noir-protocol-circuits/crates/serde/src/writer.nr",
1735
+ "source": "pub struct Writer<let N: u32> {\n data: [Field; N],\n offset: u32,\n}\n\nimpl<let N: u32> Writer<N> {\n pub fn new() -> Self {\n Self { data: [0; N], offset: 0 }\n }\n\n pub fn write(&mut self, value: Field) {\n self.data[self.offset] = value;\n self.offset += 1;\n }\n\n pub fn write_u32(&mut self, value: u32) {\n self.write(value as Field);\n }\n\n pub fn write_u64(&mut self, value: u64) {\n self.write(value as Field);\n }\n\n pub fn write_bool(&mut self, value: bool) {\n self.write(value as Field);\n }\n\n pub fn write_array<let K: u32>(&mut self, value: [Field; K]) {\n for i in 0..K {\n self.data[i + self.offset] = value[i];\n }\n self.offset += K;\n }\n\n pub fn write_struct<T, let K: u32>(&mut self, value: T, serialize: fn(T) -> [Field; K]) {\n self.write_array(serialize(value));\n }\n\n pub fn write_struct_array<T, let K: u32, let C: u32>(\n &mut self,\n value: [T; C],\n serialize: fn(T) -> [Field; K],\n ) {\n for i in 0..C {\n self.write_struct(value[i], serialize);\n }\n }\n\n pub fn advance_offset(&mut self, offset: u32) {\n self.offset += offset;\n }\n\n pub fn finish(self) -> [Field; N] {\n assert_eq(self.offset, self.data.len(), \"Writer did not write all data\");\n self.data\n }\n}\n"
1736
+ },
1737
+ "52": {
1738
+ "function_locations": [
1739
+ {
1740
+ "name": "PublicChecks::check_timestamp",
1741
+ "start": 969
1742
+ },
1743
+ {
1744
+ "name": "PublicChecks::check_block_number",
1745
+ "start": 1482
1746
+ }
1747
+ ],
1748
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/noir-contracts/contracts/standard/public_checks_contract/src/main.nr",
1749
+ "source": "mod test;\n\nuse aztec::{macros::{aztec, AztecConfig}, messages::discovery::do_sync_state_no_op};\n\n/// The purpose of this contract is to perform a check in public without revealing what contract enqueued the public\n/// call. This can be achieved by enqueueing an `incognito` public call.\n///\n/// Note that this contract should not be grouped with protocol contracts as it is not part of the protocol. We keep\n/// it here for now as it allows us to use hardcoded address.\n#[aztec(AztecConfig::new().custom_sync_state(do_sync_state_no_op))]\npub contract PublicChecks {\n use aztec::{macros::functions::{external, view}, utils::comparison::compare};\n\n // docs:start:check_timestamp\n /// Asserts that the current timestamp satisfies the `operation` with respect\n /// to the `value.\n /// NOTE: signature is hardcoded in `aztec-nr/aztec/src/public_checks.nr`; keep in sync.\n #[external(\"public\")]\n #[view]\n fn check_timestamp(operation: u8, value: u64) {\n let lhs_field = self.context.timestamp() as Field;\n let rhs_field = value as Field;\n assert(compare(lhs_field, operation, rhs_field), \"Timestamp mismatch.\");\n }\n // docs:end:check_timestamp\n\n /// Asserts that the current block number satisfies the `operation` with respect\n /// to the `value.\n /// NOTE: signature is hardcoded in `aztec-nr/aztec/src/public_checks.nr`; keep in sync.\n #[external(\"public\")]\n #[view]\n fn check_block_number(operation: u8, value: u32) {\n assert(\n compare(\n self.context.block_number() as Field,\n operation,\n value as Field,\n ),\n \"Block number mismatch.\",\n );\n }\n}\n"
1750
+ },
1751
+ "6": {
1752
+ "function_locations": [
1753
+ {
1754
+ "name": "BoundedVec<T, MaxLen>::new",
1755
+ "start": 2304
1756
+ },
1757
+ {
1758
+ "name": "BoundedVec<T, MaxLen>::get",
1759
+ "start": 2907
1760
+ },
1761
+ {
1762
+ "name": "BoundedVec<T, MaxLen>::get_unchecked",
1763
+ "start": 3815
1764
+ },
1765
+ {
1766
+ "name": "BoundedVec<T, MaxLen>::set",
1767
+ "start": 4398
1768
+ },
1769
+ {
1770
+ "name": "BoundedVec<T, MaxLen>::set_unchecked",
1771
+ "start": 5926
1772
+ },
1773
+ {
1774
+ "name": "BoundedVec<T, MaxLen>::push",
1775
+ "start": 6464
1776
+ },
1777
+ {
1778
+ "name": "BoundedVec<T, MaxLen>::len",
1779
+ "start": 7072
1780
+ },
1781
+ {
1782
+ "name": "BoundedVec<T, MaxLen>::set_len",
1783
+ "start": 7970
1784
+ },
1785
+ {
1786
+ "name": "BoundedVec<T, MaxLen>::truncate",
1787
+ "start": 8742
1788
+ },
1789
+ {
1790
+ "name": "BoundedVec<T, MaxLen>::max_len",
1791
+ "start": 9234
1792
+ },
1793
+ {
1794
+ "name": "BoundedVec<T, MaxLen>::storage",
1795
+ "start": 9832
1796
+ },
1797
+ {
1798
+ "name": "BoundedVec<T, MaxLen>::extend_from_array",
1799
+ "start": 10388
1800
+ },
1801
+ {
1802
+ "name": "BoundedVec<T, MaxLen>::extend_from_vector",
1803
+ "start": 11159
1804
+ },
1805
+ {
1806
+ "name": "BoundedVec<T, MaxLen>::extend_from_bounded_vec",
1807
+ "start": 12104
1808
+ },
1809
+ {
1810
+ "name": "BoundedVec<T, MaxLen>::from_array",
1811
+ "start": 13251
1812
+ },
1813
+ {
1814
+ "name": "BoundedVec<T, MaxLen>::pop",
1815
+ "start": 13994
1816
+ },
1817
+ {
1818
+ "name": "BoundedVec<T, MaxLen>::any",
1819
+ "start": 14536
1820
+ },
1821
+ {
1822
+ "name": "BoundedVec<T, MaxLen>::map",
1823
+ "start": 15452
1824
+ },
1825
+ {
1826
+ "name": "BoundedVec<T, MaxLen>::mapi",
1827
+ "start": 16387
1828
+ },
1829
+ {
1830
+ "name": "BoundedVec<T, MaxLen>::for_each",
1831
+ "start": 17280
1832
+ },
1833
+ {
1834
+ "name": "BoundedVec<T, MaxLen>::for_eachi",
1835
+ "start": 18085
1836
+ },
1837
+ {
1838
+ "name": "BoundedVec<T, MaxLen>::from_parts",
1839
+ "start": 18778
1840
+ },
1841
+ {
1842
+ "name": "BoundedVec<T, MaxLen>::from_parts_unchecked",
1843
+ "start": 20242
1844
+ },
1845
+ {
1846
+ "name": "<impl Eq for BoundedVec<T, MaxLen>>::eq",
1847
+ "start": 20454
1848
+ },
1849
+ {
1850
+ "name": "unconstrained_eq",
1851
+ "start": 21378
1852
+ },
1853
+ {
1854
+ "name": "<impl From<[T; Len]> for BoundedVec<T, MaxLen>>::from",
1855
+ "start": 21674
1856
+ },
1857
+ {
1858
+ "name": "bounded_vec_tests::get::panics_when_reading_elements_past_end_of_vec",
1859
+ "start": 21957
1860
+ },
1861
+ {
1862
+ "name": "bounded_vec_tests::get::panics_when_reading_beyond_length",
1863
+ "start": 22192
1864
+ },
1865
+ {
1866
+ "name": "bounded_vec_tests::get::get_works_within_bounds",
1867
+ "start": 22367
1868
+ },
1869
+ {
1870
+ "name": "bounded_vec_tests::get::get_unchecked_works",
1871
+ "start": 22626
1872
+ },
1873
+ {
1874
+ "name": "bounded_vec_tests::get::get_unchecked_works_past_len",
1875
+ "start": 22870
1876
+ },
1877
+ {
1878
+ "name": "bounded_vec_tests::set::set_updates_values_properly",
1879
+ "start": 23143
1880
+ },
1881
+ {
1882
+ "name": "bounded_vec_tests::set::panics_when_writing_elements_past_end_of_vec",
1883
+ "start": 23781
1884
+ },
1885
+ {
1886
+ "name": "bounded_vec_tests::set::panics_when_setting_beyond_length",
1887
+ "start": 24016
1888
+ },
1889
+ {
1890
+ "name": "bounded_vec_tests::set::set_unchecked_operations",
1891
+ "start": 24191
1892
+ },
1893
+ {
1894
+ "name": "bounded_vec_tests::set::set_unchecked_operations_past_len",
1895
+ "start": 24523
1896
+ },
1897
+ {
1898
+ "name": "bounded_vec_tests::set::set_preserves_other_elements",
1899
+ "start": 24787
1900
+ },
1901
+ {
1902
+ "name": "bounded_vec_tests::set_len::set_len_works_after_multiple_unchecked_sets",
1903
+ "start": 25262
1904
+ },
1905
+ {
1906
+ "name": "bounded_vec_tests::set_len::set_len_can_reduce_the_length",
1907
+ "start": 26109
1908
+ },
1909
+ {
1910
+ "name": "bounded_vec_tests::set_len::panics_when_set_len_beyond_max_len",
1911
+ "start": 26660
1912
+ },
1913
+ {
1914
+ "name": "bounded_vec_tests::truncate::truncate_shortens_to_len",
1915
+ "start": 26919
1916
+ },
1917
+ {
1918
+ "name": "bounded_vec_tests::truncate::truncate_to_zero_empties_the_vec",
1919
+ "start": 27280
1920
+ },
1921
+ {
1922
+ "name": "bounded_vec_tests::truncate::truncate_to_equal_len_is_noop",
1923
+ "start": 27500
1924
+ },
1925
+ {
1926
+ "name": "bounded_vec_tests::truncate::truncate_to_greater_len_is_noop",
1927
+ "start": 27722
1928
+ },
1929
+ {
1930
+ "name": "bounded_vec_tests::truncate::truncate_beyond_max_len_is_noop",
1931
+ "start": 27944
1932
+ },
1933
+ {
1934
+ "name": "bounded_vec_tests::truncate::truncate_does_not_zero_remaining_storage",
1935
+ "start": 28176
1936
+ },
1937
+ {
1938
+ "name": "bounded_vec_tests::truncate::truncate_then_push_continues_from_new_len",
1939
+ "start": 28631
1940
+ },
1941
+ {
1942
+ "name": "bounded_vec_tests::any::returns_false_if_predicate_not_satisfied",
1943
+ "start": 29184
1944
+ },
1945
+ {
1946
+ "name": "bounded_vec_tests::any::returns_true_if_predicate_satisfied",
1947
+ "start": 29468
1948
+ },
1949
+ {
1950
+ "name": "bounded_vec_tests::any::returns_false_on_empty_boundedvec",
1951
+ "start": 29717
1952
+ },
1953
+ {
1954
+ "name": "bounded_vec_tests::any::any_with_complex_predicates",
1955
+ "start": 29958
1956
+ },
1957
+ {
1958
+ "name": "bounded_vec_tests::any::any_with_partial_vector",
1959
+ "start": 30321
1960
+ },
1961
+ {
1962
+ "name": "bounded_vec_tests::map::applies_function_correctly",
1963
+ "start": 30787
1964
+ },
1965
+ {
1966
+ "name": "bounded_vec_tests::map::applies_function_that_changes_return_type",
1967
+ "start": 31209
1968
+ },
1969
+ {
1970
+ "name": "bounded_vec_tests::map::does_not_apply_function_past_len",
1971
+ "start": 31557
1972
+ },
1973
+ {
1974
+ "name": "bounded_vec_tests::map::map_with_conditional_logic",
1975
+ "start": 31930
1976
+ },
1977
+ {
1978
+ "name": "bounded_vec_tests::map::map_preserves_length",
1979
+ "start": 32254
1980
+ },
1981
+ {
1982
+ "name": "bounded_vec_tests::map::map_on_empty_vector",
1983
+ "start": 32546
1984
+ },
1985
+ {
1986
+ "name": "bounded_vec_tests::mapi::applies_function_correctly",
1987
+ "start": 32999
1988
+ },
1989
+ {
1990
+ "name": "bounded_vec_tests::mapi::applies_function_that_changes_return_type",
1991
+ "start": 33432
1992
+ },
1993
+ {
1994
+ "name": "bounded_vec_tests::mapi::does_not_apply_function_past_len",
1995
+ "start": 33789
1996
+ },
1997
+ {
1998
+ "name": "bounded_vec_tests::mapi::mapi_with_index_branching_logic",
1999
+ "start": 34171
2000
+ },
2001
+ {
2002
+ "name": "bounded_vec_tests::for_each::for_each_map",
2003
+ "start": 34779
2004
+ },
2005
+ {
2006
+ "name": "bounded_vec_tests::for_each::smoke_test",
2007
+ "start": 35039
2008
+ },
2009
+ {
2010
+ "name": "bounded_vec_tests::for_each::applies_function_correctly",
2011
+ "start": 35447
2012
+ },
2013
+ {
2014
+ "name": "bounded_vec_tests::for_each::applies_function_that_changes_return_type",
2015
+ "start": 35781
2016
+ },
2017
+ {
2018
+ "name": "bounded_vec_tests::for_each::does_not_apply_function_past_len",
2019
+ "start": 36139
2020
+ },
2021
+ {
2022
+ "name": "bounded_vec_tests::for_each::for_each_on_empty_vector",
2023
+ "start": 36520
2024
+ },
2025
+ {
2026
+ "name": "bounded_vec_tests::for_each::for_each_with_side_effects",
2027
+ "start": 36806
2028
+ },
2029
+ {
2030
+ "name": "bounded_vec_tests::for_eachi::for_eachi_mapi",
2031
+ "start": 37412
2032
+ },
2033
+ {
2034
+ "name": "bounded_vec_tests::for_eachi::smoke_test",
2035
+ "start": 37679
2036
+ },
2037
+ {
2038
+ "name": "bounded_vec_tests::for_eachi::applies_function_correctly",
2039
+ "start": 38135
2040
+ },
2041
+ {
2042
+ "name": "bounded_vec_tests::for_eachi::applies_function_that_changes_return_type",
2043
+ "start": 38479
2044
+ },
2045
+ {
2046
+ "name": "bounded_vec_tests::for_eachi::does_not_apply_function_past_len",
2047
+ "start": 38847
2048
+ },
2049
+ {
2050
+ "name": "bounded_vec_tests::for_eachi::for_eachi_on_empty_vector",
2051
+ "start": 39234
2052
+ },
2053
+ {
2054
+ "name": "bounded_vec_tests::for_eachi::for_eachi_with_index_tracking",
2055
+ "start": 39527
2056
+ },
2057
+ {
2058
+ "name": "bounded_vec_tests::from_array::empty",
2059
+ "start": 40004
2060
+ },
2061
+ {
2062
+ "name": "bounded_vec_tests::from_array::equal_len",
2063
+ "start": 40314
2064
+ },
2065
+ {
2066
+ "name": "bounded_vec_tests::from_array::max_len_greater_then_array_len",
2067
+ "start": 40631
2068
+ },
2069
+ {
2070
+ "name": "bounded_vec_tests::from_array::max_len_lower_then_array_len",
2071
+ "start": 41102
2072
+ },
2073
+ {
2074
+ "name": "bounded_vec_tests::from_array::from_array_preserves_order",
2075
+ "start": 41245
2076
+ },
2077
+ {
2078
+ "name": "bounded_vec_tests::from_array::from_array_with_different_types",
2079
+ "start": 41534
2080
+ },
2081
+ {
2082
+ "name": "bounded_vec_tests::trait_from::simple",
2083
+ "start": 41971
2084
+ },
2085
+ {
2086
+ "name": "bounded_vec_tests::trait_eq::empty_equality",
2087
+ "start": 42409
2088
+ },
2089
+ {
2090
+ "name": "bounded_vec_tests::trait_eq::equality",
2091
+ "start": 42656
2092
+ },
2093
+ {
2094
+ "name": "bounded_vec_tests::trait_eq::inequality",
2095
+ "start": 42980
2096
+ },
2097
+ {
2098
+ "name": "bounded_vec_tests::from_parts::from_parts",
2099
+ "start": 43519
2100
+ },
2101
+ {
2102
+ "name": "bounded_vec_tests::push_pop::push_and_pop_operations",
2103
+ "start": 44192
2104
+ },
2105
+ {
2106
+ "name": "bounded_vec_tests::push_pop::push_to_full_vector",
2107
+ "start": 44818
2108
+ },
2109
+ {
2110
+ "name": "bounded_vec_tests::push_pop::pop_from_empty_vector",
2111
+ "start": 45092
2112
+ },
2113
+ {
2114
+ "name": "bounded_vec_tests::push_pop::push_pop_cycle",
2115
+ "start": 45261
2116
+ },
2117
+ {
2118
+ "name": "bounded_vec_tests::extend::extend_from_array",
2119
+ "start": 45956
2120
+ },
2121
+ {
2122
+ "name": "bounded_vec_tests::extend::extend_from_vector",
2123
+ "start": 46302
2124
+ },
2125
+ {
2126
+ "name": "bounded_vec_tests::extend::extend_from_bounded_vec",
2127
+ "start": 46696
2128
+ },
2129
+ {
2130
+ "name": "bounded_vec_tests::extend::extend_from_bounded_vec_limit",
2131
+ "start": 47317
2132
+ },
2133
+ {
2134
+ "name": "bounded_vec_tests::extend::extend_from_bounded_vec_full_and_empty",
2135
+ "start": 47831
2136
+ },
2137
+ {
2138
+ "name": "bounded_vec_tests::extend::extend_from_bounded_vec_zero_len",
2139
+ "start": 48335
2140
+ },
2141
+ {
2142
+ "name": "bounded_vec_tests::extend::extend_from_bounded_vec_last_zeroed",
2143
+ "start": 48629
2144
+ },
2145
+ {
2146
+ "name": "bounded_vec_tests::extend::extend_from_bounded_vec_empty_self",
2147
+ "start": 49054
2148
+ },
2149
+ {
2150
+ "name": "bounded_vec_tests::extend::extend_from_bounded_vec_preserves_tail_storage",
2151
+ "start": 49672
2152
+ },
2153
+ {
2154
+ "name": "bounded_vec_tests::extend::extend_from_bounded_vec_equal_capacity",
2155
+ "start": 50276
2156
+ },
2157
+ {
2158
+ "name": "bounded_vec_tests::extend::extend_array_beyond_max_len",
2159
+ "start": 50863
2160
+ },
2161
+ {
2162
+ "name": "bounded_vec_tests::extend::extend_vector_beyond_max_len",
2163
+ "start": 51141
2164
+ },
2165
+ {
2166
+ "name": "bounded_vec_tests::extend::extend_bounded_vec_beyond_max_len",
2167
+ "start": 51444
2168
+ },
2169
+ {
2170
+ "name": "bounded_vec_tests::extend::extend_with_empty_collections",
2171
+ "start": 51730
2172
+ },
2173
+ {
2174
+ "name": "bounded_vec_tests::storage::storage_consistency",
2175
+ "start": 52330
2176
+ },
2177
+ {
2178
+ "name": "bounded_vec_tests::storage::storage_after_pop",
2179
+ "start": 52832
2180
+ },
2181
+ {
2182
+ "name": "bounded_vec_tests::storage::vector_immutable",
2183
+ "start": 53154
2184
+ }
2185
+ ],
2186
+ "path": "std/collections/bounded_vec.nr",
2187
+ "source": "use crate::{cmp::Eq, convert::From, runtime::is_unconstrained, static_assert};\n\n/// A `BoundedVec<T, MaxLen>` is a growable storage similar to a built-in vector except that it\n/// is bounded with a maximum possible length. `BoundedVec` is also not\n/// subject to the same restrictions vectors are (notably, nested vectors are disallowed).\n///\n/// Since a BoundedVec is backed by a normal array under the hood, growing the BoundedVec by\n/// pushing an additional element is also more efficient - the length only needs to be increased\n/// by one.\n///\n/// For these reasons `BoundedVec<T, N>` should generally be preferred over vectors when there\n/// is a reasonable maximum bound that can be placed on the vector.\n///\n/// Example:\n///\n/// ```noir\n/// let mut vector: BoundedVec<Field, 10> = BoundedVec::new();\n/// for i in 0..5 {\n/// vector.push(i);\n/// }\n/// assert(vector.len() == 5);\n/// assert(vector.max_len() == 10);\n/// ```\npub struct BoundedVec<T, let MaxLen: u32> {\n storage: [T; MaxLen],\n len: u32,\n}\n\nimpl<T, let MaxLen: u32> BoundedVec<T, MaxLen> {\n /// Creates a new, empty vector of length zero.\n ///\n /// Since this container is backed by an array internally, it still needs an initial value\n /// to give each element. To resolve this, each element is zeroed internally. This value\n /// is guaranteed to be inaccessible unless `get_unchecked` is used.\n ///\n /// Example:\n ///\n /// ```noir\n /// let empty_vector: BoundedVec<Field, 10> = BoundedVec::new();\n /// assert(empty_vector.len() == 0);\n /// ```\n ///\n /// Note that whenever calling `new` the maximum length of the vector should generally be specified\n /// via a type signature:\n ///\n /// ```noir\n /// fn good() -> BoundedVec<Field, 10> {\n /// // Ok! MaxLen is specified with a type annotation\n /// let v1: BoundedVec<Field, 3> = BoundedVec::new();\n /// let v2 = BoundedVec::new();\n ///\n /// // Ok! MaxLen is known from the type of `good`'s return value\n /// v2\n /// }\n ///\n /// fn bad() {\n /// // Error: Type annotation needed\n /// // The compiler can't infer `MaxLen` from the following code:\n /// let mut v3 = BoundedVec::new();\n /// v3.push(5);\n /// }\n /// ```\n pub fn new() -> Self {\n let zeroed = crate::mem::zeroed();\n BoundedVec { storage: [zeroed; MaxLen], len: 0 }\n }\n\n /// Retrieves an element from the vector at the given index, starting from zero.\n ///\n /// If the given index is equal to or greater than the length of the vector, this\n /// will issue a constraint failure.\n ///\n /// Example:\n ///\n /// ```noir\n /// fn foo<let N: u32>(v: BoundedVec<u32, N>) {\n /// let first = v.get(0);\n /// let last = v.get(v.len() - 1);\n /// assert(first != last);\n /// }\n /// ```\n pub fn get(&self, index: u32) -> T {\n assert(index < self.len, \"Attempted to read past end of BoundedVec\");\n self.get_unchecked(index)\n }\n\n /// Retrieves an element from the vector at the given index, starting from zero, without\n /// performing a bounds check.\n ///\n /// Since this function does not perform a bounds check on length before accessing the element,\n /// it is unsafe! Use at your own risk!\n ///\n /// Example:\n ///\n /// ```noir\n /// fn sum_of_first_three<let N: u32>(v: BoundedVec<u32, N>) -> u32 {\n /// // Always ensure the length is larger than the largest\n /// // index passed to get_unchecked\n /// assert(v.len() > 2);\n /// let first = v.get_unchecked(0);\n /// let second = v.get_unchecked(1);\n /// let third = v.get_unchecked(2);\n /// first + second + third\n /// }\n /// ```\n pub fn get_unchecked(&self, index: u32) -> T {\n self.storage[index]\n }\n\n /// Writes an element to the vector at the given index, starting from zero.\n ///\n /// If the given index is equal to or greater than the length of the vector, this will issue a constraint failure.\n ///\n /// Example:\n ///\n /// ```noir\n /// fn foo<let N: u32>(v: BoundedVec<u32, N>) {\n /// let first = v.get(0);\n /// assert(first != 42);\n /// v.set(0, 42);\n /// let new_first = v.get(0);\n /// assert(new_first == 42);\n /// }\n /// ```\n pub fn set(&mut self, index: u32, value: T) {\n assert(index < self.len, \"Attempted to write past end of BoundedVec\");\n self.set_unchecked(index, value)\n }\n\n /// Writes an element to the vector at the given index, starting from zero, without performing a bounds check.\n ///\n /// Since this function does not perform a bounds check on length before accessing the element, it is unsafe! Use at your own risk!\n ///\n /// Example:\n ///\n /// ```noir\n /// fn set_unchecked_example() {\n /// let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n /// vec.extend_from_array([1, 2]);\n ///\n /// // Here we're safely writing within the valid range of `vec`\n /// // `vec` now has the value [42, 2]\n /// vec.set_unchecked(0, 42);\n ///\n /// // We can then safely read this value back out of `vec`.\n /// // Notice that we use the checked version of `get` which would prevent reading unsafe values.\n /// assert_eq(vec.get(0), 42);\n ///\n /// // We've now written past the end of `vec`.\n /// // As this index is still within the maximum potential length of `v`,\n /// // it won't cause a constraint failure.\n /// vec.set_unchecked(2, 42);\n /// println(vec);\n ///\n /// // This will write past the end of the maximum potential length of `vec`,\n /// // it will then trigger a constraint failure.\n /// vec.set_unchecked(5, 42);\n /// println(vec);\n /// }\n /// ```\n pub fn set_unchecked(&mut self, index: u32, value: T) {\n self.storage[index] = value;\n }\n\n /// Pushes an element to the end of the vector. This increases the length\n /// of the vector by one.\n ///\n /// Panics if the new length of the vector will be greater than the max length.\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut v: BoundedVec<Field, 2> = BoundedVec::new();\n ///\n /// v.push(1);\n /// v.push(2);\n ///\n /// // Panics with failed assertion \"push out of bounds\"\n /// v.push(3);\n /// ```\n pub fn push(&mut self, elem: T) {\n assert(self.len < MaxLen, \"push out of bounds\");\n\n self.storage[self.len] = elem;\n self.len += 1;\n }\n\n /// Returns the current length of this vector\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut v: BoundedVec<Field, 4> = BoundedVec::new();\n /// assert(v.len() == 0);\n ///\n /// v.push(100);\n /// assert(v.len() == 1);\n ///\n /// v.push(200);\n /// v.push(300);\n /// v.push(400);\n /// assert(v.len() == 4);\n ///\n /// let _ = v.pop();\n /// let _ = v.pop();\n /// assert(v.len() == 2);\n /// ```\n pub fn len(&self) -> u32 {\n self.len\n }\n\n /// Sets the length of the vector to any value between `0` and `MaxLen`.\n ///\n /// Increasing the length exposes elements that were written past the current\n /// length (e.g. with `set_unchecked`); decreasing it discards trailing\n /// elements. Note that this does not zero out any element of the backing storage,\n /// so elements beyond the new length remain readable through `storage`.\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut v: BoundedVec<Field, 10> = BoundedVec::from([1, 2, 3, 4, 5]);\n ///\n /// assert(v.len() == 5);\n /// v.set_unchecked(5, 6);\n /// v.set_unchecked(6, 7);\n /// v.set_unchecked(7, 8);\n /// v.set_len(8);\n /// assert(v.len() == 8);\n ///\n /// // The length can also be reduced.\n /// v.set_len(2);\n /// assert(v.len() == 2);\n /// ```\n pub fn set_len(&mut self, len: u32) {\n assert(len <= MaxLen, \"set_len out of bounds\");\n self.len = len;\n }\n\n /// Shortens the vector to `len`, keeping the first `len` elements.\n ///\n /// If `len` is greater than or equal to the current length, the vector is\n /// left unchanged. Regardless of the current length, after this call the\n /// vector is guaranteed to hold no more than `len` elements.\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut v: BoundedVec<Field, 10> = BoundedVec::from([1, 2, 3, 4, 5]);\n ///\n /// v.truncate(3);\n /// assert(v.len() == 3);\n ///\n /// // Truncating to a length greater than the current length is a no-op.\n /// v.truncate(8);\n /// assert(v.len() == 3);\n /// ```\n pub fn truncate(&mut self, len: u32) {\n if len < self.len() {\n self.len = len;\n }\n }\n\n /// Returns the maximum length of this vector. This is always\n /// equal to the `MaxLen` parameter this vector was initialized with.\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut v: BoundedVec<Field, 5> = BoundedVec::new();\n ///\n /// assert(v.max_len() == 5);\n /// v.push(10);\n /// assert(v.max_len() == 5);\n /// ```\n pub fn max_len(_self: &BoundedVec<T, MaxLen>) -> u32 {\n MaxLen\n }\n\n /// Returns the internal array within this vector.\n ///\n /// Since arrays in Noir are immutable, mutating the returned storage array will not mutate\n /// the storage held internally by this vector.\n ///\n /// Note that uninitialized elements may be zeroed out!\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut v: BoundedVec<Field, 5> = BoundedVec::new();\n ///\n /// assert(v.storage() == [0, 0, 0, 0, 0]);\n ///\n /// v.push(57);\n /// assert(v.storage() == [57, 0, 0, 0, 0]);\n /// ```\n pub fn storage(self) -> [T; MaxLen] {\n self.storage\n }\n\n /// Pushes each element from the given array to this vector.\n ///\n /// Panics if pushing each element would cause the length of this vector\n /// to exceed the maximum length.\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut vec: BoundedVec<Field, 3> = BoundedVec::new();\n /// vec.extend_from_array([2, 4]);\n ///\n /// assert(vec.len == 2);\n /// assert(vec.get(0) == 2);\n /// assert(vec.get(1) == 4);\n /// ```\n pub fn extend_from_array<let Len: u32>(&mut self, array: [T; Len]) {\n let new_len = self.len + array.len();\n assert(new_len <= MaxLen, \"extend_from_array out of bounds\");\n for i in 0..array.len() {\n self.storage[self.len + i] = array[i];\n }\n self.len = new_len;\n }\n\n /// Pushes each element from the given vector to this vector.\n ///\n /// Panics if pushing each element would cause the length of this vector\n /// to exceed the maximum length.\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut vec: BoundedVec<Field, 3> = BoundedVec::new();\n /// vec.extend_from_vector([2, 4].as_vector());\n ///\n /// assert(vec.len == 2);\n /// assert(vec.get(0) == 2);\n /// assert(vec.get(1) == 4);\n /// ```\n pub fn extend_from_vector(&mut self, vector: [T]) {\n let new_len = self.len + vector.len();\n assert(new_len <= MaxLen, \"extend_from_vector out of bounds\");\n for i in 0..vector.len() {\n self.storage[self.len + i] = vector[i];\n }\n self.len = new_len;\n }\n\n /// Pushes each element from the other vector to this vector. The length of\n /// the other vector is left unchanged.\n ///\n /// Panics if pushing each element would cause the length of this vector\n /// to exceed the maximum length.\n ///\n /// ```noir\n /// let mut v1: BoundedVec<Field, 5> = BoundedVec::new();\n /// let mut v2: BoundedVec<Field, 7> = BoundedVec::new();\n ///\n /// v2.extend_from_array([1, 2, 3]);\n /// v1.extend_from_bounded_vec(v2);\n ///\n /// assert(v1.storage() == [1, 2, 3, 0, 0]);\n /// assert(v2.storage() == [1, 2, 3, 0, 0, 0, 0]);\n /// ```\n pub fn extend_from_bounded_vec<let Len: u32>(&mut self, vec: BoundedVec<T, Len>) {\n let append_len = vec.len();\n let new_len = self.len + append_len;\n assert(new_len <= MaxLen, \"extend_from_bounded_vec out of bounds\");\n\n if is_unconstrained() {\n for i in 0..append_len {\n self.storage[self.len + i] = vec.get_unchecked(i);\n }\n } else {\n // Iterate to a static bound: the smaller of the two capacities, since we can\n // neither read nor write past either. The source's actual length is dynamic.\n let max = crate::cmp::min(Len, MaxLen);\n for i in 0..max {\n if i < append_len {\n self.storage[self.len + i] = vec.get_unchecked(i);\n }\n }\n }\n self.len = new_len;\n }\n\n /// Creates a new vector, populating it with values derived from an array input.\n /// The maximum length of the vector is determined based on the type signature.\n ///\n /// Example:\n ///\n /// ```noir\n /// let bounded_vec: BoundedVec<Field, 10> = BoundedVec::from_array([1, 2, 3])\n /// ```\n pub fn from_array<let Len: u32>(array: [T; Len]) -> Self {\n static_assert(Len <= MaxLen, \"from array out of bounds\");\n let mut vec: BoundedVec<T, MaxLen> = BoundedVec::new();\n vec.extend_from_array(array);\n vec\n }\n\n /// Pops the element at the end of the vector. This will decrease the length\n /// of the vector by one.\n ///\n /// Panics if the vector is empty.\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut v: BoundedVec<Field, 2> = BoundedVec::new();\n /// v.push(1);\n /// v.push(2);\n ///\n /// let two = v.pop();\n /// let one = v.pop();\n ///\n /// assert(two == 2);\n /// assert(one == 1);\n ///\n /// // error: cannot pop from an empty vector\n /// let _ = v.pop();\n /// ```\n pub fn pop(&mut self) -> T {\n assert(self.len > 0, \"cannot pop from an empty vector\");\n self.len -= 1;\n self.storage[self.len]\n }\n\n /// Returns true if the given predicate returns true for any element\n /// in this vector.\n ///\n /// Example:\n ///\n /// ```noir\n /// let mut v: BoundedVec<u32, 3> = BoundedVec::new();\n /// v.extend_from_array([2, 4, 6]);\n ///\n /// let all_even = !v.any(|elem: u32| elem % 2 != 0);\n /// assert(all_even);\n /// ```\n pub fn any<Env>(self, predicate: fn[Env](T) -> bool) -> bool {\n let mut ret = false;\n if is_unconstrained() {\n for i in 0..self.len {\n ret |= predicate(self.storage[i]);\n }\n } else {\n let mut exceeded_len = false;\n for i in 0..MaxLen {\n exceeded_len |= i == self.len;\n if !exceeded_len {\n ret |= predicate(self.storage[i]);\n }\n }\n }\n ret\n }\n\n /// Creates a new vector of equal size by calling a closure on each element in this vector.\n ///\n /// Example:\n ///\n /// ```noir\n /// let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n /// let result = vec.map(|value| value * 2);\n ///\n /// let expected = BoundedVec::from_array([2, 4, 6, 8]);\n /// assert_eq(result, expected);\n /// ```\n pub fn map<U, Env>(&self, f: fn[Env](T) -> U) -> BoundedVec<U, MaxLen> {\n let mut ret = BoundedVec::new();\n ret.len = self.len();\n\n if is_unconstrained() {\n for i in 0..self.len() {\n ret.storage[i] = f(self.get_unchecked(i));\n }\n } else {\n for i in 0..MaxLen {\n if i < self.len() {\n ret.storage[i] = f(self.get_unchecked(i));\n }\n }\n }\n\n ret\n }\n\n /// Creates a new vector of equal size by calling a closure on each element\n /// in this vector, along with its index.\n ///\n /// Example:\n ///\n /// ```noir\n /// let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n /// let result = vec.mapi(|i, value| i + value * 2);\n ///\n /// let expected = BoundedVec::from_array([2, 5, 8, 11]);\n /// assert_eq(result, expected);\n /// ```\n pub fn mapi<U, Env>(&self, f: fn[Env](u32, T) -> U) -> BoundedVec<U, MaxLen> {\n let mut ret = BoundedVec::new();\n ret.len = self.len();\n\n if is_unconstrained() {\n for i in 0..self.len() {\n ret.storage[i] = f(i, self.get_unchecked(i));\n }\n } else {\n for i in 0..MaxLen {\n if i < self.len() {\n ret.storage[i] = f(i, self.get_unchecked(i));\n }\n }\n }\n\n ret\n }\n\n /// Calls a closure on each element in this vector.\n ///\n /// Example:\n ///\n /// ```noir\n /// let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n /// let mut result = BoundedVec::<u32, 4>::new();\n /// vec.for_each(|value| result.push(value * 2));\n ///\n /// let expected = BoundedVec::from_array([2, 4, 6, 8]);\n /// assert_eq(result, expected);\n /// ```\n pub fn for_each<Env>(&self, f: fn[Env](T) -> ()) {\n if is_unconstrained() {\n for i in 0..self.len() {\n f(self.get_unchecked(i));\n }\n } else {\n for i in 0..MaxLen {\n if i < self.len() {\n f(self.get_unchecked(i));\n }\n }\n }\n }\n\n /// Calls a closure on each element in this vector, along with its index.\n ///\n /// Example:\n ///\n /// ```noir\n /// let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n /// let mut result = BoundedVec::<u32, 4>::new();\n /// vec.for_eachi(|i, value| result.push(i + value * 2));\n ///\n /// let expected = BoundedVec::from_array([2, 5, 8, 11]);\n /// assert_eq(result, expected);\n /// ```\n pub fn for_eachi<Env>(&self, f: fn[Env](u32, T) -> ()) {\n if is_unconstrained() {\n for i in 0..self.len() {\n f(i, self.get_unchecked(i));\n }\n } else {\n for i in 0..MaxLen {\n if i < self.len() {\n f(i, self.get_unchecked(i));\n }\n }\n }\n }\n\n /// Creates a new BoundedVec from the given array and length.\n /// The given length must be less than or equal to the length of the array.\n ///\n /// Example:\n ///\n /// ```noir\n /// let vec: BoundedVec<u32, 4> = BoundedVec::from_parts([1, 2, 3, 0], 3);\n /// assert_eq(vec.len(), 3);\n /// ```\n pub fn from_parts(array: [T; MaxLen], len: u32) -> Self {\n assert(len <= MaxLen);\n BoundedVec { storage: array, len }\n }\n\n /// Creates a new BoundedVec from the given array and length.\n /// The given length must be less than or equal to the length of the array.\n ///\n /// This function is unsafe because it expects all elements past the `len` index\n /// of `array` to be zeroed, but does not check for this internally. Use `from_parts`\n /// for a safe version of this function which does zero out any indices past the\n /// given length. Invalidating this assumption can notably cause `BoundedVec::eq`\n /// to give incorrect results since it will check even elements past `len`.\n ///\n /// Example:\n ///\n /// ```noir\n /// let vec: BoundedVec<u32, 4> = BoundedVec::from_parts_unchecked([1, 2, 3, 0], 3);\n /// assert_eq(vec.len(), 3);\n ///\n /// // invalid use!\n /// let vec1: BoundedVec<u32, 4> = BoundedVec::from_parts_unchecked([1, 2, 3, 1], 3);\n /// let vec2: BoundedVec<u32, 4> = BoundedVec::from_parts_unchecked([1, 2, 3, 2], 3);\n ///\n /// // both vecs have length 3 so we'd expect them to be equal, but this\n /// // fails because elements past the length are still checked in eq\n /// assert_eq(vec1, vec2); // fails\n /// ```\n #[deprecated(\"`BoundedVec::from_parts` no longer requires an extra loop, `BoundedVec::from_parts_unchecked` is no longer required\")]\n pub fn from_parts_unchecked(array: [T; MaxLen], len: u32) -> Self {\n assert(len <= MaxLen);\n BoundedVec { storage: array, len }\n }\n}\n\nimpl<T, let MaxLen: u32> Eq for BoundedVec<T, MaxLen>\nwhere\n T: Eq,\n{\n fn eq(self, other: BoundedVec<T, MaxLen>) -> bool {\n if self.len == other.len {\n if is_unconstrained() {\n // safety: we are already in an unconstrained context\n unsafe {\n unconstrained_eq(self, other)\n }\n } else {\n let mut eq = true;\n for i in 0..MaxLen {\n if i < self.len {\n eq &= self.storage[i] == other.storage[i];\n }\n }\n eq\n }\n } else {\n false\n }\n }\n}\n\n/// Returns true if both BoundedVecs are equal.\n/// Note: This assumes the lengths of both Vecs are already equal!\n/// This function is broken out of `impl Eq for BoundedVec` to make use of `break` in unconstrained code.\nunconstrained fn unconstrained_eq<T, let MaxLen: u32>(\n a: BoundedVec<T, MaxLen>,\n b: BoundedVec<T, MaxLen>,\n) -> bool\nwhere\n T: Eq,\n{\n let mut eq = true;\n for i in 0..a.len {\n if a.storage[i] != b.storage[i] {\n eq = false;\n break;\n }\n }\n eq\n}\n\nimpl<T, let MaxLen: u32, let Len: u32> From<[T; Len]> for BoundedVec<T, MaxLen> {\n fn from(array: [T; Len]) -> BoundedVec<T, MaxLen> {\n BoundedVec::from_array(array)\n }\n}\n\nmod bounded_vec_tests {\n\n mod get {\n use crate::collections::bounded_vec::BoundedVec;\n\n #[test(should_fail_with = \"Attempted to read past end of BoundedVec\")]\n fn panics_when_reading_elements_past_end_of_vec() {\n let vec: BoundedVec<Field, 5> = BoundedVec::new();\n\n let _ = vec.get(0);\n }\n\n #[test(should_fail_with = \"Attempted to read past end of BoundedVec\")]\n fn panics_when_reading_beyond_length() {\n let vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3]);\n let _ = vec.get(3);\n }\n\n #[test]\n fn get_works_within_bounds() {\n let vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3, 4, 5]);\n assert_eq(vec.get(0), 1);\n assert_eq(vec.get(2), 3);\n assert_eq(vec.get(4), 5);\n }\n\n #[test]\n fn get_unchecked_works() {\n let vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3]);\n assert_eq(vec.get_unchecked(0), 1);\n assert_eq(vec.get_unchecked(2), 3);\n }\n\n #[test]\n fn get_unchecked_works_past_len() {\n let vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3]);\n assert_eq(vec.get_unchecked(4), 0);\n }\n }\n\n mod set {\n use crate::collections::bounded_vec::BoundedVec;\n\n #[test]\n fn set_updates_values_properly() {\n let mut vec = BoundedVec::from_array([0, 0, 0, 0, 0]);\n\n vec.set(0, 42);\n assert_eq(vec.storage, [42, 0, 0, 0, 0]);\n\n vec.set(1, 43);\n assert_eq(vec.storage, [42, 43, 0, 0, 0]);\n\n vec.set(2, 44);\n assert_eq(vec.storage, [42, 43, 44, 0, 0]);\n\n vec.set(1, 10);\n assert_eq(vec.storage, [42, 10, 44, 0, 0]);\n\n vec.set(0, 0);\n assert_eq(vec.storage, [0, 10, 44, 0, 0]);\n }\n\n #[test(should_fail_with = \"Attempted to write past end of BoundedVec\")]\n fn panics_when_writing_elements_past_end_of_vec() {\n let mut vec: BoundedVec<Field, 5> = BoundedVec::new();\n vec.set(0, 42);\n }\n\n #[test(should_fail_with = \"Attempted to write past end of BoundedVec\")]\n fn panics_when_setting_beyond_length() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3]);\n vec.set(3, 4);\n }\n\n #[test]\n fn set_unchecked_operations() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n vec.push(1);\n vec.push(2);\n\n vec.set_unchecked(0, 10);\n assert_eq(vec.get(0), 10);\n }\n\n #[test(should_fail_with = \"Attempted to read past end of BoundedVec\")]\n fn set_unchecked_operations_past_len() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n vec.push(1);\n vec.push(2);\n\n vec.set_unchecked(3, 40);\n assert_eq(vec.get(3), 40);\n }\n\n #[test]\n fn set_preserves_other_elements() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3, 4, 5]);\n\n vec.set(2, 30);\n assert_eq(vec.get(0), 1);\n assert_eq(vec.get(1), 2);\n assert_eq(vec.get(2), 30);\n assert_eq(vec.get(3), 4);\n assert_eq(vec.get(4), 5);\n }\n }\n\n mod set_len {\n use crate::collections::bounded_vec::BoundedVec;\n\n #[test]\n fn set_len_works_after_multiple_unchecked_sets() {\n let mut vec: BoundedVec<u8, 10> = BoundedVec::from_array([1, 2, 3]);\n vec.set_unchecked(3, 44);\n vec.set_unchecked(4, 55);\n vec.set_unchecked(5, 66);\n // Index 6 is intentionally left untouched: it stays zeroed.\n vec.set_len(8);\n assert_eq(vec.len(), 8);\n\n // The explicitly written elements are exposed at their indices...\n assert_eq(vec.get(3), 44);\n assert_eq(vec.get(4), 55);\n assert_eq(vec.get(5), 66);\n // ...while the gap between the last write and the new length is zeroed.\n assert_eq(vec.get(6), 0);\n assert_eq(vec.get(7), 0);\n\n vec.extend_from_array([88, 99]);\n assert_eq(vec.len(), 10);\n }\n\n #[test]\n fn set_len_can_reduce_the_length() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3, 4, 5]);\n vec.set_len(2);\n assert_eq(vec.len(), 2);\n // Reducing the length does not zero the backing storage, so the\n // discarded elements remain readable through `storage`.\n assert_eq(vec.storage()[2], 3);\n assert_eq(vec.storage()[3], 4);\n assert_eq(vec.storage()[4], 5);\n }\n\n #[test(should_fail_with = \"set_len out of bounds\")]\n fn panics_when_set_len_beyond_max_len() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3]);\n vec.set_len(6);\n }\n }\n\n mod truncate {\n use crate::collections::bounded_vec::BoundedVec;\n\n #[test]\n fn truncate_shortens_to_len() {\n let mut vec: BoundedVec<u32, 10> = BoundedVec::from_array([1, 2, 3, 4, 5]);\n vec.truncate(3);\n assert_eq(vec.len(), 3);\n assert_eq(vec.storage()[0], 1);\n assert_eq(vec.storage()[1], 2);\n assert_eq(vec.storage()[2], 3);\n }\n\n #[test]\n fn truncate_to_zero_empties_the_vec() {\n let mut vec: BoundedVec<u32, 10> = BoundedVec::from_array([1, 2, 3]);\n vec.truncate(0);\n assert_eq(vec.len(), 0);\n }\n\n #[test]\n fn truncate_to_equal_len_is_noop() {\n let mut vec: BoundedVec<u32, 10> = BoundedVec::from_array([1, 2, 3]);\n vec.truncate(3);\n assert_eq(vec.len(), 3);\n }\n\n #[test]\n fn truncate_to_greater_len_is_noop() {\n let mut vec: BoundedVec<u32, 10> = BoundedVec::from_array([1, 2, 3]);\n vec.truncate(8);\n assert_eq(vec.len(), 3);\n }\n\n #[test]\n fn truncate_beyond_max_len_is_noop() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3]);\n vec.truncate(100);\n assert_eq(vec.len(), 3);\n }\n\n #[test]\n fn truncate_does_not_zero_remaining_storage() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3, 4, 5]);\n vec.truncate(2);\n assert_eq(vec.len(), 2);\n // Items beyond the new length are left untouched in the backing storage.\n assert_eq(vec.storage()[2], 3);\n assert_eq(vec.storage()[3], 4);\n assert_eq(vec.storage()[4], 5);\n }\n\n #[test]\n fn truncate_then_push_continues_from_new_len() {\n let mut vec: BoundedVec<u32, 10> = BoundedVec::from_array([1, 2, 3, 4, 5]);\n vec.truncate(2);\n vec.push(30);\n assert_eq(vec.len(), 3);\n assert_eq(vec.storage()[0], 1);\n assert_eq(vec.storage()[1], 2);\n assert_eq(vec.storage()[2], 30);\n }\n }\n\n mod any {\n use crate::collections::bounded_vec::BoundedVec;\n use crate::internal::test_unconstrained;\n\n #[test]\n #[test_unconstrained]\n fn returns_false_if_predicate_not_satisfied() {\n let vec: BoundedVec<bool, 4> = BoundedVec::from_array([false, false, false, false]);\n let result = vec.any(|value| value);\n\n assert(!result);\n }\n\n #[test]\n #[test_unconstrained]\n fn returns_true_if_predicate_satisfied() {\n let vec: BoundedVec<bool, 4> = BoundedVec::from_array([false, false, true, true]);\n let result = vec.any(|value| value);\n\n assert(result);\n }\n\n #[test]\n fn returns_false_on_empty_boundedvec() {\n let vec: BoundedVec<bool, 0> = BoundedVec::new();\n let result = vec.any(|value| value);\n\n assert(!result);\n }\n\n #[test]\n #[test_unconstrained]\n fn any_with_complex_predicates() {\n let vec: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3, 4, 5]);\n\n assert(vec.any(|x| x > 3));\n assert(!vec.any(|x| x > 10));\n assert(vec.any(|x| x % 2 == 0)); // has a even number\n assert(vec.any(|x| x == 3)); // has a specific value\n }\n\n #[test]\n fn any_with_partial_vector() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n vec.push(1);\n vec.push(2);\n\n assert(vec.any(|x| x == 1));\n assert(vec.any(|x| x == 2));\n assert(!vec.any(|x| x == 3));\n }\n }\n\n mod map {\n use crate::collections::bounded_vec::BoundedVec;\n use crate::internal::test_unconstrained;\n\n #[test]\n #[test_unconstrained]\n fn applies_function_correctly() {\n // docs:start:bounded-vec-map-example\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n let result = vec.map(|value| value * 2);\n // docs:end:bounded-vec-map-example\n let expected = BoundedVec::from_array([2, 4, 6, 8]);\n\n assert_eq(result, expected);\n }\n\n #[test]\n fn applies_function_that_changes_return_type() {\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n let result = vec.map(|value| (value * 2) as Field);\n let expected: BoundedVec<Field, 4> = BoundedVec::from_array([2, 4, 6, 8]);\n\n assert_eq(result, expected);\n }\n\n #[test]\n fn does_not_apply_function_past_len() {\n let vec: BoundedVec<u32, 3> = BoundedVec::from_array([0, 1]);\n let result = vec.map(|value| if value == 0 { 5 } else { value });\n let expected = BoundedVec::from_array([5, 1]);\n\n assert_eq(result, expected);\n assert_eq(result.get_unchecked(2), 0);\n }\n\n #[test]\n fn map_with_conditional_logic() {\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n\n let result = vec.map(|x| if x % 2 == 0 { x * 2 } else { x });\n let expected = BoundedVec::from_array([1, 4, 3, 8]);\n assert_eq(result, expected);\n }\n\n #[test]\n fn map_preserves_length() {\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n let result = vec.map(|x| x * 2);\n\n assert_eq(result.len(), vec.len());\n assert_eq(result.max_len(), vec.max_len());\n }\n\n #[test]\n fn map_on_empty_vector() {\n let vec: BoundedVec<u32, 5> = BoundedVec::new();\n let result = vec.map(|x| x * 2);\n assert_eq(result, vec);\n assert_eq(result.len(), 0);\n assert_eq(result.max_len(), 5);\n }\n }\n\n mod mapi {\n use crate::collections::bounded_vec::BoundedVec;\n use crate::internal::test_unconstrained;\n\n #[test]\n #[test_unconstrained]\n fn applies_function_correctly() {\n // docs:start:bounded-vec-mapi-example\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n let result = vec.mapi(|i, value| i + value * 2);\n // docs:end:bounded-vec-mapi-example\n let expected = BoundedVec::from_array([2, 5, 8, 11]);\n\n assert_eq(result, expected);\n }\n\n #[test]\n fn applies_function_that_changes_return_type() {\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n let result = vec.mapi(|i, value| (i + value * 2) as Field);\n let expected: BoundedVec<Field, 4> = BoundedVec::from_array([2, 5, 8, 11]);\n\n assert_eq(result, expected);\n }\n\n #[test]\n fn does_not_apply_function_past_len() {\n let vec: BoundedVec<u32, 3> = BoundedVec::from_array([0, 1]);\n let result = vec.mapi(|_, value| if value == 0 { 5 } else { value });\n let expected = BoundedVec::from_array([5, 1]);\n\n assert_eq(result, expected);\n assert_eq(result.get_unchecked(2), 0);\n }\n\n #[test]\n fn mapi_with_index_branching_logic() {\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n\n let result = vec.mapi(|i, x| if i % 2 == 0 { x * 2 } else { x });\n let expected = BoundedVec::from_array([2, 2, 6, 4]);\n assert_eq(result, expected);\n }\n }\n\n mod for_each {\n use crate::collections::bounded_vec::BoundedVec;\n use crate::internal::test_unconstrained;\n\n // map in terms of for_each\n fn for_each_map<T, U, Env, let MaxLen: u32>(\n input: BoundedVec<T, MaxLen>,\n f: fn[Env](T) -> U,\n ) -> BoundedVec<U, MaxLen> {\n let mut output = BoundedVec::<U, MaxLen>::new();\n let output_ref = &mut output;\n input.for_each(|x| output_ref.push(f(x)));\n output\n }\n\n #[test]\n #[test_unconstrained]\n fn smoke_test() {\n let mut acc = 0;\n let acc_ref = &mut acc;\n // docs:start:bounded-vec-for-each-example\n let vec: BoundedVec<u32, 3> = BoundedVec::from_array([1, 2, 3]);\n vec.for_each(|value| { *acc_ref += value; });\n // docs:end:bounded-vec-for-each-example\n assert_eq(acc, 6);\n }\n\n #[test]\n fn applies_function_correctly() {\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n let result = for_each_map(vec, |value| value * 2);\n let expected = BoundedVec::from_array([2, 4, 6, 8]);\n\n assert_eq(result, expected);\n }\n\n #[test]\n fn applies_function_that_changes_return_type() {\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n let result = for_each_map(vec, |value| (value * 2) as Field);\n let expected: BoundedVec<Field, 4> = BoundedVec::from_array([2, 4, 6, 8]);\n\n assert_eq(result, expected);\n }\n\n #[test]\n fn does_not_apply_function_past_len() {\n let vec: BoundedVec<u32, 3> = BoundedVec::from_array([0, 1]);\n let result = for_each_map(vec, |value| if value == 0 { 5 } else { value });\n let expected = BoundedVec::from_array([5, 1]);\n\n assert_eq(result, expected);\n assert_eq(result.get_unchecked(2), 0);\n }\n\n #[test]\n fn for_each_on_empty_vector() {\n let vec: BoundedVec<u32, 5> = BoundedVec::new();\n let mut count = 0;\n let count_ref = &mut count;\n vec.for_each(|_| { *count_ref += 1; });\n assert_eq(count, 0);\n }\n\n #[test]\n fn for_each_with_side_effects() {\n let vec: BoundedVec<u32, 3> = BoundedVec::from_array([1, 2, 3]);\n let mut seen = BoundedVec::<u32, 3>::new();\n let seen_ref = &mut seen;\n vec.for_each(|x| seen_ref.push(x));\n assert_eq(seen, vec);\n }\n }\n\n mod for_eachi {\n use crate::collections::bounded_vec::BoundedVec;\n use crate::internal::test_unconstrained;\n\n // mapi in terms of for_eachi\n fn for_eachi_mapi<T, U, Env, let MaxLen: u32>(\n input: BoundedVec<T, MaxLen>,\n f: fn[Env](u32, T) -> U,\n ) -> BoundedVec<U, MaxLen> {\n let mut output = BoundedVec::<U, MaxLen>::new();\n let output_ref = &mut output;\n input.for_eachi(|i, x| output_ref.push(f(i, x)));\n output\n }\n\n #[test]\n #[test_unconstrained]\n fn smoke_test() {\n let mut acc = 0;\n let acc_ref = &mut acc;\n // docs:start:bounded-vec-for-eachi-example\n let vec: BoundedVec<u32, 3> = BoundedVec::from_array([1, 2, 3]);\n vec.for_eachi(|i, value| { *acc_ref += i * value; });\n // docs:end:bounded-vec-for-eachi-example\n\n // 0 * 1 + 1 * 2 + 2 * 3\n assert_eq(acc, 8);\n }\n\n #[test]\n fn applies_function_correctly() {\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n let result = for_eachi_mapi(vec, |i, value| i + value * 2);\n let expected = BoundedVec::from_array([2, 5, 8, 11]);\n\n assert_eq(result, expected);\n }\n\n #[test]\n fn applies_function_that_changes_return_type() {\n let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);\n let result = for_eachi_mapi(vec, |i, value| (i + value * 2) as Field);\n let expected: BoundedVec<Field, 4> = BoundedVec::from_array([2, 5, 8, 11]);\n\n assert_eq(result, expected);\n }\n\n #[test]\n fn does_not_apply_function_past_len() {\n let vec: BoundedVec<u32, 3> = BoundedVec::from_array([0, 1]);\n let result = for_eachi_mapi(vec, |_, value| if value == 0 { 5 } else { value });\n let expected = BoundedVec::from_array([5, 1]);\n\n assert_eq(result, expected);\n assert_eq(result.get_unchecked(2), 0);\n }\n\n #[test]\n fn for_eachi_on_empty_vector() {\n let vec: BoundedVec<u32, 5> = BoundedVec::new();\n let mut count = 0;\n let count_ref = &mut count;\n vec.for_eachi(|_, _| { *count_ref += 1; });\n assert_eq(count, 0);\n }\n\n #[test]\n fn for_eachi_with_index_tracking() {\n let vec: BoundedVec<u32, 3> = BoundedVec::from_array([10, 20, 30]);\n let mut indices = BoundedVec::<u32, 3>::new();\n let indices_ref = &mut indices;\n vec.for_eachi(|i, _| indices_ref.push(i));\n\n let expected = BoundedVec::from_array([0, 1, 2]);\n assert_eq(indices, expected);\n }\n\n }\n\n mod from_array {\n use crate::collections::bounded_vec::BoundedVec;\n\n #[test]\n fn empty() {\n let empty_array: [Field; 0] = [];\n let bounded_vec = BoundedVec::from_array([]);\n\n assert_eq(bounded_vec.max_len(), 0);\n assert_eq(bounded_vec.len(), 0);\n assert_eq(bounded_vec.storage(), empty_array);\n }\n\n #[test]\n fn equal_len() {\n let array = [1, 2, 3];\n let bounded_vec = BoundedVec::from_array(array);\n\n assert_eq(bounded_vec.max_len(), 3);\n assert_eq(bounded_vec.len(), 3);\n assert_eq(bounded_vec.storage(), array);\n }\n\n #[test]\n fn max_len_greater_then_array_len() {\n let array = [1, 2, 3];\n let bounded_vec: BoundedVec<Field, 10> = BoundedVec::from_array(array);\n\n assert_eq(bounded_vec.max_len(), 10);\n assert_eq(bounded_vec.len(), 3);\n assert_eq(bounded_vec.get(0), 1);\n assert_eq(bounded_vec.get(1), 2);\n assert_eq(bounded_vec.get(2), 3);\n }\n\n #[test(should_fail_with = \"from array out of bounds\")]\n fn max_len_lower_then_array_len() {\n let _: BoundedVec<Field, 2> = BoundedVec::from_array([0; 3]);\n }\n\n #[test]\n fn from_array_preserves_order() {\n let array = [5, 3, 1, 4, 2];\n let vec: BoundedVec<u32, 5> = BoundedVec::from_array(array);\n for i in 0..array.len() {\n assert_eq(vec.get(i), array[i]);\n }\n }\n\n #[test]\n fn from_array_with_different_types() {\n let bool_array = [true, false, true];\n let bool_vec: BoundedVec<bool, 3> = BoundedVec::from_array(bool_array);\n assert_eq(bool_vec.len(), 3);\n assert_eq(bool_vec.get(0), true);\n assert_eq(bool_vec.get(1), false);\n }\n }\n\n mod trait_from {\n use crate::collections::bounded_vec::BoundedVec;\n use crate::convert::From;\n\n #[test]\n fn simple() {\n let array = [1, 2];\n let bounded_vec: BoundedVec<Field, 10> = BoundedVec::from(array);\n\n assert_eq(bounded_vec.max_len(), 10);\n assert_eq(bounded_vec.len(), 2);\n assert_eq(bounded_vec.get(0), 1);\n assert_eq(bounded_vec.get(1), 2);\n }\n }\n\n mod trait_eq {\n use crate::collections::bounded_vec::BoundedVec;\n\n #[test]\n fn empty_equality() {\n let bounded_vec1: BoundedVec<Field, 3> = BoundedVec::new();\n let bounded_vec2: BoundedVec<Field, 3> = BoundedVec::new();\n\n assert_eq(bounded_vec1, bounded_vec2);\n }\n\n #[test]\n fn equality() {\n let mut bounded_vec1: BoundedVec<Field, 3> = BoundedVec::new();\n let mut bounded_vec2: BoundedVec<Field, 3> = BoundedVec::new();\n\n bounded_vec1.push(1);\n bounded_vec2.push(1);\n assert(bounded_vec1 == bounded_vec2);\n }\n\n #[test]\n fn inequality() {\n let mut bounded_vec1: BoundedVec<Field, 3> = BoundedVec::new();\n let mut bounded_vec2: BoundedVec<Field, 3> = BoundedVec::new();\n\n bounded_vec1.push(1);\n assert(bounded_vec1 != bounded_vec2);\n\n bounded_vec2.push(2);\n assert(bounded_vec1 != bounded_vec2);\n }\n }\n\n mod from_parts {\n use crate::collections::bounded_vec::BoundedVec;\n use crate::internal::test_unconstrained;\n\n #[test]\n #[test_unconstrained]\n fn from_parts() {\n // docs:start:from-parts\n let vec: BoundedVec<u32, 4> = BoundedVec::from_parts([1, 2, 3, 0], 3);\n assert_eq(vec.len(), 3);\n\n // Any elements past the given length are ignored, so these\n // two BoundedVecs will be completely equal\n let vec1: BoundedVec<u32, 4> = BoundedVec::from_parts([1, 2, 3, 1], 3);\n let vec2: BoundedVec<u32, 4> = BoundedVec::from_parts([1, 2, 3, 2], 3);\n assert_eq(vec1, vec2);\n // docs:end:from-parts\n }\n }\n\n mod push_pop {\n use crate::collections::bounded_vec::BoundedVec;\n\n #[test]\n fn push_and_pop_operations() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n\n assert_eq(vec.len(), 0);\n\n vec.push(1);\n assert_eq(vec.len(), 1);\n assert_eq(vec.get(0), 1);\n\n vec.push(2);\n assert_eq(vec.len(), 2);\n assert_eq(vec.get(1), 2);\n\n let popped = vec.pop();\n assert_eq(popped, 2);\n assert_eq(vec.len(), 1);\n\n let popped2 = vec.pop();\n assert_eq(popped2, 1);\n assert_eq(vec.len(), 0);\n }\n\n #[test(should_fail_with = \"push out of bounds\")]\n fn push_to_full_vector() {\n let mut vec: BoundedVec<u32, 2> = BoundedVec::new();\n vec.push(1);\n vec.push(2);\n vec.push(3); // should panic\n }\n\n #[test(should_fail_with = \"cannot pop from an empty vector\")]\n fn pop_from_empty_vector() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n let _ = vec.pop(); // should panic\n }\n\n #[test]\n fn push_pop_cycle() {\n let mut vec: BoundedVec<u32, 3> = BoundedVec::new();\n\n // push to full\n vec.push(1);\n vec.push(2);\n vec.push(3);\n assert_eq(vec.len(), 3);\n\n // pop all\n assert_eq(vec.pop(), 3);\n assert_eq(vec.pop(), 2);\n assert_eq(vec.pop(), 1);\n assert_eq(vec.len(), 0);\n\n // push again\n vec.push(4);\n assert_eq(vec.len(), 1);\n assert_eq(vec.get(0), 4);\n }\n }\n\n mod extend {\n use crate::collections::bounded_vec::BoundedVec;\n use crate::internal::test_unconstrained;\n\n #[test]\n fn extend_from_array() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n vec.push(1);\n vec.extend_from_array([2, 3]);\n\n assert_eq(vec.len(), 3);\n assert_eq(vec.get(0), 1);\n assert_eq(vec.get(1), 2);\n assert_eq(vec.get(2), 3);\n }\n\n #[test]\n fn extend_from_vector() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n vec.push(1);\n vec.extend_from_vector([2, 3].as_vector());\n\n assert_eq(vec.len(), 3);\n assert_eq(vec.get(0), 1);\n assert_eq(vec.get(1), 2);\n assert_eq(vec.get(2), 3);\n }\n\n #[test]\n #[test_unconstrained]\n fn extend_from_bounded_vec() {\n // The source deliberately has a higher capacity,\n // to make sure we are not trying to assign out-of-bounds.\n let mut vec1: BoundedVec<u32, 5> = BoundedVec::new();\n let mut vec2: BoundedVec<u32, 9> = BoundedVec::new();\n\n vec1.push(1);\n vec2.push(2);\n vec2.push(3);\n\n vec1.extend_from_bounded_vec(vec2);\n\n assert_eq(vec1.len(), 3);\n assert_eq(vec1.get(0), 1);\n assert_eq(vec1.get(1), 2);\n assert_eq(vec1.get(2), 3);\n }\n\n #[test]\n fn extend_from_bounded_vec_limit() {\n // Capacity and contents chosen so the last item must be assigned to.\n let mut vec1: BoundedVec<u32, 2> = BoundedVec::new();\n let mut vec2: BoundedVec<u32, 5> = BoundedVec::new();\n\n vec1.push(1);\n vec2.push(2);\n\n vec1.extend_from_bounded_vec(vec2);\n\n assert_eq(vec1.len(), 2);\n assert_eq(vec1.get(0), 1);\n assert_eq(vec1.get(1), 2);\n }\n\n #[test]\n fn extend_from_bounded_vec_full_and_empty() {\n // Capacity and contents chosen so the last item must be assigned to.\n let mut vec1: BoundedVec<u32, 2> = BoundedVec::new();\n let vec2: BoundedVec<u32, 5> = BoundedVec::new();\n\n vec1.push(1);\n vec1.push(2);\n\n vec1.extend_from_bounded_vec(vec2);\n\n assert_eq(vec1.len(), 2);\n assert_eq(vec1.get(0), 1);\n assert_eq(vec1.get(1), 2);\n }\n\n #[test]\n fn extend_from_bounded_vec_zero_len() {\n let mut vec1: BoundedVec<u32, 0> = BoundedVec::new();\n let vec2: BoundedVec<u32, 0> = BoundedVec::new();\n\n vec1.extend_from_bounded_vec(vec2);\n\n assert_eq(vec1.len(), 0);\n }\n\n #[test]\n fn extend_from_bounded_vec_last_zeroed() {\n let mut vec1: BoundedVec<u32, 4> = BoundedVec::new();\n let mut vec2: BoundedVec<u32, 4> = BoundedVec::new();\n\n vec1.push(1);\n vec1.push(2);\n vec2.push(3);\n\n vec1.extend_from_bounded_vec(vec2);\n\n assert_eq(vec1.len(), 3);\n assert_eq(vec1.get_unchecked(3), 0);\n }\n\n #[test]\n fn extend_from_bounded_vec_empty_self() {\n // self.len == 0 with Len > MaxLen: the source is clamped to\n // MaxLen elements, filling the destination exactly to capacity.\n let mut vec1: BoundedVec<u32, 3> = BoundedVec::new();\n let vec2: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3]);\n\n vec1.extend_from_bounded_vec(vec2);\n\n assert_eq(vec1.len(), 3);\n assert_eq(vec1.get(0), 1);\n assert_eq(vec1.get(1), 2);\n assert_eq(vec1.get(2), 3);\n }\n\n #[test]\n #[test_unconstrained]\n fn extend_from_bounded_vec_preserves_tail_storage() {\n // The destination has meaningful (nonzero) storage past `len`.\n // Extending must leave that tail untouched, identically in the\n // constrained and unconstrained branches.\n let mut dst: BoundedVec<u32, 4> = BoundedVec::from_parts([10, 99, 123, 7], 1);\n let src: BoundedVec<u32, 4> = BoundedVec::from_parts([20, 0, 0, 0], 1);\n\n dst.extend_from_bounded_vec(src);\n\n assert_eq(dst.len(), 2);\n assert_eq(dst.storage(), [10, 20, 123, 7]);\n }\n\n #[test]\n fn extend_from_bounded_vec_equal_capacity() {\n // Len == MaxLen, fills to capacity.\n let mut vec1: BoundedVec<u32, 4> = BoundedVec::new();\n vec1.push(1);\n let vec2: BoundedVec<u32, 4> = BoundedVec::from_array([2, 3, 4]);\n\n vec1.extend_from_bounded_vec(vec2);\n\n assert_eq(vec1.len(), 4);\n assert_eq(vec1.get(0), 1);\n assert_eq(vec1.get(1), 2);\n assert_eq(vec1.get(2), 3);\n assert_eq(vec1.get(3), 4);\n }\n\n #[test(should_fail_with = \"extend_from_array out of bounds\")]\n fn extend_array_beyond_max_len() {\n let mut vec: BoundedVec<u32, 3> = BoundedVec::new();\n vec.push(1);\n vec.extend_from_array([2, 3, 4]); // should panic\n }\n\n #[test(should_fail_with = \"extend_from_vector out of bounds\")]\n fn extend_vector_beyond_max_len() {\n let mut vec: BoundedVec<u32, 3> = BoundedVec::new();\n vec.push(1);\n vec.extend_from_vector([2, 3, 4].as_vector()); // S]should panic\n }\n\n #[test(should_fail_with = \"extend_from_bounded_vec out of bounds\")]\n fn extend_bounded_vec_beyond_max_len() {\n let mut vec: BoundedVec<u32, 3> = BoundedVec::new();\n let other: BoundedVec<u32, 5> = BoundedVec::from_array([1, 2, 3, 4, 5]);\n vec.extend_from_bounded_vec(other); // should panic\n }\n\n #[test]\n fn extend_with_empty_collections() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n let original_len = vec.len();\n\n vec.extend_from_array([]);\n assert_eq(vec.len(), original_len);\n\n vec.extend_from_vector([].as_vector());\n assert_eq(vec.len(), original_len);\n\n let empty: BoundedVec<u32, 3> = BoundedVec::new();\n vec.extend_from_bounded_vec(empty);\n assert_eq(vec.len(), original_len);\n }\n }\n\n mod storage {\n use crate::collections::bounded_vec::BoundedVec;\n\n #[test]\n fn storage_consistency() {\n let mut vec: BoundedVec<u32, 5> = BoundedVec::new();\n\n // test initial storage state\n assert_eq(vec.storage(), [0, 0, 0, 0, 0]);\n\n vec.push(1);\n vec.push(2);\n\n // test storage after modifications\n assert_eq(vec.storage(), [1, 2, 0, 0, 0]);\n\n // storage doesn't change length\n assert_eq(vec.len(), 2);\n assert_eq(vec.max_len(), 5);\n }\n\n #[test]\n fn storage_after_pop() {\n let mut vec: BoundedVec<u32, 3> = BoundedVec::from_array([1, 2, 3]);\n\n let _ = vec.pop();\n // after pop, the last element should be unmodified\n assert_eq(vec.storage(), [1, 2, 3]);\n assert_eq(vec.len(), 2);\n }\n\n #[test]\n fn vector_immutable() {\n let vec: BoundedVec<u32, 3> = BoundedVec::from_array([1, 2, 3]);\n let storage = vec.storage();\n\n assert_eq(storage, [1, 2, 3]);\n\n // Verify that the original vector is unchanged\n assert_eq(vec.len(), 3);\n assert_eq(vec.get(0), 1);\n assert_eq(vec.get(1), 2);\n assert_eq(vec.get(2), 3);\n }\n }\n}\n"
2188
+ },
2189
+ "71": {
2190
+ "function_locations": [
2191
+ {
2192
+ "name": "<impl Eq for PublicContext>::eq",
2193
+ "start": 3345
2194
+ },
2195
+ {
2196
+ "name": "PublicContext::new",
2197
+ "start": 3930
2198
+ },
2199
+ {
2200
+ "name": "PublicContext::emit_public_log_unsafe",
2201
+ "start": 4879
2202
+ },
2203
+ {
2204
+ "name": "PublicContext::note_hash_exists",
2205
+ "start": 5803
2206
+ },
2207
+ {
2208
+ "name": "PublicContext::l1_to_l2_msg_exists",
2209
+ "start": 6816
2210
+ },
2211
+ {
2212
+ "name": "PublicContext::nullifier_exists_unsafe",
2213
+ "start": 10031
2214
+ },
2215
+ {
2216
+ "name": "PublicContext::consume_l1_to_l2_message",
2217
+ "start": 11961
2218
+ },
2219
+ {
2220
+ "name": "PublicContext::message_portal",
2221
+ "start": 14085
2222
+ },
2223
+ {
2224
+ "name": "PublicContext::call_public_function",
2225
+ "start": 14975
2226
+ },
2227
+ {
2228
+ "name": "PublicContext::static_call_public_function",
2229
+ "start": 16607
2230
+ },
2231
+ {
2232
+ "name": "PublicContext::push_note_hash",
2233
+ "start": 18391
2234
+ },
2235
+ {
2236
+ "name": "PublicContext::push_nullifier_unsafe",
2237
+ "start": 19837
2238
+ },
2239
+ {
2240
+ "name": "PublicContext::this_address",
2241
+ "start": 20427
2242
+ },
2243
+ {
2244
+ "name": "PublicContext::maybe_msg_sender",
2245
+ "start": 21522
2246
+ },
2247
+ {
2248
+ "name": "PublicContext::selector",
2249
+ "start": 22294
2250
+ },
2251
+ {
2252
+ "name": "PublicContext::get_args_hash",
2253
+ "start": 23033
2254
+ },
2255
+ {
2256
+ "name": "PublicContext::transaction_fee",
2257
+ "start": 24425
2258
+ },
2259
+ {
2260
+ "name": "PublicContext::chain_id",
2261
+ "start": 25014
2262
+ },
2263
+ {
2264
+ "name": "PublicContext::version",
2265
+ "start": 25684
2266
+ },
2267
+ {
2268
+ "name": "PublicContext::block_number",
2269
+ "start": 26624
2270
+ },
2271
+ {
2272
+ "name": "PublicContext::timestamp",
2273
+ "start": 27736
2274
+ },
2275
+ {
2276
+ "name": "PublicContext::min_fee_per_l2_gas",
2277
+ "start": 29017
2278
+ },
2279
+ {
2280
+ "name": "PublicContext::min_fee_per_da_gas",
2281
+ "start": 29544
2282
+ },
2283
+ {
2284
+ "name": "PublicContext::l2_gas_left",
2285
+ "start": 29942
2286
+ },
2287
+ {
2288
+ "name": "PublicContext::da_gas_left",
2289
+ "start": 30558
2290
+ },
2291
+ {
2292
+ "name": "PublicContext::is_static_call",
2293
+ "start": 31023
2294
+ },
2295
+ {
2296
+ "name": "PublicContext::raw_storage_read",
2297
+ "start": 31865
2298
+ },
2299
+ {
2300
+ "name": "PublicContext::storage_read",
2301
+ "start": 32723
2302
+ },
2303
+ {
2304
+ "name": "PublicContext::raw_storage_write",
2305
+ "start": 33391
2306
+ },
2307
+ {
2308
+ "name": "PublicContext::storage_write",
2309
+ "start": 34125
2310
+ },
2311
+ {
2312
+ "name": "<impl Empty for PublicContext>::empty",
2313
+ "start": 34250
2314
+ }
2315
+ ],
2316
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/context/public_context.nr",
2317
+ "source": "use crate::{\n context::gas::GasOpts,\n hash::{\n compute_l1_to_l2_message_hash, compute_l1_to_l2_message_nullifier, compute_secret_hash,\n compute_siloed_nullifier,\n },\n oracle::avm,\n};\nuse crate::protocol::{\n abis::function_selector::FunctionSelector,\n address::{AztecAddress, EthAddress},\n constants::{MAX_U32_VALUE, NULL_MSG_SENDER_CONTRACT_ADDRESS},\n traits::{Empty, FromField, Packable, Serialize, ToField},\n utils::writer::Writer,\n};\n\n/// # PublicContext\n///\n/// The **main interface** between an #[external(\"public\")] function and the Aztec blockchain.\n///\n/// An instance of the PublicContext is initialized automatically at the outset of every public function, within the\n/// #[external(\"public\")] macro, so you'll never need to consciously instantiate this yourself.\n///\n/// The instance is always named `context`, and it will always be available within the body of every\n/// #[external(\"public\")] function in your smart contract.\n///\n/// Typical usage for a smart contract developer will be to call getter methods of the PublicContext.\n///\n/// _Pushing_ data and requests to the context is mostly handled within aztec-nr's own functions, so typically a smart\n/// contract developer won't need to call any setter methods directly.\n///\n/// ## Responsibilities\n/// - Exposes contextual data to a public function:\n/// - Data relating to how this public function was called:\n/// - msg_sender, this_address\n/// - Data relating to the current blockchain state:\n/// - timestamp, block_number, chain_id, version\n/// - Gas and fee information\n/// - Provides state access:\n/// - Read/write public storage (key-value mapping)\n/// - Check existence of notes and nullifiers (Some patterns use notes & nullifiers to store public (not private)\n/// information)\n/// - Enables consumption of L1->L2 messages.\n/// - Enables calls to other public smart contract functions:\n/// - Writes data to the blockchain:\n/// - Updates to public state variables\n/// - New public logs (for events)\n/// - New L2->L1 messages\n/// - New notes & nullifiers (E.g. pushing public info to notes/nullifiers, or for completing \"partial notes\")\n///\n/// ## Key Differences from Private Execution\n///\n/// Unlike private functions -- which are executed on the user's device and which can only reference historic state --\n/// public functions are executed by a block proposer and are executed \"live\" on the _current_ tip of the chain. This\n/// means public functions can:\n/// - Read and write _current_ public state\n/// - Immediately see the effects of earlier transactions in the same block\n///\n/// Also, public functions are executed within a zkVM (the \"AVM\"), so that they can _revert_ whilst still ensuring\n/// payment to the proposer and prover. (Private functions cannot revert: they either succeed, or they cannot be\n/// included).\n///\n/// ## Optimising Public Functions\n///\n/// Using the AVM to execute public functions means they compile down to \"AVM bytecode\" instead of the ACIR that\n/// private functions (standalone circuits) compile to. Therefore the approach to optimising a public function is\n/// fundamentally different from optimising a public function.\n///\npub struct PublicContext {\n args_hash: Option<Field>,\n compute_args_hash: fn() -> Field,\n}\n\nimpl Eq for PublicContext {\n fn eq(self, other: Self) -> bool {\n (self.args_hash == other.args_hash)\n // Can't compare the function compute_args_hash\n }\n}\n\nimpl PublicContext {\n /// Creates a new PublicContext instance.\n ///\n /// Low-level function: This is called automatically by the #[external(\"public\")] macro, so you shouldn't need to\n /// be called directly by smart contract developers.\n ///\n /// # Arguments\n /// * `compute_args_hash` - Function to compute the args_hash\n ///\n /// # Returns\n /// * A new PublicContext instance\n ///\n pub fn new(compute_args_hash: fn() -> Field) -> Self {\n PublicContext { args_hash: Option::none(), compute_args_hash }\n }\n\n /// Emits a _public_ log that will be visible onchain to everyone.\n ///\n /// # Arguments\n /// * `tag` - A tag placed at `fields[0]` of the emitted log. Nodes index logs by this value, allowing\n /// clients to efficiently query for matching logs without scanning all of them.\n /// * `log` - The data to log, must implement Serialize trait.\n ///\n /// ## Safety\n ///\n /// The `tag` should be domain-separated (e.g. via [`crate::protocol::hash::compute_log_tag`]) to prevent\n /// collisions between logs from different sources. Without domain separation, two unrelated log types that\n /// happen to share a raw tag value become indistinguishable. Prefer `self.emit(event)` for events, which\n /// handles tagging automatically.\n pub fn emit_public_log_unsafe<T>(_self: Self, tag: Field, log: T)\n where\n T: Serialize,\n {\n // We use a Writer to serialize the log directly after the tag, avoiding an extra O(n) copy that would\n // result from serializing first and then prepending the tag.\n let mut writer: Writer<1 + <T as Serialize>::N> = Writer::new();\n writer.write(tag);\n Serialize::stream_serialize(log, &mut writer);\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe { avm::emit_public_log(writer.finish().as_vector()) };\n }\n\n /// Checks if a given note hash exists in the note hash tree at a particular leaf_index.\n ///\n /// # Arguments\n /// * `note_hash` - The note hash to check for existence\n /// * `leaf_index` - The index where the note hash should be located\n ///\n /// # Returns\n /// * `bool` - True if the note hash exists at the specified index\n ///\n pub fn note_hash_exists(_self: Self, note_hash: Field, leaf_index: u64) -> bool {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::note_hash_exists(note_hash, leaf_index)\n }\n }\n\n /// Checks if a specific L1-to-L2 message exists in the L1-to-L2 message tree at a particular leaf index.\n ///\n /// Common use cases include token bridging, cross-chain governance, and triggering L2 actions based on L1 events.\n ///\n /// This function should be called before attempting to consume an L1-to-L2 message.\n ///\n /// # Arguments\n /// * `msg_hash` - Hash of the L1-to-L2 message to check\n /// * `msg_leaf_index` - The index where the message should be located\n ///\n /// # Returns\n /// * `bool` - True if the message exists at the specified index\n ///\n /// # Advanced\n /// * Uses the AVM l1_to_l2_msg_exists opcode for tree lookup\n /// * Messages are copied from L1 Inbox to L2 by block proposers\n ///\n pub fn l1_to_l2_msg_exists(_self: Self, msg_hash: Field, msg_leaf_index: Field) -> bool {\n // Safety: AVM opcodes are constrained by the AVM itself TODO(alvaro): Make l1l2msg leaf index a u64 upstream\n unsafe {\n avm::l1_to_l2_msg_exists(msg_hash, msg_leaf_index as u64)\n }\n }\n\n /// Returns `true` if an `unsiloed_nullifier` has been emitted by `contract_address`.\n ///\n /// Note that unsiloed nullifiers are not the actual values stored in the nullifier tree: they are first siloed via\n /// [`crate::hash::compute_siloed_nullifier`] with the emitting contract's address.\n ///\n /// ## Use Cases\n ///\n /// Nullifiers are typically used as a _privacy-preserving_ record of a one-time action, but they can also be used\n /// to efficiently record _public_ one-time actions as well. This is cheaper than using public storage, and has the\n /// added benefit of the nullifier being emittable from a private function.\n ///\n /// An example is to check whether a contract has been published: we emit a nullifier that is deterministic and\n /// which has a _public_ preimage.\n ///\n /// ## Public vs Private\n ///\n /// In general, one should not attempt to prove nullifier non-existence in private, as that will not consider the\n /// possibility of the nullifier having been emitted in any transaction between the anchor block and the inclusion\n /// block. Private functions instead prove existence via\n /// [`crate::context::PrivateContext::assert_nullifier_exists`]\n /// and 'prove' non-existence by _emitting_ the nullifer, which would cause the transaction to fail if the\n /// nullifier existed.\n ///\n /// This is not the case in public functions, which **do** have access to the tip of the blockchain and so can\n /// reliably prove whether a nullifier exists or not.\n ///\n /// ## Safety\n ///\n /// While it is safe to rely on this function's return value to determine if a nullifier exists or not, it is often\n /// **not** safe to infer additional information from that. In particular, it is **unsafe** to infer that the\n /// existence of a nullifier emitted from a private function implies that all other side-effects of said private\n /// execution have been completed, more concretely that any enqueued public calls have been executed.\n ///\n /// For example, if a function in contract `A` privately emits nullifier `X` and then enqueues public function `Y`,\n /// then it is **unsafe** for a contract `B` to infer that `Y` has alredy executed simply because `X` exists.\n ///\n /// This is because **all** private transaction effects are committed _before_ enqueued public functions are run\n /// (in\n /// order to not reveal detailed timing information about the transaction), so it is possible to observe a\n /// nullifier that was emitted alongside the enqueuing of a public call **before** said call has been completed.\n ///\n /// ## Cost\n ///\n /// This emits the `CHECKNULLIFIEREXISTS` opcode, which conceptually performs a merkle inclusion proof on the\n /// nullifier tree (both when the nullifier exists and when it doesn't).\n pub fn nullifier_exists_unsafe(_self: Self, unsiloed_nullifier: Field, contract_address: AztecAddress) -> bool {\n let siloed_nullifier = compute_siloed_nullifier(contract_address, unsiloed_nullifier);\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::nullifier_exists(siloed_nullifier)\n }\n }\n\n /// Consumes a message sent from Ethereum (L1) to Aztec (L2) -- effectively marking it as \"read\".\n ///\n /// Use this function if you only want the message to ever be \"referred to\" once. Once consumed using this method,\n /// the message cannot be consumed again, because a nullifier is emitted. If your use case wants for the message to\n /// be read unlimited times, then you can always read any historic message from the L1-to-L2 messages tree, using\n /// the `l1_to_l2_msg_exists` method. Messages never technically get deleted from that tree.\n ///\n /// The message will first be inserted into an Aztec \"Inbox\" smart contract on L1. It will not be available for\n /// consumption immediately. Messages get copied-over from the L1 Inbox to L2 by the next Proposer in batches. So\n /// you will need to wait until the messages are copied before you can consume them.\n ///\n /// # Arguments\n /// * `content` - The message content that was sent from L1\n /// * `secret` - Secret fields used for message privacy (if needed)\n /// * `sender` - Ethereum address that sent the message\n /// * `leaf_index` - Index of the message in the L1-to-L2 message tree\n ///\n /// # Advanced\n /// * Validates message existence in the L1-to-L2 message tree\n /// * Prevents double-consumption by emitting a nullifier\n /// * Message hash is computed from all parameters + chain context\n /// * Will revert if message doesn't exist or was already consumed\n ///\n pub fn consume_l1_to_l2_message<let N: u32>(\n self: Self,\n content: Field,\n secret: [Field; N],\n sender: EthAddress,\n leaf_index: Field,\n ) {\n let secret_hash = compute_secret_hash(secret);\n let message_hash = compute_l1_to_l2_message_hash(\n sender,\n self.chain_id(),\n /*recipient=*/\n self.this_address(),\n self.version(),\n content,\n secret_hash,\n leaf_index,\n );\n let nullifier = compute_l1_to_l2_message_nullifier(message_hash, secret);\n\n assert(!self.nullifier_exists_unsafe(nullifier, self.this_address()), \"L1-to-L2 message is already nullified\");\n assert(self.l1_to_l2_msg_exists(message_hash, leaf_index), \"Tried to consume nonexistent L1-to-L2 message\");\n\n self.push_nullifier_unsafe(nullifier);\n }\n\n /// Sends an \"L2 -> L1 message\" from this function (Aztec, L2) to a smart contract on Ethereum (L1). L1 contracts\n /// which are designed to send/receive messages to/from Aztec are called \"Portal Contracts\".\n ///\n /// Common use cases include withdrawals, cross-chain asset transfers, and triggering L1 actions based on L2 state\n /// changes.\n ///\n /// The message will be inserted into an Aztec \"Outbox\" contract on L1, when this transaction's block is proposed\n /// to L1. Sending the message will not result in any immediate state changes in the target portal contract. The\n /// message will need to be manually consumed from the Outbox through a separate Ethereum transaction: a user will\n /// need to call a function of the portal contract -- a function specifically designed to make a call to the Outbox\n /// to consume the message. The message will only be available for consumption once the _epoch_ proof has been\n /// submitted. Given that there are multiple Aztec blocks within an epoch, it might take some time for this epoch\n /// proof to be submitted -- especially if the block was near the start of an epoch.\n ///\n /// # Arguments\n /// * `recipient` - Ethereum address that will receive the message\n /// * `content` - Message content (32 bytes as a Field element)\n ///\n pub fn message_portal(_self: Self, recipient: EthAddress, content: Field) {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe { avm::send_l2_to_l1_msg(recipient, content) };\n }\n\n /// Calls a public function on another contract.\n ///\n /// Will revert if the called function reverts or runs out of gas.\n ///\n /// # Arguments\n /// * `contract_address` - Address of the contract to call\n /// * `function_selector` - Function to call on the target contract\n /// * `args` - Arguments to pass to the function\n /// * `gas_opts` - An optional allocation of gas to the called function.\n ///\n /// # Returns\n /// * `[Field]` - Return data from the called function\n ///\n pub unconstrained fn call_public_function<let N: u32>(\n _self: Self,\n contract_address: AztecAddress,\n function_selector: FunctionSelector,\n args: [Field; N],\n gas_opts: GasOpts,\n ) -> [Field] {\n let calldata = [function_selector.to_field()].concat(args);\n\n avm::call(\n gas_opts.l2_gas.unwrap_or(MAX_U32_VALUE),\n gas_opts.da_gas.unwrap_or(MAX_U32_VALUE),\n contract_address,\n calldata,\n );\n // Use success_copy to determine whether the call succeeded\n let success = avm::success_copy();\n\n let result_data = avm::returndata_copy(0, avm::returndata_size());\n if !success {\n // Rethrow the revert data.\n avm::revert(result_data);\n }\n result_data\n }\n\n /// Makes a read-only call to a public function on another contract.\n ///\n /// This is similar to Solidity's `staticcall`. The called function cannot modify state or emit events. Any nested\n /// calls are constrained to also be staticcalls.\n ///\n /// Useful for querying data from other contracts safely.\n ///\n /// Will revert if the called function reverts or runs out of gas.\n ///\n /// # Arguments\n /// * `contract_address` - Address of the contract to call\n /// * `function_selector` - Function to call on the target contract\n /// * `args` - Array of arguments to pass to the called function\n /// * `gas_opts` - An optional allocation of gas to the called function.\n ///\n /// # Returns\n /// * `[Field]` - Return data from the called function\n ///\n pub unconstrained fn static_call_public_function<let N: u32>(\n _self: Self,\n contract_address: AztecAddress,\n function_selector: FunctionSelector,\n args: [Field; N],\n gas_opts: GasOpts,\n ) -> [Field] {\n let calldata = [function_selector.to_field()].concat(args);\n\n avm::call_static(\n gas_opts.l2_gas.unwrap_or(MAX_U32_VALUE),\n gas_opts.da_gas.unwrap_or(MAX_U32_VALUE),\n contract_address,\n calldata,\n );\n // Use success_copy to determine whether the call succeeded\n let success = avm::success_copy();\n\n let result_data = avm::returndata_copy(0, avm::returndata_size());\n if !success {\n // Rethrow the revert data.\n avm::revert(result_data);\n }\n result_data\n }\n\n /// Adds a new note hash to the Aztec blockchain's global Note Hash Tree.\n ///\n /// Notes are ordinarily constructed and emitted by _private_ functions, to ensure that both the content of the\n /// note, and the contract that emitted the note, stay private.\n ///\n /// There are however some useful patterns whereby a note needs to contain _public_ data. The ability to push a new\n /// note_hash from a _public_ function means that notes can be injected with public data immediately -- as soon as\n /// the public value is known. The slower alternative would be to submit a follow-up transaction so that a private\n /// function can inject the data. Both are possible on Aztec.\n ///\n /// Search \"Partial Note\" for a very common pattern which enables a note to be \"partially\" populated with some data\n /// in a _private_ function, and then later \"completed\" with some data in a public function.\n ///\n /// # Arguments\n /// * `note_hash` - The hash of the note to add to the tree\n ///\n /// # Advanced\n /// * The note hash will be siloed with the contract address by the protocol\n ///\n pub fn push_note_hash(_self: Self, note_hash: Field) {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe { avm::emit_note_hash(note_hash) };\n }\n\n /// Creates a new [nullifier](crate::nullifier).\n ///\n /// While nullifiers are primarily intended as a _privacy-preserving_ record of a one-time action, they can also\n /// be used to efficiently record _public_ one-time actions. This function allows creating nullifiers from public\n /// contract functions, which behave just like those created from private functions.\n ///\n /// ## Safety\n ///\n /// This is a low-level function that must be used with great care to avoid subtle corruption of contract state.\n ///\n /// In particular, callers must ensure all nullifiers created by a contract are properly domain-separated, so that\n /// unrelated components don't interfere with one another (e.g. a transaction nullifier accidentally marking a\n /// variable as initialized). Note nullifiers should only be created via\n /// [`crate::context::PrivateContext::push_nullifier_for_note_hash`].\n ///\n /// ## Advanced\n ///\n /// The raw `nullifier` is not what is inserted into the Aztec state tree: it will be first siloed by contract\n /// address via [`crate::protocol::hash::compute_siloed_nullifier`] in order to prevent accidental or malicious\n /// interference of nullifiers from different contracts.\n pub fn push_nullifier_unsafe(_self: Self, nullifier: Field) {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe { avm::emit_nullifier(nullifier) };\n }\n\n /// Returns the address of the current contract being executed.\n ///\n /// This is equivalent to `address(this)` in Solidity (hence the name). Use this to identify the current contract's\n /// address, commonly needed for access control or when interacting with other contracts.\n ///\n /// # Returns\n /// * `AztecAddress` - The contract address of the current function being executed.\n ///\n pub fn this_address(_self: Self) -> AztecAddress {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::address()\n }\n }\n\n /// Returns the contract address that initiated this function call.\n ///\n /// This is similar to `msg.sender` in Solidity (hence the name).\n ///\n /// Important Note: If the calling function is a _private_ function, then it had the option of hiding its address\n /// when enqueuing this public function call. In such cases, this method will return `Option<AztecAddress>::none`.\n /// If the calling function is a _public_ function, it will always return an `Option<AztecAddress>::some` (i.e. a\n /// non-null value).\n ///\n /// # Returns\n /// * `Option<AztecAddress>` - The address of the smart contract that called this function (be it an app contract\n /// or a user's account contract).\n ///\n /// # Advanced\n /// * Value is provided by the AVM sender opcode\n /// * In nested calls, this is the immediate caller, not the original transaction sender\n ///\n pub fn maybe_msg_sender(_self: Self) -> Option<AztecAddress> {\n // Safety: AVM opcodes are constrained by the AVM itself\n let maybe_msg_sender = unsafe { avm::sender() };\n if maybe_msg_sender == NULL_MSG_SENDER_CONTRACT_ADDRESS {\n Option::none()\n } else {\n Option::some(maybe_msg_sender)\n }\n }\n\n /// Returns the function selector of the currently-executing function.\n ///\n /// This is similar to `msg.sig` in Solidity, returning the first 4 bytes of the function signature.\n ///\n /// # Returns\n /// * `FunctionSelector` - The 4-byte function identifier\n ///\n /// # Advanced\n /// * Extracted from the first element of calldata\n /// * Used internally for function dispatch in the AVM\n ///\n pub fn selector(_self: Self) -> FunctionSelector {\n // The selector is the first element of the calldata when calling a public function through dispatch.\n // Safety: AVM opcodes are constrained by the AVM itself.\n let raw_selector: [Field; 1] = unsafe { avm::calldata_copy(0, 1) };\n FunctionSelector::from_field(raw_selector[0])\n }\n\n /// Returns the hash of the arguments passed to the current function.\n ///\n /// Very low-level function: The #[external(\"public\")] macro uses this internally. Smart contract developers\n /// typically won't need to access this directly as arguments are automatically made available.\n ///\n /// # Returns\n /// * `Field` - Hash of the function arguments\n ///\n pub fn get_args_hash(mut self) -> Field {\n if !self.args_hash.is_some() {\n self.args_hash = Option::some((self.compute_args_hash)());\n }\n\n self.args_hash.unwrap_unchecked()\n }\n\n /// Returns the \"transaction fee\" for the current transaction. This is the final tx fee that will be deducted from\n /// the fee_payer's \"fee-juice\" balance (in the protocol's Base Rollup circuit).\n ///\n /// # Returns\n /// * `Field` - The actual, final cost of the transaction, taking into account: the actual gas used during the\n /// setup and app-logic phases, and the fixed amount of gas that's been allocated by the user for the teardown\n /// phase. I.e. effectiveL2FeePerGas * l2GasUsed + effectiveDAFeePerGas * daGasUsed\n ///\n /// This will return `0` during the \"setup\" and \"app-logic\" phases of tx execution (because the final tx fee is not\n /// known at that time). This will only return a nonzero value during the \"teardown\" phase of execution, where the\n /// final tx fee can actually be computed.\n ///\n /// Regardless of _when_ this function is called during the teardown phase, it will always return the same final tx\n /// fee value. The teardown phase does not consume a variable amount of gas: it always consumes a pre-allocated\n /// amount of gas, as specified by the user when they generate their tx.\n ///\n pub fn transaction_fee(_self: Self) -> Field {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::transaction_fee()\n }\n }\n\n /// Returns the chain ID of the current network.\n ///\n /// This is similar to `block.chainid` in Solidity. Returns the unique identifier for the blockchain network this\n /// transaction is executing on.\n ///\n /// Helps prevent cross-chain replay attacks. Useful if implementing multi-chain contract logic.\n ///\n /// # Returns\n /// * `Field` - The chain ID as a field element\n ///\n pub fn chain_id(_self: Self) -> Field {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::chain_id()\n }\n }\n\n /// Returns the Aztec protocol version that this transaction is executing under. Different versions may have\n /// different rules, opcodes, or cryptographic primitives.\n ///\n /// This is similar to how Ethereum has different EVM versions.\n ///\n /// Useful for forward/backward compatibility checks\n ///\n /// Not to be confused with contract versions; this is the protocol version.\n ///\n /// # Returns\n /// * `Field` - The protocol version as a field element\n ///\n pub fn version(_self: Self) -> Field {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::version()\n }\n }\n /// Returns the current block number.\n ///\n /// This is similar to `block.number` in Solidity.\n ///\n /// Note: the current block number is only available within a public function (as opposed to a private function).\n ///\n /// Note: the time intervals between blocks should not be relied upon as being consistent:\n /// - Timestamps of blocks fall within a range, rather than at exact regular intervals.\n /// - Slots can be missed.\n /// - Protocol upgrades can completely change the intervals between blocks (and indeed the current roadmap plans to\n /// reduce the time between blocks, eventually). Use `context.timestamp()` for more-reliable time-based logic.\n ///\n /// # Returns\n /// * `u32` - The current block number\n ///\n pub fn block_number(_self: Self) -> u32 {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::block_number()\n }\n }\n\n /// Returns the timestamp of the current block.\n ///\n /// This is similar to `block.timestamp` in Solidity.\n ///\n /// All functions of all transactions in a block share the exact same timestamp (even though technically each\n /// transaction is executed one-after-the-other).\n ///\n /// Important note: Timestamps of Aztec blocks are not at reliably-fixed intervals. The proposer of the block has\n /// some flexibility to choose a timestamp which is in a valid _range_: Obviously the timestamp of this block must\n /// be strictly greater than that of the previous block, and must must be less than the timestamp of whichever\n /// ethereum block the aztec block is proposed to. Furthermore, if the timestamp is not deemed close enough to the\n /// actual current time, the committee of validators will not attest to the block.\n ///\n /// # Returns\n /// * `u64` - Unix timestamp in seconds\n ///\n pub fn timestamp(_self: Self) -> u64 {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::timestamp()\n }\n }\n\n /// Returns the fee per unit of L2 gas for this transaction (aka the \"L2 gas price\"), as chosen by the user.\n ///\n /// L2 gas covers the cost of executing public functions and handling side-effects within the AVM.\n ///\n /// # Returns\n /// * `u128` - Fee per unit of L2 gas\n ///\n /// Wallet developers should be mindful that the choice of gas price (which is publicly visible) can leak\n /// information about the user, e.g.:\n /// - which wallet software the user is using;\n /// - the amount of time which has elapsed from the time the user's wallet chose a gas price (at the going rate),\n /// to the time of tx submission. This can give clues about the proving time, and hence the nature of the tx.\n /// - the urgency of the transaction (which is kind of unavoidable, if the tx is indeed urgent).\n /// - the wealth of the user.\n /// - the exact user (if the gas price is explicitly chosen by the user to be some unique number like 0.123456789,\n /// or their favorite number). Wallet devs might wish to consider fuzzing the choice of gas price.\n ///\n pub fn min_fee_per_l2_gas(_self: Self) -> u128 {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::min_fee_per_l2_gas()\n }\n }\n\n /// Returns the fee per unit of DA (Data Availability) gas (aka the \"DA gas price\").\n ///\n /// DA gas covers the cost of making transaction data available on L1.\n ///\n /// See the warning in `min_fee_per_l2_gas` for how gas prices can be leaky.\n ///\n /// # Returns\n /// * `u128` - Fee per unit of DA gas\n ///\n pub fn min_fee_per_da_gas(_self: Self) -> u128 {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::min_fee_per_da_gas()\n }\n }\n\n /// Returns the remaining L2 gas available for this transaction.\n ///\n /// Different AVM opcodes consume different amounts of gas.\n ///\n /// # Returns\n /// * `u32` - Remaining L2 gas units\n ///\n pub fn l2_gas_left(_self: Self) -> u32 {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::l2_gas_left()\n }\n }\n\n /// Returns the remaining DA (Data Availability) gas available for this transaction.\n ///\n /// DA gas is consumed when emitting data that needs to be made available on L1, such as public logs or state\n /// updates. All of the side-effects from the private part of the tx also consume DA gas before execution of any\n /// public functions even begins.\n ///\n /// # Returns\n /// * `u32` - Remaining DA gas units\n ///\n pub fn da_gas_left(_self: Self) -> u32 {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::da_gas_left()\n }\n }\n\n /// Checks if the current execution is within a staticcall context, where no state changes or logs are allowed to\n /// be emitted (by this function or any nested function calls).\n ///\n /// # Returns\n /// * `bool` - True if in staticcall context, false otherwise\n ///\n pub fn is_static_call(_self: Self) -> bool {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe {\n avm::is_static_call()\n }\n }\n\n /// Reads raw field values from public storage. Reads N consecutive storage slots starting from the given slot.\n ///\n /// Very low-level function. Users should typically use the public state variable abstractions to perform reads:\n /// PublicMutable & PublicImmutable.\n ///\n /// # Arguments\n /// * `storage_slot` - The starting storage slot to read from\n ///\n /// # Returns\n /// * `[Field; N]` - Array of N field values from consecutive storage slots\n ///\n /// # Generic Parameters\n /// * `N` - the number of consecutive slots to return, starting from the `storage_slot`.\n ///\n pub fn raw_storage_read<let N: u32>(self: Self, storage_slot: Field) -> [Field; N] {\n let mut out = [0; N];\n for i in 0..N {\n // Safety: AVM opcodes are constrained by the AVM itself\n out[i] = unsafe { avm::storage_read(storage_slot + i as Field, self.this_address().to_field()) };\n }\n out\n }\n\n /// Reads a typed value from public storage.\n ///\n /// Low-level function. Users should typically use the public state variable abstractions to perform reads:\n /// PublicMutable & PublicImmutable.\n ///\n /// # Arguments\n /// * `storage_slot` - The storage slot to read from\n ///\n /// # Returns\n /// * `T` - The deserialized value from storage\n ///\n /// # Generic Parameters\n /// * `T` - The type that the caller expects to read from the `storage_slot`.\n ///\n pub fn storage_read<T>(self, storage_slot: Field) -> T\n where\n T: Packable,\n {\n T::unpack(self.raw_storage_read(storage_slot))\n }\n\n /// Writes raw field values to public storage. Writes to N consecutive storage slots starting from the given slot.\n ///\n /// Very low-level function. Users should typically use the public state variable abstractions to perform writes:\n /// PublicMutable & PublicImmutable.\n ///\n /// Public storage writes take effect immediately.\n ///\n /// # Arguments\n /// * `storage_slot` - The starting storage slot to write to\n /// * `values` - Array of N Fields to write to storage\n ///\n pub fn raw_storage_write<let N: u32>(_self: Self, storage_slot: Field, values: [Field; N]) {\n for i in 0..N {\n // Safety: AVM opcodes are constrained by the AVM itself\n unsafe { avm::storage_write(storage_slot + i as Field, values[i]) };\n }\n }\n\n /// Writes a typed value to public storage.\n ///\n /// Low-level function. Users should typically use the public state variable abstractions to perform writes:\n /// PublicMutable & PublicImmutable.\n ///\n /// # Arguments\n /// * `storage_slot` - The storage slot to write to\n /// * `value` - The typed value to write to storage\n ///\n /// # Generic Parameters\n /// * `T` - The type to write to storage.\n ///\n pub fn storage_write<T>(self, storage_slot: Field, value: T)\n where\n T: Packable,\n {\n self.raw_storage_write(storage_slot, value.pack());\n }\n}\n\nimpl Empty for PublicContext {\n fn empty() -> Self {\n PublicContext::new(|| 0)\n }\n}\n"
2318
+ },
2319
+ "73": {
2320
+ "function_locations": [
2321
+ {
2322
+ "name": "<impl From<UtilityContextData> for UtilityContext>::from",
2323
+ "start": 560
2324
+ },
2325
+ {
2326
+ "name": "UtilityContext::new",
2327
+ "start": 751
2328
+ },
2329
+ {
2330
+ "name": "UtilityContext::at",
2331
+ "start": 858
2332
+ },
2333
+ {
2334
+ "name": "UtilityContext::block_header",
2335
+ "start": 1230
2336
+ },
2337
+ {
2338
+ "name": "UtilityContext::block_number",
2339
+ "start": 1302
2340
+ },
2341
+ {
2342
+ "name": "UtilityContext::timestamp",
2343
+ "start": 1386
2344
+ },
2345
+ {
2346
+ "name": "UtilityContext::this_address",
2347
+ "start": 1479
2348
+ },
2349
+ {
2350
+ "name": "UtilityContext::maybe_msg_sender",
2351
+ "start": 2268
2352
+ },
2353
+ {
2354
+ "name": "UtilityContext::version",
2355
+ "start": 2472
2356
+ },
2357
+ {
2358
+ "name": "UtilityContext::chain_id",
2359
+ "start": 2552
2360
+ },
2361
+ {
2362
+ "name": "UtilityContext::raw_storage_read",
2363
+ "start": 2699
2364
+ },
2365
+ {
2366
+ "name": "UtilityContext::storage_read",
2367
+ "start": 2891
2368
+ }
2369
+ ],
2370
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/context/utility_context.nr",
2371
+ "source": "use crate::oracle::{execution::{get_utility_context, UtilityContextData}, storage::storage_read};\nuse crate::protocol::{\n abis::block_header::BlockHeader, address::AztecAddress, constants::NULL_MSG_SENDER_CONTRACT_ADDRESS,\n traits::Packable,\n};\n\n// If you'll modify this struct don't forget to update utility_context.ts as well.\npub struct UtilityContext {\n block_header: BlockHeader,\n contract_address: AztecAddress,\n msg_sender: AztecAddress,\n}\n\nimpl From<UtilityContextData> for UtilityContext {\n fn from(data: UtilityContextData) -> Self {\n Self { block_header: data.block_header, contract_address: data.contract_address, msg_sender: data.msg_sender }\n }\n}\n\nimpl UtilityContext {\n pub unconstrained fn new() -> Self {\n get_utility_context()\n }\n\n pub unconstrained fn at(contract_address: AztecAddress) -> Self {\n // We get a context with default contract address, and then we construct the final context with the provided\n // contract address.\n let default_context = get_utility_context();\n\n Self { block_header: default_context.block_header, contract_address, msg_sender: default_context.msg_sender }\n }\n\n pub fn block_header(self) -> BlockHeader {\n self.block_header\n }\n\n pub fn block_number(self) -> u32 {\n self.block_header.block_number()\n }\n\n pub fn timestamp(self) -> u64 {\n self.block_header.timestamp()\n }\n\n pub fn this_address(self) -> AztecAddress {\n self.contract_address\n }\n\n /// Returns the address that initiated this utility call.\n ///\n /// This is similar to `msg.sender` in Solidity (hence the name). A utility function called by another contract\n /// (via a nested utility call) sees that contract's address. A utility function invoked directly (e.g. by a wallet\n /// or dApp) has no caller and sees `Option::none`.\n ///\n /// Important Note: utility functions are simulated client-side and never proven, so this value is whatever the\n /// simulator (PXE) set it to: nothing about it is verified onchain. It exists to assist simulation in a\n /// cooperative environment and must not be relied on as a security guarantee.\n pub unconstrained fn maybe_msg_sender(self) -> Option<AztecAddress> {\n if self.msg_sender == NULL_MSG_SENDER_CONTRACT_ADDRESS {\n Option::none()\n } else {\n Option::some(self.msg_sender)\n }\n }\n\n pub fn version(self) -> Field {\n self.block_header.version()\n }\n\n pub fn chain_id(self) -> Field {\n self.block_header.chain_id()\n }\n\n pub unconstrained fn raw_storage_read<let N: u32>(self: Self, storage_slot: Field) -> [Field; N] {\n storage_read(self.block_header, self.this_address(), storage_slot)\n }\n\n pub unconstrained fn storage_read<T>(self, storage_slot: Field) -> T\n where\n T: Packable,\n {\n T::unpack(self.raw_storage_read(storage_slot))\n }\n}\n"
2372
+ },
2373
+ "75": {
2374
+ "function_locations": [
2375
+ {
2376
+ "name": "ContractSelfPublic<Storage, CallSelf, CallSelfStatic, CallInternal>::new",
2377
+ "start": 3401
2378
+ },
2379
+ {
2380
+ "name": "ContractSelfPublic<Storage, CallSelf, CallSelfStatic, CallInternal>::msg_sender",
2381
+ "start": 4116
2382
+ },
2383
+ {
2384
+ "name": "ContractSelfPublic<Storage, CallSelf, CallSelfStatic, CallInternal>::emit",
2385
+ "start": 5018
2386
+ },
2387
+ {
2388
+ "name": "ContractSelfPublic<Storage, CallSelf, CallSelfStatic, CallInternal>::call",
2389
+ "start": 5659
2390
+ },
2391
+ {
2392
+ "name": "ContractSelfPublic<Storage, CallSelf, CallSelfStatic, CallInternal>::view",
2393
+ "start": 6480
2394
+ }
2395
+ ],
2396
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/contract_self/contract_self_public.nr",
2397
+ "source": "//! The `self` contract value for public execution contexts.\n\nuse crate::{\n context::{calls::{PublicCall, PublicStaticCall}, PublicContext},\n event::{event_emission::emit_event_in_public, event_interface::EventInterface},\n};\nuse crate::protocol::{address::AztecAddress, traits::{Deserialize, Serialize}};\n\n/// Core interface for interacting with aztec-nr contract features in public execution contexts.\n///\n/// This struct is automatically injected into every [`external`](crate::macros::functions::external) and\n/// [`internal`](crate::macros::functions::internal) contract function marked with `\"public\"` by the Aztec macro\n/// system and is accessible through the `self` variable.\n///\n/// ## Type Parameters\n///\n/// - `Storage`: The contract's storage struct (defined with [`storage`](crate::macros::storage::storage), or `()` if\n/// the contract has no storage\n/// - `CallSelf`: Macro-generated type for calling contract's own non-view functions\n/// - `CallSelfStatic`: Macro-generated type for calling contract's own view functions\n/// - `CallInternal`: Macro-generated type for calling internal functions\npub struct ContractSelfPublic<Storage, CallSelf, CallSelfStatic, CallInternal> {\n /// The address of this contract\n pub address: AztecAddress,\n\n /// The contract's storage instance, representing the struct to which the\n /// [`storage`](crate::macros::storage::storage) macro was applied in your contract. If the contract has no\n /// storage, the type of this will be `()`.\n ///\n /// This storage instance is specialized for the current execution context (public) and\n /// provides access to the contract's state variables.\n ///\n /// ## Developer Note\n ///\n /// If you've arrived here while trying to access your contract's storage while the `Storage` generic type is set\n /// to unit type `()`, it means you haven't yet defined a Storage struct using the\n /// [`storage`](crate::macros::storage::storage) macro in your contract. For guidance on setting this up, please\n /// refer to our docs: https://docs.aztec.network/developers/docs/guides/smart_contracts/storage\n pub storage: Storage,\n\n /// The public execution context.\n pub context: PublicContext,\n\n /// Provides type-safe methods for calling this contract's own non-view functions.\n ///\n /// Example API:\n /// ```noir\n /// self.call_self.some_public_function(args)\n /// ```\n pub call_self: CallSelf,\n\n /// Provides type-safe methods for calling this contract's own view functions.\n ///\n /// Example API:\n /// ```noir\n /// self.call_self_static.some_view_function(args)\n /// ```\n pub call_self_static: CallSelfStatic,\n\n /// Provides type-safe methods for calling internal functions.\n ///\n /// Example API:\n /// ```noir\n /// self.internal.some_internal_function(args)\n /// ```\n pub internal: CallInternal,\n}\n\nimpl<Storage, CallSelf, CallSelfStatic, CallInternal> ContractSelfPublic<Storage, CallSelf, CallSelfStatic, CallInternal> {\n /// Creates a new `ContractSelfPublic` instance for a public function.\n ///\n /// This constructor is called automatically by the macro system and should not be called directly.\n pub fn new(\n context: PublicContext,\n storage: Storage,\n call_self: CallSelf,\n call_self_static: CallSelfStatic,\n internal: CallInternal,\n ) -> Self {\n Self { context, storage, address: context.this_address(), call_self, call_self_static, internal }\n }\n\n /// The address of the contract address that made this function call.\n ///\n /// This is similar to Solidity's `msg.sender` value.\n ///\n /// ## Incognito Calls\n ///\n /// Contracts can call public functions from private ones hiding their identity (see\n ///\n /// [`ContractSelfPrivate::enqueue_incognito`](crate::contract_self::ContractSelfPrivate::enqueue_incognito)).\n /// This function reverts when executed in such a context.\n ///\n /// If you need to handle these cases, use [`PublicContext::maybe_msg_sender`].\n pub fn msg_sender(self: Self) -> AztecAddress {\n self.context.maybe_msg_sender().unwrap()\n }\n\n /// Emits an event publicly.\n ///\n /// Public events are emitted as plaintext and are therefore visible to everyone. This is is the same as Solidity\n /// events on EVM chains.\n ///\n /// Unlike private events, they don't require delivery of an event message.\n ///\n /// # Example\n /// ```noir\n /// #[event]\n /// struct Update { value: Field }\n ///\n /// #[external(\"public\")]\n /// fn publish_update(value: Field) {\n /// self.emit(Update { value });\n /// }\n /// ```\n ///\n /// # Cost\n ///\n /// Public event emission is achieved by emitting public transaction logs. A total of `N+1` fields are emitted,\n /// where `N` is the serialization length of the event.\n pub unconstrained fn emit<Event>(&mut self, event: Event)\n where\n Event: EventInterface + Serialize,\n {\n emit_event_in_public(self.context, event);\n }\n\n /// Makes a public contract call.\n ///\n /// Will revert if the called function reverts or runs out of gas.\n ///\n /// # Arguments\n /// * `call` - The object representing the public function to invoke.\n ///\n /// # Returns\n /// * `T` - Whatever data the called function has returned.\n ///\n /// # Example\n /// ```noir\n /// self.call(Token::at(address).transfer_in_public(recipient, amount));\n /// ```\n ///\n pub unconstrained fn call<let M: u32, let N: u32, T>(self, call: PublicCall<M, N, T>) -> T\n where\n T: Deserialize,\n {\n call.call(self.context)\n }\n\n /// Makes a public read-only contract call.\n ///\n /// This is similar to Solidity's `staticcall`. The called function cannot modify state or emit events. Any nested\n /// calls are constrained to also be static calls.\n ///\n /// Will revert if the called function reverts or runs out of gas.\n ///\n /// # Arguments\n /// * `call` - The object representing the read-only public function to invoke.\n ///\n /// # Returns\n /// * `T` - Whatever data the called function has returned.\n ///\n /// # Example\n /// ```noir\n /// self.view(Token::at(address).balance_of_public(recipient));\n /// ```\n ///\n pub unconstrained fn view<let M: u32, let N: u32, T>(self, call: PublicStaticCall<M, N, T>) -> T\n where\n T: Deserialize,\n {\n call.view(self.context)\n }\n}\n"
2398
+ },
2399
+ "78": {
2400
+ "function_locations": [
2401
+ {
2402
+ "name": "<impl ArrayOracles for EphemeralOracles>::len_oracle",
2403
+ "start": 1625
2404
+ },
2405
+ {
2406
+ "name": "<impl ArrayOracles for EphemeralOracles>::push_oracle",
2407
+ "start": 1763
2408
+ },
2409
+ {
2410
+ "name": "<impl ArrayOracles for EphemeralOracles>::pop_oracle",
2411
+ "start": 1896
2412
+ },
2413
+ {
2414
+ "name": "<impl ArrayOracles for EphemeralOracles>::get_oracle",
2415
+ "start": 2032
2416
+ },
2417
+ {
2418
+ "name": "<impl ArrayOracles for EphemeralOracles>::set_oracle",
2419
+ "start": 2181
2420
+ },
2421
+ {
2422
+ "name": "<impl ArrayOracles for EphemeralOracles>::remove_oracle",
2423
+ "start": 2309
2424
+ },
2425
+ {
2426
+ "name": "<impl ArrayOracles for EphemeralOracles>::clear_oracle",
2427
+ "start": 2419
2428
+ },
2429
+ {
2430
+ "name": "<impl Serialize for UnconstrainedArray<T, EphemeralOracles>>::serialize",
2431
+ "start": 2754
2432
+ },
2433
+ {
2434
+ "name": "<impl Serialize for UnconstrainedArray<T, EphemeralOracles>>::stream_serialize",
2435
+ "start": 2849
2436
+ },
2437
+ {
2438
+ "name": "<impl Deserialize for UnconstrainedArray<T, EphemeralOracles>>::deserialize",
2439
+ "start": 3147
2440
+ },
2441
+ {
2442
+ "name": "<impl Deserialize for UnconstrainedArray<T, EphemeralOracles>>::stream_deserialize",
2443
+ "start": 3259
2444
+ }
2445
+ ],
2446
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/ephemeral/mod.nr",
2447
+ "source": "use crate::oracle::ephemeral_oracles;\nuse crate::protocol::traits::{Deserialize, Serialize};\nuse crate::protocol::utils::{reader::Reader, writer::Writer};\nuse crate::unconstrained_array::{ArrayOracles, UnconstrainedArray};\n\n/// A dynamically sized array that exists only during a single contract call frame.\n///\n/// Ephemeral arrays are backed by in-memory storage on the PXE side rather than a persistent database. Each contract\n/// call frame gets its own isolated slot space of ephemeral arrays. Child simulations cannot see the parent's\n/// ephemeral arrays, and vice versa.\n///\n/// Each logical array operation (push, pop, get, etc.) is a single oracle call, making ephemeral arrays significantly\n/// cheaper than capsule arrays.\n///\n/// ## Use Cases\n///\n/// Ephemeral arrays are designed for passing data between PXE (TypeScript) and contracts (Noir) during simulation,\n/// for example, note validation requests or event validation responses. This data type is appropriate for data that\n/// is not supposed to be persisted.\n///\n/// For data that needs to persist across simulations, contract calls, etc, use\n/// [`CapsuleArray`](crate::capsules::CapsuleArray) instead.\n///\n/// For data that must be shared across all frames of the same contract (private and utility) within one top-level PXE\n/// call (transaction simulation or utility call) but not persisted, use\n/// [`TransientArray`](crate::transient::TransientArray).\npub type EphemeralArray<T> = UnconstrainedArray<T, EphemeralOracles>;\n\npub struct EphemeralOracles {}\n\nimpl ArrayOracles for EphemeralOracles {\n unconstrained fn len_oracle(slot: Field) -> u32 {\n ephemeral_oracles::len_oracle(slot)\n }\n\n unconstrained fn push_oracle<let N: u32>(slot: Field, values: [Field; N]) -> u32 {\n ephemeral_oracles::push_oracle(slot, values)\n }\n\n unconstrained fn pop_oracle<let N: u32>(slot: Field) -> [Field; N] {\n ephemeral_oracles::pop_oracle(slot)\n }\n\n unconstrained fn get_oracle<let N: u32>(slot: Field, index: u32) -> [Field; N] {\n ephemeral_oracles::get_oracle(slot, index)\n }\n\n unconstrained fn set_oracle<let N: u32>(slot: Field, index: u32, values: [Field; N]) {\n ephemeral_oracles::set_oracle(slot, index, values)\n }\n\n unconstrained fn remove_oracle(slot: Field, index: u32) {\n ephemeral_oracles::remove_oracle(slot, index)\n }\n\n unconstrained fn clear_oracle(slot: Field) {\n ephemeral_oracles::clear_oracle(slot)\n }\n}\n\n/// Serializes an `EphemeralArray` as its slot, allowing oracle function signatures to use ephemeral array types\n/// instead of opaque `Field` slots.\nimpl<T> Serialize for UnconstrainedArray<T, EphemeralOracles> {\n let N: u32 = 1;\n\n fn serialize(self) -> [Field; Self::N] {\n [self.slot]\n }\n\n fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {\n writer.write(self.slot);\n }\n}\n\n/// Deserializes a single Field into an `EphemeralArray` handle, treating the field value as the slot identifier.\nimpl<T> Deserialize for UnconstrainedArray<T, EphemeralOracles> {\n let N: u32 = 1;\n\n fn deserialize(fields: [Field; Self::N]) -> Self {\n Self { slot: fields[0] }\n }\n\n fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {\n Self { slot: reader.read() }\n }\n}\n\n#[crate::unconstrained_array::test_suite::unconstrained_array_tests(quote { crate::ephemeral::EphemeralOracles })]\nmod test {}\n"
2448
+ },
2449
+ "84": {
2450
+ "function_locations": [
2451
+ {
2452
+ "name": "record_retractable_fact",
2453
+ "start": 2758
2454
+ },
2455
+ {
2456
+ "name": "record_non_retractable_fact",
2457
+ "start": 3394
2458
+ },
2459
+ {
2460
+ "name": "delete_fact_collection",
2461
+ "start": 4031
2462
+ },
2463
+ {
2464
+ "name": "get_fact_collection",
2465
+ "start": 4409
2466
+ },
2467
+ {
2468
+ "name": "get_fact_collections_by_type",
2469
+ "start": 4802
2470
+ },
2471
+ {
2472
+ "name": "test::setup",
2473
+ "start": 5529
2474
+ },
2475
+ {
2476
+ "name": "test::make_payload",
2477
+ "start": 5744
2478
+ },
2479
+ {
2480
+ "name": "test::assert_payload",
2481
+ "start": 5978
2482
+ },
2483
+ {
2484
+ "name": "test::record_fact",
2485
+ "start": 6219
2486
+ },
2487
+ {
2488
+ "name": "test::records_and_reads_a_fact",
2489
+ "start": 6494
2490
+ },
2491
+ {
2492
+ "name": "test::reads_collections_by_type",
2493
+ "start": 7371
2494
+ },
2495
+ {
2496
+ "name": "test::records_a_retractable_fact_finalized_at_latest_block",
2497
+ "start": 8121
2498
+ },
2499
+ {
2500
+ "name": "test::retractable_fact_above_proven_tip_is_pending",
2501
+ "start": 9360
2502
+ },
2503
+ {
2504
+ "name": "test::deletes_a_fact_collection",
2505
+ "start": 10240
2506
+ },
2507
+ {
2508
+ "name": "test::reading_unknown_collection_returns_none",
2509
+ "start": 10746
2510
+ },
2511
+ {
2512
+ "name": "test::cannot_record_for_other_contract",
2513
+ "start": 11155
2514
+ },
2515
+ {
2516
+ "name": "test::re_recording_an_identical_fact_is_a_no_op",
2517
+ "start": 11457
2518
+ },
2519
+ {
2520
+ "name": "test::deleting_a_non_existing_collection_is_a_no_op",
2521
+ "start": 11953
2522
+ },
2523
+ {
2524
+ "name": "test::recording_a_fact_after_delete_recreates_the_collection",
2525
+ "start": 12385
2526
+ }
2527
+ ],
2528
+ "path": "/Users/maximvezenov/Documents/dev/AztecProtocol/aztec-packages/noir-projects/labs/aztec-nr/aztec/src/facts/mod.nr",
2529
+ "source": "//! Per-contract storage of immutable facts grouped into collections.\n//!\n//! A fact is a contract-defined, typed, immutable datum. Facts are grouped into collections identified by a\n//! `(collection type, collection id)` tuple.\n//!\n//! They are stored in PXE's FactStore, which automatically deals with reorgs by removing any facts\n//! associated with blocks that have been pruned.\nuse crate::ephemeral::EphemeralArray;\nuse crate::oracle::fact_store::{\n delete_fact_collection_oracle, get_fact_collection_oracle, get_fact_collections_by_type_oracle, record_fact_oracle,\n};\nuse crate::protocol::{address::AztecAddress, traits::{Deserialize, Serialize}};\n\nmod origin_state;\npub use origin_state::OriginBlockState;\n\n/// The block a retractable fact originates from.\n#[derive(Deserialize, Eq, Serialize)]\npub struct OriginBlock {\n pub block_number: u32,\n pub block_hash: Field,\n}\n\n/// A retractable fact's origin block.\n#[derive(Deserialize, Eq, Serialize)]\npub struct RetractableFactOrigin {\n pub block_number: u32,\n pub block_hash: Field,\n pub block_state: OriginBlockState,\n}\n\n/// A single immutable fact in a collection.\n#[derive(Deserialize, Serialize)]\npub struct Fact {\n /// A user-defined identifier for fact kinds. Typically used to determine how to deserialize `payload`.\n pub fact_type_id: Field,\n pub payload: EphemeralArray<Field>,\n /// The block the fact is associated to, if any. A fact with an origin block is said to be a 'retractable' fact,\n /// and will be automatically deleted if its origin block gets pruned in a reorg. Typically used by facts\n /// associated with a transaction (e.g. 'processed entry X using data from tx Y in block Z').\n pub origin_block: Option<RetractableFactOrigin>,\n}\n\n/// A fact collection as returned by the store.\n#[derive(Deserialize, Serialize)]\npub struct FactCollection {\n pub contract_address: AztecAddress,\n pub scope: AztecAddress,\n /// The collection's type. A single contract may have facts in collections of different types (e.g. one for the\n /// processing offchain messages, another for partial notes, etc.).\n pub fact_collection_type_id: Field,\n /// The collection's unique identifier among the other collections of this type in this contract and scope.\n pub fact_collection_id: Field,\n pub facts: EphemeralArray<Fact>,\n}\n\n/// Records a retractable fact into a collection: PXE prunes it if `origin_block` is reorg'd away. Re-recording an\n/// identical fact is a no-op.\npub unconstrained fn record_retractable_fact(\n contract_address: AztecAddress,\n scope: AztecAddress,\n fact_collection_type_id: Field,\n fact_collection_id: Field,\n fact_type_id: Field,\n payload: EphemeralArray<Field>,\n origin_block: OriginBlock,\n) {\n record_fact_oracle(\n contract_address,\n scope,\n fact_collection_type_id,\n fact_collection_id,\n fact_type_id,\n payload,\n Option::some(origin_block),\n );\n}\n\n/// Records a non-retractable fact into a collection: it survives reorgs and will persist until the fact collection\n/// itself is deleted. Re-recording an identical fact is a no-op.\npub unconstrained fn record_non_retractable_fact(\n contract_address: AztecAddress,\n scope: AztecAddress,\n fact_collection_type_id: Field,\n fact_collection_id: Field,\n fact_type_id: Field,\n payload: EphemeralArray<Field>,\n) {\n record_fact_oracle(\n contract_address,\n scope,\n fact_collection_type_id,\n fact_collection_id,\n fact_type_id,\n payload,\n Option::none(),\n );\n}\n\n/// Deletes a fact collection, removing all its facts from PXE storage.\n///\n/// Collections must be eventually deleted to reclaim storage and to stop reprocessing past the lifespan of the\n/// workflows they enable.\n///\n/// A no-op if no such collection exists.\npub unconstrained fn delete_fact_collection(\n contract_address: AztecAddress,\n scope: AztecAddress,\n fact_collection_type_id: Field,\n fact_collection_id: Field,\n) {\n delete_fact_collection_oracle(\n contract_address,\n scope,\n fact_collection_type_id,\n fact_collection_id,\n );\n}\n\n/// Fetches a fact collection.\npub unconstrained fn get_fact_collection(\n contract_address: AztecAddress,\n scope: AztecAddress,\n fact_collection_type_id: Field,\n fact_collection_id: Field,\n) -> Option<FactCollection> {\n get_fact_collection_oracle(\n contract_address,\n scope,\n fact_collection_type_id,\n fact_collection_id,\n )\n}\n\n/// Returns every fact collection of `fact_collection_type_id`.\npub unconstrained fn get_fact_collections_by_type(\n contract_address: AztecAddress,\n scope: AztecAddress,\n fact_collection_type_id: Field,\n) -> EphemeralArray<FactCollection> {\n get_fact_collections_by_type_oracle(contract_address, scope, fact_collection_type_id)\n}\n\nmod test {\n use crate::ephemeral::EphemeralArray;\n use crate::facts::{\n delete_fact_collection, get_fact_collection, get_fact_collections_by_type, OriginBlock,\n record_non_retractable_fact, record_retractable_fact,\n };\n use crate::protocol::address::AztecAddress;\n use crate::protocol::traits::{FromField, ToField};\n use crate::test::helpers::test_environment::TestEnvironment;\n\n global TYPE_ID: Field = 42;\n global COLLECTION_ID: Field = 7;\n global FACT_TYPE_ID: Field = 99;\n global PAYLOAD: [Field; 3] = [123, 456, 789];\n\n unconstrained fn setup() -> (TestEnvironment, AztecAddress) {\n let mut env = TestEnvironment::new();\n let scope = env.create_light_account();\n (env, scope)\n }\n\n unconstrained fn make_payload<let N: u32>(values: [Field; N]) -> EphemeralArray<Field> {\n let payload: EphemeralArray<Field> = EphemeralArray::empty();\n for i in 0..N {\n payload.push(values[i]);\n }\n payload\n }\n\n unconstrained fn assert_payload(payload: EphemeralArray<Field>) {\n assert_eq(payload.len(), PAYLOAD.len());\n for i in 0..PAYLOAD.len() {\n assert_eq(payload.get(i), PAYLOAD[i]);\n }\n }\n\n unconstrained fn record_fact(contract_address: AztecAddress, scope: AztecAddress) {\n record_non_retractable_fact(\n contract_address,\n scope,\n TYPE_ID,\n COLLECTION_ID,\n FACT_TYPE_ID,\n make_payload(PAYLOAD),\n );\n }\n\n #[test]\n unconstrained fn records_and_reads_a_fact() {\n let (env, scope) = setup();\n env.private_context(|context| {\n let contract_address = context.this_address();\n record_fact(contract_address, scope);\n\n let collection = get_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID).unwrap();\n assert_eq(collection.contract_address, contract_address);\n assert_eq(collection.scope, scope);\n assert_eq(collection.fact_collection_type_id, TYPE_ID);\n assert_eq(collection.fact_collection_id, COLLECTION_ID);\n assert_eq(collection.facts.len(), 1);\n\n let fact = collection.facts.get(0);\n assert_eq(fact.fact_type_id, FACT_TYPE_ID);\n assert_payload(fact.payload);\n assert(fact.origin_block.is_none());\n });\n }\n\n #[test]\n unconstrained fn reads_collections_by_type() {\n let (env, scope) = setup();\n env.private_context(|context| {\n let contract_address = context.this_address();\n record_fact(contract_address, scope);\n\n let collections = get_fact_collections_by_type(contract_address, scope, TYPE_ID);\n assert_eq(collections.len(), 1);\n\n let collection = collections.get(0);\n assert_eq(collection.fact_collection_id, COLLECTION_ID);\n assert_eq(collection.facts.len(), 1);\n\n let fact = collection.facts.get(0);\n assert_eq(fact.fact_type_id, FACT_TYPE_ID);\n assert_payload(fact.payload);\n });\n }\n\n #[test]\n unconstrained fn records_a_retractable_fact_finalized_at_latest_block() {\n let (env, scope) = setup();\n let origin_block_number = env.last_block_number();\n env.private_context(|context| {\n let contract_address = context.this_address();\n record_retractable_fact(\n contract_address,\n scope,\n TYPE_ID,\n COLLECTION_ID,\n FACT_TYPE_ID,\n make_payload(PAYLOAD),\n OriginBlock { block_number: origin_block_number, block_hash: 0xabc },\n );\n\n let collection = get_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID).unwrap();\n assert_eq(collection.facts.len(), 1);\n\n let fact = collection.facts.get(0);\n assert_eq(fact.fact_type_id, FACT_TYPE_ID);\n assert_payload(fact.payload);\n\n let origin = fact.origin_block.unwrap();\n assert_eq(origin.block_number, origin_block_number);\n assert_eq(origin.block_hash, 0xabc);\n // TXE finalizes every mined block, so an origin at the latest block is Finalized.\n assert(origin.block_state.is_finalized());\n });\n }\n\n #[test]\n unconstrained fn retractable_fact_above_proven_tip_is_pending() {\n let (env, scope) = setup();\n let future_block_number = env.last_block_number() + 100;\n env.private_context(|context| {\n let contract_address = context.this_address();\n record_retractable_fact(\n contract_address,\n scope,\n TYPE_ID,\n COLLECTION_ID,\n FACT_TYPE_ID,\n make_payload(PAYLOAD),\n OriginBlock { block_number: future_block_number, block_hash: 0xabc },\n );\n\n let origin = get_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID)\n .unwrap()\n .facts\n .get(0)\n .origin_block\n .unwrap();\n assert(origin.block_state.is_pending());\n });\n }\n\n #[test]\n unconstrained fn deletes_a_fact_collection() {\n let (env, scope) = setup();\n env.private_context(|context| {\n let contract_address = context.this_address();\n record_fact(contract_address, scope);\n delete_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID);\n\n let collections = get_fact_collections_by_type(contract_address, scope, TYPE_ID);\n assert_eq(collections.len(), 0);\n });\n }\n\n #[test]\n unconstrained fn reading_unknown_collection_returns_none() {\n let (env, scope) = setup();\n env.private_context(|context| {\n let contract_address = context.this_address();\n let collection = get_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID);\n assert(collection.is_none());\n });\n }\n\n #[test(should_fail_with = \"not allowed to access\")]\n unconstrained fn cannot_record_for_other_contract() {\n let (env, scope) = setup();\n env.private_context(|context| {\n let other = AztecAddress::from_field(context.this_address().to_field() + 1);\n record_fact(other, scope);\n });\n }\n\n #[test]\n unconstrained fn re_recording_an_identical_fact_is_a_no_op() {\n let (env, scope) = setup();\n env.private_context(|context| {\n let contract_address = context.this_address();\n record_fact(contract_address, scope);\n record_fact(contract_address, scope);\n\n let collection = get_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID).unwrap();\n assert_eq(collection.facts.len(), 1);\n });\n }\n\n #[test]\n unconstrained fn deleting_a_non_existing_collection_is_a_no_op() {\n let (env, scope) = setup();\n env.private_context(|context| {\n let contract_address = context.this_address();\n delete_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID);\n\n assert(get_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID).is_none());\n });\n }\n\n #[test]\n unconstrained fn recording_a_fact_after_delete_recreates_the_collection() {\n let (env, scope) = setup();\n env.private_context(|context| {\n let contract_address = context.this_address();\n\n record_fact(contract_address, scope);\n let collection_before_delete =\n get_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID).unwrap();\n assert_eq(collection_before_delete.facts.len(), 1);\n\n delete_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID);\n assert(get_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID).is_none());\n\n record_fact(contract_address, scope);\n let collection_after_recreate =\n get_fact_collection(contract_address, scope, TYPE_ID, COLLECTION_ID).unwrap();\n assert_eq(collection_after_recreate.facts.len(), 1);\n });\n }\n}\n"
2530
+ }
2531
+ },
2532
+ "functions": [
2533
+ {
2534
+ "abi": {
2535
+ "error_types": {
2536
+ "3445904810750103705": {
2537
+ "error_kind": "string",
2538
+ "string": "Block number mismatch."
2539
+ },
2540
+ "7259463707251703666": {
2541
+ "error_kind": "string",
2542
+ "string": "Function check_block_number can only be called statically"
2543
+ },
2544
+ "9688791427233494233": {
2545
+ "error_kind": "fmtstring",
2546
+ "item_types": [],
2547
+ "length": 17
2548
+ }
2549
+ },
2550
+ "parameters": [
2551
+ {
2552
+ "name": "operation",
2553
+ "type": {
2554
+ "kind": "integer",
2555
+ "sign": "unsigned",
2556
+ "width": 8
2557
+ },
2558
+ "visibility": "private"
2559
+ },
2560
+ {
2561
+ "name": "value",
2562
+ "type": {
2563
+ "kind": "integer",
2564
+ "sign": "unsigned",
2565
+ "width": 32
2566
+ },
2567
+ "visibility": "private"
2568
+ }
2569
+ ],
2570
+ "return_type": null
2571
+ },
2572
+ "bytecode": "JwACBAEoAAABBIBLJwAABEslAAAATycCBAQCJwIFBAAfCgAEAAUASRwASUkCHABKSgQtCEkCLQhKAyUAAABuJwICBEsnAgMEADsOAAMAAicAQwIBJwBEAgInAEUCAycARgIEJwBHAgUnAEgCBiYeAgAFAB4CAAUAHgIABQknAgYBASQCAAUAAACPJQAAAu4eAgAFBRwKBQcAHAoDBQAKKgcFAwwqBwUICiICQwUkAgAFAAAAuiMAAADDLQoDBCMAAALgCiICRAcWCgMJJAIABwAAANkjAAAA4i0KCQUjAAAC1woiAkUKJAIACgAAAPQjAAAA/S0KCAcjAAACzgoiAkYLJAIACwAAAQ8jAAABGRIqCAMKIwAAAsUKIgJHCxYKCAwkAgALAAABLyMAAAE5BCoMCQMjAAACvAoiAkgIJAIACAAAAUsjAAABUCMAAAKzJwICAkknAgMCbicCBAJ2JwIFAmEnAgcCbCcCCAJpJwIJAmQnAgoCICcCCwJvJwIMAnAnAg0CZScCDgJyJwIPAnQtCAEQJwIRBBIACAERAScDEAQBACIQAhEtChESLQ4CEgAiEgISLQ4DEgAiEgISLQ4EEgAiEgISLQ4FEgAiEgISLQ4HEgAiEgISLQ4IEgAiEgISLQ4JEgAiEgISLQ4KEgAiEgISLQ4LEgAiEgISLQ4MEgAiEgISLQ4NEgAiEgISLQ4OEgAiEgISLQ4FEgAiEgISLQ4PEgAiEgISLQ4IEgAiEgISLQ4LEgAiEgISLQ4DEicCAgEAJwIDAAAKKgIGBCQCAAQAAAKzJwIFBBMtCAEHJwIIBBMACAEIAS0KBwgqAwAIBYZ1gHg7GjTZACIIAggAIhACCScCCgQRLQIJAy0CCAQtAgoFJQAAAwAnAgkEEQAqCAkILQ4DCAAiCAIIPA4FBy0KDAMjAAACvC0KAwojAAACxS0KCgcjAAACzi0KBwUjAAAC1y0KBQQjAAAC4CQCAAQAAALtJQAAAzImKgEAAQVkvsvHipP/cjwEAgEmAAADBQctAAMILQAECSMAAAMkLQEIBi0EBgkAAAgCCAAACQIJDAAIBwokAAAKAAADEiYqAQABBS/SUCsOkdCZPAQCASY=",
2573
+ "custom_attributes": [
2574
+ "abi_public",
2575
+ "abi_view"
2576
+ ],
2577
+ "debug_symbols": "rZfRauMwEEX/Jc950Iw0Gqm/spSStm4JmCS4ycJS8u87cnUdpyBTvPsSX1/bRzPSaGJ/bl6758v70/7wdvzYPPz63DwP+77fvz/1x5fdeX88mPu5ceWHyA6ytaNsHrId2c6JizCDvAnvIFIVwZuIRRRHTUhxUhHmsDMRzeECjsUpN2cDst3MzoBsNzNHEzYol8e9PcVKJshEonpPsnu8xeNducdG9+Sr43EpEAQcgSNwIpwIR+EonARnGjTDydUJjiCkijKDXwIOw+HJyVV4D5GqCAyhVSD4gOBDBDACGAHUAAFgwhAJwIwhkIUgC0EWgiyEAkQdQthD1CHEM0QdQrAEgiUQAVAwhAAYMUQEUDGEFqCVjSSGgJOrE0v9fAmByFWMwY8Czhh8EWO1FDGGOgo4AkcAFDwe8fgYahEKR+Eg1IhQdRzLal5DiSder9sNtt7Teei6svNme9F26Gk3dIfz5uFw6fvt5veuv4w3fZx2h/F43g121bZId3i1owHf9n1X1HV7e9q1H7WVjvVpIdIJQEx3CGojgotcEYE4NBHcRlDKyIEyuSbCtxHsrCArw7S/paL3jLDA0ARCnuWR0k/zYOtUIHj1zTxiG+FDkIqwviW3LOSOoP9hJtK/zsRSXcU81ZVyeyZogeGJKGMuiIJrJUIL1UkuIRD7U8vrckl5yiXEZi4LCPsnVEQhkSeE8H0iS8UZlbFJTPvcnA1pQyIjkyhuzVzcJTKr8G+JLBEiobbsbYDXEIR4IgRtTmZeKK0c0LLcrb45yY8Jgaemx6lJ4IXKVMloFmr/ULfViPcIXmoWRFOzoFlxf4tioW9659AsvJt372+Ihcoke69CWZkO3EplcT7DtCLqVq2IuKnjeL+KoA4bTDmui0FBkLyOMN+hKwkR+yumdbWtitrWnNcRPGLQlVkkj3lIsU3wSw3TIQue1XUIP24z9oI8tZnZapY282hnu5f9cPfpdC2sYb977rt6+nY5vMyunv+ccAWfXqfh+NK9XoaukG7fX/Yy+YskbK2/PZavsPGUttZ9H69l9L8=",
2578
+ "is_unconstrained": true,
2579
+ "name": "check_block_number"
2580
+ },
2581
+ {
2582
+ "abi": {
2583
+ "error_types": {
2584
+ "13950240626967988787": {
2585
+ "error_kind": "string",
2586
+ "string": "Timestamp mismatch."
2587
+ },
2588
+ "6989792215391248978": {
2589
+ "error_kind": "string",
2590
+ "string": "Function check_timestamp can only be called statically"
2591
+ },
2592
+ "9688791427233494233": {
2593
+ "error_kind": "fmtstring",
2594
+ "item_types": [],
2595
+ "length": 17
2596
+ }
2597
+ },
2598
+ "parameters": [
2599
+ {
2600
+ "name": "operation",
2601
+ "type": {
2602
+ "kind": "integer",
2603
+ "sign": "unsigned",
2604
+ "width": 8
2605
+ },
2606
+ "visibility": "private"
2607
+ },
2608
+ {
2609
+ "name": "value",
2610
+ "type": {
2611
+ "kind": "integer",
2612
+ "sign": "unsigned",
2613
+ "width": 64
2614
+ },
2615
+ "visibility": "private"
2616
+ }
2617
+ ],
2618
+ "return_type": null
2619
+ },
2620
+ "bytecode": "JwACBAEoAAABBIBLJwAABEslAAAATycCBAQCJwIFBAAfCgAEAAUASRwASUkCHABKSgUtCEkCLQhKAyUAAABuJwICBEsnAgMEADsOAAMAAicAQwIBJwBEAgInAEUCAycARgIEJwBHAgUnAEgCBiYeAgAFAB4CAAUAHgIABQknAgYBASQCAAUAAACPJQAAAu4eAgAFBhwKBQcAHAoDBQAKKgcFAwwqBwUICiICQwUkAgAFAAAAuiMAAADDLQoDBCMAAALgCiICRAcWCgMJJAIABwAAANkjAAAA4i0KCQUjAAAC1woiAkUKJAIACgAAAPQjAAAA/S0KCAcjAAACzgoiAkYLJAIACwAAAQ8jAAABGRIqCAMKIwAAAsUKIgJHCxYKCAwkAgALAAABLyMAAAE5BCoMCQMjAAACvAoiAkgIJAIACAAAAUsjAAABUCMAAAKzJwICAkknAgMCbicCBAJ2JwIFAmEnAgcCbCcCCAJpJwIJAmQnAgoCICcCCwJvJwIMAnAnAg0CZScCDgJyJwIPAnQtCAEQJwIRBBIACAERAScDEAQBACIQAhEtChESLQ4CEgAiEgISLQ4DEgAiEgISLQ4EEgAiEgISLQ4FEgAiEgISLQ4HEgAiEgISLQ4IEgAiEgISLQ4JEgAiEgISLQ4KEgAiEgISLQ4LEgAiEgISLQ4MEgAiEgISLQ4NEgAiEgISLQ4OEgAiEgISLQ4FEgAiEgISLQ4PEgAiEgISLQ4IEgAiEgISLQ4LEgAiEgISLQ4DEicCAgEAJwIDAAAKKgIGBCQCAAQAAAKzJwIFBBMtCAEHJwIIBBMACAEIAS0KBwgqAwAIBYZ1gHg7GjTZACIIAggAIhACCScCCgQRLQIJAy0CCAQtAgoFJQAAAwAnAgkEEQAqCAkILQ4DCAAiCAIIPA4FBy0KDAMjAAACvC0KAwojAAACxS0KCgcjAAACzi0KBwUjAAAC1y0KBQQjAAAC4CQCAAQAAALtJQAAAzImKgEAAQVhALr8hC+iUjwEAgEmAAADBQctAAMILQAECSMAAAMkLQEIBi0EBgkAAAgCCAAACQIJDAAIBwokAAAKAAADEiYqAQABBcGZNfBNpkozPAQCASY=",
2621
+ "custom_attributes": [
2622
+ "abi_public",
2623
+ "abi_view"
2624
+ ],
2625
+ "debug_symbols": "rVfbbuIwEP0XnnnwjD1ju7+yqipK0woJAUphpVXFv+849QmhkiOU3RdyfGKfuXg8Jl+rt+718vGyO7wfP1dPv75Wr/1uv999vOyP2815dzwY+7Vy5YfIHrK2p6yesj3ZxsQFGEHegHcAqYLgDWgBhYkGpDCpAGPYGVBjuAhrYcrkbIJsk9mZINtkZjVgRrks97aKIxkgA4nqnGRzvPnjXZlj1j35yni8CgQARsAIGAWjYCKYCCaBGY1mMLkywRGAVFAy+A3AMBgemVyB9wCpgsAAsQI4H+B8UAgqBBWCMQBAMMFEgmCGCUQhiEIQhSAKoQBQTQh7gGpCPANUE4ItEGyBCAQFJgSCChMKwQgTsQha2UhiADC5Mlrq5xsIQK5gcH4AYAbnCxiqpYDB1QGAETACQcFyxfLB1QIimAgGripcjYMtq/kYij96va5XOHov577rysmbnEU7oadN3x3Oq6fDZb9fr35v9pdh0udpcxie501vb+2IdIc3e5rg+27fFXRd31a79lLbaa2rhSiOAsR0J0FtieCUq0QgDk0JbktQyoiBMrmmhG9LsLOCrBqG/S2UeK8RZjRigkKexJHSo3GwdSoo+OibcWhbwocgVcL6ltyikDuF+B8ykf41E3N1pXmsq8jtTNCMhieijFwQBdcKhGaqk1yCI3ap5WWxpDzGErQZy4xEzthUcpNTJnwfx3xtehwzwyE1kyFtEc0IJE7P+uOpmMbBqRWHm9sOCaOCLlNIow/2b6SZyzxTWBk+BHerbk7ysELgseVN0vBTgWfqMkpGq4h2P902Q+8leK5VEI2tgial/cOLma7pnUOr8G7au39IzBQm2b8qVJXhwK1QZvMZxh2JbtGOiBv7jfeLFKLDHRRZl/kQoSB5mYIyUqmyUEHRuTUtq+0YUdsx52UKHj7EhVEkjzwkbSv4uX7pxm45qesQHm8z4xVoV0++azPPNtpsd/3dh9O1aPW7zeu+q8P3y2E7eXv+c8IbfHid+uO2e7v0XVG6fX3ZX8lfZH2SNDyXb7AyVLFhfL4W638B",
2626
+ "is_unconstrained": true,
2627
+ "name": "check_timestamp"
2628
+ },
2629
+ {
2630
+ "abi": {
2631
+ "error_types": {
2632
+ "14990209321349310352": {
2633
+ "error_kind": "string",
2634
+ "string": "attempt to add with overflow"
2635
+ },
2636
+ "16431471497789672479": {
2637
+ "error_kind": "string",
2638
+ "string": "Index out of bounds"
2639
+ },
2640
+ "4215903597095405243": {
2641
+ "error_kind": "string",
2642
+ "string": "offchain message anchor timestamp is implausibly far in the future"
2643
+ },
2644
+ "9530675838293881722": {
2645
+ "error_kind": "string",
2646
+ "string": "Writer did not write all data"
2647
+ }
2648
+ },
2649
+ "parameters": [
2650
+ {
2651
+ "name": "messages",
2652
+ "type": {
2653
+ "fields": [
2654
+ {
2655
+ "name": "storage",
2656
+ "type": {
2657
+ "kind": "array",
2658
+ "length": 16,
2659
+ "type": {
2660
+ "fields": [
2661
+ {
2662
+ "name": "ciphertext",
2663
+ "type": {
2664
+ "fields": [
2665
+ {
2666
+ "name": "storage",
2667
+ "type": {
2668
+ "kind": "array",
2669
+ "length": 15,
2670
+ "type": {
2671
+ "kind": "field"
2672
+ }
2673
+ }
2674
+ },
2675
+ {
2676
+ "name": "len",
2677
+ "type": {
2678
+ "kind": "integer",
2679
+ "sign": "unsigned",
2680
+ "width": 32
2681
+ }
2682
+ }
2683
+ ],
2684
+ "kind": "struct",
2685
+ "path": "std::collections::bounded_vec::BoundedVec"
2686
+ }
2687
+ },
2688
+ {
2689
+ "name": "recipient",
2690
+ "type": {
2691
+ "fields": [
2692
+ {
2693
+ "name": "inner",
2694
+ "type": {
2695
+ "kind": "field"
2696
+ }
2697
+ }
2698
+ ],
2699
+ "kind": "struct",
2700
+ "path": "aztec::protocol_types::address::aztec_address::AztecAddress"
2701
+ }
2702
+ },
2703
+ {
2704
+ "name": "tx_hash",
2705
+ "type": {
2706
+ "fields": [
2707
+ {
2708
+ "name": "_is_some",
2709
+ "type": {
2710
+ "kind": "boolean"
2711
+ }
2712
+ },
2713
+ {
2714
+ "name": "_value",
2715
+ "type": {
2716
+ "kind": "field"
2717
+ }
2718
+ }
2719
+ ],
2720
+ "kind": "struct",
2721
+ "path": "std::option::Option"
2722
+ }
2723
+ },
2724
+ {
2725
+ "name": "anchor_block_timestamp",
2726
+ "type": {
2727
+ "kind": "integer",
2728
+ "sign": "unsigned",
2729
+ "width": 64
2730
+ }
2731
+ }
2732
+ ],
2733
+ "kind": "struct",
2734
+ "path": "aztec::messages::processing::offchain::OffchainMessage"
2735
+ }
2736
+ }
2737
+ },
2738
+ {
2739
+ "name": "len",
2740
+ "type": {
2741
+ "kind": "integer",
2742
+ "sign": "unsigned",
2743
+ "width": 32
2744
+ }
2745
+ }
2746
+ ],
2747
+ "kind": "struct",
2748
+ "path": "std::collections::bounded_vec::BoundedVec"
2749
+ },
2750
+ "visibility": "private"
2751
+ }
2752
+ ],
2753
+ "return_type": null
2754
+ },
2755
+ "bytecode": "H4sIAAAAAAAA/+2deWBcVfXHk8xMlmm27gtNZmuazKQoXUGQpXtLqa0tBQGxDMm0jc3WZFIaKuJYtgpokpZNEJC2obUUgRYBKyKLuHCvbAKiFRCoiAiIFrGC8ruhnZk7771735JvOj9/v9u/bvPmfs55737vuefdeXOeq6f72rtaVqyoWxVtaF7eFquLNayNdSd2zmhraGxsWDkz2ti4OacnsW16W1u0c1/uKZu6unse8+fI/+XmmH4kxxooFwXKQ4FcKJAbBfKgQPkoUAEKVIgCFaFAXhRoEApUjAKVoEClKFAZClSOAg1GgYagQENRoGEo0HAUaAQKNBIFGoUCjUaBxqBAR6FAY1GgChSoEgXyoUB+FCiAAgVRoBAKNA4FqkKBxqNA1ShQDQoURoEiKFAtCjQBBToaBfoUCvRpFOgYFGgiCjQJBZqMAk1BgaaiQNNQoGNRoONQoM+gQMejQCegQJ9FgU5EgU5CgU5GgU5BgaajQDNQoJko0CwUaDYKNAcFmosCzUOB5qNAp6JAC1Cg01CghSjQ51CgRSjQYhTo8yjQEhRoKQp0Ogq0DAU6AwU6EwX6Agp0Fgp0Ngp0Dgr0RRToXBToSyjQchToPBQoigKdjwLVoUD1KFAMBVqBAq1EgVahQA0o0JdRoNUoUCMK1IQCNaNALShQKwq0BgVqQ4HaUaA4CtSBAq1FgS5AgdahQJ0o0IUo0HoU6Cso0EUo0FdRoItRIPI1GCkBI30dRtoAI10CI10KI10GI10OI10BI22Ekb4BI10JI10FI10NI30TRvoWjNQFI3XDSD0w0iYYaTOMdA2MdC2MdB2MdD2MdAOM9G0Y6UYY6SYY6Tsw0s0w0i0w0q0w0ndhpNtgpC0w0lYYaRuM1Asj3Q4jbYeRdsBI34ORdsJId8BIu2CkO2Gk78NId8FId8NI98BIu2GkPTDSvTDSD2Ck+2Ck+2GkB2CkH8JIe2GkH8FID8JIP4aRHoKRfgIjPQwjPQIjPQojPQYj/RRGehxG+hmM9HMY6Rcw0i9hpCdgJAIjURjpVzDSkzDSUzDS0zDSMzDSszDSr2Gk52Ck52GkF2Ck38BIL8JIv4WRfgcj7YORfg8jvQQjvQwjvQIj/QFGehVGeg1Geh1G2g8j/RFGegNG+hOM9CaM9GcY6S0Y6S8w0tsw0jsw0rsw0l9hpPdgpL/BSH+HkQ7ASO/DSP+AkT6Akf4JIx2Ekf4FI30II30EI/0bRvoPjPQxikRxFZgorgYTxVVhorg6TBRXiYniajFRXDUmiqvHRHEVmSiuJhPFVWWiuLpMFFeZieJqM1FcdSaKq89EcRWaKK5GE8VVaaK4Ok0UV6mJ4mo1UVy1Joqr10RxFZsormYTxVVtori6TRRXuYniajdRXPUmiqvfRHEVnCiuhhPFVXGiuDpOFFfJieJqOVFcNSeKq+dEcRWdKK6mE8VVdaK4uk4UV9mJ4mo7UVx1J4qr70RxFZ4orsYTxVV5org6TxRX6Yniaj1RXLUniqv3RHEVnyiu5hPFVX2iuLpPFFf5ieJqP1Fc9Sdqpf5TondpQ/PKxphVpIVKUF2busx/TpO7L3d6Tm6ey+3JLygs8g4qLiktKx88ZOiw4SNGjho95qixFZU+fyAYGlc1vromHKmdcPSnPn3MxEmTp0ydduxxnzn+hM+eeNLJp0yfMXPW7Dlz580/dcFpCz+3aPHnlyw9fdkZZ37hrLPP+eK5X1p+XvT8uvrYipWrGr68urGpuaV1TVt7vGPtBes6L1z/lYu+ejH5GkmQr5MN5BJyKbmMXE6uIBvJN8iV5CpyNfkm+RbpIt2kh2wim8k15FpyHbme3EC+TW4kN5HvkJvJLeRW8l1yG9lCtpJtpJfcTraTHeR7ZCe5g+wid5Lvk7vI3eQespvsIfeSH5D7yP3kAfJDspf8iDxIfkweIj8hD5NHyKPkMfJT8jj5Gfk5+QX5JXmCEELJr8iT5CnyNHmGPEt+TZ4jz5MXyG/Ii+S35HdkH/k9eYm8TF4hfyCvktfI62Q/+SN5g/yJvEn+TN4ifyFvk3fIu+Sv5D3yN/J3coC8T/5BPiD/JAfJv8iH5CPyb/If8jHblWS7iWwXkO3esV03tlvGdrnY7hTbVWK7QWwXh+2+sF0TttvBdinY7gLbFWB38+wunN09s7tedrfK7jLZ3SG7q2N3Y+wuit39sLsWdrfB7hJYds+ycpZNsyyYZa8s62TZIsvyWHbGsiqWDbEshmUfLGtgqz1bpdnqylZFtpqxVYitHizqs2jNoiyLjiyqsWjEogib/WzWstnGZglTN1NjVxfTra5e/j5PZ2LbzJbm9vimRO+sBvbXeF7i9vnN8djKWNuWZZPNl7lcbf9cW/0TG7X9c2z1z92Y2NpX6r+b5q1MkbYviTVG4+z03PZY0/UEj72rkZO4o8+b+mg8OrOltTN1UvN4nzg485079TPTDd6q5lNnpRvJT922bKLmQ+ekG2nUtCmaT61ONyQGm9INscGWdENi8OJ0Q2KQJLiW2CTZwLUkRgnfkpm9hmtJzF7HtWRmb+daMrM7uJbE7E6uJTO7l2vJzD7ItSRmH+JaMrNPci2Z2ae5lsTss1xLZvY1riUzu59rScy+wbVkZj/gWjKzB7mWxOyHXEtili0zfFNimC1FfFNsmq1WfFNq3Mc3pcYDfFNmPMQ3pcYn802p8al8U2b8WL4pNT6Xb0qNz+ebMuML+KbU+Dl8U2r8XL4pM76cb0qNt/BNqfE1fFNmvJ1vSo1v4JtS45fyTZnxy/mm1PgVfDPDuC5LsJkzzet3nnFeYsvClrU9fFaRSr907Hx77Ghi54yG5mhbJ+u0qDW1JuZumV5f/8nppyxxFnbNb67/5K/9S8FYOplpPG0iZV5/znnaq1HID43mWBHvtu5aDbLnbpmW7pWMQ7E9drn9cSgWj4MXNA7F+nHwasfh8H9d/IBkHHHzLmcc8fBDkczsmxLblsZb2mLGo+gFjKLgZAv1J1vIWxF0K9J3K0pfo62ntUTruVMp4OGyEy2w5WbKnnJSOfl/wkkVrFWwVsFaOamcVMFaBWsVrNXsVU4qJ1WwVsFaBWsVYpSTKlirYK2CtQrWyknlpArWKlirYK1mr3JSOamCtQrWKlirEKOcVMFaBWsVrFWwVk4qJ1WwVsFaBWs1e5WTykkVrFWwVsFaOamcVMFaBWsVrNXsVU4qJ1WwVsFaBWs1e5WTKlirYK2CtQrWyknlpArWKlirYK1mr3JSOamCtQrWKlirEKOcVMFaBWsVrFWwVk4qJ7PopCbU5qWbbu0xV7JXX3nzZBhZ19/a5rkb9QSX3XeobGVXs7Xb+Dxc2vfFzMyo4m5Cz226Vdt/1rY5DbHGetbx6okP7152+Qv7zp81+h7Xe+v3P/qA/4KXS/cXuPOfH3b0+lu0HWenOh58+5krb8x5ZPeIV107Rh5zz0U3n/z++kXv9jQOf/ei2I133q/tOMfe9dCd8Vx7/d29S2LxjrZm47WyQLtWutLrTMayU5j+QMbfi9Ir1tZTO5pamYo6kpPl8JH8NCM5UbSd8429K9R6J5wgSaC2Q5FJB+/202Lt7aevijYbmilI9Pad1PwVKZe9NG9N6orOYSfTsLK5b/Zcszd6YTxWt7wj3rh8ZSy+LN7Q2BDvZCMXj62L78sZldi1MNbU0tbJ/GtjFtOK9giP5AuPFAiPFAqPFAmPeIVHBgmPFAuPlAiPlAqPlAmPlAuPDBYeGSI8MlR4ZJjwyHDhkRHCIyOFR8Q6GC08MkZ45CjhkbF9kutd2tDU2hg7FKj+2/6X+c4Ns49Mm2KLuXXZxEnHyf9q1++uLhUPVDzIbjwYKzxSoeLBkY8H/X+dYH9f5lOuJxTw70ey8X5HLqTYcsHgLTtF9ggePcFr6yRy+r3/kat/4RI3qMnEd4NwSygzyzSiuNKZZrobzbssBb+lH/B8Y3jq5Zmes8WbWQs7GoXcQlG3Uv1tap7pvW2JvlMpv8Job8FL+KZ1R4p5IQq6lTnx32Djr4w/Fa3/xbKTK3V2cqXczq12U6KE/5h8DFj45JbC1K22yI87kwqcvaYj2tiu7c95oNdhKc27PqXDc4UmOJHz8BL+GorGpfeQW33vgzO6vl7j2XFTyqvzbIy4m48x4qBRzAWN/m6DG2zSl6Q2J2xHxlK7O8M6Qpk9wjA9odzE/WFi9wfbMz5ETxhijzBUTxhqj1CgJwyzRyjUE4bbIxTpCSPsEQy+ZBhpjzBITxhlj1CsJ4y2RyjRE8bYI5TqCWPtEQZbSjbuFgWlCmfJRgXN25OEeyaI4H5nyYaf5t1nnmz4nSUbQSeLdUDfKch5oluPA3zTuiN+fjkQdBvnxP+QvtM4/lS0/of4piP/hetrlRP/DU66Sub/OL5px//Urrug03gn3huc8niZ91V804H3c0Wdqp14b3DK1TLvx/NNR9opgvrvt+m/Xzaxg84mdlCSaAdkzgy0Pc3aUSl53CJob10abv9xi6D4cYtK0OMWBteqUvL4SrXd5NS6cKslw1CTIYnDS/gr+qGs4W9tBKZr9KZrTOdMWLBw1/D+6xfuMM176f/blKng0y3NMZ9RKvaW0CnBRecslBpc9CDNeycJd7ltKDBgKoOgVLYVsksfFDoiOEvuWpUZnGU1zTvA5YSiB6Mqtd9/u+1GraSNOu1gVqe/67Y+1arNp5rR/OSuik6MYQsX2WDgfBZyyxrd1oyAEDQYoRqa97H51ozBNargPRPPrhr9YsVdZvHMC3Izj7mnie+pZujwtrwog3Ym2xB1FWZXtiEnsg0NqGyrRdDKAZZtpaFsXUPNZesTDH+lfPh91DXCwvCHBm74fU6G39fP4a+UDv84G3eplf0e/soMVRsNf4Abfm2A4HpXyQNEjUAhIblCmP0qCwrxDZxCakwVEnaSQkb0ncIZitcqJMJfddE0NApV5goJSxUSyhC+QVLrOoZTiP4DVdQ1KZWATccvIFMt6KNm4PRRYaqPkNGa7iCChKwuIOPBeU+oP3kPG6FT+AhyWAhz/5f5OJvzUZZkpf3XxkIuwPvlsVC07xuUa91PXQssaL1i4LTudxIL/f2MhUFpLKwR7txL96QdxsJgxhQ2ioVnmCdLwV4jdIV88IPUdVYKvVaYxRpsTFXYfUDE9sZUhXhjKgTamKqQJuGaq5ExSjrxcEdLQBsg/3XIcitbMa5Vdr8V4yiFht+KuVan4DttDTU3cbW7KhV8U3ildF+G+Uy/zAg7C9MsCKwx/3ou4iRQGkTXCO+X9tKE+eauQ8xPVqZFrZs1rhhez/CA3ZJ5+pNQhU02SWS5UcRZwlUsv7bWB9nKGlRrdQ2KGMivlroS5mtQrUDbEbm2GfwSc21PcKLtWn2nCbxf2utfyzetajvMdxqoBEqi7bCptmuluVCxXtu1FrQtWz3nOAqocmUXD5SyN1vIrpwpm+VX15kru9aJsg2W6VqZsjO+JnAQtYNCZYezGbWDktvgOdJsJWIn3Q0OeLobHPh0NwjbMkh12j6jMVq3ekbLusSexS3tsYb6luZJi2NtTR1x9smW5h7+0rv5kOW2EVUy7tTFKWaFeYoZtpkFOlyOuacZhuiYEb4pnIi1wiUmko30yXyJkd9uD5LebtfagErTp4iFZSskHa8y+WNZwvHyZ45XhO+UhcAZcjJeIWlKEOGvl2gLxyB0hgc8dIbFodMPCp1hJ1/Xye/GbITOMB86I25nyh4kV7boKyyDEfUP+ENJfvGI+kAj6pd+A9dfFQ+zIaSwZGJlTLrk8vacdHKW2JBjxPwGyjzxDRtn1c/KHvIL2BgWv7WHhPxH3J6Nh5KC/LHkOL5idyvf5KEktpX/Wgp+0IYCzR9K8ktlWyF/nhO+E/Zmdr+8dZgMOdiryNiHk92k+20MnJXNoojVW2q/wQhFqOuA+S11xPFDSRHJTUBYMvP85jMv4EyTAer6KLuaDDjZ3ww4SWEsf4lWbeOBAiuarLaqSZ/ho4zuAufbPCbPCwSp22th+AMDN/xB0+Gvln6tY10z1RlydvLEUcDZd/HVVr+LDxgP/3DnD5wF5MPvo+5RFoY/mM0HzqpBD5xVZ8hZMvyVNp43DFgY/qB0+AO8YcMJGjJ5nMhdlVwd3FPsrg6VZquDuya7q4P5PmrAyd5gUDqUldLt1/E2MhYrDyT6rD6Q6DeewZP1jxO5jwf7GOiPj0xFx1l6nMhn7n+lQMh+uZArqfvE7D4rVGkqZJ/R0Dj4qamPvyqy+0A7zwr5+y1kf8b8NBLyPAvrnJNnhRh6AfesUEYlrQcOVdJqamiv6yultSTaXN/S9Mkmabe43lG3vjqXjSHlLqT25tPHN23sVAbsFnWwva8VGPidyoB0Q0N8cxSQRmufjbHhv7vkRXJfutxaa0f7qtmtq2JNsbZoo1gigW7D0lI9Yk0ldsyLRVunt7VFO3lB5PZo6kBtO/QRjQRznSmwWClQKTAbChQ+bKH0p/R35PQ3V+lP6S+rK3CRUqBSYFYVWKgUqBSYVQUOVQpUCsyqAocpBSoFZlWBw5UClQKzqsARSoFKgVlV4EilQKXArCpwlFKgUmBWFThaKVApMKsKHKMUqBSYVQWWKgUqBWZVgflKgUqBWVXgWKVApcCsKnCwUqBSYFYVOEQpUCkwqwoss6VA2etw/AOuQP/Avw7HL/2Fiu53vZxrsp+h+GyNDUqB/iOvQN7hPWmH2em0tNXPidbFu7puEJo/SnhknPbI4Us0S9gjJOgxW3Ly9l/oLn7ZfMkNR+Rl3n3vZLXwgm/rP4Ky+P7VCu49ippPFUlChNfumxxthwivOEQUgUKEV3/VitJztr8vhC0XmTV8WzF33pphKOOPJd9Leaw+SnGfExanMXidc5npz/bKBT9jzHins/6XbOXUM9XKCzw9J4gMe5y9wNNDPSel4Gf2A55vDJ9uXmvS4+wFngYv/jZ/CaCBiksyLrMmK/DyTeuOeNLNYhvKNvffI50OJTr/PbKTK3F2ciXctNfOKy//MdGPcYv6+WPcweIf43pNf4xrcEJe08teKpWNW38dSvnrbn0sLa5DHv3qYxD2hKEiTxrKM7KZF6vS6Ux7rG9xibexfGZpZ3PdzGjdqtj85rXRxob6rq5NkvzGML3KKxf2cG2ylHiVG+YAvUti8Y62Zt2CmFo00x+eNkUstdcLF8/Ou/cqX2Lr6W3R1u6edP/khQIZeqrgrQNPPL6ya8ANHZ/Y/9Go8ON7zQ0djhOH/5yfnsGGeUkB/8ttbZ+89KqQ/Dj1xDMjgyftidXEJxU3DDsUaTu40h0yLHvTH8j4+6C0a8nJ1Kq5KoVpRnLyazsXGnvn1XonDD9JoLbDIJMOxZmrtdZMkW5MiqmnUSQvj938MXnFOgSj7ALp+ZKZjx796hu7LzTV8/8AGfoiAfVXAQA=",
2756
+ "custom_attributes": [
2757
+ "abi_utility"
2758
+ ],
2759
+ "debug_symbols": "tZzbblQ5F4Tfpa9zYa/lI68yQihAGEWKAsrAL/1Ceffx8na5Ohlt0/QmN+QLSVd528vVPrTy8/T57uOPvz/cP375+s/p3V8/Tx+f7h8e7v/+8PD10+33+6+P7X9/npz9k1RO7/SmfdXTu9y+hva12td0eue9QQYUQB0QHcADBKCAAIgAKEcoRyhHKCdTtmYlDxCAAkw5GJhyNEiADDBlaVBM2Z6vmo49YFVAAERAAmRAAdQNsnMADxCAAgIgAhIgAwoAyh7KHsoeyh7KHsoeyh7KHsoeyh7KAmWBsjRlEQMFBEBTlmSQABlQAHWAOoAHCEABAQBlhbJCWU25GNQBwQGasjoDASigvVytzVaQqgYeIAD7ZbOwgtwgAhIgAwqgDrCC3MADBGDK2SAAIiABTLnVas72Kuv53F4VvEEAREACZEAB1AHFATxAAKZsvVECIAISwJStPaUA6oDqAB4gAAUEQAQkgClHgwKoGxSbMhuYcjYw5WqggACIgATIgAKoA2zKbOABTTk6AwUEQAQ0nagGdYBNkA08QAAKCIAISIAMMOVgUAfYBNnAA0wwGQRABCSAvdw6ymZBtOeyWbCBABQQABGQABlQAHWATZlkvWFTZgMBKKApJzGIgARoysmaalNmgzrApswGHiAABQRABCQAlBOUE5RtEiXrFpsyqRgkgL3KnsumTLbG25TpYFNmAw8QgAICAMoFyjZlNiiAOsCmzAam7A0EYMrWUTZlNoiABGjK2crGpswGdYNqU2YDDxCAAsLmVW3KbJAAGVAAdYBNmRwMPMCUo4ECAiACTDkZZEAB1AE2iTbwAAHo8LJJtEEEJEAGFIApt+6tNok28AABKCAAIsCUs4HptNqoNps2aDrFGQhAAQG/EwEJkAEFAGWbTcW612bTBqYsBgoIgIjfSYAMKIA6IEHZZlOxbrHZtIECAiACEiADTNmG0mZTh2zK1vjsAQJQQABEQAJkQAHUAQXKBcoFyjbjqj2OzbgNIqApVytsm3EblAE2raq12SZRtYqySbRBBtgvm4VNIgPvbBYN8pNkkk4Kk+KkNClPspWVcx3rxL5uG+iJ5pM72cLMacdCrBP78mygJwpRiYEYiYnY3ULHQqwT1RG7W+ooRCUGYiQmYiYWYp0YHLG79S4JQlRiIPZNQ+/IbUOyYSYWYp24bUw29EQhKjEQu5vvmIiZWCb2jYnv3de3JgOVGIiRmIiZWIh1YnbE7hY7ClGJgdgtevflTCzEOrF0sV7URYmBGImJmImFWCdWR/REc5Pe1X33NTAQI9HcbCPSMBML0dzEntj3vZjtHxp6Yt8x+o5KDMRITMRMLERzs41EG35HpFvfow2km6ebp5unm6ebp1sPhQ2Fbj0UBtKth8JAugndhG5CN6Gb0K2HwkC69VAYSLceCgPppnRTuindlG6Bbj0UBtKth8JAuvVQGEi3QLdAt0C3SLdIt8gqiXTroTCQbj0UBtIt0i3SLdEt0S3RLbFKEt16VAykW4+KgXRLdMt0y3TLdMt0y6ySTLeeGgPp1lNjIN0K3QrdCt0K3QrdCquk0K1nyUC69SzZsNKt0q3SrdKt0q3SrbJKKt16lgycbsIsETfdhFkizBJhlgizRJglwiwRN92EWSKebswS8XRjlgizRJglwiwRZokwS8TTjVkiQjdmiQjdmCXCLBFmiTBLhFkizBJRujFLROnGLBGlG7NEmCXCLBFmiTBLhFkigW7MEgl0Y5ZIoBuzRJglwiwRZokwS4RZIpFuzBKJdGOWSKQbs0SYJcIsEWaJMEuEWSKJbswSSXRjlkiiG7NEmCXCLBFmiTBLhFkimW7MEsl0Y5ZIphuzRJglwiwRZokwS4RZIoVuzBIpdGOWSKEbs0SYJcIsEWaJMEuEWSKVbswSqXRjlqibbsosUWaJMkuUWaLMEmWWqJtuyixRRzdmiXq6MUuUWaLMEmWWKLNEmSXq6cYs0S1LYkc783WdumzpGImJmImFWCduobGhJwpRiXRTuindtniwpaf2IAj9eXoQDAzESEzETCzEOrEHwUBPpFukW6RbpFsPAjuUbZiJhVgn9iAY6IlCVGIXCx27WHh+vjnhBujD96e7O7sAOrsSahdF326f7h6/n949/nh4uDn97/bhR/+lf77dPvav32+f2k/bWN89fm5fm+CX+4c7o+cbvtrtv9SCOo6XWxDLlGjL8Rcifl+kHcIPiXbqPQWyvni97L++2P1Rf307T2UDavyNp8h+PkWMafcpwr5IKxh0ZKuSs3aklxLxYEekox2xfAY7bR/PkNLuM5RFX7YbooK+bJdEZYqk35BIlRIl70j4xZBqEdSltqP06xqR2Yjq9xqxKMw2fzEg2q4+d7tzreGOa8QyNdqF2a7GqjLyHBJt9077zUjHS+MXGpfVRjlaG79qxSXFIasKzXUOSrsZ2u1R8W+r0c5ukTrt0PYswNOrZ9FFf9iCEv1hK7R9lUWNhbZzHiKhbQinRujvdWcaiwhtBwBoR9QzhXx5K8SjP0Jb2e63Iq/eUDLGxZYi++3Iq7ENfo6td/vtqG+r0c47wuzT1Kr9TOXl2OqqyuKs1IbhOo3kMPXbtUk6rqGLZ1lUSEwOHRJb5+xrLOpUFIsFibJbH0uFghCTkvYrbDmyWsMc2fCiPl49SVm+Qc03hrD/JCuFs0VH3VUI7mhvLhUu6k11x6si6OHn0DetinYBglbYDUjef5LFO2QM0IhxvyqWCoKqiLqoinK4N8sb92adG6R2wxN3ezP647UV5WhvLBX+QG/kHNgbddEbq/d4mTstOzC9qiXBBSxFgztbVr9ux1pD49QI+/MkHq7ReLxGlyueisVs0MUqIfk/sOJZryJj5iqy7q9F00KlujBXGu3icmpoW5W+0FjtdgKX1dyltAPAlwqrGq1xblNqdldptAsJaLRbCLlSo8jUqFe2o3/2YdNol6hXtmMuNZpGvbIdkqfGWZL+nkaY06Xd+l2poZUaV/aHt09QDY0SrtRgn7YCuVKjFGpc2R8yjznajdJ+f+TVbqdm5rHn2Pp8eTO4Ymj3NVc+Spwbpnalo9dpJJZpurZME0sspes02rEEyqOt8/enXNE3HZYmMfegNe83Y3lGUecpc60Sdt8XyurMJmqMPBvI++8uJR8/oyjl6BnFshUXnlFUd/wdu7rj5wtV3lbj8jOKGo6fUSw1LjyjuFhjcUZR8/EdQz28Nq2H16brkb30jMI7f/SIwbvD+6e1xGXdoceH1bt4/Enimw7sxccMbcl59JTAu3q8O+obd8eF5wR+ddNzcX34w6dQa4k/0CGXHhX45U3NhWcFq6Zcus/3vhzv1MNpul43XLbT9/IHtvrrxVjwc6sfQ3C7izG/OjHQErlRPzvFkfxaZHX8MessnF0nts3m7zwN36RidHrlAjUUzz6puuiT5Qp17izbCnXVJ6tYDfOmNoYX75ivReofCCM9fLS/7pHz1fLZivs/PaKrPMqs+uJZJ7lcvotJZa7r6lnC/2d4dXk05fgxk7MDnRIuvsqvSbgh2/80gNd1sc4ye1msr58lr8aWO2UNu1f563bEwt1UPNuR/ZZImlXWeP+DCeHwJ05+1Q7PBEgSd0SWg+s5uHXxOY3VJVJ2GNp8dnTp2yA/v2/f3n66f3rxtweeTerp/vbjw9349suPx09nP/3+/2/4Cf52wbenr5/uPv94ujMl/gGD9s9frWbqTTtjy+9vTtq+T21SJfXtO/sgpP04tR/n8v7Z2vMv",
2760
+ "is_unconstrained": true,
2761
+ "name": "offchain_receive"
2762
+ },
2763
+ {
2764
+ "abi": {
2765
+ "error_types": {
2766
+ "11194752367584870169": {
2767
+ "error_kind": "fmtstring",
2768
+ "item_types": [
2769
+ {
2770
+ "kind": "field"
2771
+ }
2772
+ ],
2773
+ "length": 27
2774
+ },
2775
+ "13950240626967988787": {
2776
+ "error_kind": "string",
2777
+ "string": "Timestamp mismatch."
2778
+ },
2779
+ "3445904810750103705": {
2780
+ "error_kind": "string",
2781
+ "string": "Block number mismatch."
2782
+ },
2783
+ "6989792215391248978": {
2784
+ "error_kind": "string",
2785
+ "string": "Function check_timestamp can only be called statically"
2786
+ },
2787
+ "7259463707251703666": {
2788
+ "error_kind": "string",
2789
+ "string": "Function check_block_number can only be called statically"
2790
+ },
2791
+ "9688791427233494233": {
2792
+ "error_kind": "fmtstring",
2793
+ "item_types": [],
2794
+ "length": 17
2795
+ }
2796
+ },
2797
+ "parameters": [
2798
+ {
2799
+ "name": "selector",
2800
+ "type": {
2801
+ "kind": "field"
2802
+ },
2803
+ "visibility": "private"
2804
+ }
2805
+ ],
2806
+ "return_type": null
2807
+ },
2808
+ "bytecode": "JwACBAEoAAABBIBTJwAABFMlAAAAQScCAwQBJwIEBAAfCgADAAQAUi0IUgIlAAAAjScCAgRTJwIDBAA7DgADAAInAEMCAScARAICJwBFAgMnAEYCBCcARwIFJwBIAgYnAEkBACcASgEBJwBLAiAnAEwCZScATQJsJwBOAm4nAE8CbycAUAJyJwBRAnQmKQIAAwAY1alOCioCAwQnAgUEACcCBwQDACoFBwYtCAEDAAgBBgEnAwMEAQAiAwIGLQ4FBgAiBgIGLQ4FBicCBgQDACoDBgUnAgUEAScCBgQCJwIHBAAkAgAEAAAA8CMAAAHALQgBBCcCCAQDAAgBCAEnAwQEAQAiBAIIHzoABgAFAAgAKgQFCC0LCAgcCggKAhwKCgkAHAoJCAIAKgQGCS0LCQkcCgkKBRwKCgQAHgIACQAeAgAJAB4CAAkJJAIACQAAAVclAAAETh4CAAkGHAoJCgAnAgsEDC0IAAwtCgoOLQoIDy0KBBAACAALACUAAARgLQIAAC0KDgkkAgAJAAABlSUAAAZ/LQsDBAAiBAIELQ4EAwAiAwIILQsICCcCCQQDACoDCQQ7DgAIAAQjAAABwCkCAAQAT2MoqAoqAgQIJAIACAAAAdsjAAACqy0IAQQnAggEAwAIAQgBJwMEBAEAIgQCCB86AAYABQAIACoEBQgtCwgIHAoICQIcCgkFABwKBQgCACoEBgUtCwUFHAoFBgQcCgYEAB4CAAUAHgIABQAeAgAFCSQCAAUAAAJCJQAABpEeAgAFBRwKBQYAJwIJBAotCAAKLQoGDC0KCA0tCgQOAAgACQAlAAAEYC0CAAAtCgwFJAIABQAAAoAlAAAGoy0LAwQAIgQCBC0OBAMAIgMCBS0LBQUnAgYEAwAqAwYEOw4ABQAEIwAAAqsnAgMCVScCBAJrJwIFAncnAgYCcycCBwJjJwIIAnsnAgkCfS0IAQonAgsEHAAIAQsBJwMKBAEAIgoCCy0KCwwtDgMMACIMAgwtDE4MACIMAgwtDgQMACIMAgwtDE4MACIMAgwtDE8MACIMAgwtDgUMACIMAgwtDE4MACIMAgwtDEsMACIMAgwtDgYMACIMAgwtDEwMACIMAgwtDE0MACIMAgwtDEwMACIMAgwtDgcMACIMAgwtDFEMACIMAgwtDE8MACIMAgwtDFAMACIMAgwtDEsMACIMAgwtDggMACIMAgwtDgYMACIMAgwtDEwMACIMAgwtDE0MACIMAgwtDEwMACIMAgwtDgcMACIMAgwtDFEMACIMAgwtDE8MACIMAgwtDFAMACIMAgwtDgkMJwIDAAEKIElKBCQCAAQAAAROJwIFBB4tCAEGJwIHBB4ACAEHAS0KBgcqAwAHBZtbv/dKW/8ZACIHAgcAIgoCCCcCCQQbLQIIAy0CBwQtAgkFJQAABrUnAggEGwAqBwgHLQ4DBwAiBwIHLQ4CBwAiBwIHPA4FBioBAAEFYQC6/IQvolI8BAIBJgoqAgQGDCoCBAcKIgNDAiQCAAIAAAR8IwAABIUtCgYFIwAABnoKIgNEBBYKBggkAgAEAAAEmyMAAASkLQoIAiMAAAZxCiIDRQkkAgAJAAAEtiMAAAS/LQoHBCMAAAZoCiIDRgokAgAKAAAE0SMAAATbEioHBgkjAAAGXwoiA0cKFgoHCyQCAAoAAATxIwAABPsEKgsIBiMAAAZWCiIDSAckAgAHAAAFDSMAAAUSIwAABk0nAgICSScCAwJ2JwIEAmEnAgUCaScCBgJkJwIHAnAtCAEIJwIJBBIACAEJAScDCAQBACIIAgktCgkKLQ4CCgAiCgIKLQxOCgAiCgIKLQ4DCgAiCgIKLQ4ECgAiCgIKLQxNCgAiCgIKLQ4FCgAiCgIKLQ4GCgAiCgIKLQxLCgAiCgIKLQxPCgAiCgIKLQ4HCgAiCgIKLQxMCgAiCgIKLQxQCgAiCgIKLQ4ECgAiCgIKLQxRCgAiCgIKLQ4FCgAiCgIKLQxPCgAiCgIKLQxOCicCAgAACiBJSgMkAgADAAAGTScCBAQTLQgBBScCBgQTAAgBBgEtCgUGKgMABgWGdYB4Oxo02QAiBgIGACIIAgcnAgkEES0CBwMtAgYELQIJBSUAAAa1JwIHBBEAKgYHBi0OAgYAIgYCBjwOBAUtCgsGIwAABlYtCgYJIwAABl8tCgkEIwAABmgtCgQCIwAABnEtCgIFIwAABnotCgUCJioBAAEFwZk18E2mSjM8BAIBJioBAAEFZL7Lx4qT/3I8BAIBJioBAAEFL9JQKw6R0Jk8BAIBJgAAAwUHLQADCC0ABAkjAAAG2S0BCAYtBAYJAAAIAggAAAkCCQwACAcKJAAACgAABscm",
2809
+ "custom_attributes": [
2810
+ "abi_public"
2811
+ ],
2812
+ "debug_symbols": "tVlbbls5DN2Lv/OhBymK2UpRFGnqFgYMJ3CTAQZF9j7kFUnbAXSR3ml/yiO6OnyIomjn1+7b/uvrjy+H0/enn7v7T792X8+H4/Hw48vx6fHh5fB0Eu2vXdJ/MuTdfb7bZUwmcXdfRLZk0tZkawKTPGS3dbc1V5N9kSUVkzQkCA+oBJM8JNoabd1sTbKfVNKQXfztKtuQbGuWdU53u5qyA/E8S0g1JweqEZJaNBjVFI1OzNSqGlTQDYAG0hWohgWgaKoyYzfQioNmQNM0ADhgA9013bezbhc3ICUHI9uQRjYhg0ndUgWU6oAM1OLANeqwkiENSbikEmikFjqYtDXbmsca00g15mJypBpLNmnrKuuKCpoBPdzaFKCBpayUZKkr8QaXwlIzS2XpLqoONErJNHbRQFIgGtBdWlYD0ABNz3kAdMAGNGsDuKZUB7pdMtoqGoBR2A3A5Eh9Q8t0Q8t9a8WBZbqRa9ThqruWs1XArmHTUKoOXJNdk11TigMyUF1TXQOugWZAkzwAOmADeo0GcBPkRskJuxN2J9RLNYAR9pQcgAMz0T2K7lF0j6J7FL1mB2aigxOCmwAnRDeBTtjcRHNCchPkhN1NdCdkN8FOyGaC/SzYz4JzcWAmuGQHZoJrcoAOnBDAgROim0AnbG6iOSG5CXLC7iaWSwoK2ACbJiftqYbIUc6BmqMSOu1zA2l/G0gbnKHQYegwmFuwtGDRNmcodD10PTx153PiYGa3lrUNAy5IWDAp0hyjPkRZPUB9SrImDqsivV6oe4v2ctS9pQozNkUa0fL/ikaEpEh9xq5IPR069k+r1oGh0OXQ5dCV0JXQ6c00RI4gdBA6DB02R9oEDWEgdqRvh6Gw1sODHswczOzMoG3RkDNDToEgkFuDiA0iNojYIGIDCGYIaxjMGNYwmFtYa8FMYY2CuYe1Hswc1tiZMaVAwtzSgthRDp32H0PkSDuQoeYIQqdNaCDtOQNp0zEUOgodBXMPlh4s2noMua6lFAgCLd6/vd3tfDT78nLe73Uyu5rVZIJ7fjjvTy+7+9Pr8Xi3++fh+Lr8p5/PD6dFvjyc5VPh3J++iRTC74fjXtHb3WV3mm+F3Hy3TBs5CHL+MIVUJhiFwLaFojO6F5wSTinqnEImymIUBWu9UPT+US9Y7oR7IWxTL3DFi6wT5/AilwuF3J0birYWCDpDoyuCusmHmqY+rFAAAHlVAPYpBf/FMG58uKFoH65MZM9EbZ2nB5rLnAOTPjILB+Z8cUOeoluOldqE1EpcsgJzDphzyDctvyKZc5pzrFVGwqhwwfUSDb0jWatP6k7BML1ma6GUQlGgleo8lL5ytBD1VaFdOgbhLQX/gWyU9L+zsVZgjaPAqMyzUVY4qlx59nRkmQGmoaxUqYxt7ohcEN4YTOcIBtr8aFc4mP1kZai9HAqW20jWS7TGY0Ad+jQdNCdp7JHQ9bX/jWRcB1L6LJA1BjmSoJBheRtFVKgUBs8oVt93qJf3neaP81qBpnjgq3x3mKZzpXnJjy09mjnx9D2o8BcfpRsn+vxhXD0RaTV+ItjK7ETqSm2K9yVdIqk8K/C60kJb8QJvmDYV+E0kV438d8oTs9/U3IA2UVwmvyy9dEOFYypeF5jafPCDtfkzRce5euEBPnzL2IdoSJf9peOHJ/kSM8ZVs3lPACttky7jEsmPaZc03NY20NqzHLOnwKs35J0Xay97StFu0vWw9I5i5WWXr9zxHAqGMgslrY6fnk5KW85DKslr6urryG8QUPIrTqVt8oCcAHkTwXWH2EYQ3bL1TUVN5EVNzJsIqntA20Lo1XPQ25wAeUtn+Cyrh8fD+eYPNG/KdD48fD3ubfn99fR49enLv8/+if+B5/n89Lj/9nreK9Plrzzyq8Un+UXqriJ91p/RdCn5qJA+v6n1/wA=",
2813
+ "is_unconstrained": true,
2814
+ "name": "public_dispatch"
2815
+ },
2816
+ {
2817
+ "abi": {
2818
+ "error_types": {},
2819
+ "parameters": [
2820
+ {
2821
+ "name": "scope",
2822
+ "type": {
2823
+ "fields": [
2824
+ {
2825
+ "name": "inner",
2826
+ "type": {
2827
+ "kind": "field"
2828
+ }
2829
+ }
2830
+ ],
2831
+ "kind": "struct",
2832
+ "path": "aztec::protocol_types::address::aztec_address::AztecAddress"
2833
+ },
2834
+ "visibility": "private"
2835
+ }
2836
+ ],
2837
+ "return_type": null
2838
+ },
2839
+ "bytecode": "H4sIAAAAAAAA/9XUy07CQBQG4OHiFe93XfkKojFutYTEBRsIa9LQk2aSoSXtgVhXzhtMQd254qIRfQK3PoYPI91AwRyaujCxu843558z7bSplv/46npWteKijuDLwZXDheCmpgtxz3zZL3HLFNBWfuvzmM2+EixyClNtpaKDfKbUcMVQZ0+yp9mWi23Zz3EHqpiUz9cWgglOp3yajY6crk/Eqr/LTdezeOuP61+KIHTkTUj9dgejhHS8BCbfgtdq6Khrdt0bbUUL9xQK7xTsZms8kBzP7wY5fuZnR8m/fipMdkto1/2JPkNhg7ztADetoOGHD/0WoVppoKiYgGXkgqM3bADhBr/YgXwvQM12vEvDcMB1wzGUpEmZI2WelAVSFklZImWZlAwpK6SskrJGyjopG6RskrJFyjYpO6TskrJHyj4p9Nk5JOUoOHLD/2utLqCX5yCM/3Y38alGTjk/i5XZLZ9kL2aPxu1bqX4RsOFY312tuID3BgAA",
2840
+ "custom_attributes": [
2841
+ "abi_utility"
2842
+ ],
2843
+ "debug_symbols": "dZHdCoMwDIXfJddetDrnz6uMIVWjFEqV2g6G9N2XSp164U2T9OR8hGSFHls3NlIP0wL1a4XWSKXk2KipE1ZOmn5XYOHhHOrM+wR2qbEGMSinXiLMwqC2UGunVAIfodzWtMxCb9EKQypLAHVPkYCDVBgynxxudm/lrMrzaKe8Sv8IzvILhN9DiiePiKI8AEV28af3/pJn0V8++DFARQO8qRSdNJcd+oAyUrQKYzk43Z1U+513Zb/BbKYOe2cwkDaN2D8=",
2844
+ "is_unconstrained": true,
2845
+ "name": "sync_state"
2846
+ }
2847
+ ],
2848
+ "name": "PublicChecks",
2849
+ "noir_version": "1.0.0-beta.26+40d6574f851d926f93e0c3a271bac3e6e82ac905",
2850
+ "outputs": {
2851
+ "globals": {},
2852
+ "structs": {
2853
+ "functions": [
2854
+ {
2855
+ "fields": [
2856
+ {
2857
+ "name": "parameters",
2858
+ "type": {
2859
+ "fields": [
2860
+ {
2861
+ "name": "operation",
2862
+ "type": {
2863
+ "kind": "integer",
2864
+ "sign": "unsigned",
2865
+ "width": 8
2866
+ }
2867
+ },
2868
+ {
2869
+ "name": "value",
2870
+ "type": {
2871
+ "kind": "integer",
2872
+ "sign": "unsigned",
2873
+ "width": 32
2874
+ }
2875
+ }
2876
+ ],
2877
+ "kind": "struct",
2878
+ "path": "PublicChecks::check_block_number_parameters"
2879
+ }
2880
+ }
2881
+ ],
2882
+ "kind": "struct",
2883
+ "path": "PublicChecks::check_block_number_abi"
2884
+ },
2885
+ {
2886
+ "fields": [
2887
+ {
2888
+ "name": "parameters",
2889
+ "type": {
2890
+ "fields": [
2891
+ {
2892
+ "name": "operation",
2893
+ "type": {
2894
+ "kind": "integer",
2895
+ "sign": "unsigned",
2896
+ "width": 8
2897
+ }
2898
+ },
2899
+ {
2900
+ "name": "value",
2901
+ "type": {
2902
+ "kind": "integer",
2903
+ "sign": "unsigned",
2904
+ "width": 64
2905
+ }
2906
+ }
2907
+ ],
2908
+ "kind": "struct",
2909
+ "path": "PublicChecks::check_timestamp_parameters"
2910
+ }
2911
+ }
2912
+ ],
2913
+ "kind": "struct",
2914
+ "path": "PublicChecks::check_timestamp_abi"
2915
+ },
2916
+ {
2917
+ "fields": [
2918
+ {
2919
+ "name": "parameters",
2920
+ "type": {
2921
+ "fields": [
2922
+ {
2923
+ "name": "messages",
2924
+ "type": {
2925
+ "fields": [
2926
+ {
2927
+ "name": "storage",
2928
+ "type": {
2929
+ "kind": "array",
2930
+ "length": 16,
2931
+ "type": {
2932
+ "fields": [
2933
+ {
2934
+ "name": "ciphertext",
2935
+ "type": {
2936
+ "fields": [
2937
+ {
2938
+ "name": "storage",
2939
+ "type": {
2940
+ "kind": "array",
2941
+ "length": 15,
2942
+ "type": {
2943
+ "kind": "field"
2944
+ }
2945
+ }
2946
+ },
2947
+ {
2948
+ "name": "len",
2949
+ "type": {
2950
+ "kind": "integer",
2951
+ "sign": "unsigned",
2952
+ "width": 32
2953
+ }
2954
+ }
2955
+ ],
2956
+ "kind": "struct",
2957
+ "path": "std::collections::bounded_vec::BoundedVec"
2958
+ }
2959
+ },
2960
+ {
2961
+ "name": "recipient",
2962
+ "type": {
2963
+ "fields": [
2964
+ {
2965
+ "name": "inner",
2966
+ "type": {
2967
+ "kind": "field"
2968
+ }
2969
+ }
2970
+ ],
2971
+ "kind": "struct",
2972
+ "path": "aztec::protocol_types::address::aztec_address::AztecAddress"
2973
+ }
2974
+ },
2975
+ {
2976
+ "name": "tx_hash",
2977
+ "type": {
2978
+ "fields": [
2979
+ {
2980
+ "name": "_is_some",
2981
+ "type": {
2982
+ "kind": "boolean"
2983
+ }
2984
+ },
2985
+ {
2986
+ "name": "_value",
2987
+ "type": {
2988
+ "kind": "field"
2989
+ }
2990
+ }
2991
+ ],
2992
+ "kind": "struct",
2993
+ "path": "std::option::Option"
2994
+ }
2995
+ },
2996
+ {
2997
+ "name": "anchor_block_timestamp",
2998
+ "type": {
2999
+ "kind": "integer",
3000
+ "sign": "unsigned",
3001
+ "width": 64
3002
+ }
3003
+ }
3004
+ ],
3005
+ "kind": "struct",
3006
+ "path": "aztec::messages::processing::offchain::OffchainMessage"
3007
+ }
3008
+ }
3009
+ },
3010
+ {
3011
+ "name": "len",
3012
+ "type": {
3013
+ "kind": "integer",
3014
+ "sign": "unsigned",
3015
+ "width": 32
3016
+ }
3017
+ }
3018
+ ],
3019
+ "kind": "struct",
3020
+ "path": "std::collections::bounded_vec::BoundedVec"
3021
+ }
3022
+ }
3023
+ ],
3024
+ "kind": "struct",
3025
+ "path": "PublicChecks::offchain_receive_parameters"
3026
+ }
3027
+ }
3028
+ ],
3029
+ "kind": "struct",
3030
+ "path": "PublicChecks::offchain_receive_abi"
3031
+ },
3032
+ {
3033
+ "fields": [
3034
+ {
3035
+ "name": "parameters",
3036
+ "type": {
3037
+ "fields": [
3038
+ {
3039
+ "name": "scope",
3040
+ "type": {
3041
+ "fields": [
3042
+ {
3043
+ "name": "inner",
3044
+ "type": {
3045
+ "kind": "field"
3046
+ }
3047
+ }
3048
+ ],
3049
+ "kind": "struct",
3050
+ "path": "aztec::protocol_types::address::aztec_address::AztecAddress"
3051
+ }
3052
+ }
3053
+ ],
3054
+ "kind": "struct",
3055
+ "path": "PublicChecks::sync_state_parameters"
3056
+ }
3057
+ }
3058
+ ],
3059
+ "kind": "struct",
3060
+ "path": "PublicChecks::sync_state_abi"
3061
+ }
3062
+ ]
3063
+ }
3064
+ },
3065
+ "transpiled": true,
3066
+ "aztec_version": "6.0.0-nightly.20260829"
3067
+ }