From 1c7e8ad78e0226c35a2197302e104fe252bf7a8d Mon Sep 17 00:00:00 2001 From: benesjan Date: Thu, 24 Oct 2024 15:40:38 +0000 Subject: [PATCH] fmt --- .../aztec-nr/address-note/src/address_note.nr | 26 +- noir-projects/aztec-nr/authwit/src/account.nr | 9 +- noir-projects/aztec-nr/authwit/src/auth.nr | 115 ++--- .../aztec-nr/authwit/src/cheatcodes.nr | 25 +- .../aztec-nr/authwit/src/entrypoint/app.nr | 6 +- .../aztec-nr/authwit/src/entrypoint/fee.nr | 6 +- .../authwit/src/entrypoint/function_call.nr | 6 +- .../aztec/src/context/call_interfaces.nr | 156 ++---- .../context/inputs/private_context_inputs.nr | 7 +- .../aztec-nr/aztec/src/context/mod.nr | 6 +- .../aztec/src/context/packed_returns.nr | 7 +- .../aztec/src/context/private_context.nr | 188 +++---- .../aztec/src/context/public_context.nr | 54 +- .../src/context/unconstrained_context.nr | 13 +- noir-projects/aztec-nr/aztec/src/deploy.nr | 18 +- .../encrypted_event_emission.nr | 40 +- .../encrypted_logs/encrypted_note_emission.nr | 31 +- .../aztec/src/encrypted_logs/header.nr | 21 +- .../aztec/src/encrypted_logs/payload.nr | 94 ++-- noir-projects/aztec-nr/aztec/src/hash.nr | 39 +- .../aztec/src/history/contract_inclusion.nr | 8 +- .../aztec/src/history/note_inclusion.nr | 14 +- .../aztec/src/history/note_validity.nr | 9 +- .../aztec/src/history/nullifier_inclusion.nr | 35 +- .../src/history/nullifier_non_inclusion.nr | 29 +- .../aztec/src/history/public_storage.nr | 63 +-- .../aztec-nr/aztec/src/initializer.nr | 25 +- .../aztec-nr/aztec/src/keys/constants.nr | 5 +- .../aztec-nr/aztec/src/keys/getters/mod.nr | 15 +- .../aztec-nr/aztec/src/keys/getters/test.nr | 4 +- .../aztec/src/keys/point_to_symmetric_key.nr | 10 +- .../aztec-nr/aztec/src/macros/dispatch/mod.nr | 27 +- .../aztec/src/macros/functions/interfaces.nr | 18 +- .../aztec/src/macros/functions/mod.nr | 35 +- .../aztec-nr/aztec/src/macros/mod.nr | 17 +- .../aztec-nr/aztec/src/macros/notes/mod.nr | 148 ++---- .../aztec-nr/aztec/src/macros/storage/mod.nr | 24 +- .../aztec-nr/aztec/src/macros/utils.nr | 56 +-- noir-projects/aztec-nr/aztec/src/messaging.nr | 15 +- .../aztec-nr/aztec/src/note/lifecycle.nr | 30 +- .../aztec/src/note/note_getter/mod.nr | 89 ++-- .../aztec/src/note/note_getter/test.nr | 33 +- .../aztec/src/note/note_getter_options.nr | 26 +- .../aztec-nr/aztec/src/note/note_header.nr | 9 +- .../aztec-nr/aztec/src/note/note_type_id.nr | 1 - .../aztec/src/note/note_viewer_options.nr | 10 +- .../aztec-nr/aztec/src/note/utils.nr | 33 +- .../aztec-nr/aztec/src/oracle/arguments.nr | 8 +- .../aztec/src/oracle/call_private_function.nr | 10 +- .../oracle/enqueue_public_function_call.nr | 16 +- .../aztec/src/oracle/get_contract_instance.nr | 23 +- .../oracle/get_l1_to_l2_membership_witness.nr | 11 +- .../src/oracle/get_membership_witness.nr | 12 +- .../get_nullifier_membership_witness.nr | 20 +- .../src/oracle/get_public_data_witness.nr | 24 +- .../aztec/src/oracle/get_sibling_path.nr | 8 +- .../aztec-nr/aztec/src/oracle/header.nr | 27 +- .../src/oracle/key_validation_request.nr | 10 +- .../aztec-nr/aztec/src/oracle/keys.nr | 18 +- .../aztec-nr/aztec/src/oracle/logs.nr | 44 +- .../aztec-nr/aztec/src/oracle/notes.nr | 47 +- .../aztec-nr/aztec/src/oracle/returns.nr | 4 +- .../aztec-nr/aztec/src/oracle/storage.nr | 16 +- noir-projects/aztec-nr/aztec/src/prelude.nr | 10 +- .../aztec-nr/aztec/src/state_vars/map.nr | 5 +- .../aztec/src/state_vars/private_immutable.nr | 22 +- .../aztec/src/state_vars/private_mutable.nr | 22 +- .../src/state_vars/private_mutable/test.nr | 11 +- .../aztec/src/state_vars/private_set.nr | 27 +- .../aztec/src/state_vars/public_immutable.nr | 12 +- .../aztec/src/state_vars/public_mutable.nr | 8 +- .../aztec/src/state_vars/shared_immutable.nr | 19 +- .../shared_mutable/scheduled_delay_change.nr | 7 +- .../scheduled_delay_change/test.nr | 86 +--- .../shared_mutable/scheduled_value_change.nr | 15 +- .../scheduled_value_change/test.nr | 38 +- .../shared_mutable/shared_mutable.nr | 60 +-- .../src/state_vars/shared_mutable/test.nr | 90 ++-- .../aztec/src/test/helpers/cheatcodes.nr | 36 +- .../src/test/helpers/test_environment.nr | 40 +- .../aztec-nr/aztec/src/test/helpers/utils.nr | 57 +-- .../aztec/src/test/mocks/mock_note.nr | 25 +- .../unencrypted_event_emission.nr | 15 +- .../aztec/src/utils/collapse_array.nr | 34 +- .../aztec-nr/aztec/src/utils/comparison.nr | 25 +- .../aztec-nr/aztec/src/utils/point.nr | 8 +- .../aztec-nr/aztec/src/utils/test.nr | 6 +- .../src/easy_private_uint.nr | 31 +- .../aztec-nr/uint-note/src/uint_note.nr | 15 +- .../aztec-nr/value-note/src/balance_utils.nr | 10 +- .../aztec-nr/value-note/src/filter.nr | 2 +- .../aztec-nr/value-note/src/utils.nr | 29 +- .../aztec-nr/value-note/src/value_note.nr | 26 +- .../src/dapp_payload.nr | 6 +- .../app_subscription_contract/src/main.nr | 46 +- .../src/subscription_note.nr | 24 +- .../contracts/auth_contract/src/main.nr | 5 +- .../contracts/auth_contract/src/test/utils.nr | 3 +- .../auth_registry_contract/src/main.nr | 17 +- .../auth_wit_test_contract/src/main.nr | 4 +- .../avm_initializer_test_contract/src/main.nr | 4 +- .../contracts/avm_test_contract/src/main.nr | 54 +- .../contracts/card_game_contract/src/cards.nr | 18 +- .../contracts/card_game_contract/src/game.nr | 12 +- .../contracts/card_game_contract/src/main.nr | 36 +- .../contracts/child_contract/src/main.nr | 9 +- .../contracts/claim_contract/src/main.nr | 9 +- .../src/events/class_registered.nr | 5 +- .../events/private_function_broadcasted.nr | 25 +- .../unconstrained_function_broadcasted.nr | 24 +- .../src/main.nr | 104 ++-- .../src/main.nr | 16 +- .../contracts/counter_contract/src/main.nr | 14 +- .../crowdfunding_contract/src/main.nr | 24 +- .../docs_example_contract/src/main.nr | 110 ++-- .../docs_example_contract/src/options.nr | 33 +- .../src/types/card_note.nr | 16 +- .../easy_private_token_contract/src/main.nr | 2 +- .../easy_private_voting_contract/src/main.nr | 6 +- .../ecdsa_k_account_contract/src/main.nr | 25 +- .../ecdsa_r_account_contract/src/main.nr | 25 +- .../contracts/escrow_contract/src/main.nr | 10 +- .../contracts/fee_juice_contract/src/main.nr | 10 +- .../contracts/fpc_contract/src/lib.nr | 5 +- .../contracts/fpc_contract/src/main.nr | 39 +- .../import_test_contract/src/main.nr | 34 +- .../inclusion_proofs_contract/src/main.nr | 43 +- .../contracts/lending_contract/src/asset.nr | 2 +- .../contracts/lending_contract/src/helpers.nr | 4 +- .../contracts/lending_contract/src/main.nr | 101 ++-- .../src/test/transfer_in_private.nr | 66 +-- .../src/test/transfer_in_public.nr | 57 +-- .../src/test/transfer_to_private.nr | 34 +- .../src/test/transfer_to_public.nr | 63 +-- .../contracts/parent_contract/src/main.nr | 171 +++---- .../pending_note_hashes_contract/src/main.nr | 163 +++--- .../private_fpc_contract/src/main.nr | 6 +- .../private_fpc_contract/src/settings.nr | 5 +- .../contracts/router_contract/src/main.nr | 8 +- .../schnorr_account_contract/src/main.nr | 35 +- .../src/public_key_note.nr | 15 +- .../src/main.nr | 8 +- .../src/auth_oracle.nr | 6 +- .../src/main.nr | 4 +- .../src/util.nr | 2 +- .../contracts/spam_contract/src/main.nr | 44 +- .../spam_contract/src/types/balance_set.nr | 37 +- .../spam_contract/src/types/token_note.nr | 21 +- .../stateful_test_contract/src/main.nr | 10 +- .../static_child_contract/src/main.nr | 25 +- .../static_parent_contract/src/main.nr | 70 ++- .../contracts/test_contract/src/main.nr | 180 +++---- .../contracts/test_contract/src/test_note.nr | 8 +- .../contracts/test_log_contract/src/main.nr | 68 +-- .../token_blacklist_contract/src/main.nr | 59 +-- .../src/types/balances_map.nr | 36 +- .../src/types/roles.nr | 6 +- .../src/types/token_note.nr | 21 +- .../src/types/transparent_note.nr | 13 +- .../token_bridge_contract/src/main.nr | 29 +- .../contracts/token_contract/src/main.nr | 156 ++---- .../token_contract/src/test/access_control.nr | 3 +- .../contracts/token_contract/src/test/burn.nr | 70 +-- .../token_contract/src/test/minting.nr | 75 +-- .../src/test/reading_constants.nr | 4 +- .../token_contract/src/test/refunds.nr | 50 +- .../token_contract/src/test/shielding.nr | 67 +-- .../src/test/transfer_private.nr | 76 +-- .../src/test/transfer_public.nr | 78 +-- .../token_contract/src/test/unshielding.nr | 63 +-- .../token_contract/src/test/utils.nr | 27 +- .../token_contract/src/types/balance_set.nr | 36 +- .../token_contract/src/types/token_note.nr | 21 +- .../src/types/transparent_note.nr | 16 +- .../contracts/uniswap_contract/src/main.nr | 108 ++-- .../contracts/uniswap_contract/src/util.nr | 25 +- .../parity-lib/src/base/base_parity_inputs.nr | 4 +- .../parity-lib/src/parity_public_inputs.nr | 6 +- .../parity-lib/src/root/root_parity_input.nr | 13 +- .../parity-lib/src/root/root_parity_inputs.nr | 47 +- .../src/root/root_rollup_parity_input.nr | 14 +- .../private-kernel-init-simulated/src/main.nr | 4 +- .../crates/private-kernel-init/src/main.nr | 4 +- .../src/main.nr | 4 +- .../crates/private-kernel-inner/src/main.nr | 4 +- .../components/previous_kernel_validator.nr | 101 +--- .../previous_kernel_validator_hints.nr | 11 +- .../components/private_call_data_validator.nr | 192 +++---- .../find_first_revertible_item_index.nr | 7 +- .../validate_contract_address.nr | 21 +- .../validate_split_ranges.nr | 13 +- ...private_kernel_circuit_output_validator.nr | 146 +++--- ...e_kernel_circuit_public_inputs_composer.nr | 73 +-- .../src/components/reset_output_composer.nr | 37 +- .../reset_output_hints.nr | 37 +- ...r_propagated_note_hash_indexes_for_logs.nr | 6 +- .../squash_transient_data.nr | 12 +- .../src/components/reset_output_validator.nr | 80 +-- .../src/components/tail_output_composer.nr | 16 +- .../tail_output_composer/meter_gas_used.nr | 12 +- .../src/components/tail_output_validator.nr | 49 +- .../tail_output_hints.nr | 18 +- .../tail_to_public_output_composer.nr | 17 +- .../meter_gas_used.nr | 16 +- .../split_to_public.nr | 4 +- .../tail_to_public_output_validator.nr | 70 ++- .../tail_to_public_output_hints.nr | 24 +- .../src/private_kernel_empty.nr | 13 +- .../src/private_kernel_init.nr | 43 +- .../src/private_kernel_inner.nr | 70 ++- .../src/private_kernel_reset.nr | 177 +++---- .../src/private_kernel_tail.nr | 98 ++-- .../src/private_kernel_tail_to_public.nr | 142 +++--- .../mod.nr | 11 +- .../validate_against_previous_kernel.nr | 13 +- .../validate_arrays.nr | 4 +- .../mod.nr | 30 +- .../validate_propagated_from_private_call.nr | 5 +- .../mod.nr | 20 +- ..._from_previous_kernel_with_private_call.nr | 20 +- .../new_from_tx_request.nr | 7 +- .../propagate_from_private_call.nr | 12 +- .../reset_output_validator_builder/mod.nr | 33 +- .../meter_gas_used.nr | 13 +- .../tests/tail_output_composer_builder/mod.nr | 5 +- .../tail_output_validator_builder/mod.nr | 6 +- .../meter_gas_used.nr | 17 +- .../mod.nr | 2 +- .../split_to_public.nr | 8 +- .../tail_to_public_output_composer.nr | 32 +- .../src/main.nr | 21 +- .../crates/private-kernel-reset/src/main.nr | 21 +- .../private-kernel-tail-simulated/src/main.nr | 5 +- .../src/main.nr | 7 +- .../private-kernel-tail-to-public/src/main.nr | 7 +- .../crates/private-kernel-tail/src/main.nr | 5 +- .../enqueued_call_data_validator.nr | 59 +-- .../components/previous_kernel_validator.nr | 29 +- .../public_kernel_output_composer.nr | 23 +- .../propagate_accumulated_data.nr | 13 +- .../public_kernel_output_validator.nr | 126 ++--- .../components/public_tail_output_composer.nr | 35 +- .../combine_data.nr | 61 ++- .../generate_output_hints.nr | 63 +-- ...generate_overridable_public_data_writes.nr | 9 +- .../generate_public_data_leaves.nr | 21 +- .../public_tail_output_validator.nr | 94 ++-- .../validate_linked_public_data_writes.nr | 137 ++--- .../validate_public_data_leaf_memberships.nr | 9 +- .../validate_unique_leaf_slots.nr | 12 +- .../components/vm_circuit_output_composer.nr | 52 +- .../propagate_accumulated_data.nr | 49 +- .../src/public_kernel_inner.nr | 6 +- .../src/public_kernel_merge.nr | 69 ++- .../src/public_kernel_tail.nr | 244 ++++----- .../public-kernel-merge-simulated/src/main.nr | 4 +- .../public-kernel-tail-simulated/src/main.nr | 4 +- .../crates/reset-kernel-lib/src/lib.nr | 2 +- .../src/note_hash_read_request_reset.nr | 85 ++-- ...llifier_non_existent_read_request_reset.nr | 5 +- .../src/nullifier_read_request_reset.nr | 109 ++-- .../private_validation_request_processor.nr | 41 +- .../src/public_data_read_request_hints.nr | 11 +- .../public_validation_request_processor.nr | 67 ++- .../src/reset/key_validation_hint.nr | 39 +- .../src/reset/mutable_data_read_request.nr | 144 ++---- .../src/reset/non_existent_read_request.nr | 85 ++-- .../src/reset/read_request.nr | 137 +++-- .../src/reset/transient_data.nr | 140 +++--- .../src/reset/tree_leaf_read_request.nr | 6 +- .../note_hash_read_request_hints_builder.nr | 24 +- ...non_existent_read_request_hints_builder.nr | 32 +- .../nullifier_read_request_hints_builder.nr | 24 +- .../base_or_merge_rollup_public_inputs.nr | 10 +- ...block_root_or_block_merge_public_inputs.nr | 21 +- .../src/abis/constant_rollup_data.nr | 6 +- .../src/abis/previous_rollup_block_data.nr | 22 +- .../src/abis/previous_rollup_data.nr | 21 +- .../rollup-lib/src/base/base_rollup_inputs.nr | 475 ++++++++---------- .../rollup-lib/src/base/state_diff_hints.nr | 8 +- .../block_merge/block_merge_rollup_inputs.nr | 27 +- .../block_root/block_root_rollup_inputs.nr | 34 +- .../empty_block_root_rollup_inputs.nr | 6 +- .../crates/rollup-lib/src/block_root/mod.nr | 18 +- .../crates/rollup-lib/src/components.nr | 151 +++--- .../src/merge/merge_rollup_inputs.nr | 37 +- .../crates/rollup-lib/src/root/mod.nr | 37 +- .../rollup-lib/src/root/root_rollup_inputs.nr | 11 +- .../src/tests/block_root_rollup_inputs.nr | 17 +- .../rollup-lib/src/tests/l1_to_l2_roots.nr | 5 +- .../src/tests/previous_rollup_block_data.nr | 5 +- .../src/tests/previous_rollup_data.nr | 5 +- .../combined_accumulated_data.nr | 48 +- .../private_accumulated_data.nr | 33 +- .../private_accumulated_data_builder.nr | 23 +- .../public_accumulated_data.nr | 59 ++- .../public_accumulated_data_builder.nr | 24 +- .../src/abis/append_only_tree_snapshot.nr | 9 +- .../crates/types/src/abis/call_context.nr | 8 +- .../types/src/abis/combined_constant_data.nr | 8 +- .../contract_class_function_leaf_preimage.nr | 2 +- .../crates/types/src/abis/function_data.nr | 7 +- .../types/src/abis/function_selector.nr | 3 +- .../crates/types/src/abis/gas.nr | 2 +- .../crates/types/src/abis/gas_settings.nr | 13 +- .../crates/types/src/abis/global_variables.nr | 9 +- .../kernel_circuit_public_inputs.nr | 21 +- .../abis/kernel_circuit_public_inputs/mod.nr | 4 +- .../private_kernel_circuit_public_inputs.nr | 45 +- ...te_kernel_circuit_public_inputs_builder.nr | 15 +- .../public_kernel_circuit_public_inputs.nr | 20 +- ...ic_kernel_circuit_public_inputs_builder.nr | 17 +- .../vm_circuit_public_inputs.nr | 49 +- .../crates/types/src/abis/kernel_data.nr | 22 +- .../crates/types/src/abis/log_hash.nr | 54 +- .../crates/types/src/abis/max_block_number.nr | 4 +- .../crates/types/src/abis/note_hash.nr | 17 +- .../types/src/abis/note_hash_leaf_preimage.nr | 11 +- .../crates/types/src/abis/nullifier.nr | 29 +- .../types/src/abis/nullifier_leaf_preimage.nr | 11 +- .../types/src/abis/private_call_request.nr | 6 +- .../src/abis/private_circuit_public_inputs.nr | 113 ++--- .../abis/private_kernel/private_call_data.nr | 18 +- .../types/src/abis/private_kernel_data.nr | 16 +- .../types/src/abis/public_call_request.nr | 4 +- .../abis/public_call_stack_item_compressed.nr | 11 +- .../src/abis/public_circuit_public_inputs.nr | 75 ++- .../crates/types/src/abis/public_data_read.nr | 9 +- .../src/abis/public_data_update_request.nr | 22 +- .../types/src/abis/public_data_write.nr | 15 +- .../src/abis/public_inner_call_request.nr | 7 +- .../types/src/abis/public_kernel_data.nr | 22 +- .../src/abis/public_kernel_inner_data.nr | 4 +- .../crates/types/src/abis/read_request.nr | 11 +- .../key_validation_request.nr | 5 +- .../key_validation_request_and_generator.nr | 19 +- .../private_validation_requests.nr | 55 +- .../private_validation_requests_builder.nr | 29 +- .../public_validation_requests.nr | 71 ++- .../public_validation_requests_builder.nr | 33 +- .../rollup_validation_requests.nr | 2 +- ...ed_key_validation_request_and_generator.nr | 13 +- .../crates/types/src/address/aztec_address.nr | 32 +- .../types/src/address/partial_address.nr | 18 +- .../src/address/salted_initialization_hash.nr | 12 +- .../crates/types/src/contract_class_id.nr | 4 +- .../crates/types/src/contract_instance.nr | 22 +- .../crates/types/src/contrakt/storage_read.nr | 6 +- .../src/contrakt/storage_update_request.nr | 10 +- .../crates/types/src/data/hash.nr | 7 +- .../crates/types/src/data/public_data_hint.nr | 9 +- .../types/src/data/public_data_leaf_hint.nr | 7 +- .../types/src/data/public_data_tree_leaf.nr | 12 +- .../data/public_data_tree_leaf_preimage.nr | 8 +- .../crates/types/src/debug_log.nr | 9 +- .../crates/types/src/hash.nr | 101 ++-- .../crates/types/src/header.nr | 28 +- .../crates/types/src/lib.nr | 2 +- .../types/src/merkle_tree/append_only_tree.nr | 16 +- .../types/src/merkle_tree/indexed_tree.nr | 38 +- .../indexed_tree/check_valid_low_leaf.nr | 10 +- .../types/src/merkle_tree/membership.nr | 85 ++-- .../types/src/merkle_tree/merkle_tree.nr | 12 +- .../crates/types/src/merkle_tree/mod.nr | 2 +- .../crates/types/src/merkle_tree/root.nr | 2 +- .../src/merkle_tree/variable_merkle_tree.nr | 10 +- .../types/src/messaging/l2_to_l1_message.nr | 23 +- .../crates/types/src/meta/mod.nr | 42 +- .../types/src/partial_state_reference.nr | 10 +- .../crates/types/src/public_keys.nr | 70 +-- .../crates/types/src/recursion/proof.nr | 2 +- .../types/src/recursion/verification_key.nr | 4 +- .../crates/types/src/state_reference.nr | 19 +- .../crates/types/src/storage/map.nr | 10 +- .../crates/types/src/tests/fixture_builder.nr | 453 +++++++---------- .../src/tests/fixtures/contract_functions.nr | 11 +- .../types/src/tests/fixtures/contracts.nr | 13 +- .../tests/fixtures/protocol_contract_tree.nr | 2 +- .../types/src/tests/fixtures/vk_tree.nr | 22 +- .../types/src/tests/merkle_tree_utils.nr | 29 +- .../crates/types/src/tests/utils.nr | 8 +- .../crates/types/src/traits.nr | 6 +- .../types/src/transaction/tx_context.nr | 4 +- .../types/src/transaction/tx_request.nr | 25 +- .../crates/types/src/type_serialization.nr | 6 +- .../crates/types/src/utils/arrays.nr | 55 +- .../src/utils/arrays/assert_array_appended.nr | 37 +- .../utils/arrays/assert_array_prepended.nr | 9 +- .../src/utils/arrays/assert_combined_array.nr | 51 +- ...combined_sorted_transformed_value_array.nr | 149 +++--- .../get_combined_order_hints.nr | 111 ++-- .../assert_combined_transformed_array.nr | 55 +- .../src/utils/arrays/assert_deduped_array.nr | 23 +- ..._exposed_sorted_transformed_value_array.nr | 27 +- .../get_order_hints.nr | 50 +- .../src/utils/arrays/assert_sorted_array.nr | 5 +- .../assert_sorted_transformed_value_array.nr | 28 +- ...t_split_sorted_transformed_value_arrays.nr | 75 ++- .../get_split_order_hints.nr | 64 ++- .../assert_split_transformed_value_arrays.nr | 40 +- .../src/utils/arrays/get_sorted_result.nr | 20 +- .../src/utils/arrays/get_sorted_tuple.nr | 13 +- .../crates/types/src/utils/arrays/sort_by.nr | 18 +- .../types/src/utils/arrays/sort_by_counter.nr | 46 +- .../crates/types/src/utils/field.nr | 4 +- .../crates/types/src/utils/mod.nr | 12 +- .../crates/types/src/utils/reader.nr | 6 +- .../crates/types/src/utils/uint256.nr | 4 +- 408 files changed, 5429 insertions(+), 8529 deletions(-) diff --git a/noir-projects/aztec-nr/address-note/src/address_note.nr b/noir-projects/aztec-nr/address-note/src/address_note.nr index 62786dd4b0b..26cb3eb8840 100644 --- a/noir-projects/aztec-nr/address-note/src/address_note.nr +++ b/noir-projects/aztec-nr/address-note/src/address_note.nr @@ -1,13 +1,7 @@ use dep::aztec::{ - protocol_types::{ - address::AztecAddress, constants::GENERATOR_INDEX__NOTE_NULLIFIER, - hash::poseidon2_hash_with_separator, - }, - note::{ - note_header::NoteHeader, note_interface::NullifiableNote, - utils::compute_note_hash_for_nullify, - }, oracle::random::random, keys::getters::get_nsk_app, context::PrivateContext, - macros::notes::note, + protocol_types::{address::AztecAddress, constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + note::{note_header::NoteHeader, note_interface::NullifiableNote, utils::compute_note_hash_for_nullify}, + oracle::random::random, keys::getters::get_nsk_app, context::PrivateContext, macros::notes::note }; // docs:start:address_note_def @@ -24,15 +18,11 @@ pub struct AddressNote { impl NullifiableNote for AddressNote { - fn compute_nullifier( - self, - context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { let secret = context.request_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } @@ -41,7 +31,7 @@ impl NullifiableNote for AddressNote { let secret = get_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } } @@ -52,7 +42,9 @@ impl AddressNote { // malicious sender could use non-random values to make the note less private. But they already know the full // note pre-image anyway, and so the recipient already trusts them to not disclose this information. We can // therefore assume that the sender will cooperate in the random value generation. - let randomness = unsafe { random() }; + let randomness = unsafe { + random() + }; AddressNote { address, npk_m_hash, randomness, header: NoteHeader::empty() } } // docs:end:address_note_def diff --git a/noir-projects/aztec-nr/authwit/src/account.nr b/noir-projects/aztec-nr/authwit/src/account.nr index 55f0e7918d8..d9542e4526e 100644 --- a/noir-projects/aztec-nr/authwit/src/account.nr +++ b/noir-projects/aztec-nr/authwit/src/account.nr @@ -1,7 +1,7 @@ use dep::aztec::{ context::PrivateContext, protocol_types::constants::{GENERATOR_INDEX__COMBINED_PAYLOAD, GENERATOR_INDEX__TX_NULLIFIER}, - hash::poseidon2_hash_with_separator, + hash::poseidon2_hash_with_separator }; use crate::entrypoint::{app::AppPayload, fee::FeePayload}; @@ -40,7 +40,7 @@ impl AccountActions<&mut PrivateContext> { let combined_payload_hash = poseidon2_hash_with_separator( [app_payload.hash(), fee_payload.hash()], - GENERATOR_INDEX__COMBINED_PAYLOAD, + GENERATOR_INDEX__COMBINED_PAYLOAD ); assert(valid_fn(self.context, combined_payload_hash)); @@ -48,8 +48,7 @@ impl AccountActions<&mut PrivateContext> { self.context.end_setup(); app_payload.execute_calls(self.context); if cancellable { - let tx_nullifier = - poseidon2_hash_with_separator([app_payload.nonce], GENERATOR_INDEX__TX_NULLIFIER); + let tx_nullifier = poseidon2_hash_with_separator([app_payload.nonce], GENERATOR_INDEX__TX_NULLIFIER); self.context.push_nullifier(tx_nullifier); } } @@ -74,7 +73,7 @@ impl AccountActions<&mut PrivateContext> { self.context.msg_sender(), self.context.chain_id(), self.context.version(), - inner_hash, + inner_hash ); let valid_fn = self.is_valid_impl; assert(valid_fn(self.context, message_hash) == true, "Message not authorized by account"); diff --git a/noir-projects/aztec-nr/authwit/src/auth.nr b/noir-projects/aztec-nr/authwit/src/auth.nr index 88b8f3ea9b4..7918a6a1f86 100644 --- a/noir-projects/aztec-nr/authwit/src/auth.nr +++ b/noir-projects/aztec-nr/authwit/src/auth.nr @@ -1,9 +1,10 @@ use dep::aztec::protocol_types::{ abis::function_selector::FunctionSelector, address::AztecAddress, constants::{ - GENERATOR_INDEX__AUTHWIT_INNER, GENERATOR_INDEX__AUTHWIT_OUTER, - GENERATOR_INDEX__AUTHWIT_NULLIFIER, CANONICAL_AUTH_REGISTRY_ADDRESS, - }, hash::poseidon2_hash_with_separator, + GENERATOR_INDEX__AUTHWIT_INNER, GENERATOR_INDEX__AUTHWIT_OUTER, GENERATOR_INDEX__AUTHWIT_NULLIFIER, + CANONICAL_AUTH_REGISTRY_ADDRESS +}, + hash::poseidon2_hash_with_separator }; use dep::aztec::{context::{PrivateContext, PublicContext, gas::GasOpts}, hash::hash_args_array}; @@ -200,11 +201,13 @@ global IS_VALID_SELECTOR = 0x47dacd73; // 4 last bytes of poseidon2_hash_bytes(" */ // docs:start:assert_current_call_valid_authwit pub fn assert_current_call_valid_authwit(context: &mut PrivateContext, on_behalf_of: AztecAddress) { - let inner_hash = compute_inner_authwit_hash([ + let inner_hash = compute_inner_authwit_hash( + [ context.msg_sender().to_field(), context.selector().to_field(), - context.args_hash, - ]); + context.args_hash + ] + ); assert_inner_hash_valid_authwit(context, on_behalf_of, inner_hash); } // docs:end:assert_current_call_valid_authwit @@ -218,19 +221,15 @@ pub fn assert_current_call_valid_authwit(context: &mut PrivateContext, on_behalf * @param on_behalf_of The address that have authorized the current call * @param inner_hash The hash of the message to authorize */ -pub fn assert_inner_hash_valid_authwit( - context: &mut PrivateContext, - on_behalf_of: AztecAddress, - inner_hash: Field, -) { +pub fn assert_inner_hash_valid_authwit(context: &mut PrivateContext, on_behalf_of: AztecAddress, inner_hash: Field) { // We perform a static call here and not a standard one to ensure that the account contract cannot re-enter. - let result: Field = context - .static_call_private_function( - on_behalf_of, - comptime { FunctionSelector::from_signature("verify_private_authwit(Field)") }, - [inner_hash], - ) - .unpack_into(); + let result: Field = context.static_call_private_function( + on_behalf_of, + comptime { + FunctionSelector::from_signature("verify_private_authwit(Field)") + }, + [inner_hash] + ).unpack_into(); assert(result == IS_VALID_SELECTOR, "Message not authorized by account"); // Compute the nullifier, similar computation to the outer hash, but without the chain_id and version. // Those should already be handled in the verification, so we just need something to nullify, that allow same inner_hash for multiple actors. @@ -252,13 +251,15 @@ pub fn assert_inner_hash_valid_authwit( // docs:start:assert_current_call_valid_authwit_public pub fn assert_current_call_valid_authwit_public( context: &mut PublicContext, - on_behalf_of: AztecAddress, + on_behalf_of: AztecAddress ) { - let inner_hash = compute_inner_authwit_hash([ + let inner_hash = compute_inner_authwit_hash( + [ (*context).msg_sender().to_field(), (*context).selector().to_field(), - (*context).get_args_hash(), - ]); + (*context).get_args_hash() + ] + ); assert_inner_hash_valid_authwit_public(context, on_behalf_of, inner_hash); } // docs:end:assert_current_call_valid_authwit_public @@ -274,19 +275,15 @@ pub fn assert_current_call_valid_authwit_public( * * @param on_behalf_of The address that have authorized the `inner_hash` */ -pub fn assert_inner_hash_valid_authwit_public( - context: &mut PublicContext, - on_behalf_of: AztecAddress, - inner_hash: Field, -) { - let result: Field = context - .call_public_function( - CANONICAL_AUTH_REGISTRY_ADDRESS, - comptime { FunctionSelector::from_signature("consume((Field),Field)") }, - [on_behalf_of.to_field(), inner_hash].as_slice(), - GasOpts::default(), - ) - .deserialize_into(); +pub fn assert_inner_hash_valid_authwit_public(context: &mut PublicContext, on_behalf_of: AztecAddress, inner_hash: Field) { + let result: Field = context.call_public_function( + CANONICAL_AUTH_REGISTRY_ADDRESS, + comptime { + FunctionSelector::from_signature("consume((Field),Field)") + }, + [on_behalf_of.to_field(), inner_hash].as_slice(), + GasOpts::default() + ).deserialize_into(); assert(result == IS_VALID_SELECTOR, "Message not authorized by account"); } @@ -311,11 +308,10 @@ pub fn compute_authwit_message_hash_from_call( chain_id: Field, version: Field, selector: FunctionSelector, - args: [Field; N], + args: [Field; N] ) -> Field { let args_hash = hash_args_array(args); - let inner_hash = - compute_inner_authwit_hash([caller.to_field(), selector.to_field(), args_hash]); + let inner_hash = compute_inner_authwit_hash([caller.to_field(), selector.to_field(), args_hash]); compute_authwit_message_hash(consumer, chain_id, version, inner_hash) } // docs:end:compute_authwit_message_hash_from_call @@ -343,7 +339,7 @@ pub fn compute_inner_authwit_hash(args: [Field; N]) -> Field { pub fn compute_authwit_nullifier(on_behalf_of: AztecAddress, inner_hash: Field) -> Field { poseidon2_hash_with_separator( [on_behalf_of.to_field(), inner_hash], - GENERATOR_INDEX__AUTHWIT_NULLIFIER, + GENERATOR_INDEX__AUTHWIT_NULLIFIER ) } @@ -355,15 +351,10 @@ pub fn compute_authwit_nullifier(on_behalf_of: AztecAddress, inner_hash: Field) * @param version The version of the chain that the message is being consumed on * @param inner_hash The hash of the "inner" message that is being consumed */ -pub fn compute_authwit_message_hash( - consumer: AztecAddress, - chain_id: Field, - version: Field, - inner_hash: Field, -) -> Field { +pub fn compute_authwit_message_hash(consumer: AztecAddress, chain_id: Field, version: Field, inner_hash: Field) -> Field { poseidon2_hash_with_separator( [consumer.to_field(), chain_id, version, inner_hash], - GENERATOR_INDEX__AUTHWIT_OUTER, + GENERATOR_INDEX__AUTHWIT_OUTER ) } @@ -376,14 +367,14 @@ pub fn compute_authwit_message_hash( * @param authorize True if the message should be authorized, false if it should be revoked */ pub fn set_authorized(context: &mut PublicContext, message_hash: Field, authorize: bool) { - context - .call_public_function( - CANONICAL_AUTH_REGISTRY_ADDRESS, - comptime { FunctionSelector::from_signature("set_authorized(Field,bool)") }, - [message_hash, authorize as Field].as_slice(), - GasOpts::default(), - ) - .assert_empty(); + context.call_public_function( + CANONICAL_AUTH_REGISTRY_ADDRESS, + comptime { + FunctionSelector::from_signature("set_authorized(Field,bool)") + }, + [message_hash, authorize as Field].as_slice(), + GasOpts::default() + ).assert_empty(); } /** @@ -394,12 +385,12 @@ pub fn set_authorized(context: &mut PublicContext, message_hash: Field, authoriz * @param reject True if all authwits should be rejected, false otherwise */ pub fn set_reject_all(context: &mut PublicContext, reject: bool) { - context - .call_public_function( - CANONICAL_AUTH_REGISTRY_ADDRESS, - comptime { FunctionSelector::from_signature("set_reject_all(bool)") }, - [context.this_address().to_field(), reject as Field].as_slice(), - GasOpts::default(), - ) - .assert_empty(); + context.call_public_function( + CANONICAL_AUTH_REGISTRY_ADDRESS, + comptime { + FunctionSelector::from_signature("set_reject_all(bool)") + }, + [context.this_address().to_field(), reject as Field].as_slice(), + GasOpts::default() + ).assert_empty(); } diff --git a/noir-projects/aztec-nr/authwit/src/cheatcodes.nr b/noir-projects/aztec-nr/authwit/src/cheatcodes.nr index a61c1f24d5c..4dd029dd42f 100644 --- a/noir-projects/aztec-nr/authwit/src/cheatcodes.nr +++ b/noir-projects/aztec-nr/authwit/src/cheatcodes.nr @@ -1,28 +1,21 @@ use dep::aztec::{ protocol_types::address::AztecAddress, - context::{public_context::PublicContext, call_interfaces::CallInterface}, - test::helpers::cheatcodes, oracle::execution::{get_block_number, get_contract_address}, - hash::hash_args, + context::{public_context::PublicContext, call_interfaces::CallInterface}, test::helpers::cheatcodes, + oracle::execution::{get_block_number, get_contract_address}, hash::hash_args }; use crate::auth::{compute_inner_authwit_hash, compute_authwit_message_hash, set_authorized}; -pub fn add_private_authwit_from_call_interface( - on_behalf_of: AztecAddress, - caller: AztecAddress, - call_interface: C, -) +pub fn add_private_authwit_from_call_interface(on_behalf_of: AztecAddress, caller: AztecAddress, call_interface: C) where - C: CallInterface, -{ + C: CallInterface, { let target = call_interface.get_contract_address(); let inputs = cheatcodes::get_private_context_inputs(get_block_number()); let chain_id = inputs.tx_context.chain_id; let version = inputs.tx_context.version; let args_hash = hash_args(call_interface.get_args()); let selector = call_interface.get_selector(); - let inner_hash = - compute_inner_authwit_hash([caller.to_field(), selector.to_field(), args_hash]); + let inner_hash = compute_inner_authwit_hash([caller.to_field(), selector.to_field(), args_hash]); let message_hash = compute_authwit_message_hash(target, chain_id, version, inner_hash); cheatcodes::add_authwit(on_behalf_of, message_hash); } @@ -30,11 +23,10 @@ where pub fn add_public_authwit_from_call_interface( on_behalf_of: AztecAddress, caller: AztecAddress, - call_interface: C, + call_interface: C ) where - C: CallInterface, -{ + C: CallInterface, { let current_contract = get_contract_address(); cheatcodes::set_contract_address(on_behalf_of); let target = call_interface.get_contract_address(); @@ -43,8 +35,7 @@ where let version = inputs.tx_context.version; let args_hash = hash_args(call_interface.get_args()); let selector = call_interface.get_selector(); - let inner_hash = - compute_inner_authwit_hash([caller.to_field(), selector.to_field(), args_hash]); + let inner_hash = compute_inner_authwit_hash([caller.to_field(), selector.to_field(), args_hash]); let message_hash = compute_authwit_message_hash(target, chain_id, version, inner_hash); let mut context = PublicContext::new(|| { panic(f"Provide args hash manually") }); context.args_hash = Option::some(args_hash); diff --git a/noir-projects/aztec-nr/authwit/src/entrypoint/app.nr b/noir-projects/aztec-nr/authwit/src/entrypoint/app.nr index 1aac89e567f..7bccd4425aa 100644 --- a/noir-projects/aztec-nr/authwit/src/entrypoint/app.nr +++ b/noir-projects/aztec-nr/authwit/src/entrypoint/app.nr @@ -1,7 +1,7 @@ use dep::aztec::prelude::PrivateContext; use dep::aztec::protocol_types::{ constants::GENERATOR_INDEX__SIGNATURE_PAYLOAD, hash::poseidon2_hash_with_separator, - traits::{Hash, Serialize}, + traits::{Hash, Serialize} }; use crate::entrypoint::function_call::FunctionCall; @@ -62,14 +62,14 @@ impl AppPayload { call.target_address, call.function_selector, call.args_hash, - call.is_static, + call.is_static ); } else { let _result = context.call_private_function_with_packed_args( call.target_address, call.function_selector, call.args_hash, - call.is_static, + call.is_static ); } } diff --git a/noir-projects/aztec-nr/authwit/src/entrypoint/fee.nr b/noir-projects/aztec-nr/authwit/src/entrypoint/fee.nr index 7033b8e97d3..3a29e8b12e6 100644 --- a/noir-projects/aztec-nr/authwit/src/entrypoint/fee.nr +++ b/noir-projects/aztec-nr/authwit/src/entrypoint/fee.nr @@ -1,7 +1,7 @@ use dep::aztec::prelude::PrivateContext; use dep::aztec::protocol_types::{ constants::GENERATOR_INDEX__FEE_PAYLOAD, hash::poseidon2_hash_with_separator, - traits::{Hash, Serialize}, + traits::{Hash, Serialize} }; use crate::entrypoint::function_call::FunctionCall; @@ -61,14 +61,14 @@ impl FeePayload { call.target_address, call.function_selector, call.args_hash, - call.is_static, + call.is_static ); } else { let _result = context.call_private_function_with_packed_args( call.target_address, call.function_selector, call.args_hash, - call.is_static, + call.is_static ); } } diff --git a/noir-projects/aztec-nr/authwit/src/entrypoint/function_call.nr b/noir-projects/aztec-nr/authwit/src/entrypoint/function_call.nr index d146c8a488e..daa2b1164bb 100644 --- a/noir-projects/aztec-nr/authwit/src/entrypoint/function_call.nr +++ b/noir-projects/aztec-nr/authwit/src/entrypoint/function_call.nr @@ -1,6 +1,4 @@ -use dep::aztec::protocol_types::{ - abis::function_selector::FunctionSelector, address::AztecAddress, traits::Serialize, -}; +use dep::aztec::protocol_types::{abis::function_selector::FunctionSelector, address::AztecAddress, traits::Serialize}; // 1 (ARGS_HASH) + 1 (FUNCTION_SELECTOR) + 1 (TARGET_ADDRESS) + 1 (IS_PUBLIC) + 1 (IS_STATIC) global FUNCTION_CALL_SIZE: u32 = 5; @@ -22,7 +20,7 @@ impl Serialize for FunctionCall { self.function_selector.to_field(), self.target_address.to_field(), self.is_public as Field, - self.is_static as Field, + self.is_static as Field ] } } diff --git a/noir-projects/aztec-nr/aztec/src/context/call_interfaces.nr b/noir-projects/aztec-nr/aztec/src/context/call_interfaces.nr index c888c7b490a..097df33474d 100644 --- a/noir-projects/aztec-nr/aztec/src/context/call_interfaces.nr +++ b/noir-projects/aztec-nr/aztec/src/context/call_interfaces.nr @@ -1,10 +1,8 @@ -use dep::protocol_types::{ - abis::function_selector::FunctionSelector, address::AztecAddress, traits::Deserialize, -}; +use dep::protocol_types::{abis::function_selector::FunctionSelector, address::AztecAddress, traits::Deserialize}; use crate::context::{ private_context::PrivateContext, public_context::PublicContext, gas::GasOpts, - inputs::PrivateContextInputs, + inputs::PrivateContextInputs }; use crate::oracle::arguments::pack_arguments; @@ -43,32 +41,26 @@ pub struct PrivateCallInterface { } impl PrivateCallInterface { - pub fn call(self, context: &mut PrivateContext) -> T + pub fn call( + self, + context: &mut PrivateContext + ) -> T where - T: Deserialize, - { + T: Deserialize, { pack_arguments(self.args); - let returns = context.call_private_function_with_packed_args( - self.target_contract, - self.selector, - self.args_hash, - false, - ); + let returns = context.call_private_function_with_packed_args(self.target_contract, self.selector, self.args_hash, false); let unpacked: T = returns.unpack_into(); unpacked } - pub fn view(self, context: &mut PrivateContext) -> T + pub fn view( + self, + context: &mut PrivateContext + ) -> T where - T: Deserialize, - { + T: Deserialize, { pack_arguments(self.args); - let returns = context.call_private_function_with_packed_args( - self.target_contract, - self.selector, - self.args_hash, - true, - ); + let returns = context.call_private_function_with_packed_args(self.target_contract, self.selector, self.args_hash, true); returns.unpack_into() } } @@ -88,26 +80,12 @@ pub struct PrivateVoidCallInterface { impl PrivateVoidCallInterface { pub fn call(self, context: &mut PrivateContext) { pack_arguments(self.args); - context - .call_private_function_with_packed_args( - self.target_contract, - self.selector, - self.args_hash, - false, - ) - .assert_empty(); + context.call_private_function_with_packed_args(self.target_contract, self.selector, self.args_hash, false).assert_empty(); } pub fn view(self, context: &mut PrivateContext) { pack_arguments(self.args); - context - .call_private_function_with_packed_args( - self.target_contract, - self.selector, - self.args_hash, - true, - ) - .assert_empty(); + context.call_private_function_with_packed_args(self.target_contract, self.selector, self.args_hash, true).assert_empty(); } } @@ -124,17 +102,14 @@ pub struct PrivateStaticCallInterface { } impl PrivateStaticCallInterface { - pub fn view(self, context: &mut PrivateContext) -> T + pub fn view( + self, + context: &mut PrivateContext + ) -> T where - T: Deserialize, - { + T: Deserialize, { pack_arguments(self.args); - let returns = context.call_private_function_with_packed_args( - self.target_contract, - self.selector, - self.args_hash, - true, - ); + let returns = context.call_private_function_with_packed_args(self.target_contract, self.selector, self.args_hash, true); returns.unpack_into() } } @@ -154,14 +129,7 @@ pub struct PrivateStaticVoidCallInterface { impl PrivateStaticVoidCallInterface { pub fn view(self, context: &mut PrivateContext) { pack_arguments(self.args); - context - .call_private_function_with_packed_args( - self.target_contract, - self.selector, - self.args_hash, - true, - ) - .assert_empty(); + context.call_private_function_with_packed_args(self.target_contract, self.selector, self.args_hash, true).assert_empty(); } } @@ -183,29 +151,23 @@ impl PublicCallInterface { self } - pub fn call(self, context: &mut PublicContext) -> T + pub fn call( + self, + context: &mut PublicContext + ) -> T where - T: Deserialize, - { - let returns = context.call_public_function( - self.target_contract, - self.selector, - self.args, - self.gas_opts, - ); + T: Deserialize, { + let returns = context.call_public_function(self.target_contract, self.selector, self.args, self.gas_opts); returns.deserialize_into() } - pub fn view(self, context: &mut PublicContext) -> T + pub fn view( + self, + context: &mut PublicContext + ) -> T where - T: Deserialize, - { - let returns = context.static_call_public_function( - self.target_contract, - self.selector, - self.args, - self.gas_opts, - ); + T: Deserialize, { + let returns = context.static_call_public_function(self.target_contract, self.selector, self.args, self.gas_opts); returns.deserialize_into() } @@ -217,7 +179,7 @@ impl PublicCallInterface { self.selector, args_hash, /*static=*/ - false, + false ) } @@ -229,7 +191,7 @@ impl PublicCallInterface { self.selector, args_hash, /*static=*/ - true, + true ) } } @@ -253,22 +215,12 @@ impl PublicVoidCallInterface { } pub fn call(self, context: &mut PublicContext) { - let returns = context.call_public_function( - self.target_contract, - self.selector, - self.args, - self.gas_opts, - ); + let returns = context.call_public_function(self.target_contract, self.selector, self.args, self.gas_opts); returns.assert_empty() } pub fn view(self, context: &mut PublicContext) { - let returns = context.static_call_public_function( - self.target_contract, - self.selector, - self.args, - self.gas_opts, - ); + let returns = context.static_call_public_function(self.target_contract, self.selector, self.args, self.gas_opts); returns.assert_empty() } @@ -280,7 +232,7 @@ impl PublicVoidCallInterface { self.selector, args_hash, /*static=*/ - false, + false ) } @@ -292,7 +244,7 @@ impl PublicVoidCallInterface { self.selector, args_hash, /*static=*/ - true, + true ) } } @@ -315,16 +267,13 @@ impl PublicStaticCallInterface { self } - pub fn view(self, context: &mut PublicContext) -> T + pub fn view( + self, + context: &mut PublicContext + ) -> T where - T: Deserialize, - { - let returns = context.static_call_public_function( - self.target_contract, - self.selector, - self.args, - self.gas_opts, - ); + T: Deserialize, { + let returns = context.static_call_public_function(self.target_contract, self.selector, self.args, self.gas_opts); let unpacked: T = returns.deserialize_into(); unpacked } @@ -337,7 +286,7 @@ impl PublicStaticCallInterface { self.selector, args_hash, /*static=*/ - true, + true ) } } @@ -361,12 +310,7 @@ impl PublicStaticVoidCallInterface { } pub fn view(self, context: &mut PublicContext) { - let returns = context.static_call_public_function( - self.target_contract, - self.selector, - self.args, - self.gas_opts, - ); + let returns = context.static_call_public_function(self.target_contract, self.selector, self.args, self.gas_opts); returns.assert_empty() } @@ -378,7 +322,7 @@ impl PublicStaticVoidCallInterface { self.selector, args_hash, /*static=*/ - true, + true ) } } diff --git a/noir-projects/aztec-nr/aztec/src/context/inputs/private_context_inputs.nr b/noir-projects/aztec-nr/aztec/src/context/inputs/private_context_inputs.nr index d41648e4983..da24e14ad48 100644 --- a/noir-projects/aztec-nr/aztec/src/context/inputs/private_context_inputs.nr +++ b/noir-projects/aztec-nr/aztec/src/context/inputs/private_context_inputs.nr @@ -1,7 +1,4 @@ -use dep::protocol_types::{ - transaction::tx_context::TxContext, abis::call_context::CallContext, header::Header, - traits::Empty, -}; +use dep::protocol_types::{transaction::tx_context::TxContext, abis::call_context::CallContext, header::Header, traits::Empty}; // PrivateContextInputs are expected to be provided to each private function // docs:start:private-context-inputs @@ -19,7 +16,7 @@ impl Empty for PrivateContextInputs { call_context: CallContext::empty(), historical_header: Header::empty(), tx_context: TxContext::empty(), - start_side_effect_counter: 0 as u32, + start_side_effect_counter: 0 as u32 } } } diff --git a/noir-projects/aztec-nr/aztec/src/context/mod.nr b/noir-projects/aztec-nr/aztec/src/context/mod.nr index f4cf63fd925..4747f2d0ffb 100644 --- a/noir-projects/aztec-nr/aztec/src/context/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/context/mod.nr @@ -10,9 +10,9 @@ mod call_interfaces; mod gas; pub use call_interfaces::{ - PrivateCallInterface, PrivateStaticCallInterface, PublicCallInterface, - PublicStaticCallInterface, PrivateVoidCallInterface, PrivateStaticVoidCallInterface, - PublicVoidCallInterface, PublicStaticVoidCallInterface, + PrivateCallInterface, PrivateStaticCallInterface, PublicCallInterface, PublicStaticCallInterface, + PrivateVoidCallInterface, PrivateStaticVoidCallInterface, PublicVoidCallInterface, + PublicStaticVoidCallInterface }; pub use private_context::PrivateContext; pub use packed_returns::PackedReturns; diff --git a/noir-projects/aztec-nr/aztec/src/context/packed_returns.nr b/noir-projects/aztec-nr/aztec/src/context/packed_returns.nr index ebb86a9621f..9fd3bc4a8ea 100644 --- a/noir-projects/aztec-nr/aztec/src/context/packed_returns.nr +++ b/noir-projects/aztec-nr/aztec/src/context/packed_returns.nr @@ -21,15 +21,16 @@ impl PackedReturns { pub fn unpack(self) -> [Field; N] { // We verify that the value returned by `unpack_returns` is the preimage of `packed_returns`, fully constraining // it. - let unpacked: [Field; N] = unsafe { unpack_returns(self.packed_returns) }; + let unpacked: [Field; N] = unsafe { + unpack_returns(self.packed_returns) + }; assert_eq(self.packed_returns, hash_args_array(unpacked)); unpacked } pub fn unpack_into(self) -> T where - T: Deserialize, - { + T: Deserialize, { let unpacked: [Field; N] = self.unpack(); Deserialize::deserialize(unpacked) } diff --git a/noir-projects/aztec-nr/aztec/src/context/private_context.nr b/noir-projects/aztec-nr/aztec/src/context/private_context.nr index 049a828acd2..fe102fd3d33 100644 --- a/noir-projects/aztec-nr/aztec/src/context/private_context.nr +++ b/noir-projects/aztec-nr/aztec/src/context/private_context.nr @@ -3,32 +3,32 @@ use crate::{ messaging::process_l1_to_l2_message, hash::{hash_args_array, ArgsHasher}, keys::constants::{NULLIFIER_INDEX, OUTGOING_INDEX, NUM_KEY_TYPES, sk_generators}, oracle::{ - key_validation_request::get_key_validation_request, arguments, returns::pack_returns, - call_private_function::call_private_function_internal, header::get_header_at, - logs::{emit_encrypted_note_log, emit_encrypted_event_log}, - enqueue_public_function_call::{ - enqueue_public_function_call_internal, notify_set_min_revertible_side_effect_counter, - set_public_teardown_function_call_internal, - }, - }, + key_validation_request::get_key_validation_request, arguments, returns::pack_returns, + call_private_function::call_private_function_internal, header::get_header_at, + logs::{emit_encrypted_note_log, emit_encrypted_event_log}, + enqueue_public_function_call::{ + enqueue_public_function_call_internal, notify_set_min_revertible_side_effect_counter, + set_public_teardown_function_call_internal +} +} }; use dep::protocol_types::{ abis::{ - call_context::CallContext, function_selector::FunctionSelector, - max_block_number::MaxBlockNumber, - validation_requests::{KeyValidationRequest, KeyValidationRequestAndGenerator}, - private_call_request::PrivateCallRequest, - private_circuit_public_inputs::PrivateCircuitPublicInputs, - public_call_request::PublicCallRequest, read_request::ReadRequest, note_hash::NoteHash, - nullifier::Nullifier, log_hash::{LogHash, NoteLogHash, EncryptedLogHash}, - }, address::{AztecAddress, EthAddress}, + call_context::CallContext, function_selector::FunctionSelector, max_block_number::MaxBlockNumber, + validation_requests::{KeyValidationRequest, KeyValidationRequestAndGenerator}, + private_call_request::PrivateCallRequest, private_circuit_public_inputs::PrivateCircuitPublicInputs, + public_call_request::PublicCallRequest, read_request::ReadRequest, note_hash::NoteHash, + nullifier::Nullifier, log_hash::{LogHash, NoteLogHash, EncryptedLogHash} +}, + address::{AztecAddress, EthAddress}, constants::{ - MAX_NOTE_HASHES_PER_CALL, MAX_L2_TO_L1_MSGS_PER_CALL, MAX_NULLIFIERS_PER_CALL, - MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL, MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, - MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, MAX_NULLIFIER_READ_REQUESTS_PER_CALL, - MAX_KEY_VALIDATION_REQUESTS_PER_CALL, MAX_ENCRYPTED_LOGS_PER_CALL, - MAX_UNENCRYPTED_LOGS_PER_CALL, MAX_NOTE_ENCRYPTED_LOGS_PER_CALL, PUBLIC_DISPATCH_SELECTOR, - }, header::Header, messaging::l2_to_l1_message::L2ToL1Message, traits::Empty, + MAX_NOTE_HASHES_PER_CALL, MAX_L2_TO_L1_MSGS_PER_CALL, MAX_NULLIFIERS_PER_CALL, + MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL, MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, + MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, MAX_NULLIFIER_READ_REQUESTS_PER_CALL, + MAX_KEY_VALIDATION_REQUESTS_PER_CALL, MAX_ENCRYPTED_LOGS_PER_CALL, MAX_UNENCRYPTED_LOGS_PER_CALL, + MAX_NOTE_ENCRYPTED_LOGS_PER_CALL, PUBLIC_DISPATCH_SELECTOR +}, + header::Header, messaging::l2_to_l1_message::L2ToL1Message, traits::Empty }; // When finished, one can call .finish() to convert back to the abi @@ -94,7 +94,7 @@ impl PrivateContext { note_encrypted_logs_hashes: BoundedVec::new(), encrypted_logs_hashes: BoundedVec::new(), unencrypted_logs_hashes: BoundedVec::new(), - last_key_validation_requests: [Option::none(); NUM_KEY_TYPES], + last_key_validation_requests: [Option::none(); NUM_KEY_TYPES] } } @@ -127,19 +127,11 @@ impl PrivateContext { } fn push_nullifier(&mut self, nullifier: Field) { - self.nullifiers.push( - Nullifier { value: nullifier, note_hash: 0, counter: self.next_counter() }, - ); + self.nullifiers.push(Nullifier { value: nullifier, note_hash: 0, counter: self.next_counter() }); } fn push_nullifier_for_note_hash(&mut self, nullifier: Field, nullified_note_hash: Field) { - self.nullifiers.push( - Nullifier { - value: nullifier, - note_hash: nullified_note_hash, - counter: self.next_counter(), - }, - ); + self.nullifiers.push(Nullifier { value: nullifier, note_hash: nullified_note_hash, counter: self.next_counter() }); } // Returns the header of a block whose state is used during private execution (not the block the transaction is @@ -169,9 +161,7 @@ impl PrivateContext { max_block_number: self.max_block_number, note_hash_read_requests: self.note_hash_read_requests.storage, nullifier_read_requests: self.nullifier_read_requests.storage, - key_validation_requests_and_generators: self - .key_validation_requests_and_generators - .storage, + key_validation_requests_and_generators: self.key_validation_requests_and_generators.storage, note_hashes: self.note_hashes.storage, nullifiers: self.nullifiers.storage, private_call_requests: self.private_call_requests.storage, @@ -184,15 +174,12 @@ impl PrivateContext { encrypted_logs_hashes: self.encrypted_logs_hashes.storage, unencrypted_logs_hashes: self.unencrypted_logs_hashes.storage, historical_header: self.historical_header, - tx_context: self.inputs.tx_context, + tx_context: self.inputs.tx_context } } pub fn set_as_fee_payer(&mut self) { - dep::protocol_types::debug_log::debug_log_format( - "Setting {0} as fee payer", - [self.this_address().to_field()], - ); + dep::protocol_types::debug_log::debug_log_format("Setting {0} as fee payer", [self.this_address().to_field()]); self.is_fee_payer = true; } @@ -231,8 +218,7 @@ impl PrivateContext { } fn request_sk_app(&mut self, pk_m_hash: Field, key_index: Field) -> Field { - let cached_request = - self.last_key_validation_requests[key_index].unwrap_or(KeyValidationRequest::empty()); + let cached_request = self.last_key_validation_requests[key_index].unwrap_or(KeyValidationRequest::empty()); if cached_request.pk_m.hash() == pk_m_hash { // We get a match so the cached request is the latest one @@ -241,10 +227,7 @@ impl PrivateContext { // We didn't get a match meaning the cached result is stale. We fetch new values from oracle and instruct // protocol circuits to validate them by storing the validation request in context. let request = get_key_validation_request(pk_m_hash, key_index); - let request_and_generator = KeyValidationRequestAndGenerator { - request, - sk_app_generator: sk_generators[key_index], - }; + let request_and_generator = KeyValidationRequestAndGenerator { request, sk_app_generator: sk_generators[key_index] }; // We constrain that the pk_m_hash matches the one in the request (otherwise we could get an arbitrary // valid key request and not the one corresponding to pk_m_hash). assert(request.pk_m.hash() == pk_m_hash); @@ -272,7 +255,7 @@ impl PrivateContext { self.chain_id(), self.version(), content, - secret, + secret ); // Push nullifier (and the "commitment" corresponding to this can be "empty") @@ -286,7 +269,7 @@ impl PrivateContext { &mut self, randomness: Field, log: [u8; M], - log_hash: Field, + log_hash: Field ) { let counter = self.next_counter(); let contract_address = self.this_address(); @@ -297,12 +280,7 @@ impl PrivateContext { emit_encrypted_event_log(contract_address, randomness, log, counter); } - pub fn emit_raw_note_log( - &mut self, - note_hash_counter: u32, - log: [u8; M], - log_hash: Field, - ) { + pub fn emit_raw_note_log(&mut self, note_hash_counter: u32, log: [u8; M], log_hash: Field) { let counter = self.next_counter(); let len = log.len() as Field + 4; let side_effect = NoteLogHash { value: log_hash, counter, length: len, note_hash_counter }; @@ -315,38 +293,28 @@ impl PrivateContext { &mut self, contract_address: AztecAddress, function_selector: FunctionSelector, - args: [Field; ARGS_COUNT], + args: [Field; ARGS_COUNT] ) -> PackedReturns { let args_hash = hash_args_array(args); arguments::pack_arguments_array(args); - self.call_private_function_with_packed_args( - contract_address, - function_selector, - args_hash, - false, - ) + self.call_private_function_with_packed_args(contract_address, function_selector, args_hash, false) } pub fn static_call_private_function( &mut self, contract_address: AztecAddress, function_selector: FunctionSelector, - args: [Field; ARGS_COUNT], + args: [Field; ARGS_COUNT] ) -> PackedReturns { let args_hash = hash_args_array(args); arguments::pack_arguments_array(args); - self.call_private_function_with_packed_args( - contract_address, - function_selector, - args_hash, - true, - ) + self.call_private_function_with_packed_args(contract_address, function_selector, args_hash, true) } pub fn call_private_function_no_args( &mut self, contract_address: AztecAddress, - function_selector: FunctionSelector, + function_selector: FunctionSelector ) -> PackedReturns { self.call_private_function_with_packed_args(contract_address, function_selector, 0, false) } @@ -354,7 +322,7 @@ impl PrivateContext { pub fn static_call_private_function_no_args( &mut self, contract_address: AztecAddress, - function_selector: FunctionSelector, + function_selector: FunctionSelector ) -> PackedReturns { self.call_private_function_with_packed_args(contract_address, function_selector, 0, true) } @@ -364,7 +332,7 @@ impl PrivateContext { contract_address: AztecAddress, function_selector: FunctionSelector, args_hash: Field, - is_static_call: bool, + is_static_call: bool ) -> PackedReturns { let mut is_static_call = is_static_call | self.inputs.call_context.is_static_call; let start_side_effect_counter = self.side_effect_counter; @@ -373,7 +341,7 @@ impl PrivateContext { function_selector, args_hash, start_side_effect_counter, - is_static_call, + is_static_call ); self.side_effect_counter = end_side_effect_counter + 1; @@ -389,21 +357,10 @@ impl PrivateContext { // > self.min_revertible_side_effect_counter { // self.min_revertible_side_effect_counter = item.public_inputs.min_revertible_side_effect_counter; // } - let call_context = CallContext { - msg_sender: self.this_address(), - contract_address, - function_selector, - is_static_call, - }; + let call_context = CallContext { msg_sender: self.this_address(), contract_address, function_selector, is_static_call }; self.private_call_requests.push( - PrivateCallRequest { - call_context, - args_hash, - returns_hash, - start_side_effect_counter, - end_side_effect_counter, - }, + PrivateCallRequest { call_context, args_hash, returns_hash, start_side_effect_counter, end_side_effect_counter } ); PackedReturns::new(returns_hash) @@ -413,38 +370,28 @@ impl PrivateContext { &mut self, contract_address: AztecAddress, function_selector: FunctionSelector, - args: [Field; ARGS_COUNT], + args: [Field; ARGS_COUNT] ) { let args_hash = hash_args_array(args); arguments::pack_arguments_array(args); - self.call_public_function_with_packed_args( - contract_address, - function_selector, - args_hash, - false, - ) + self.call_public_function_with_packed_args(contract_address, function_selector, args_hash, false) } pub fn static_call_public_function( &mut self, contract_address: AztecAddress, function_selector: FunctionSelector, - args: [Field; ARGS_COUNT], + args: [Field; ARGS_COUNT] ) { let args_hash = hash_args_array(args); arguments::pack_arguments_array(args); - self.call_public_function_with_packed_args( - contract_address, - function_selector, - args_hash, - true, - ) + self.call_public_function_with_packed_args(contract_address, function_selector, args_hash, true) } pub fn call_public_function_no_args( &mut self, contract_address: AztecAddress, - function_selector: FunctionSelector, + function_selector: FunctionSelector ) { self.call_public_function_with_packed_args(contract_address, function_selector, 0, false) } @@ -452,7 +399,7 @@ impl PrivateContext { pub fn static_call_public_function_no_args( &mut self, contract_address: AztecAddress, - function_selector: FunctionSelector, + function_selector: FunctionSelector ) { self.call_public_function_with_packed_args(contract_address, function_selector, 0, true) } @@ -462,7 +409,7 @@ impl PrivateContext { contract_address: AztecAddress, function_selector: FunctionSelector, args_hash: Field, - is_static_call: bool, + is_static_call: bool ) { let counter = self.next_counter(); @@ -478,17 +425,14 @@ impl PrivateContext { function_selector, args_hash, counter, - is_static_call, + is_static_call ); // Public calls are rerouted through the dispatch function. - let function_selector = comptime { FunctionSelector::from_field(PUBLIC_DISPATCH_SELECTOR) }; - let call_context = CallContext { - msg_sender: self.this_address(), - contract_address, - function_selector, - is_static_call, + let function_selector = comptime { + FunctionSelector::from_field(PUBLIC_DISPATCH_SELECTOR) }; + let call_context = CallContext { msg_sender: self.this_address(), contract_address, function_selector, is_static_call }; let call_request = PublicCallRequest { call_context, args_hash, counter }; self.public_call_requests.push(call_request); @@ -498,16 +442,11 @@ impl PrivateContext { &mut self, contract_address: AztecAddress, function_selector: FunctionSelector, - args: [Field; ARGS_COUNT], + args: [Field; ARGS_COUNT] ) { let args_hash = hash_args_array(args); arguments::pack_arguments_array(args); - self.set_public_teardown_function_with_packed_args( - contract_address, - function_selector, - args_hash, - false, - ) + self.set_public_teardown_function_with_packed_args(contract_address, function_selector, args_hash, false) } pub fn set_public_teardown_function_with_packed_args( @@ -515,7 +454,7 @@ impl PrivateContext { contract_address: AztecAddress, function_selector: FunctionSelector, args_hash: Field, - is_static_call: bool, + is_static_call: bool ) { let counter = self.next_counter(); @@ -531,16 +470,13 @@ impl PrivateContext { function_selector, args_hash, counter, - is_static_call, + is_static_call ); - let function_selector = comptime { FunctionSelector::from_field(PUBLIC_DISPATCH_SELECTOR) }; - let call_context = CallContext { - msg_sender: self.this_address(), - contract_address, - function_selector, - is_static_call, + let function_selector = comptime { + FunctionSelector::from_field(PUBLIC_DISPATCH_SELECTOR) }; + let call_context = CallContext { msg_sender: self.this_address(), contract_address, function_selector, is_static_call }; self.public_teardown_call_request = PublicCallRequest { call_context, args_hash, counter }; } @@ -575,7 +511,7 @@ impl Empty for PrivateContext { note_encrypted_logs_hashes: BoundedVec::new(), encrypted_logs_hashes: BoundedVec::new(), unencrypted_logs_hashes: BoundedVec::new(), - last_key_validation_requests: [Option::none(); NUM_KEY_TYPES], + last_key_validation_requests: [Option::none(); NUM_KEY_TYPES] } } } diff --git a/noir-projects/aztec-nr/aztec/src/context/public_context.nr b/noir-projects/aztec-nr/aztec/src/context/public_context.nr index 8c09a49c8c0..9945faf9c49 100644 --- a/noir-projects/aztec-nr/aztec/src/context/public_context.nr +++ b/noir-projects/aztec-nr/aztec/src/context/public_context.nr @@ -15,10 +15,12 @@ impl PublicContext { PublicContext { args_hash: Option::none(), compute_args_hash } } - pub fn emit_unencrypted_log(_self: &mut Self, log: T) + pub fn emit_unencrypted_log( + _self: &mut Self, + log: T + ) where - T: Serialize, - { + T: Serialize, { emit_unencrypted_log(Serialize::serialize(log).as_slice()); } @@ -39,7 +41,7 @@ impl PublicContext { content: Field, secret: Field, sender: EthAddress, - leaf_index: Field, + leaf_index: Field ) { let secret_hash = compute_secret_hash(secret); let message_hash = compute_message_hash( @@ -49,17 +51,15 @@ impl PublicContext { self.this_address(), self.version(), content, - secret_hash, + secret_hash ); let nullifier = compute_message_nullifier(message_hash, secret, leaf_index); assert( - !self.nullifier_exists(nullifier, self.this_address()), - "L1-to-L2 message is already nullified", + !self.nullifier_exists(nullifier, self.this_address()), "L1-to-L2 message is already nullified" ); assert( - self.l1_to_l2_msg_exists(message_hash, leaf_index), - "Tried to consume nonexistent L1-to-L2 message", + self.l1_to_l2_msg_exists(message_hash, leaf_index), "Tried to consume nonexistent L1-to-L2 message" ); self.push_nullifier(nullifier); @@ -74,14 +74,14 @@ impl PublicContext { contract_address: AztecAddress, function_selector: FunctionSelector, args: [Field], - gas_opts: GasOpts, + gas_opts: GasOpts ) -> FunctionReturns { let args = &[function_selector.to_field()].append(args); let results = call( gas_for_call(gas_opts), contract_address, args, - PUBLIC_DISPATCH_SELECTOR, + PUBLIC_DISPATCH_SELECTOR ); let data_to_return: [Field; RETURNS_COUNT] = results.0; let success: u8 = results.1; @@ -95,14 +95,14 @@ impl PublicContext { contract_address: AztecAddress, function_selector: FunctionSelector, args: [Field], - gas_opts: GasOpts, + gas_opts: GasOpts ) -> FunctionReturns { let args = &[function_selector.to_field()].append(args); let (data_to_return, success): ([Field; RETURNS_COUNT], u8) = call_static( gas_for_call(gas_opts), contract_address, args, - PUBLIC_DISPATCH_SELECTOR, + PUBLIC_DISPATCH_SELECTOR ); assert(success == 1, "Nested static call failed!"); @@ -175,10 +175,12 @@ impl PublicContext { out } - fn storage_read(self, storage_slot: Field) -> T + fn storage_read( + self, + storage_slot: Field + ) -> T where - T: Deserialize, - { + T: Deserialize, { T::deserialize(self.raw_storage_read(storage_slot)) } @@ -188,10 +190,13 @@ impl PublicContext { } } - fn storage_write(self, storage_slot: Field, value: T) + fn storage_write( + self, + storage_slot: Field, + value: T + ) where - T: Serialize, - { + T: Serialize, { self.raw_storage_write(storage_slot, value.serialize()); } } @@ -272,7 +277,7 @@ unconstrained fn call( gas: [Field; 2], address: AztecAddress, args: [Field], - function_selector: Field, + function_selector: Field ) -> ([Field; RET_SIZE], u8) { call_opcode(gas, address, args, function_selector) } @@ -280,7 +285,7 @@ unconstrained fn call_static( gas: [Field; 2], address: AztecAddress, args: [Field], - function_selector: Field, + function_selector: Field ) -> ([Field; RET_SIZE], u8) { call_static_opcode(gas, address, args, function_selector) } @@ -384,7 +389,7 @@ unconstrained fn call_opcode( address: AztecAddress, args: [Field], // TODO(5110): consider passing in calldata directly - function_selector: Field, + function_selector: Field ) -> ([Field; RET_SIZE], u8) {} // ^ return data ^ success @@ -394,7 +399,7 @@ unconstrained fn call_static_opcode( address: AztecAddress, args: [Field], // TODO(5110): consider passing in calldata directly - function_selector: Field, + function_selector: Field ) -> ([Field; RET_SIZE], u8) {} // ^ return data ^ success @@ -419,8 +424,7 @@ impl FunctionReturns { pub fn deserialize_into(self) -> T where - T: Deserialize, - { + T: Deserialize, { Deserialize::deserialize(self.raw()) } } diff --git a/noir-projects/aztec-nr/aztec/src/context/unconstrained_context.nr b/noir-projects/aztec-nr/aztec/src/context/unconstrained_context.nr index fad4adff72b..7774a4e60e0 100644 --- a/noir-projects/aztec-nr/aztec/src/context/unconstrained_context.nr +++ b/noir-projects/aztec-nr/aztec/src/context/unconstrained_context.nr @@ -1,8 +1,5 @@ use dep::protocol_types::{address::AztecAddress, traits::Deserialize}; -use crate::oracle::{ - execution::{get_chain_id, get_version, get_contract_address, get_block_number}, - storage::storage_read, -}; +use crate::oracle::{execution::{get_chain_id, get_version, get_contract_address, get_block_number}, storage::storage_read}; pub struct UnconstrainedContext { block_number: u32, @@ -57,10 +54,12 @@ impl UnconstrainedContext { storage_read(self.this_address(), storage_slot, self.block_number()) } - unconstrained fn storage_read(self, storage_slot: Field) -> T + unconstrained fn storage_read( + self, + storage_slot: Field + ) -> T where - T: Deserialize, - { + T: Deserialize, { T::deserialize(self.raw_storage_read(storage_slot)) } } diff --git a/noir-projects/aztec-nr/aztec/src/deploy.nr b/noir-projects/aztec-nr/aztec/src/deploy.nr index 2920d1c9241..919170e46f3 100644 --- a/noir-projects/aztec-nr/aztec/src/deploy.nr +++ b/noir-projects/aztec-nr/aztec/src/deploy.nr @@ -1,9 +1,6 @@ use crate::{context::PrivateContext, oracle::get_contract_instance::get_contract_instance}; -use dep::protocol_types::{ - address::AztecAddress, abis::function_selector::FunctionSelector, - constants::DEPLOYER_CONTRACT_ADDRESS, -}; +use dep::protocol_types::{address::AztecAddress, abis::function_selector::FunctionSelector, constants::DEPLOYER_CONTRACT_ADDRESS}; // Calls `deploy` on the deployer contract to deploy a new instance. pub fn deploy_contract(context: &mut PrivateContext, target: AztecAddress) { @@ -12,8 +9,7 @@ pub fn deploy_contract(context: &mut PrivateContext, target: AztecAddress) { let universal_deploy = instance.deployer.is_zero(); if !universal_deploy { assert( - instance.deployer == context.this_address(), - "Deployer address does not match current address", + instance.deployer == context.this_address(), "Deployer address does not match current address" ); } @@ -36,10 +32,10 @@ pub fn deploy_contract(context: &mut PrivateContext, target: AztecAddress) { let _call_result = context.call_private_function( DEPLOYER_CONTRACT_ADDRESS, comptime { - FunctionSelector::from_signature( - "deploy(Field,(Field),Field,(((Field,Field,bool)),((Field,Field,bool)),((Field,Field,bool)),((Field,Field,bool))),bool)", - ) - }, - serialized_args, + FunctionSelector::from_signature( + "deploy(Field,(Field),Field,(((Field,Field,bool)),((Field,Field,bool)),((Field,Field,bool)),((Field,Field,bool))),bool)" + ) + }, + serialized_args ); } diff --git a/noir-projects/aztec-nr/aztec/src/encrypted_logs/encrypted_event_emission.nr b/noir-projects/aztec-nr/aztec/src/encrypted_logs/encrypted_event_emission.nr index 960313d961f..3b2f4dca0e5 100644 --- a/noir-projects/aztec-nr/aztec/src/encrypted_logs/encrypted_event_emission.nr +++ b/noir-projects/aztec-nr/aztec/src/encrypted_logs/encrypted_event_emission.nr @@ -1,11 +1,8 @@ use crate::{ context::PrivateContext, event::event_interface::EventInterface, - encrypted_logs::payload::compute_encrypted_log, keys::getters::get_ovsk_app, - oracle::random::random, -}; -use dep::protocol_types::{ - address::AztecAddress, public_keys::{OvpkM, IvpkM}, hash::sha256_to_field, + encrypted_logs::payload::compute_encrypted_log, keys::getters::get_ovsk_app, oracle::random::random }; +use dep::protocol_types::{address::AztecAddress, public_keys::{OvpkM, IvpkM}, hash::sha256_to_field}; fn compute_raw_event_log( context: PrivateContext, @@ -14,15 +11,13 @@ fn compute_raw_event_log( ovsk_app: Field, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> ([u8; 416 + N * 32], Field) where - Event: EventInterface, -{ + Event: EventInterface, { let contract_address: AztecAddress = context.this_address(); let plaintext = event.private_to_be_bytes(randomness); - let encrypted_log: [u8; 416 + N * 32] = - compute_encrypted_log(contract_address, ovsk_app, ovpk, ivpk, recipient, plaintext); + let encrypted_log: [u8; 416 + N * 32] = compute_encrypted_log(contract_address, ovsk_app, ovpk, ivpk, recipient, plaintext); let log_hash = sha256_to_field(encrypted_log); (encrypted_log, log_hash) } @@ -33,11 +28,10 @@ unconstrained fn compute_raw_event_log_unconstrained( randomness: Field, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> ([u8; 416 + N * 32], Field) where - Event: EventInterface, -{ + Event: EventInterface, { let ovsk_app = get_ovsk_app(ovpk.hash()); compute_raw_event_log(context, event, randomness, ovsk_app, ovpk, ivpk, recipient) } @@ -46,11 +40,10 @@ pub fn encode_and_encrypt_event( context: &mut PrivateContext, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> fn[(&mut PrivateContext, OvpkM, IvpkM, AztecAddress)](Event) -> () where - Event: EventInterface, -{ + Event: EventInterface, { |e: Event| { // We use the randomness to preserve function privacy by making it non brute-forceable, so a malicious sender could // use non-random values to reveal the plaintext. But they already know it themselves anyway, and is presumably not @@ -68,11 +61,10 @@ pub fn encode_and_encrypt_event_unconstrained( context: &mut PrivateContext, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> fn[(&mut PrivateContext, OvpkM, IvpkM, AztecAddress)](Event) -> () where - Event: EventInterface, -{ + Event: EventInterface, { |e: Event| { // We use the randomness to preserve function privacy by making it non brute-forceable, so a malicious sender could // use non-random values to reveal the plaintext. But they already know it themselves anyway, and is presumably not @@ -94,11 +86,10 @@ pub fn encode_and_encrypt_event_with_randomness( randomness: Field, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> fn[(&mut PrivateContext, OvpkM, Field, IvpkM, AztecAddress)](Event) -> () where - Event: EventInterface, -{ + Event: EventInterface, { |e: Event| { let ovsk_app: Field = context.request_ovsk_app(ovpk.hash()); let (encrypted_log, log_hash) = @@ -112,11 +103,10 @@ pub fn encode_and_encrypt_event_with_randomness_unconstrained randomness: Field, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> fn[(&mut PrivateContext, Field, OvpkM, IvpkM, AztecAddress)](Event) -> () where - Event: EventInterface, -{ + Event: EventInterface, { |e: Event| { // Having the log hash be unconstrained here is fine because the way this works is we send the log hash // to the kernel, and it gets included as part of its public inputs. Then we send the tx to the sequencer, diff --git a/noir-projects/aztec-nr/aztec/src/encrypted_logs/encrypted_note_emission.nr b/noir-projects/aztec-nr/aztec/src/encrypted_logs/encrypted_note_emission.nr index 698da4ee6e7..74aa92861ba 100644 --- a/noir-projects/aztec-nr/aztec/src/encrypted_logs/encrypted_note_emission.nr +++ b/noir-projects/aztec-nr/aztec/src/encrypted_logs/encrypted_note_emission.nr @@ -1,10 +1,10 @@ use crate::{ context::PrivateContext, note::{note_emission::NoteEmission, note_interface::NoteInterface}, - keys::getters::get_ovsk_app, encrypted_logs::payload::compute_encrypted_log, + keys::getters::get_ovsk_app, encrypted_logs::payload::compute_encrypted_log }; use dep::protocol_types::{ address::AztecAddress, public_keys::{PublicKeys, OvpkM, IvpkM}, hash::sha256_to_field, - abis::note_hash::NoteHash, + abis::note_hash::NoteHash }; fn compute_raw_note_log( @@ -13,11 +13,10 @@ fn compute_raw_note_log( ovsk_app: Field, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> (u32, [u8; 416 + N * 32], Field) where - Note: NoteInterface, -{ + Note: NoteInterface, { let note_header = note.get_header(); let note_hash_counter = note_header.note_hash_counter; let storage_slot = note_header.storage_slot; @@ -29,8 +28,7 @@ where let contract_address: AztecAddress = context.this_address(); let plaintext = note.to_be_bytes(storage_slot); - let encrypted_log: [u8; 416 + N * 32] = - compute_encrypted_log(contract_address, ovsk_app, ovpk, ivpk, recipient, plaintext); + let encrypted_log: [u8; 416 + N * 32] = compute_encrypted_log(contract_address, ovsk_app, ovpk, ivpk, recipient, plaintext); let log_hash = sha256_to_field(encrypted_log); (note_hash_counter, encrypted_log, log_hash) @@ -41,11 +39,10 @@ unconstrained fn compute_raw_note_log_unconstrained( note: Note, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> (u32, [u8; 416 + N * 32], Field) where - Note: NoteInterface, -{ + Note: NoteInterface, { let ovsk_app = get_ovsk_app(ovpk.hash()); compute_raw_note_log(context, note, ovsk_app, ovpk, ivpk, recipient) } @@ -57,11 +54,10 @@ pub fn encode_and_encrypt_note( context: &mut PrivateContext, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> fn[(&mut PrivateContext, OvpkM, IvpkM, AztecAddress)](NoteEmission) -> () where - Note: NoteInterface, -{ + Note: NoteInterface, { |e: NoteEmission| { let ovsk_app: Field = context.request_ovsk_app(ovpk.hash()); @@ -75,11 +71,10 @@ pub fn encode_and_encrypt_note_unconstrained( context: &mut PrivateContext, ovpk: OvpkM, ivpk: IvpkM, - recipient: AztecAddress, + recipient: AztecAddress ) -> fn[(&mut PrivateContext, OvpkM, IvpkM, AztecAddress)](NoteEmission) -> () where - Note: NoteInterface, -{ + Note: NoteInterface, { |e: NoteEmission| { // Having the log hash be unconstrained here is fine because the way this works is we send the log hash // to the kernel, and it gets included as part of its public inputs. Then we send the tx to the sequencer, @@ -114,7 +109,7 @@ pub fn encrypt_and_emit_partial_log( context: &mut PrivateContext, log_plaintext: [u8; M], recipient_keys: PublicKeys, - recipient: AztecAddress, + recipient: AztecAddress ) { let ovsk_app: Field = context.request_ovsk_app(recipient_keys.ovpk_m.hash()); @@ -124,7 +119,7 @@ pub fn encrypt_and_emit_partial_log( recipient_keys.ovpk_m, recipient_keys.ivpk_m, recipient, - log_plaintext, + log_plaintext ); let log_hash = sha256_to_field(encrypted_log); diff --git a/noir-projects/aztec-nr/aztec/src/encrypted_logs/header.nr b/noir-projects/aztec-nr/aztec/src/encrypted_logs/header.nr index 1872fbb21d8..70927d52e64 100644 --- a/noir-projects/aztec-nr/aztec/src/encrypted_logs/header.nr +++ b/noir-projects/aztec-nr/aztec/src/encrypted_logs/header.nr @@ -1,6 +1,4 @@ -use dep::protocol_types::{ - address::AztecAddress, public_keys::{PublicKeys, IvpkM, ToPoint}, scalar::Scalar, point::Point, -}; +use dep::protocol_types::{address::AztecAddress, public_keys::{PublicKeys, IvpkM, ToPoint}, scalar::Scalar, point::Point}; use crate::keys::point_to_symmetric_key::point_to_symmetric_key; @@ -15,10 +13,13 @@ impl EncryptedLogHeader { EncryptedLogHeader { address } } - fn compute_ciphertext(self, secret: Scalar, pk: T) -> [u8; 48] + fn compute_ciphertext( + self, + secret: Scalar, + pk: T + ) -> [u8; 48] where - T: ToPoint, - { + T: ToPoint, { let full_key = point_to_symmetric_key(secret, pk.to_point()); let mut sym_key = [0; 16]; let mut iv = [0; 16]; @@ -39,14 +40,14 @@ unconstrained fn test_encrypted_log_header_matches_noir() { let header = EncryptedLogHeader::new(address); let secret = Scalar { lo: 0x00000000000000000000000000000000649e7ca01d9de27b21624098b897babd, - hi: 0x0000000000000000000000000000000023b3127c127b1f29a7adff5cccf8fb06, + hi: 0x0000000000000000000000000000000023b3127c127b1f29a7adff5cccf8fb06 }; let point = IvpkM { inner: Point { x: 0x2688431c705a5ff3e6c6f2573c9e3ba1c1026d2251d0dbbf2d810aa53fd1d186, y: 0x1e96887b117afca01c00468264f4f80b5bb16d94c1808a448595f115556e5c8e, - is_infinite: false, - }, + is_infinite: false + } }; let ciphertext = header.compute_ciphertext(secret, point); @@ -56,7 +57,7 @@ unconstrained fn test_encrypted_log_header_matches_noir() { let expected_header_ciphertext_from_typescript = [ 226, 240, 253, 6, 28, 52, 19, 131, 33, 132, 178, 212, 245, 62, 14, 190, 194, 44, 7, 131, 160, 83, 64, 181, 98, 38, 153, 214, 62, 171, 253, 161, 111, 191, 28, 247, 216, 26, 222, 171, - 176, 218, 48, 209, 73, 89, 200, 209, + 176, 218, 48, 209, 73, 89, 200, 209 ]; assert_eq(ciphertext, expected_header_ciphertext_from_typescript); diff --git a/noir-projects/aztec-nr/aztec/src/encrypted_logs/payload.nr b/noir-projects/aztec-nr/aztec/src/encrypted_logs/payload.nr index 60dad2821f0..98e5a22082f 100644 --- a/noir-projects/aztec-nr/aztec/src/encrypted_logs/payload.nr +++ b/noir-projects/aztec-nr/aztec/src/encrypted_logs/payload.nr @@ -1,16 +1,15 @@ use dep::protocol_types::{ address::AztecAddress, scalar::Scalar, point::Point, public_keys::{OvpkM, IvpkM}, - constants::GENERATOR_INDEX__SYMMETRIC_KEY, hash::poseidon2_hash_with_separator, + constants::GENERATOR_INDEX__SYMMETRIC_KEY, hash::poseidon2_hash_with_separator }; use std::{ aes128::aes128_encrypt, embedded_curve_ops::fixed_base_scalar_mul as derive_public_key, - hash::from_field_unsafe as fr_to_fq_unsafe, field::bn254::decompose, + hash::from_field_unsafe as fr_to_fq_unsafe, field::bn254::decompose }; use crate::{ - oracle::random::random, utils::point::point_to_bytes, - encrypted_logs::header::EncryptedLogHeader, - keys::point_to_symmetric_key::point_to_symmetric_key, + oracle::random::random, utils::point::point_to_bytes, encrypted_logs::header::EncryptedLogHeader, + keys::point_to_symmetric_key::point_to_symmetric_key }; pub fn compute_encrypted_log( @@ -19,7 +18,7 @@ pub fn compute_encrypted_log( ovpk: OvpkM, ivpk: IvpkM, recipient: AztecAddress, - plaintext: [u8; P], + plaintext: [u8; P] ) -> [u8; M] { let (eph_sk, eph_pk) = generate_ephemeral_key_pair(); @@ -28,8 +27,7 @@ pub fn compute_encrypted_log( let incoming_header_ciphertext: [u8; 48] = header.compute_ciphertext(eph_sk, ivpk); let outgoing_header_ciphertext: [u8; 48] = header.compute_ciphertext(eph_sk, ovpk); let incoming_body_ciphertext = compute_incoming_body_ciphertext(plaintext, eph_sk, ivpk); - let outgoing_body_ciphertext: [u8; 144] = - compute_outgoing_body_ciphertext(recipient, ivpk, fr_to_fq(ovsk_app), eph_sk, eph_pk); + let outgoing_body_ciphertext: [u8; 144] = compute_outgoing_body_ciphertext(recipient, ivpk, fr_to_fq(ovsk_app), eph_sk, eph_pk); let mut encrypted_bytes: [u8; M] = [0; M]; // @todo We ignore the tags for now @@ -77,7 +75,9 @@ fn generate_ephemeral_key_pair() -> (Scalar, Point) { // sender could use non-random values to reveal the plaintext. But they already know it themselves anyway, and so // the recipient already trusts them to not disclose this information. We can therefore assume that the sender will // cooperate in the random value generation. - let randomness = unsafe { random() }; + let randomness = unsafe { + random() + }; // We use the unsafe version of `fr_to_fq` because multi_scalar_mul (called by derive_public_key) will constrain // the scalars. @@ -87,11 +87,7 @@ fn generate_ephemeral_key_pair() -> (Scalar, Point) { (eph_sk, eph_pk) } -pub fn compute_incoming_body_ciphertext( - plaintext: [u8; P], - eph_sk: Scalar, - ivpk: IvpkM, -) -> [u8] { +pub fn compute_incoming_body_ciphertext(plaintext: [u8; P], eph_sk: Scalar, ivpk: IvpkM) -> [u8] { let full_key = point_to_symmetric_key(eph_sk, ivpk.to_point()); let mut sym_key = [0; 16]; let mut iv = [0; 16]; @@ -110,7 +106,7 @@ pub fn compute_outgoing_body_ciphertext( recipient_ivpk: IvpkM, ovsk_app: Scalar, eph_sk: Scalar, - eph_pk: Point, + eph_pk: Point ) -> [u8; 144] { // Again, we could compute `eph_pk` here, but we keep the interface more similar // and also make it easier to optimise it later as we just pass it along @@ -134,9 +130,8 @@ pub fn compute_outgoing_body_ciphertext( // We compute the symmetric key using poseidon. let full_key: [u8; 32] = poseidon2_hash_with_separator( [ovsk_app.hi, ovsk_app.lo, eph_pk.x, eph_pk.y], - GENERATOR_INDEX__SYMMETRIC_KEY as Field, - ) - .to_be_bytes(); + GENERATOR_INDEX__SYMMETRIC_KEY as Field + ).to_be_bytes(); let mut sym_key = [0; 16]; let mut iv = [0; 16]; @@ -149,35 +144,29 @@ pub fn compute_outgoing_body_ciphertext( } mod test { - use crate::encrypted_logs::payload::{ - compute_encrypted_log, compute_incoming_body_ciphertext, compute_outgoing_body_ciphertext, - }; + use crate::encrypted_logs::payload::{compute_encrypted_log, compute_incoming_body_ciphertext, compute_outgoing_body_ciphertext}; use std::embedded_curve_ops::fixed_base_scalar_mul as derive_public_key; - use dep::protocol_types::{ - address::AztecAddress, public_keys::{OvpkM, IvpkM}, point::Point, scalar::Scalar, - }; + use dep::protocol_types::{address::AztecAddress, public_keys::{OvpkM, IvpkM}, point::Point, scalar::Scalar}; use std::test::OracleMock; #[test] unconstrained fn test_encrypted_log_matches_typescript() { // All the values in this test were copied over from `tagged_log.test.ts` - let contract_address = AztecAddress::from_field( - 0x10f48cd9eff7ae5b209c557c70de2e657ee79166868676b787e9417e19260e04, - ); + let contract_address = AztecAddress::from_field(0x10f48cd9eff7ae5b209c557c70de2e657ee79166868676b787e9417e19260e04); let ovsk_app = 0x03a6513d6def49f41d20373d2cec894c23e7492794b08fc50c0e8a1bd2512612; let ovpk_m = OvpkM { inner: Point { x: 0x1961448682803198631f299340e4206bb12809d4bebbf012b30f59af73ba1a15, y: 0x133674060c3925142aceb4f1dcd9f9137d0217d37ff8729ee5ceaa6e2790353d, - is_infinite: false, - }, + is_infinite: false + } }; let ivpk_m = IvpkM { inner: Point { x: 0x260cd3904f6df16e974c29944fdc839e40fb5cf293f03df2eb370851d3a527bc, y: 0x0eef2964fe6640e84c82b5d2915892409b38e9e25d39f68dd79edb725c55387f, - is_infinite: false, - }, + is_infinite: false + } }; let plaintext = [ @@ -186,24 +175,15 @@ mod test { 247, 174, 91, 32, 156, 85, 124, 112, 222, 46, 101, 126, 231, 145, 102, 134, 134, 118, 183, 135, 233, 65, 126, 25, 38, 14, 4, 15, 228, 107, 229, 131, 183, 31, 74, 181, 183, 12, 38, 87, 255, 29, 5, 204, 207, 29, 41, 42, 147, 105, 98, 141, 26, 25, 79, 148, 78, - 101, 153, 0, 0, 16, 39, + 101, 153, 0, 0, 16, 39 ]; let eph_sk = 0x1358d15019d4639393d62b97e1588c095957ce74a1c32d6ec7d62fe6705d9538; let _ = OracleMock::mock("getRandomField").returns(eph_sk); - let recipient = AztecAddress::from_field( - 0x10ee41ee4b62703b16f61e03cb0d88c4b306a9eb4a6ceeb2aff13428541689a2, - ); + let recipient = AztecAddress::from_field(0x10ee41ee4b62703b16f61e03cb0d88c4b306a9eb4a6ceeb2aff13428541689a2); - let log: [u8; 448] = compute_encrypted_log( - contract_address, - ovsk_app, - ovpk_m, - ivpk_m, - recipient, - plaintext, - ); + let log: [u8; 448] = compute_encrypted_log(contract_address, ovsk_app, ovpk_m, ivpk_m, recipient, plaintext); // The following value was generated by `tagged_log.test.ts` // --> Run the test with AZTEC_GENERATE_TEST_DATA=1 flag to update test data. @@ -230,7 +210,7 @@ mod test { 68, 131, 217, 117, 140, 19, 147, 37, 197, 192, 21, 43, 172, 239, 239, 205, 15, 110, 76, 26, 211, 42, 117, 4, 15, 135, 145, 247, 37, 73, 84, 164, 149, 250, 35, 0, 205, 105, 178, 143, 104, 98, 100, 250, 193, 154, 136, 175, 177, 109, 225, 207, 252, 147, 250, 250, 189, - 117, 147, 101, 230, 132, + 117, 147, 101, 230, 132 ]; assert_eq(encrypted_log_from_typescript, log); } @@ -240,14 +220,14 @@ mod test { // All the values in this test were copied over from `encrypted_note_log_incoming_body.test.ts` let eph_sk = Scalar { lo: 0x00000000000000000000000000000000649e7ca01d9de27b21624098b897babd, - hi: 0x0000000000000000000000000000000023b3127c127b1f29a7adff5cccf8fb06, + hi: 0x0000000000000000000000000000000023b3127c127b1f29a7adff5cccf8fb06 }; let ivpk = IvpkM { inner: Point { x: 0x2688431c705a5ff3e6c6f2573c9e3ba1c1026d2251d0dbbf2d810aa53fd1d186, y: 0x1e96887b117afca01c00468264f4f80b5bb16d94c1808a448595f115556e5c8e, - is_infinite: false, - }, + is_infinite: false + } }; let plaintext = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -255,7 +235,7 @@ mod test { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3 ]; // `compute_incoming_body_ciphertext(...)` function then derives symmetric key from `eph_sk` and `ivpk` and encrypts @@ -274,7 +254,7 @@ mod test { 245, 142, 232, 87, 252, 28, 67, 67, 90, 214, 254, 89, 47, 68, 66, 187, 227, 8, 59, 162, 25, 141, 97, 141, 217, 197, 115, 15, 212, 202, 157, 41, 150, 62, 219, 57, 224, 92, 185, 212, 142, 94, 146, 41, 178, 145, 68, 169, 23, 185, 206, 138, 70, 47, 176, 210, 165, 236, - 23, 206, 229, 108, + 23, 206, 229, 108 ]; assert_eq(note_body_ciphertext_from_typescript.len(), ciphertext.len()); @@ -288,15 +268,15 @@ mod test { fn test_encrypted_log_outgoing_body_matches_typescript() { let eph_sk = Scalar { lo: 0x00000000000000000000000000000000d0d302ee245dfaf2807e604eec4715fe, - hi: 0x000000000000000000000000000000000f096b423017226a18461115fa8d34bb, + hi: 0x000000000000000000000000000000000f096b423017226a18461115fa8d34bb }; let recipient_ivsk = Scalar { lo: 0x000000000000000000000000000000004828f8f95676ebb481df163f87fd4022, - hi: 0x000000000000000000000000000000000f4d97c25d578f9348251a71ca17ae31, + hi: 0x000000000000000000000000000000000f4d97c25d578f9348251a71ca17ae31 }; let sender_ovsk_app = Scalar { lo: 0x0000000000000000000000000000000074d2e28c6bc5176ac02cf7c7d36a444e, - hi: 0x00000000000000000000000000000000089c6887cb1446d86c64e81afc78048b, + hi: 0x00000000000000000000000000000000089c6887cb1446d86c64e81afc78048b }; let eph_pk = derive_public_key(eph_sk); @@ -304,13 +284,7 @@ mod test { let recipient = AztecAddress::from_field(0xdeadbeef); - let ciphertext = compute_outgoing_body_ciphertext( - recipient, - recipient_ivpk, - sender_ovsk_app, - eph_sk, - eph_pk, - ); + let ciphertext = compute_outgoing_body_ciphertext(recipient, recipient_ivpk, sender_ovsk_app, eph_sk, eph_pk); // The following value was generated by `encrypted_log_outgoing_body.test.ts` // --> Run the test with AZTEC_GENERATE_TEST_DATA=1 flag to update test data. @@ -322,7 +296,7 @@ mod test { 152, 83, 42, 170, 13, 106, 209, 254, 74, 39, 145, 73, 215, 17, 234, 196, 89, 30, 58, 120, 127, 88, 69, 121, 61, 18, 206, 89, 118, 243, 238, 177, 71, 73, 47, 147, 4, 155, 25, 173, 248, 206, 52, 17, 180, 122, 186, 106, 191, 252, 102, 197, 91, 16, 39, 94, 91, 224, - 30, 168, 177, 26, 144, 5, 124, 128, 6, + 30, 168, 177, 26, 144, 5, 124, 128, 6 ]; assert_eq(outgoing_body_ciphertext_from_typescript, ciphertext); diff --git a/noir-projects/aztec-nr/aztec/src/hash.nr b/noir-projects/aztec-nr/aztec/src/hash.nr index c58c78dbb82..b96fec6e1a5 100644 --- a/noir-projects/aztec-nr/aztec/src/hash.nr +++ b/noir-projects/aztec-nr/aztec/src/hash.nr @@ -1,10 +1,8 @@ use dep::protocol_types::{ address::{AztecAddress, EthAddress}, - constants::{ - GENERATOR_INDEX__SECRET_HASH, GENERATOR_INDEX__MESSAGE_NULLIFIER, - GENERATOR_INDEX__FUNCTION_ARGS, - }, point::Point, traits::Hash, - hash::{sha256_to_field, poseidon2_hash_with_separator, poseidon2_hash_with_separator_slice}, + constants::{GENERATOR_INDEX__SECRET_HASH, GENERATOR_INDEX__MESSAGE_NULLIFIER, GENERATOR_INDEX__FUNCTION_ARGS}, + point::Point, traits::Hash, + hash::{sha256_to_field, poseidon2_hash_with_separator, poseidon2_hash_with_separator_slice} }; use crate::utils::to_bytes::{arr_to_be_bytes_arr, str_to_be_bytes_arr}; @@ -18,10 +16,7 @@ pub fn compute_secret_hash(secret: Field) -> Field { poseidon2_hash_with_separator([secret], GENERATOR_INDEX__SECRET_HASH) } -pub fn compute_unencrypted_log_hash( - contract_address: AztecAddress, - log: [u8; N], -) -> Field { +pub fn compute_unencrypted_log_hash(contract_address: AztecAddress, log: [u8; N]) -> Field { let mut hash_bytes = [0; N + 36]; // Address is converted to 32 bytes in ts let address_bytes: [u8; 32] = contract_address.to_field().to_be_bytes(); @@ -45,7 +40,7 @@ pub fn compute_message_hash( recipient: AztecAddress, version: Field, content: Field, - secret_hash: Field, + secret_hash: Field ) -> Field { let mut hash_bytes = [0 as u8; 192]; let sender_bytes: [u8; 32] = sender.to_field().to_be_bytes(); @@ -72,7 +67,7 @@ pub fn compute_message_hash( pub fn compute_message_nullifier(message_hash: Field, secret: Field, leaf_index: Field) -> Field { poseidon2_hash_with_separator( [message_hash, secret, leaf_index], - GENERATOR_INDEX__MESSAGE_NULLIFIER, + GENERATOR_INDEX__MESSAGE_NULLIFIER ) } @@ -131,15 +126,13 @@ unconstrained fn compute_var_args_hash() { #[test] unconstrained fn compute_unenc_log_hash_array() { - let contract_address = AztecAddress::from_field( - 0x233a3e0df23b2b15b324194cb4a151f26c0b7333250781d34cc269d85dc334c6, - ); + let contract_address = AztecAddress::from_field(0x233a3e0df23b2b15b324194cb4a151f26c0b7333250781d34cc269d85dc334c6); let log = [ 0x20660de09f35f876e3e69d227b2a35166ad05f09d82d06366ec9b6f65a51fec2, 0x1b52bfe3b8689761916f76dc3d38aa8810860db325cd39ca611eed980091f01c, 0x2e559c4045c378a56ad13b9edb1e8de4e7ad3b3aa35cc7ba9ec77f7a68fa43a4, 0x25d0f689c4a4178a29d59306f2675824d19be6d25e44fa03b03f49c263053dd2, - 0x2d513a722d6f352dc0961f156afdc5e31495b9f0e35cb069261a8e55e2df67fd, + 0x2d513a722d6f352dc0961f156afdc5e31495b9f0e35cb069261a8e55e2df67fd ]; let serialized_log = arr_to_be_bytes_arr(log); let hash = compute_unencrypted_log_hash(contract_address, serialized_log); @@ -148,12 +141,8 @@ unconstrained fn compute_unenc_log_hash_array() { #[test] unconstrained fn compute_unenc_log_hash_addr() { - let contract_address = AztecAddress::from_field( - 0x233a3e0df23b2b15b324194cb4a151f26c0b7333250781d34cc269d85dc334c6, - ); - let log = AztecAddress::from_field( - 0x26aa302d4715fd8a687453cb26d616b0768027bd54bcae56b09d908ecd9f8303, - ); + let contract_address = AztecAddress::from_field(0x233a3e0df23b2b15b324194cb4a151f26c0b7333250781d34cc269d85dc334c6); + let log = AztecAddress::from_field(0x26aa302d4715fd8a687453cb26d616b0768027bd54bcae56b09d908ecd9f8303); let serialized_log: [u8; 32] = log.to_field().to_be_bytes(); let hash = compute_unencrypted_log_hash(contract_address, serialized_log); assert(hash == 0x0083ab647dfb26e7ddee90a0f4209d049d4660cab42000c544b986aaa84c55a3); @@ -161,9 +150,7 @@ unconstrained fn compute_unenc_log_hash_addr() { #[test] unconstrained fn compute_unenc_log_hash_str() { - let contract_address = AztecAddress::from_field( - 0x1b401e1146c5c507962287065c81f0ef7590adae3802c533d7549d6bf0a41bd8, - ); + let contract_address = AztecAddress::from_field(0x1b401e1146c5c507962287065c81f0ef7590adae3802c533d7549d6bf0a41bd8); let log = "dummy"; let serialized_log = str_to_be_bytes_arr(log); let hash = compute_unencrypted_log_hash(contract_address, serialized_log); @@ -172,9 +159,7 @@ unconstrained fn compute_unenc_log_hash_str() { #[test] unconstrained fn compute_unenc_log_hash_longer_str() { - let contract_address = AztecAddress::from_field( - 0x1b401e1146c5c507962287065c81f0ef7590adae3802c533d7549d6bf0a41bd8, - ); + let contract_address = AztecAddress::from_field(0x1b401e1146c5c507962287065c81f0ef7590adae3802c533d7549d6bf0a41bd8); let log = "Hello this is a string"; let serialized_log = str_to_be_bytes_arr(log); let hash = compute_unencrypted_log_hash(contract_address, serialized_log); diff --git a/noir-projects/aztec-nr/aztec/src/history/contract_inclusion.nr b/noir-projects/aztec-nr/aztec/src/history/contract_inclusion.nr index 456c1dac837..46219e12e16 100644 --- a/noir-projects/aztec-nr/aztec/src/history/contract_inclusion.nr +++ b/noir-projects/aztec-nr/aztec/src/history/contract_inclusion.nr @@ -1,6 +1,6 @@ use dep::protocol_types::{ header::Header, address::AztecAddress, hash::compute_siloed_nullifier, - constants::DEPLOYER_CONTRACT_ADDRESS, + constants::DEPLOYER_CONTRACT_ADDRESS }; trait ProveContractDeployment { @@ -10,8 +10,7 @@ trait ProveContractDeployment { impl ProveContractDeployment for Header { fn prove_contract_deployment(self, contract_address: AztecAddress) { // Compute deployment nullifier - let nullifier = - compute_siloed_nullifier(DEPLOYER_CONTRACT_ADDRESS, contract_address.to_field()); + let nullifier = compute_siloed_nullifier(DEPLOYER_CONTRACT_ADDRESS, contract_address.to_field()); self.prove_nullifier_inclusion(nullifier); } @@ -24,8 +23,7 @@ trait ProveContractNonDeployment { impl ProveContractNonDeployment for Header { fn prove_contract_non_deployment(self, contract_address: AztecAddress) { // Compute deployment nullifier - let nullifier = - compute_siloed_nullifier(DEPLOYER_CONTRACT_ADDRESS, contract_address.to_field()); + let nullifier = compute_siloed_nullifier(DEPLOYER_CONTRACT_ADDRESS, contract_address.to_field()); // docs:start:prove_nullifier_non_inclusion self.prove_nullifier_non_inclusion(nullifier); diff --git a/noir-projects/aztec-nr/aztec/src/history/note_inclusion.nr b/noir-projects/aztec-nr/aztec/src/history/note_inclusion.nr index a7f18eb4e99..f0fc349f0da 100644 --- a/noir-projects/aztec-nr/aztec/src/history/note_inclusion.nr +++ b/noir-projects/aztec-nr/aztec/src/history/note_inclusion.nr @@ -3,7 +3,7 @@ use dep::protocol_types::header::Header; use crate::{ note::{utils::compute_note_hash_for_nullify, note_interface::{NoteInterface, NullifiableNote}}, - oracle::get_membership_witness::get_note_hash_membership_witness, + oracle::get_membership_witness::get_note_hash_membership_witness }; trait ProveNoteInclusion { @@ -13,10 +13,12 @@ trait ProveNoteInclusion { } impl ProveNoteInclusion for Header { - fn prove_note_inclusion(self, note: Note) + fn prove_note_inclusion( + self, + note: Note + ) where - Note: NoteInterface + NullifiableNote, - { + Note: NoteInterface + NullifiableNote, { let note_hash = compute_note_hash_for_nullify(note); let witness = unsafe { @@ -27,9 +29,7 @@ impl ProveNoteInclusion for Header { // we don't even care _where_ in the tree it is stored. This is because entries in the note hash tree are // unique. assert_eq( - self.state.partial.note_hash_tree.root, - root_from_sibling_path(note_hash, witness.index, witness.path), - "Proving note inclusion failed", + self.state.partial.note_hash_tree.root, root_from_sibling_path(note_hash, witness.index, witness.path), "Proving note inclusion failed" ); } } diff --git a/noir-projects/aztec-nr/aztec/src/history/note_validity.nr b/noir-projects/aztec-nr/aztec/src/history/note_validity.nr index 3efac1fc1aa..0d6d5e9b22a 100644 --- a/noir-projects/aztec-nr/aztec/src/history/note_validity.nr +++ b/noir-projects/aztec-nr/aztec/src/history/note_validity.nr @@ -13,10 +13,13 @@ trait ProveNoteValidity { } impl ProveNoteValidity for Header { - fn prove_note_validity(self, note: Note, context: &mut PrivateContext) + fn prove_note_validity( + self, + note: Note, + context: &mut PrivateContext + ) where - Note: NoteInterface + NullifiableNote, - { + Note: NoteInterface + NullifiableNote, { self.prove_note_inclusion(note); self.prove_note_not_nullified(note, context); } diff --git a/noir-projects/aztec-nr/aztec/src/history/nullifier_inclusion.nr b/noir-projects/aztec-nr/aztec/src/history/nullifier_inclusion.nr index 3651acabab9..963e456a07d 100644 --- a/noir-projects/aztec-nr/aztec/src/history/nullifier_inclusion.nr +++ b/noir-projects/aztec-nr/aztec/src/history/nullifier_inclusion.nr @@ -2,9 +2,8 @@ use dep::protocol_types::merkle_tree::root::root_from_sibling_path; use dep::protocol_types::header::Header; use crate::{ - context::PrivateContext, - oracle::get_nullifier_membership_witness::get_nullifier_membership_witness, - note::{utils::compute_siloed_nullifier, note_interface::{NoteInterface, NullifiableNote}}, + context::PrivateContext, oracle::get_nullifier_membership_witness::get_nullifier_membership_witness, + note::{utils::compute_siloed_nullifier, note_interface::{NoteInterface, NullifiableNote}} }; trait ProveNullifierInclusion { @@ -22,19 +21,14 @@ impl ProveNullifierInclusion for Header { // the leaf that contains the nullifier we're proving inclusion for. assert( self.state.partial.nullifier_tree.root - == root_from_sibling_path(witness.leaf_preimage.hash(), witness.index, witness.path) - , - "Proving nullifier inclusion failed", - ); - - // 3) Then we simply check that the value in the leaf is the expected one. Note that we don't need to perform - // any checks on the rest of the values in the leaf preimage (the next index or next nullifier), since all we - // care about is showing that the tree contains an entry with the expected nullifier. - assert( - witness.leaf_preimage.nullifier == nullifier, - "Nullifier does not match value in witness", - ); - } + == root_from_sibling_path(witness.leaf_preimage.hash(), witness.index, witness.path), "Proving nullifier inclusion failed" + ); + + // 3) Then we simply check that the value in the leaf is the expected one. Note that we don't need to perform + // any checks on the rest of the values in the leaf preimage (the next index or next nullifier), since all we + // care about is showing that the tree contains an entry with the expected nullifier. + assert(witness.leaf_preimage.nullifier == nullifier, "Nullifier does not match value in witness"); + } } trait ProveNoteIsNullified { @@ -49,10 +43,13 @@ trait ProveNoteIsNullified { impl ProveNoteIsNullified for Header { // docs:start:prove_note_is_nullified - fn prove_note_is_nullified(self, note: Note, context: &mut PrivateContext) + fn prove_note_is_nullified( + self, + note: Note, + context: &mut PrivateContext + ) where - Note: NoteInterface + NullifiableNote, - { + Note: NoteInterface + NullifiableNote, { let nullifier = compute_siloed_nullifier(note, context); self.prove_nullifier_inclusion(nullifier); diff --git a/noir-projects/aztec-nr/aztec/src/history/nullifier_non_inclusion.nr b/noir-projects/aztec-nr/aztec/src/history/nullifier_non_inclusion.nr index e8cf5d7bf4d..a814ce985e3 100644 --- a/noir-projects/aztec-nr/aztec/src/history/nullifier_non_inclusion.nr +++ b/noir-projects/aztec-nr/aztec/src/history/nullifier_non_inclusion.nr @@ -1,11 +1,9 @@ use dep::protocol_types::merkle_tree::root::root_from_sibling_path; -use dep::protocol_types::{ - header::Header, utils::field::{full_field_less_than, full_field_greater_than}, -}; +use dep::protocol_types::{header::Header, utils::field::{full_field_less_than, full_field_greater_than}}; use crate::{ context::PrivateContext, note::{utils::compute_siloed_nullifier, note_interface::{NoteInterface, NullifiableNote}}, - oracle::get_nullifier_membership_witness::get_low_nullifier_membership_witness, + oracle::get_nullifier_membership_witness::get_low_nullifier_membership_witness }; trait ProveNullifierNonInclusion { @@ -16,10 +14,7 @@ impl ProveNullifierNonInclusion for Header { fn prove_nullifier_non_inclusion(self, nullifier: Field) { // 1) Get the membership witness of a low nullifier of the nullifier let witness = unsafe { - get_low_nullifier_membership_witness( - self.global_variables.block_number as u32, - nullifier, - ) + get_low_nullifier_membership_witness(self.global_variables.block_number as u32, nullifier) }; // 2) First we prove that the tree leaf in the witness is present in the nullifier tree. This is expected to be @@ -28,14 +23,12 @@ impl ProveNullifierNonInclusion for Header { let low_nullifier_leaf = witness.leaf_preimage; assert( self.state.partial.nullifier_tree.root - == root_from_sibling_path(low_nullifier_leaf.hash(), witness.index, witness.path), - "Proving nullifier non-inclusion failed: Could not prove low nullifier inclusion", + == root_from_sibling_path(low_nullifier_leaf.hash(), witness.index, witness.path), "Proving nullifier non-inclusion failed: Could not prove low nullifier inclusion" ); // 3) Prove that the low leaf is indeed smaller than the nullifier assert( - full_field_less_than(low_nullifier_leaf.nullifier, nullifier), - "Proving nullifier non-inclusion failed: low_nullifier.value < nullifier.value check failed", + full_field_less_than(low_nullifier_leaf.nullifier, nullifier), "Proving nullifier non-inclusion failed: low_nullifier.value < nullifier.value check failed" ); // 4) Prove that the low leaf is pointing "over" the nullifier, which means that the nullifier is not included @@ -43,8 +36,7 @@ impl ProveNullifierNonInclusion for Header { // special case in which the low leaf is the largest of all entries, in which case there's no 'next' entry. assert( full_field_greater_than(low_nullifier_leaf.next_nullifier, nullifier) - | (low_nullifier_leaf.next_index == 0), - "Proving nullifier non-inclusion failed: low_nullifier.next_value > nullifier.value check failed", + | (low_nullifier_leaf.next_index == 0), "Proving nullifier non-inclusion failed: low_nullifier.next_value > nullifier.value check failed" ); } } @@ -61,10 +53,13 @@ trait ProveNoteNotNullified { impl ProveNoteNotNullified for Header { // docs:start:prove_note_not_nullified - fn prove_note_not_nullified(self, note: Note, context: &mut PrivateContext) + fn prove_note_not_nullified( + self, + note: Note, + context: &mut PrivateContext + ) where - Note: NoteInterface + NullifiableNote, - { + Note: NoteInterface + NullifiableNote, { let nullifier = compute_siloed_nullifier(note, context); self.prove_nullifier_non_inclusion(nullifier); diff --git a/noir-projects/aztec-nr/aztec/src/history/public_storage.nr b/noir-projects/aztec-nr/aztec/src/history/public_storage.nr index 78aeeb63be7..58f64664a86 100644 --- a/noir-projects/aztec-nr/aztec/src/history/public_storage.nr +++ b/noir-projects/aztec-nr/aztec/src/history/public_storage.nr @@ -1,6 +1,6 @@ use dep::protocol_types::{ constants::GENERATOR_INDEX__PUBLIC_LEAF_INDEX, hash::poseidon2_hash_with_separator, - address::AztecAddress, header::Header, utils::field::full_field_less_than, + address::AztecAddress, header::Header, utils::field::full_field_less_than }; use dep::protocol_types::merkle_tree::root::root_from_sibling_path; @@ -15,22 +15,18 @@ trait PublicStorageHistoricalRead { } impl PublicStorageHistoricalRead for Header { - fn public_storage_historical_read( - self, - storage_slot: Field, - contract_address: AztecAddress, - ) -> Field { + fn public_storage_historical_read(self, storage_slot: Field, contract_address: AztecAddress) -> Field { // 1) Compute the leaf index by siloing the storage slot with the contract address let public_data_tree_index = poseidon2_hash_with_separator( [contract_address.to_field(), storage_slot], - GENERATOR_INDEX__PUBLIC_LEAF_INDEX, + GENERATOR_INDEX__PUBLIC_LEAF_INDEX ); // 2) Get the membership witness for the tree index. let witness = unsafe { get_public_data_witness( self.global_variables.block_number as u32, - public_data_tree_index, + public_data_tree_index ) }; @@ -40,35 +36,28 @@ impl PublicStorageHistoricalRead for Header { // (slot, next index and next slot). assert( self.state.partial.public_data_tree.root - == root_from_sibling_path(witness.leaf_preimage.hash(), witness.index, witness.path) - , - "Proving public value inclusion failed", - ); - - // 4) Now that we know the preimage is valid, we determine the value that's represented by this tree entry. Here - // we have two scenarios: - // 1. The tree entry is initialized, and the value is the same as the one in the witness - // 2. The entry was never initialized, and the value is default zero (the default) - // The code below is based on the same checks in `validate_public_data_reads` in `base_rollup_inputs`. - let preimage = witness.leaf_preimage; - - let is_less_than_slot = full_field_less_than(preimage.slot, public_data_tree_index); - let is_next_greater_than = - full_field_less_than(public_data_tree_index, preimage.next_slot); - let is_max = ((preimage.next_index == 0) & (preimage.next_slot == 0)); - let is_in_range = is_less_than_slot & (is_next_greater_than | is_max); + == root_from_sibling_path(witness.leaf_preimage.hash(), witness.index, witness.path), "Proving public value inclusion failed" + ); - let value = if is_in_range { - 0 - } else { - assert_eq( - preimage.slot, - public_data_tree_index, - "Public data tree index doesn't match witness", - ); - preimage.value - }; + // 4) Now that we know the preimage is valid, we determine the value that's represented by this tree entry. Here + // we have two scenarios: + // 1. The tree entry is initialized, and the value is the same as the one in the witness + // 2. The entry was never initialized, and the value is default zero (the default) + // The code below is based on the same checks in `validate_public_data_reads` in `base_rollup_inputs`. + let preimage = witness.leaf_preimage; + + let is_less_than_slot = full_field_less_than(preimage.slot, public_data_tree_index); + let is_next_greater_than = full_field_less_than(public_data_tree_index, preimage.next_slot); + let is_max = ((preimage.next_index == 0) & (preimage.next_slot == 0)); + let is_in_range = is_less_than_slot & (is_next_greater_than | is_max); + + let value = if is_in_range { + 0 + } else { + assert_eq(preimage.slot, public_data_tree_index, "Public data tree index doesn't match witness"); + preimage.value + }; - value - } + value + } } diff --git a/noir-projects/aztec-nr/aztec/src/initializer.nr b/noir-projects/aztec-nr/aztec/src/initializer.nr index ec966af74af..1be907c5ce9 100644 --- a/noir-projects/aztec-nr/aztec/src/initializer.nr +++ b/noir-projects/aztec-nr/aztec/src/initializer.nr @@ -1,22 +1,20 @@ use dep::protocol_types::{ - address::AztecAddress, hash::poseidon2_hash_with_separator, - constants::GENERATOR_INDEX__CONSTRUCTOR, abis::function_selector::FunctionSelector, + address::AztecAddress, hash::poseidon2_hash_with_separator, constants::GENERATOR_INDEX__CONSTRUCTOR, + abis::function_selector::FunctionSelector }; use crate::{ context::{PrivateContext, PublicContext}, oracle::get_contract_instance::get_contract_instance, - oracle::get_contract_instance::get_contract_instance_avm, + oracle::get_contract_instance::get_contract_instance_avm }; pub fn mark_as_initialized_public(context: &mut PublicContext) { - let init_nullifier = - compute_unsiloed_contract_initialization_nullifier((*context).this_address()); + let init_nullifier = compute_unsiloed_contract_initialization_nullifier((*context).this_address()); context.push_nullifier(init_nullifier); } pub fn mark_as_initialized_private(context: &mut PrivateContext) { - let init_nullifier = - compute_unsiloed_contract_initialization_nullifier((*context).this_address()); + let init_nullifier = compute_unsiloed_contract_initialization_nullifier((*context).this_address()); context.push_nullifier(init_nullifier); } @@ -40,8 +38,7 @@ pub fn assert_initialization_matches_address_preimage_public(context: PublicCont let expected_init = compute_initialization_hash(context.selector(), context.get_args_hash()); assert(instance.initialization_hash == expected_init, "Initialization hash does not match"); assert( - (instance.deployer.is_zero()) | (instance.deployer == context.msg_sender()), - "Initializer address is not the contract deployer", + (instance.deployer.is_zero()) | (instance.deployer == context.msg_sender()), "Initializer address is not the contract deployer" ); } @@ -51,17 +48,13 @@ pub fn assert_initialization_matches_address_preimage_private(context: PrivateCo let expected_init = compute_initialization_hash(context.selector(), context.get_args_hash()); assert(instance.initialization_hash == expected_init, "Initialization hash does not match"); assert( - (instance.deployer.is_zero()) | (instance.deployer == context.msg_sender()), - "Initializer address is not the contract deployer", + (instance.deployer.is_zero()) | (instance.deployer == context.msg_sender()), "Initializer address is not the contract deployer" ); } -pub fn compute_initialization_hash( - init_selector: FunctionSelector, - init_args_hash: Field, -) -> Field { +pub fn compute_initialization_hash(init_selector: FunctionSelector, init_args_hash: Field) -> Field { poseidon2_hash_with_separator( [init_selector.to_field(), init_args_hash], - GENERATOR_INDEX__CONSTRUCTOR, + GENERATOR_INDEX__CONSTRUCTOR ) } diff --git a/noir-projects/aztec-nr/aztec/src/keys/constants.nr b/noir-projects/aztec-nr/aztec/src/keys/constants.nr index 2d465369fed..80964780b47 100644 --- a/noir-projects/aztec-nr/aztec/src/keys/constants.nr +++ b/noir-projects/aztec-nr/aztec/src/keys/constants.nr @@ -1,7 +1,4 @@ -use dep::protocol_types::constants::{ - GENERATOR_INDEX__NSK_M, GENERATOR_INDEX__IVSK_M, GENERATOR_INDEX__OVSK_M, - GENERATOR_INDEX__TSK_M, -}; +use dep::protocol_types::constants::{GENERATOR_INDEX__NSK_M, GENERATOR_INDEX__IVSK_M, GENERATOR_INDEX__OVSK_M, GENERATOR_INDEX__TSK_M}; // Note: In fetch_key_from_registry we expect that the shared mutable slot is index * 2 + 1 for the x coordinate and // index * 2 + 2 for the y coordinate. For example, the npk_m x coordinates will be stored in a map at storage slot diff --git a/noir-projects/aztec-nr/aztec/src/keys/getters/mod.nr b/noir-projects/aztec-nr/aztec/src/keys/getters/mod.nr index 52502eed6bf..81be552bed0 100644 --- a/noir-projects/aztec-nr/aztec/src/keys/getters/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/keys/getters/mod.nr @@ -1,9 +1,7 @@ use dep::protocol_types::{address::AztecAddress, public_keys::PublicKeys}; use crate::{ - oracle::{ - keys::get_public_keys_and_partial_address, - key_validation_request::get_key_validation_request, - }, keys::constants::{NULLIFIER_INDEX, OUTGOING_INDEX}, + oracle::{keys::get_public_keys_and_partial_address, key_validation_request::get_key_validation_request}, + keys::constants::{NULLIFIER_INDEX, OUTGOING_INDEX} }; mod test; @@ -23,12 +21,11 @@ pub unconstrained fn get_ovsk_app(ovpk_m_hash: Field) -> Field { // keys at once since the constraints for reading them all are actually fewer than if we read them one at a time - any // read keys that are not required by the caller can simply be discarded. pub fn get_public_keys(account: AztecAddress) -> PublicKeys { - let (hinted_canonical_public_keys, partial_address) = - unsafe { get_public_keys_and_partial_address(account) }; + let (hinted_canonical_public_keys, partial_address) = unsafe { + get_public_keys_and_partial_address(account) + }; assert_eq( - account, - AztecAddress::compute(hinted_canonical_public_keys.hash(), partial_address), - "Invalid public keys hint for address", + account, AztecAddress::compute(hinted_canonical_public_keys.hash(), partial_address), "Invalid public keys hint for address" ); hinted_canonical_public_keys diff --git a/noir-projects/aztec-nr/aztec/src/keys/getters/test.nr b/noir-projects/aztec-nr/aztec/src/keys/getters/test.nr index 9a5ee36603c..a0147001bed 100644 --- a/noir-projects/aztec-nr/aztec/src/keys/getters/test.nr +++ b/noir-projects/aztec-nr/aztec/src/keys/getters/test.nr @@ -18,9 +18,7 @@ unconstrained fn test_get_public_keys_unknown() { // Instead of querying for some unknown account, which would result in the oracle erroring out, we mock a bad oracle // response to check that the circuit properly checks the address derivation. - let _ = OracleMock::mock("getPublicKeysAndPartialAddress") - .returns([0; KEY_ORACLE_RESPONSE_LENGTH]) - .times(1); + let _ = OracleMock::mock("getPublicKeysAndPartialAddress").returns([0; KEY_ORACLE_RESPONSE_LENGTH]).times(1); let _ = get_public_keys(account.address); } diff --git a/noir-projects/aztec-nr/aztec/src/keys/point_to_symmetric_key.nr b/noir-projects/aztec-nr/aztec/src/keys/point_to_symmetric_key.nr index 7c55cbe548b..75c5e301b61 100644 --- a/noir-projects/aztec-nr/aztec/src/keys/point_to_symmetric_key.nr +++ b/noir-projects/aztec-nr/aztec/src/keys/point_to_symmetric_key.nr @@ -1,6 +1,4 @@ -use dep::protocol_types::{ - constants::GENERATOR_INDEX__SYMMETRIC_KEY, scalar::Scalar, point::Point, utils::arr_copy_slice, -}; +use dep::protocol_types::{constants::GENERATOR_INDEX__SYMMETRIC_KEY, scalar::Scalar, point::Point, utils::arr_copy_slice}; use crate::utils::point::point_to_bytes; use std::{hash::sha256, embedded_curve_ops::multi_scalar_mul}; @@ -21,12 +19,12 @@ unconstrained fn test_point_to_symmetric_key_matches_noir() { // Value taken from "derive shared secret" test in encrypt_buffer.test.ts let secret = Scalar { lo: 0x00000000000000000000000000000000649e7ca01d9de27b21624098b897babd, - hi: 0x0000000000000000000000000000000023b3127c127b1f29a7adff5cccf8fb06, + hi: 0x0000000000000000000000000000000023b3127c127b1f29a7adff5cccf8fb06 }; let point = Point { x: 0x2688431c705a5ff3e6c6f2573c9e3ba1c1026d2251d0dbbf2d810aa53fd1d186, y: 0x1e96887b117afca01c00468264f4f80b5bb16d94c1808a448595f115556e5c8e, - is_infinite: false, + is_infinite: false }; let key = point_to_symmetric_key(secret, point); @@ -35,7 +33,7 @@ unconstrained fn test_point_to_symmetric_key_matches_noir() { // --> Run the test with AZTEC_GENERATE_TEST_DATA=1 flag to update test data. let key_from_typescript = [ 251, 232, 177, 34, 2, 174, 35, 92, 165, 118, 168, 3, 153, 140, 46, 210, 203, 154, 184, 158, - 236, 33, 95, 77, 93, 120, 72, 88, 190, 209, 64, 159, + 236, 33, 95, 77, 93, 120, 72, 88, 190, 209, 64, 159 ]; assert_eq(key, key_from_typescript); } diff --git a/noir-projects/aztec-nr/aztec/src/macros/dispatch/mod.nr b/noir-projects/aztec-nr/aztec/src/macros/dispatch/mod.nr index e2ac081fb88..cc844efc54c 100644 --- a/noir-projects/aztec-nr/aztec/src/macros/dispatch/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/macros/dispatch/mod.nr @@ -4,12 +4,12 @@ use std::panic; /// Returns an `fn public_dispatch(...)` function for the given module that's assumed to be an Aztec contract. pub comptime fn generate_public_dispatch(m: Module) -> Quoted { let functions = m.functions(); - let functions = - functions.filter(|function: FunctionDefinition| function.has_named_attribute("public")); + let functions = functions.filter(|function: FunctionDefinition| function.has_named_attribute("public")); let unit = get_type::<()>(); - let ifs = functions.map(|function: FunctionDefinition| { + let ifs = functions.map( + |function: FunctionDefinition| { let name = function.name(); let parameters = function.parameters(); let return_type = function.return_type(); @@ -78,7 +78,8 @@ pub comptime fn generate_public_dispatch(m: Module) -> Quoted { } }; if_ - }); + } + ); if ifs.len() == 0 { // No dispatch function if there are no public functions @@ -118,10 +119,12 @@ comptime fn size_in_fields(typ: Type) -> u32 { } comptime fn array_size_in_fields(typ: Type) -> Option { - typ.as_array().and_then(|typ: (Type, Type)| { + typ.as_array().and_then( + |typ: (Type, Type)| { let (typ, element_size) = typ; element_size.as_constant().map(|x: u32| { x * size_in_fields(typ) }) - }) + } + ) } comptime fn bool_size_in_fields(typ: Type) -> Option { @@ -157,24 +160,28 @@ comptime fn str_size_in_fields(typ: Type) -> Option { } comptime fn struct_size_in_fields(typ: Type) -> Option { - typ.as_struct().map(|typ: (StructDefinition, [Type])| { + typ.as_struct().map( + |typ: (StructDefinition, [Type])| { let struct_type = typ.0; let mut size = 0; for field in struct_type.fields() { size += size_in_fields(field.1); } size - }) + } + ) } comptime fn tuple_size_in_fields(typ: Type) -> Option { - typ.as_tuple().map(|types: [Type]| { + typ.as_tuple().map( + |types: [Type]| { let mut size = 0; for typ in types { size += size_in_fields(typ); } size - }) + } + ) } comptime fn get_type() -> Type { diff --git a/noir-projects/aztec-nr/aztec/src/macros/functions/interfaces.nr b/noir-projects/aztec-nr/aztec/src/macros/functions/interfaces.nr index d2800f8fae4..2d79e1f4516 100644 --- a/noir-projects/aztec-nr/aztec/src/macros/functions/interfaces.nr +++ b/noir-projects/aztec-nr/aztec/src/macros/functions/interfaces.nr @@ -1,19 +1,15 @@ use std::{ meta::{unquote, type_of}, collections::umap::UHashMap, - hash::{BuildHasherDefault, poseidon2::Poseidon2Hasher}, -}; -use crate::macros::utils::{ - get_fn_visibility, is_fn_view, is_fn_private, add_to_field_slice, compute_fn_selector, - is_fn_public, + hash::{BuildHasherDefault, poseidon2::Poseidon2Hasher} }; +use crate::macros::utils::{get_fn_visibility, is_fn_view, is_fn_private, add_to_field_slice, compute_fn_selector, is_fn_public}; comptime mut global STUBS: UHashMap> = UHashMap::default(); pub(crate) comptime fn create_fn_abi_export(f: FunctionDefinition) -> Quoted { let name = f.name(); - let mut parameters = - f.parameters().map(|(name, typ): (Quoted, Type)| { quote { $name: $typ } }).join(quote {,}); + let mut parameters = f.parameters().map(|(name, typ): (Quoted, Type)| { quote { $name: $typ } }).join(quote {,}); let parameters_struct_name = f"{name}_parameters".quoted_contents(); let parameters = quote { @@ -77,7 +73,7 @@ pub comptime fn stub_fn(f: FunctionDefinition) -> Quoted { $args_hasher $appended_arg } - }, + } ); let args_hash_name = if fn_visibility == quote { private } { @@ -95,8 +91,7 @@ pub comptime fn stub_fn(f: FunctionDefinition) -> Quoted { args_acc }; - let fn_parameters_list = - fn_parameters.map(|(name, typ): (Quoted, Type)| { quote { $name: $typ } }).join(quote {,}); + let fn_parameters_list = fn_parameters.map(|(name, typ): (Quoted, Type)| { quote { $name: $typ } }).join(quote {,}); let fn_name_str = fn_name.as_str_quote(); @@ -108,8 +103,7 @@ pub comptime fn stub_fn(f: FunctionDefinition) -> Quoted { quote { $fn_name_len, $fn_return_type } }; - let call_interface_name = f"dep::aztec::context::call_interfaces::{fn_visibility_capitalized}{is_static_call_capitalized}{is_void_capitalized}CallInterface" - .quoted_contents(); + let call_interface_name = f"dep::aztec::context::call_interfaces::{fn_visibility_capitalized}{is_static_call_capitalized}{is_void_capitalized}CallInterface".quoted_contents(); let fn_selector: Field = compute_fn_selector(f); diff --git a/noir-projects/aztec-nr/aztec/src/macros/functions/mod.nr b/noir-projects/aztec-nr/aztec/src/macros/functions/mod.nr index b60212dc10f..89695de75bc 100644 --- a/noir-projects/aztec-nr/aztec/src/macros/functions/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/macros/functions/mod.nr @@ -3,7 +3,7 @@ mod interfaces; use std::meta::type_of; use super::utils::{ modify_fn_body, is_fn_private, get_fn_visibility, is_fn_view, is_fn_initializer, is_fn_internal, - fn_has_noinitcheck, add_to_hasher, module_has_storage, module_has_initializer, + fn_has_noinitcheck, add_to_hasher, module_has_storage, module_has_initializer }; use protocol_types::meta::flatten_to_fields; @@ -64,8 +64,7 @@ pub comptime fn noinitcheck(_f: FunctionDefinition) { comptime fn create_assert_correct_initializer_args(f: FunctionDefinition) -> Quoted { let fn_visibility = get_fn_visibility(f); - f"dep::aztec::initializer::assert_initialization_matches_address_preimage_{fn_visibility}(context);" - .quoted_contents() + f"dep::aztec::initializer::assert_initialization_matches_address_preimage_{fn_visibility}(context);".quoted_contents() } comptime fn create_mark_as_initialized(f: FunctionDefinition) -> Quoted { @@ -75,8 +74,7 @@ comptime fn create_mark_as_initialized(f: FunctionDefinition) -> Quoted { comptime fn create_init_check(f: FunctionDefinition) -> Quoted { let fn_visibility = get_fn_visibility(f); - f"dep::aztec::initializer::assert_is_initialized_{fn_visibility}(&mut context);" - .quoted_contents() + f"dep::aztec::initializer::assert_is_initialized_{fn_visibility}(&mut context);".quoted_contents() } /// Private functions are executed client-side and preserve privacy. @@ -93,11 +91,13 @@ pub comptime fn private(f: FunctionDefinition) -> Quoted { // First we change the function signature so that it also receives `PrivateContextInputs`, which contain information // about the execution context (e.g. the caller). let original_params = f.parameters(); - f.set_parameters(&[( - quote { inputs }, - quote { crate::context::inputs::private_context_inputs::PrivateContextInputs }.as_type(), - )] - .append(original_params)); + f.set_parameters( + &[ + ( + quote { inputs }, quote { crate::context::inputs::private_context_inputs::PrivateContextInputs }.as_type() + ) + ].append(original_params) + ); let mut body = f.body().as_block().unwrap(); @@ -116,7 +116,7 @@ pub comptime fn private(f: FunctionDefinition) -> Quoted { $args_hasher $appended_arg } - }, + } ); let context_creation = quote { let mut context = dep::aztec::context::private_context::PrivateContext::new(inputs, args_hasher.hash()); }; @@ -164,11 +164,9 @@ pub comptime fn private(f: FunctionDefinition) -> Quoted { // The original return value is passed to a second args hasher which the context receives. let (body_without_return, last_body_expr) = body.pop_back(); let return_value = last_body_expr.quoted(); - let return_value_assignment = - quote { let $return_value_var_name: $return_value_type = $return_value; }; + let return_value_assignment = quote { let $return_value_var_name: $return_value_type = $return_value; }; let return_hasher_name = quote { return_hasher }; - let return_value_into_hasher = - add_to_hasher(return_hasher_name, return_value_var_name, return_value_type); + let return_value_into_hasher = add_to_hasher(return_hasher_name, return_value_var_name, return_value_type); body = body_without_return; @@ -215,8 +213,7 @@ pub comptime fn private(f: FunctionDefinition) -> Quoted { f.set_body(modified_body); f.add_attribute("recursive"); f.set_return_type( - quote { dep::protocol_types::abis::private_circuit_public_inputs::PrivateCircuitPublicInputs } - .as_type(), + quote { dep::protocol_types::abis::private_circuit_public_inputs::PrivateCircuitPublicInputs }.as_type() ); f.set_return_data(); @@ -243,9 +240,7 @@ comptime fn transform_public(f: FunctionDefinition) -> Quoted { // Public functions undergo a lot of transformations from their Aztec.nr form. let original_params = f.parameters(); - let args_len = original_params - .map(|(name, typ): (Quoted, Type)| flatten_to_fields(name, typ, &[]).0.len()) - .fold(0, |acc: u32, val: u32| acc + val); + let args_len = original_params.map(|(name, typ): (Quoted, Type)| flatten_to_fields(name, typ, &[]).0.len()).fold(0, |acc: u32, val: u32| acc + val); // Unlike in the private case, in public the `context` does not need to receive the hash of the original params. let context_creation = quote { let mut context = dep::aztec::context::public_context::PublicContext::new(|| { diff --git a/noir-projects/aztec-nr/aztec/src/macros/mod.nr b/noir-projects/aztec-nr/aztec/src/macros/mod.nr index cc9b860f528..88c4034caac 100644 --- a/noir-projects/aztec-nr/aztec/src/macros/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/macros/mod.nr @@ -19,14 +19,15 @@ use dispatch::generate_public_dispatch; /// Note: This is a module annotation, so the returned quote gets injected inside the module (contract) itself. pub comptime fn aztec(m: Module) -> Quoted { let interface = generate_contract_interface(m); - let unconstrained_functions = m.functions().filter(|f: FunctionDefinition| { + let unconstrained_functions = m.functions().filter( + |f: FunctionDefinition| { f.is_unconstrained() & !f.has_named_attribute("test") & !f.has_named_attribute("public") - }); + } + ); for f in unconstrained_functions { transform_unconstrained(f); } - let compute_note_hash_and_optionally_a_nullifier = - generate_compute_note_hash_and_optionally_a_nullifier(); + let compute_note_hash_and_optionally_a_nullifier = generate_compute_note_hash_and_optionally_a_nullifier(); let note_exports = generate_note_exports(); let public_dispatch = generate_public_dispatch(m); quote { @@ -167,9 +168,9 @@ comptime fn generate_note_exports() -> Quoted { let notes = NOTES.values(); // Second value in each tuple is `note_serialized_len` and that is ignored here because it's only used when // generating the `compute_note_hash_and_optionally_a_nullifier` function. - notes - .map(|(s, _, note_type_id, fields): (StructDefinition, u32, Field, [(Quoted, u32, bool)])| { + notes.map( + |(s, _, note_type_id, fields): (StructDefinition, u32, Field, [(Quoted, u32, bool)])| { generate_note_export(s, note_type_id, fields) - }) - .join(quote {}) + } + ).join(quote {}) } diff --git a/noir-projects/aztec-nr/aztec/src/macros/notes/mod.nr b/noir-projects/aztec-nr/aztec/src/macros/notes/mod.nr index edbf60dc17b..85866061bd7 100644 --- a/noir-projects/aztec-nr/aztec/src/macros/notes/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/macros/notes/mod.nr @@ -1,6 +1,6 @@ use std::{ meta::{type_of, unquote, typ::fresh_type_variable}, collections::umap::UHashMap, - hash::{BuildHasherDefault, poseidon2::Poseidon2Hasher}, + hash::{BuildHasherDefault, poseidon2::Poseidon2Hasher} }; use protocol_types::meta::{flatten_to_fields, pack_from_fields}; use crate::note::{note_header::NoteHeader, note_getter_options::PropertySelector}; @@ -25,7 +25,7 @@ comptime fn compute_note_type_id(name: Quoted) -> Field { let hash = protocol_types::hash::poseidon2_hash_bytes(bytes); let hash_bytes = hash.to_be_bytes::<4>(); protocol_types::utils::field::field_from_bytes(hash_bytes, true) - }, + } ) } @@ -65,15 +65,14 @@ comptime fn generate_note_interface( s: StructDefinition, note_type_id: Field, indexed_fixed_fields: [(Quoted, Type, u32)], - indexed_nullable_fields: [(Quoted, Type, u32)], + indexed_nullable_fields: [(Quoted, Type, u32)] ) -> (Quoted, u32) { let name = s.name(); let typ = s.as_type(); // First we compute note content serialization. We do that by passing the whole note struct // to the `flatten_to_fields(...)` and omitting the header. - let (content_fields_list, content_aux_vars_list) = - flatten_to_fields(quote { self }, typ, &[quote {self.header}]); + let (content_fields_list, content_aux_vars_list) = flatten_to_fields(quote { self }, typ, &[quote {self.header}]); // If there are `aux_vars` we need to join them with `;` and add a trailing `;` to the joined string. let content_aux_vars = if content_aux_vars_list.len() > 0 { @@ -90,27 +89,24 @@ comptime fn generate_note_interface( typ, quote { value }, 0, - &[(quote {header}, quote { aztec::note::note_header::NoteHeader::empty() })], + &[(quote {header}, quote { aztec::note::note_header::NoteHeader::empty() })] ); // Second we compute quotes for MSM // `compute_note_hash()` is computed over all the fields so we need to merge fixed and nullable. let merged_fields = indexed_fixed_fields.append(indexed_nullable_fields); // Now we prefix each of the merged fields with `self.` since they refer to the struct members here. - let prefixed_merged_fields = merged_fields.map(|(name, typ, index): (Quoted, Type, u32)| { + let prefixed_merged_fields = merged_fields.map( + |(name, typ, index): (Quoted, Type, u32)| { (quote { self.$name }, typ, index) - }); - let (new_generators_list, new_scalars_list, _, new_aux_vars) = - generate_multi_scalar_mul(prefixed_merged_fields); + } + ); + let (new_generators_list, new_scalars_list, _, new_aux_vars) = generate_multi_scalar_mul(prefixed_merged_fields); - let new_generators = - new_generators_list.push_back(quote { aztec::generators::G_slot }).join(quote {,}); - let new_scalars = new_scalars_list - .push_back(quote { std::hash::from_field_unsafe(self.header.storage_slot) }) - .join(quote {,}); + let new_generators = new_generators_list.push_back(quote { aztec::generators::G_slot }).join(quote {,}); + let new_scalars = new_scalars_list.push_back(quote { std::hash::from_field_unsafe(self.header.storage_slot) }).join(quote {,}); - ( - quote { + (quote { impl aztec::note::note_interface::NoteInterface<$content_len> for $name { fn to_be_bytes(self, storage_slot: Field) -> [u8; $content_len * 32 + 64] { let serialized_note = self.serialize_content(); @@ -164,9 +160,7 @@ comptime fn generate_note_interface( point.x } } - }, - content_len, - ) + }, content_len) } /// Generates note properties struct for a given note struct `s`. @@ -199,9 +193,7 @@ comptime fn generate_note_properties(s: StructDefinition) -> Quoted { let non_header_fields = s.fields().filter(|(_, typ): (Quoted, Type)| typ != note_header_type); - let properties_types = non_header_fields - .map(|(name, _): (Quoted, Type)| { quote { $name: $property_selector_type } }) - .join(quote {,}); + let properties_types = non_header_fields.map(|(name, _): (Quoted, Type)| { quote { $name: $property_selector_type } }).join(quote {,}); // TODO #8694: Properly handle non-field types https://github.com/AztecProtocol/aztec-packages/issues/8694 let mut properties_list = &[]; @@ -254,7 +246,7 @@ comptime fn generate_note_properties(s: StructDefinition) -> Quoted { pub(crate) comptime fn generate_note_export( s: StructDefinition, note_type_id: Field, - fields: [(Quoted, u32, bool)], + fields: [(Quoted, u32, bool)] ) -> Quoted { let name = s.name(); let mut hasher = Poseidon2Hasher::default(); @@ -302,9 +294,7 @@ pub(crate) comptime fn generate_note_export( /// ] /// args_list: [amount: U128, npk_m_hash: Field, randomness: Field] /// aux_vars: [] -comptime fn generate_multi_scalar_mul( - indexed_fields: [(Quoted, Type, u32)], -) -> ([Quoted], [Quoted], [Quoted], Quoted) { +comptime fn generate_multi_scalar_mul(indexed_fields: [(Quoted, Type, u32)]) -> ([Quoted], [Quoted], [Quoted], Quoted) { let mut generators_list = &[]; let mut scalars_list = &[]; let mut args_list = &[]; @@ -388,31 +378,22 @@ comptime fn generate_multi_scalar_mul( comptime fn generate_setup_payload( s: StructDefinition, indexed_fixed_fields: [(Quoted, Type, u32)], - indexed_nullable_fields: [(Quoted, Type, u32)], + indexed_nullable_fields: [(Quoted, Type, u32)] ) -> (Quoted, Quoted) { let name = s.name(); let setup_payload_name = f"{name}SetupPayload".quoted_contents(); // First we get the MSM related quotes - let (new_generators_list, new_scalars_list, new_args_list, new_aux_vars) = - generate_multi_scalar_mul(indexed_fixed_fields); - let new_args = &[quote {mut self}] - .append(new_args_list) - .push_back(quote { storage_slot: Field }) - .join(quote {,}); - let new_generators = - new_generators_list.push_back(quote { aztec::generators::G_slot }).join(quote {,}); - let new_scalars = new_scalars_list - .push_back(quote { std::hash::from_field_unsafe(storage_slot) }) - .join(quote {,}); + let (new_generators_list, new_scalars_list, new_args_list, new_aux_vars) = generate_multi_scalar_mul(indexed_fixed_fields); + let new_args = &[quote {mut self}].append(new_args_list).push_back(quote { storage_slot: Field }).join(quote {,}); + let new_generators = new_generators_list.push_back(quote { aztec::generators::G_slot }).join(quote {,}); + let new_scalars = new_scalars_list.push_back(quote { std::hash::from_field_unsafe(storage_slot) }).join(quote {,}); // Then the log plaintext ones let log_plaintext_length = indexed_fixed_fields.len() * 32 + 64; - let setup_log_plaintext = - get_setup_log_plaintext_body(s, log_plaintext_length, indexed_nullable_fields); + let setup_log_plaintext = get_setup_log_plaintext_body(s, log_plaintext_length, indexed_nullable_fields); - ( - quote { + (quote { struct $setup_payload_name { log_plaintext: [u8; $log_plaintext_length], hiding_point: aztec::protocol_types::point::Point @@ -439,9 +420,7 @@ comptime fn generate_setup_payload( Self { log_plaintext: [0; $log_plaintext_length], hiding_point: aztec::protocol_types::point::Point::empty() } } } - }, - setup_payload_name, - ) + }, setup_payload_name) } /// Generates setup log plaintext for a given note struct `s`. The setup log plaintext is computed by serializing @@ -451,15 +430,13 @@ comptime fn generate_setup_payload( comptime fn get_setup_log_plaintext_body( s: StructDefinition, log_plaintext_length: u32, - indexed_nullable_fields: [(Quoted, Type, u32)], + indexed_nullable_fields: [(Quoted, Type, u32)] ) -> Quoted { let name = s.name(); // Now we compute serialization of the fixed fields. We do that by passing the whole note struct // to the flatten_to_fields function but we omit the NoteHeader and the nullable fields. - let to_omit = indexed_nullable_fields.map(|(name, _, _): (Quoted, Type, u32)| name).push_back( - quote { header }, - ); + let to_omit = indexed_nullable_fields.map(|(name, _, _): (Quoted, Type, u32)| name).push_back(quote { header }); let (fields_list, aux_vars) = flatten_to_fields(quote { }, s.as_type(), to_omit); // If there are `aux_vars` we need to join them with `;` and add a trailing `;` to the joined string. @@ -529,7 +506,7 @@ comptime fn get_setup_log_plaintext_body( comptime fn generate_finalization_payload( s: StructDefinition, indexed_fixed_fields: [(Quoted, Type, u32)], - indexed_nullable_fields: [(Quoted, Type, u32)], + indexed_nullable_fields: [(Quoted, Type, u32)] ) -> (Quoted, Quoted) { let name = s.name(); let finalization_payload_name = f"{name}FinalizationPayload".quoted_contents(); @@ -537,9 +514,7 @@ comptime fn generate_finalization_payload( // We compute serialization of the nullable fields which are to be emitted as an unencrypted log. We do that by // passing the whole note struct to the `flatten_to_fields(...)` function but we omit the `NoteHeader` and // the fixed fields. - let to_omit = indexed_fixed_fields.map(|(name, _, _): (Quoted, Type, u32)| name).push_back( - quote { header }, - ); + let to_omit = indexed_fixed_fields.map(|(name, _, _): (Quoted, Type, u32)| name).push_back(quote { header }); let (fields_list, aux_vars) = flatten_to_fields(quote { }, s.as_type(), to_omit); // If there are `aux_vars` we need to join them with `;` and add a trailing `;` to the joined string. @@ -555,15 +530,13 @@ comptime fn generate_finalization_payload( let fields = fields_list.join(quote {,}); // Now we compute quotes relevant to the multi-scalar multiplication. - let (generators_list, scalars_list, args_list, msm_aux_vars) = - generate_multi_scalar_mul(indexed_nullable_fields); + let (generators_list, scalars_list, args_list, msm_aux_vars) = generate_multi_scalar_mul(indexed_nullable_fields); let generators = generators_list.join(quote {,}); let scalars = scalars_list.join(quote {,}); let args = args_list.join(quote {,}); - ( - quote { + (quote { struct $finalization_payload_name { log: [Field; $log_length], note_hash: Field, @@ -590,9 +563,7 @@ comptime fn generate_finalization_payload( Self { log: [0; $log_length], note_hash: 0 } } } - }, - finalization_payload_name, - ) + }, finalization_payload_name) } /// Generates `PartialNote` implementation for a given note struct `s`. @@ -609,11 +580,7 @@ comptime fn generate_finalization_payload( /// } /// } /// ``` -comptime fn generate_partial_note_impl( - s: StructDefinition, - setup_payload_name: Quoted, - finalization_payload_name: Quoted, -) -> Quoted { +comptime fn generate_partial_note_impl(s: StructDefinition, setup_payload_name: Quoted, finalization_payload_name: Quoted) -> Quoted { let name = s.name(); quote { impl aztec::note::note_interface::PartialNote<$setup_payload_name, $finalization_payload_name> for $name { @@ -635,7 +602,7 @@ comptime fn register_note( note_serialized_len: u32, note_type_id: Field, fixed_fields: [(Quoted, Type, u32)], - nullable_fields: [(Quoted, Type, u32)], + nullable_fields: [(Quoted, Type, u32)] ) { let mut fields = &[]; for field in fixed_fields { @@ -647,7 +614,10 @@ comptime fn register_note( fields = fields.push_back((name, index, true)); } - NOTES.insert(note.as_type(), (note, note_serialized_len, note_type_id, fields)); + NOTES.insert( + note.as_type(), + (note, note_serialized_len, note_type_id, fields) + ); } /// Separates note struct members into fixed and nullable ones. It also stores the index of where each struct member @@ -655,7 +625,7 @@ comptime fn register_note( /// An example of a struct member occupying multiple fields is `amount` in `TokenNote` that uses `U128` type. comptime fn index_note_fields( s: StructDefinition, - nullable_fields: [Quoted], + nullable_fields: [Quoted] ) -> ([(Quoted, Type, u32)], [(Quoted, Type, u32)]) { let mut indexed_fixed_fields: [(Quoted, Type, u32)] = &[]; let mut indexed_nullable_fields = &[]; @@ -706,24 +676,16 @@ pub comptime fn partial_note(s: StructDefinition, nullable_fields: [Quoted]) -> let note_properties = generate_note_properties(s); let note_type_id = compute_note_type_id(s.name()); - let (setup_payload_impl, setup_payload_name) = - generate_setup_payload(s, indexed_fixed_fields, indexed_nullable_fields); - let (finalization_payload_impl, finalization_payload_name) = - generate_finalization_payload(s, indexed_fixed_fields, indexed_nullable_fields); - let (note_interface_impl, note_serialized_len) = generate_note_interface( - s, - note_type_id, - indexed_fixed_fields, - indexed_nullable_fields, - ); - let partial_note_impl = - generate_partial_note_impl(s, setup_payload_name, finalization_payload_name); + let (setup_payload_impl, setup_payload_name) = generate_setup_payload(s, indexed_fixed_fields, indexed_nullable_fields); + let (finalization_payload_impl, finalization_payload_name) = generate_finalization_payload(s, indexed_fixed_fields, indexed_nullable_fields); + let (note_interface_impl, note_serialized_len) = generate_note_interface(s, note_type_id, indexed_fixed_fields, indexed_nullable_fields); + let partial_note_impl = generate_partial_note_impl(s, setup_payload_name, finalization_payload_name); register_note( s, note_serialized_len, note_type_id, indexed_fixed_fields, - indexed_nullable_fields, + indexed_nullable_fields ); quote { @@ -749,18 +711,13 @@ pub comptime fn note(s: StructDefinition) -> Quoted { let note_properties = generate_note_properties(s); let note_type_id = compute_note_type_id(s.name()); - let (note_interface_impl, note_serialized_len) = generate_note_interface( - s, - note_type_id, - indexed_fixed_fields, - indexed_nullable_fields, - ); + let (note_interface_impl, note_serialized_len) = generate_note_interface(s, note_type_id, indexed_fixed_fields, indexed_nullable_fields); register_note( s, note_serialized_len, note_type_id, indexed_fixed_fields, - indexed_nullable_fields, + indexed_nullable_fields ); quote { @@ -780,17 +737,10 @@ pub comptime fn note_custom_interface(s: StructDefinition) -> Quoted { let note_properties = generate_note_properties(s); let note_type_id = compute_note_type_id(s.name()); let serialized_len_type = fresh_type_variable(); - let note_interface_impl = s.as_type().get_trait_impl( - quote { crate::note::note_interface::NoteInterface<$serialized_len_type> } - .as_trait_constraint(), - ); + let note_interface_impl = s.as_type().get_trait_impl(quote { crate::note::note_interface::NoteInterface<$serialized_len_type> }.as_trait_constraint()); let name = s.name(); - let note_serialized_len = note_interface_impl - .expect(f"Note {name} must implement NoteInterface trait") - .trait_generic_args()[0] - .as_constant() - .unwrap(); + let note_serialized_len = note_interface_impl.expect(f"Note {name} must implement NoteInterface trait").trait_generic_args()[0].as_constant().unwrap(); let (indexed_fixed_fields, indexed_nullable_fields) = index_note_fields(s, &[]); register_note( @@ -798,7 +748,7 @@ pub comptime fn note_custom_interface(s: StructDefinition) -> Quoted { note_serialized_len, note_type_id, indexed_fixed_fields, - indexed_nullable_fields, + indexed_nullable_fields ); quote { diff --git a/noir-projects/aztec-nr/aztec/src/macros/storage/mod.nr b/noir-projects/aztec-nr/aztec/src/macros/storage/mod.nr index c9535db0716..9126e3e076d 100644 --- a/noir-projects/aztec-nr/aztec/src/macros/storage/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/macros/storage/mod.nr @@ -1,7 +1,4 @@ -use std::{ - collections::umap::UHashMap, hash::{BuildHasherDefault, poseidon2::Poseidon2Hasher}, - meta::unquote, -}; +use std::{collections::umap::UHashMap, hash::{BuildHasherDefault, poseidon2::Poseidon2Hasher}, meta::unquote}; use super::utils::get_serialized_size; use super::utils::is_note; @@ -30,8 +27,7 @@ pub comptime fn storage(s: StructDefinition) -> Quoted { //let context_generic = s.add_generic("Context"); for field in s.fields() { let (name, typ) = field; - let (storage_field_constructor, serialized_size) = - generate_storage_field_constructor(typ, quote { $slot }, false); + let (storage_field_constructor, serialized_size) = generate_storage_field_constructor(typ, quote { $slot }, false); storage_vars_constructors = storage_vars_constructors.push_back(quote { $name: $storage_field_constructor }); // We have `Storable` in a separate `.nr` file instead of defining it in the last quote of this function @@ -101,22 +97,16 @@ pub comptime fn storage_no_init(_s: StructDefinition) { /// Returns the expression required to initialize a state variable with a given slot, along with its serialization size, /// i.e. how many contiguous storage slots the variable requires. -comptime fn generate_storage_field_constructor( - typ: Type, - slot: Quoted, - parent_is_map: bool, -) -> (Quoted, u32) { +comptime fn generate_storage_field_constructor(typ: Type, slot: Quoted, parent_is_map: bool) -> (Quoted, u32) { assert( - typ.as_struct().is_some(), - "Storage containers must be generic structs of the form `Container<_, Context>`, or Map", + typ.as_struct().is_some(), "Storage containers must be generic structs of the form `Container<_, Context>`, or Map" ); let (container_struct, generics) = typ.as_struct().unwrap(); let struct_name = container_struct.name(); if is_storage_map(typ) { // Map state variables recursively initialize their contents - this includes nested maps. - let (value_constructor, _) = - generate_storage_field_constructor(generics[1], quote { slot }, true); + let (value_constructor, _) = generate_storage_field_constructor(generics[1], quote { slot }, true); (quote { $struct_name::new(context, $slot, | context, slot | { $value_constructor }) }, 1) } else { let (container_struct, container_struct_generics) = typ.as_struct().unwrap(); @@ -163,9 +153,7 @@ comptime fn is_storage_map(typ: Type) -> bool { } comptime fn add_context_generic(typ: Type, context_generic: Type) -> Type { - let (def, mut generics) = typ.as_struct().expect( - f"Storage containers must be generic structs of the form `Container<..., Context>`", - ); + let (def, mut generics) = typ.as_struct().expect(f"Storage containers must be generic structs of the form `Container<..., Context>`"); let name = def.name(); if is_storage_map(typ) { diff --git a/noir-projects/aztec-nr/aztec/src/macros/utils.nr b/noir-projects/aztec-nr/aztec/src/macros/utils.nr index 7eb80d1c650..703b1e3d391 100644 --- a/noir-projects/aztec-nr/aztec/src/macros/utils.nr +++ b/noir-projects/aztec-nr/aztec/src/macros/utils.nr @@ -37,13 +37,16 @@ pub(crate) comptime fn fn_has_noinitcheck(f: FunctionDefinition) -> bool { /// Takes a function body as a collection of expressions, and alters it by prepending and appending quoted values. pub(crate) comptime fn modify_fn_body(body: [Expr], prepend: Quoted, append: Quoted) -> Expr { // We need to quote the body before we can alter its contents, so we fold it by quoting each expression. - let mut body_quote = body.fold(quote {}, |full_quote: Quoted, expr: Expr| { + let mut body_quote = body.fold( + quote {}, + |full_quote: Quoted, expr: Expr| { let expr_quote = expr.quoted(); quote { $full_quote $expr_quote } - }); + } + ); body_quote = quote { { $prepend @@ -74,9 +77,7 @@ pub(crate) comptime fn add_to_field_slice(slice_name: Quoted, name: Quoted, typ: $slice_name = $slice_name.append($name.as_bytes().map(| byte: u8 | byte as Field).as_slice()); } } else { - panic( - f"Cannot add to slice: unsupported type {typ} variable {name}", - ) + panic(f"Cannot add to slice: unsupported type {typ} variable {name}") } } @@ -100,9 +101,7 @@ pub(crate) comptime fn add_to_hasher(hasher_name: Quoted, name: Quoted, typ: Typ $hasher_name.add_multiple($name.as_bytes().map(| byte: u8 | byte as Field)); } } else { - panic( - f"Cannot add to hasher: unsupported type {typ} of variable {name}", - ) + panic(f"Cannot add to hasher: unsupported type {typ} of variable {name}") } } @@ -129,8 +128,7 @@ comptime fn signature_of_type(typ: Type) -> Quoted { f"[{element_typ_quote};{array_len}]".quoted_contents() } else if typ.as_struct().is_some() { let (s, _) = typ.as_struct().unwrap(); - let field_signatures = - s.fields().map(|(_, typ): (Quoted, Type)| { signature_of_type(typ) }).join(quote {,}); + let field_signatures = s.fields().map(|(_, typ): (Quoted, Type)| { signature_of_type(typ) }).join(quote {,}); f"({field_signatures})".quoted_contents() } else if typ.as_tuple().is_some() { // Note that tuples are handled the same way as structs @@ -164,7 +162,7 @@ impl AsStrQuote for Quoted { quote { let signature_as_array: [u8; $total_len] = $acc.as_array(); signature_as_array.as_str_unchecked() - }, + } ); quote { $result } } @@ -178,8 +176,7 @@ pub(crate) comptime fn compute_fn_selector(f: FunctionDefinition) -> Field { // // The signature will be "foo(Field,AztecAddress)". let fn_name = f.name(); - let args_signatures = - f.parameters().map(|(_, typ): (Quoted, Type)| { signature_of_type(typ) }).join(quote {,}); + let args_signatures = f.parameters().map(|(_, typ): (Quoted, Type)| { signature_of_type(typ) }).join(quote {,}); let signature_quote = quote { $fn_name($args_signatures) }; let signature_str_quote = signature_quote.as_str_quote(); @@ -200,12 +197,11 @@ pub(crate) comptime fn compute_event_selector(s: StructDefinition) -> Field { // // The signature will be "Foo(Field,AztecAddress)". let event_name = s.name(); - let args_signatures = s - .fields() - .map(|(_, typ): (Quoted, Type)| { + let args_signatures = s.fields().map( + |(_, typ): (Quoted, Type)| { signature_of_type(typ) // signature_of_type can handle structs, so this supports nested structs - }) - .join(quote {,}); + } + ).join(quote {,}); let signature_quote = quote { $event_name($args_signatures) }; let signature_str_quote = signature_quote.as_str_quote(); @@ -217,22 +213,17 @@ pub(crate) comptime fn compute_event_selector(s: StructDefinition) -> Field { pub(crate) comptime fn get_serialized_size(typ: Type) -> u32 { let any = fresh_type_variable(); - let maybe_serialize_impl = - typ.get_trait_impl(quote { protocol_types::traits::Serialize<$any> }.as_trait_constraint()); + let maybe_serialize_impl = typ.get_trait_impl(quote { protocol_types::traits::Serialize<$any> }.as_trait_constraint()); - maybe_serialize_impl - .expect( - f"Attempted to fetch serialization length, but {typ} does not implement the Serialize trait", - ) - .trait_generic_args()[0] - .as_constant() - .unwrap() + maybe_serialize_impl.expect(f"Attempted to fetch serialization length, but {typ} does not implement the Serialize trait").trait_generic_args()[0].as_constant().unwrap() } pub(crate) comptime fn module_has_storage(m: Module) -> bool { - m.structs().any(|s: StructDefinition| { + m.structs().any( + |s: StructDefinition| { s.has_named_attribute("storage") | s.has_named_attribute("storage_no_init") - }) + } + ) } pub(crate) comptime fn module_has_initializer(m: Module) -> bool { @@ -240,10 +231,13 @@ pub(crate) comptime fn module_has_initializer(m: Module) -> bool { } pub(crate) comptime fn is_note(typ: Type) -> bool { - typ.as_struct().map_or(false, |struc: (StructDefinition, [Type])| { + typ.as_struct().map_or( + false, + |struc: (StructDefinition, [Type])| { let (def, _) = struc; def.has_named_attribute("note") | def.has_named_attribute("partial_note") | def.has_named_attribute("note_custom_interface") - }) + } + ) } diff --git a/noir-projects/aztec-nr/aztec/src/messaging.nr b/noir-projects/aztec-nr/aztec/src/messaging.nr index ffeddf4d72f..aecc3db1c07 100644 --- a/noir-projects/aztec-nr/aztec/src/messaging.nr +++ b/noir-projects/aztec-nr/aztec/src/messaging.nr @@ -1,11 +1,9 @@ use crate::{ hash::{compute_secret_hash, compute_message_hash, compute_message_nullifier}, - oracle::get_l1_to_l2_membership_witness::get_l1_to_l2_membership_witness, + oracle::get_l1_to_l2_membership_witness::get_l1_to_l2_membership_witness }; -use dep::protocol_types::{ - address::{AztecAddress, EthAddress}, merkle_tree::root::root_from_sibling_path, -}; +use dep::protocol_types::{address::{AztecAddress, EthAddress}, merkle_tree::root::root_from_sibling_path}; pub fn process_l1_to_l2_message( l1_to_l2_root: Field, @@ -14,7 +12,7 @@ pub fn process_l1_to_l2_message( chain_id: Field, version: Field, content: Field, - secret: Field, + secret: Field ) -> Field { let secret_hash = compute_secret_hash(secret); let message_hash = compute_message_hash( @@ -23,13 +21,14 @@ pub fn process_l1_to_l2_message( contract_address, version, content, - secret_hash, + secret_hash ); // We prove that `message_hash` is in the tree by showing the derivation of the tree root, using a merkle path we // get from an oracle. - let (leaf_index, sibling_path) = - unsafe { get_l1_to_l2_membership_witness(contract_address, message_hash, secret) }; + let (leaf_index, sibling_path) = unsafe { + get_l1_to_l2_membership_witness(contract_address, message_hash, secret) + }; let root = root_from_sibling_path(message_hash, leaf_index, sibling_path); assert(root == l1_to_l2_root, "Message not in state"); diff --git a/noir-projects/aztec-nr/aztec/src/note/lifecycle.nr b/noir-projects/aztec-nr/aztec/src/note/lifecycle.nr index a348ef3f876..73bf4309444 100644 --- a/noir-projects/aztec-nr/aztec/src/note/lifecycle.nr +++ b/noir-projects/aztec-nr/aztec/src/note/lifecycle.nr @@ -2,18 +2,17 @@ use crate::context::{PrivateContext, PublicContext}; use crate::note::{ note_header::NoteHeader, note_interface::{NoteInterface, NullifiableNote}, utils::{compute_note_hash_for_read_request, compute_note_hash_for_nullify_internal}, - note_emission::NoteEmission, + note_emission::NoteEmission }; use crate::oracle::notes::{notify_created_note, notify_nullified_note}; pub fn create_note( context: &mut PrivateContext, storage_slot: Field, - note: &mut Note, + note: &mut Note ) -> NoteEmission where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { let contract_address = (*context).this_address(); let note_hash_counter = context.side_effect_counter; @@ -27,7 +26,7 @@ where Note::get_note_type_id(), serialized_note, note_hash, - note_hash_counter, + note_hash_counter ); context.push_note_hash(note_hash); @@ -38,11 +37,10 @@ where pub fn create_note_hash_from_public( context: &mut PublicContext, storage_slot: Field, - note: &mut Note, + note: &mut Note ) where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { let contract_address = (*context).this_address(); // Public note hashes are transient, but have no side effect counters, so we just need note_hash_counter != 0 let header = NoteHeader { contract_address, storage_slot, nonce: 0, note_hash_counter: 1 }; @@ -53,10 +51,12 @@ where } // Note: This function is currently totally unused. -pub fn destroy_note(context: &mut PrivateContext, note: Note) +pub fn destroy_note( + context: &mut PrivateContext, + note: Note +) where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { let note_hash_for_read_request = compute_note_hash_for_read_request(note); destroy_note_unsafe(context, note, note_hash_for_read_request) @@ -65,13 +65,11 @@ where pub fn destroy_note_unsafe( context: &mut PrivateContext, note: Note, - note_hash_for_read_request: Field, + note_hash_for_read_request: Field ) where - Note: NoteInterface + NullifiableNote, -{ - let note_hash_for_nullify = - compute_note_hash_for_nullify_internal(note, note_hash_for_read_request); + Note: NoteInterface + NullifiableNote, { + let note_hash_for_nullify = compute_note_hash_for_nullify_internal(note, note_hash_for_read_request); let nullifier = note.compute_nullifier(context, note_hash_for_nullify); let note_hash_counter = note.get_header().note_hash_counter; diff --git a/noir-projects/aztec-nr/aztec/src/note/note_getter/mod.nr b/noir-projects/aztec-nr/aztec/src/note/note_getter/mod.nr index fb463154c9d..c23325ef939 100644 --- a/noir-projects/aztec-nr/aztec/src/note/note_getter/mod.nr +++ b/noir-projects/aztec-nr/aztec/src/note/note_getter/mod.nr @@ -1,12 +1,10 @@ -use dep::protocol_types::constants::{ - MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, GET_NOTES_ORACLE_RETURN_LENGTH, -}; +use dep::protocol_types::constants::{MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, GET_NOTES_ORACLE_RETURN_LENGTH}; use crate::context::PrivateContext; use crate::note::{ constants::{GET_NOTE_ORACLE_RETURN_LENGTH, VIEW_NOTE_ORACLE_RETURN_LENGTH}, note_getter_options::{NoteGetterOptions, Select, Sort, SortOrder, NoteStatus, PropertySelector}, note_interface::{NoteInterface, NullifiableNote}, note_viewer_options::NoteViewerOptions, - utils::compute_note_hash_for_read_request, + utils::compute_note_hash_for_read_request }; use crate::oracle; use crate::utils::comparison::compare; @@ -15,10 +13,7 @@ pub use crate::note::constants::MAX_NOTES_PER_PAGE; mod test; -fn extract_property_value_from_selector( - serialized_note: [Field; N], - selector: PropertySelector, -) -> Field { +fn extract_property_value_from_selector(serialized_note: [Field; N], selector: PropertySelector) -> Field { // Selectors use PropertySelectors in order to locate note properties inside the serialized note. // This allows easier packing and custom (de)serialization schemas. A note property is located // inside the serialized note using the index inside the array, a byte offset and a length. @@ -38,8 +33,7 @@ fn extract_property_value_from_selector( fn check_note_header(context: PrivateContext, storage_slot: Field, note: Note) where - Note: NoteInterface, -{ + Note: NoteInterface, { let header = note.get_header(); let contract_address = context.this_address(); assert(header.contract_address.eq(contract_address), "Mismatch note header contract address."); @@ -48,16 +42,14 @@ where fn check_note_fields( serialized_note: [Field; N], - selects: BoundedVec, N>, + selects: BoundedVec, N> ) { for i in 0..selects.len { let select = selects.get_unchecked(i).unwrap_unchecked(); - let value_field = - extract_property_value_from_selector(serialized_note, select.property_selector); + let value_field = extract_property_value_from_selector(serialized_note, select.property_selector); assert( - compare(value_field, select.comparator, select.value.to_field()), - "Mismatch return note field.", + compare(value_field, select.comparator, select.value.to_field()), "Mismatch return note field." ); } } @@ -65,7 +57,7 @@ fn check_note_fields( fn check_notes_order( fields_0: [Field; N], fields_1: [Field; N], - sorts: BoundedVec, N>, + sorts: BoundedVec, N> ) { for i in 0..sorts.len { let sort = sorts.get_unchecked(i).unwrap_unchecked(); @@ -83,12 +75,13 @@ fn check_notes_order( pub fn get_note( context: &mut PrivateContext, - storage_slot: Field, + storage_slot: Field ) -> (Note, Field) where - Note: NoteInterface + NullifiableNote, -{ - let note = unsafe { get_note_internal(storage_slot) }; + Note: NoteInterface + NullifiableNote, { + let note = unsafe { + get_note_internal(storage_slot) + }; // Constraining that we got a valid note from the oracle is fairly straightforward: all we need to do is check that // the metadata is correct, and that the note exists. @@ -103,12 +96,13 @@ where pub fn get_notes( context: &mut PrivateContext, storage_slot: Field, - options: NoteGetterOptions, - ) -> (BoundedVec, BoundedVec) + options: NoteGetterOptions +) -> (BoundedVec, BoundedVec) where - Note: NoteInterface + NullifiableNote + Eq, -{ - let opt_notes = unsafe { get_notes_internal(storage_slot, options) }; + Note: NoteInterface + NullifiableNote + Eq, { + let opt_notes = unsafe { + get_notes_internal(storage_slot, options) + }; // We apply the constraints in a separate function instead of inlining them here to make it easier to test that // these checks correctly reject bad notes. @@ -118,7 +112,7 @@ where unconstrained fn apply_preprocessor( notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], preprocessor: fn([Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], PREPROCESSOR_ARGS) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - preprocessor_args: PREPROCESSOR_ARGS, + preprocessor_args: PREPROCESSOR_ARGS ) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] { preprocessor(notes, preprocessor_args) } @@ -127,11 +121,10 @@ fn constrain_get_notes_internal; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - options: NoteGetterOptions, - ) -> (BoundedVec, BoundedVec) + options: NoteGetterOptions +) -> (BoundedVec, BoundedVec) where - Note: NoteInterface + NullifiableNote + Eq, -{ + Note: NoteInterface + NullifiableNote + Eq, { // The filter is applied first to avoid pushing note read requests for notes we're not interested in. Note that // while the filter function can technically mutate the contents of the notes (as opposed to simply removing some), // the private kernel will later validate that these note actually exist, so transformations would cause for that @@ -141,8 +134,7 @@ where let filtered_notes = filter_fn(opt_notes, filter_args); let notes = crate::utils::collapse_array(filtered_notes); - let mut note_hashes: BoundedVec = - BoundedVec::new(); + let mut note_hashes: BoundedVec = BoundedVec::new(); // We have now collapsed the sparse array of Options into a BoundedVec. This is a more ergonomic type and also // results in reduced gate counts when setting a limit value, since we guarantee that the limit is an upper bound @@ -174,8 +166,7 @@ where unconstrained fn get_note_internal(storage_slot: Field) -> Note where - Note: NoteInterface, -{ + Note: NoteInterface, { let placeholder_note = [Option::none()]; let placeholder_fields = [0; GET_NOTE_ORACLE_RETURN_LENGTH]; let placeholder_note_length = [0; N]; @@ -196,21 +187,18 @@ where NoteStatus.ACTIVE, placeholder_note, placeholder_fields, - placeholder_note_length, - )[0] - .expect(f"Failed to get a note") // Notice: we don't allow dummies to be returned from get_note (singular). + placeholder_note_length + )[0].expect(f"Failed to get a note") // Notice: we don't allow dummies to be returned from get_note (singular). } unconstrained fn get_notes_internal( storage_slot: Field, - options: NoteGetterOptions, + options: NoteGetterOptions ) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] where - Note: NoteInterface, -{ + Note: NoteInterface, { // This function simply performs some transformations from NoteGetterOptions into the types required by the oracle. - let (num_selects, select_by_indexes, select_by_offsets, select_by_lengths, select_values, select_comparators, sort_by_indexes, sort_by_offsets, sort_by_lengths, sort_order) = - flatten_options(options.selects, options.sorts); + let (num_selects, select_by_indexes, select_by_offsets, select_by_lengths, select_values, select_comparators, sort_by_indexes, sort_by_offsets, sort_by_lengths, sort_order) = flatten_options(options.selects, options.sorts); let placeholder_opt_notes = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; let placeholder_fields = [0; GET_NOTES_ORACLE_RETURN_LENGTH]; let placeholder_note_length = [0; N]; @@ -232,7 +220,7 @@ where options.status, placeholder_opt_notes, placeholder_fields, - placeholder_note_length, + placeholder_note_length ); apply_preprocessor(opt_notes, options.preprocessor, options.preprocessor_args) @@ -240,13 +228,11 @@ where pub unconstrained fn view_notes( storage_slot: Field, - options: NoteViewerOptions, + options: NoteViewerOptions ) -> BoundedVec where - Note: NoteInterface, -{ - let (num_selects, select_by_indexes, select_by_offsets, select_by_lengths, select_values, select_comparators, sort_by_indexes, sort_by_offsets, sort_by_lengths, sort_order) = - flatten_options(options.selects, options.sorts); + Note: NoteInterface, { + let (num_selects, select_by_indexes, select_by_offsets, select_by_lengths, select_values, select_comparators, sort_by_indexes, sort_by_offsets, sort_by_lengths, sort_order) = flatten_options(options.selects, options.sorts); let placeholder_opt_notes = [Option::none(); MAX_NOTES_PER_PAGE]; let placeholder_fields = [0; VIEW_NOTE_ORACLE_RETURN_LENGTH]; let placeholder_note_length = [0; N]; @@ -268,7 +254,7 @@ where options.status, placeholder_opt_notes, placeholder_fields, - placeholder_note_length, + placeholder_note_length ); let mut notes = BoundedVec::new(); @@ -283,7 +269,7 @@ where unconstrained fn flatten_options( selects: BoundedVec, N>, - sorts: BoundedVec, N>, + sorts: BoundedVec, N> ) -> (u8, [u8; N], [u8; N], [u8; N], [Field; N], [u8; N], [u8; N], [u8; N], [u8; N], [u8; N]) { let mut num_selects = 0; let mut select_by_indexes = [0; N]; @@ -319,7 +305,6 @@ unconstrained fn flatten_options( } ( - num_selects, select_by_indexes, select_by_offsets, select_by_lengths, select_values, - select_comparators, sort_by_indexes, sort_by_offsets, sort_by_lengths, sort_order, + num_selects, select_by_indexes, select_by_offsets, select_by_lengths, select_values, select_comparators, sort_by_indexes, sort_by_offsets, sort_by_lengths, sort_order ) } diff --git a/noir-projects/aztec-nr/aztec/src/note/note_getter/test.nr b/noir-projects/aztec-nr/aztec/src/note/note_getter/test.nr index b9267de3c5a..112686982db 100644 --- a/noir-projects/aztec-nr/aztec/src/note/note_getter/test.nr +++ b/noir-projects/aztec-nr/aztec/src/note/note_getter/test.nr @@ -1,9 +1,10 @@ use dep::protocol_types::constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL; use crate::{ note::{ - note_getter_options::{NoteGetterOptions, SortOrder, PropertySelector}, - note_getter::constrain_get_notes_internal, - }, oracle::execution::get_contract_address, + note_getter_options::{NoteGetterOptions, SortOrder, PropertySelector}, + note_getter::constrain_get_notes_internal +}, + oracle::execution::get_contract_address }; use crate::test::{helpers::test_environment::TestEnvironment, mocks::mock_note::MockNote}; @@ -24,11 +25,10 @@ unconstrained fn build_valid_note(value: Field) -> MockNote { unconstrained fn assert_equivalent_vec_and_array( vec: BoundedVec, - arr: [Option; N], + arr: [Option; N] ) where - T: Eq, -{ + T: Eq, { let mut count = 0; for i in 0..N { @@ -50,8 +50,7 @@ unconstrained fn processes_single_note() { notes_to_constrain[0] = Option::some(build_valid_note(13)); let options = NoteGetterOptions::new(); - let (returned, _) = - constrain_get_notes_internal(&mut context, storage_slot, notes_to_constrain, options); + let (returned, _) = constrain_get_notes_internal(&mut context, storage_slot, notes_to_constrain, options); assert_equivalent_vec_and_array(returned, notes_to_constrain); assert_eq(context.note_hash_read_requests.len(), 1); @@ -67,8 +66,7 @@ unconstrained fn processes_many_notes() { notes_to_constrain[1] = Option::some(build_valid_note(19)); let options = NoteGetterOptions::new(); - let (returned, _) = - constrain_get_notes_internal(&mut context, storage_slot, notes_to_constrain, options); + let (returned, _) = constrain_get_notes_internal(&mut context, storage_slot, notes_to_constrain, options); assert_equivalent_vec_and_array(returned, notes_to_constrain); assert_eq(context.note_hash_read_requests.len(), 2); @@ -88,8 +86,7 @@ unconstrained fn collapses_notes_at_the_beginning_of_the_array() { opt_notes[13] = Option::some(build_valid_note(5)); let options = NoteGetterOptions::new(); - let (returned, _) = - constrain_get_notes_internal(&mut context, storage_slot, opt_notes, options); + let (returned, _) = constrain_get_notes_internal(&mut context, storage_slot, opt_notes, options); let mut expected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; expected[0] = Option::some(build_valid_note(0)); @@ -107,12 +104,10 @@ unconstrained fn can_return_zero_notes() { let mut env = setup(); let mut context = env.private(); - let opt_notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] = - [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; + let opt_notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; let options = NoteGetterOptions::new(); - let (returned, _) = - constrain_get_notes_internal(&mut context, storage_slot, opt_notes, options); + let (returned, _) = constrain_get_notes_internal(&mut context, storage_slot, opt_notes, options); assert_eq(returned.len(), 0); } @@ -121,8 +116,7 @@ unconstrained fn rejects_mote_notes_than_limit() { let mut env = setup(); let mut context = env.private(); - let mut opt_notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] = - [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; + let mut opt_notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; opt_notes[1] = Option::some(build_valid_note(0)); opt_notes[2] = Option::some(build_valid_note(1)); opt_notes[3] = Option::some(build_valid_note(2)); @@ -155,8 +149,7 @@ unconstrained fn applies_filter_before_constraining() { }; let options = NoteGetterOptions::with_filter(filter_fn, ()); - let (returned, _) = - constrain_get_notes_internal(&mut context, storage_slot, notes_to_constrain, options); + let (returned, _) = constrain_get_notes_internal(&mut context, storage_slot, notes_to_constrain, options); // Only the note with value 42 should be returned, and moved to the beginning of the array. The other notes were not // constrained, and hence validation did not fail. diff --git a/noir-projects/aztec-nr/aztec/src/note/note_getter_options.nr b/noir-projects/aztec-nr/aztec/src/note/note_getter_options.nr index 452818b9c3b..821f4558981 100644 --- a/noir-projects/aztec-nr/aztec/src/note/note_getter_options.nr +++ b/noir-projects/aztec-nr/aztec/src/note/note_getter_options.nr @@ -54,7 +54,7 @@ global NoteStatus = NoteStatusEnum { // This is the default filter and preprocessor, which does nothing fn return_all_notes( notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - _p: Field, + _p: Field ) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] { notes } @@ -90,11 +90,10 @@ impl NoteGetterOptions Self where - T: ToField, - { + T: ToField, { self.selects.push(Option::some(Select::new(property_selector, comparator, value.to_field()))); *self } @@ -134,8 +133,7 @@ impl NoteGetterOptions NoteGetterOptions where - Note: NoteInterface, -{ + Note: NoteInterface, { // This function initializes a NoteGetterOptions that simply returns the maximum number of notes allowed in a call. pub fn new() -> Self { Self { @@ -147,21 +145,20 @@ where preprocessor_args: 0, filter: return_all_notes, filter_args: 0, - status: NoteStatus.ACTIVE, + status: NoteStatus.ACTIVE } } } impl NoteGetterOptions where - Note: NoteInterface, -{ + Note: NoteInterface, { // This function initializes a NoteGetterOptions with a preprocessor, which takes the notes returned from // the database and preprocessor_args as its parameters. // `preprocessor_args` allows you to provide additional data or context to the custom preprocessor. pub fn with_preprocessor( preprocessor: fn([Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], PREPROCESSOR_ARGS) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - preprocessor_args: PREPROCESSOR_ARGS, + preprocessor_args: PREPROCESSOR_ARGS ) -> Self { Self { selects: BoundedVec::new(), @@ -172,21 +169,20 @@ where preprocessor_args, filter: return_all_notes, filter_args: 0, - status: NoteStatus.ACTIVE, + status: NoteStatus.ACTIVE } } } impl NoteGetterOptions where - Note: NoteInterface, -{ + Note: NoteInterface, { // This function initializes a NoteGetterOptions with a filter, which takes // the notes returned from the database and filter_args as its parameters. // `filter_args` allows you to provide additional data or context to the custom filter. pub fn with_filter( filter: fn([Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], FILTER_ARGS) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - filter_args: FILTER_ARGS, + filter_args: FILTER_ARGS ) -> Self { Self { selects: BoundedVec::new(), @@ -197,7 +193,7 @@ where preprocessor_args: 0, filter, filter_args, - status: NoteStatus.ACTIVE, + status: NoteStatus.ACTIVE } } } diff --git a/noir-projects/aztec-nr/aztec/src/note/note_header.nr b/noir-projects/aztec-nr/aztec/src/note/note_header.nr index f1981f2401f..f92009038f8 100644 --- a/noir-projects/aztec-nr/aztec/src/note/note_header.nr +++ b/noir-projects/aztec-nr/aztec/src/note/note_header.nr @@ -11,12 +11,7 @@ pub struct NoteHeader { impl Empty for NoteHeader { fn empty() -> Self { - NoteHeader { - contract_address: AztecAddress::zero(), - nonce: 0, - storage_slot: 0, - note_hash_counter: 0, - } + NoteHeader { contract_address: AztecAddress::zero(), nonce: 0, storage_slot: 0, note_hash_counter: 0 } } } @@ -47,7 +42,7 @@ impl Serialize for NoteHeader { self.contract_address.to_field(), self.nonce, self.storage_slot, - self.note_hash_counter as Field, + self.note_hash_counter as Field ] } } diff --git a/noir-projects/aztec-nr/aztec/src/note/note_type_id.nr b/noir-projects/aztec-nr/aztec/src/note/note_type_id.nr index 8b137891791..e69de29bb2d 100644 --- a/noir-projects/aztec-nr/aztec/src/note/note_type_id.nr +++ b/noir-projects/aztec-nr/aztec/src/note/note_type_id.nr @@ -1 +0,0 @@ - diff --git a/noir-projects/aztec-nr/aztec/src/note/note_viewer_options.nr b/noir-projects/aztec-nr/aztec/src/note/note_viewer_options.nr index 321e3d6c0ad..671a322f026 100644 --- a/noir-projects/aztec-nr/aztec/src/note/note_viewer_options.nr +++ b/noir-projects/aztec-nr/aztec/src/note/note_viewer_options.nr @@ -17,14 +17,13 @@ pub struct NoteViewerOptions { impl NoteViewerOptions { pub fn new() -> NoteViewerOptions where - Note: NoteInterface, - { + Note: NoteInterface, { NoteViewerOptions { selects: BoundedVec::new(), sorts: BoundedVec::new(), limit: MAX_NOTES_PER_PAGE as u32, offset: 0, - status: NoteStatus.ACTIVE, + status: NoteStatus.ACTIVE } } @@ -36,11 +35,10 @@ impl NoteViewerOptions { &mut self, property_selector: PropertySelector, comparator: u8, - value: T, + value: T ) -> Self where - T: ToField, - { + T: ToField, { self.selects.push(Option::some(Select::new(property_selector, comparator, value.to_field()))); *self } diff --git a/noir-projects/aztec-nr/aztec/src/note/utils.nr b/noir-projects/aztec-nr/aztec/src/note/utils.nr index 0dab8de2243..5f61dc70e84 100644 --- a/noir-projects/aztec-nr/aztec/src/note/utils.nr +++ b/noir-projects/aztec-nr/aztec/src/note/utils.nr @@ -1,22 +1,22 @@ use crate::{ context::PrivateContext, - note::{note_header::NoteHeader, note_interface::{NullifiableNote, NoteInterface}}, + note::{note_header::NoteHeader, note_interface::{NullifiableNote, NoteInterface}} }; use dep::protocol_types::{ hash::{ - compute_unique_note_hash, compute_siloed_note_hash as compute_siloed_note_hash, - compute_siloed_nullifier as compute_siloed_nullifier_from_preimage, - }, utils::arr_copy_slice, + compute_unique_note_hash, compute_siloed_note_hash as compute_siloed_note_hash, + compute_siloed_nullifier as compute_siloed_nullifier_from_preimage +}, + utils::arr_copy_slice }; pub fn compute_siloed_nullifier( note_with_header: Note, - context: &mut PrivateContext, + context: &mut PrivateContext ) -> Field where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { let header = note_with_header.get_header(); let note_hash_for_nullify = compute_note_hash_for_nullify(note_with_header); let inner_nullifier = note_with_header.compute_nullifier(context, note_hash_for_nullify); @@ -27,8 +27,7 @@ where // TODO(#7775): make this not impossible to understand pub fn compute_note_hash_for_read_request(note: Note) -> Field where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { let note_hash = note.compute_note_hash(); let nonce = note.get_header().nonce; let counter = note.get_header().note_hash_counter; @@ -43,11 +42,10 @@ where // TODO(#7775): make this not impossible to understand pub fn compute_note_hash_for_nullify_internal( note: Note, - note_hash_for_read_request: Field, + note_hash_for_read_request: Field ) -> Field where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { let header = note.get_header(); if header.note_hash_counter != 0 { @@ -56,8 +54,7 @@ where note_hash_for_read_request } else { // Case 2: Non-revertible note, nullified by a revertible nullifier - let unique_note_hash = - compute_unique_note_hash(header.nonce, note_hash_for_read_request); + let unique_note_hash = compute_unique_note_hash(header.nonce, note_hash_for_read_request); compute_siloed_note_hash(header.contract_address, unique_note_hash) } } else { @@ -111,8 +108,7 @@ where pub fn compute_note_hash_for_nullify(note: Note) -> Field where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { let note_hash_for_read_request = compute_note_hash_for_read_request(note); compute_note_hash_for_nullify_internal(note, note_hash_for_read_request) } @@ -121,11 +117,10 @@ pub unconstrained fn compute_note_hash_and_optionally_a_nullifier T, note_header: NoteHeader, compute_nullifier: bool, - serialized_note: [Field; S], + serialized_note: [Field; S] ) -> [Field; 4] where - T: NoteInterface + NullifiableNote, -{ + T: NoteInterface + NullifiableNote, { let mut note = deserialize_content(arr_copy_slice(serialized_note, [0; N], 0)); note.set_header(note_header); diff --git a/noir-projects/aztec-nr/aztec/src/oracle/arguments.nr b/noir-projects/aztec-nr/aztec/src/oracle/arguments.nr index 8321bccc27a..a6ea2b95de2 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/arguments.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/arguments.nr @@ -5,14 +5,18 @@ pub fn pack_arguments(args: [Field]) { // This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to call. When // unpacking however the caller must check that the returned value is indeed the preimage. - unsafe { pack_arguments_oracle_wrapper(args) }; + unsafe { + pack_arguments_oracle_wrapper(args) + }; } /// Same as `pack_arguments`, but using arrays instead of slices. pub fn pack_arguments_array(args: [Field; N]) { // This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to call. When // unpacking however the caller must check that the returned value is indeed the preimage. - unsafe { pack_arguments_array_oracle_wrapper(args) }; + unsafe { + pack_arguments_array_oracle_wrapper(args) + }; } unconstrained fn pack_arguments_oracle_wrapper(args: [Field]) { diff --git a/noir-projects/aztec-nr/aztec/src/oracle/call_private_function.nr b/noir-projects/aztec-nr/aztec/src/oracle/call_private_function.nr index 16bb50aacf2..aae089cd731 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/call_private_function.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/call_private_function.nr @@ -1,6 +1,4 @@ -use dep::protocol_types::{ - abis::function_selector::FunctionSelector, address::AztecAddress, utils::reader::Reader, -}; +use dep::protocol_types::{abis::function_selector::FunctionSelector, address::AztecAddress, utils::reader::Reader}; #[oracle(callPrivateFunction)] unconstrained fn call_private_function_oracle( @@ -8,7 +6,7 @@ unconstrained fn call_private_function_oracle( _function_selector: FunctionSelector, _args_hash: Field, _start_side_effect_counter: u32, - _is_static_call: bool, + _is_static_call: bool ) -> [Field; 2] {} pub unconstrained fn call_private_function_internal( @@ -16,14 +14,14 @@ pub unconstrained fn call_private_function_internal( function_selector: FunctionSelector, args_hash: Field, start_side_effect_counter: u32, - is_static_call: bool, + is_static_call: bool ) -> (u32, Field) { let fields = call_private_function_oracle( contract_address, function_selector, args_hash, start_side_effect_counter, - is_static_call, + is_static_call ); let mut reader = Reader::new(fields); diff --git a/noir-projects/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr b/noir-projects/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr index 1bf5812d8b2..1e9711b91d1 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/enqueue_public_function_call.nr @@ -6,7 +6,7 @@ unconstrained fn enqueue_public_function_call_oracle( _function_selector: FunctionSelector, _args_hash: Field, _side_effect_counter: u32, - _is_static_call: bool, + _is_static_call: bool ) -> Field {} pub unconstrained fn enqueue_public_function_call_internal( @@ -14,14 +14,14 @@ pub unconstrained fn enqueue_public_function_call_internal( function_selector: FunctionSelector, args_hash: Field, side_effect_counter: u32, - is_static_call: bool, + is_static_call: bool ) -> Field { enqueue_public_function_call_oracle( contract_address, function_selector, args_hash, side_effect_counter, - is_static_call, + is_static_call ) } @@ -31,7 +31,7 @@ unconstrained fn set_public_teardown_function_call_oracle( _function_selector: FunctionSelector, _args_hash: Field, _side_effect_counter: u32, - _is_static_call: bool, + _is_static_call: bool ) -> Field {} pub unconstrained fn set_public_teardown_function_call_internal( @@ -39,19 +39,21 @@ pub unconstrained fn set_public_teardown_function_call_internal( function_selector: FunctionSelector, args_hash: Field, side_effect_counter: u32, - is_static_call: bool, + is_static_call: bool ) -> Field { set_public_teardown_function_call_oracle( contract_address, function_selector, args_hash, side_effect_counter, - is_static_call, + is_static_call ) } pub fn notify_set_min_revertible_side_effect_counter(counter: u32) { - unsafe { notify_set_min_revertible_side_effect_counter_oracle_wrapper(counter) }; + unsafe { + notify_set_min_revertible_side_effect_counter_oracle_wrapper(counter) + }; } pub unconstrained fn notify_set_min_revertible_side_effect_counter_oracle_wrapper(counter: u32) { diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_contract_instance.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_contract_instance.nr index 7e8416c50c9..0912dd49d02 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_contract_instance.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_contract_instance.nr @@ -1,34 +1,27 @@ use dep::protocol_types::{ address::AztecAddress, contract_instance::ContractInstance, constants::CONTRACT_INSTANCE_LENGTH, - utils::reader::Reader, + utils::reader::Reader }; #[oracle(getContractInstance)] -unconstrained fn get_contract_instance_oracle( - _address: AztecAddress, -) -> [Field; CONTRACT_INSTANCE_LENGTH] {} +unconstrained fn get_contract_instance_oracle(_address: AztecAddress) -> [Field; CONTRACT_INSTANCE_LENGTH] {} // Returns a ContractInstance plus a boolean indicating whether the instance was found. #[oracle(avmOpcodeGetContractInstance)] -unconstrained fn get_contract_instance_oracle_avm( - _address: AztecAddress, -) -> [Field; CONTRACT_INSTANCE_LENGTH + 1] {} +unconstrained fn get_contract_instance_oracle_avm(_address: AztecAddress) -> [Field; CONTRACT_INSTANCE_LENGTH + 1] {} -unconstrained fn get_contract_instance_internal( - address: AztecAddress, -) -> [Field; CONTRACT_INSTANCE_LENGTH] { +unconstrained fn get_contract_instance_internal(address: AztecAddress) -> [Field; CONTRACT_INSTANCE_LENGTH] { get_contract_instance_oracle(address) } -pub unconstrained fn get_contract_instance_internal_avm( - address: AztecAddress, -) -> [Field; CONTRACT_INSTANCE_LENGTH + 1] { +pub unconstrained fn get_contract_instance_internal_avm(address: AztecAddress) -> [Field; CONTRACT_INSTANCE_LENGTH + 1] { get_contract_instance_oracle_avm(address) } pub fn get_contract_instance(address: AztecAddress) -> ContractInstance { - let instance = - unsafe { ContractInstance::deserialize(get_contract_instance_internal(address)) }; + let instance = unsafe { + ContractInstance::deserialize(get_contract_instance_internal(address)) + }; // The to_address function combines all values in the instance object to produce an address, so by checking that we // get the expected address we validate the entire struct. assert_eq(instance.to_address(), address); diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr index 313791269c4..b5774779874 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_l1_to_l2_membership_witness.nr @@ -1,16 +1,13 @@ -use dep::protocol_types::{ - address::AztecAddress, constants::L1_TO_L2_MSG_TREE_HEIGHT, utils::arr_copy_slice, -}; +use dep::protocol_types::{address::AztecAddress, constants::L1_TO_L2_MSG_TREE_HEIGHT, utils::arr_copy_slice}; /// Returns the leaf index and sibling path of an entry in the L1 to L2 messaging tree, which can then be used to prove /// its existence. pub unconstrained fn get_l1_to_l2_membership_witness( contract_address: AztecAddress, message_hash: Field, - secret: Field, + secret: Field ) -> (Field, [Field; L1_TO_L2_MSG_TREE_HEIGHT]) { - let returned_message = - get_l1_to_l2_membership_witness_oracle(contract_address, message_hash, secret); + let returned_message = get_l1_to_l2_membership_witness_oracle(contract_address, message_hash, secret); let leaf_index = returned_message[0]; let sibling_path = arr_copy_slice(returned_message, [0; L1_TO_L2_MSG_TREE_HEIGHT], 1); @@ -22,5 +19,5 @@ pub unconstrained fn get_l1_to_l2_membership_witness( unconstrained fn get_l1_to_l2_membership_witness_oracle( _contract_address: AztecAddress, _message_hash: Field, - _secret: Field, + _secret: Field ) -> [Field; L1_TO_L2_MSG_TREE_HEIGHT + 1] {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_membership_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_membership_witness.nr index 3987fab937a..c4f81e072c2 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_membership_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_membership_witness.nr @@ -1,6 +1,4 @@ -use dep::protocol_types::{ - constants::{ARCHIVE_HEIGHT, NOTE_HASH_TREE_HEIGHT}, utils::arr_copy_slice, -}; +use dep::protocol_types::{constants::{ARCHIVE_HEIGHT, NOTE_HASH_TREE_HEIGHT}, utils::arr_copy_slice}; global NOTE_HASH_TREE_ID = 1; global ARCHIVE_TREE_ID = 4; @@ -21,13 +19,13 @@ pub struct MembershipWitness { unconstrained fn get_membership_witness_oracle( _block_number: u32, _tree_id: Field, - _leaf_value: Field, + _leaf_value: Field ) -> [Field; M] {} pub unconstrained fn get_membership_witness( block_number: u32, tree_id: Field, - leaf_value: Field, + leaf_value: Field ) -> MembershipWitness { let fields: [Field; M] = get_membership_witness_oracle(block_number, tree_id, leaf_value); MembershipWitness { index: fields[0], path: arr_copy_slice(fields, [0; N], 1) } @@ -37,7 +35,7 @@ pub unconstrained fn get_membership_witness( pub unconstrained fn get_note_hash_membership_witness( block_number: u32, - leaf_value: Field, + leaf_value: Field ) -> MembershipWitness { get_membership_witness(block_number, NOTE_HASH_TREE_ID, leaf_value) } @@ -47,7 +45,7 @@ pub unconstrained fn get_note_hash_membership_witness( pub unconstrained fn get_archive_membership_witness( block_number: u32, - leaf_value: Field, + leaf_value: Field ) -> MembershipWitness { get_membership_witness(block_number, ARCHIVE_TREE_ID, leaf_value) } diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_nullifier_membership_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_nullifier_membership_witness.nr index 3bf863ebee9..c63db464eb2 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_nullifier_membership_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_nullifier_membership_witness.nr @@ -1,6 +1,6 @@ use dep::protocol_types::{ abis::nullifier_leaf_preimage::{NullifierLeafPreimage, NULLIFIER_LEAF_PREIMAGE_LENGTH}, - constants::NULLIFIER_TREE_HEIGHT, utils::arr_copy_slice, + constants::NULLIFIER_TREE_HEIGHT, utils::arr_copy_slice }; // INDEX_LENGTH + NULLIFIER_LEAF_PREIMAGE_LENGTH + NULLIFIER_TREE_HEIGHT @@ -21,8 +21,8 @@ impl NullifierMembershipWitness { path: arr_copy_slice( fields, [0; NULLIFIER_TREE_HEIGHT], - 1 + NULLIFIER_LEAF_PREIMAGE_LENGTH, - ), + 1 + NULLIFIER_LEAF_PREIMAGE_LENGTH + ) } } } @@ -30,15 +30,12 @@ impl NullifierMembershipWitness { #[oracle(getLowNullifierMembershipWitness)] unconstrained fn get_low_nullifier_membership_witness_oracle( _block_number: u32, - _nullifier: Field, + _nullifier: Field ) -> [Field; NULLIFIER_MEMBERSHIP_WITNESS] {} // Nullifier here refers to the nullifier we are looking to get non-inclusion proof for (by proving that a lower // nullifier's next_value is bigger than the nullifier) -pub unconstrained fn get_low_nullifier_membership_witness( - block_number: u32, - nullifier: Field, -) -> NullifierMembershipWitness { +pub unconstrained fn get_low_nullifier_membership_witness(block_number: u32, nullifier: Field) -> NullifierMembershipWitness { let fields = get_low_nullifier_membership_witness_oracle(block_number, nullifier); NullifierMembershipWitness::deserialize(fields) } @@ -46,15 +43,12 @@ pub unconstrained fn get_low_nullifier_membership_witness( #[oracle(getNullifierMembershipWitness)] unconstrained fn get_nullifier_membership_witness_oracle( _block_number: u32, - _nullifier: Field, + _nullifier: Field ) -> [Field; NULLIFIER_MEMBERSHIP_WITNESS] {} // Nullifier here refers to the nullifier we are looking to get non-inclusion proof for (by proving that a lower // nullifier's next_value is bigger than the nullifier) -pub unconstrained fn get_nullifier_membership_witness( - block_number: u32, - nullifier: Field, -) -> NullifierMembershipWitness { +pub unconstrained fn get_nullifier_membership_witness(block_number: u32, nullifier: Field) -> NullifierMembershipWitness { let fields = get_nullifier_membership_witness_oracle(block_number, nullifier); NullifierMembershipWitness::deserialize(fields) } diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_public_data_witness.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_public_data_witness.nr index f37a79a3875..ae3133ace00 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_public_data_witness.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_public_data_witness.nr @@ -1,6 +1,4 @@ -use dep::protocol_types::{ - constants::PUBLIC_DATA_TREE_HEIGHT, data::PublicDataTreeLeafPreimage, utils::arr_copy_slice, -}; +use dep::protocol_types::{constants::PUBLIC_DATA_TREE_HEIGHT, data::PublicDataTreeLeafPreimage, utils::arr_copy_slice}; global LEAF_PREIMAGE_LENGTH: u32 = 4; global PUBLIC_DATA_WITNESS: u32 = 45; @@ -14,26 +12,14 @@ pub struct PublicDataWitness { #[oracle(getPublicDataTreeWitness)] unconstrained fn get_public_data_witness_oracle( _block_number: u32, - _public_data_tree_index: Field, + _public_data_tree_index: Field ) -> [Field; PUBLIC_DATA_WITNESS] {} -pub unconstrained fn get_public_data_witness( - block_number: u32, - public_data_tree_index: Field, -) -> PublicDataWitness { +pub unconstrained fn get_public_data_witness(block_number: u32, public_data_tree_index: Field) -> PublicDataWitness { let fields = get_public_data_witness_oracle(block_number, public_data_tree_index); PublicDataWitness { index: fields[0], - leaf_preimage: PublicDataTreeLeafPreimage { - slot: fields[1], - value: fields[2], - next_index: fields[3] as u32, - next_slot: fields[4], - }, - path: arr_copy_slice( - fields, - [0; PUBLIC_DATA_TREE_HEIGHT], - 1 + LEAF_PREIMAGE_LENGTH, - ), + leaf_preimage: PublicDataTreeLeafPreimage { slot: fields[1], value: fields[2], next_index: fields[3] as u32, next_slot: fields[4] }, + path: arr_copy_slice(fields, [0; PUBLIC_DATA_TREE_HEIGHT], 1 + LEAF_PREIMAGE_LENGTH) } } diff --git a/noir-projects/aztec-nr/aztec/src/oracle/get_sibling_path.nr b/noir-projects/aztec-nr/aztec/src/oracle/get_sibling_path.nr index 6e8edfaa305..252fbc06cd2 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/get_sibling_path.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/get_sibling_path.nr @@ -2,14 +2,10 @@ unconstrained fn get_sibling_path_oracle( _block_number: u32, _tree_id: Field, - _leaf_index: Field, + _leaf_index: Field ) -> [Field; N] {} -pub unconstrained fn get_sibling_path( - block_number: u32, - tree_id: Field, - leaf_index: Field, -) -> [Field; N] { +pub unconstrained fn get_sibling_path(block_number: u32, tree_id: Field, leaf_index: Field) -> [Field; N] { let value: [Field; N] = get_sibling_path_oracle(block_number, tree_id, leaf_index); value } diff --git a/noir-projects/aztec-nr/aztec/src/oracle/header.nr b/noir-projects/aztec-nr/aztec/src/oracle/header.nr index b093494e4a1..3b4ccb2ceff 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/header.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/header.nr @@ -1,9 +1,7 @@ use dep::protocol_types::merkle_tree::root::root_from_sibling_path; use dep::protocol_types::{constants::HEADER_LENGTH, header::Header}; -use crate::{ - context::PrivateContext, oracle::get_membership_witness::get_archive_membership_witness, -}; +use crate::{context::PrivateContext, oracle::get_membership_witness::get_archive_membership_witness}; use crate::test::helpers::test_environment::TestEnvironment; @@ -32,12 +30,13 @@ pub fn get_header_at(block_number: u32, context: PrivateContext) -> Header { // We could not perform the proof otherwise because the last archive root from the header would not "contain" // the header we want to prove against assert( - last_archive_block_number >= block_number, - "Last archive block number is smaller than the block number we want to prove against", + last_archive_block_number >= block_number, "Last archive block number is smaller than the block number we want to prove against" ); // 3) Get the header hint of a given block from an oracle - let historical = unsafe { get_header_at_internal(block_number) }; + let historical = unsafe { + get_header_at_internal(block_number) + }; // 4) We make sure that the header hint we received from the oracle exists in the state tree and is the actual header // at the desired block number @@ -45,7 +44,7 @@ pub fn get_header_at(block_number: u32, context: PrivateContext) -> Header { historical, block_number, last_archive_block_number, - header.last_archive.root, + header.last_archive.root ); // 5) Return the block header @@ -57,24 +56,24 @@ fn constrain_get_header_at_internal( header_hint: Header, block_number: u32, last_archive_block_number: u32, - last_archive_root: Field, + last_archive_root: Field ) { // 1) Compute the block hash from the block header let block_hash = header_hint.hash(); // 2) Get the membership witness of the block in the archive tree - let witness = unsafe { get_archive_membership_witness(last_archive_block_number, block_hash) }; + let witness = unsafe { + get_archive_membership_witness(last_archive_block_number, block_hash) + }; // 3) Check that the block is in the archive (i.e. the witness is valid) assert( - last_archive_root == root_from_sibling_path(block_hash, witness.index, witness.path), - "Proving membership of a block in archive failed", + last_archive_root == root_from_sibling_path(block_hash, witness.index, witness.path), "Proving membership of a block in archive failed" ); // 4) Check that the header hint has the same block number as the block number we are looking for, ensuring we are actually grabbing the header we specify assert( - header_hint.global_variables.block_number as u32 == block_number, - "Block number provided is not the same as the block number from the header hint", + header_hint.global_variables.block_number as u32 == block_number, "Block number provided is not the same as the block number from the header hint" ); } @@ -95,6 +94,6 @@ unconstrained fn fetching_a_valid_but_different_header_should_fail() { bad_header, 2, current_header.global_variables.block_number as u32 - 1, - current_header.last_archive.root, + current_header.last_archive.root ); } diff --git a/noir-projects/aztec-nr/aztec/src/oracle/key_validation_request.nr b/noir-projects/aztec-nr/aztec/src/oracle/key_validation_request.nr index 6a779675fc4..8db93e173b0 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/key_validation_request.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/key_validation_request.nr @@ -1,16 +1,14 @@ -use dep::protocol_types::abis::validation_requests::{ - KeyValidationRequest, key_validation_request::KEY_VALIDATION_REQUEST_LENGTH, -}; +use dep::protocol_types::abis::validation_requests::{KeyValidationRequest, key_validation_request::KEY_VALIDATION_REQUEST_LENGTH}; #[oracle(getKeyValidationRequest)] unconstrained fn get_key_validation_request_oracle( _pk_m_hash: Field, - _key_index: Field, + _key_index: Field ) -> [Field; KEY_VALIDATION_REQUEST_LENGTH] {} unconstrained fn get_key_validation_request_internal( npk_m_hash: Field, - key_index: Field, + key_index: Field ) -> KeyValidationRequest { let result = get_key_validation_request_oracle(npk_m_hash, key_index); KeyValidationRequest::deserialize(result) @@ -18,7 +16,7 @@ unconstrained fn get_key_validation_request_internal( pub unconstrained fn get_key_validation_request( pk_m_hash: Field, - key_index: Field, + key_index: Field ) -> KeyValidationRequest { get_key_validation_request_internal(pk_m_hash, key_index) } diff --git a/noir-projects/aztec-nr/aztec/src/oracle/keys.nr b/noir-projects/aztec-nr/aztec/src/oracle/keys.nr index 7c6bb4a317f..434635d40c8 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/keys.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/keys.nr @@ -1,27 +1,19 @@ use dep::protocol_types::{ address::{AztecAddress, PartialAddress}, public_keys::{PublicKeys, NpkM, IvpkM, OvpkM, TpkM}, - point::Point, + point::Point }; #[oracle(getPublicKeysAndPartialAddress)] unconstrained fn get_public_keys_and_partial_address_oracle(_address: AztecAddress) -> [Field; 13] {} -pub unconstrained fn get_public_keys_and_partial_address( - address: AztecAddress, -) -> (PublicKeys, PartialAddress) { +pub unconstrained fn get_public_keys_and_partial_address(address: AztecAddress) -> (PublicKeys, PartialAddress) { let result = get_public_keys_and_partial_address_oracle(address); let keys = PublicKeys { npk_m: NpkM { inner: Point { x: result[0], y: result[1], is_infinite: result[2] as bool } }, - ivpk_m: IvpkM { - inner: Point { x: result[3], y: result[4], is_infinite: result[5] as bool }, - }, - ovpk_m: OvpkM { - inner: Point { x: result[6], y: result[7], is_infinite: result[8] as bool }, - }, - tpk_m: TpkM { - inner: Point { x: result[9], y: result[10], is_infinite: result[11] as bool }, - }, + ivpk_m: IvpkM { inner: Point { x: result[3], y: result[4], is_infinite: result[5] as bool } }, + ovpk_m: OvpkM { inner: Point { x: result[6], y: result[7], is_infinite: result[8] as bool } }, + tpk_m: TpkM { inner: Point { x: result[9], y: result[10], is_infinite: result[11] as bool } } }; let partial_address = PartialAddress::from_field(result[12]); diff --git a/noir-projects/aztec-nr/aztec/src/oracle/logs.nr b/noir-projects/aztec-nr/aztec/src/oracle/logs.nr index 85e54210bf4..462a57d2f1a 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/logs.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/logs.nr @@ -2,11 +2,7 @@ use dep::protocol_types::address::AztecAddress; /// Informs the simulator that an encrypted note log has been emitted, helping it keep track of side-effects and easing /// debugging. -pub fn emit_encrypted_note_log( - note_hash_counter: u32, - encrypted_note: [u8; M], - counter: u32, -) { +pub fn emit_encrypted_note_log(note_hash_counter: u32, encrypted_note: [u8; M], counter: u32) { // This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to call. unsafe { emit_encrypted_note_log_oracle_wrapper(note_hash_counter, encrypted_note, counter) @@ -15,20 +11,10 @@ pub fn emit_encrypted_note_log( /// Informs the simulator that an encrypted event log has been emitted, helping it keep track of side-effects and easing /// debugging. -pub fn emit_encrypted_event_log( - contract_address: AztecAddress, - randomness: Field, - encrypted_event: [u8; M], - counter: u32, -) { +pub fn emit_encrypted_event_log(contract_address: AztecAddress, randomness: Field, encrypted_event: [u8; M], counter: u32) { // This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to call. unsafe { - emit_encrypted_event_log_oracle_wrapper( - contract_address, - randomness, - encrypted_event, - counter, - ) + emit_encrypted_event_log_oracle_wrapper(contract_address, randomness, encrypted_event, counter) } } @@ -41,11 +27,7 @@ pub fn emit_unencrypted_log_private(contract_address: AztecAddress, message: } } -unconstrained fn emit_encrypted_note_log_oracle_wrapper( - note_hash_counter: u32, - encrypted_note: [u8; M], - counter: u32, -) { +unconstrained fn emit_encrypted_note_log_oracle_wrapper(note_hash_counter: u32, encrypted_note: [u8; M], counter: u32) { emit_encrypted_note_log_oracle(note_hash_counter, encrypted_note, counter) } @@ -53,16 +35,12 @@ unconstrained fn emit_encrypted_event_log_oracle_wrapper( contract_address: AztecAddress, randomness: Field, encrypted_event: [u8; M], - counter: u32, + counter: u32 ) { emit_encrypted_event_log_oracle(contract_address, randomness, encrypted_event, counter) } -unconstrained fn emit_unencrypted_log_private_oracle_wrapper( - contract_address: AztecAddress, - message: T, - counter: u32, -) { +unconstrained fn emit_unencrypted_log_private_oracle_wrapper(contract_address: AztecAddress, message: T, counter: u32) { let _ = emit_unencrypted_log_private_oracle(contract_address, message, counter); } @@ -71,7 +49,7 @@ unconstrained fn emit_unencrypted_log_private_oracle_wrapper( pub unconstrained fn emit_contract_class_unencrypted_log_private( contract_address: AztecAddress, message: [Field; N], - counter: u32, + counter: u32 ) -> Field { emit_contract_class_unencrypted_log_private_oracle(contract_address, message, counter) } @@ -81,7 +59,7 @@ pub unconstrained fn emit_contract_class_unencrypted_log_private( unconstrained fn emit_encrypted_note_log_oracle( _note_hash_counter: u32, _encrypted_note: [u8; M], - _counter: u32, + _counter: u32 ) {} #[oracle(emitEncryptedEventLog)] @@ -89,19 +67,19 @@ unconstrained fn emit_encrypted_event_log_oracle( _contract_address: AztecAddress, _randomness: Field, _encrypted_event: [u8; M], - _counter: u32, + _counter: u32 ) {} #[oracle(emitUnencryptedLog)] unconstrained fn emit_unencrypted_log_private_oracle( _contract_address: AztecAddress, _message: T, - _counter: u32, + _counter: u32 ) -> Field {} #[oracle(emitContractClassUnencryptedLog)] unconstrained fn emit_contract_class_unencrypted_log_private_oracle( contract_address: AztecAddress, message: [Field; N], - counter: u32, + counter: u32 ) -> Field {} diff --git a/noir-projects/aztec-nr/aztec/src/oracle/notes.nr b/noir-projects/aztec-nr/aztec/src/oracle/notes.nr index 90c3dcad862..1eb38ff0915 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/notes.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/notes.nr @@ -9,17 +9,11 @@ pub fn notify_created_note( note_type_id: Field, serialized_note: [Field; N], note_hash: Field, - counter: u32, + counter: u32 ) { // This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to call. unsafe { - notify_created_note_oracle_wrapper( - storage_slot, - note_type_id, - serialized_note, - note_hash, - counter, - ) + notify_created_note_oracle_wrapper(storage_slot, note_type_id, serialized_note, note_hash, counter) }; } @@ -28,7 +22,9 @@ pub fn notify_created_note( /// actual block. pub fn notify_nullified_note(nullifier: Field, note_hash: Field, counter: u32) { // This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to call. - unsafe { notify_nullified_note_oracle_wrapper(nullifier, note_hash, counter) }; + unsafe { + notify_nullified_note_oracle_wrapper(nullifier, note_hash, counter) + }; } unconstrained fn notify_created_note_oracle_wrapper( @@ -36,15 +32,9 @@ unconstrained fn notify_created_note_oracle_wrapper( note_type_id: Field, serialized_note: [Field; N], note_hash: Field, - counter: u32, + counter: u32 ) { - let _ = notify_created_note_oracle( - storage_slot, - note_type_id, - serialized_note, - note_hash, - counter, - ); + let _ = notify_created_note_oracle(storage_slot, note_type_id, serialized_note, note_hash, counter); } #[oracle(notifyCreatedNote)] @@ -53,23 +43,19 @@ unconstrained fn notify_created_note_oracle( _note_type_id: Field, _serialized_note: [Field; N], _note_hash: Field, - _counter: u32, + _counter: u32 ) -> Field {} unconstrained fn notify_nullified_note_oracle_wrapper( nullifier: Field, note_hash: Field, - counter: u32, + counter: u32 ) { let _ = notify_nullified_note_oracle(nullifier, note_hash, counter); } #[oracle(notifyNullifiedNote)] -unconstrained fn notify_nullified_note_oracle( - _nullifier: Field, - _note_hash: Field, - _counter: u32, -) -> Field {} +unconstrained fn notify_nullified_note_oracle(_nullifier: Field, _note_hash: Field, _counter: u32) -> Field {} #[oracle(getNotes)] unconstrained fn get_notes_oracle( @@ -88,7 +74,7 @@ unconstrained fn get_notes_oracle( _offset: u32, _status: u8, _return_size: u32, - _placeholder_fields: [Field; S], + _placeholder_fields: [Field; S] ) -> [Field; S] {} unconstrained fn get_notes_oracle_wrapper( @@ -106,7 +92,7 @@ unconstrained fn get_notes_oracle_wrapper( limit: u32, offset: u32, status: u8, - mut placeholder_fields: [Field; S], + mut placeholder_fields: [Field; S] ) -> [Field; S] { let return_size = placeholder_fields.len() as u32; get_notes_oracle( @@ -125,7 +111,7 @@ unconstrained fn get_notes_oracle_wrapper( offset, status, return_size, - placeholder_fields, + placeholder_fields ) } @@ -146,11 +132,10 @@ pub unconstrained fn get_notes; S], // TODO: Remove it and use `limit` to initialize the note array. placeholder_fields: [Field; NS], // TODO: Remove it and use `limit` to initialize the note array. - _placeholder_note_length: [Field; N], // Turbofish hack? Compiler breaks calculating read_offset unless we add this parameter + _placeholder_note_length: [Field; N] // Turbofish hack? Compiler breaks calculating read_offset unless we add this parameter ) -> [Option; S] where - Note: NoteInterface, -{ + Note: NoteInterface, { let fields = get_notes_oracle_wrapper( storage_slot, num_selects, @@ -166,7 +151,7 @@ where limit, offset, status, - placeholder_fields, + placeholder_fields ); let num_notes = fields[0] as u32; let contract_address = AztecAddress::from_field(fields[1]); diff --git a/noir-projects/aztec-nr/aztec/src/oracle/returns.nr b/noir-projects/aztec-nr/aztec/src/oracle/returns.nr index b12009e6313..f38cbf78a11 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/returns.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/returns.nr @@ -5,7 +5,9 @@ pub fn pack_returns(returns: [Field]) { // This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to call. When // unpacking however the caller must check that the returned value is indeed the preimage. - unsafe { pack_returns_oracle_wrapper(returns) }; + unsafe { + pack_returns_oracle_wrapper(returns) + }; } pub unconstrained fn pack_returns_oracle_wrapper(returns: [Field]) { diff --git a/noir-projects/aztec-nr/aztec/src/oracle/storage.nr b/noir-projects/aztec-nr/aztec/src/oracle/storage.nr index 5a7e6018a53..aeaab2ea885 100644 --- a/noir-projects/aztec-nr/aztec/src/oracle/storage.nr +++ b/noir-projects/aztec-nr/aztec/src/oracle/storage.nr @@ -1,34 +1,28 @@ use dep::protocol_types::{address::AztecAddress, traits::Deserialize}; #[oracle(storageRead)] -unconstrained fn storage_read_oracle( - address: Field, - storage_slot: Field, - block_number: Field, - length: Field, -) -> [Field; N] {} +unconstrained fn storage_read_oracle(address: Field, storage_slot: Field, block_number: Field, length: Field) -> [Field; N] {} pub unconstrained fn raw_storage_read( address: AztecAddress, storage_slot: Field, - block_number: u32, + block_number: u32 ) -> [Field; N] { storage_read_oracle( address.to_field(), storage_slot, block_number as Field, - N as Field, + N as Field ) } pub unconstrained fn storage_read( address: AztecAddress, storage_slot: Field, - block_number: u32, + block_number: u32 ) -> T where - T: Deserialize, -{ + T: Deserialize, { T::deserialize(raw_storage_read(address, storage_slot, block_number)) } diff --git a/noir-projects/aztec-nr/aztec/src/prelude.nr b/noir-projects/aztec-nr/aztec/src/prelude.nr index 4eaed773154..5d4d32954d7 100644 --- a/noir-projects/aztec-nr/aztec/src/prelude.nr +++ b/noir-projects/aztec-nr/aztec/src/prelude.nr @@ -1,7 +1,7 @@ // docs:start:prelude pub use dep::protocol_types::{ address::{AztecAddress, EthAddress}, abis::function_selector::FunctionSelector, point::Point, - traits::{Serialize, Deserialize}, + traits::{Serialize, Deserialize} }; pub use crate::{ state_vars::{ @@ -11,9 +11,9 @@ pub use crate::{ }, context::{PrivateContext, PackedReturns, FunctionReturns, PublicContext}, note::{ - note_header::NoteHeader, note_interface::{NoteInterface, NullifiableNote}, - note_getter_options::NoteGetterOptions, note_viewer_options::NoteViewerOptions, - utils::compute_note_hash_and_optionally_a_nullifier as utils_compute_note_hash_and_optionally_a_nullifier, - }, + note_header::NoteHeader, note_interface::{NoteInterface, NullifiableNote}, + note_getter_options::NoteGetterOptions, note_viewer_options::NoteViewerOptions, + utils::compute_note_hash_and_optionally_a_nullifier as utils_compute_note_hash_and_optionally_a_nullifier +} }; // docs:end:prelude diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/map.nr b/noir-projects/aztec-nr/aztec/src/state_vars/map.nr index ddb88ac8038..1734041b9f0 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/map.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/map.nr @@ -16,7 +16,7 @@ impl Map { pub fn new( context: Context, storage_slot: Field, - state_var_constructor: fn(Context, Field) -> V, + state_var_constructor: fn(Context, Field) -> V ) -> Self { assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1."); Map { context, storage_slot, state_var_constructor } @@ -26,8 +26,7 @@ impl Map { // docs:start:at pub fn at(self, key: K) -> V where - K: ToField, - { + K: ToField, { // TODO(#1204): use a generator index for the storage slot let derived_storage_slot = derive_storage_slot_in_map(self.storage_slot, key); diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/private_immutable.nr b/noir-projects/aztec-nr/aztec/src/state_vars/private_immutable.nr index 4f6ff618fae..59ad0ebb3a7 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/private_immutable.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/private_immutable.nr @@ -1,12 +1,10 @@ -use dep::protocol_types::{ - constants::GENERATOR_INDEX__INITIALIZATION_NULLIFIER, hash::poseidon2_hash_with_separator, -}; +use dep::protocol_types::{constants::GENERATOR_INDEX__INITIALIZATION_NULLIFIER, hash::poseidon2_hash_with_separator}; use crate::context::{PrivateContext, UnconstrainedContext}; use crate::note::{ lifecycle::create_note, note_getter::{get_note, view_notes}, note_interface::{NoteInterface, NullifiableNote}, note_viewer_options::NoteViewerOptions, - note_emission::NoteEmission, + note_emission::NoteEmission }; use crate::oracle::notes::check_nullifier_exists; use crate::state_vars::storage::Storage; @@ -37,17 +35,19 @@ impl PrivateImmutable { pub fn compute_initialization_nullifier(self) -> Field { poseidon2_hash_with_separator( [self.storage_slot], - GENERATOR_INDEX__INITIALIZATION_NULLIFIER, + GENERATOR_INDEX__INITIALIZATION_NULLIFIER ) } } impl PrivateImmutable { // docs:start:initialize - pub fn initialize(self, note: &mut Note) -> NoteEmission + pub fn initialize( + self, + note: &mut Note + ) -> NoteEmission where - Note: NoteInterface + NullifiableNote, - { + Note: NoteInterface + NullifiableNote, { // Nullify the storage slot. let nullifier = self.compute_initialization_nullifier(); self.context.push_nullifier(nullifier); @@ -59,8 +59,7 @@ impl PrivateImmutable { // docs:start:get_note pub fn get_note(self) -> Note where - Note: NoteInterface + NullifiableNote, - { + Note: NoteInterface + NullifiableNote, { let storage_slot = self.storage_slot; get_note(self.context, storage_slot).0 } @@ -79,8 +78,7 @@ impl PrivateImmutable { // docs:start:view_note pub unconstrained fn view_note(self) -> Note where - Note: NoteInterface + NullifiableNote, - { + Note: NoteInterface + NullifiableNote, { let mut options = NoteViewerOptions::new(); view_notes(self.storage_slot, options.set_limit(1)).get(0) } diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable.nr b/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable.nr index 29cc9c6b88b..c6f63ed4ef8 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable.nr @@ -1,12 +1,10 @@ -use dep::protocol_types::{ - constants::GENERATOR_INDEX__INITIALIZATION_NULLIFIER, hash::poseidon2_hash_with_separator, -}; +use dep::protocol_types::{constants::GENERATOR_INDEX__INITIALIZATION_NULLIFIER, hash::poseidon2_hash_with_separator}; use crate::context::{PrivateContext, UnconstrainedContext}; use crate::note::{ lifecycle::{create_note, destroy_note_unsafe}, note_getter::{get_note, view_notes}, note_interface::{NoteInterface, NullifiableNote}, note_viewer_options::NoteViewerOptions, - note_emission::NoteEmission, + note_emission::NoteEmission }; use crate::oracle::notes::check_nullifier_exists; use crate::state_vars::storage::Storage; @@ -41,15 +39,14 @@ impl PrivateMutable { pub fn compute_initialization_nullifier(self) -> Field { poseidon2_hash_with_separator( [self.storage_slot], - GENERATOR_INDEX__INITIALIZATION_NULLIFIER, + GENERATOR_INDEX__INITIALIZATION_NULLIFIER ) } } impl PrivateMutable where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { // docs:start:initialize pub fn initialize(self, note: &mut Note) -> NoteEmission { // Nullify the storage slot. @@ -62,8 +59,7 @@ where // docs:start:replace pub fn replace(self, new_note: &mut Note) -> NoteEmission { - let (prev_note, note_hash_for_read_request): (Note, Field) = - get_note(self.context, self.storage_slot); + let (prev_note, note_hash_for_read_request): (Note, Field) = get_note(self.context, self.storage_slot); // Nullify previous note. destroy_note_unsafe(self.context, prev_note, note_hash_for_read_request); @@ -84,8 +80,9 @@ where // an inclusion proof for the current note // This means that an honest oracle will assist the prover to produce a valid proof, while a malicious oracle // (i.e. one that returns an incorrect value for is_initialized) will simply fail to produce a proof. - let is_initialized = - unsafe { check_nullifier_exists(self.compute_initialization_nullifier()) }; + let is_initialized = unsafe { + check_nullifier_exists(self.compute_initialization_nullifier()) + }; if (!is_initialized) { self.initialize(note) @@ -110,8 +107,7 @@ where impl PrivateMutable where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { pub unconstrained fn is_initialized(self) -> bool { let nullifier = self.compute_initialization_nullifier(); check_nullifier_exists(nullifier) diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable/test.nr b/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable/test.nr index 4d72ba7ac33..378a9e8d48e 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable/test.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable/test.nr @@ -1,6 +1,6 @@ use crate::{ context::PrivateContext, state_vars::private_mutable::PrivateMutable, - oracle::execution::get_contract_address, + oracle::execution::get_contract_address }; use crate::test::{mocks::mock_note::MockNote, helpers::test_environment::TestEnvironment}; use std::test::OracleMock; @@ -14,9 +14,7 @@ unconstrained fn setup() -> TestEnvironment { env } -unconstrained fn in_private( - env: &mut TestEnvironment, -) -> PrivateMutable { +unconstrained fn in_private(env: &mut TestEnvironment) -> PrivateMutable { let state_var = PrivateMutable::new(&mut env.private(), storage_slot); // This oracle is called for its side effects alone - it's always expected to return 0. @@ -31,10 +29,7 @@ unconstrained fn test_initialize_or_replace_without_nullifier() { let state_var = in_private(&mut env); let value = 42; - let mut note = MockNote::new(value) - .contract_address(get_contract_address()) - .storage_slot(storage_slot) - .build(); + let mut note = MockNote::new(value).contract_address(get_contract_address()).storage_slot(storage_slot).build(); let _ = OracleMock::mock("checkNullifierExists").returns(0); state_var.initialize_or_replace(&mut note).discard(); diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/private_set.nr b/noir-projects/aztec-nr/aztec/src/state_vars/private_set.nr index da2d4926411..be3766ca722 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/private_set.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/private_set.nr @@ -1,13 +1,11 @@ -use dep::protocol_types::{ - constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, abis::read_request::ReadRequest, -}; +use dep::protocol_types::{constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, abis::read_request::ReadRequest}; use crate::context::{PrivateContext, PublicContext, UnconstrainedContext}; use crate::note::{ constants::MAX_NOTES_PER_PAGE, lifecycle::{create_note, create_note_hash_from_public, destroy_note_unsafe}, note_getter::{get_notes, view_notes}, note_getter_options::NoteGetterOptions, note_interface::{NoteInterface, NullifiableNote}, note_viewer_options::NoteViewerOptions, - utils::compute_note_hash_for_read_request, note_emission::NoteEmission, + utils::compute_note_hash_for_read_request, note_emission::NoteEmission }; use crate::state_vars::storage::Storage; @@ -31,8 +29,7 @@ impl PrivateSet { impl PrivateSet where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { // docs:start:insert_from_public pub fn insert_from_public(self, note: &mut Note) { create_note_hash_from_public(self.context, self.storage_slot, note); @@ -42,8 +39,7 @@ where impl PrivateSet where - Note: NoteInterface + NullifiableNote + Eq, -{ + Note: NoteInterface + NullifiableNote + Eq, { // docs:start:insert pub fn insert(self, note: &mut Note) -> NoteEmission { create_note(self.context, self.storage_slot, note) @@ -52,7 +48,7 @@ where pub fn pop_notes( self, - options: NoteGetterOptions, + options: NoteGetterOptions ) -> BoundedVec { let (notes, note_hashes) = get_notes(self.context, self.storage_slot, options); // We iterate in a range 0..options.limit instead of 0..notes.len() because options.limit is known at compile @@ -75,8 +71,7 @@ where /// in significantly less constrains due to avoiding an extra hash and read request check. pub fn remove(self, note: Note) { let note_hash = compute_note_hash_for_read_request(note); - let has_been_read = - self.context.note_hash_read_requests.any(|r: ReadRequest| r.value == note_hash); + let has_been_read = self.context.note_hash_read_requests.any(|r: ReadRequest| r.value == note_hash); assert(has_been_read, "Can only remove a note that has been read from the set."); destroy_note_unsafe(self.context, note, note_hash); @@ -86,7 +81,7 @@ where /// in significantly less constrains due to avoiding 1 read request check. pub fn get_notes( self, - options: NoteGetterOptions, + options: NoteGetterOptions ) -> BoundedVec { get_notes(self.context, self.storage_slot, options).0 } @@ -94,13 +89,9 @@ where impl PrivateSet where - Note: NoteInterface + NullifiableNote, -{ + Note: NoteInterface + NullifiableNote, { // docs:start:view_notes - pub unconstrained fn view_notes( - self, - options: NoteViewerOptions, - ) -> BoundedVec { + pub unconstrained fn view_notes(self, options: NoteViewerOptions) -> BoundedVec { view_notes(self.storage_slot, options) } // docs:end:view_notes diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr b/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr index 4fac882d8a9..64f32004784 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr @@ -1,7 +1,5 @@ use crate::{context::{PublicContext, UnconstrainedContext}, state_vars::storage::Storage}; -use dep::protocol_types::{ - constants::INITIALIZATION_SLOT_SEPARATOR, traits::{Deserialize, Serialize}, -}; +use dep::protocol_types::{constants::INITIALIZATION_SLOT_SEPARATOR, traits::{Deserialize, Serialize}}; // Just like SharedImmutable but without the ability to read from private functions. // docs:start:public_immutable_struct @@ -18,7 +16,7 @@ impl PublicImmutable { pub fn new( // Note: Passing the contexts to new(...) just to have an interface compatible with a Map. context: Context, - storage_slot: Field, + storage_slot: Field ) -> Self { assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1."); PublicImmutable { context, storage_slot } @@ -28,8 +26,7 @@ impl PublicImmutable { impl PublicImmutable where - T: Serialize + Deserialize, -{ + T: Serialize + Deserialize, { // docs:start:public_immutable_struct_write pub fn initialize(self, value: T) { // We check that the struct is not yet initialized by checking if the initialization slot is 0 @@ -53,8 +50,7 @@ where impl PublicImmutable where - T: Deserialize, -{ + T: Deserialize, { pub unconstrained fn read(self) -> T { self.context.storage_read(self.storage_slot) } diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/public_mutable.nr b/noir-projects/aztec-nr/aztec/src/state_vars/public_mutable.nr index a1472db195d..679944828cb 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/public_mutable.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/public_mutable.nr @@ -16,7 +16,7 @@ impl PublicMutable { pub fn new( // Note: Passing the contexts to new(...) just to have an interface compatible with a Map. context: Context, - storage_slot: Field, + storage_slot: Field ) -> Self { assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1."); PublicMutable { context, storage_slot } @@ -26,8 +26,7 @@ impl PublicMutable { impl PublicMutable where - T: Serialize + Deserialize, -{ + T: Serialize + Deserialize, { // docs:start:public_mutable_struct_read pub fn read(self) -> T { self.context.storage_read(self.storage_slot) @@ -43,8 +42,7 @@ where impl PublicMutable where - T: Deserialize, -{ + T: Deserialize, { pub unconstrained fn read(self) -> T { self.context.storage_read(self.storage_slot) } diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/shared_immutable.nr b/noir-projects/aztec-nr/aztec/src/state_vars/shared_immutable.nr index 8c6f3ecb9ab..d40639653d8 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/shared_immutable.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/shared_immutable.nr @@ -1,9 +1,5 @@ -use crate::{ - context::{PrivateContext, PublicContext, UnconstrainedContext}, state_vars::storage::Storage, -}; -use dep::protocol_types::{ - constants::INITIALIZATION_SLOT_SEPARATOR, traits::{Deserialize, Serialize}, -}; +use crate::{context::{PrivateContext, PublicContext, UnconstrainedContext}, state_vars::storage::Storage}; +use dep::protocol_types::{constants::INITIALIZATION_SLOT_SEPARATOR, traits::{Deserialize, Serialize}}; // Just like PublicImmutable but with the ability to read from private functions. pub struct SharedImmutable { @@ -17,7 +13,7 @@ impl SharedImmutable { pub fn new( // Note: Passing the contexts to new(...) just to have an interface compatible with a Map. context: Context, - storage_slot: Field, + storage_slot: Field ) -> Self { assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1."); Self { context, storage_slot } @@ -26,8 +22,7 @@ impl SharedImmutable { impl SharedImmutable where - T: Serialize + Deserialize, -{ + T: Serialize + Deserialize, { // Intended to be only called once. pub fn initialize(self, value: T) { // We check that the struct is not yet initialized by checking if the initialization slot is 0 @@ -47,8 +42,7 @@ where impl SharedImmutable where - T: Serialize + Deserialize, -{ + T: Serialize + Deserialize, { pub unconstrained fn read_public(self) -> T { self.context.storage_read(self.storage_slot) } @@ -56,8 +50,7 @@ where impl SharedImmutable where - T: Serialize + Deserialize, -{ + T: Serialize + Deserialize, { pub fn read_private(self) -> T { let header = self.context.get_header(); let mut fields = [0; T_SERIALIZED_LEN]; diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/scheduled_delay_change.nr b/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/scheduled_delay_change.nr index 05ce69f59df..1b1081497ea 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/scheduled_delay_change.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/scheduled_delay_change.nr @@ -119,7 +119,7 @@ impl ScheduledDelayChange { min( self.pre.unwrap_or(INITIAL_DELAY), - blocks_until_change + self.post.unwrap_or(INITIAL_DELAY), + blocks_until_change + self.post.unwrap_or(INITIAL_DELAY) ) } } @@ -130,8 +130,7 @@ impl Serialize<1> for ScheduledDelayChange Deserialize<1> for ScheduledDelayChange) { // We have to do explicit type annotations because Noir lacks turbofish support. // TODO: improve syntax once https://github.com/noir-lang/noir/issues/4710 is implemented. - let converted: ScheduledDelayChange = - ScheduledDelayChange::deserialize((original).serialize()); + let converted: ScheduledDelayChange = ScheduledDelayChange::deserialize((original).serialize()); assert_eq(original, converted); // This also tests the Eq impl assert_eq(original.pre, converted.pre); @@ -20,26 +19,10 @@ unconstrained fn test_serde() { let post = 2; let block_of_change = 50; - assert_equal_after_conversion(ScheduledDelayChange::new( - Option::some(pre), - Option::some(post), - block_of_change, - )); - assert_equal_after_conversion(ScheduledDelayChange::new( - Option::some(pre), - Option::none(), - block_of_change, - )); - assert_equal_after_conversion(ScheduledDelayChange::new( - Option::none(), - Option::some(post), - block_of_change, - )); - assert_equal_after_conversion(ScheduledDelayChange::new( - Option::none(), - Option::none(), - block_of_change, - )); + assert_equal_after_conversion(ScheduledDelayChange::new(Option::some(pre), Option::some(post), block_of_change)); + assert_equal_after_conversion(ScheduledDelayChange::new(Option::some(pre), Option::none(), block_of_change)); + assert_equal_after_conversion(ScheduledDelayChange::new(Option::none(), Option::some(post), block_of_change)); + assert_equal_after_conversion(ScheduledDelayChange::new(Option::none(), Option::none(), block_of_change)); } #[test] @@ -50,32 +33,16 @@ unconstrained fn test_serde_large_values() { let post = (max_u32 - 1) as u32; let block_of_change = (max_u32 - 2) as u32; - assert_equal_after_conversion(ScheduledDelayChange::new( - Option::some(pre), - Option::some(post), - block_of_change, - )); - assert_equal_after_conversion(ScheduledDelayChange::new( - Option::some(pre), - Option::none(), - block_of_change, - )); - assert_equal_after_conversion(ScheduledDelayChange::new( - Option::none(), - Option::some(post), - block_of_change, - )); - assert_equal_after_conversion(ScheduledDelayChange::new( - Option::none(), - Option::none(), - block_of_change, - )); + assert_equal_after_conversion(ScheduledDelayChange::new(Option::some(pre), Option::some(post), block_of_change)); + assert_equal_after_conversion(ScheduledDelayChange::new(Option::some(pre), Option::none(), block_of_change)); + assert_equal_after_conversion(ScheduledDelayChange::new(Option::none(), Option::some(post), block_of_change)); + assert_equal_after_conversion(ScheduledDelayChange::new(Option::none(), Option::none(), block_of_change)); } unconstrained fn get_non_initial_delay_change( pre: u32, post: u32, - block_of_change: u32, + block_of_change: u32 ) -> ScheduledDelayChange { ScheduledDelayChange::new(Option::some(pre), Option::some(post), block_of_change) } @@ -234,13 +201,12 @@ unconstrained fn test_schedule_change_to_longer_delay_from_initial() { unconstrained fn assert_effective_minimum_delay_invariants( delay_change: &mut ScheduledDelayChange, historical_block_number: u32, - effective_minimum_delay: u32, + effective_minimum_delay: u32 ) { // The effective minimum delays guarantees the earliest block in which a scheduled value change could be made // effective. No action, even if executed immediately after the historical block, should result in a scheduled // value change having a block of change lower than this. - let expected_earliest_value_change_block = - historical_block_number + 1 + effective_minimum_delay; + let expected_earliest_value_change_block = historical_block_number + 1 + effective_minimum_delay; if delay_change.block_of_change > historical_block_number { // If a delay change is already scheduled to happen in the future, we then must consider the scenario in @@ -253,8 +219,7 @@ unconstrained fn assert_effective_minimum_delay_invariants ScheduledValueChange { // subtract 1. min( self.block_of_change - 1, - historical_block_number + minimum_delay, + historical_block_number + minimum_delay ) } } @@ -123,7 +123,7 @@ impl ScheduledValueChange { new_value: T, current_block_number: u32, minimum_delay: u32, - block_of_change: u32, + block_of_change: u32 ) { assert(block_of_change >= current_block_number + minimum_delay); @@ -135,8 +135,7 @@ impl ScheduledValueChange { impl Serialize<3> for ScheduledValueChange where - T: ToField, -{ + T: ToField, { fn serialize(self) -> [Field; 3] { [self.pre.to_field(), self.post.to_field(), self.block_of_change.to_field()] } @@ -144,21 +143,19 @@ where impl Deserialize<3> for ScheduledValueChange where - T: FromField, -{ + T: FromField, { fn deserialize(input: [Field; 3]) -> Self { Self { pre: FromField::from_field(input[0]), post: FromField::from_field(input[1]), - block_of_change: FromField::from_field(input[2]), + block_of_change: FromField::from_field(input[2]) } } } impl Eq for ScheduledValueChange where - T: Eq, -{ + T: Eq, { fn eq(self, other: Self) -> bool { (self.pre == other.pre) & (self.post == other.post) diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/scheduled_value_change/test.nr b/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/scheduled_value_change/test.nr index 4677830d013..f335635d306 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/scheduled_value_change/test.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/scheduled_value_change/test.nr @@ -23,8 +23,7 @@ unconstrained fn test_get_current_at() { let post = 2; let block_of_change = 50; - let value_change: ScheduledValueChange = - ScheduledValueChange::new(pre, post, block_of_change); + let value_change: ScheduledValueChange = ScheduledValueChange::new(pre, post, block_of_change); assert_eq(value_change.get_current_at(0), pre); assert_eq(value_change.get_current_at(block_of_change - 1), pre); @@ -38,8 +37,7 @@ unconstrained fn test_get_scheduled() { let post = 2; let block_of_change = 50; - let value_change: ScheduledValueChange = - ScheduledValueChange::new(pre, post, block_of_change); + let value_change: ScheduledValueChange = ScheduledValueChange::new(pre, post, block_of_change); assert_eq(value_change.get_scheduled(), (post, block_of_change)); } @@ -47,7 +45,7 @@ unconstrained fn test_get_scheduled() { unconstrained fn assert_block_horizon_invariants( value_change: &mut ScheduledValueChange, historical_block_number: u32, - block_horizon: u32, + block_horizon: u32 ) { // The current value should not change at the block horizon (but it might later). let current_at_historical = value_change.get_current_at(historical_block_number); @@ -61,7 +59,7 @@ unconstrained fn assert_block_horizon_invariants( new, historical_block_number + 1, TEST_DELAY, - historical_block_number + 1 + TEST_DELAY, + historical_block_number + 1 + TEST_DELAY ); assert(value_change.block_of_change > block_horizon); @@ -73,8 +71,7 @@ unconstrained fn test_get_block_horizon_change_in_past() { let historical_block_number = 100; let block_of_change = 50; - let mut value_change: ScheduledValueChange = - ScheduledValueChange::new(1, 2, block_of_change); + let mut value_change: ScheduledValueChange = ScheduledValueChange::new(1, 2, block_of_change); let block_horizon = value_change.get_block_horizon(historical_block_number, TEST_DELAY); assert_eq(block_horizon, historical_block_number + TEST_DELAY); @@ -87,8 +84,7 @@ unconstrained fn test_get_block_horizon_change_in_immediate_past() { let historical_block_number = 100; let block_of_change = 100; - let mut value_change: ScheduledValueChange = - ScheduledValueChange::new(1, 2, block_of_change); + let mut value_change: ScheduledValueChange = ScheduledValueChange::new(1, 2, block_of_change); let block_horizon = value_change.get_block_horizon(historical_block_number, TEST_DELAY); assert_eq(block_horizon, historical_block_number + TEST_DELAY); @@ -101,8 +97,7 @@ unconstrained fn test_get_block_horizon_change_in_near_future() { let historical_block_number = 100; let block_of_change = 120; - let mut value_change: ScheduledValueChange = - ScheduledValueChange::new(1, 2, block_of_change); + let mut value_change: ScheduledValueChange = ScheduledValueChange::new(1, 2, block_of_change); // Note that this is the only scenario in which the block of change informs the block horizon. // This may result in privacy leaks when interacting with applications that have a scheduled change @@ -118,8 +113,7 @@ unconstrained fn test_get_block_horizon_change_in_far_future() { let historical_block_number = 100; let block_of_change = 500; - let mut value_change: ScheduledValueChange = - ScheduledValueChange::new(1, 2, block_of_change); + let mut value_change: ScheduledValueChange = ScheduledValueChange::new(1, 2, block_of_change); let block_horizon = value_change.get_block_horizon(historical_block_number, TEST_DELAY); assert_eq(block_horizon, historical_block_number + TEST_DELAY); @@ -132,8 +126,7 @@ unconstrained fn test_get_block_horizon_n0_delay() { let historical_block_number = 100; let block_of_change = 50; - let mut value_change: ScheduledValueChange = - ScheduledValueChange::new(1, 2, block_of_change); + let mut value_change: ScheduledValueChange = ScheduledValueChange::new(1, 2, block_of_change); let block_horizon = value_change.get_block_horizon(historical_block_number, 0); // Since the block horizon equals the historical block number, it is not possible to read the current value in @@ -147,8 +140,7 @@ unconstrained fn test_schedule_change_before_change() { let post = 2; let block_of_change = 500; - let mut value_change: ScheduledValueChange = - ScheduledValueChange::new(pre, post, block_of_change); + let mut value_change: ScheduledValueChange = ScheduledValueChange::new(pre, post, block_of_change); let new = 42; let current_block_number = block_of_change - 50; @@ -156,7 +148,7 @@ unconstrained fn test_schedule_change_before_change() { new, current_block_number, TEST_DELAY, - current_block_number + TEST_DELAY, + current_block_number + TEST_DELAY ); // Because we re-schedule before the last scheduled change takes effect, the old `post` value is lost. @@ -171,8 +163,7 @@ unconstrained fn test_schedule_change_after_change() { let post = 2; let block_of_change = 500; - let mut value_change: ScheduledValueChange = - ScheduledValueChange::new(pre, post, block_of_change); + let mut value_change: ScheduledValueChange = ScheduledValueChange::new(pre, post, block_of_change); let new = 42; let current_block_number = block_of_change + 50; @@ -180,7 +171,7 @@ unconstrained fn test_schedule_change_after_change() { new, current_block_number, TEST_DELAY, - current_block_number + TEST_DELAY, + current_block_number + TEST_DELAY ); assert_eq(value_change.pre, post); @@ -194,8 +185,7 @@ unconstrained fn test_schedule_change_no_delay() { let post = 2; let block_of_change = 500; - let mut value_change: ScheduledValueChange = - ScheduledValueChange::new(pre, post, block_of_change); + let mut value_change: ScheduledValueChange = ScheduledValueChange::new(pre, post, block_of_change); let new = 42; let current_block_number = block_of_change + 50; diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/shared_mutable.nr b/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/shared_mutable.nr index b07f08e552d..03a1edbff24 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/shared_mutable.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/shared_mutable.nr @@ -1,14 +1,12 @@ use dep::protocol_types::{ hash::{poseidon2_hash, poseidon2_hash_with_separator}, address::AztecAddress, - traits::{FromField, ToField}, utils::arrays::array_concat, + traits::{FromField, ToField}, utils::arrays::array_concat }; use crate::context::{PrivateContext, PublicContext, UnconstrainedContext}; use crate::state_vars::{ storage::Storage, - shared_mutable::{ - scheduled_value_change::ScheduledValueChange, scheduled_delay_change::ScheduledDelayChange, - }, + shared_mutable::{scheduled_value_change::ScheduledValueChange, scheduled_delay_change::ScheduledDelayChange} }; use crate::oracle::storage::storage_read; use dep::std::mem::zeroed; @@ -47,8 +45,7 @@ impl Storage for SharedMutable SharedMutable where - T: ToField + FromField + Eq, -{ + T: ToField + FromField + Eq, { pub fn new(context: Context, storage_slot: Field) -> Self { assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1."); Self { context, storage_slot } @@ -77,8 +74,7 @@ where impl SharedMutable where - T: ToField + FromField + Eq, -{ + T: ToField + FromField + Eq, { pub fn schedule_value_change(self, new_value: T) { let mut value_change = self.read_value_change(); @@ -134,7 +130,7 @@ where fn write( self, value_change: ScheduledValueChange, - delay_change: ScheduledDelayChange, + delay_change: ScheduledDelayChange ) { // Whenever we write to public storage, we write both the value change and delay change as well as the hash of // them both. This guarantees that the hash is always kept up to date. @@ -146,22 +142,20 @@ where self.context.storage_write(self.get_delay_change_storage_slot(), delay_change); self.context.storage_write( self.get_hash_storage_slot(), - SharedMutable::hash_scheduled_data(value_change, delay_change), + SharedMutable::hash_scheduled_data(value_change, delay_change) ); } } impl SharedMutable where - T: ToField + FromField + Eq, -{ + T: ToField + FromField + Eq, { pub fn get_current_value_in_private(self) -> T { // When reading the current value in private we construct a historical state proof for the public value. // However, since this value might change, we must constrain the maximum transaction block number as this proof // will only be valid for however many blocks we can ensure the value will not change, which will depend on the // current delay and any scheduled delay changes. - let (value_change, delay_change, historical_block_number) = - self.historical_read_from_public_storage(); + let (value_change, delay_change, historical_block_number) = self.historical_read_from_public_storage(); // We use the effective minimum delay as opposed to the current delay at the historical block as this one also // takes into consideration any scheduled delay changes. @@ -170,10 +164,8 @@ where // block, i.e. at block 201. But if there was a delay change scheduled for block 210 to reduce the delay to 20 // blocks, then if a value change was scheduled at block 210 it would go into effect at block 230, which is // earlier than what we'd expect if we only considered the current delay. - let effective_minimum_delay = - delay_change.get_effective_minimum_delay_at(historical_block_number); - let block_horizon = - value_change.get_block_horizon(historical_block_number, effective_minimum_delay); + let effective_minimum_delay = delay_change.get_effective_minimum_delay_at(historical_block_number); + let block_horizon = value_change.get_block_horizon(historical_block_number, effective_minimum_delay); // We prevent this transaction from being included in any block after the block horizon, ensuring that the // historical public value matches the current one, since it can only change after the horizon. @@ -181,9 +173,7 @@ where value_change.get_current_at(historical_block_number) } - fn historical_read_from_public_storage( - self, - ) -> (ScheduledValueChange, ScheduledDelayChange, u32) { + fn historical_read_from_public_storage(self) -> (ScheduledValueChange, ScheduledDelayChange, u32) { let header = self.context.get_header(); let address = self.context.this_address(); @@ -204,22 +194,16 @@ where if hash != 0 { assert_eq( - hash, - SharedMutable::hash_scheduled_data(value_change_hint, delay_change_hint), - "Hint values do not match hash", + hash, SharedMutable::hash_scheduled_data(value_change_hint, delay_change_hint), "Hint values do not match hash" ); } else { // The hash slot can only hold a zero if it is uninitialized, meaning no value or delay change was ever // scheduled. Therefore, the hints must then correspond to uninitialized scheduled changes. assert_eq( - value_change_hint, - ScheduledValueChange::deserialize(zeroed()), - "Non-zero value change for zero hash", + value_change_hint, ScheduledValueChange::deserialize(zeroed()), "Non-zero value change for zero hash" ); assert_eq( - delay_change_hint, - ScheduledDelayChange::deserialize(zeroed()), - "Non-zero delay change for zero hash", + delay_change_hint, ScheduledDelayChange::deserialize(zeroed()), "Non-zero delay change for zero hash" ); }; @@ -228,18 +212,16 @@ where fn hash_scheduled_data( value_change: ScheduledValueChange, - delay_change: ScheduledDelayChange, + delay_change: ScheduledDelayChange ) -> Field { - let concatenated: [Field; 4] = - array_concat(value_change.serialize(), delay_change.serialize()); + let concatenated: [Field; 4] = array_concat(value_change.serialize(), delay_change.serialize()); poseidon2_hash(concatenated) } } impl SharedMutable where - T: ToField + FromField + Eq, -{ + T: ToField + FromField + Eq, { pub unconstrained fn get_current_value_in_unconstrained(self) -> T { let block_number = self.context.block_number() as u32; self.read_value_change().get_current_at(block_number) @@ -253,11 +235,10 @@ where unconstrained fn get_public_storage_hints( address: AztecAddress, storage_slot: Field, - block_number: u32, + block_number: u32 ) -> (ScheduledValueChange, ScheduledDelayChange) where - T: ToField + FromField + Eq, -{ + T: ToField + FromField + Eq, { // This function cannot be part of the &mut PrivateContext impl because that'd mean that by passing `self` we'd also // be passing a mutable reference to an unconstrained function, which is not allowed. We therefore create a dummy // state variable here so that we can access the methods to compute storage slots. This will all be removed in the @@ -265,7 +246,6 @@ where let dummy: SharedMutable = SharedMutable::new((), storage_slot); ( - storage_read(address, dummy.get_value_change_storage_slot(), block_number), - storage_read(address, dummy.get_delay_change_storage_slot(), block_number), + storage_read(address, dummy.get_value_change_storage_slot(), block_number), storage_read(address, dummy.get_delay_change_storage_slot(), block_number) ) } diff --git a/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/test.nr b/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/test.nr index e3850f280c8..41964e6190b 100644 --- a/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/test.nr +++ b/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/test.nr @@ -1,9 +1,10 @@ use crate::{ context::{PublicContext, PrivateContext, UnconstrainedContext}, state_vars::shared_mutable::{ - shared_mutable::SharedMutable, scheduled_value_change::ScheduledValueChange, - scheduled_delay_change::ScheduledDelayChange, - }, test::helpers::test_environment::TestEnvironment, + shared_mutable::SharedMutable, scheduled_value_change::ScheduledValueChange, + scheduled_delay_change::ScheduledDelayChange +}, + test::helpers::test_environment::TestEnvironment }; use dep::std::{test::OracleMock, mem::zeroed}; @@ -20,22 +21,18 @@ unconstrained fn setup() -> TestEnvironment { TestEnvironment::new() } -unconstrained fn in_public( - env: TestEnvironment, -) -> SharedMutable { +unconstrained fn in_public(env: TestEnvironment) -> SharedMutable { SharedMutable::new(&mut env.public(), storage_slot) } unconstrained fn in_private( env: &mut TestEnvironment, - historical_block_number: u32, + historical_block_number: u32 ) -> SharedMutable { SharedMutable::new(&mut env.private_at(historical_block_number), storage_slot) } -unconstrained fn in_unconstrained( - env: TestEnvironment, -) -> SharedMutable { +unconstrained fn in_unconstrained(env: TestEnvironment) -> SharedMutable { SharedMutable::new(env.unkonstrained(), storage_slot) } @@ -178,10 +175,7 @@ unconstrained fn test_get_current_value_in_private_initial() { let state_var = in_private(&mut env, historical_block_number); assert_eq(state_var.get_current_value_in_private(), zeroed()); - assert_eq( - state_var.context.max_block_number.unwrap(), - historical_block_number + TEST_INITIAL_DELAY, - ); + assert_eq(state_var.context.max_block_number.unwrap(), historical_block_number + TEST_INITIAL_DELAY); } #[test] @@ -230,8 +224,7 @@ unconstrained fn test_get_current_value_in_private_at_change() { let private_state_var = in_private(&mut env, historical_block_number); assert_eq(private_state_var.get_current_value_in_private(), new_value); assert_eq( - private_state_var.context.max_block_number.unwrap(), - historical_block_number + TEST_INITIAL_DELAY, + private_state_var.context.max_block_number.unwrap(), historical_block_number + TEST_INITIAL_DELAY ); } @@ -248,8 +241,7 @@ unconstrained fn test_get_current_value_in_private_after_change() { let private_state_var = in_private(&mut env, historical_block_number); assert_eq(private_state_var.get_current_value_in_private(), new_value); assert_eq( - private_state_var.context.max_block_number.unwrap(), - historical_block_number + TEST_INITIAL_DELAY, + private_state_var.context.max_block_number.unwrap(), historical_block_number + TEST_INITIAL_DELAY ); } @@ -272,10 +264,7 @@ unconstrained fn test_get_current_value_in_private_with_non_initial_delay() { let private_state_var = in_private(&mut env, historical_block_number); assert_eq(private_state_var.get_current_value_in_private(), new_value); - assert_eq( - private_state_var.context.max_block_number.unwrap(), - historical_block_number + new_delay, - ); + assert_eq(private_state_var.context.max_block_number.unwrap(), historical_block_number + new_delay); } #[test(should_fail_with = "Hint values do not match hash")] @@ -288,15 +277,12 @@ unconstrained fn test_get_current_value_in_private_bad_value_hints() { let schedule_block_number = env.block_number(); let private_state_var = in_private(&mut env, schedule_block_number); - let mocked: ScheduledValueChange = - ScheduledValueChange::new(0, new_value + 1, schedule_block_number); - let _ = OracleMock::mock("storageRead") - .with_params(( - env.contract_address().to_field(), private_state_var.get_value_change_storage_slot(), - schedule_block_number, 3, - )) - .returns(mocked.serialize()) - .times(1); + let mocked: ScheduledValueChange = ScheduledValueChange::new(0, new_value + 1, schedule_block_number); + let _ = OracleMock::mock("storageRead").with_params( + ( + env.contract_address().to_field(), private_state_var.get_value_change_storage_slot(), schedule_block_number, 3 + ) + ).returns(mocked.serialize()).times(1); let _ = private_state_var.get_current_value_in_private(); } @@ -311,15 +297,12 @@ unconstrained fn test_get_current_value_in_private_bad_delay_hints() { let schedule_block_number = env.block_number(); let private_state_var = in_private(&mut env, schedule_block_number); - let mocked: ScheduledDelayChange = - ScheduledDelayChange::new(Option::none(), Option::some(42), schedule_block_number); - let _ = OracleMock::mock("storageRead") - .with_params(( - env.contract_address().to_field(), private_state_var.get_delay_change_storage_slot(), - schedule_block_number, 1, - )) - .returns(mocked.serialize()) - .times(1); + let mocked: ScheduledDelayChange = ScheduledDelayChange::new(Option::none(), Option::some(42), schedule_block_number); + let _ = OracleMock::mock("storageRead").with_params( + ( + env.contract_address().to_field(), private_state_var.get_delay_change_storage_slot(), schedule_block_number, 1 + ) + ).returns(mocked.serialize()).times(1); let _ = private_state_var.get_current_value_in_private(); } @@ -332,13 +315,11 @@ unconstrained fn test_get_current_value_in_private_bad_zero_hash_value_hints() { let state_var = in_private(&mut env, historical_block_number); let mocked: ScheduledValueChange = ScheduledValueChange::new(0, new_value, 0); - let _ = OracleMock::mock("storageRead") - .with_params(( - env.contract_address().to_field(), state_var.get_value_change_storage_slot(), - historical_block_number, 3, - )) - .returns(mocked.serialize()) - .times(1); + let _ = OracleMock::mock("storageRead").with_params( + ( + env.contract_address().to_field(), state_var.get_value_change_storage_slot(), historical_block_number, 3 + ) + ).returns(mocked.serialize()).times(1); let _ = state_var.get_current_value_in_private(); } @@ -350,15 +331,12 @@ unconstrained fn test_get_current_value_in_private_bad_zero_hash_delay_hints() { let historical_block_number = env.block_number(); let state_var = in_private(&mut env, historical_block_number); - let mocked: ScheduledDelayChange = - ScheduledDelayChange::new(Option::none(), Option::some(new_delay), 0); - let _ = OracleMock::mock("storageRead") - .with_params(( - env.contract_address().to_field(), state_var.get_delay_change_storage_slot(), - historical_block_number, 1, - )) - .returns(mocked.serialize()) - .times(1); + let mocked: ScheduledDelayChange = ScheduledDelayChange::new(Option::none(), Option::some(new_delay), 0); + let _ = OracleMock::mock("storageRead").with_params( + ( + env.contract_address().to_field(), state_var.get_delay_change_storage_slot(), historical_block_number, 1 + ) + ).returns(mocked.serialize()).times(1); let _ = state_var.get_current_value_in_private(); } diff --git a/noir-projects/aztec-nr/aztec/src/test/helpers/cheatcodes.nr b/noir-projects/aztec-nr/aztec/src/test/helpers/cheatcodes.nr index 2e7a44ada8f..a9eef7a559b 100644 --- a/noir-projects/aztec-nr/aztec/src/test/helpers/cheatcodes.nr +++ b/noir-projects/aztec-nr/aztec/src/test/helpers/cheatcodes.nr @@ -1,6 +1,6 @@ use dep::protocol_types::{ abis::function_selector::FunctionSelector, address::AztecAddress, public_keys::PublicKeys, - constants::CONTRACT_INSTANCE_LENGTH, contract_instance::ContractInstance, + constants::CONTRACT_INSTANCE_LENGTH, contract_instance::ContractInstance }; use crate::context::inputs::PrivateContextInputs; use crate::test::helpers::utils::TestAccount; @@ -21,9 +21,7 @@ pub unconstrained fn advance_blocks_by(blocks: u32) { oracle_advance_blocks_by(blocks); } -pub unconstrained fn get_private_context_inputs( - historical_block_number: u32, -) -> PrivateContextInputs { +pub unconstrained fn get_private_context_inputs(historical_block_number: u32) -> PrivateContextInputs { oracle_get_private_context_inputs(historical_block_number) } @@ -32,17 +30,13 @@ pub unconstrained fn deploy( name: str, initializer: str

, args: [Field], - public_keys_hash: Field, + public_keys_hash: Field ) -> ContractInstance { let instance_fields = oracle_deploy(path, name, initializer, args, public_keys_hash); ContractInstance::deserialize(instance_fields) } -pub unconstrained fn direct_storage_write( - contract_address: AztecAddress, - storage_slot: Field, - fields: [Field; N], -) { +pub unconstrained fn direct_storage_write(contract_address: AztecAddress, storage_slot: Field, fields: [Field; N]) { let _hash = direct_storage_write_oracle(contract_address, storage_slot, fields); } @@ -62,11 +56,7 @@ pub unconstrained fn add_authwit(address: AztecAddress, message_hash: Field) { orable_add_authwit(address, message_hash) } -pub unconstrained fn assert_public_call_fails( - target_address: AztecAddress, - function_selector: FunctionSelector, - args: [Field], -) { +pub unconstrained fn assert_public_call_fails(target_address: AztecAddress, function_selector: FunctionSelector, args: [Field]) { oracle_assert_public_call_fails(target_address, function_selector, args) } @@ -75,14 +65,14 @@ pub unconstrained fn assert_private_call_fails( function_selector: FunctionSelector, argsHash: Field, sideEffectsCounter: Field, - isStaticCall: bool, + isStaticCall: bool ) { oracle_assert_private_call_fails( target_address, function_selector, argsHash, sideEffectsCounter, - isStaticCall, + isStaticCall ) } @@ -99,9 +89,7 @@ unconstrained fn oracle_get_side_effects_counter() -> u32 {} unconstrained fn oracle_advance_blocks_by(blocks: u32) {} #[oracle(getPrivateContextInputs)] -unconstrained fn oracle_get_private_context_inputs( - historical_block_number: u32, -) -> PrivateContextInputs {} +unconstrained fn oracle_get_private_context_inputs(historical_block_number: u32) -> PrivateContextInputs {} #[oracle(deploy)] unconstrained fn oracle_deploy( @@ -109,14 +97,14 @@ unconstrained fn oracle_deploy( name: str, initializer: str

, args: [Field], - public_keys_hash: Field, + public_keys_hash: Field ) -> [Field; CONTRACT_INSTANCE_LENGTH] {} #[oracle(directStorageWrite)] unconstrained fn direct_storage_write_oracle( _contract_address: AztecAddress, _storage_slot: Field, - _values: [Field; N], + _values: [Field; N] ) -> [Field; N] {} #[oracle(createAccount)] @@ -135,7 +123,7 @@ unconstrained fn orable_add_authwit(address: AztecAddress, message_hash: Field) unconstrained fn oracle_assert_public_call_fails( target_address: AztecAddress, function_selector: FunctionSelector, - args: [Field], + args: [Field] ) {} #[oracle(assertPrivateCallFails)] @@ -144,5 +132,5 @@ unconstrained fn oracle_assert_private_call_fails( function_selector: FunctionSelector, argsHash: Field, sideEffectsCounter: Field, - isStaticCall: bool, + isStaticCall: bool ) {} diff --git a/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment.nr b/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment.nr index 8755aefb94a..35a70bed7d8 100644 --- a/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment.nr +++ b/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment.nr @@ -8,9 +8,7 @@ use crate::test::helpers::{cheatcodes, utils::Deployer}; use crate::hash::hash_args; use crate::note::{note_header::NoteHeader, note_interface::{NoteInterface, NullifiableNote}}; -use crate::oracle::{ - execution::{get_block_number, get_contract_address}, notes::notify_created_note, -}; +use crate::oracle::{execution::{get_block_number, get_contract_address}, notes::notify_created_note}; use protocol_types::constants::PUBLIC_DISPATCH_SELECTOR; pub struct TestEnvironment {} @@ -93,7 +91,7 @@ impl TestEnvironment { unconstrained fn deploy( _self: Self, path: str, - name: str, + name: str ) -> Deployer { Deployer { path, name, public_keys_hash: 0 } } @@ -102,31 +100,30 @@ impl TestEnvironment { Deployer { path: "", name, public_keys_hash: 0 } } - unconstrained fn assert_public_call_fails(_self: Self, call_interface: C) + unconstrained fn assert_public_call_fails( + _self: Self, + call_interface: C + ) where - C: CallInterface, - { + C: CallInterface, { // Public functions are routed through the dispatch function. let fn_selector = FunctionSelector::from_field(PUBLIC_DISPATCH_SELECTOR); - let calldata = - &[call_interface.get_selector().to_field()].append(call_interface.get_args()); - cheatcodes::assert_public_call_fails( - call_interface.get_contract_address(), - fn_selector, - calldata, - ); + let calldata = &[call_interface.get_selector().to_field()].append(call_interface.get_args()); + cheatcodes::assert_public_call_fails(call_interface.get_contract_address(), fn_selector, calldata); } - unconstrained fn assert_private_call_fails(_self: Self, call_interface: C) + unconstrained fn assert_private_call_fails( + _self: Self, + call_interface: C + ) where - C: CallInterface, - { + C: CallInterface, { cheatcodes::assert_private_call_fails( call_interface.get_contract_address(), call_interface.get_selector(), hash_args(call_interface.get_args()), cheatcodes::get_side_effects_counter() as Field, - call_interface.get_is_static(), + call_interface.get_is_static() ); } @@ -136,11 +133,10 @@ impl TestEnvironment { _self: Self, note: &mut Note, storage_slot: Field, - contract_address: AztecAddress, + contract_address: AztecAddress ) where - Note: NoteInterface + NullifiableNote, - { + Note: NoteInterface + NullifiableNote, { let original_contract_address = get_contract_address(); cheatcodes::set_contract_address(contract_address); let note_hash_counter = cheatcodes::get_side_effects_counter(); @@ -154,7 +150,7 @@ impl TestEnvironment { Note::get_note_type_id(), serialized_note, note_hash, - note_hash_counter, + note_hash_counter ); cheatcodes::set_contract_address(original_contract_address); } diff --git a/noir-projects/aztec-nr/aztec/src/test/helpers/utils.nr b/noir-projects/aztec-nr/aztec/src/test/helpers/utils.nr index 4b2e537386e..bbaf1f40d72 100644 --- a/noir-projects/aztec-nr/aztec/src/test/helpers/utils.nr +++ b/noir-projects/aztec-nr/aztec/src/test/helpers/utils.nr @@ -1,12 +1,10 @@ use dep::protocol_types::{ traits::{Deserialize, Serialize}, address::AztecAddress, public_keys::{PublicKeys, PUBLIC_KEYS_LENGTH}, abis::function_selector::FunctionSelector, - contract_instance::ContractInstance, + contract_instance::ContractInstance }; -use crate::context::{ - PrivateContext, PublicContext, UnconstrainedContext, inputs::PrivateContextInputs, -}; +use crate::context::{PrivateContext, PublicContext, UnconstrainedContext, inputs::PrivateContextInputs}; use crate::context::call_interfaces::{PublicCallInterface, CallInterface}; use crate::test::helpers::cheatcodes; @@ -26,17 +24,16 @@ pub struct Deployer { impl Deployer { pub unconstrained fn with_private_initializer( self, - call_interface: C, + call_interface: C ) -> ContractInstance where - C: CallInterface

, - { + C: CallInterface

, { let instance = cheatcodes::deploy( self.path, self.name, call_interface.get_name(), call_interface.get_args(), - self.public_keys_hash, + self.public_keys_hash ); cheatcodes::advance_blocks_by(1); let inputs = cheatcodes::get_private_context_inputs(get_block_number() - 1); @@ -48,7 +45,7 @@ impl Deployer { instance.to_address(), call_interface.get_selector(), args_hash, - call_interface.get_is_static(), + call_interface.get_is_static() ); instance @@ -56,61 +53,55 @@ impl Deployer { pub unconstrained fn with_public_void_initializer( self, - call_interface: C, + call_interface: C ) -> ContractInstance where - C: CallInterface

, - { + C: CallInterface

, { let instance = cheatcodes::deploy( self.path, self.name, call_interface.get_name(), call_interface.get_args(), - self.public_keys_hash, + self.public_keys_hash ); cheatcodes::advance_blocks_by(1); let mut public_context = PublicContext::new(|| { panic(f"Provide args hash manually") }); - public_context - .call_public_function( - instance.to_address(), - call_interface.get_selector(), - call_interface.get_args(), - GasOpts::default(), - ) - .assert_empty(); + public_context.call_public_function( + instance.to_address(), + call_interface.get_selector(), + call_interface.get_args(), + GasOpts::default() + ).assert_empty(); instance } pub unconstrained fn with_public_initializer( self, - call_interface: C, + call_interface: C ) -> ContractInstance where C: CallInterface

, - T: Deserialize<_>, - { + T: Deserialize<_>, { let instance = cheatcodes::deploy( self.path, self.name, call_interface.get_name(), call_interface.get_args(), - self.public_keys_hash, + self.public_keys_hash ); cheatcodes::advance_blocks_by(1); let mut public_context = PublicContext::new(|| { panic(f"Provide args hash manually") }); - let _: T = public_context - .call_public_function( - instance.to_address(), - call_interface.get_selector(), - call_interface.get_args(), - GasOpts::default(), - ) - .deserialize_into(); + let _: T = public_context.call_public_function( + instance.to_address(), + call_interface.get_selector(), + call_interface.get_args(), + GasOpts::default() + ).deserialize_into(); instance } diff --git a/noir-projects/aztec-nr/aztec/src/test/mocks/mock_note.nr b/noir-projects/aztec-nr/aztec/src/test/mocks/mock_note.nr index 4991710182f..a42d141d380 100644 --- a/noir-projects/aztec-nr/aztec/src/test/mocks/mock_note.nr +++ b/noir-projects/aztec-nr/aztec/src/test/mocks/mock_note.nr @@ -1,15 +1,9 @@ use crate::{ context::PrivateContext, generators::Ga1 as G_val, - note::{ - note_header::NoteHeader, note_interface::NoteInterface, - utils::compute_note_hash_for_nullify, - }, + note::{note_header::NoteHeader, note_interface::NoteInterface, utils::compute_note_hash_for_nullify} }; -use dep::protocol_types::{ - address::AztecAddress, constants::GENERATOR_INDEX__NOTE_NULLIFIER, - hash::poseidon2_hash_with_separator, -}; +use dep::protocol_types::{address::AztecAddress, constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}; use dep::std::{embedded_curve_ops::multi_scalar_mul, hash::from_field_unsafe}; use crate::note::note_interface::NullifiableNote; @@ -21,16 +15,12 @@ pub(crate) struct MockNote { } impl NullifiableNote for MockNote { - fn compute_nullifier( - _self: Self, - _context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(_self: Self, _context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { // We don't use any kind of secret here since this is only a mock note and having it here would make tests // more cumbersome poseidon2_hash_with_separator( [note_hash_for_nullify], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } @@ -40,7 +30,7 @@ impl NullifiableNote for MockNote { let note_hash_for_nullify = compute_note_hash_for_nullify(self); poseidon2_hash_with_separator( [note_hash_for_nullify], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } } @@ -90,10 +80,7 @@ impl NoteInterface for MockNote { } fn compute_note_hash(self: Self) -> Field { - assert( - self.header.storage_slot != 0, - "Storage slot must be set before computing note hash", - ); + assert(self.header.storage_slot != 0, "Storage slot must be set before computing note hash"); // We use the unsafe version because the multi_scalar_mul will constrain the scalars. let value_scalar = from_field_unsafe(self.value); multi_scalar_mul([G_val], [value_scalar]).x diff --git a/noir-projects/aztec-nr/aztec/src/unencrypted_logs/unencrypted_event_emission.nr b/noir-projects/aztec-nr/aztec/src/unencrypted_logs/unencrypted_event_emission.nr index d57bdc43a5d..8d95dcb7cb1 100644 --- a/noir-projects/aztec-nr/aztec/src/unencrypted_logs/unencrypted_event_emission.nr +++ b/noir-projects/aztec-nr/aztec/src/unencrypted_logs/unencrypted_event_emission.nr @@ -1,12 +1,14 @@ use crate::{context::PublicContext, event::event_interface::EventInterface}; use dep::protocol_types::traits::Serialize; -fn emit(context: &mut PublicContext, event: Event) +fn emit( + context: &mut PublicContext, + event: Event +) where Event: EventInterface, Event: Serialize, - [Field; N]: LensForEventSelector, -{ + [Field; N]: LensForEventSelector, { let selector = Event::get_event_type_id(); let serialized_event = event.serialize(); @@ -22,14 +24,11 @@ where context.emit_unencrypted_log(emitted_log); } -pub fn encode_event( - context: &mut PublicContext, -) -> fn[(&mut PublicContext,)](Event) -> () +pub fn encode_event(context: &mut PublicContext) -> fn[(&mut PublicContext,)](Event) -> () where Event: EventInterface, Event: Serialize, - [Field; N]: LensForEventSelector, -{ + [Field; N]: LensForEventSelector, { |e: Event| { emit(context, e); } } diff --git a/noir-projects/aztec-nr/aztec/src/utils/collapse_array.nr b/noir-projects/aztec-nr/aztec/src/utils/collapse_array.nr index ff5bc2adb82..716516191ed 100644 --- a/noir-projects/aztec-nr/aztec/src/utils/collapse_array.nr +++ b/noir-projects/aztec-nr/aztec/src/utils/collapse_array.nr @@ -5,14 +5,15 @@ // collapsed: [3, 1] pub fn collapse_array(input: [Option; N]) -> BoundedVec where - T: Eq, -{ + T: Eq, { // Computing the collpased BoundedVec would result in a very large number of constraints, since we'd need to loop // over the input array and conditionally write to a dynamic vec index, which is a very unfriendly pattern to the // proving backend. // Instead, we use an unconstrained function to produce the final collapsed array, along with some hints, and then // verify that the input and collapsed arrays are equivalent. - let (collapsed, collapsed_to_input_index_mapping) = unsafe { get_collapse_hints(input) }; + let (collapsed, collapsed_to_input_index_mapping) = unsafe { + get_collapse_hints(input) + }; verify_collapse_hints(input, collapsed, collapsed_to_input_index_mapping); collapsed } @@ -20,11 +21,10 @@ where pub(crate) fn verify_collapse_hints( input: [Option; N], collapsed: BoundedVec, - collapsed_to_input_index_mapping: BoundedVec, + collapsed_to_input_index_mapping: BoundedVec ) where - T: Eq, -{ + T: Eq, { // collapsed should be a BoundedVec with all the non-none elements in input, in the same order. We need to lay down // multiple constraints to guarantee this. // First we check that the number of elements is correct @@ -44,11 +44,7 @@ where // - collapsed: [3, 1] // - collapsed_to_input_index_mapping: [0, 2] // These two arrays should therefore have the same length. - assert_eq( - collapsed.len(), - collapsed_to_input_index_mapping.len(), - "Collapse hint vec length mismatch", - ); + assert_eq(collapsed.len(), collapsed_to_input_index_mapping.len(), "Collapse hint vec length mismatch"); // We now look at each collapsed entry and check that there is a valid equal entry in the input array. let mut last_index = Option::none(); @@ -57,11 +53,7 @@ where let input_index = collapsed_to_input_index_mapping.get_unchecked(i); assert(input_index < N, "Out of bounds index hint"); - assert_eq( - collapsed.get_unchecked(i), - input[input_index].unwrap(), - "Wrong collapsed vec content", - ); + assert_eq(collapsed.get_unchecked(i), input[input_index].unwrap(), "Wrong collapsed vec content"); // By requiring increasing input indices, we both guarantee that we're not looking at the same input // element more than once, and that we're going over them in the original order. @@ -72,11 +64,7 @@ where } else { // BoundedVec assumes that the unused parts of the storage are zeroed out (e.g. in the Eq impl), so we make // sure that this property holds. - assert_eq( - collapsed.get_unchecked(i), - std::mem::zeroed(), - "Dirty collapsed vec storage", - ); + assert_eq(collapsed.get_unchecked(i), std::mem::zeroed(), "Dirty collapsed vec storage"); } } // We now know that: @@ -87,9 +75,7 @@ where // Therefore, the collapsed array is correct. } -unconstrained fn get_collapse_hints( - input: [Option; N], -) -> (BoundedVec, BoundedVec) { +unconstrained fn get_collapse_hints(input: [Option; N]) -> (BoundedVec, BoundedVec) { let mut collapsed: BoundedVec = BoundedVec::new(); let mut collapsed_to_input_index_mapping: BoundedVec = BoundedVec::new(); diff --git a/noir-projects/aztec-nr/aztec/src/utils/comparison.nr b/noir-projects/aztec-nr/aztec/src/utils/comparison.nr index d3ec8c4f612..5cd5144bae5 100644 --- a/noir-projects/aztec-nr/aztec/src/utils/comparison.nr +++ b/noir-projects/aztec-nr/aztec/src/utils/comparison.nr @@ -59,17 +59,11 @@ mod test { let lhs = 10; let rhs = 10; - assert( - compare(lhs, Comparator.GTE, rhs), - "Expected lhs to be greater than or equal to rhs", - ); + assert(compare(lhs, Comparator.GTE, rhs), "Expected lhs to be greater than or equal to rhs"); let lhs = 11; let rhs = 10; - assert( - compare(lhs, Comparator.GTE, rhs), - "Expected lhs to be greater than or equal to rhs", - ); + assert(compare(lhs, Comparator.GTE, rhs), "Expected lhs to be greater than or equal to rhs"); let lhs = 10; let rhs = 11; @@ -85,10 +79,7 @@ mod test { let lhs = 11; let rhs = 10; - assert( - !compare(lhs, Comparator.LTE, rhs), - "Expected lhs to not be less than or equal to rhs", - ); + assert(!compare(lhs, Comparator.LTE, rhs), "Expected lhs to not be less than or equal to rhs"); let lhs = 10; let rhs = 10; @@ -96,16 +87,10 @@ mod test { let lhs = 10; let rhs = 11; - assert( - !compare(lhs, Comparator.GTE, rhs), - "Expected lhs to not be greater than or equal to rhs", - ); + assert(!compare(lhs, Comparator.GTE, rhs), "Expected lhs to not be greater than or equal to rhs"); let lhs = 10; let rhs = 11; - assert( - !compare(lhs, Comparator.GTE, rhs), - "Expected lhs to not be greater than or equal to rhs", - ); + assert(!compare(lhs, Comparator.GTE, rhs), "Expected lhs to not be greater than or equal to rhs"); } } diff --git a/noir-projects/aztec-nr/aztec/src/utils/point.nr b/noir-projects/aztec-nr/aztec/src/utils/point.nr index ecfb802dd48..6b61610de14 100644 --- a/noir-projects/aztec-nr/aztec/src/utils/point.nr +++ b/noir-projects/aztec-nr/aztec/src/utils/point.nr @@ -40,14 +40,14 @@ mod test { let p = Point { x: 0x1af41f5de96446dc3776a1eb2d98bb956b7acd9979a67854bec6fa7c2973bd73, y: 0x07fc22c7f2c7057571f137fe46ea9c95114282bc95d37d71ec4bfb88de457d4a, - is_infinite: false, + is_infinite: false }; let compressed_point = point_to_bytes(p); let expected_compressed_point_positive_sign = [ 154, 244, 31, 93, 233, 100, 70, 220, 55, 118, 161, 235, 45, 152, 187, 149, 107, 122, - 205, 153, 121, 166, 120, 84, 190, 198, 250, 124, 41, 115, 189, 115, + 205, 153, 121, 166, 120, 84, 190, 198, 250, 124, 41, 115, 189, 115 ]; assert_eq(expected_compressed_point_positive_sign, compressed_point); } @@ -57,14 +57,14 @@ mod test { let p = Point { x: 0x247371652e55dd74c9af8dbe9fb44931ba29a9229994384bd7077796c14ee2b5, y: 0x26441aec112e1ae4cee374f42556932001507ad46e255ffb27369c7e3766e5c0, - is_infinite: false, + is_infinite: false }; let compressed_point = point_to_bytes(p); let expected_compressed_point_negative_sign = [ 36, 115, 113, 101, 46, 85, 221, 116, 201, 175, 141, 190, 159, 180, 73, 49, 186, 41, 169, - 34, 153, 148, 56, 75, 215, 7, 119, 150, 193, 78, 226, 181, + 34, 153, 148, 56, 75, 215, 7, 119, 150, 193, 78, 226, 181 ]; assert_eq(expected_compressed_point_negative_sign, compressed_point); diff --git a/noir-projects/aztec-nr/aztec/src/utils/test.nr b/noir-projects/aztec-nr/aztec/src/utils/test.nr index c201e480a07..7919429d1bc 100644 --- a/noir-projects/aztec-nr/aztec/src/utils/test.nr +++ b/noir-projects/aztec-nr/aztec/src/utils/test.nr @@ -30,8 +30,7 @@ unconstrained fn collapse_sparse_array() { #[test] unconstrained fn collapse_array_front_padding() { - let original = - [Option::none(), Option::none(), Option::some(7), Option::none(), Option::some(3)]; + let original = [Option::none(), Option::none(), Option::some(7), Option::none(), Option::some(3)]; let collapsed = collapse_array(original); assert_eq(collapsed.len(), 2); @@ -41,8 +40,7 @@ unconstrained fn collapse_array_front_padding() { #[test] unconstrained fn collapse_array_back_padding() { - let original = - [Option::some(7), Option::none(), Option::some(3), Option::none(), Option::none()]; + let original = [Option::some(7), Option::none(), Option::some(3), Option::none(), Option::none()]; let collapsed = collapse_array(original); assert_eq(collapsed.len(), 2); diff --git a/noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr b/noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr index ec014ecd026..0a0ab73e964 100644 --- a/noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr +++ b/noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr @@ -1,8 +1,7 @@ use dep::aztec::{ context::PrivateContext, protocol_types::address::AztecAddress, note::note_getter_options::NoteGetterOptions, state_vars::PrivateSet, - encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, - keys::getters::get_public_keys, + encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, keys::getters::get_public_keys }; use dep::value_note::{filter::filter_notes_min_sum, value_note::ValueNote}; @@ -31,12 +30,14 @@ impl EasyPrivateUint<&mut PrivateContext> { // Insert the new note to the owner's set of notes. // docs:start:insert - self.set.insert(&mut addend_note).emit(encode_and_encrypt_note( - self.context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + self.set.insert(&mut addend_note).emit( + encode_and_encrypt_note( + self.context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); // docs:end:insert } @@ -63,11 +64,13 @@ impl EasyPrivateUint<&mut PrivateContext> { // Creates change note for the owner. let result_value = minuend - subtrahend; let mut result_note = ValueNote::new(result_value as Field, owner_keys.npk_m.hash()); - self.set.insert(&mut result_note).emit(encode_and_encrypt_note( - self.context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + self.set.insert(&mut result_note).emit( + encode_and_encrypt_note( + self.context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); } } diff --git a/noir-projects/aztec-nr/uint-note/src/uint_note.nr b/noir-projects/aztec-nr/uint-note/src/uint_note.nr index 4552c980c64..1e91f4ac2f6 100644 --- a/noir-projects/aztec-nr/uint-note/src/uint_note.nr +++ b/noir-projects/aztec-nr/uint-note/src/uint_note.nr @@ -1,8 +1,7 @@ use dep::aztec::{ prelude::{NullifiableNote, PrivateContext}, - protocol_types::{ - constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator, - }, note::utils::compute_note_hash_for_nullify, keys::getters::get_nsk_app, macros::notes::note, + protocol_types::{constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + note::utils::compute_note_hash_for_nullify, keys::getters::get_nsk_app, macros::notes::note }; #[note] @@ -16,15 +15,11 @@ pub struct UintNote { } impl NullifiableNote for UintNote { - fn compute_nullifier( - self, - context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { let secret = context.request_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } @@ -33,7 +28,7 @@ impl NullifiableNote for UintNote { let secret = get_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER, + GENERATOR_INDEX__NOTE_NULLIFIER ) } } diff --git a/noir-projects/aztec-nr/value-note/src/balance_utils.nr b/noir-projects/aztec-nr/value-note/src/balance_utils.nr index 35254d99943..5bb21120a54 100644 --- a/noir-projects/aztec-nr/value-note/src/balance_utils.nr +++ b/noir-projects/aztec-nr/value-note/src/balance_utils.nr @@ -1,17 +1,11 @@ -use dep::aztec::{ - context::UnconstrainedContext, state_vars::PrivateSet, - note::note_viewer_options::NoteViewerOptions, -}; +use dep::aztec::{context::UnconstrainedContext, state_vars::PrivateSet, note::note_viewer_options::NoteViewerOptions}; use crate::value_note::ValueNote; pub unconstrained fn get_balance(set: PrivateSet) -> Field { get_balance_with_offset(set, 0) } -pub unconstrained fn get_balance_with_offset( - set: PrivateSet, - offset: u32, -) -> Field { +pub unconstrained fn get_balance_with_offset(set: PrivateSet, offset: u32) -> Field { let mut balance = 0; // docs:start:view_notes let mut options = NoteViewerOptions::new(); diff --git a/noir-projects/aztec-nr/value-note/src/filter.nr b/noir-projects/aztec-nr/value-note/src/filter.nr index fb24074a0d9..8024414d4e5 100644 --- a/noir-projects/aztec-nr/value-note/src/filter.nr +++ b/noir-projects/aztec-nr/value-note/src/filter.nr @@ -3,7 +3,7 @@ use crate::value_note::ValueNote; pub fn filter_notes_min_sum( notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - min_sum: Field, + min_sum: Field ) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] { let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; diff --git a/noir-projects/aztec-nr/value-note/src/utils.nr b/noir-projects/aztec-nr/value-note/src/utils.nr index e5cedaf9dcb..3efc118588b 100644 --- a/noir-projects/aztec-nr/value-note/src/utils.nr +++ b/noir-projects/aztec-nr/value-note/src/utils.nr @@ -6,13 +6,8 @@ use crate::{filter::filter_notes_min_sum, value_note::{ValueNote, VALUE_NOTE_LEN // Sort the note values (0th field) in descending order. // Pick the fewest notes whose sum is equal to or greater than `amount`. -pub fn create_note_getter_options_for_decreasing_balance( - amount: Field, -) -> NoteGetterOptions { - NoteGetterOptions::with_filter(filter_notes_min_sum, amount).sort( - ValueNote::properties().value, - SortOrder.DESC, - ) +pub fn create_note_getter_options_for_decreasing_balance(amount: Field) -> NoteGetterOptions { + NoteGetterOptions::with_filter(filter_notes_min_sum, amount).sort(ValueNote::properties().value, SortOrder.DESC) } // Creates a new note for the recipient. @@ -22,19 +17,21 @@ pub fn increment( balance: PrivateSet, amount: Field, recipient: AztecAddress, - outgoing_viewer: AztecAddress, // docs:end:increment_args + outgoing_viewer: AztecAddress // docs:end:increment_args ) { let recipient_keys = get_public_keys(recipient); let outgoing_viewer_ovpk_m = get_public_keys(outgoing_viewer).ovpk_m; let mut note = ValueNote::new(amount, recipient_keys.npk_m.hash()); // Insert the new note to the owner's set of notes and emit the log if value is non-zero. - balance.insert(&mut note).emit(encode_and_encrypt_note( - balance.context, - outgoing_viewer_ovpk_m, - recipient_keys.ivpk_m, - recipient, - )); + balance.insert(&mut note).emit( + encode_and_encrypt_note( + balance.context, + outgoing_viewer_ovpk_m, + recipient_keys.ivpk_m, + recipient + ) + ); } // Find some of the `owner`'s notes whose values add up to the `amount`. @@ -45,7 +42,7 @@ pub fn decrement( balance: PrivateSet, amount: Field, owner: AztecAddress, - outgoing_viewer: AztecAddress, + outgoing_viewer: AztecAddress ) { let sum = decrement_by_at_most(balance, amount, owner, outgoing_viewer); assert(sum == amount, "Balance too low"); @@ -63,7 +60,7 @@ pub fn decrement_by_at_most( balance: PrivateSet, max_amount: Field, owner: AztecAddress, - outgoing_viewer: AztecAddress, + outgoing_viewer: AztecAddress ) -> Field { let options = create_note_getter_options_for_decreasing_balance(max_amount); let notes = balance.pop_notes(options); diff --git a/noir-projects/aztec-nr/value-note/src/value_note.nr b/noir-projects/aztec-nr/value-note/src/value_note.nr index 69d6cd68dbf..ebd2b97a437 100644 --- a/noir-projects/aztec-nr/value-note/src/value_note.nr +++ b/noir-projects/aztec-nr/value-note/src/value_note.nr @@ -1,12 +1,8 @@ use dep::aztec::{ - protocol_types::{ - traits::Serialize, constants::GENERATOR_INDEX__NOTE_NULLIFIER, - hash::poseidon2_hash_with_separator, - }, macros::notes::note, - note::{ - note_header::NoteHeader, note_interface::NullifiableNote, - utils::compute_note_hash_for_nullify, - }, oracle::random::random, keys::getters::get_nsk_app, context::PrivateContext, + protocol_types::{traits::Serialize, constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + macros::notes::note, + note::{note_header::NoteHeader, note_interface::NullifiableNote, utils::compute_note_hash_for_nullify}, + oracle::random::random, keys::getters::get_nsk_app, context::PrivateContext }; global VALUE_NOTE_LEN: u32 = 3; // 3 plus a header. @@ -27,15 +23,11 @@ pub struct ValueNote { impl NullifiableNote for ValueNote { // docs:start:nullifier - fn compute_nullifier( - self, - context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { let secret = context.request_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } @@ -46,7 +38,7 @@ impl NullifiableNote for ValueNote { let secret = get_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } } @@ -57,7 +49,9 @@ impl ValueNote { // malicious sender could use non-random values to make the note less private. But they already know the full // note pre-image anyway, and so the recipient already trusts them to not disclose this information. We can // therefore assume that the sender will cooperate in the random value generation. - let randomness = unsafe { random() }; + let randomness = unsafe { + random() + }; let header = NoteHeader::empty(); ValueNote { value, npk_m_hash, randomness, header } } diff --git a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/dapp_payload.nr b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/dapp_payload.nr index 46946dac5eb..f866a5960bf 100644 --- a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/dapp_payload.nr +++ b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/dapp_payload.nr @@ -1,7 +1,7 @@ use dep::aztec::prelude::{PrivateContext, AztecAddress}; use dep::aztec::protocol_types::{ constants::GENERATOR_INDEX__SIGNATURE_PAYLOAD, hash::poseidon2_hash_with_separator, - traits::{Hash, Serialize}, + traits::{Hash, Serialize} }; use dep::authwit::entrypoint::function_call::FunctionCall; @@ -63,14 +63,14 @@ impl DAppPayload { call.target_address, call.function_selector, call.args_hash, - call.is_static, + call.is_static ); } else { let _result = context.call_private_function_with_packed_args( call.target_address, call.function_selector, call.args_hash, - call.is_static, + call.is_static ); } } diff --git a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/main.nr b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/main.nr index 29890944b7f..dfd2f5480ab 100644 --- a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/main.nr @@ -8,11 +8,10 @@ contract AppSubscription { use crate::{dapp_payload::DAppPayload, subscription_note::SubscriptionNote}; use aztec::{ - prelude::{AztecAddress, Map, PrivateMutable, SharedImmutable}, - keys::getters::get_public_keys, protocol_types::constants::MAX_FIELD_VALUE, - utils::comparison::Comparator, + prelude::{AztecAddress, Map, PrivateMutable, SharedImmutable}, keys::getters::get_public_keys, + protocol_types::constants::MAX_FIELD_VALUE, utils::comparison::Comparator, encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, - macros::{storage::storage, functions::{public, initializer, private}}, + macros::{storage::storage, functions::{public, initializer, private}} }; use authwit::auth::assert_current_call_valid_authwit; use token::Token; @@ -48,12 +47,7 @@ contract AppSubscription { // We are emitting both the outgoing and the incoming logs to the subscriber here because passing a separate // outgoing_viewer arg to entrypoint function is impractical and the outgoing are not so valuable here. let keys = get_public_keys(user_address); - storage.subscriptions.at(user_address).replace(&mut note).emit(encode_and_encrypt_note( - &mut context, - keys.ovpk_m, - keys.ivpk_m, - user_address, - )); + storage.subscriptions.at(user_address).replace(&mut note).emit(encode_and_encrypt_note(&mut context, keys.ovpk_m, keys.ivpk_m, user_address)); context.set_as_fee_payer(); @@ -76,7 +70,7 @@ contract AppSubscription { subscription_recipient_address: AztecAddress, subscription_token_address: AztecAddress, subscription_price: Field, - fee_juice_limit_per_tx: Field, + fee_juice_limit_per_tx: Field ) { storage.target_address.initialize(target_address); storage.subscription_token_address.initialize(subscription_token_address); @@ -86,43 +80,35 @@ contract AppSubscription { } #[private] - fn subscribe( - subscriber: AztecAddress, - nonce: Field, - expiry_block_number: Field, - tx_count: Field, - ) { + fn subscribe(subscriber: AztecAddress, nonce: Field, expiry_block_number: Field, tx_count: Field) { assert(tx_count as u64 <= SUBSCRIPTION_TXS as u64); - Token::at(storage.subscription_token_address.read_private()) - .transfer_from( - context.msg_sender(), - storage.subscription_recipient_address.read_private(), - storage.subscription_price.read_private(), - nonce, - ) - .call(&mut context); + Token::at(storage.subscription_token_address.read_private()).transfer_from( + context.msg_sender(), + storage.subscription_recipient_address.read_private(), + storage.subscription_price.read_private(), + nonce + ).call(&mut context); // Assert that the `current_block_number > expiry_block_number - SUBSCRIPTION_DURATION_IN_BLOCKS`. // --> We do that via the router contract to conceal which contract is performing the check. privately_check_block_number( Comparator.GT, expiry_block_number - SUBSCRIPTION_DURATION_IN_BLOCKS, - &mut context, + &mut context ); let subscriber_keys = get_public_keys(subscriber); let msg_sender_ovpk_m = get_public_keys(context.msg_sender()).ovpk_m; - let mut subscription_note = - SubscriptionNote::new(subscriber_keys.npk_m.hash(), expiry_block_number, tx_count); + let mut subscription_note = SubscriptionNote::new(subscriber_keys.npk_m.hash(), expiry_block_number, tx_count); storage.subscriptions.at(subscriber).initialize_or_replace(&mut subscription_note).emit( encode_and_encrypt_note( &mut context, msg_sender_ovpk_m, subscriber_keys.ivpk_m, - subscriber, - ), + subscriber + ) ); } diff --git a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/subscription_note.nr b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/subscription_note.nr index 815c512544e..d71aa02b9d2 100644 --- a/noir-projects/noir-contracts/contracts/app_subscription_contract/src/subscription_note.nr +++ b/noir-projects/noir-contracts/contracts/app_subscription_contract/src/subscription_note.nr @@ -2,7 +2,7 @@ use dep::aztec::{ hash::poseidon2_hash_with_separator, note::utils::compute_note_hash_for_nullify, keys::getters::get_nsk_app, oracle::random::random, prelude::{PrivateContext, NoteHeader, NullifiableNote}, - protocol_types::constants::GENERATOR_INDEX__NOTE_NULLIFIER, macros::notes::note, + protocol_types::constants::GENERATOR_INDEX__NOTE_NULLIFIER, macros::notes::note }; #[note] @@ -16,15 +16,11 @@ pub struct SubscriptionNote { } impl NullifiableNote for SubscriptionNote { - fn compute_nullifier( - self, - context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { let secret = context.request_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } @@ -33,7 +29,7 @@ impl NullifiableNote for SubscriptionNote { let secret = get_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } } @@ -44,13 +40,9 @@ impl SubscriptionNote { // malicious sender could use non-random values to make the note less private. But they already know the full // note pre-image anyway, and so the recipient already trusts them to not disclose this information. We can // therefore assume that the sender will cooperate in the random value generation. - let randomness = unsafe { random() }; - Self { - npk_m_hash, - expiry_block_number, - remaining_txs, - randomness, - header: NoteHeader::empty(), - } + let randomness = unsafe { + random() + }; + Self { npk_m_hash, expiry_block_number, remaining_txs, randomness, header: NoteHeader::empty() } } } diff --git a/noir-projects/noir-contracts/contracts/auth_contract/src/main.nr b/noir-projects/noir-contracts/contracts/auth_contract/src/main.nr index cf5c1d9c089..18f4cd0aebb 100644 --- a/noir-projects/noir-contracts/contracts/auth_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/auth_contract/src/main.nr @@ -8,7 +8,7 @@ use dep::aztec::macros::aztec; contract Auth { use dep::aztec::{ protocol_types::address::AztecAddress, state_vars::{PublicImmutable, SharedMutable}, - macros::{storage::storage, functions::{private, public, initializer, view}}, + macros::{storage::storage, functions::{private, public, initializer, view}} }; // Authorizing a new address has a certain block delay before it goes into effect. @@ -52,8 +52,7 @@ contract Auth { #[view] fn get_scheduled_authorized() -> AztecAddress { // docs:start:shared_mutable_get_scheduled_public - let (scheduled_value, _block_of_change): (AztecAddress, u32) = - storage.authorized.get_scheduled_value_in_public(); + let (scheduled_value, _block_of_change): (AztecAddress, u32) = storage.authorized.get_scheduled_value_in_public(); // docs:end:shared_mutable_get_scheduled_public scheduled_value } diff --git a/noir-projects/noir-contracts/contracts/auth_contract/src/test/utils.nr b/noir-projects/noir-contracts/contracts/auth_contract/src/test/utils.nr index 3ba53d12941..9b1d920a2a1 100644 --- a/noir-projects/noir-contracts/contracts/auth_contract/src/test/utils.nr +++ b/noir-projects/noir-contracts/contracts/auth_contract/src/test/utils.nr @@ -11,8 +11,7 @@ pub unconstrained fn setup() -> (&mut TestEnvironment, AztecAddress, AztecAddres let initializer_call_interface = Auth::interface().constructor(admin); - let auth_contract = - env.deploy_self("Auth").with_public_void_initializer(initializer_call_interface); + let auth_contract = env.deploy_self("Auth").with_public_void_initializer(initializer_call_interface); let auth_contract_address = auth_contract.to_address(); env.advance_block_by(1); (&mut env, auth_contract_address, admin, to_authorize, other) diff --git a/noir-projects/noir-contracts/contracts/auth_registry_contract/src/main.nr b/noir-projects/noir-contracts/contracts/auth_registry_contract/src/main.nr index e21398eefcc..4fed8760fce 100644 --- a/noir-projects/noir-contracts/contracts/auth_registry_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/auth_registry_contract/src/main.nr @@ -4,11 +4,9 @@ use dep::aztec::macros::aztec; contract AuthRegistry { use dep::aztec::{ state_vars::{PublicMutable, Map}, protocol_types::address::AztecAddress, - macros::{storage::storage, functions::{private, public, internal, view}}, - }; - use dep::authwit::auth::{ - IS_VALID_SELECTOR, compute_authwit_message_hash, assert_current_call_valid_authwit, + macros::{storage::storage, functions::{private, public, internal, view}} }; + use dep::authwit::auth::{IS_VALID_SELECTOR, compute_authwit_message_hash, assert_current_call_valid_authwit}; #[storage] struct Storage { @@ -58,7 +56,7 @@ contract AuthRegistry { context.msg_sender(), context.chain_id(), context.version(), - inner_hash, + inner_hash ); let authorized = storage.approved_actions.at(on_behalf_of).at(message_hash).read(); @@ -83,9 +81,7 @@ contract AuthRegistry { #[private] fn set_authorized_private(approver: AztecAddress, message_hash: Field, authorize: bool) { assert_current_call_valid_authwit(&mut context, approver); - AuthRegistry::at(context.this_address()) - ._set_authorized(approver, message_hash, authorize) - .enqueue(&mut context); + AuthRegistry::at(context.this_address())._set_authorized(approver, message_hash, authorize).enqueue(&mut context); } /** @@ -127,10 +123,7 @@ contract AuthRegistry { storage.approved_actions.at(on_behalf_of).at(message_hash).read() } - unconstrained fn unconstrained_is_consumable( - on_behalf_of: AztecAddress, - message_hash: Field, - ) -> pub bool { + unconstrained fn unconstrained_is_consumable(on_behalf_of: AztecAddress, message_hash: Field) -> pub bool { storage.approved_actions.at(on_behalf_of).at(message_hash).read() } } diff --git a/noir-projects/noir-contracts/contracts/auth_wit_test_contract/src/main.nr b/noir-projects/noir-contracts/contracts/auth_wit_test_contract/src/main.nr index eb317769c20..41b9f6d10ba 100644 --- a/noir-projects/noir-contracts/contracts/auth_wit_test_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/auth_wit_test_contract/src/main.nr @@ -4,9 +4,7 @@ use dep::aztec::macros::aztec; contract AuthWitTest { use dep::aztec::{protocol_types::address::AztecAddress, macros::functions::{private, public}}; - use dep::authwit::auth::{ - assert_inner_hash_valid_authwit, assert_inner_hash_valid_authwit_public, - }; + use dep::authwit::auth::{assert_inner_hash_valid_authwit, assert_inner_hash_valid_authwit_public}; #[private] fn consume(on_behalf_of: AztecAddress, inner_hash: Field) { diff --git a/noir-projects/noir-contracts/contracts/avm_initializer_test_contract/src/main.nr b/noir-projects/noir-contracts/contracts/avm_initializer_test_contract/src/main.nr index 463e17c5030..8c74544a783 100644 --- a/noir-projects/noir-contracts/contracts/avm_initializer_test_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/avm_initializer_test_contract/src/main.nr @@ -3,9 +3,7 @@ use dep::aztec::macros::aztec; #[aztec] contract AvmInitializerTest { // Libs - use dep::aztec::{ - state_vars::PublicImmutable, macros::{storage::storage, functions::{initializer, public}}, - }; + use dep::aztec::{state_vars::PublicImmutable, macros::{storage::storage, functions::{initializer, public}}}; #[storage] struct Storage { diff --git a/noir-projects/noir-contracts/contracts/avm_test_contract/src/main.nr b/noir-projects/noir-contracts/contracts/avm_test_contract/src/main.nr index ff31737f6ab..2004444887f 100644 --- a/noir-projects/noir-contracts/contracts/avm_test_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/avm_test_contract/src/main.nr @@ -33,15 +33,9 @@ contract AvmTest { use dep::aztec::protocol_types::constants::CONTRACT_INSTANCE_LENGTH; use dep::aztec::prelude::Map; use dep::aztec::state_vars::PublicMutable; - use dep::aztec::protocol_types::{ - address::{AztecAddress, EthAddress}, point::Point, scalar::Scalar, - }; - use dep::aztec::oracle::get_contract_instance::{ - get_contract_instance_avm, get_contract_instance_internal_avm, - }; - use dep::aztec::protocol_types::{ - abis::function_selector::FunctionSelector, storage::map::derive_storage_slot_in_map, - }; + use dep::aztec::protocol_types::{address::{AztecAddress, EthAddress}, point::Point, scalar::Scalar}; + use dep::aztec::oracle::get_contract_instance::{get_contract_instance_avm, get_contract_instance_internal_avm}; + use dep::aztec::protocol_types::{abis::function_selector::FunctionSelector, storage::map::derive_storage_slot_in_map}; use dep::compressed_string::CompressedString; use dep::aztec::macros::{storage::storage, functions::{public, private}}; use dep::aztec::context::gas::GasOpts; @@ -159,11 +153,7 @@ contract AvmTest { #[public] fn elliptic_curve_add_and_double() -> Point { - let g = Point { - x: 1, - y: 17631683881184975370165255887551781615748388533673675138860, - is_infinite: false, - }; + let g = Point { x: 1, y: 17631683881184975370165255887551781615748388533673675138860, is_infinite: false }; let doubled = g + g; let added = g + doubled; @@ -172,11 +162,7 @@ contract AvmTest { #[public] fn variable_base_msm() -> Point { - let g = Point { - x: 1, - y: 17631683881184975370165255887551781615748388533673675138860, - is_infinite: false, - }; + let g = Point { x: 1, y: 17631683881184975370165255887551781615748388533673675138860, is_infinite: false }; let scalar = Scalar { lo: 3, hi: 0 }; let scalar2 = Scalar { lo: 20, hi: 0 }; let triple_g = multi_scalar_mul([g, g], [scalar, scalar2]); @@ -208,7 +194,7 @@ contract AvmTest { #[public] fn to_radix_le(input: Field) -> [u8; 10] { - input.to_le_radix( /*base=*/ 2) + input.to_le_radix(/*base=*/ 2) } // Helper functions to demonstrate an internal call stack in error messages @@ -282,7 +268,7 @@ contract AvmTest { #[public] fn pedersen_hash_with_index(data: [Field; 10]) -> Field { - std::hash::pedersen_hash_with_separator(data, /*index=*/ 20) + std::hash::pedersen_hash_with_separator(data, /*index=*/ 20) } /************************************************************************ @@ -390,8 +376,9 @@ contract AvmTest { #[public] fn check_selector() { assert( - context.selector() == comptime { FunctionSelector::from_signature("check_selector()") }, - "Unexpected selector!", + context.selector() == comptime { + FunctionSelector::from_signature("check_selector()") + }, "Unexpected selector!" ); } @@ -402,11 +389,10 @@ contract AvmTest { #[public] fn emit_unencrypted_log() { - context.emit_unencrypted_log( /*message=*/ [10, 20, 30]); - context.emit_unencrypted_log( /*message=*/ "Hello, world!"); - let s: CompressedString<2, 44> = - CompressedString::from_string("A long time ago, in a galaxy far far away..."); - context.emit_unencrypted_log( /*message=*/ s); + context.emit_unencrypted_log(/*message=*/ [10, 20, 30]); + context.emit_unencrypted_log(/*message=*/ "Hello, world!"); + let s: CompressedString<2, 44> = CompressedString::from_string("A long time ago, in a galaxy far far away..."); + context.emit_unencrypted_log(/*message=*/ s); } #[public] @@ -434,10 +420,7 @@ contract AvmTest { #[public] fn assert_nullifier_exists(nullifier: Field) { - assert( - context.nullifier_exists(nullifier, context.this_address()), - "Nullifier doesn't exist!", - ); + assert(context.nullifier_exists(nullifier, context.this_address()), "Nullifier doesn't exist!"); } // Use the standard context interface to emit a new nullifier @@ -474,12 +457,9 @@ contract AvmTest { arg_a: Field, arg_b: Field, l2_gas: Field, - da_gas: Field, + da_gas: Field ) -> pub Field { - AvmTest::at(context.this_address()) - .add_args_return(arg_a, arg_b) - .with_gas(GasOpts::new(l2_gas, da_gas)) - .call(&mut context) + AvmTest::at(context.this_address()).add_args_return(arg_a, arg_b).with_gas(GasOpts::new(l2_gas, da_gas)).call(&mut context) } // Use the `call_public_function` wrapper to initiate a nested call to the add function diff --git a/noir-projects/noir-contracts/contracts/card_game_contract/src/cards.nr b/noir-projects/noir-contracts/contracts/card_game_contract/src/cards.nr index ded14bb8b76..3f7adf33c83 100644 --- a/noir-projects/noir-contracts/contracts/card_game_contract/src/cards.nr +++ b/noir-projects/noir-contracts/contracts/card_game_contract/src/cards.nr @@ -2,10 +2,9 @@ use dep::aztec::prelude::{AztecAddress, PrivateContext, NoteGetterOptions, NoteV use dep::aztec::{ context::UnconstrainedContext, - protocol_types::{ - traits::{ToField, Serialize, FromField}, constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, - }, encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, - keys::getters::get_public_keys, state_vars::PrivateSet, note::constants::MAX_NOTES_PER_PAGE, + protocol_types::{traits::{ToField, Serialize, FromField}, constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL}, + encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, keys::getters::get_public_keys, + state_vars::PrivateSet, note::constants::MAX_NOTES_PER_PAGE }; use dep::value_note::value_note::ValueNote; @@ -71,7 +70,7 @@ pub struct Deck { pub fn filter_cards( notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - desired_cards: [Card; N], + desired_cards: [Card; N] ) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] { let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; @@ -113,12 +112,7 @@ impl Deck<&mut PrivateContext> { let mut inserted_cards = &[]; for card in cards { let mut card_note = CardNote::from_card(card, owner_npk_m_hash); - self.set.insert(&mut card_note.note).emit(encode_and_encrypt_note( - self.set.context, - msg_sender_ovpk_m, - owner_ivpk_m, - owner, - )); + self.set.insert(&mut card_note.note).emit(encode_and_encrypt_note(self.set.context, msg_sender_ovpk_m, owner_ivpk_m, owner)); inserted_cards = inserted_cards.push_back(card_note); } @@ -154,7 +148,7 @@ global PACK_CARDS = 3; // Limited by number of write requests (max 4) pub fn get_pack_cards( seed: Field, owner: AztecAddress, - context: &mut PrivateContext, + context: &mut PrivateContext ) -> [Card; PACK_CARDS] { let owner_npk_m_hash = get_public_keys(owner).npk_m.hash(); diff --git a/noir-projects/noir-contracts/contracts/card_game_contract/src/game.nr b/noir-projects/noir-contracts/contracts/card_game_contract/src/game.nr index 01991ddf74d..4275b435427 100644 --- a/noir-projects/noir-contracts/contracts/card_game_contract/src/game.nr +++ b/noir-projects/noir-contracts/contracts/card_game_contract/src/game.nr @@ -67,7 +67,7 @@ impl Serialize for Game { game.finished as Field, game.claimed as Field, game.current_player as Field, - game.current_round as Field, + game.current_round as Field ] } } @@ -82,7 +82,7 @@ impl Deserialize for Game { Card::from_field(fields[6]), Card::from_field(fields[7]), Card::from_field(fields[8]), - Card::from_field(fields[9]), + Card::from_field(fields[9]) ]; Game { players, @@ -91,7 +91,7 @@ impl Deserialize for Game { finished: fields[11] as bool, claimed: fields[12] as bool, current_player: fields[13] as u32, - current_round: fields[14] as u32, + current_round: fields[14] as u32 } } } @@ -119,9 +119,11 @@ impl Game { let entry = self.players[i]; assert(entry.is_initialized(), "Game not full"); } - let sorted_by_deck_strength = self.players.sort_via(|a: PlayerEntry, b: PlayerEntry| { + let sorted_by_deck_strength = self.players.sort_via( + |a: PlayerEntry, b: PlayerEntry| { a.deck_strength < b.deck_strength - }); + } + ); self.players = sorted_by_deck_strength; self.started = true; } diff --git a/noir-projects/noir-contracts/contracts/card_game_contract/src/main.nr b/noir-projects/noir-contracts/contracts/card_game_contract/src/main.nr index 2cdb926ac63..095f870193b 100644 --- a/noir-projects/noir-contracts/contracts/card_game_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/card_game_contract/src/main.nr @@ -22,8 +22,7 @@ contract CardGame { } #[private] - fn buy_pack( - seed: Field, // The randomness used to generate the cards. Passed in for now. + fn buy_pack(seed: Field // The randomness used to generate the cards. Passed in for now. ) { let buyer = context.msg_sender(); let mut cards = get_pack_cards(seed, buyer, &mut context); @@ -43,9 +42,7 @@ contract CardGame { let mut game_deck = storage.game_decks.at(game as Field).at(player); let _added_to_game_deck = game_deck.add_cards(cards, player); let strength = compute_deck_strength(cards); - CardGame::at(context.this_address()).on_game_joined(game, player, strength as u32).enqueue( - &mut context, - ); + CardGame::at(context.this_address()).on_game_joined(game, player, strength as u32).enqueue(&mut context); } #[public] @@ -54,10 +51,7 @@ contract CardGame { let game_storage = storage.games.at(game as Field); let mut game_data = game_storage.read(); - assert( - game_data.add_player(PlayerEntry { address: player, deck_strength, points: 0 }), - "Game full", - ); + assert(game_data.add_player(PlayerEntry { address: player, deck_strength, points: 0 }), "Game full"); game_storage.write(game_data); } @@ -79,9 +73,7 @@ contract CardGame { game_deck.remove_cards([card]); // docs:start:call_public_function - CardGame::at(context.this_address()).on_card_played(game, player, card.to_field()).enqueue( - &mut context, - ); + CardGame::at(context.this_address()).on_card_played(game, player, card.to_field()).enqueue(&mut context); // docs:end:call_public_function } @@ -107,9 +99,7 @@ contract CardGame { let mut collection = storage.collections.at(player); let _inserted_cards = collection.add_cards(cards, player); - CardGame::at(context.this_address()) - .on_cards_claimed(game, player, pedersen_hash(cards_fields, 0)) - .enqueue(&mut context); + CardGame::at(context.this_address()).on_cards_claimed(game, player, pedersen_hash(cards_fields, 0)).enqueue(&mut context); } #[public] @@ -121,10 +111,7 @@ contract CardGame { assert(!game_data.claimed, "Already claimed"); game_data.claimed = true; - assert_eq( - cards_hash, - pedersen_hash(game_data.rounds_cards.map(|card: Card| card.to_field()), 0), - ); + assert_eq(cards_hash, pedersen_hash(game_data.rounds_cards.map(|card: Card| card.to_field()), 0)); let winner = game_data.winner(); assert(player.eq(winner.address), "Not the winner"); @@ -132,19 +119,12 @@ contract CardGame { game_storage.write(game_data); } - unconstrained fn view_collection_cards( - owner: AztecAddress, - offset: u32, - ) -> pub BoundedVec { + unconstrained fn view_collection_cards(owner: AztecAddress, offset: u32) -> pub BoundedVec { let collection = storage.collections.at(owner); collection.view_cards(offset) } - unconstrained fn view_game_cards( - game: u32, - player: AztecAddress, - offset: u32, - ) -> pub BoundedVec { + unconstrained fn view_game_cards(game: u32, player: AztecAddress, offset: u32) -> pub BoundedVec { let game_deck = storage.game_decks.at(game as Field).at(player); game_deck.view_cards(offset) diff --git a/noir-projects/noir-contracts/contracts/child_contract/src/main.nr b/noir-projects/noir-contracts/contracts/child_contract/src/main.nr index 7e97d112e5f..8c375f80dda 100644 --- a/noir-projects/noir-contracts/contracts/child_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/child_contract/src/main.nr @@ -9,7 +9,7 @@ contract Child { note::note_getter_options::NoteGetterOptions, encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, keys::getters::get_public_keys, utils::comparison::Comparator, - macros::{storage::storage, functions::{private, public, internal}}, + macros::{storage::storage, functions::{private, public, internal}} }; use dep::value_note::value_note::ValueNote; @@ -58,12 +58,7 @@ contract Child { let owner_keys = get_public_keys(owner); let mut note = ValueNote::new(new_value, owner_keys.npk_m.hash()); - storage.a_map_with_private_values.at(owner).insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - owner_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + storage.a_map_with_private_values.at(owner).insert(&mut note).emit(encode_and_encrypt_note(&mut context, owner_keys.ovpk_m, owner_keys.ivpk_m, owner)); new_value } diff --git a/noir-projects/noir-contracts/contracts/claim_contract/src/main.nr b/noir-projects/noir-contracts/contracts/claim_contract/src/main.nr index 0d7259d168c..0a7cdc4fda4 100644 --- a/noir-projects/noir-contracts/contracts/claim_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/claim_contract/src/main.nr @@ -5,7 +5,7 @@ contract Claim { use dep::aztec::{ note::utils::compute_note_hash_for_nullify, protocol_types::address::AztecAddress, state_vars::SharedImmutable, - macros::{storage::storage, functions::{private, public, initializer}}, + macros::{storage::storage, functions::{private, public, initializer}} }; use dep::value_note::value_note::ValueNote; use token::Token; @@ -30,8 +30,7 @@ contract Claim { // 1) Check that the note corresponds to the target contract and belongs to the sender let target_address = storage.target_contract.read_private(); assert( - target_address == proof_note.header.contract_address, - "Note does not correspond to the target contract", + target_address == proof_note.header.contract_address, "Note does not correspond to the target contract" ); // 2) Prove that the note hash exists in the note hash tree @@ -50,8 +49,6 @@ contract Claim { context.push_nullifier(nullifier); // 4) Finally we mint the reward token to the sender of the transaction - Token::at(storage.reward_token.read_private()) - .mint_public(recipient, proof_note.value) - .enqueue(&mut context); + Token::at(storage.reward_token.read_private()).mint_public(recipient, proof_note.value).enqueue(&mut context); } } diff --git a/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/class_registered.nr b/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/class_registered.nr index f89db47b7bd..3a67ffbf2e0 100644 --- a/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/class_registered.nr +++ b/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/class_registered.nr @@ -1,8 +1,7 @@ use dep::aztec::protocol_types::{ contract_class_id::ContractClassId, - constants::{ - MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS, REGISTERER_CONTRACT_CLASS_REGISTERED_MAGIC_VALUE, - }, traits::Serialize, + constants::{MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS, REGISTERER_CONTRACT_CLASS_REGISTERED_MAGIC_VALUE}, + traits::Serialize }; // #[event] diff --git a/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/private_function_broadcasted.nr b/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/private_function_broadcasted.nr index 7a542059f9b..24b82a26618 100644 --- a/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/private_function_broadcasted.nr +++ b/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/private_function_broadcasted.nr @@ -2,11 +2,12 @@ use dep::aztec::prelude::FunctionSelector; use dep::aztec::protocol_types::{ contract_class_id::ContractClassId, constants::{ - FUNCTION_TREE_HEIGHT, ARTIFACT_FUNCTION_TREE_MAX_HEIGHT, - MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS, - REGISTERER_PRIVATE_FUNCTION_BROADCASTED_MAGIC_VALUE, - REGISTERER_PRIVATE_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS, - }, traits::Serialize, + FUNCTION_TREE_HEIGHT, ARTIFACT_FUNCTION_TREE_MAX_HEIGHT, + MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS, + REGISTERER_PRIVATE_FUNCTION_BROADCASTED_MAGIC_VALUE, + REGISTERER_PRIVATE_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS +}, + traits::Serialize }; pub struct InnerPrivateFunction { @@ -29,9 +30,7 @@ pub struct PrivateFunction { } impl Serialize for PrivateFunction { - fn serialize( - self: Self, - ) -> [Field; MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS + 3] { + fn serialize(self: Self) -> [Field; MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS + 3] { let mut packed = [0; MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS + 3]; packed[0] = self.selector.to_field(); packed[1] = self.metadata_hash; @@ -56,13 +55,9 @@ pub struct ClassPrivateFunctionBroadcasted { } impl Serialize for ClassPrivateFunctionBroadcasted { - fn serialize( - self: Self, - ) -> [Field; MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS + REGISTERER_PRIVATE_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS] { - let mut packed = [ - 0; MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS - + REGISTERER_PRIVATE_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS - ]; + fn serialize(self: Self) -> [Field; MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS + REGISTERER_PRIVATE_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS] { + let mut packed = [0; MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS + + REGISTERER_PRIVATE_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS]; packed[0] = REGISTERER_PRIVATE_FUNCTION_BROADCASTED_MAGIC_VALUE; packed[1] = self.contract_class_id.to_field(); packed[2] = self.artifact_metadata_hash; diff --git a/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/unconstrained_function_broadcasted.nr b/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/unconstrained_function_broadcasted.nr index d2a9995d8ed..810f677135d 100644 --- a/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/unconstrained_function_broadcasted.nr +++ b/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/events/unconstrained_function_broadcasted.nr @@ -2,11 +2,11 @@ use dep::aztec::prelude::FunctionSelector; use dep::aztec::protocol_types::{ contract_class_id::ContractClassId, constants::{ - ARTIFACT_FUNCTION_TREE_MAX_HEIGHT, - MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS, - REGISTERER_UNCONSTRAINED_FUNCTION_BROADCASTED_MAGIC_VALUE, - REGISTERER_UNCONSTRAINED_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS, - }, traits::Serialize, + ARTIFACT_FUNCTION_TREE_MAX_HEIGHT, MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS, + REGISTERER_UNCONSTRAINED_FUNCTION_BROADCASTED_MAGIC_VALUE, + REGISTERER_UNCONSTRAINED_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS +}, + traits::Serialize }; pub struct InnerUnconstrainedFunction { @@ -27,9 +27,7 @@ pub struct UnconstrainedFunction { } impl Serialize for UnconstrainedFunction { - fn serialize( - self: Self, - ) -> [Field; MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS + 2] { + fn serialize(self: Self) -> [Field; MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS + 2] { let mut packed = [0; MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS + 2]; packed[0] = self.selector.to_field(); packed[1] = self.metadata_hash; @@ -51,13 +49,9 @@ pub struct ClassUnconstrainedFunctionBroadcasted { } impl Serialize for ClassUnconstrainedFunctionBroadcasted { - fn serialize( - self: Self, - ) -> [Field; MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS + REGISTERER_UNCONSTRAINED_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS] { - let mut packed = [ - 0; MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS - + REGISTERER_UNCONSTRAINED_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS - ]; + fn serialize(self: Self) -> [Field; MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS + REGISTERER_UNCONSTRAINED_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS] { + let mut packed = [0; MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS + + REGISTERER_UNCONSTRAINED_FUNCTION_BROADCASTED_ADDITIONAL_FIELDS]; packed[0] = REGISTERER_UNCONSTRAINED_FUNCTION_BROADCASTED_MAGIC_VALUE; packed[1] = self.contract_class_id.to_field(); packed[2] = self.artifact_metadata_hash; diff --git a/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/main.nr b/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/main.nr index 4a20582ea6e..89db2b4e8ae 100644 --- a/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/contract_class_registerer_contract/src/main.nr @@ -8,27 +8,23 @@ contract ContractClassRegisterer { use dep::aztec::protocol_types::{ contract_class_id::ContractClassId, constants::{ - ARTIFACT_FUNCTION_TREE_MAX_HEIGHT, FUNCTION_TREE_HEIGHT, - MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS, - MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS, - MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS, - }, abis::log_hash::LogHash, + ARTIFACT_FUNCTION_TREE_MAX_HEIGHT, FUNCTION_TREE_HEIGHT, + MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS, + MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS, + MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS + }, + abis::log_hash::LogHash }; use dep::aztec::{ context::PrivateContext, oracle::logs::emit_contract_class_unencrypted_log_private, - macros::functions::private, + macros::functions::private }; use crate::events::{ class_registered::ContractClassRegistered, - private_function_broadcasted::{ - ClassPrivateFunctionBroadcasted, PrivateFunction, InnerPrivateFunction, - }, - unconstrained_function_broadcasted::{ - ClassUnconstrainedFunctionBroadcasted, UnconstrainedFunction, - InnerUnconstrainedFunction, - }, + private_function_broadcasted::{ClassPrivateFunctionBroadcasted, PrivateFunction, InnerPrivateFunction}, + unconstrained_function_broadcasted::{ClassUnconstrainedFunctionBroadcasted, UnconstrainedFunction, InnerUnconstrainedFunction} }; // docs:start:import_pop_capsule @@ -36,43 +32,32 @@ contract ContractClassRegisterer { // docs:end:import_pop_capsule #[private] - fn register( - artifact_hash: Field, - private_functions_root: Field, - public_bytecode_commitment: Field, - ) { + fn register(artifact_hash: Field, private_functions_root: Field, public_bytecode_commitment: Field) { // TODO: Validate public_bytecode_commitment is the correct commitment of packed_public_bytecode // TODO: Validate packed_public_bytecode is legit public bytecode // docs:start:pop_capsule - let packed_public_bytecode: [Field; MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS] = - pop_capsule(); + let packed_public_bytecode: [Field; MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS] = pop_capsule(); // docs:end:pop_capsule // Compute contract class id from preimage let contract_class_id = ContractClassId::compute( artifact_hash, private_functions_root, - public_bytecode_commitment, + public_bytecode_commitment ); // Emit the contract class id as a nullifier to be able to prove that this class has been (not) registered - let event = ContractClassRegistered { - contract_class_id, - version: 1, - artifact_hash, - private_functions_root, - packed_public_bytecode, - }; + let event = ContractClassRegistered { contract_class_id, version: 1, artifact_hash, private_functions_root, packed_public_bytecode }; context.push_nullifier(contract_class_id.to_field()); // Broadcast class info including public bytecode dep::aztec::oracle::debug_log::debug_log_format( "ContractClassRegistered: {}", [ - contract_class_id.to_field(), - artifact_hash, - private_functions_root, - public_bytecode_commitment, - ], + contract_class_id.to_field(), + artifact_hash, + private_functions_root, + public_bytecode_commitment + ] ); emit_contract_class_unencrypted_log(&mut context, event.serialize()); } @@ -86,10 +71,9 @@ contract ContractClassRegisterer { private_function_tree_leaf_index: Field, artifact_function_tree_sibling_path: [Field; ARTIFACT_FUNCTION_TREE_MAX_HEIGHT], artifact_function_tree_leaf_index: Field, - function_data: InnerPrivateFunction, + function_data: InnerPrivateFunction ) { - let private_bytecode: [Field; MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS] = - pop_capsule(); + let private_bytecode: [Field; MAX_PACKED_BYTECODE_SIZE_PER_PRIVATE_FUNCTION_IN_FIELDS] = pop_capsule(); let event = ClassPrivateFunctionBroadcasted { contract_class_id, @@ -103,19 +87,19 @@ contract ContractClassRegisterer { selector: function_data.selector, metadata_hash: function_data.metadata_hash, vk_hash: function_data.vk_hash, - bytecode: private_bytecode, - }, + bytecode: private_bytecode + } }; dep::aztec::oracle::debug_log::debug_log_format( "ClassPrivateFunctionBroadcasted: {}", [ - contract_class_id.to_field(), - artifact_metadata_hash, - unconstrained_functions_artifact_tree_root, - function_data.selector.to_field(), - function_data.vk_hash, - function_data.metadata_hash, - ], + contract_class_id.to_field(), + artifact_metadata_hash, + unconstrained_functions_artifact_tree_root, + function_data.selector.to_field(), + function_data.vk_hash, + function_data.metadata_hash + ] ); emit_contract_class_unencrypted_log(&mut context, event.serialize()); } @@ -127,10 +111,9 @@ contract ContractClassRegisterer { private_functions_artifact_tree_root: Field, artifact_function_tree_sibling_path: [Field; ARTIFACT_FUNCTION_TREE_MAX_HEIGHT], artifact_function_tree_leaf_index: Field, - function_data: InnerUnconstrainedFunction, + function_data: InnerUnconstrainedFunction ) { - let unconstrained_bytecode: [Field; MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS] = - pop_capsule(); + let unconstrained_bytecode: [Field; MAX_PACKED_BYTECODE_SIZE_PER_UNCONSTRAINED_FUNCTION_IN_FIELDS] = pop_capsule(); let event = ClassUnconstrainedFunctionBroadcasted { contract_class_id, artifact_metadata_hash, @@ -140,27 +123,24 @@ contract ContractClassRegisterer { function: UnconstrainedFunction { selector: function_data.selector, metadata_hash: function_data.metadata_hash, - bytecode: unconstrained_bytecode, - }, + bytecode: unconstrained_bytecode + } }; dep::aztec::oracle::debug_log::debug_log_format( "ClassUnconstrainedFunctionBroadcasted: {}", [ - contract_class_id.to_field(), - artifact_metadata_hash, - private_functions_artifact_tree_root, - function_data.selector.to_field(), - function_data.metadata_hash, - ], + contract_class_id.to_field(), + artifact_metadata_hash, + private_functions_artifact_tree_root, + function_data.selector.to_field(), + function_data.metadata_hash + ] ); emit_contract_class_unencrypted_log(&mut context, event.serialize()); } #[contract_library_method] - fn emit_contract_class_unencrypted_log( - context: &mut PrivateContext, - log: [Field; N], - ) { + fn emit_contract_class_unencrypted_log(context: &mut PrivateContext, log: [Field; N]) { let contract_address = context.this_address(); let counter = context.next_counter(); @@ -177,8 +157,6 @@ contract ContractClassRegisterer { let log_hash = emit_contract_class_unencrypted_log_private(contract_address, log, counter); // 40 = addr (32) + raw log len (4) + processed log len (4) - context.unencrypted_logs_hashes.push( - LogHash { value: log_hash, counter, length: 40 + (N as Field) * 32 }, - ); + context.unencrypted_logs_hashes.push(LogHash { value: log_hash, counter, length: 40 + (N as Field) * 32 }); } } diff --git a/noir-projects/noir-contracts/contracts/contract_instance_deployer_contract/src/main.nr b/noir-projects/noir-contracts/contracts/contract_instance_deployer_contract/src/main.nr index 6ffb083f264..25b895a1625 100644 --- a/noir-projects/noir-contracts/contracts/contract_instance_deployer_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/contract_instance_deployer_contract/src/main.nr @@ -4,13 +4,12 @@ use dep::aztec::macros::aztec; contract ContractInstanceDeployer { use dep::aztec::protocol_types::{ address::{AztecAddress, PublicKeysHash, PartialAddress}, public_keys::PublicKeys, - contract_class_id::ContractClassId, - constants::DEPLOYER_CONTRACT_INSTANCE_DEPLOYED_MAGIC_VALUE, abis::log_hash::LogHash, - traits::Serialize, + contract_class_id::ContractClassId, constants::DEPLOYER_CONTRACT_INSTANCE_DEPLOYED_MAGIC_VALUE, + abis::log_hash::LogHash, traits::Serialize }; use dep::aztec::{ hash::compute_unencrypted_log_hash, oracle::logs::emit_unencrypted_log_private, - macros::{events::event, functions::private}, utils::to_bytes::arr_to_be_bytes_arr, + macros::{events::event, functions::private}, utils::to_bytes::arr_to_be_bytes_arr }; use std::meta::derive; @@ -71,7 +70,7 @@ contract ContractInstanceDeployer { self.public_keys.ovpk_m.serialize()[1], self.public_keys.tpk_m.serialize()[0], self.public_keys.tpk_m.serialize()[1], - self.deployer.to_field(), + self.deployer.to_field() ] } } @@ -82,7 +81,7 @@ contract ContractInstanceDeployer { contract_class_id: ContractClassId, initialization_hash: Field, public_keys: PublicKeys, - universal_deploy: bool, + universal_deploy: bool ) { // TODO(@spalladino): assert nullifier_exists silo(contract_class_id, ContractClassRegisterer) let deployer = if universal_deploy { @@ -91,8 +90,7 @@ contract ContractInstanceDeployer { context.msg_sender() }; - let partial_address = - PartialAddress::compute(contract_class_id, salt, initialization_hash, deployer); + let partial_address = PartialAddress::compute(contract_class_id, salt, initialization_hash, deployer); let address = AztecAddress::compute(public_keys.hash(), partial_address); @@ -108,7 +106,7 @@ contract ContractInstanceDeployer { initialization_hash, salt, deployer, - version: 1, + version: 1 }; let payload = event.serialize(); diff --git a/noir-projects/noir-contracts/contracts/counter_contract/src/main.nr b/noir-projects/noir-contracts/contracts/counter_contract/src/main.nr index ba0824ab138..2a2b238e17d 100644 --- a/noir-projects/noir-contracts/contracts/counter_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/counter_contract/src/main.nr @@ -32,10 +32,7 @@ contract Counter { #[private] fn increment(owner: AztecAddress, outgoing_viewer: AztecAddress) { unsafe { - dep::aztec::oracle::debug_log::debug_log_format( - "Incrementing counter for owner {0}", - [owner.to_field()], - ); + dep::aztec::oracle::debug_log::debug_log_format("Incrementing counter for owner {0}", [owner.to_field()]); } let counters = storage.counters; counters.at(owner).add(1, owner, outgoing_viewer); @@ -64,8 +61,7 @@ contract Counter { let initial_value: Field = 5; env.impersonate(owner); // Deploy contract and initialize - let initializer = - Counter::interface().initialize(initial_value as u64, owner, outgoing_viewer); + let initializer = Counter::interface().initialize(initial_value as u64, owner, outgoing_viewer); let counter_contract = env.deploy_self("Counter").with_private_initializer(initializer); let contract_address = counter_contract.to_address(); // docs:start:txe_test_read_notes @@ -77,8 +73,7 @@ contract Counter { let notes: BoundedVec = view_notes(owner_slot, options); let initial_note_value = notes.get(0).value; assert( - initial_note_value == initial_value, - f"Expected {initial_value} but got {initial_note_value}", + initial_note_value == initial_value, f"Expected {initial_value} but got {initial_note_value}" ); // docs:end:txe_test_read_notes // Increment the counter @@ -87,8 +82,7 @@ contract Counter { let current_value_for_owner = get_counter(owner); let expected_current_value = initial_value + 1; assert( - expected_current_value == current_value_for_owner, - f"Expected {expected_current_value} but got {current_value_for_owner}", + expected_current_value == current_value_for_owner, f"Expected {expected_current_value} but got {current_value_for_owner}" ); } // docs:end:txe_test_increment diff --git a/noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr b/noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr index a2304487c59..bf268f3ab5f 100644 --- a/noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/crowdfunding_contract/src/main.nr @@ -10,9 +10,8 @@ contract Crowdfunding { encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, keys::getters::get_public_keys, prelude::{AztecAddress, PrivateSet, SharedImmutable}, utils::comparison::Comparator, unencrypted_logs::unencrypted_event_emission::encode_event, - macros::{ - storage::storage, events::event, functions::{public, initializer, private, internal}, - }, protocol_types::traits::Serialize, + macros::{storage::storage, events::event, functions::{public, initializer, private, internal}}, + protocol_types::traits::Serialize }; use std::meta::derive; // docs:start:import_valuenote @@ -71,9 +70,7 @@ contract Crowdfunding { // docs:start:do-transfer // 2) Transfer the donation tokens from donor to this contract let donor = context.msg_sender(); - Token::at(storage.donation_token.read_private()) - .transfer_from(donor, context.this_address(), amount as Field, 0) - .call(&mut context); + Token::at(storage.donation_token.read_private()).transfer_from(donor, context.this_address(), amount as Field, 0).call(&mut context); // docs:end:do-transfer // 3) Create a value note for the donor so that he can later on claim a rewards token in the Claim // contract by proving that the hash of this note exists in the note hash tree. @@ -81,12 +78,7 @@ contract Crowdfunding { // docs:start:valuenote_new let mut note = ValueNote::new(amount as Field, donor_keys.npk_m.hash()); // docs:end:valuenote_new - storage.donation_receipts.insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - donor_keys.ovpk_m, - donor_keys.ivpk_m, - donor, - )); + storage.donation_receipts.insert(&mut note).emit(encode_and_encrypt_note(&mut context, donor_keys.ovpk_m, donor_keys.ivpk_m, donor)); } // docs:end:donate @@ -99,13 +91,9 @@ contract Crowdfunding { assert(context.msg_sender() == operator_address, "Not an operator"); // 2) Transfer the donation tokens from this contract to the operator - Token::at(storage.donation_token.read_private()) - .transfer(operator_address, amount as Field) - .call(&mut context); + Token::at(storage.donation_token.read_private()).transfer(operator_address, amount as Field).call(&mut context); // 3) Emit an unencrypted event so that anyone can audit how much the operator has withdrawn - Crowdfunding::at(context.this_address()) - ._publish_donation_receipts(amount, operator_address) - .enqueue(&mut context); + Crowdfunding::at(context.this_address())._publish_donation_receipts(amount, operator_address).enqueue(&mut context); } // docs:end:operator-withdrawals diff --git a/noir-projects/noir-contracts/contracts/docs_example_contract/src/main.nr b/noir-projects/noir-contracts/contracts/docs_example_contract/src/main.nr index fd3e0194d57..60cdacb91ba 100644 --- a/noir-projects/noir-contracts/contracts/docs_example_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/docs_example_contract/src/main.nr @@ -18,12 +18,12 @@ contract DocsExample { // how to import dependencies defined in your workspace use dep::aztec::prelude::{ AztecAddress, NoteViewerOptions, PrivateContext, Map, PublicMutable, PublicImmutable, - PrivateMutable, PrivateImmutable, PrivateSet, SharedImmutable, + PrivateMutable, PrivateImmutable, PrivateSet, SharedImmutable }; use dep::aztec::{ encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, keys::getters::get_public_keys, - macros::{storage::{storage, storage_no_init}, functions::{public, private, internal, view}}, + macros::{storage::{storage, storage_no_init}, functions::{public, private, internal, view}} }; // how to import methods from other files/folders within your workspace @@ -73,7 +73,7 @@ contract DocsExample { profiles: Map::new( context, 4, - |context, slot| { PrivateMutable::new(context, slot) }, + |context, slot| { PrivateMutable::new(context, slot) } ), // docs:end:state_vars-MapPrivateMutable // docs:start:storage-set-init @@ -85,11 +85,11 @@ contract DocsExample { minters: Map::new( context, 8, - |context, slot| { PublicMutable::new(context, slot) }, + |context, slot| { PublicMutable::new(context, slot) } ), // docs:end:storage-minters-init // docs:start:storage-public-immutable - public_immutable: PublicImmutable::new(context, 9), // docs:end:storage-public-immutable + public_immutable: PublicImmutable::new(context, 9)// docs:end:storage-public-immutable } } } @@ -115,9 +115,7 @@ contract DocsExample { // and returns the response. // Used to test that we can retrieve values through calls and // correctly return them in the simulation - let mut leader = DocsExample::at(context.this_address()) - .get_shared_immutable_constrained_private() - .view(&mut context); + let mut leader = DocsExample::at(context.this_address()).get_shared_immutable_constrained_private().view(&mut context); leader.points += 1; leader } @@ -128,9 +126,7 @@ contract DocsExample { // and returns the response. // Used to test that we can retrieve values through calls and // correctly return them in the simulation - let mut leader = DocsExample::at(context.this_address()) - .get_shared_immutable_constrained_public() - .view(&mut context); + let mut leader = DocsExample::at(context.this_address()).get_shared_immutable_constrained_public().view(&mut context); leader.points += 1; leader } @@ -177,12 +173,14 @@ contract DocsExample { let msg_sender_keys = get_public_keys(context.msg_sender()); let mut new_card = CardNote::new(points, randomness, msg_sender_keys.npk_m.hash()); - storage.private_immutable.initialize(&mut new_card).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - msg_sender_keys.ivpk_m, - context.msg_sender(), - )); + storage.private_immutable.initialize(&mut new_card).emit( + encode_and_encrypt_note( + &mut context, + msg_sender_keys.ovpk_m, + msg_sender_keys.ivpk_m, + context.msg_sender() + ) + ); } // docs:end:initialize-private-mutable @@ -193,12 +191,14 @@ contract DocsExample { let mut legendary_card = CardNote::new(points, randomness, msg_sender_keys.npk_m.hash()); // create and broadcast note - storage.legendary_card.initialize(&mut legendary_card).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - msg_sender_keys.ivpk_m, - context.msg_sender(), - )); + storage.legendary_card.initialize(&mut legendary_card).emit( + encode_and_encrypt_note( + &mut context, + msg_sender_keys.ovpk_m, + msg_sender_keys.ivpk_m, + context.msg_sender() + ) + ); } #[private] @@ -207,12 +207,14 @@ contract DocsExample { for i in 0..amounts.len() { let mut note = CardNote::new(amounts[i], 1, msg_sender_keys.npk_m.hash()); - storage.set.insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - msg_sender_keys.ivpk_m, - context.msg_sender(), - )); + storage.set.insert(&mut note).emit( + encode_and_encrypt_note( + &mut context, + msg_sender_keys.ovpk_m, + msg_sender_keys.ivpk_m, + context.msg_sender() + ) + ); } } #[private] @@ -220,12 +222,14 @@ contract DocsExample { let msg_sender_keys = get_public_keys(context.msg_sender()); let mut note = CardNote::new(amount, randomness, msg_sender_keys.npk_m.hash()); - storage.set.insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - msg_sender_keys.ivpk_m, - context.msg_sender(), - )); + storage.set.insert(&mut note).emit( + encode_and_encrypt_note( + &mut context, + msg_sender_keys.ovpk_m, + msg_sender_keys.ivpk_m, + context.msg_sender() + ) + ); } // docs:start:state_vars-NoteGetterOptionsComparatorExampleNoir unconstrained fn read_note(comparator: u8, amount: Field) -> BoundedVec { @@ -238,15 +242,15 @@ contract DocsExample { let msg_sender_keys = get_public_keys(context.msg_sender()); let mut new_card = CardNote::new(points, randomness, msg_sender_keys.npk_m.hash()); - storage.legendary_card.replace(&mut new_card).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - msg_sender_keys.ivpk_m, - context.msg_sender(), - )); - DocsExample::at(context.this_address()).update_leader(context.msg_sender(), points).enqueue( - &mut context, + storage.legendary_card.replace(&mut new_card).emit( + encode_and_encrypt_note( + &mut context, + msg_sender_keys.ovpk_m, + msg_sender_keys.ivpk_m, + context.msg_sender() + ) ); + DocsExample::at(context.this_address()).update_leader(context.msg_sender(), points).enqueue(&mut context); } #[private] fn increase_legendary_points() { @@ -260,16 +264,16 @@ contract DocsExample { let points = card.points + 1; let mut new_card = CardNote::new(points, card.randomness, msg_sender_keys.npk_m.hash()); // docs:start:state_vars-PrivateMutableReplace - storage.legendary_card.replace(&mut new_card).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - msg_sender_keys.ivpk_m, - context.msg_sender(), - )); - // docs:end:state_vars-PrivateMutableReplace - DocsExample::at(context.this_address()).update_leader(context.msg_sender(), points).enqueue( - &mut context, + storage.legendary_card.replace(&mut new_card).emit( + encode_and_encrypt_note( + &mut context, + msg_sender_keys.ovpk_m, + msg_sender_keys.ivpk_m, + context.msg_sender() + ) ); + // docs:end:state_vars-PrivateMutableReplace + DocsExample::at(context.this_address()).update_leader(context.msg_sender(), points).enqueue(&mut context); } #[private] #[view] @@ -328,7 +332,7 @@ contract DocsExample { // ************************************************************ // Our original inputs! a: Field, - b: Field, // The actual return type of our circuit is the PrivateCircuitPublicInputs struct, this will be the + b: Field // The actual return type of our circuit is the PrivateCircuitPublicInputs struct, this will be the // input to our kernel! // docs:start:context-example-return ) -> pub PrivateCircuitPublicInputs { diff --git a/noir-projects/noir-contracts/contracts/docs_example_contract/src/options.nr b/noir-projects/noir-contracts/contracts/docs_example_contract/src/options.nr index 928e5fbf71a..b0216a98b51 100644 --- a/noir-projects/noir-contracts/contracts/docs_example_contract/src/options.nr +++ b/noir-projects/noir-contracts/contracts/docs_example_contract/src/options.nr @@ -9,13 +9,14 @@ use dep::aztec::{note::note_getter_options::SortOrder, utils::comparison::Compar // docs:start:state_vars-NoteGetterOptionsSelectSortOffset pub fn create_npk_card_getter_options( account_npk_m_hash: Field, - offset: u32, + offset: u32 ) -> NoteGetterOptions { let mut options = NoteGetterOptions::new(); - options - .select(CardNote::properties().npk_m_hash, Comparator.EQ, account_npk_m_hash) - .sort(CardNote::properties().points, SortOrder.DESC) - .set_offset(offset) + options.select( + CardNote::properties().npk_m_hash, + Comparator.EQ, + account_npk_m_hash + ).sort(CardNote::properties().points, SortOrder.DESC).set_offset(offset) } // docs:end:state_vars-NoteGetterOptionsSelectSortOffset @@ -23,20 +24,21 @@ pub fn create_npk_card_getter_options( pub fn create_exact_card_getter_options( points: u8, secret: Field, - account_npk_m_hash: Field, + account_npk_m_hash: Field ) -> NoteGetterOptions { let mut options = NoteGetterOptions::new(); - options - .select(CardNote::properties().points, Comparator.EQ, points as Field) - .select(CardNote::properties().randomness, Comparator.EQ, secret) - .select(CardNote::properties().npk_m_hash, Comparator.EQ, account_npk_m_hash) + options.select(CardNote::properties().points, Comparator.EQ, points as Field).select(CardNote::properties().randomness, Comparator.EQ, secret).select( + CardNote::properties().npk_m_hash, + Comparator.EQ, + account_npk_m_hash + ) } // docs:end:state_vars-NoteGetterOptionsMultiSelects // docs:start:state_vars-OptionFilter pub fn filter_min_points( cards: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - min_points: u8, + min_points: u8 ) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] { let mut selected_cards = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; let mut num_selected = 0; @@ -51,13 +53,8 @@ pub fn filter_min_points( // docs:end:state_vars-OptionFilter // docs:start:state_vars-NoteGetterOptionsFilter -pub fn create_cards_with_min_points_getter_options( - min_points: u8, -) -> NoteGetterOptions { - NoteGetterOptions::with_filter(filter_min_points, min_points).sort( - CardNote::properties().points, - SortOrder.ASC, - ) +pub fn create_cards_with_min_points_getter_options(min_points: u8) -> NoteGetterOptions { + NoteGetterOptions::with_filter(filter_min_points, min_points).sort(CardNote::properties().points, SortOrder.ASC) } // docs:end:state_vars-NoteGetterOptionsFilter diff --git a/noir-projects/noir-contracts/contracts/docs_example_contract/src/types/card_note.nr b/noir-projects/noir-contracts/contracts/docs_example_contract/src/types/card_note.nr index c1d2fbf4e95..ad593ccf139 100644 --- a/noir-projects/noir-contracts/contracts/docs_example_contract/src/types/card_note.nr +++ b/noir-projects/noir-contracts/contracts/docs_example_contract/src/types/card_note.nr @@ -1,10 +1,8 @@ use dep::aztec::prelude::{NullifiableNote, PrivateContext, NoteHeader}; use dep::aztec::{ note::utils::compute_note_hash_for_nullify, keys::getters::get_nsk_app, - protocol_types::{ - traits::Serialize, constants::GENERATOR_INDEX__NOTE_NULLIFIER, - hash::poseidon2_hash_with_separator, - }, macros::notes::note, + protocol_types::{traits::Serialize, constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + macros::notes::note }; // docs:start:state_vars-CardNote @@ -29,15 +27,11 @@ impl CardNote { // docs:start:note_interface impl NullifiableNote for CardNote { - fn compute_nullifier( - self, - context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { let secret = context.request_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } @@ -46,7 +40,7 @@ impl NullifiableNote for CardNote { let secret = get_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } } diff --git a/noir-projects/noir-contracts/contracts/easy_private_token_contract/src/main.nr b/noir-projects/noir-contracts/contracts/easy_private_token_contract/src/main.nr index e2a94ae71ee..8e118629ed8 100644 --- a/noir-projects/noir-contracts/contracts/easy_private_token_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/easy_private_token_contract/src/main.nr @@ -38,7 +38,7 @@ contract EasyPrivateToken { amount: u64, sender: AztecAddress, recipient: AztecAddress, - outgoing_viewer: AztecAddress, + outgoing_viewer: AztecAddress ) { let balances = storage.balances; diff --git a/noir-projects/noir-contracts/contracts/easy_private_voting_contract/src/main.nr b/noir-projects/noir-contracts/contracts/easy_private_voting_contract/src/main.nr index 5e0b77265fe..5d65675ab8a 100644 --- a/noir-projects/noir-contracts/contracts/easy_private_voting_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/easy_private_voting_contract/src/main.nr @@ -6,7 +6,7 @@ contract EasyPrivateVoting { use dep::aztec::prelude::{AztecAddress, Map, PublicMutable, SharedImmutable}; use dep::aztec::{ keys::getters::get_public_keys, - macros::{storage::storage, functions::{public, initializer, private, internal}}, + macros::{storage::storage, functions::{public, initializer, private, internal}} }; // docs:end:imports // docs:start:storage_struct @@ -39,9 +39,7 @@ contract EasyPrivateVoting { let secret = context.request_nsk_app(msg_sender_npk_m_hash); // get secret key of caller of function let nullifier = std::hash::pedersen_hash([context.msg_sender().to_field(), secret]); // derive nullifier from sender and secret context.push_nullifier(nullifier); - EasyPrivateVoting::at(context.this_address()).add_to_tally_public(candidate).enqueue( - &mut context, - ); + EasyPrivateVoting::at(context.this_address()).add_to_tally_public(candidate).enqueue(&mut context); } // docs:end:cast_vote diff --git a/noir-projects/noir-contracts/contracts/ecdsa_k_account_contract/src/main.nr b/noir-projects/noir-contracts/contracts/ecdsa_k_account_contract/src/main.nr index 1e6fe084acb..b1c573e6f52 100644 --- a/noir-projects/noir-contracts/contracts/ecdsa_k_account_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/ecdsa_k_account_contract/src/main.nr @@ -8,12 +8,12 @@ contract EcdsaKAccount { use dep::aztec::{ encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, keys::getters::get_public_keys, - macros::{storage::storage, functions::{private, initializer, view, noinitcheck}}, + macros::{storage::storage, functions::{private, initializer, view, noinitcheck}} }; use dep::authwit::{ entrypoint::{app::AppPayload, fee::FeePayload}, account::AccountActions, - auth_witness::get_auth_witness, + auth_witness::get_auth_witness }; use dep::ecdsa_public_key_note::EcdsaPublicKeyNote; @@ -32,14 +32,8 @@ contract EcdsaKAccount { // Not emitting outgoing for msg_sender here to not have to register keys for the contract through which we // deploy this (typically MultiCallEntrypoint). I think it's ok here as I feel the outgoing here is not that // important. - let mut pub_key_note = - EcdsaPublicKeyNote::new(signing_pub_key_x, signing_pub_key_y, this_keys.npk_m.hash()); - storage.public_key.initialize(&mut pub_key_note).emit(encode_and_encrypt_note( - &mut context, - this_keys.ovpk_m, - this_keys.ivpk_m, - this, - )); + let mut pub_key_note = EcdsaPublicKeyNote::new(signing_pub_key_x, signing_pub_key_y, this_keys.npk_m.hash()); + storage.public_key.initialize(&mut pub_key_note).emit(encode_and_encrypt_note(&mut context, this_keys.ovpk_m, this_keys.ivpk_m, this)); } // Note: If you globally change the entrypoint signature don't forget to update account_entrypoint.ts @@ -64,7 +58,9 @@ contract EcdsaKAccount { let public_key = storage.public_key.get_note(); // Load auth witness - let witness: [Field; 64] = unsafe { get_auth_witness(outer_hash) }; + let witness: [Field; 64] = unsafe { + get_auth_witness(outer_hash) + }; let mut signature: [u8; 64] = [0; 64]; for i in 0..64 { signature[i] = witness[i] as u8; @@ -74,12 +70,7 @@ contract EcdsaKAccount { // Note that noir expects the hash of the message/challenge as input to the ECDSA verification. let outer_hash_bytes: [u8; 32] = outer_hash.to_be_bytes(); let hashed_message: [u8; 32] = std::hash::sha256(outer_hash_bytes); - std::ecdsa_secp256k1::verify_signature( - public_key.x, - public_key.y, - signature, - hashed_message, - ) + std::ecdsa_secp256k1::verify_signature(public_key.x, public_key.y, signature, hashed_message) } } diff --git a/noir-projects/noir-contracts/contracts/ecdsa_r_account_contract/src/main.nr b/noir-projects/noir-contracts/contracts/ecdsa_r_account_contract/src/main.nr index bf47165081e..8c21c43ba68 100644 --- a/noir-projects/noir-contracts/contracts/ecdsa_r_account_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/ecdsa_r_account_contract/src/main.nr @@ -7,12 +7,12 @@ contract EcdsaRAccount { use dep::aztec::{ encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, keys::getters::get_public_keys, - macros::{storage::storage, functions::{private, initializer, view, noinitcheck}}, + macros::{storage::storage, functions::{private, initializer, view, noinitcheck}} }; use dep::authwit::{ entrypoint::{app::AppPayload, fee::FeePayload}, account::AccountActions, - auth_witness::get_auth_witness, + auth_witness::get_auth_witness }; use dep::ecdsa_public_key_note::EcdsaPublicKeyNote; @@ -31,14 +31,8 @@ contract EcdsaRAccount { // Not emitting outgoing for msg_sender here to not have to register keys for the contract through which we // deploy this (typically MultiCallEntrypoint). I think it's ok here as I feel the outgoing here is not that // important. - let mut pub_key_note = - EcdsaPublicKeyNote::new(signing_pub_key_x, signing_pub_key_y, this_keys.npk_m.hash()); - storage.public_key.initialize(&mut pub_key_note).emit(encode_and_encrypt_note( - &mut context, - this_keys.ovpk_m, - this_keys.ivpk_m, - this, - )); + let mut pub_key_note = EcdsaPublicKeyNote::new(signing_pub_key_x, signing_pub_key_y, this_keys.npk_m.hash()); + storage.public_key.initialize(&mut pub_key_note).emit(encode_and_encrypt_note(&mut context, this_keys.ovpk_m, this_keys.ivpk_m, this)); } // Note: If you globally change the entrypoint signature don't forget to update account_entrypoint.ts @@ -63,7 +57,9 @@ contract EcdsaRAccount { let public_key = storage.public_key.get_note(); // Load auth witness - let witness: [Field; 64] = unsafe { get_auth_witness(outer_hash) }; + let witness: [Field; 64] = unsafe { + get_auth_witness(outer_hash) + }; let mut signature: [u8; 64] = [0; 64]; for i in 0..64 { signature[i] = witness[i] as u8; @@ -73,11 +69,6 @@ contract EcdsaRAccount { // Note that noir expects the hash of the message/challenge as input to the ECDSA verification. let outer_hash_bytes: [u8; 32] = outer_hash.to_be_bytes(); let hashed_message: [u8; 32] = std::hash::sha256(outer_hash_bytes); - std::ecdsa_secp256r1::verify_signature( - public_key.x, - public_key.y, - signature, - hashed_message, - ) + std::ecdsa_secp256r1::verify_signature(public_key.x, public_key.y, signature, hashed_message) } } diff --git a/noir-projects/noir-contracts/contracts/escrow_contract/src/main.nr b/noir-projects/noir-contracts/contracts/escrow_contract/src/main.nr index 59fd82197f7..785f6dbcfc1 100644 --- a/noir-projects/noir-contracts/contracts/escrow_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/escrow_contract/src/main.nr @@ -6,8 +6,7 @@ contract Escrow { use dep::aztec::prelude::{AztecAddress, PrivateImmutable}; use dep::aztec::{ encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, - keys::getters::get_public_keys, - macros::{storage::storage, functions::{private, initializer}}, + keys::getters::get_public_keys, macros::{storage::storage, functions::{private, initializer}} }; // docs:start:addressnote_import @@ -29,12 +28,7 @@ contract Escrow { // docs:start:addressnote_new let mut note = AddressNote::new(owner, owner_keys.npk_m.hash()); // docs:end:addressnote_new - storage.owner.initialize(&mut note).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + storage.owner.initialize(&mut note).emit(encode_and_encrypt_note(&mut context, msg_sender_keys.ovpk_m, owner_keys.ivpk_m, owner)); } // Withdraws balance. Requires that msg.sender is the owner. diff --git a/noir-projects/noir-contracts/contracts/fee_juice_contract/src/main.nr b/noir-projects/noir-contracts/contracts/fee_juice_contract/src/main.nr index 2f4129a84de..cae4f57ee4f 100644 --- a/noir-projects/noir-contracts/contracts/fee_juice_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/fee_juice_contract/src/main.nr @@ -7,7 +7,7 @@ contract FeeJuice { use dep::aztec::{ protocol_types::{address::{AztecAddress, EthAddress}, constants::FEE_JUICE_INITIAL_MINT}, state_vars::{SharedImmutable, PublicMutable, Map}, - macros::{storage::storage, functions::{private, public, view, internal}}, + macros::{storage::storage, functions::{private, public, view, internal}} }; use crate::lib::get_bridge_gas_msg_hash; @@ -28,9 +28,7 @@ contract FeeJuice { let self = context.this_address(); // Increase self balance and set as fee payer, and end setup - FeeJuice::at(self)._increase_public_balance(self, FEE_JUICE_INITIAL_MINT).enqueue( - &mut context, - ); + FeeJuice::at(self)._increase_public_balance(self, FEE_JUICE_INITIAL_MINT).enqueue(&mut context); context.set_as_fee_payer(); context.end_setup(); @@ -58,9 +56,7 @@ contract FeeJuice { // TODO(palla/gas) Emit an unencrypted log to announce which L1 to L2 message has been claimed // Otherwise, we cannot trace L1 deposits to their corresponding claims on L2 - FeeJuice::at(context.this_address())._increase_public_balance(to, amount).enqueue( - &mut context, - ); + FeeJuice::at(context.this_address())._increase_public_balance(to, amount).enqueue(&mut context); } #[public] diff --git a/noir-projects/noir-contracts/contracts/fpc_contract/src/lib.nr b/noir-projects/noir-contracts/contracts/fpc_contract/src/lib.nr index e9aad0aeb73..1af0c18152e 100644 --- a/noir-projects/noir-contracts/contracts/fpc_contract/src/lib.nr +++ b/noir-projects/noir-contracts/contracts/fpc_contract/src/lib.nr @@ -2,9 +2,6 @@ use dep::aztec::context::PublicContext; pub fn compute_rebate(context: PublicContext, initial_amount: Field) -> Field { let actual_fee = context.transaction_fee(); - assert( - !initial_amount.lt(actual_fee), - "Initial amount paid to the paymaster does not cover actual fee", - ); + assert(!initial_amount.lt(actual_fee), "Initial amount paid to the paymaster does not cover actual fee"); initial_amount - actual_fee } diff --git a/noir-projects/noir-contracts/contracts/fpc_contract/src/main.nr b/noir-projects/noir-contracts/contracts/fpc_contract/src/main.nr index 7b3900f8c4e..aee2342072e 100644 --- a/noir-projects/noir-contracts/contracts/fpc_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/fpc_contract/src/main.nr @@ -7,7 +7,7 @@ contract FPC { use dep::aztec::{ protocol_types::{abis::function_selector::FunctionSelector, address::AztecAddress}, state_vars::SharedImmutable, - macros::{storage::storage, functions::{private, public, initializer, internal}}, + macros::{storage::storage, functions::{private, public, initializer, internal}} }; use dep::token::Token; use crate::lib::compute_rebate; @@ -24,42 +24,33 @@ contract FPC { } #[private] - fn fee_entrypoint_private( - amount: Field, - asset: AztecAddress, - secret_hash: Field, - nonce: Field, - ) { + fn fee_entrypoint_private(amount: Field, asset: AztecAddress, secret_hash: Field, nonce: Field) { assert(asset == storage.other_asset.read_private()); - Token::at(asset).unshield(context.msg_sender(), context.this_address(), amount, nonce).call( - &mut context, - ); + Token::at(asset).unshield(context.msg_sender(), context.this_address(), amount, nonce).call(&mut context); context.set_as_fee_payer(); // Would like to get back to // FPC::at(context.this_address()).pay_refund_with_shielded_rebate(amount, asset, secret_hash).set_public_teardown_function(&mut context); context.set_public_teardown_function( context.this_address(), comptime { - FunctionSelector::from_signature( - "pay_refund_with_shielded_rebate(Field,(Field),Field)", - ) - }, - [amount, asset.to_field(), secret_hash], + FunctionSelector::from_signature("pay_refund_with_shielded_rebate(Field,(Field),Field)") + }, + [amount, asset.to_field(), secret_hash] ); } #[private] fn fee_entrypoint_public(amount: Field, asset: AztecAddress, nonce: Field) { - FPC::at(context.this_address()) - .prepare_fee(context.msg_sender(), amount, asset, nonce) - .enqueue(&mut context); + FPC::at(context.this_address()).prepare_fee(context.msg_sender(), amount, asset, nonce).enqueue(&mut context); context.set_as_fee_payer(); // TODO(#6277) for improving interface: // FPC::at(context.this_address()).pay_refund(context.msg_sender(), amount, asset).set_public_teardown_function(&mut context); context.set_public_teardown_function( context.this_address(), - comptime { FunctionSelector::from_signature("pay_refund((Field),Field,(Field))") }, - [context.msg_sender().to_field(), amount, asset.to_field()], + comptime { + FunctionSelector::from_signature("pay_refund((Field),Field,(Field))") + }, + [context.msg_sender().to_field(), amount, asset.to_field()] ); } @@ -67,9 +58,7 @@ contract FPC { #[internal] fn prepare_fee(from: AztecAddress, amount: Field, asset: AztecAddress, nonce: Field) { // docs:start:public_call - Token::at(asset).transfer_public(from, context.this_address(), amount, nonce).call( - &mut context, - ); + Token::at(asset).transfer_public(from, context.this_address(), amount, nonce).call(&mut context); // docs:end:public_call } @@ -78,9 +67,7 @@ contract FPC { fn pay_refund(refund_address: AztecAddress, amount: Field, asset: AztecAddress) { // Just do public refunds for the present let refund = compute_rebate(context, amount); - Token::at(asset).transfer_public(context.this_address(), refund_address, refund, 0).call( - &mut context, - ); + Token::at(asset).transfer_public(context.this_address(), refund_address, refund, 0).call(&mut context); } #[public] diff --git a/noir-projects/noir-contracts/contracts/import_test_contract/src/main.nr b/noir-projects/noir-contracts/contracts/import_test_contract/src/main.nr index 3a3b7ec8b68..6f5a19f3fda 100644 --- a/noir-projects/noir-contracts/contracts/import_test_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/import_test_contract/src/main.nr @@ -16,25 +16,23 @@ contract ImportTest { // See yarn-project/end-to-end/src/e2e_nested_contract.test.ts #[private] fn main_contract(target: AztecAddress) -> Field { - Test::at(target) - .test_code_gen( - 1, - true, - 1 as u32, - [1, 2], + Test::at(target).test_code_gen( + 1, + true, + 1 as u32, + [1, 2], + DummyNote { amount: 1, secret_hash: 2 }, + DeepStruct { + a_field: 1, + a_bool: true, + a_note: DummyNote { amount: 1, secret_hash: 2 }, + many_notes: [ DummyNote { amount: 1, secret_hash: 2 }, - DeepStruct { - a_field: 1, - a_bool: true, - a_note: DummyNote { amount: 1, secret_hash: 2 }, - many_notes: [ - DummyNote { amount: 1, secret_hash: 2 }, - DummyNote { amount: 1, secret_hash: 2 }, - DummyNote { amount: 1, secret_hash: 2 }, - ], - }, - ) - .call(&mut context) + DummyNote { amount: 1, secret_hash: 2 }, + DummyNote { amount: 1, secret_hash: 2 } + ] + } + ).call(&mut context) } // Calls the get_this_address on the Test contract at the target address diff --git a/noir-projects/noir-contracts/contracts/inclusion_proofs_contract/src/main.nr b/noir-projects/noir-contracts/contracts/inclusion_proofs_contract/src/main.nr index 2c96b03771b..bb37b9c3887 100644 --- a/noir-projects/noir-contracts/contracts/inclusion_proofs_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/inclusion_proofs_contract/src/main.nr @@ -4,14 +4,11 @@ use dep::aztec::macros::aztec; #[aztec] contract InclusionProofs { use dep::aztec::prelude::{AztecAddress, NoteGetterOptions, Map, PrivateSet, PublicMutable}; - use dep::aztec::{ - encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, - keys::getters::get_public_keys, - }; + use dep::aztec::{encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, keys::getters::get_public_keys}; use dep::aztec::{ note::note_getter_options::NoteStatus, - macros::{storage::storage, functions::{private, public, initializer}}, + macros::{storage::storage, functions::{private, public, initializer}} }; // docs:start:value_note_imports use dep::value_note::value_note::ValueNote; @@ -37,12 +34,7 @@ contract InclusionProofs { let owner_keys = get_public_keys(owner); let mut note = ValueNote::new(value, owner_keys.npk_m.hash()); - storage.private_values.at(owner).insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + storage.private_values.at(owner).insert(&mut note).emit(encode_and_encrypt_note(&mut context, msg_sender_keys.ovpk_m, owner_keys.ivpk_m, owner)); } // docs:end:create_note @@ -51,7 +43,7 @@ contract InclusionProofs { owner: AztecAddress, use_block_number: bool, block_number: u32, // The block at which we'll prove that the note exists - nullified: bool, + nullified: bool ) { // docs:start:get_note_from_pxe // 1) Get the note from PXE. @@ -79,7 +71,7 @@ contract InclusionProofs { fn test_note_inclusion_fail_case( owner: AztecAddress, use_block_number: bool, - block_number: u32, // The block at which we'll prove that the note exists + block_number: u32 // The block at which we'll prove that the note exists ) { let header = context.get_header(); let owner_npk_m_hash = get_public_keys(owner).npk_m.hash(); @@ -103,7 +95,7 @@ contract InclusionProofs { // Value below is only used when the note is not found --> used to test the nullifier non-inclusion failure // case (it allows me to pass in random value of note nullifier - I cannot add and fetch a random note from PXE // because PXE performs note commitment inclusion check when you add a new note). - fail_case: bool, + fail_case: bool ) { // 1) Get the note from PXE let private_values = storage.private_values.at(owner); @@ -129,7 +121,7 @@ contract InclusionProofs { owner: AztecAddress, use_block_number: bool, block_number: u32, // The block at which we'll prove that the note exists and is not nullified - nullified: bool, + nullified: bool ) { // 1) Get the note from PXE. let private_values = storage.private_values.at(owner); @@ -169,7 +161,7 @@ contract InclusionProofs { fn test_nullifier_inclusion( nullifier: Field, use_block_number: bool, - block_number: u32, // The block at which we'll prove that the nullifier exists in the nullifier tree + block_number: u32 // The block at which we'll prove that the nullifier exists in the nullifier tree ) { let header = if (use_block_number) { context.get_header_at(block_number) @@ -193,17 +185,15 @@ contract InclusionProofs { } #[private] - fn test_storage_historical_read_unset_slot( - block_number: u32, // The block at which we'll read the public storage value + fn test_storage_historical_read_unset_slot(block_number: u32 // The block at which we'll read the public storage value ) { let header = context.get_header_at(block_number); // docs:start:public_storage_historical_read assert_eq( header.public_storage_historical_read( storage.public_unused_value.storage_slot, - context.this_address(), - ), - 0, + context.this_address() + ), 0 ); // docs:end:public_storage_historical_read } @@ -212,7 +202,7 @@ contract InclusionProofs { fn test_storage_historical_read( expected: Field, use_block_number: bool, - block_number: u32, // The block at which we'll read the public storage value + block_number: u32 // The block at which we'll read the public storage value ) { let header = if (use_block_number) { context.get_header_at(block_number) @@ -220,10 +210,7 @@ contract InclusionProofs { context.get_header() }; - let actual = header.public_storage_historical_read( - storage.public_value.storage_slot, - context.this_address(), - ); + let actual = header.public_storage_historical_read(storage.public_value.storage_slot, context.this_address()); assert_eq(actual, expected, "Actual public value does not match expected"); } @@ -234,7 +221,7 @@ contract InclusionProofs { contract_address: AztecAddress, block_number: u32, test_deployment: bool, - test_initialization: bool, + test_initialization: bool ) { let header = context.get_header_at(block_number); @@ -256,7 +243,7 @@ contract InclusionProofs { contract_address: AztecAddress, block_number: u32, test_deployment: bool, - test_initialization: bool, + test_initialization: bool ) { let header = context.get_header_at(block_number); diff --git a/noir-projects/noir-contracts/contracts/lending_contract/src/asset.nr b/noir-projects/noir-contracts/contracts/lending_contract/src/asset.nr index e8ec7af56aa..bbee9ba545e 100644 --- a/noir-projects/noir-contracts/contracts/lending_contract/src/asset.nr +++ b/noir-projects/noir-contracts/contracts/lending_contract/src/asset.nr @@ -23,7 +23,7 @@ impl Serialize for Asset { Asset.last_updated_ts as Field, Asset.loan_to_value.lo, Asset.loan_to_value.hi, - Asset.oracle.to_field(), + Asset.oracle.to_field() ] } } diff --git a/noir-projects/noir-contracts/contracts/lending_contract/src/helpers.nr b/noir-projects/noir-contracts/contracts/lending_contract/src/helpers.nr index 0d186db0d60..c5e537e88ed 100644 --- a/noir-projects/noir-contracts/contracts/lending_contract/src/helpers.nr +++ b/noir-projects/noir-contracts/contracts/lending_contract/src/helpers.nr @@ -18,7 +18,7 @@ pub fn covered_by_collateral( loan_to_value: U128, collateral: U128, increase: U128, - decrease: U128, + decrease: U128 ) -> U128 { let price_precision = U128::from_integer(1000000000); let ltv_precision = U128::from_integer(10000); @@ -49,7 +49,7 @@ pub fn debt_updates( interest_accumulator: U128, static_debt: U128, increase: U128, - decrease: U128, + decrease: U128 ) -> DebtReturn { assert(interest_accumulator > U128::from_integer(0)); let accumulator_precision = U128::from_integer(1000000000); diff --git a/noir-projects/noir-contracts/contracts/lending_contract/src/main.nr b/noir-projects/noir-contracts/contracts/lending_contract/src/main.nr index 3066eb5b04b..b15216589f3 100644 --- a/noir-projects/noir-contracts/contracts/lending_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/lending_contract/src/main.nr @@ -23,9 +23,7 @@ contract Lending { use dep::token::Token; use dep::price_feed::PriceFeed; - use dep::aztec::macros::{ - storage::storage, functions::{private, public, initializer, internal, view}, - }; + use dep::aztec::macros::{storage::storage, functions::{private, public, initializer, internal, view}}; // Storage structure, containing all storage, and specifying what slots they use. #[storage] @@ -47,7 +45,7 @@ contract Lending { oracle: AztecAddress, loan_to_value: Field, collateral_asset: AztecAddress, - stable_coin: AztecAddress, + stable_coin: AztecAddress ) { let asset_loc = storage.assets.at(0); let asset: Asset = asset_loc.read(); @@ -61,12 +59,7 @@ contract Lending { let last_updated_ts = context.timestamp(); asset_loc.write( - Asset { - interest_accumulator: U128::from_integer(1000000000), - last_updated_ts, - loan_to_value, - oracle, - }, + Asset { interest_accumulator: U128::from_integer(1000000000), last_updated_ts, loan_to_value, oracle } ); storage.collateral_asset.write(collateral_asset); @@ -106,33 +99,27 @@ contract Lending { nonce: Field, secret: Field, on_behalf_of: Field, - collateral_asset: AztecAddress, + collateral_asset: AztecAddress ) { - let on_behalf_of = - compute_identifier(secret, on_behalf_of, context.msg_sender().to_field()); - let _res = Token::at(collateral_asset) - .unshield(from, context.this_address(), amount, nonce) - .call(&mut context); + let on_behalf_of = compute_identifier(secret, on_behalf_of, context.msg_sender().to_field()); + let _res = Token::at(collateral_asset).unshield(from, context.this_address(), amount, nonce).call(&mut context); // docs:start:enqueue_public - Lending::at(context.this_address()) - ._deposit(AztecAddress::from_field(on_behalf_of), amount, collateral_asset) - .enqueue(&mut context); + Lending::at(context.this_address())._deposit( + AztecAddress::from_field(on_behalf_of), + amount, + collateral_asset + ).enqueue(&mut context); // docs:end:enqueue_public } #[public] - fn deposit_public( - amount: Field, - nonce: Field, - on_behalf_of: Field, - collateral_asset: AztecAddress, - ) { - let _ = Token::at(collateral_asset) - .transfer_public(context.msg_sender(), context.this_address(), amount, nonce) - .call(&mut context); - let _ = Lending::at(context.this_address()) - ._deposit(AztecAddress::from_field(on_behalf_of), amount, collateral_asset) - .call(&mut context); + fn deposit_public(amount: Field, nonce: Field, on_behalf_of: Field, collateral_asset: AztecAddress) { + let _ = Token::at(collateral_asset).transfer_public(context.msg_sender(), context.this_address(), amount, nonce).call(&mut context); + let _ = Lending::at(context.this_address())._deposit( + AztecAddress::from_field(on_behalf_of), + amount, + collateral_asset + ).call(&mut context); } #[public] @@ -151,16 +138,12 @@ contract Lending { #[private] fn withdraw_private(secret: Field, to: AztecAddress, amount: Field) { let on_behalf_of = compute_identifier(secret, 0, context.msg_sender().to_field()); - Lending::at(context.this_address()) - ._withdraw(AztecAddress::from_field(on_behalf_of), to, amount) - .enqueue(&mut context); + Lending::at(context.this_address())._withdraw(AztecAddress::from_field(on_behalf_of), to, amount).enqueue(&mut context); } #[public] fn withdraw_public(to: AztecAddress, amount: Field) { - let _ = Lending::at(context.this_address()) - ._withdraw(context.msg_sender(), to, amount) - .call(&mut context); + let _ = Lending::at(context.this_address())._withdraw(context.msg_sender(), to, amount).call(&mut context); } #[public] @@ -182,13 +165,13 @@ contract Lending { asset.loan_to_value, U128::from_integer(collateral), U128::from_integer(0), - U128::from_integer(amount), + U128::from_integer(amount) ); let debt_returns = debt_updates( asset.interest_accumulator, U128::from_integer(static_debt), U128::from_integer(0), - U128::from_integer(0), + U128::from_integer(0) ); assert(debt_returns.debt_value < debt_covered); @@ -197,24 +180,18 @@ contract Lending { // @todo @LHerskind Support both shielding and transfers (for now just transfer) let collateral_asset = storage.collateral_asset.read(); - let _ = Token::at(collateral_asset) - .transfer_public(context.this_address(), recipient, amount, 0) - .call(&mut context); + let _ = Token::at(collateral_asset).transfer_public(context.this_address(), recipient, amount, 0).call(&mut context); } #[private] fn borrow_private(secret: Field, to: AztecAddress, amount: Field) { let on_behalf_of = compute_identifier(secret, 0, context.msg_sender().to_field()); - let _ = Lending::at(context.this_address()) - ._borrow(AztecAddress::from_field(on_behalf_of), to, amount) - .enqueue(&mut context); + let _ = Lending::at(context.this_address())._borrow(AztecAddress::from_field(on_behalf_of), to, amount).enqueue(&mut context); } #[public] fn borrow_public(to: AztecAddress, amount: Field) { - let _ = Lending::at(context.this_address())._borrow(context.msg_sender(), to, amount).call( - &mut context, - ); + let _ = Lending::at(context.this_address())._borrow(context.msg_sender(), to, amount).call(&mut context); } #[public] @@ -232,13 +209,13 @@ contract Lending { asset.loan_to_value, collateral, U128::from_integer(0), - U128::from_integer(0), + U128::from_integer(0) ); let debt_returns = debt_updates( asset.interest_accumulator, static_debt, U128::from_integer(amount), - U128::from_integer(0), + U128::from_integer(0) ); assert(debt_returns.debt_value < debt_covered); @@ -257,26 +234,19 @@ contract Lending { nonce: Field, secret: Field, on_behalf_of: Field, - stable_coin: AztecAddress, + stable_coin: AztecAddress ) { - let on_behalf_of = - compute_identifier(secret, on_behalf_of, context.msg_sender().to_field()); + let on_behalf_of = compute_identifier(secret, on_behalf_of, context.msg_sender().to_field()); // docs:start:private_call let _ = Token::at(stable_coin).burn(from, amount, nonce).call(&mut context); // docs:end:private_call - let _ = Lending::at(context.this_address()) - ._repay(AztecAddress::from_field(on_behalf_of), amount, stable_coin) - .enqueue(&mut context); + let _ = Lending::at(context.this_address())._repay(AztecAddress::from_field(on_behalf_of), amount, stable_coin).enqueue(&mut context); } #[public] fn repay_public(amount: Field, nonce: Field, owner: AztecAddress, stable_coin: AztecAddress) { - let _ = Token::at(stable_coin).burn_public(context.msg_sender(), amount, nonce).call( - &mut context, - ); - let _ = Lending::at(context.this_address())._repay(owner, amount, stable_coin).call( - &mut context, - ); + let _ = Token::at(stable_coin).burn_public(context.msg_sender(), amount, nonce).call(&mut context); + let _ = Lending::at(context.this_address())._repay(owner, amount, stable_coin).call(&mut context); } #[public] @@ -292,7 +262,7 @@ contract Lending { asset.interest_accumulator, static_debt, U128::from_integer(0), - U128::from_integer(amount), + U128::from_integer(amount) ); storage.static_debt.at(owner).write(debt_returns.static_debt.to_integer()); @@ -312,9 +282,8 @@ contract Lending { let asset: Asset = storage.assets.at(0).read(); let debt = debt_value( U128::from_integer(static_debt), - U128::from_integer(asset.interest_accumulator), - ) - .to_integer(); + U128::from_integer(asset.interest_accumulator) + ).to_integer(); Position { collateral, static_debt, debt } } diff --git a/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_in_private.nr b/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_in_private.nr index d80a77b38f1..0d11bef5441 100644 --- a/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_in_private.nr +++ b/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_in_private.nr @@ -7,13 +7,10 @@ use crate::NFT; #[test] unconstrained fn transfer_in_private() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ false); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ false); // Transfer the NFT to the recipient - NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 0).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 0).call(&mut env.private()); // Recipient should have the note in their private nfts utils::assert_owns_private_nft(nft_contract_address, recipient, token_id); @@ -22,13 +19,10 @@ unconstrained fn transfer_in_private() { #[test] unconstrained fn transfer_in_private_to_self() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, owner, _, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ false); + let (env, nft_contract_address, owner, _, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ false); // Transfer the NFT back to the owner - NFT::at(nft_contract_address).transfer_in_private(owner, owner, token_id, 0).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_in_private(owner, owner, token_id, 0).call(&mut env.private()); // NFT owner should stay the same utils::assert_owns_private_nft(nft_contract_address, owner, token_id); @@ -37,14 +31,11 @@ unconstrained fn transfer_in_private_to_self() { #[test] unconstrained fn transfer_in_private_to_non_deployed_account() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, sender, _, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ false); + let (env, nft_contract_address, sender, _, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ false); let not_deployed = cheatcodes::create_account(); // Transfer the NFT to the recipient - NFT::at(nft_contract_address) - .transfer_in_private(sender, not_deployed.address, token_id, 0) - .call(&mut env.private()); + NFT::at(nft_contract_address).transfer_in_private(sender, not_deployed.address, token_id, 0).call(&mut env.private()); // Owner of the private NFT should be the not_deployed account utils::assert_owns_private_nft(nft_contract_address, not_deployed.address, token_id); @@ -53,17 +44,11 @@ unconstrained fn transfer_in_private_to_non_deployed_account() { #[test] unconstrained fn transfer_in_private_on_behalf_of_other() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ true); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ true); // Transfer the NFT to the recipient - let transfer_in_private_call_interface = - NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 1); - authwit_cheatcodes::add_private_authwit_from_call_interface( - sender, - recipient, - transfer_in_private_call_interface, - ); + let transfer_in_private_call_interface = NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 1); + authwit_cheatcodes::add_private_authwit_from_call_interface(sender, recipient, transfer_in_private_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); @@ -77,13 +62,10 @@ unconstrained fn transfer_in_private_on_behalf_of_other() { #[test(should_fail_with = "NFT not found when transferring")] unconstrained fn transfer_in_private_failure_not_an_owner() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, owner, not_owner, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ false); + let (env, nft_contract_address, owner, not_owner, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ false); // Try transferring the NFT from not_owner env.impersonate(not_owner); - NFT::at(nft_contract_address).transfer_in_private(not_owner, owner, token_id, 0).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_in_private(not_owner, owner, token_id, 0).call(&mut env.private()); } #[test(should_fail_with = "invalid nonce")] @@ -91,16 +73,13 @@ unconstrained fn transfer_in_private_failure_on_behalf_of_self_non_zero_nonce() // Setup without account contracts. We are not using authwits here, so dummy accounts are enough. // The nonce check is in the beginning so we don't need to waste time on minting the NFT and transferring // it to private. - let (env, nft_contract_address, sender, recipient) = - utils::setup( /* with_account_contracts */ false); + let (env, nft_contract_address, sender, recipient) = utils::setup(/* with_account_contracts */ false); // We set random value for the token_id as the nonce check is before we use the value. let token_id = random(); // Try transferring the NFT - NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 1).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 1).call(&mut env.private()); } #[test(should_fail_with = "Authorization not found for message hash")] @@ -108,8 +87,7 @@ unconstrained fn transfer_in_private_failure_on_behalf_of_other_without_approval // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. // The authwit check is in the beginning so we don't need to waste time on minting the NFT and transferring // it to private. - let (env, nft_contract_address, sender, recipient) = - utils::setup( /* with_account_contracts */ true); + let (env, nft_contract_address, sender, recipient) = utils::setup(/* with_account_contracts */ true); // We set random value for the token_id as the nonce check is before we use the value. let token_id = random(); @@ -117,9 +95,7 @@ unconstrained fn transfer_in_private_failure_on_behalf_of_other_without_approval // Impersonate recipient to perform the call env.impersonate(recipient); // Try transferring the NFT - NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 1).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 1).call(&mut env.private()); } #[test(should_fail_with = "Authorization not found for message hash")] @@ -127,19 +103,13 @@ unconstrained fn transfer_in_private_failure_on_behalf_of_other_wrong_caller() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. // The authwit check is in the beginning so we don't need to waste time on minting the NFT and transferring // it to private. - let (env, nft_contract_address, sender, recipient) = - utils::setup( /* with_account_contracts */ true); + let (env, nft_contract_address, sender, recipient) = utils::setup(/* with_account_contracts */ true); // We set random value for the token_id as the nonce check is before we use the value. let token_id = random(); - let transfer_in_private_from_call_interface = - NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 1); - authwit_cheatcodes::add_private_authwit_from_call_interface( - sender, - sender, - transfer_in_private_from_call_interface, - ); + let transfer_in_private_from_call_interface = NFT::at(nft_contract_address).transfer_in_private(sender, recipient, token_id, 1); + authwit_cheatcodes::add_private_authwit_from_call_interface(sender, sender, transfer_in_private_from_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Try transferring the NFT diff --git a/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_in_public.nr b/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_in_public.nr index b5fb7c59698..ac8eb37d978 100644 --- a/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_in_public.nr +++ b/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_in_public.nr @@ -6,13 +6,10 @@ use crate::NFT; #[test] unconstrained fn transfer_in_public() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_and_mint(/* with_account_contracts */ false); // Transfer the NFT - NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 0).call( - &mut env.public(), - ); + NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 0).call(&mut env.public()); utils::assert_owns_public_nft(env, nft_contract_address, recipient, token_id); } @@ -20,8 +17,7 @@ unconstrained fn transfer_in_public() { #[test] unconstrained fn transfer_in_public_to_self() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, user, _, token_id) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, nft_contract_address, user, _, token_id) = utils::setup_and_mint(/* with_account_contracts */ false); // Transfer the NFT NFT::at(nft_contract_address).transfer_in_public(user, user, token_id, 0).call(&mut env.public()); @@ -33,16 +29,10 @@ unconstrained fn transfer_in_public_to_self() { #[test] unconstrained fn transfer_in_public_on_behalf_of_other() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_and_mint( /* with_account_contracts */ true); - - let transfer_in_public_from_call_interface = - NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 1); - authwit_cheatcodes::add_public_authwit_from_call_interface( - sender, - recipient, - transfer_in_public_from_call_interface, - ); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_and_mint(/* with_account_contracts */ true); + + let transfer_in_public_from_call_interface = NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 1); + authwit_cheatcodes::add_public_authwit_from_call_interface(sender, recipient, transfer_in_public_from_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Transfer the NFT @@ -57,57 +47,42 @@ unconstrained fn transfer_in_public_failure_on_behalf_of_self_non_zero_nonce() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough. // The authwit check is in the beginning so we don't need to waste time on minting the NFT and transferring // it to private.. - let (env, nft_contract_address, sender, recipient) = - utils::setup( /* with_account_contracts */ false); + let (env, nft_contract_address, sender, recipient) = utils::setup(/* with_account_contracts */ false); // We set random value for the token_id as the nonce check is before we use the value. let token_id = random(); // Try to transfer the NFT - NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, random()).call( - &mut env.public(), - ); + NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, random()).call(&mut env.public()); } #[test(should_fail_with = "invalid owner")] unconstrained fn transfer_in_public_non_existent_nft() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, sender, recipient) = - utils::setup( /* with_account_contracts */ false); + let (env, nft_contract_address, sender, recipient) = utils::setup(/* with_account_contracts */ false); // Try to transfer the NFT let token_id = 612; - NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 0).call( - &mut env.public(), - ); + NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 0).call(&mut env.public()); } #[test(should_fail_with = "unauthorized")] unconstrained fn transfer_in_public_failure_on_behalf_of_other_without_approval() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_and_mint(/* with_account_contracts */ true); // Impersonate recipient to perform the call env.impersonate(recipient); // Try to transfer tokens - NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 1).call( - &mut env.public(), - ); + NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 1).call(&mut env.public()); } #[test(should_fail_with = "unauthorized")] unconstrained fn transfer_in_public_failure_on_behalf_of_other_wrong_caller() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_and_mint( /* with_account_contracts */ true); - let transfer_in_public_from_call_interface = - NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 1); - authwit_cheatcodes::add_public_authwit_from_call_interface( - sender, - sender, - transfer_in_public_from_call_interface, - ); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_and_mint(/* with_account_contracts */ true); + let transfer_in_public_from_call_interface = NFT::at(nft_contract_address).transfer_in_public(sender, recipient, token_id, 1); + authwit_cheatcodes::add_public_authwit_from_call_interface(sender, sender, transfer_in_public_from_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Try to transfer tokens diff --git a/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_to_private.nr b/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_to_private.nr index e67a1eba5fe..dd82ce8648c 100644 --- a/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_to_private.nr +++ b/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_to_private.nr @@ -14,8 +14,7 @@ unconstrained fn transfer_to_private_internal_orchestration() { // The transfer to private is done in `utils::setup_mint_and_transfer_to_private` and for this reason // in this test we just call it and check the outcome. // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, user, _, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ false); + let (env, nft_contract_address, user, _, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ false); // User should have the note in their private nfts utils::assert_owns_private_nft(nft_contract_address, user, token_id); @@ -39,27 +38,18 @@ unconstrained fn transfer_to_private_external_orchestration() { // We prepare the transfer let hiding_point_slot: Field = NFT::at(nft_contract_address).prepare_transfer_to_private(recipient).call(&mut env.private()); - // Finalize the transfer of the NFT (message sender owns the NFT in public) - NFT::at(nft_contract_address).finalize_transfer_to_private(token_id, hiding_point_slot).call( - &mut env.public(), - ); + NFT::at(nft_contract_address).finalize_transfer_to_private(token_id, hiding_point_slot).call(&mut env.public()); // TODO(#8771): We need to manually add the note because in the partial notes flow `notify_created_note_oracle` // is not called and we don't have a `NoteProcessor` in TXE. let recipient_npk_m_hash = get_public_keys(recipient).npk_m.hash(); - let private_nfts_recipient_slot = - derive_storage_slot_in_map(NFT::storage_layout().private_nfts.slot, recipient); + let private_nfts_recipient_slot = derive_storage_slot_in_map(NFT::storage_layout().private_nfts.slot, recipient); env.add_note( - &mut NFTNote { - token_id, - npk_m_hash: recipient_npk_m_hash, - randomness: note_randomness, - header: NoteHeader::empty(), - }, + &mut NFTNote { token_id, npk_m_hash: recipient_npk_m_hash, randomness: note_randomness, header: NoteHeader::empty() }, private_nfts_recipient_slot, - nft_contract_address, + nft_contract_address ); // Recipient should have the note in their private nfts @@ -72,23 +62,19 @@ unconstrained fn transfer_to_private_external_orchestration() { #[test(should_fail_with = "transfer not prepared")] unconstrained fn transfer_to_private_transfer_not_prepared() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, _, _, token_id) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, nft_contract_address, _, _, token_id) = utils::setup_and_mint(/* with_account_contracts */ false); // Transfer was not prepared so we can use random value for the hiding point slot let hiding_point_slot = random(); // Try finalizing the transfer without preparing it - NFT::at(nft_contract_address).finalize_transfer_to_private(token_id, hiding_point_slot).call( - &mut env.public(), - ); + NFT::at(nft_contract_address).finalize_transfer_to_private(token_id, hiding_point_slot).call(&mut env.public()); } #[test(should_fail_with = "invalid NFT owner")] unconstrained fn transfer_to_private_failure_not_an_owner() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, _, not_owner, token_id) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, nft_contract_address, _, not_owner, token_id) = utils::setup_and_mint(/* with_account_contracts */ false); // (For this specific test we could set a random value for the commitment and not do the call to `prepare...` // as the NFT owner check is before we use the value but that would made the test less robust against changes @@ -97,7 +83,5 @@ unconstrained fn transfer_to_private_failure_not_an_owner() { // Try transferring someone else's public NFT env.impersonate(not_owner); - NFT::at(nft_contract_address).finalize_transfer_to_private(token_id, hiding_point_slot).call( - &mut env.public(), - ); + NFT::at(nft_contract_address).finalize_transfer_to_private(token_id, hiding_point_slot).call(&mut env.public()); } diff --git a/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_to_public.nr b/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_to_public.nr index b386a4c0454..14604c18aaf 100644 --- a/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_to_public.nr +++ b/noir-projects/noir-contracts/contracts/nft_contract/src/test/transfer_to_public.nr @@ -6,12 +6,9 @@ use crate::NFT; #[test] unconstrained fn transfer_to_public() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ false); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ false); - NFT::at(nft_contract_address).transfer_to_public(sender, recipient, token_id, 0).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_to_public(sender, recipient, token_id, 0).call(&mut env.private()); // Recipient should be the public owner utils::assert_owns_public_nft(env, nft_contract_address, recipient, token_id); @@ -20,12 +17,9 @@ unconstrained fn transfer_to_public() { #[test] unconstrained fn transfer_to_public_to_self() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, user, _, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ false); + let (env, nft_contract_address, user, _, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ false); - NFT::at(nft_contract_address).transfer_to_public(user, user, token_id, 0).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_to_public(user, user, token_id, 0).call(&mut env.private()); // Check the user stayed the public owner utils::assert_owns_public_nft(env, nft_contract_address, user, token_id); @@ -33,16 +27,10 @@ unconstrained fn transfer_to_public_to_self() { #[test] unconstrained fn transfer_to_public_on_behalf_of_other() { - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ true); - - let transfer_to_public_call_interface = - NFT::at(nft_contract_address).transfer_to_public(sender, recipient, token_id, 0); - authwit_cheatcodes::add_private_authwit_from_call_interface( - sender, - recipient, - transfer_to_public_call_interface, - ); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ true); + + let transfer_to_public_call_interface = NFT::at(nft_contract_address).transfer_to_public(sender, recipient, token_id, 0); + authwit_cheatcodes::add_private_authwit_from_call_interface(sender, recipient, transfer_to_public_call_interface); // Impersonate recipient env.impersonate(recipient); // transfer_to_public the NFT @@ -55,38 +43,26 @@ unconstrained fn transfer_to_public_on_behalf_of_other() { #[test(should_fail_with = "NFT not found when transferring to public")] unconstrained fn transfer_to_public_failure_not_an_owner() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, _, not_owner, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ false); + let (env, nft_contract_address, _, not_owner, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ false); env.impersonate(not_owner); - NFT::at(nft_contract_address).transfer_to_public(not_owner, not_owner, token_id, 0).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_to_public(not_owner, not_owner, token_id, 0).call(&mut env.private()); } #[test(should_fail_with = "invalid nonce")] unconstrained fn transfer_to_public_failure_on_behalf_of_self_non_zero_nonce() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, nft_contract_address, user, _, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ false); + let (env, nft_contract_address, user, _, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ false); - NFT::at(nft_contract_address).transfer_to_public(user, user, token_id, random()).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_to_public(user, user, token_id, random()).call(&mut env.private()); } #[test(should_fail_with = "Authorization not found for message hash")] unconstrained fn transfer_to_public_failure_on_behalf_of_other_invalid_designated_caller() { - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ true); - - let transfer_to_public_call_interface = - NFT::at(nft_contract_address).transfer_to_public(sender, recipient, token_id, 0); - authwit_cheatcodes::add_private_authwit_from_call_interface( - sender, - sender, - transfer_to_public_call_interface, - ); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ true); + + let transfer_to_public_call_interface = NFT::at(nft_contract_address).transfer_to_public(sender, recipient, token_id, 0); + authwit_cheatcodes::add_private_authwit_from_call_interface(sender, sender, transfer_to_public_call_interface); // Impersonate recipient env.impersonate(recipient); // transfer_to_public the NFT @@ -95,13 +71,10 @@ unconstrained fn transfer_to_public_failure_on_behalf_of_other_invalid_designate #[test(should_fail_with = "Authorization not found for message hash")] unconstrained fn transfer_to_public_failure_on_behalf_of_other_no_approval() { - let (env, nft_contract_address, sender, recipient, token_id) = - utils::setup_mint_and_transfer_to_private( /* with_account_contracts */ true); + let (env, nft_contract_address, sender, recipient, token_id) = utils::setup_mint_and_transfer_to_private(/* with_account_contracts */ true); // Impersonate recipient env.impersonate(recipient); // transfer_to_public the NFT - NFT::at(nft_contract_address).transfer_to_public(sender, recipient, token_id, 0).call( - &mut env.private(), - ); + NFT::at(nft_contract_address).transfer_to_public(sender, recipient, token_id, 0).call(&mut env.private()); } diff --git a/noir-projects/noir-contracts/contracts/parent_contract/src/main.nr b/noir-projects/noir-contracts/contracts/parent_contract/src/main.nr index 141e2ad10f8..a938f343ea5 100644 --- a/noir-projects/noir-contracts/contracts/parent_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/parent_contract/src/main.nr @@ -16,47 +16,41 @@ contract Parent { fn pub_entry_point( target_contract: AztecAddress, target_selector: FunctionSelector, - init_value: Field, + init_value: Field ) -> Field { - context - .call_public_function( - target_contract, - target_selector, - [init_value].as_slice(), - GasOpts::default(), - ) - .deserialize_into() + context.call_public_function( + target_contract, + target_selector, + [init_value].as_slice(), + GasOpts::default() + ).deserialize_into() } // Same as pub_entry_point, but calls the target contract twice, using the return value from the first invocation as the argument for the second. #[public] fn pub_entry_point_twice( target_contract: AztecAddress, target_selector: FunctionSelector, - init_value: Field, + init_value: Field ) -> Field { - let return_value: Field = context - .call_public_function( - target_contract, - target_selector, - [init_value].as_slice(), - GasOpts::default(), - ) - .deserialize_into(); - context - .call_public_function( - target_contract, - target_selector, - [return_value].as_slice(), - GasOpts::default(), - ) - .deserialize_into() + let return_value: Field = context.call_public_function( + target_contract, + target_selector, + [init_value].as_slice(), + GasOpts::default() + ).deserialize_into(); + context.call_public_function( + target_contract, + target_selector, + [return_value].as_slice(), + GasOpts::default() + ).deserialize_into() } // Private function to enqueue a call to the target_contract address using the selector and argument provided #[private] fn enqueue_call_to_child( target_contract: AztecAddress, target_selector: FunctionSelector, - target_value: Field, + target_value: Field ) { context.call_public_function(target_contract, target_selector, [target_value]); } @@ -66,7 +60,7 @@ contract Parent { #[private] fn enqueue_calls_to_child_with_nested_first( target_contract: AztecAddress, - target_selector: FunctionSelector, + target_selector: FunctionSelector ) { let enqueue_call_to_child_selector = comptime { FunctionSelector::from_signature("enqueue_call_to_child((Field),(u32),Field)") @@ -74,7 +68,7 @@ contract Parent { let _ret = context.call_private_function( context.this_address(), enqueue_call_to_child_selector, - [target_contract.to_field(), target_selector.to_field(), 10], + [target_contract.to_field(), target_selector.to_field(), 10] ); context.call_public_function(target_contract, target_selector, [20]); } @@ -84,7 +78,7 @@ contract Parent { #[private] fn enqueue_calls_to_child_with_nested_last( target_contract: AztecAddress, - target_selector: FunctionSelector, + target_selector: FunctionSelector ) { context.call_public_function(target_contract, target_selector, [20]); let enqueue_call_to_child_selector = comptime { @@ -93,7 +87,7 @@ contract Parent { let _ret = context.call_private_function( context.this_address(), enqueue_call_to_child_selector, - [target_contract.to_field(), target_selector.to_field(), 10], + [target_contract.to_field(), target_selector.to_field(), 10] ); } // Private function to enqueue a call to the target_contract address using the selector and argument provided @@ -101,7 +95,7 @@ contract Parent { fn enqueue_call_to_child_twice( target_contract: AztecAddress, target_selector: FunctionSelector, - target_value: Field, + target_value: Field ) { // Enqueue the first public call context.call_public_function(target_contract, target_selector, [target_value]); @@ -113,15 +107,16 @@ contract Parent { fn enqueue_call_to_pub_entry_point( target_contract: AztecAddress, target_selector: FunctionSelector, - target_value: Field, + target_value: Field ) { - let pub_entry_point_selector = - comptime { FunctionSelector::from_signature("pub_entry_point((Field),(u32),Field)") }; + let pub_entry_point_selector = comptime { + FunctionSelector::from_signature("pub_entry_point((Field),(u32),Field)") + }; let this_address = context.this_address(); let _void = context.call_public_function( this_address, pub_entry_point_selector, - [target_contract.to_field(), target_selector.to_field(), target_value], + [target_contract.to_field(), target_selector.to_field(), target_value] ); } // Private function to enqueue two calls to the pub_entry_point function of this same contract, passing the target arguments provided @@ -129,27 +124,28 @@ contract Parent { fn enqueue_calls_to_pub_entry_point( target_contract: AztecAddress, target_selector: FunctionSelector, - target_value: Field, + target_value: Field ) { - let pub_entry_point_selector = - comptime { FunctionSelector::from_signature("pub_entry_point((Field),(u32),Field)") }; + let pub_entry_point_selector = comptime { + FunctionSelector::from_signature("pub_entry_point((Field),(u32),Field)") + }; let this_address = context.this_address(); context.call_public_function( this_address, pub_entry_point_selector, - [target_contract.to_field(), target_selector.to_field(), target_value], + [target_contract.to_field(), target_selector.to_field(), target_value] ); context.call_public_function( this_address, pub_entry_point_selector, - [target_contract.to_field(), target_selector.to_field(), target_value + 1], + [target_contract.to_field(), target_selector.to_field(), target_value + 1] ); } #[private] fn private_static_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 2], + args: [Field; 2] ) -> Field { // Call the target private function context.static_call_private_function(target_contract, target_selector, args).unpack_into() @@ -158,7 +154,7 @@ contract Parent { fn private_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 2], + args: [Field; 2] ) -> Field { // Call the target private function context.call_private_function(target_contract, target_selector, args).unpack_into() @@ -168,19 +164,16 @@ contract Parent { fn private_nested_static_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 2], + args: [Field; 2] ) -> Field { // Call the target private function statically - let private_call_selector = - FunctionSelector::from_signature("private_call((Field),(u32),[Field;2])"); + let private_call_selector = FunctionSelector::from_signature("private_call((Field),(u32),[Field;2])"); let this_address = context.this_address(); - let return_value: Field = context - .static_call_private_function( - this_address, - private_call_selector, - [target_contract.to_field(), target_selector.to_field(), args[0], args[1]], - ) - .unpack_into(); + let return_value: Field = context.static_call_private_function( + this_address, + private_call_selector, + [target_contract.to_field(), target_selector.to_field(), args[0], args[1]] + ).unpack_into(); // Copy the return value from the call to this function's return values return_value } @@ -189,52 +182,46 @@ contract Parent { fn public_static_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 1], + args: [Field; 1] ) -> Field { - context - .static_call_public_function( - target_contract, - target_selector, - args.as_slice(), - GasOpts::default(), - ) - .deserialize_into() + context.static_call_public_function( + target_contract, + target_selector, + args.as_slice(), + GasOpts::default() + ).deserialize_into() } // Public function to set a static context and verify correct propagation for nested public calls #[public] fn public_nested_static_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 1], + args: [Field; 1] ) -> Field { // Call the target public function through the pub entrypoint statically - let pub_entry_point_selector = - FunctionSelector::from_signature("pub_entry_point((Field),(u32),Field)"); + let pub_entry_point_selector = FunctionSelector::from_signature("pub_entry_point((Field),(u32),Field)"); let this_address = context.this_address(); - context - .static_call_public_function( - this_address, - pub_entry_point_selector, - [target_contract.to_field(), target_selector.to_field(), args[0]].as_slice(), - GasOpts::default(), - ) - .deserialize_into() + context.static_call_public_function( + this_address, + pub_entry_point_selector, + [target_contract.to_field(), target_selector.to_field(), args[0]].as_slice(), + GasOpts::default() + ).deserialize_into() } // Private function to enqueue a static call to the pub_entry_point function of another contract, passing the target arguments provided #[private] fn enqueue_static_nested_call_to_pub_function( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 1], + args: [Field; 1] ) { // Call the target public function through the pub entrypoint statically - let pub_entry_point_selector = - FunctionSelector::from_signature("pub_entry_point((Field),(u32),Field)"); + let pub_entry_point_selector = FunctionSelector::from_signature("pub_entry_point((Field),(u32),Field)"); let this_address = context.this_address(); context.static_call_public_function( this_address, pub_entry_point_selector, - [target_contract.to_field(), target_selector.to_field(), args[0]], + [target_contract.to_field(), target_selector.to_field(), args[0]] ); } // Private function to enqueue a static call to the pub_entry_point function of another contract, passing the target arguments provided @@ -242,7 +229,7 @@ contract Parent { fn enqueue_static_call_to_pub_function( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 1], + args: [Field; 1] ) { // Call the target private function context.static_call_public_function(target_contract, target_selector, args); @@ -267,13 +254,13 @@ contract Parent { cheatcodes::advance_blocks_by(1); // Set value in child through parent let value_to_set = 7; - let result = Parent::at(parent_contract_address) - .private_call( - child_contract_address, - comptime { FunctionSelector::from_signature("private_set_value(Field,(Field))") }, - [value_to_set, owner.to_field()], - ) - .call(&mut env.private()); + let result = Parent::at(parent_contract_address).private_call( + child_contract_address, + comptime { + FunctionSelector::from_signature("private_set_value(Field,(Field))") + }, + [value_to_set, owner.to_field()] + ).call(&mut env.private()); assert(result == value_to_set); // Read the stored value in the note. We have to change the contract address to the child contract in order to read its notes env.impersonate(child_contract_address); @@ -285,13 +272,13 @@ contract Parent { assert(note_value == value_to_set); assert(note_value == result); // Get value from child through parent - let read_result = Parent::at(parent_contract_address) - .private_call( - child_contract_address, - comptime { FunctionSelector::from_signature("private_get_value(Field,(Field))") }, - [7, owner.to_field()], - ) - .call(&mut env.private()); + let read_result = Parent::at(parent_contract_address).private_call( + child_contract_address, + comptime { + FunctionSelector::from_signature("private_get_value(Field,(Field))") + }, + [7, owner.to_field()] + ).call(&mut env.private()); assert(note_value == read_result); } } diff --git a/noir-projects/noir-contracts/contracts/pending_note_hashes_contract/src/main.nr b/noir-projects/noir-contracts/contracts/pending_note_hashes_contract/src/main.nr index c25ab29afdb..c15aef6208b 100644 --- a/noir-projects/noir-contracts/contracts/pending_note_hashes_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/pending_note_hashes_contract/src/main.nr @@ -7,13 +7,9 @@ use dep::aztec::macros::aztec; #[aztec] contract PendingNoteHashes { // Libs - use dep::aztec::prelude::{ - AztecAddress, FunctionSelector, NoteGetterOptions, PrivateContext, Map, PrivateSet, - }; + use dep::aztec::prelude::{AztecAddress, FunctionSelector, NoteGetterOptions, PrivateContext, Map, PrivateSet}; use dep::value_note::{filter::filter_notes_min_sum, value_note::ValueNote}; - use dep::aztec::protocol_types::constants::{ - MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, MAX_NOTE_HASHES_PER_CALL, - }; + use dep::aztec::protocol_types::constants::{MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, MAX_NOTE_HASHES_PER_CALL}; use dep::aztec::encrypted_logs::encrypted_note_emission::encode_and_encrypt_note; use dep::aztec::note::note_emission::NoteEmission; use dep::aztec::keys::getters::get_public_keys; @@ -34,7 +30,7 @@ contract PendingNoteHashes { fn test_insert_then_get_then_nullify_flat( amount: Field, owner: AztecAddress, - outgoing_viewer: AztecAddress, + outgoing_viewer: AztecAddress ) -> Field { let owner_balance = storage.balances.at(owner); @@ -44,12 +40,14 @@ contract PendingNoteHashes { let mut note = ValueNote::new(amount, owner_keys.npk_m.hash()); // Insert note - owner_balance.insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + owner_balance.insert(&mut note).emit( + encode_and_encrypt_note( + &mut context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); let options = NoteGetterOptions::with_filter(filter_notes_min_sum, amount); // get note inserted above @@ -97,12 +95,14 @@ contract PendingNoteHashes { let mut note = ValueNote::new(amount, owner_keys.npk_m.hash()); // Insert note - owner_balance.insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + owner_balance.insert(&mut note).emit( + encode_and_encrypt_note( + &mut context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); } // Nested/inner function to create and insert a note @@ -112,7 +112,7 @@ contract PendingNoteHashes { fn insert_note_static_randomness( amount: Field, owner: AztecAddress, - outgoing_viewer: AztecAddress, + outgoing_viewer: AztecAddress ) { let mut owner_balance = storage.balances.at(owner); @@ -123,12 +123,14 @@ contract PendingNoteHashes { note.randomness = 2; // Insert note - owner_balance.insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + owner_balance.insert(&mut note).emit( + encode_and_encrypt_note( + &mut context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); } // Nested/inner function to create and insert a note @@ -145,20 +147,24 @@ contract PendingNoteHashes { // Insert note let emission = owner_balance.insert(&mut note); - emission.emit(encode_and_encrypt_note( - &mut context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + emission.emit( + encode_and_encrypt_note( + &mut context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); // Emit note again - emission.emit(encode_and_encrypt_note( - &mut context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + emission.emit( + encode_and_encrypt_note( + &mut context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); } // Nested/inner function to get a note and confirm it matches the expected value @@ -194,19 +200,19 @@ contract PendingNoteHashes { owner: AztecAddress, outgoing_viewer: AztecAddress, insert_fn_selector: FunctionSelector, - get_then_nullify_fn_selector: FunctionSelector, + get_then_nullify_fn_selector: FunctionSelector ) { // nested call to create/insert note let _res = context.call_private_function( inputs.call_context.contract_address, insert_fn_selector, - [amount, owner.to_field(), outgoing_viewer.to_field()], + [amount, owner.to_field(), outgoing_viewer.to_field()] ); // nested call to read and nullify that note let _res = context.call_private_function( inputs.call_context.contract_address, get_then_nullify_fn_selector, - [amount, owner.to_field()], + [amount, owner.to_field()] ); } @@ -217,7 +223,7 @@ contract PendingNoteHashes { owner: AztecAddress, outgoing_viewer: AztecAddress, insert_fn_selector: FunctionSelector, - get_then_nullify_fn_selector: FunctionSelector, + get_then_nullify_fn_selector: FunctionSelector ) { // args for nested calls let insertArgs = [amount, owner.to_field(), outgoing_viewer.to_field()]; @@ -227,23 +233,23 @@ contract PendingNoteHashes { let _callStackItem1 = context.call_private_function( inputs.call_context.contract_address, insert_fn_selector, - insertArgs, + insertArgs ); let _callStackItem2 = context.call_private_function( inputs.call_context.contract_address, insert_fn_selector, - insertArgs, + insertArgs ); // nested call to read and nullify that note let _callStackItem3 = context.call_private_function( inputs.call_context.contract_address, get_then_nullify_fn_selector, - getNullifyArgs, + getNullifyArgs ); let _callStackItem4 = context.call_private_function( inputs.call_context.contract_address, get_then_nullify_fn_selector, - getNullifyArgs, + getNullifyArgs ); // nested call to confirm that balance is zero // TODO(dbanks12): once > 4 nested calls is supported, can confirm 0 balance: @@ -257,7 +263,7 @@ contract PendingNoteHashes { owner: AztecAddress, outgoing_viewer: AztecAddress, insert_fn_selector: FunctionSelector, - get_then_nullify_fn_selector: FunctionSelector, + get_then_nullify_fn_selector: FunctionSelector ) { // args for nested calls let insertArgs = [amount, owner.to_field(), outgoing_viewer.to_field()]; @@ -267,18 +273,18 @@ contract PendingNoteHashes { let _callStackItem1 = context.call_private_function( inputs.call_context.contract_address, insert_fn_selector, - insertArgs, + insertArgs ); let _callStackItem2 = context.call_private_function( inputs.call_context.contract_address, insert_fn_selector, - insertArgs, + insertArgs ); // nested call to read and nullify that note let _callStackItem3 = context.call_private_function( inputs.call_context.contract_address, get_then_nullify_fn_selector, - getNullifyArgs, + getNullifyArgs ); } @@ -291,7 +297,7 @@ contract PendingNoteHashes { owner: AztecAddress, outgoing_viewer: AztecAddress, insert_fn_selector: FunctionSelector, - get_then_nullify_fn_selector: FunctionSelector, + get_then_nullify_fn_selector: FunctionSelector ) { // args for nested calls let insertArgs = [amount, owner.to_field(), outgoing_viewer.to_field()]; @@ -301,18 +307,18 @@ contract PendingNoteHashes { let _callStackItem1 = context.call_private_function( inputs.call_context.contract_address, insert_fn_selector, - insertArgs, + insertArgs ); // nested call to read and nullify that note let _callStackItem2 = context.call_private_function( inputs.call_context.contract_address, get_then_nullify_fn_selector, - getNullifyArgs, + getNullifyArgs ); let _callStackItem3 = context.call_private_function( inputs.call_context.contract_address, get_then_nullify_fn_selector, - getNullifyArgs, + getNullifyArgs ); } // Confirm cannot get/read a pending note hash in a nested call @@ -334,20 +340,18 @@ contract PendingNoteHashes { fn test_recursively_create_notes( owner: AztecAddress, outgoing_viewer: AztecAddress, - how_many_recursions: u64, + how_many_recursions: u64 ) { create_max_notes(owner, outgoing_viewer, storage, &mut context); - PendingNoteHashes::at(context.this_address()) - .recursively_destroy_and_create_notes(owner, outgoing_viewer, how_many_recursions) - .call(&mut context); + PendingNoteHashes::at(context.this_address()).recursively_destroy_and_create_notes(owner, outgoing_viewer, how_many_recursions).call(&mut context); } #[private] fn recursively_destroy_and_create_notes( owner: AztecAddress, outgoing_viewer: AztecAddress, - executions_left: u64, + executions_left: u64 ) { assert(executions_left > 0); @@ -357,9 +361,7 @@ contract PendingNoteHashes { let executions_left = executions_left - 1; if executions_left > 0 { - PendingNoteHashes::at(context.this_address()) - .recursively_destroy_and_create_notes(owner, outgoing_viewer, executions_left) - .call(&mut context); + PendingNoteHashes::at(context.this_address()).recursively_destroy_and_create_notes(owner, outgoing_viewer, executions_left).call(&mut context); } } @@ -376,12 +378,14 @@ contract PendingNoteHashes { let mut good_note = ValueNote::new(10, owner_npk_m_hash); // Insert good note with real log - owner_balance.insert(&mut good_note).emit(encode_and_encrypt_note( - &mut context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + owner_balance.insert(&mut good_note).emit( + encode_and_encrypt_note( + &mut context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); // We will emit a note log with an incorrect preimage to ensure the pxe throws // This note has not been inserted... @@ -390,12 +394,14 @@ contract PendingNoteHashes { let existing_note_header = good_note.get_header(); bad_note.set_header(existing_note_header); - NoteEmission::new(bad_note).emit(encode_and_encrypt_note( - &mut context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + NoteEmission::new(bad_note).emit( + encode_and_encrypt_note( + &mut context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); } #[contract_library_method] @@ -403,7 +409,7 @@ contract PendingNoteHashes { owner: AztecAddress, outgoing_viewer: AztecAddress, storage: Storage<&mut PrivateContext>, - context: &mut PrivateContext, + context: &mut PrivateContext ) { let owner_balance = storage.balances.at(owner); @@ -414,12 +420,7 @@ contract PendingNoteHashes { for i in 0..max_notes_per_call() { let mut note = ValueNote::new(i as Field, owner_npk_m_hash); - owner_balance.insert(&mut note).emit(encode_and_encrypt_note( - context, - outgoing_viewer_ovpk_m, - owner_ivpk_m, - owner, - )); + owner_balance.insert(&mut note).emit(encode_and_encrypt_note(context, outgoing_viewer_ovpk_m, owner_ivpk_m, owner)); } } diff --git a/noir-projects/noir-contracts/contracts/private_fpc_contract/src/main.nr b/noir-projects/noir-contracts/contracts/private_fpc_contract/src/main.nr index c3ec2837927..2c5663962c3 100644 --- a/noir-projects/noir-contracts/contracts/private_fpc_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/private_fpc_contract/src/main.nr @@ -7,7 +7,7 @@ contract PrivateFPC { use dep::aztec::{ protocol_types::{address::AztecAddress, hash::compute_siloed_nullifier}, state_vars::SharedImmutable, - macros::{storage::storage, functions::{private, initializer, public}}, + macros::{storage::storage, functions::{private, initializer, public}} }; use token::Token; use crate::settings::Settings; @@ -31,9 +31,7 @@ contract PrivateFPC { assert(asset == settings.other_asset); - Token::at(asset).setup_refund(settings.admin, context.msg_sender(), amount).call( - &mut context, - ); + Token::at(asset).setup_refund(settings.admin, context.msg_sender(), amount).call(&mut context); context.set_as_fee_payer(); } } diff --git a/noir-projects/noir-contracts/contracts/private_fpc_contract/src/settings.nr b/noir-projects/noir-contracts/contracts/private_fpc_contract/src/settings.nr index fe5a5474e01..3a3ea50030b 100644 --- a/noir-projects/noir-contracts/contracts/private_fpc_contract/src/settings.nr +++ b/noir-projects/noir-contracts/contracts/private_fpc_contract/src/settings.nr @@ -15,9 +15,6 @@ impl Serialize for Settings { impl Deserialize for Settings { fn deserialize(fields: [Field; SETTINGS_LENGTH]) -> Self { - Settings { - other_asset: AztecAddress::from_field(fields[0]), - admin: AztecAddress::from_field(fields[1]), - } + Settings { other_asset: AztecAddress::from_field(fields[0]), admin: AztecAddress::from_field(fields[1]) } } } diff --git a/noir-projects/noir-contracts/contracts/router_contract/src/main.nr b/noir-projects/noir-contracts/contracts/router_contract/src/main.nr index 10908953fbc..914b3829f75 100644 --- a/noir-projects/noir-contracts/contracts/router_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/router_contract/src/main.nr @@ -15,9 +15,7 @@ contract Router { /// to the `value. #[private] fn check_timestamp(operation: u8, value: u64) { - Router::at(context.this_address())._check_timestamp(operation, value).enqueue_view( - &mut context, - ); + Router::at(context.this_address())._check_timestamp(operation, value).enqueue_view(&mut context); } #[public] @@ -34,9 +32,7 @@ contract Router { /// to the `value. #[private] fn check_block_number(operation: u8, value: Field) { - Router::at(context.this_address())._check_block_number(operation, value).enqueue_view( - &mut context, - ); + Router::at(context.this_address())._check_block_number(operation, value).enqueue_view(&mut context); } #[public] diff --git a/noir-projects/noir-contracts/contracts/schnorr_account_contract/src/main.nr b/noir-projects/noir-contracts/contracts/schnorr_account_contract/src/main.nr index ddd2ae24292..0079745c3be 100644 --- a/noir-projects/noir-contracts/contracts/schnorr_account_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/schnorr_account_contract/src/main.nr @@ -12,14 +12,11 @@ contract SchnorrAccount { use dep::aztec::encrypted_logs::encrypted_note_emission::encode_and_encrypt_note; use dep::authwit::{ entrypoint::{app::AppPayload, fee::FeePayload}, account::AccountActions, - auth_witness::get_auth_witness, - auth::{compute_authwit_nullifier, compute_authwit_message_hash}, + auth_witness::get_auth_witness, auth::{compute_authwit_nullifier, compute_authwit_message_hash} }; use dep::aztec::{hash::compute_siloed_nullifier, keys::getters::get_public_keys}; use dep::aztec::oracle::get_nullifier_membership_witness::get_low_nullifier_membership_witness; - use dep::aztec::macros::{ - storage::storage, functions::{private, initializer, view, noinitcheck}, - }; + use dep::aztec::macros::{storage::storage, functions::{private, initializer, view, noinitcheck}}; use crate::public_key_note::PublicKeyNote; @@ -37,14 +34,8 @@ contract SchnorrAccount { // Not emitting outgoing for msg_sender here to not have to register keys for the contract through which we // deploy this (typically MultiCallEntrypoint). I think it's ok here as I feel the outgoing here is not that // important. - let mut pub_key_note = - PublicKeyNote::new(signing_pub_key_x, signing_pub_key_y, this_keys.npk_m.hash()); - storage.signing_public_key.initialize(&mut pub_key_note).emit(encode_and_encrypt_note( - &mut context, - this_keys.ovpk_m, - this_keys.ivpk_m, - this, - )); + let mut pub_key_note = PublicKeyNote::new(signing_pub_key_x, signing_pub_key_y, this_keys.npk_m.hash()); + storage.signing_public_key.initialize(&mut pub_key_note).emit(encode_and_encrypt_note(&mut context, this_keys.ovpk_m, this_keys.ivpk_m, this)); } // Note: If you globally change the entrypoint signature don't forget to update account_entrypoint.ts file @@ -70,7 +61,9 @@ contract SchnorrAccount { let storage = Storage::init(context); let public_key = storage.signing_public_key.get_note(); // Load auth witness - let witness: [Field; 64] = unsafe { get_auth_witness(outer_hash) }; + let witness: [Field; 64] = unsafe { + get_auth_witness(outer_hash) + }; let mut signature: [u8; 64] = [0; 64]; for i in 0..64 { signature[i] = witness[i] as u8; @@ -81,7 +74,7 @@ contract SchnorrAccount { public_key.x, public_key.y, signature, - outer_hash.to_be_bytes::<32>(), + outer_hash.to_be_bytes::<32>() ) // docs:end:is_valid_impl } @@ -95,12 +88,7 @@ contract SchnorrAccount { unconstrained fn lookup_validity(consumer: AztecAddress, inner_hash: Field) -> pub bool { let public_key = storage.signing_public_key.view_note(); - let message_hash = compute_authwit_message_hash( - consumer, - context.chain_id(), - context.version(), - inner_hash, - ); + let message_hash = compute_authwit_message_hash(consumer, context.chain_id(), context.version(), inner_hash); let witness: [Field; 64] = get_auth_witness(message_hash); let mut signature: [u8; 64] = [0; 64]; @@ -111,7 +99,7 @@ contract SchnorrAccount { public_key.x, public_key.y, signature, - message_hash.to_be_bytes::<32>(), + message_hash.to_be_bytes::<32>() ); // Compute the nullifier and check if it is spent @@ -119,8 +107,7 @@ contract SchnorrAccount { // it is not as part of execution of the contract, so we are good. let nullifier = compute_authwit_nullifier(context.this_address(), inner_hash); let siloed_nullifier = compute_siloed_nullifier(consumer, nullifier); - let lower_wit = - get_low_nullifier_membership_witness(context.block_number(), siloed_nullifier); + let lower_wit = get_low_nullifier_membership_witness(context.block_number(), siloed_nullifier); let is_spent = lower_wit.leaf_preimage.nullifier == siloed_nullifier; !is_spent & valid_in_private diff --git a/noir-projects/noir-contracts/contracts/schnorr_account_contract/src/public_key_note.nr b/noir-projects/noir-contracts/contracts/schnorr_account_contract/src/public_key_note.nr index 2234c8316f2..6574d1a19e4 100644 --- a/noir-projects/noir-contracts/contracts/schnorr_account_contract/src/public_key_note.nr +++ b/noir-projects/noir-contracts/contracts/schnorr_account_contract/src/public_key_note.nr @@ -1,9 +1,8 @@ use dep::aztec::prelude::{NoteHeader, NullifiableNote, PrivateContext}; use dep::aztec::{ note::utils::compute_note_hash_for_nullify, keys::getters::get_nsk_app, - protocol_types::{ - constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator, - }, macros::notes::note, + protocol_types::{constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + macros::notes::note }; // Stores a public key composed of two fields @@ -17,15 +16,11 @@ pub struct PublicKeyNote { } impl NullifiableNote for PublicKeyNote { - fn compute_nullifier( - self, - context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { let secret = context.request_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } @@ -34,7 +29,7 @@ impl NullifiableNote for PublicKeyNote { let secret = get_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } } diff --git a/noir-projects/noir-contracts/contracts/schnorr_hardcoded_account_contract/src/main.nr b/noir-projects/noir-contracts/contracts/schnorr_hardcoded_account_contract/src/main.nr index 30790f2a817..de8a0cd2745 100644 --- a/noir-projects/noir-contracts/contracts/schnorr_hardcoded_account_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/schnorr_hardcoded_account_contract/src/main.nr @@ -7,7 +7,7 @@ contract SchnorrHardcodedAccount { use dep::aztec::prelude::PrivateContext; use dep::authwit::{ entrypoint::{app::AppPayload, fee::FeePayload}, account::AccountActions, - auth_witness::get_auth_witness, + auth_witness::get_auth_witness }; use dep::aztec::macros::functions::{private, view}; @@ -33,7 +33,9 @@ contract SchnorrHardcodedAccount { #[contract_library_method] fn is_valid_impl(_context: &mut PrivateContext, outer_hash: Field) -> bool { // Load auth witness and format as an u8 array - let witness: [Field; 64] = unsafe { get_auth_witness(outer_hash) }; + let witness: [Field; 64] = unsafe { + get_auth_witness(outer_hash) + }; let mut signature: [u8; 64] = [0; 64]; for i in 0..64 { signature[i] = witness[i] as u8; @@ -44,7 +46,7 @@ contract SchnorrHardcodedAccount { public_key_x, public_key_y, signature, - outer_hash.to_be_bytes::<32>(), + outer_hash.to_be_bytes::<32>() ) } // docs:end:is-valid diff --git a/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/auth_oracle.nr b/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/auth_oracle.nr index 97b1205054d..92bf7d6ad45 100644 --- a/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/auth_oracle.nr +++ b/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/auth_oracle.nr @@ -1,7 +1,5 @@ use dep::authwit::auth_witness; -use dep::aztec::protocol_types::{ - address::PartialAddress, utils::arr_copy_slice, public_keys::{PublicKeys, PUBLIC_KEYS_LENGTH}, -}; +use dep::aztec::protocol_types::{address::PartialAddress, utils::arr_copy_slice, public_keys::{PublicKeys, PUBLIC_KEYS_LENGTH}}; pub struct AuthWitness { keys: PublicKeys, @@ -18,7 +16,7 @@ impl AuthWitness { Self { keys: PublicKeys::deserialize(arr_copy_slice(values, [0; PUBLIC_KEYS_LENGTH], 0)), signature, - partial_address: PartialAddress::from_field(values[76]), + partial_address: PartialAddress::from_field(values[76]) } } } diff --git a/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/main.nr b/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/main.nr index 25a1c376799..5aeef442a41 100644 --- a/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/main.nr @@ -29,7 +29,9 @@ contract SchnorrSingleKeyAccount { #[contract_library_method] fn is_valid_impl(context: &mut PrivateContext, outer_hash: Field) -> bool { - let witness = unsafe { get_auth_witness(outer_hash) }; + let witness = unsafe { + get_auth_witness(outer_hash) + }; recover_address(outer_hash, witness).eq(context.this_address()) } } diff --git a/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/util.nr b/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/util.nr index 82e839cda08..824847e2c0c 100644 --- a/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/util.nr +++ b/noir-projects/noir-contracts/contracts/schnorr_single_key_account_contract/src/util.nr @@ -9,7 +9,7 @@ pub fn recover_address(message_hash: Field, witness: AuthWitness) -> AztecAddres witness.keys.ivpk_m.inner.x, witness.keys.ivpk_m.inner.y, witness.signature, - message_bytes, + message_bytes ); assert(verification == true); diff --git a/noir-projects/noir-contracts/contracts/spam_contract/src/main.nr b/noir-projects/noir-contracts/contracts/spam_contract/src/main.nr index c44c8b050aa..2337690507b 100644 --- a/noir-projects/noir-contracts/contracts/spam_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/spam_contract/src/main.nr @@ -11,12 +11,13 @@ contract Spam { encrypted_logs::encrypted_note_emission::encode_and_encrypt_note_unconstrained, keys::getters::get_public_keys, protocol_types::{ - hash::poseidon2_hash_with_separator, - constants::{ - MAX_NOTE_HASHES_PER_CALL, MAX_NULLIFIERS_PER_CALL, GENERATOR_INDEX__NOTE_NULLIFIER, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, - }, - }, macros::{storage::storage, functions::{private, public, internal}}, + hash::poseidon2_hash_with_separator, + constants::{ + MAX_NOTE_HASHES_PER_CALL, MAX_NULLIFIERS_PER_CALL, GENERATOR_INDEX__NOTE_NULLIFIER, + MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL + } + }, + macros::{storage::storage, functions::{private, public, internal}} }; use crate::types::{token_note::TokenNote, balance_set::BalanceSet}; @@ -35,34 +36,27 @@ contract Spam { for _ in 0..MAX_NOTE_HASHES_PER_CALL { storage.balances.at(caller).add(caller_keys.npk_m, U128::from_integer(amount)).emit( - encode_and_encrypt_note_unconstrained( - &mut context, - caller_keys.ovpk_m, - caller_keys.ivpk_m, - caller, - ), + encode_and_encrypt_note_unconstrained(&mut context, caller_keys.ovpk_m, caller_keys.ivpk_m, caller) ); } for i in 0..MAX_NULLIFIERS_PER_CALL { if (i < nullifier_count) { - context.push_nullifier(poseidon2_hash_with_separator( - [nullifier_seed, i as Field], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, - )); + context.push_nullifier( + poseidon2_hash_with_separator( + [nullifier_seed, i as Field], + GENERATOR_INDEX__NOTE_NULLIFIER as Field + ) + ); } } if (call_public) { - Spam::at(context.this_address()) - .public_spam(0, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL) - .enqueue(&mut context); - Spam::at(context.this_address()) - .public_spam( - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - ) - .enqueue(&mut context); + Spam::at(context.this_address()).public_spam(0, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL).enqueue(&mut context); + Spam::at(context.this_address()).public_spam( + MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, + MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX + ).enqueue(&mut context); } } diff --git a/noir-projects/noir-contracts/contracts/spam_contract/src/types/balance_set.nr b/noir-projects/noir-contracts/contracts/spam_contract/src/types/balance_set.nr index fe7840ff1ba..10be965cfd4 100644 --- a/noir-projects/noir-contracts/contracts/spam_contract/src/types/balance_set.nr +++ b/noir-projects/noir-contracts/contracts/spam_contract/src/types/balance_set.nr @@ -1,11 +1,9 @@ // This file is copied from the token contract. -use dep::aztec::prelude::{ - NoteGetterOptions, NoteViewerOptions, NoteInterface, NullifiableNote, PrivateSet, -}; +use dep::aztec::prelude::{NoteGetterOptions, NoteViewerOptions, NoteInterface, NullifiableNote, PrivateSet}; use dep::aztec::{ context::{PrivateContext, UnconstrainedContext}, protocol_types::{constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, public_keys::NpkM}, - note::note_emission::OuterNoteEmission, + note::note_emission::OuterNoteEmission }; use crate::types::token_note::OwnedNote; @@ -23,18 +21,16 @@ impl BalanceSet { impl BalanceSet { pub unconstrained fn balance_of(self: Self) -> U128 where - T: NoteInterface + NullifiableNote + OwnedNote, - { + T: NoteInterface + NullifiableNote + OwnedNote, { self.balance_of_with_offset(0) } pub unconstrained fn balance_of_with_offset( self: Self, - offset: u32, + offset: u32 ) -> U128 where - T: NoteInterface + NullifiableNote + OwnedNote, - { + T: NoteInterface + NullifiableNote + OwnedNote, { let mut balance = U128::from_integer(0); // docs:start:view_notes let mut options = NoteViewerOptions::new(); @@ -57,11 +53,10 @@ impl BalanceSet { pub fn add( self: Self, owner_npk_m: NpkM, - addend: U128, + addend: U128 ) -> OuterNoteEmission where - T: NoteInterface + NullifiableNote + OwnedNote + Eq, - { + T: NoteInterface + NullifiableNote + OwnedNote + Eq, { if addend == U128::from_integer(0) { OuterNoteEmission::new(Option::none()) } else { @@ -77,11 +72,10 @@ impl BalanceSet { pub fn sub( self: Self, owner_npk_m: NpkM, - amount: U128, + amount: U128 ) -> OuterNoteEmission where - T: NoteInterface + NullifiableNote + OwnedNote + Eq, - { + T: NoteInterface + NullifiableNote + OwnedNote + Eq, { let subtracted = self.try_sub(amount, MAX_NOTE_HASH_READ_REQUESTS_PER_CALL); // try_sub may have substracted more or less than amount. We must ensure that we subtracted at least as much as @@ -102,18 +96,16 @@ impl BalanceSet { pub fn try_sub( self: Self, target_amount: U128, - max_notes: u32, + max_notes: u32 ) -> U128 where - T: NoteInterface + NullifiableNote + OwnedNote + Eq, - { + T: NoteInterface + NullifiableNote + OwnedNote + Eq, { // We are using a preprocessor here (filter applied in an unconstrained context) instead of a filter because // we do not need to prove correct execution of the preprocessor. // Because the `min_sum` notes is not constrained, users could choose to e.g. not call it. However, all this // might result in is simply higher DA costs due to more nullifiers being emitted. Since we don't care // about proving optimal note usage, we can save these constraints and make the circuit smaller. - let options = NoteGetterOptions::with_preprocessor(preprocess_notes_min_sum, target_amount) - .set_limit(max_notes); + let options = NoteGetterOptions::with_preprocessor(preprocess_notes_min_sum, target_amount).set_limit(max_notes); let notes = self.set.pop_notes(options); let mut subtracted = U128::from_integer(0); @@ -135,11 +127,10 @@ impl BalanceSet { // Note that proper usage of this preprocessor requires for notes to be sorted in descending order. pub fn preprocess_notes_min_sum( notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - min_sum: U128, + min_sum: U128 ) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] where - T: NoteInterface + NullifiableNote + OwnedNote, -{ + T: NoteInterface + NullifiableNote + OwnedNote, { let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; let mut sum = U128::from_integer(0); for i in 0..notes.len() { diff --git a/noir-projects/noir-contracts/contracts/spam_contract/src/types/token_note.nr b/noir-projects/noir-contracts/contracts/spam_contract/src/types/token_note.nr index 5108ad854b0..03bc8e3a803 100644 --- a/noir-projects/noir-contracts/contracts/spam_contract/src/types/token_note.nr +++ b/noir-projects/noir-contracts/contracts/spam_contract/src/types/token_note.nr @@ -1,9 +1,8 @@ use dep::aztec::{ prelude::{NoteHeader, NullifiableNote, PrivateContext}, - protocol_types::{ - constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator, - }, note::utils::compute_note_hash_for_nullify, oracle::random::random, - keys::getters::get_nsk_app, macros::notes::note, + protocol_types::{constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + note::utils::compute_note_hash_for_nullify, oracle::random::random, keys::getters::get_nsk_app, + macros::notes::note }; trait OwnedNote { @@ -24,15 +23,11 @@ pub struct TokenNote { impl NullifiableNote for TokenNote { // docs:start:nullifier - fn compute_nullifier( - self, - context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { let secret = context.request_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } // docs:end:nullifier @@ -42,7 +37,7 @@ impl NullifiableNote for TokenNote { let secret = get_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER, + GENERATOR_INDEX__NOTE_NULLIFIER ) } } @@ -61,7 +56,9 @@ impl OwnedNote for TokenNote { // malicious sender could use non-random values to make the note less private. But they already know the full // note pre-image anyway, and so the recipient already trusts them to not disclose this information. We can // therefore assume that the sender will cooperate in the random value generation. - let randomness = unsafe { random() }; + let randomness = unsafe { + random() + }; Self { amount, npk_m_hash: owner_npk_m_hash, randomness, header: NoteHeader::empty() } } diff --git a/noir-projects/noir-contracts/contracts/stateful_test_contract/src/main.nr b/noir-projects/noir-contracts/contracts/stateful_test_contract/src/main.nr index fc65d46ef8a..fd229a997d6 100644 --- a/noir-projects/noir-contracts/contracts/stateful_test_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/stateful_test_contract/src/main.nr @@ -7,7 +7,7 @@ contract StatefulTest { use dep::value_note::{balance_utils, utils::{increment, decrement}, value_note::ValueNote}; use dep::aztec::{ initializer::assert_is_initialized_private, - macros::{storage::storage, functions::{private, public, initializer, noinitcheck, view}}, + macros::{storage::storage, functions::{private, public, initializer, noinitcheck, view}} }; #[storage] @@ -19,9 +19,7 @@ contract StatefulTest { #[private] #[initializer] fn constructor(owner: AztecAddress, outgoing_viewer: AztecAddress, value: Field) { - StatefulTest::at(context.this_address()) - .create_note_no_init_check(owner, outgoing_viewer, value) - .call(&mut context); + StatefulTest::at(context.this_address()).create_note_no_init_check(owner, outgoing_viewer, value).call(&mut context); } #[private] @@ -36,9 +34,7 @@ contract StatefulTest { #[public] #[initializer] fn public_constructor(owner: AztecAddress, _ignored_arg: AztecAddress, value: Field) { - StatefulTest::at(context.this_address()) - .increment_public_value_no_init_check(owner, value) - .call(&mut context); + StatefulTest::at(context.this_address()).increment_public_value_no_init_check(owner, value).call(&mut context); } #[private] diff --git a/noir-projects/noir-contracts/contracts/static_child_contract/src/main.nr b/noir-projects/noir-contracts/contracts/static_child_contract/src/main.nr index b79a844b4c8..0f052efcb01 100644 --- a/noir-projects/noir-contracts/contracts/static_child_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/static_child_contract/src/main.nr @@ -9,7 +9,7 @@ contract StaticChild { note::note_getter_options::NoteGetterOptions, encrypted_logs::encrypted_note_emission::encode_and_encrypt_note, keys::getters::get_public_keys, utils::comparison::Comparator, - macros::{storage::storage, functions::{private, public, view}}, + macros::{storage::storage, functions::{private, public, view}} }; use dep::value_note::value_note::ValueNote; @@ -49,12 +49,7 @@ contract StaticChild { let mut note = ValueNote::new(new_value, owner_keys.npk_m.hash()); - storage.a_private_value.insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + storage.a_private_value.insert(&mut note).emit(encode_and_encrypt_note(&mut context, msg_sender_keys.ovpk_m, owner_keys.ivpk_m, owner)); new_value } @@ -63,18 +58,20 @@ contract StaticChild { fn private_set_value( new_value: Field, owner: AztecAddress, - outgoing_viewer: AztecAddress, + outgoing_viewer: AztecAddress ) -> Field { let owner_keys = get_public_keys(owner); let outgoing_viewer_keys = get_public_keys(outgoing_viewer); let mut note = ValueNote::new(new_value, owner_keys.npk_m.hash()); - storage.a_private_value.insert(&mut note).emit(encode_and_encrypt_note( - &mut context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + storage.a_private_value.insert(&mut note).emit( + encode_and_encrypt_note( + &mut context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); new_value } diff --git a/noir-projects/noir-contracts/contracts/static_parent_contract/src/main.nr b/noir-projects/noir-contracts/contracts/static_parent_contract/src/main.nr index e0d371cbd23..9ec233e9c22 100644 --- a/noir-projects/noir-contracts/contracts/static_parent_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/static_parent_contract/src/main.nr @@ -12,16 +12,14 @@ contract StaticParent { fn public_call( target_contract: AztecAddress, target_selector: FunctionSelector, - arg: Field, + arg: Field ) -> Field { - context - .call_public_function( - target_contract, - target_selector, - [arg].as_slice(), - GasOpts::default(), - ) - .deserialize_into() + context.call_public_function( + target_contract, + target_selector, + [arg].as_slice(), + GasOpts::default() + ).deserialize_into() } // Private function to directly call another private function to the target_contract using the selector and args provided @@ -29,7 +27,7 @@ contract StaticParent { fn private_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 2], + args: [Field; 2] ) -> Field { context.call_private_function(target_contract, target_selector, args).unpack_into() } @@ -39,7 +37,7 @@ contract StaticParent { fn private_call_3_args( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 3], + args: [Field; 3] ) -> Field { context.call_private_function(target_contract, target_selector, args).unpack_into() } @@ -49,7 +47,7 @@ contract StaticParent { fn enqueue_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 1], + args: [Field; 1] ) { context.call_public_function(target_contract, target_selector, args); } @@ -58,7 +56,7 @@ contract StaticParent { fn private_static_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 2], + args: [Field; 2] ) -> Field { context.static_call_private_function(target_contract, target_selector, args).unpack_into() } @@ -68,7 +66,7 @@ contract StaticParent { fn private_static_call_3_args( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 3], + args: [Field; 3] ) -> Field { context.static_call_private_function(target_contract, target_selector, args).unpack_into() } @@ -78,7 +76,7 @@ contract StaticParent { fn private_get_value_from_child( target_contract: AztecAddress, value: Field, - owner: AztecAddress, + owner: AztecAddress ) -> Field { StaticChild::at(target_contract).private_get_value(value, owner).view(&mut context) } @@ -88,11 +86,9 @@ contract StaticParent { fn private_nested_static_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 2], + args: [Field; 2] ) -> Field { - StaticParent::at(context.this_address()) - .private_call(target_contract, target_selector, args) - .view(&mut context) + StaticParent::at(context.this_address()).private_call(target_contract, target_selector, args).view(&mut context) } // Just like function above but with 3 args. @@ -100,11 +96,9 @@ contract StaticParent { fn private_nested_static_call_3_args( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 3], + args: [Field; 3] ) -> Field { - StaticParent::at(context.this_address()) - .private_call_3_args(target_contract, target_selector, args) - .view(&mut context) + StaticParent::at(context.this_address()).private_call_3_args(target_contract, target_selector, args).view(&mut context) } // Public function to statically call another public function to the target_contract using the selector and value provided @@ -112,16 +106,14 @@ contract StaticParent { fn public_static_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 1], + args: [Field; 1] ) -> Field { - context - .static_call_public_function( - target_contract, - target_selector, - args.as_slice(), - GasOpts::default(), - ) - .deserialize_into() + context.static_call_public_function( + target_contract, + target_selector, + args.as_slice(), + GasOpts::default() + ).deserialize_into() } // Same as above but using a specific function from the interface @@ -135,12 +127,10 @@ contract StaticParent { fn public_nested_static_call( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 1], + args: [Field; 1] ) -> Field { // Call the target public function through the pub entrypoint statically - StaticParent::at(context.this_address()) - .public_call(target_contract, target_selector, args[0]) - .view(&mut context) + StaticParent::at(context.this_address()).public_call(target_contract, target_selector, args[0]).view(&mut context) } // Private function to enqueue a static call to a public function of another contract, passing the target arguments provided @@ -148,7 +138,7 @@ contract StaticParent { fn enqueue_static_call_to_pub_function( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 1], + args: [Field; 1] ) { context.static_call_public_function(target_contract, target_selector, args); } @@ -164,11 +154,9 @@ contract StaticParent { fn enqueue_static_nested_call_to_pub_function( target_contract: AztecAddress, target_selector: FunctionSelector, - args: [Field; 1], + args: [Field; 1] ) { // Call the target public function through the pub entrypoint statically - StaticParent::at(context.this_address()) - .public_call(target_contract, target_selector, args[0]) - .enqueue_view(&mut context) + StaticParent::at(context.this_address()).public_call(target_contract, target_selector, args[0]).enqueue_view(&mut context) } } diff --git a/noir-projects/noir-contracts/contracts/test_contract/src/main.nr b/noir-projects/noir-contracts/contracts/test_contract/src/main.nr index 88977b9c7f7..64bd22614b0 100644 --- a/noir-projects/noir-contracts/contracts/test_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/test_contract/src/main.nr @@ -8,15 +8,12 @@ contract Test { use dep::aztec::prelude::{ AztecAddress, EthAddress, FunctionSelector, NoteGetterOptions, NoteViewerOptions, - PrivateImmutable, PrivateSet, + PrivateImmutable, PrivateSet }; use dep::aztec::encrypted_logs::encrypted_note_emission::encode_and_encrypt_note; use dep::aztec::encrypted_logs::encrypted_event_emission::encode_and_encrypt_event_with_randomness_unconstrained; - use dep::aztec::protocol_types::{ - constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, traits::Serialize, point::Point, - public_keys::IvpkM, - }; + use dep::aztec::protocol_types::{constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, traits::Serialize, point::Point, public_keys::IvpkM}; use dep::aztec::note::constants::MAX_NOTES_PER_PAGE; use dep::aztec::keys::getters::get_public_keys; @@ -24,15 +21,14 @@ contract Test { use dep::aztec::{ hash::{pedersen_hash, compute_secret_hash, ArgsHasher}, note::{ - lifecycle::{create_note, destroy_note_unsafe}, note_getter::{get_notes, view_notes}, - note_getter_options::NoteStatus, - }, deploy::deploy_contract as aztec_deploy_contract, oracle::random::random, + lifecycle::{create_note, destroy_note_unsafe}, note_getter::{get_notes, view_notes}, + note_getter_options::NoteStatus + }, + deploy::deploy_contract as aztec_deploy_contract, oracle::random::random, utils::comparison::Comparator, - macros::{storage::storage, events::event, functions::{private, public, internal}}, - }; - use dep::token_portal_content_hash_lib::{ - get_mint_private_content_hash, get_mint_public_content_hash, + macros::{storage::storage, events::event, functions::{private, public, internal}} }; + use dep::token_portal_content_hash_lib::{get_mint_private_content_hash, get_mint_public_content_hash}; use dep::value_note::value_note::ValueNote; // TODO investigate why the macros require EmbeddedCurvePoint and EmbeddedCurveScalar use std::embedded_curve_ops::{EmbeddedCurveScalar, EmbeddedCurvePoint}; @@ -92,30 +88,30 @@ contract Test { value: Field, owner: AztecAddress, outgoing_viewer: AztecAddress, - storage_slot: Field, + storage_slot: Field ) { assert( - storage_slot != storage.example_constant.get_storage_slot(), - "this storage slot is reserved for example_constant", + storage_slot != storage.example_constant.get_storage_slot(), "this storage slot is reserved for example_constant" ); let outgoing_viewer_keys = get_public_keys(outgoing_viewer); let owner_keys = get_public_keys(owner); let mut note = ValueNote::new(value, owner_keys.npk_m.hash()); - create_note(&mut context, storage_slot, &mut note).emit(encode_and_encrypt_note( - &mut context, - outgoing_viewer_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + create_note(&mut context, storage_slot, &mut note).emit( + encode_and_encrypt_note( + &mut context, + outgoing_viewer_keys.ovpk_m, + owner_keys.ivpk_m, + owner + ) + ); } #[private] fn call_get_notes(storage_slot: Field, active_or_nullified: bool) -> Field { assert( - storage_slot != storage.example_constant.get_storage_slot(), - "this storage slot is reserved for example_constant", + storage_slot != storage.example_constant.get_storage_slot(), "this storage slot is reserved for example_constant" ); let mut options = NoteGetterOptions::new(); @@ -123,8 +119,7 @@ contract Test { options = options.set_status(NoteStatus.ACTIVE_OR_NULLIFIED); } - let (notes, _): (BoundedVec, BoundedVec) = - get_notes(&mut context, storage_slot, options); + let (notes, _): (BoundedVec, BoundedVec) = get_notes(&mut context, storage_slot, options); notes.get(0).value } @@ -132,8 +127,7 @@ contract Test { #[private] fn call_get_notes_many(storage_slot: Field, active_or_nullified: bool) -> [Field; 2] { assert( - storage_slot != storage.example_constant.get_storage_slot(), - "this storage slot is reserved for example_constant", + storage_slot != storage.example_constant.get_storage_slot(), "this storage slot is reserved for example_constant" ); let mut options = NoteGetterOptions::new(); @@ -141,16 +135,14 @@ contract Test { options = options.set_status(NoteStatus.ACTIVE_OR_NULLIFIED); } - let (notes, _): (BoundedVec, BoundedVec) = - get_notes(&mut context, storage_slot, options); + let (notes, _): (BoundedVec, BoundedVec) = get_notes(&mut context, storage_slot, options); [notes.get(0).value, notes.get(1).value] } unconstrained fn call_view_notes(storage_slot: Field, active_or_nullified: bool) -> pub Field { assert( - storage_slot != storage.example_constant.get_storage_slot(), - "this storage slot is reserved for example_constant", + storage_slot != storage.example_constant.get_storage_slot(), "this storage slot is reserved for example_constant" ); let mut options = NoteViewerOptions::new(); @@ -163,13 +155,9 @@ contract Test { notes.get(0).value } - unconstrained fn call_view_notes_many( - storage_slot: Field, - active_or_nullified: bool, - ) -> pub [Field; 2] { + unconstrained fn call_view_notes_many(storage_slot: Field, active_or_nullified: bool) -> pub [Field; 2] { assert( - storage_slot != storage.example_constant.get_storage_slot(), - "this storage slot is reserved for example_constant", + storage_slot != storage.example_constant.get_storage_slot(), "this storage slot is reserved for example_constant" ); let mut options = NoteViewerOptions::new(); @@ -185,13 +173,11 @@ contract Test { #[private] fn call_destroy_note(storage_slot: Field) { assert( - storage_slot != storage.example_constant.get_storage_slot(), - "this storage slot is reserved for example_constant", + storage_slot != storage.example_constant.get_storage_slot(), "this storage slot is reserved for example_constant" ); let options = NoteGetterOptions::new(); - let (notes, note_hashes): (BoundedVec, BoundedVec) = - get_notes(&mut context, storage_slot, options); + let (notes, note_hashes): (BoundedVec, BoundedVec) = get_notes(&mut context, storage_slot, options); let note = notes.get(0); let note_hash = note_hashes.get(0); @@ -206,7 +192,7 @@ contract Test { a_number: u32, an_array: [Field; 2], a_struct: DummyNote, - a_deep_struct: DeepStruct, + a_deep_struct: DeepStruct ) -> Field { let mut args = ArgsHasher::new(); args.add(a_field); @@ -230,8 +216,10 @@ contract Test { fn test_setting_teardown() { context.set_public_teardown_function( context.this_address(), - comptime { FunctionSelector::from_signature("dummy_public_call()") }, - [], + comptime { + FunctionSelector::from_signature("dummy_public_call()") + }, + [] ); } @@ -242,11 +230,7 @@ contract Test { // Purely exists for testing #[public] - fn create_l2_to_l1_message_public( - amount: Field, - secret_hash: Field, - portal_address: EthAddress, - ) { + fn create_l2_to_l1_message_public(amount: Field, secret_hash: Field, portal_address: EthAddress) { // Create a commitment to the amount let note = DummyNote::new(amount, secret_hash); @@ -284,74 +268,57 @@ contract Test { fields: [Field; 5], owner: AztecAddress, outgoing_viewer: AztecAddress, - nest: bool, + nest: bool ) { let owner_ivpk_m = get_public_keys(owner).ivpk_m; let outgoing_viewer_ovpk_m = get_public_keys(outgoing_viewer).ovpk_m; - let event = ExampleEvent { - value0: fields[0], - value1: fields[1], - value2: fields[2], - value3: fields[3], - value4: fields[4], - }; - - event.emit(encode_and_encrypt_event_with_randomness_unconstrained( - &mut context, - // testing only - a secret random value is passed in here to salt / mask the address - 5, - outgoing_viewer_ovpk_m, - owner_ivpk_m, - owner, - )); + let event = ExampleEvent { value0: fields[0], value1: fields[1], value2: fields[2], value3: fields[3], value4: fields[4] }; + + event.emit( + encode_and_encrypt_event_with_randomness_unconstrained( + &mut context, + // testing only - a secret random value is passed in here to salt / mask the address + 5, + outgoing_viewer_ovpk_m, + owner_ivpk_m, + owner + ) + ); // this contract has reached max number of functions, so using this one fn // to test nested and non nested encrypted logs if nest { - Test::at(context.this_address()) - .emit_array_as_encrypted_log([0, 0, 0, 0, 0], owner, outgoing_viewer, false) - .call(&mut context); + Test::at(context.this_address()).emit_array_as_encrypted_log([0, 0, 0, 0, 0], owner, outgoing_viewer, false).call(&mut context); let otherEvent = ExampleEvent { value0: 1, value1: 2, value2: 3, value3: 4, value4: 5 }; - otherEvent.emit(encode_and_encrypt_event_with_randomness_unconstrained( - &mut context, - // testing only - a randomness of 0 signals the kernels to not mask the address - 0, - outgoing_viewer_ovpk_m, - owner_ivpk_m, - owner, - )); + otherEvent.emit( + encode_and_encrypt_event_with_randomness_unconstrained( + &mut context, + // testing only - a randomness of 0 signals the kernels to not mask the address + 0, + outgoing_viewer_ovpk_m, + owner_ivpk_m, + owner + ) + ); } } #[private] - fn emit_encrypted_logs_nested( - value: Field, - owner: AztecAddress, - outgoing_viewer: AztecAddress, - ) { + fn emit_encrypted_logs_nested(value: Field, owner: AztecAddress, outgoing_viewer: AztecAddress) { let mut storage_slot = storage.example_constant.get_storage_slot() + 1; - Test::at(context.this_address()) - .call_create_note(value, owner, outgoing_viewer, storage_slot) - .call(&mut context); + Test::at(context.this_address()).call_create_note(value, owner, outgoing_viewer, storage_slot).call(&mut context); storage_slot += 1; let msg_sender_keys = get_public_keys(context.msg_sender()); let owner_keys = get_public_keys(owner); let mut note = ValueNote::new(value + 1, owner_keys.npk_m.hash()); - create_note(&mut context, storage_slot, &mut note).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - owner_keys.ivpk_m, - owner, - )); + create_note(&mut context, storage_slot, &mut note).emit(encode_and_encrypt_note(&mut context, msg_sender_keys.ovpk_m, owner_keys.ivpk_m, owner)); storage_slot += 1; - Test::at(context.this_address()) - .call_create_note(value + 2, owner, outgoing_viewer, storage_slot) - .call(&mut context); + Test::at(context.this_address()).call_create_note(value + 2, owner, outgoing_viewer, storage_slot).call(&mut context); } // docs:start:is-time-equal @@ -365,9 +332,9 @@ contract Test { #[public] fn emit_unencrypted(value: Field) { // docs:start:emit_unencrypted - context.emit_unencrypted_log( /*message=*/ value); - context.emit_unencrypted_log( /*message=*/ [10, 20, 30]); - context.emit_unencrypted_log( /*message=*/ "Hello, world!"); + context.emit_unencrypted_log(/*message=*/ value); + context.emit_unencrypted_log(/*message=*/ [10, 20, 30]); + context.emit_unencrypted_log(/*message=*/ "Hello, world!"); // docs:end:emit_unencrypted } @@ -377,7 +344,7 @@ contract Test { amount: Field, secret: Field, message_leaf_index: Field, - portal_address: EthAddress, + portal_address: EthAddress ) { let content_hash = get_mint_public_content_hash(to, amount); // Consume message and emit nullifier @@ -389,15 +356,14 @@ contract Test { secret_hash_for_redeeming_minted_notes: Field, amount: Field, secret_for_L1_to_L2_message_consumption: Field, - portal_address: EthAddress, + portal_address: EthAddress ) { // Consume L1 to L2 message and emit nullifier - let content_hash = - get_mint_private_content_hash(secret_hash_for_redeeming_minted_notes, amount); + let content_hash = get_mint_private_content_hash(secret_hash_for_redeeming_minted_notes, amount); context.consume_l1_to_l2_message( content_hash, secret_for_L1_to_L2_message_consumption, - portal_address, + portal_address ); } @@ -406,18 +372,14 @@ contract Test { content: Field, secret: Field, sender: EthAddress, - message_leaf_index: Field, + message_leaf_index: Field ) { // Consume message and emit nullifier context.consume_l1_to_l2_message(content, secret, sender, message_leaf_index); } #[private] - fn consume_message_from_arbitrary_sender_private( - content: Field, - secret: Field, - sender: EthAddress, - ) { + fn consume_message_from_arbitrary_sender_private(content: Field, secret: Field, sender: EthAddress) { // Consume message and emit nullifier context.consume_l1_to_l2_message(content, secret, sender); } @@ -441,7 +403,7 @@ contract Test { block_number: Field, timestamp: u64, fee_per_da_gas: Field, - fee_per_l2_gas: Field, + fee_per_l2_gas: Field ) { assert(context.chain_id() == chain_id, "Invalid chain id"); assert(context.version() == version, "Invalid version"); diff --git a/noir-projects/noir-contracts/contracts/test_contract/src/test_note.nr b/noir-projects/noir-contracts/contracts/test_contract/src/test_note.nr index 66796939be9..8092554dad4 100644 --- a/noir-projects/noir-contracts/contracts/test_contract/src/test_note.nr +++ b/noir-projects/noir-contracts/contracts/test_contract/src/test_note.nr @@ -1,6 +1,6 @@ use dep::aztec::{ note::{note_header::NoteHeader, note_interface::NullifiableNote}, context::PrivateContext, - macros::notes::note, + macros::notes::note }; // A note which stores a field and is expected to be passed around using the `addNote` function. @@ -14,11 +14,7 @@ pub struct TestNote { impl NullifiableNote for TestNote { - fn compute_nullifier( - _self: Self, - _context: &mut PrivateContext, - _note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(_self: Self, _context: &mut PrivateContext, _note_hash_for_nullify: Field) -> Field { // This note is expected to be shared between users and fstructor this reason can't be nullified using a secret. 0 } diff --git a/noir-projects/noir-contracts/contracts/test_log_contract/src/main.nr b/noir-projects/noir-contracts/contracts/test_log_contract/src/main.nr index d94213d9349..4c685a0a93c 100644 --- a/noir-projects/noir-contracts/contracts/test_log_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/test_log_contract/src/main.nr @@ -42,38 +42,41 @@ contract TestLog { let other_keys = get_public_keys(other); let msg_sender_keys = get_public_keys(context.msg_sender()); - event0.emit(encode_and_encrypt_event_with_randomness( - &mut context, - randomness[0], - // outgoing is set to other, incoming is set to msg sender - other_keys.ovpk_m, - msg_sender_keys.ivpk_m, - context.msg_sender(), - )); + event0.emit( + encode_and_encrypt_event_with_randomness( + &mut context, + randomness[0], + // outgoing is set to other, incoming is set to msg sender + other_keys.ovpk_m, + msg_sender_keys.ivpk_m, + context.msg_sender() + ) + ); // We duplicate the emission, but specifying different incoming and outgoing parties - event0.emit(encode_and_encrypt_event_with_randomness( - &mut context, - randomness[0], - // outgoing is set to msg sender, incoming is set to other - msg_sender_keys.ovpk_m, - other_keys.ivpk_m, - other, - )); - - let event1 = ExampleEvent1 { - value2: AztecAddress::from_field(preimages[2]), - value3: preimages[3] as u8, - }; - - event1.emit(encode_and_encrypt_event_with_randomness( - &mut context, - randomness[1], - // outgoing is set to other, incoming is set to msg sender - other_keys.ovpk_m, - msg_sender_keys.ivpk_m, - context.msg_sender(), - )); + event0.emit( + encode_and_encrypt_event_with_randomness( + &mut context, + randomness[0], + // outgoing is set to msg sender, incoming is set to other + msg_sender_keys.ovpk_m, + other_keys.ivpk_m, + other + ) + ); + + let event1 = ExampleEvent1 { value2: AztecAddress::from_field(preimages[2]), value3: preimages[3] as u8 }; + + event1.emit( + encode_and_encrypt_event_with_randomness( + &mut context, + randomness[1], + // outgoing is set to other, incoming is set to msg sender + other_keys.ovpk_m, + msg_sender_keys.ivpk_m, + context.msg_sender() + ) + ); } #[public] @@ -82,10 +85,7 @@ contract TestLog { event0.emit(encode_event(&mut context)); - let event1 = ExampleEvent1 { - value2: AztecAddress::from_field(preimages[2]), - value3: preimages[3] as u8, - }; + let event1 = ExampleEvent1 { value2: AztecAddress::from_field(preimages[2]), value3: preimages[3] as u8 }; event1.emit(encode_event(&mut context)); } diff --git a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/main.nr b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/main.nr index b7ff9f52f94..bc6ac51c8ed 100644 --- a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/main.nr @@ -16,21 +16,15 @@ contract TokenBlacklist { use dep::aztec::{ hash::compute_secret_hash, prelude::{AztecAddress, Map, NoteGetterOptions, PrivateSet, PublicMutable, SharedMutable}, - encrypted_logs::encrypted_note_emission::{ - encode_and_encrypt_note_unconstrained, encode_and_encrypt_note, - }, utils::comparison::Comparator, + encrypted_logs::encrypted_note_emission::{encode_and_encrypt_note_unconstrained, encode_and_encrypt_note}, + utils::comparison::Comparator, macros::{storage::storage, functions::{private, public, initializer, view, internal}}, - keys::getters::get_public_keys, + keys::getters::get_public_keys }; - use dep::authwit::auth::{ - assert_current_call_valid_authwit, assert_current_call_valid_authwit_public, - }; + use dep::authwit::auth::{assert_current_call_valid_authwit, assert_current_call_valid_authwit_public}; - use crate::types::{ - transparent_note::TransparentNote, token_note::TokenNote, balances_map::BalancesMap, - roles::UserFlags, - }; + use crate::types::{transparent_note::TransparentNote, token_note::TokenNote, balances_map::BalancesMap, roles::UserFlags}; // Changing an address' roles has a certain block delay before it goes into effect. global CHANGE_ROLES_DELAY_BLOCKS: u32 = 2; @@ -190,12 +184,7 @@ contract TokenBlacklist { // Add the token note to user's balances set let msg_sender_keys = get_public_keys(context.msg_sender()); let to_keys = get_public_keys(to); - storage.balances.add(to, U128::from_integer(amount)).emit(encode_and_encrypt_note( - &mut context, - msg_sender_keys.ovpk_m, - to_keys.ivpk_m, - to, - )); + storage.balances.add(to, U128::from_integer(amount)).emit(encode_and_encrypt_note(&mut context, msg_sender_keys.ovpk_m, to_keys.ivpk_m, to)); } #[private] @@ -212,16 +201,9 @@ contract TokenBlacklist { } let from_keys = get_public_keys(from); - storage.balances.sub(from, U128::from_integer(amount)).emit(encode_and_encrypt_note( - &mut context, - from_keys.ovpk_m, - from_keys.ivpk_m, - from, - )); - - TokenBlacklist::at(context.this_address())._increase_public_balance(to, amount).enqueue( - &mut context, - ); + storage.balances.sub(from, U128::from_integer(amount)).emit(encode_and_encrypt_note(&mut context, from_keys.ovpk_m, from_keys.ivpk_m, from)); + + TokenBlacklist::at(context.this_address())._increase_public_balance(to, amount).enqueue(&mut context); } // docs:start:transfer_private @@ -242,18 +224,10 @@ contract TokenBlacklist { let to_keys = get_public_keys(to); let amount = U128::from_integer(amount); - storage.balances.sub(from, amount).emit(encode_and_encrypt_note_unconstrained( - &mut context, - from_keys.ovpk_m, - from_keys.ivpk_m, - from, - )); - storage.balances.add(to, amount).emit(encode_and_encrypt_note_unconstrained( - &mut context, - from_keys.ovpk_m, - to_keys.ivpk_m, - to, - )); + storage.balances.sub(from, amount).emit( + encode_and_encrypt_note_unconstrained(&mut context, from_keys.ovpk_m, from_keys.ivpk_m, from) + ); + storage.balances.add(to, amount).emit(encode_and_encrypt_note_unconstrained(&mut context, from_keys.ovpk_m, to_keys.ivpk_m, to)); } #[private] @@ -268,12 +242,7 @@ contract TokenBlacklist { } let from_keys = get_public_keys(from); - storage.balances.sub(from, U128::from_integer(amount)).emit(encode_and_encrypt_note( - &mut context, - from_keys.ovpk_m, - from_keys.ivpk_m, - from, - )); + storage.balances.sub(from, U128::from_integer(amount)).emit(encode_and_encrypt_note(&mut context, from_keys.ovpk_m, from_keys.ivpk_m, from)); TokenBlacklist::at(context.this_address())._reduce_total_supply(amount).enqueue(&mut context); } diff --git a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/balances_map.nr b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/balances_map.nr index b7f1ae7206a..d2e3a47b249 100644 --- a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/balances_map.nr +++ b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/balances_map.nr @@ -1,11 +1,8 @@ -use dep::aztec::prelude::{ - AztecAddress, NoteGetterOptions, NoteViewerOptions, NoteInterface, NullifiableNote, PrivateSet, - Map, -}; +use dep::aztec::prelude::{AztecAddress, NoteGetterOptions, NoteViewerOptions, NoteInterface, NullifiableNote, PrivateSet, Map}; use dep::aztec::{ context::{PrivateContext, UnconstrainedContext}, protocol_types::constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, - note::note_emission::OuterNoteEmission, keys::getters::get_public_keys, + note::note_emission::OuterNoteEmission, keys::getters::get_public_keys }; use crate::types::token_note::OwnedNote; @@ -20,8 +17,8 @@ impl BalancesMap { map: Map::new( context, storage_slot, - |context, slot| PrivateSet::new(context, slot), - ), + |context, slot| PrivateSet::new(context, slot) + ) } } } @@ -29,22 +26,20 @@ impl BalancesMap { impl BalancesMap { pub unconstrained fn balance_of( self: Self, - owner: AztecAddress, + owner: AztecAddress ) -> U128 where - T: NoteInterface + NullifiableNote + OwnedNote, - { + T: NoteInterface + NullifiableNote + OwnedNote, { self.balance_of_with_offset(owner, 0) } pub unconstrained fn balance_of_with_offset( self: Self, owner: AztecAddress, - offset: u32, + offset: u32 ) -> U128 where - T: NoteInterface + NullifiableNote + OwnedNote, - { + T: NoteInterface + NullifiableNote + OwnedNote, { let mut balance = U128::from_integer(0); // docs:start:view_notes let mut options = NoteViewerOptions::new(); @@ -68,11 +63,10 @@ impl BalancesMap { pub fn add( self: Self, owner: AztecAddress, - addend: U128, + addend: U128 ) -> OuterNoteEmission where - T: NoteInterface + NullifiableNote + OwnedNote + Eq, - { + T: NoteInterface + NullifiableNote + OwnedNote + Eq, { if addend == U128::from_integer(0) { OuterNoteEmission::new(Option::none()) } else { @@ -91,11 +85,10 @@ impl BalancesMap { pub fn sub( self: Self, owner: AztecAddress, - subtrahend: U128, + subtrahend: U128 ) -> OuterNoteEmission where - T: NoteInterface + NullifiableNote + OwnedNote + Eq, - { + T: NoteInterface + NullifiableNote + OwnedNote + Eq, { let options = NoteGetterOptions::with_filter(filter_notes_min_sum, subtrahend); let notes = self.map.at(owner).pop_notes(options); @@ -118,11 +111,10 @@ impl BalancesMap { pub fn filter_notes_min_sum( notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - min_sum: U128, + min_sum: U128 ) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] where - T: NoteInterface + OwnedNote, -{ + T: NoteInterface + OwnedNote, { let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; let mut sum = U128::from_integer(0); for i in 0..notes.len() { diff --git a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/roles.nr b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/roles.nr index e27898f0a57..565f709cb8d 100644 --- a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/roles.nr +++ b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/roles.nr @@ -64,11 +64,7 @@ impl Serialize<3> for UserFlags { // after having received the serialized value as a return-value impl Deserialize<3> for UserFlags { fn deserialize(fields: [Field; 3]) -> Self { - Self { - is_admin: fields[0] as bool, - is_minter: fields[1] as bool, - is_blacklisted: fields[2] as bool, - } + Self { is_admin: fields[0] as bool, is_minter: fields[1] as bool, is_blacklisted: fields[2] as bool } } } diff --git a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/token_note.nr b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/token_note.nr index 16b1fe92e64..6e8583407ed 100644 --- a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/token_note.nr +++ b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/token_note.nr @@ -1,9 +1,8 @@ use dep::aztec::{ prelude::{NoteHeader, NullifiableNote, PrivateContext}, - protocol_types::{ - constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator, - }, note::utils::compute_note_hash_for_nullify, oracle::random::random, - keys::getters::get_nsk_app, macros::notes::note, + protocol_types::{constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + note::utils::compute_note_hash_for_nullify, oracle::random::random, keys::getters::get_nsk_app, + macros::notes::note }; trait OwnedNote { @@ -23,15 +22,11 @@ pub struct TokenNote { impl NullifiableNote for TokenNote { // docs:start:nullifier - fn compute_nullifier( - self, - context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { let secret = context.request_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } // docs:end:nullifier @@ -41,7 +36,7 @@ impl NullifiableNote for TokenNote { let secret = get_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } } @@ -60,7 +55,9 @@ impl OwnedNote for TokenNote { // malicious sender could use non-random values to make the note less private. But they already know the full // note pre-image anyway, and so the recipient already trusts them to not disclose this information. We can // therefore assume that the sender will cooperate in the random value generation. - let randomness = unsafe { random() }; + let randomness = unsafe { + random() + }; Self { amount, npk_m_hash: owner_npk_m_hash, randomness, header: NoteHeader::empty() } } diff --git a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/transparent_note.nr b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/transparent_note.nr index 77ea426a53f..5b440c545b2 100644 --- a/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/transparent_note.nr +++ b/noir-projects/noir-contracts/contracts/token_blacklist_contract/src/types/transparent_note.nr @@ -2,9 +2,8 @@ use dep::aztec::{ note::{note_getter_options::PropertySelector, utils::compute_note_hash_for_nullify}, prelude::{NoteHeader, NullifiableNote, PrivateContext}, - protocol_types::{ - constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator, - }, macros::notes::note, + protocol_types::{constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + macros::notes::note }; use dep::std::mem::zeroed; @@ -28,15 +27,11 @@ impl NullifiableNote for TransparentNote { // 3) the "get_notes" oracle constrains that the secret hash in the returned note matches the one computed in // circuit. // This achieves that the note can only be spent by the party that knows the secret. - fn compute_nullifier( - self, - _context: &mut PrivateContext, - _note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, _context: &mut PrivateContext, _note_hash_for_nullify: Field) -> Field { let note_hash_for_nullify = compute_note_hash_for_nullify(self); poseidon2_hash_with_separator( [note_hash_for_nullify], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } diff --git a/noir-projects/noir-contracts/contracts/token_bridge_contract/src/main.nr b/noir-projects/noir-contracts/contracts/token_bridge_contract/src/main.nr index e83b07118ab..5ed03e9adfb 100644 --- a/noir-projects/noir-contracts/contracts/token_bridge_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/token_bridge_contract/src/main.nr @@ -11,15 +11,11 @@ use dep::aztec::macros::aztec; contract TokenBridge { use dep::aztec::prelude::{AztecAddress, EthAddress, PublicMutable, SharedImmutable}; - use dep::token_portal_content_hash_lib::{ - get_mint_public_content_hash, get_mint_private_content_hash, get_withdraw_content_hash, - }; + use dep::token_portal_content_hash_lib::{get_mint_public_content_hash, get_mint_private_content_hash, get_withdraw_content_hash}; use dep::token::Token; - use dep::aztec::macros::{ - storage::storage, functions::{public, initializer, private, internal, view}, - }; + use dep::aztec::macros::{storage::storage, functions::{public, initializer, private, internal, view}}; // docs:end:token_bridge_imports // docs:start:token_bridge_storage_and_constructor @@ -60,7 +56,7 @@ contract TokenBridge { content_hash, secret, storage.portal_address.read_public(), - message_leaf_index, + message_leaf_index ); // Mint tokens @@ -76,16 +72,14 @@ contract TokenBridge { recipient: EthAddress, // ethereum address to withdraw to amount: Field, caller_on_l1: EthAddress, // ethereum address that can call this function on the L1 portal (0x0 if anyone can call) - nonce: Field, // nonce used in the approval message by `msg.sender` to let bridge burn their tokens on L2 + nonce: Field // nonce used in the approval message by `msg.sender` to let bridge burn their tokens on L2 ) { // Send an L2 to L1 message let content = get_withdraw_content_hash(recipient, amount, caller_on_l1); context.message_portal(storage.portal_address.read_public(), content); // Burn tokens - Token::at(storage.token.read()).burn_public(context.msg_sender(), amount, nonce).call( - &mut context, - ); + Token::at(storage.token.read()).burn_public(context.msg_sender(), amount, nonce).call(&mut context); } // docs:end:exit_to_l1_public // docs:start:claim_private @@ -96,24 +90,21 @@ contract TokenBridge { fn claim_private( secret_hash_for_redeeming_minted_notes: Field, // secret hash used to redeem minted notes at a later time. This enables anyone to call this function and mint tokens to a user on their behalf amount: Field, - secret_for_L1_to_L2_message_consumption: Field, // secret used to consume the L1 to L2 message + secret_for_L1_to_L2_message_consumption: Field // secret used to consume the L1 to L2 message ) { // Consume L1 to L2 message and emit nullifier - let content_hash = - get_mint_private_content_hash(secret_hash_for_redeeming_minted_notes, amount); + let content_hash = get_mint_private_content_hash(secret_hash_for_redeeming_minted_notes, amount); context.consume_l1_to_l2_message( content_hash, secret_for_L1_to_L2_message_consumption, - storage.portal_address.read_private(), + storage.portal_address.read_private() ); // Mint tokens on L2 // `mint_private` on token is public. So we call an internal public function // which then calls the public method on the token contract. // Since the secret_hash is passed, no secret is leaked. - TokenBridge::at(context.this_address()) - ._call_mint_on_token(amount, secret_hash_for_redeeming_minted_notes) - .enqueue(&mut context); + TokenBridge::at(context.this_address())._call_mint_on_token(amount, secret_hash_for_redeeming_minted_notes).enqueue(&mut context); } // docs:end:claim_private @@ -126,7 +117,7 @@ contract TokenBridge { recipient: EthAddress, // ethereum address to withdraw to amount: Field, caller_on_l1: EthAddress, // ethereum address that can call this function on the L1 portal (0x0 if anyone can call) - nonce: Field, // nonce used in the approval message by `msg.sender` to let bridge burn their tokens on L2 + nonce: Field // nonce used in the approval message by `msg.sender` to let bridge burn their tokens on L2 ) { // Send an L2 to L1 message let content = get_withdraw_content_hash(recipient, amount, caller_on_l1); diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/main.nr b/noir-projects/noir-contracts/contracts/token_contract/src/main.nr index e69d0fedec6..f9662ac1751 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/main.nr @@ -21,32 +21,21 @@ contract Token { use dep::aztec::{ context::{PrivateContext, PrivateCallInterface}, hash::compute_secret_hash, oracle::random::random, - prelude::{ - NoteGetterOptions, Map, PublicMutable, SharedImmutable, PrivateSet, AztecAddress, - FunctionSelector, - }, + prelude::{NoteGetterOptions, Map, PublicMutable, SharedImmutable, PrivateSet, AztecAddress, FunctionSelector}, encrypted_logs::{ - encrypted_note_emission::{ - encode_and_encrypt_note, encode_and_encrypt_note_unconstrained, - encrypt_and_emit_partial_log, - }, encrypted_event_emission::encode_and_encrypt_event_unconstrained, - }, keys::getters::get_public_keys, - macros::{ - storage::storage, events::event, - functions::{initializer, private, view, public, internal}, - }, utils::comparison::Comparator, protocol_types::{point::Point, traits::Serialize}, + encrypted_note_emission::{encode_and_encrypt_note, encode_and_encrypt_note_unconstrained, encrypt_and_emit_partial_log}, + encrypted_event_emission::encode_and_encrypt_event_unconstrained + }, + keys::getters::get_public_keys, + macros::{storage::storage, events::event, functions::{initializer, private, view, public, internal}}, + utils::comparison::Comparator, protocol_types::{point::Point, traits::Serialize} }; // docs:start:import_authwit - use dep::authwit::auth::{ - assert_current_call_valid_authwit, assert_current_call_valid_authwit_public, - compute_authwit_nullifier, - }; + use dep::authwit::auth::{assert_current_call_valid_authwit, assert_current_call_valid_authwit_public, compute_authwit_nullifier}; // docs:end:import_authwit - use crate::types::{ - transparent_note::TransparentNote, token_note::TokenNote, balance_set::BalanceSet, - }; + use crate::types::{transparent_note::TransparentNote, token_note::TokenNote, balance_set::BalanceSet}; // docs:end::imports @@ -220,12 +209,8 @@ contract Token { fn privately_mint_private_note(amount: Field) { let caller = context.msg_sender(); let caller_keys = get_public_keys(caller); - storage.balances.at(caller).add(caller_keys.npk_m, U128::from_integer(amount)).emit( - encode_and_encrypt_note(&mut context, caller_keys.ovpk_m, caller_keys.ivpk_m, caller), - ); - Token::at(context.this_address()) - .assert_minter_and_mint(context.msg_sender(), amount) - .enqueue(&mut context); + storage.balances.at(caller).add(caller_keys.npk_m, U128::from_integer(amount)).emit(encode_and_encrypt_note(&mut context, caller_keys.ovpk_m, caller_keys.ivpk_m, caller)); + Token::at(context.this_address()).assert_minter_and_mint(context.msg_sender(), amount).enqueue(&mut context); } #[public] #[internal] @@ -302,9 +287,7 @@ contract Token { let from = context.msg_sender(); let from_keys = get_public_keys(from); let to_keys = get_public_keys(to); - storage.balances.at(to).add(to_keys.npk_m, U128::from_integer(amount)).emit( - encode_and_encrypt_note(&mut context, from_keys.ovpk_m, to_keys.ivpk_m, to), - ); + storage.balances.at(to).add(to_keys.npk_m, U128::from_integer(amount)).emit(encode_and_encrypt_note(&mut context, from_keys.ovpk_m, to_keys.ivpk_m, to)); } // docs:end:redeem_shield // docs:start:unshield @@ -317,9 +300,7 @@ contract Token { } let from_keys = get_public_keys(from); - storage.balances.at(from).sub(from_keys.npk_m, U128::from_integer(amount)).emit( - encode_and_encrypt_note(&mut context, from_keys.ovpk_m, from_keys.ivpk_m, from), - ); + storage.balances.at(from).sub(from_keys.npk_m, U128::from_integer(amount)).emit(encode_and_encrypt_note(&mut context, from_keys.ovpk_m, from_keys.ivpk_m, from)); Token::at(context.this_address())._increase_public_balance(to, amount).enqueue(&mut context); } // docs:end:unshield @@ -343,36 +324,17 @@ contract Token { storage, from, amount, - INITIAL_TRANSFER_CALL_MAX_NOTES, + INITIAL_TRANSFER_CALL_MAX_NOTES ); storage.balances.at(from).add(from_keys.npk_m, change).emit( - encode_and_encrypt_note_unconstrained( - &mut context, - from_keys.ovpk_m, - from_keys.ivpk_m, - from, - ), - ); - storage.balances.at(to).add(to_keys.npk_m, amount).emit( - encode_and_encrypt_note_unconstrained( - &mut context, - from_keys.ovpk_m, - to_keys.ivpk_m, - to, - ), + encode_and_encrypt_note_unconstrained(&mut context, from_keys.ovpk_m, from_keys.ivpk_m, from) ); + storage.balances.at(to).add(to_keys.npk_m, amount).emit(encode_and_encrypt_note_unconstrained(&mut context, from_keys.ovpk_m, to_keys.ivpk_m, to)); // We don't constrain encryption of the note log in `transfer` (unlike in `transfer_from`) because the transfer // function is only designed to be used in situations where the event is not strictly necessary (e.g. payment to // another person where the payment is considered to be successful when the other party successfully decrypts a // note). - Transfer { from, to, amount: amount.to_field() }.emit( - encode_and_encrypt_event_unconstrained( - &mut context, - from_keys.ovpk_m, - to_keys.ivpk_m, - to, - ), - ); + Transfer { from, to, amount: amount.to_field() }.emit(encode_and_encrypt_event_unconstrained(&mut context, from_keys.ovpk_m, to_keys.ivpk_m, to)); } // docs:end:transfer #[contract_library_method] @@ -381,7 +343,7 @@ contract Token { storage: Storage<&mut PrivateContext>, account: AztecAddress, amount: U128, - max_notes: u32, + max_notes: u32 ) -> U128 { let subtracted = storage.balances.at(account).try_sub(amount, max_notes); // Failing to subtract any amount means that the owner was unable to produce more notes that could be nullified. @@ -406,7 +368,7 @@ contract Token { fn compute_recurse_subtract_balance_call( context: PrivateContext, account: AztecAddress, - remaining: U128, + remaining: U128 ) -> PrivateCallInterface<25, U128> { Token::at(context.this_address())._recurse_subtract_balance(account, remaining.to_field()) } @@ -420,7 +382,7 @@ contract Token { storage, account, U128::from_integer(amount), - RECURSIVE_TRANSFER_CALL_MAX_NOTES, + RECURSIVE_TRANSFER_CALL_MAX_NOTES ) } /** @@ -451,20 +413,10 @@ contract Token { let amount = U128::from_integer(amount); // docs:start:increase_private_balance // docs:start:encrypted - storage.balances.at(from).sub(from_keys.npk_m, amount).emit(encode_and_encrypt_note( - &mut context, - from_keys.ovpk_m, - from_keys.ivpk_m, - from, - )); + storage.balances.at(from).sub(from_keys.npk_m, amount).emit(encode_and_encrypt_note(&mut context, from_keys.ovpk_m, from_keys.ivpk_m, from)); // docs:end:encrypted // docs:end:increase_private_balance - storage.balances.at(to).add(to_keys.npk_m, amount).emit(encode_and_encrypt_note( - &mut context, - from_keys.ovpk_m, - to_keys.ivpk_m, - to, - )); + storage.balances.at(to).add(to_keys.npk_m, amount).emit(encode_and_encrypt_note(&mut context, from_keys.ovpk_m, to_keys.ivpk_m, to)); } // docs:end:transfer_from // docs:start:burn @@ -476,9 +428,7 @@ contract Token { assert(nonce == 0, "invalid nonce"); } let from_keys = get_public_keys(from); - storage.balances.at(from).sub(from_keys.npk_m, U128::from_integer(amount)).emit( - encode_and_encrypt_note(&mut context, from_keys.ovpk_m, from_keys.ivpk_m, from), - ); + storage.balances.at(from).sub(from_keys.npk_m, U128::from_integer(amount)).emit(encode_and_encrypt_note(&mut context, from_keys.ovpk_m, from_keys.ivpk_m, from)); Token::at(context.this_address())._reduce_total_supply(amount).enqueue(&mut context); } // docs:end:burn @@ -506,7 +456,7 @@ contract Token { fn setup_refund( fee_payer: AztecAddress, // Address of the entity which will receive the fee note. user: AztecAddress, // A user for which we are setting up the fee refund. - funded_amount: Field, // The amount the user funded the fee payer with (represents fee limit). + funded_amount: Field // The amount the user funded the fee payer with (represents fee limit). ) { // 1. This function is called by fee paying contract (fee_payer) when setting up a refund so we need to support // the authwit flow here and check that the user really permitted fee_payer to set up a refund on their behalf. @@ -527,33 +477,32 @@ contract Token { storage, user, U128::from_integer(funded_amount), - INITIAL_TRANSFER_CALL_MAX_NOTES, + INITIAL_TRANSFER_CALL_MAX_NOTES ); storage.balances.at(user).add(user_keys.npk_m, change).emit( - encode_and_encrypt_note_unconstrained( - &mut context, - user_keys.ovpk_m, - user_keys.ivpk_m, - user, - ), + encode_and_encrypt_note_unconstrained(&mut context, user_keys.ovpk_m, user_keys.ivpk_m, user) ); // 4. Now we get the partial payloads // TODO(#7775): Manually fetching the randomness here is not great. If we decide to include randomness in all // notes we could just inject it in macros. - let fee_payer_randomness = unsafe { random() }; - let user_randomness = unsafe { random() }; + let fee_payer_randomness = unsafe { + random() + }; + let user_randomness = unsafe { + random() + }; let fee_payer_setup_payload = TokenNote::setup_payload().new( fee_payer_npk_m_hash, fee_payer_randomness, - storage.balances.at(fee_payer).set.storage_slot, + storage.balances.at(fee_payer).set.storage_slot ); let user_setup_payload = TokenNote::setup_payload().new( user_npk_m_hash, user_randomness, - storage.balances.at(user).set.storage_slot, + storage.balances.at(user).set.storage_slot ); // 5. We encrypt and emit the partial note log @@ -561,14 +510,9 @@ contract Token { &mut context, fee_payer_setup_payload.log_plaintext, fee_payer_keys, - fee_payer, - ); - encrypt_and_emit_partial_log( - &mut context, - user_setup_payload.log_plaintext, - user_keys, - user, + fee_payer ); + encrypt_and_emit_partial_log(&mut context, user_setup_payload.log_plaintext, user_keys, user); // 6. We convert the hiding points to standard `Point` type as we cannot pass `TokenNoteHidingPoint` type // as an argument to a function due to macro limitations (the `TokenNoteHidingPoint` type is macro generated @@ -581,19 +525,17 @@ contract Token { context.set_public_teardown_function( context.this_address(), comptime { - FunctionSelector::from_signature( - "complete_refund((Field,Field,bool),(Field,Field,bool),Field)", - ) - }, + FunctionSelector::from_signature("complete_refund((Field,Field,bool),(Field,Field,bool),Field)") + }, [ - fee_payer_point.x, - fee_payer_point.y, - fee_payer_point.is_infinite as Field, - user_point.x, - user_point.y, - user_point.is_infinite as Field, - funded_amount, - ], + fee_payer_point.x, + fee_payer_point.y, + fee_payer_point.is_infinite as Field, + user_point.x, + user_point.y, + user_point.is_infinite as Field, + funded_amount + ] ); } // docs:end:setup_refund @@ -617,10 +559,8 @@ contract Token { // 3. We construct the note finalization payloads with the correct amounts and hiding points to get the note // hashes and unencrypted logs. - let fee_payer_finalization_payload = - TokenNote::finalization_payload().new(fee_payer_point, tx_fee); - let user_finalization_payload = - TokenNote::finalization_payload().new(user_point, refund_amount); + let fee_payer_finalization_payload = TokenNote::finalization_payload().new(fee_payer_point, tx_fee); + let user_finalization_payload = TokenNote::finalization_payload().new(user_point, refund_amount); // 4. We emit the `tx_fee` and `refund_amount` as unencrypted event such that the `NoteProcessor` can use it // to reconstruct the note. diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/access_control.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/access_control.nr index 9cb547b237d..2999be5dfeb 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/access_control.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/access_control.nr @@ -4,8 +4,7 @@ use crate::Token; #[test] unconstrained fn access_control() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient) = - utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient) = utils::setup(/* with_account_contracts */ false); // Set a new admin Token::at(token_contract_address).set_admin(recipient).call(&mut env.public()); diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/burn.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/burn.nr index 233b842c651..4fe45f2da9f 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/burn.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/burn.nr @@ -5,8 +5,7 @@ use crate::Token; #[test] unconstrained fn burn_public_success() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); let burn_amount = mint_amount / 10; // Burn less than balance @@ -16,18 +15,12 @@ unconstrained fn burn_public_success() { #[test] unconstrained fn burn_public_on_behalf_of_other() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let burn_amount = mint_amount / 10; // Burn on behalf of other - let burn_call_interface = - Token::at(token_contract_address).burn_public(owner, burn_amount, random()); - authwit_cheatcodes::add_public_authwit_from_call_interface( - owner, - recipient, - burn_call_interface, - ); + let burn_call_interface = Token::at(token_contract_address).burn_public(owner, burn_amount, random()); + authwit_cheatcodes::add_public_authwit_from_call_interface(owner, recipient, burn_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Burn tokens @@ -37,8 +30,7 @@ unconstrained fn burn_public_on_behalf_of_other() { #[test(should_fail_with = "attempt to subtract with underflow")] unconstrained fn burn_public_failure_more_than_balance() { - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Burn more than balance let burn_amount = mint_amount * 10; @@ -48,26 +40,21 @@ unconstrained fn burn_public_failure_more_than_balance() { #[test(should_fail_with = "invalid nonce")] unconstrained fn burn_public_failure_on_behalf_of_self_non_zero_nonce() { - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Burn on behalf of self with non-zero nonce let burn_amount = mint_amount / 10; // Try to burn - Token::at(token_contract_address).burn_public(owner, burn_amount, random()).call( - &mut env.public(), - ); + Token::at(token_contract_address).burn_public(owner, burn_amount, random()).call(&mut env.public()); } #[test(should_fail_with = "unauthorized")] unconstrained fn burn_public_failure_on_behalf_of_other_without_approval() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); // Burn on behalf of other without approval let burn_amount = mint_amount / 10; - let burn_call_interface = - Token::at(token_contract_address).burn_public(owner, burn_amount, random()); + let burn_call_interface = Token::at(token_contract_address).burn_public(owner, burn_amount, random()); // Impersonate recipient to perform the call env.impersonate(recipient); burn_call_interface.call(&mut env.public()); @@ -75,13 +62,11 @@ unconstrained fn burn_public_failure_on_behalf_of_other_without_approval() { #[test(should_fail_with = "unauthorized")] unconstrained fn burn_public_failure_on_behalf_of_other_wrong_caller() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); // Burn on behalf of other, wrong designated caller let burn_amount = mint_amount / 10; - let burn_call_interface = - Token::at(token_contract_address).burn_public(owner, burn_amount, random()); + let burn_call_interface = Token::at(token_contract_address).burn_public(owner, burn_amount, random()); authwit_cheatcodes::add_public_authwit_from_call_interface(owner, owner, burn_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); @@ -90,8 +75,7 @@ unconstrained fn burn_public_failure_on_behalf_of_other_wrong_caller() { #[test] unconstrained fn burn_private_on_behalf_of_self() { - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); let burn_amount = mint_amount / 10; // Burn less than balance @@ -101,17 +85,12 @@ unconstrained fn burn_private_on_behalf_of_self() { #[test] unconstrained fn burn_private_on_behalf_of_other() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let burn_amount = mint_amount / 10; // Burn on behalf of other let burn_call_interface = Token::at(token_contract_address).burn(owner, burn_amount, random()); - authwit_cheatcodes::add_private_authwit_from_call_interface( - owner, - recipient, - burn_call_interface, - ); + authwit_cheatcodes::add_private_authwit_from_call_interface(owner, recipient, burn_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Burn tokens @@ -121,8 +100,7 @@ unconstrained fn burn_private_on_behalf_of_other() { #[test(should_fail_with = "Balance too low")] unconstrained fn burn_private_failure_more_than_balance() { - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Burn more than balance let burn_amount = mint_amount * 10; @@ -131,8 +109,7 @@ unconstrained fn burn_private_failure_more_than_balance() { #[test(should_fail_with = "invalid nonce")] unconstrained fn burn_private_failure_on_behalf_of_self_non_zero_nonce() { - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Burn more than balance let burn_amount = mint_amount / 10; @@ -141,18 +118,13 @@ unconstrained fn burn_private_failure_on_behalf_of_self_non_zero_nonce() { #[test(should_fail_with = "Balance too low")] unconstrained fn burn_private_failure_on_behalf_of_other_more_than_balance() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); // Burn more than balance let burn_amount = mint_amount * 10; // Burn on behalf of other let burn_call_interface = Token::at(token_contract_address).burn(owner, burn_amount, random()); - authwit_cheatcodes::add_private_authwit_from_call_interface( - owner, - recipient, - burn_call_interface, - ); + authwit_cheatcodes::add_private_authwit_from_call_interface(owner, recipient, burn_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); burn_call_interface.call(&mut env.private()); @@ -160,8 +132,7 @@ unconstrained fn burn_private_failure_on_behalf_of_other_more_than_balance() { #[test(should_fail_with = "Authorization not found for message hash")] unconstrained fn burn_private_failure_on_behalf_of_other_without_approval() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); // Burn more than balance let burn_amount = mint_amount / 10; @@ -174,8 +145,7 @@ unconstrained fn burn_private_failure_on_behalf_of_other_without_approval() { #[test(should_fail_with = "Authorization not found for message hash")] unconstrained fn burn_private_failure_on_behalf_of_other_wrong_designated_caller() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); // Burn more than balance let burn_amount = mint_amount / 10; diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/minting.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/minting.nr index d4ee834bdb4..99599c54990 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/minting.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/minting.nr @@ -5,7 +5,7 @@ use crate::{types::transparent_note::TransparentNote, Token}; #[test] unconstrained fn mint_public_success() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _) = utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _) = utils::setup(/* with_account_contracts */ false); let mint_amount = 10000; Token::at(token_contract_address).mint_public(owner, mint_amount).call(&mut env.public()); @@ -19,14 +19,12 @@ unconstrained fn mint_public_success() { #[test] unconstrained fn mint_public_failures() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient) = - utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient) = utils::setup(/* with_account_contracts */ false); // As non-minter let mint_amount = 10000; env.impersonate(recipient); - let mint_public_call_interface = - Token::at(token_contract_address).mint_public(owner, mint_amount); + let mint_public_call_interface = Token::at(token_contract_address).mint_public(owner, mint_amount); env.assert_public_call_fails(mint_public_call_interface); utils::check_public_balance(token_contract_address, owner, 0); @@ -35,8 +33,7 @@ unconstrained fn mint_public_failures() { // Overflow recipient let mint_amount = 2.pow_32(128); - let mint_public_call_interface = - Token::at(token_contract_address).mint_public(owner, mint_amount); + let mint_public_call_interface = Token::at(token_contract_address).mint_public(owner, mint_amount); env.assert_public_call_fails(mint_public_call_interface); utils::check_public_balance(token_contract_address, owner, 0); @@ -44,13 +41,10 @@ unconstrained fn mint_public_failures() { // Overflow total supply let mint_for_recipient_amount = 1000; - Token::at(token_contract_address).mint_public(recipient, mint_for_recipient_amount).call( - &mut env.public(), - ); + Token::at(token_contract_address).mint_public(recipient, mint_for_recipient_amount).call(&mut env.public()); let mint_amount = 2.pow_32(128) - mint_for_recipient_amount; - let mint_public_call_interface = - Token::at(token_contract_address).mint_public(owner, mint_amount); + let mint_public_call_interface = Token::at(token_contract_address).mint_public(owner, mint_amount); env.assert_public_call_fails(mint_public_call_interface); utils::check_public_balance(token_contract_address, recipient, mint_for_recipient_amount); @@ -60,7 +54,7 @@ unconstrained fn mint_public_failures() { #[test] unconstrained fn mint_private_success() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _) = utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _) = utils::setup(/* with_account_contracts */ false); let mint_amount = 10000; // Mint some tokens let secret = random(); @@ -76,13 +70,11 @@ unconstrained fn mint_private_success() { env.add_note( &mut TransparentNote::new(mint_amount, secret_hash), Token::storage_layout().pending_shields.slot, - token_contract_address, + token_contract_address ); // Redeem our shielded tokens - Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret).call( - &mut env.private(), - ); + Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret).call(&mut env.private()); utils::check_private_balance(token_contract_address, owner, mint_amount); } @@ -90,8 +82,7 @@ unconstrained fn mint_private_success() { #[test(should_fail_with = "note not popped")] unconstrained fn mint_private_failure_double_spend() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient) = - utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient) = utils::setup(/* with_account_contracts */ false); let mint_amount = 10000; // Mint some tokens let secret = random(); @@ -107,27 +98,22 @@ unconstrained fn mint_private_failure_double_spend() { env.add_note( &mut TransparentNote::new(mint_amount, secret_hash), Token::storage_layout().pending_shields.slot, - token_contract_address, + token_contract_address ); // Redeem our shielded tokens - Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret).call( - &mut env.private(), - ); + Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret).call(&mut env.private()); utils::check_private_balance(token_contract_address, owner, mint_amount); // Attempt to double spend - Token::at(token_contract_address).redeem_shield(recipient, mint_amount, secret).call( - &mut env.private(), - ); + Token::at(token_contract_address).redeem_shield(recipient, mint_amount, secret).call(&mut env.private()); } #[test(should_fail_with = "caller is not minter")] unconstrained fn mint_private_failure_non_minter() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, _, recipient) = - utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, _, recipient) = utils::setup(/* with_account_contracts */ false); let mint_amount = 10000; // Try to mint some tokens impersonating recipient env.impersonate(recipient); @@ -140,7 +126,7 @@ unconstrained fn mint_private_failure_non_minter() { #[test(should_fail_with = "call to assert_max_bit_size")] unconstrained fn mint_private_failure_overflow() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, _, _) = utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, _, _) = utils::setup(/* with_account_contracts */ false); // Overflow recipient let mint_amount = 2.pow_32(128); @@ -152,7 +138,7 @@ unconstrained fn mint_private_failure_overflow() { #[test(should_fail_with = "attempt to add with overflow")] unconstrained fn mint_private_failure_overflow_recipient() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _) = utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _) = utils::setup(/* with_account_contracts */ false); let mint_amount = 10000; // Mint some tokens let secret = random(); @@ -165,13 +151,11 @@ unconstrained fn mint_private_failure_overflow_recipient() { env.add_note( &mut TransparentNote::new(mint_amount, secret_hash), Token::storage_layout().pending_shields.slot, - token_contract_address, + token_contract_address ); // Redeem our shielded tokens - Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret).call( - &mut env.private(), - ); + Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret).call(&mut env.private()); utils::check_private_balance(token_contract_address, owner, mint_amount); @@ -185,8 +169,7 @@ unconstrained fn mint_private_failure_overflow_recipient() { #[test(should_fail_with = "attempt to add with overflow")] unconstrained fn mint_private_failure_overflow_total_supply() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient) = - utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient) = utils::setup(/* with_account_contracts */ false); let mint_amount = 10000; // Mint some tokens let secret_owner = random(); @@ -194,12 +177,8 @@ unconstrained fn mint_private_failure_overflow_total_supply() { let secret_hash_owner = compute_secret_hash(secret_owner); let secret_hash_recipient = compute_secret_hash(secret_recipient); - Token::at(token_contract_address).mint_private(mint_amount, secret_hash_owner).call( - &mut env.public(), - ); - Token::at(token_contract_address).mint_private(mint_amount, secret_hash_recipient).call( - &mut env.public(), - ); + Token::at(token_contract_address).mint_private(mint_amount, secret_hash_owner).call(&mut env.public()); + Token::at(token_contract_address).mint_private(mint_amount, secret_hash_recipient).call(&mut env.public()); // Time travel so we can read keys from the registry env.advance_block_by(6); @@ -208,25 +187,21 @@ unconstrained fn mint_private_failure_overflow_total_supply() { env.add_note( &mut TransparentNote::new(mint_amount, secret_hash_owner), Token::storage_layout().pending_shields.slot, - token_contract_address, + token_contract_address ); env.add_note( &mut TransparentNote::new(mint_amount, secret_hash_recipient), Token::storage_layout().pending_shields.slot, - token_contract_address, + token_contract_address ); // Redeem owner's shielded tokens env.impersonate(owner); - Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret_owner).call( - &mut env.private(), - ); + Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret_owner).call(&mut env.private()); // Redeem recipient's shielded tokens env.impersonate(recipient); - Token::at(token_contract_address).redeem_shield(recipient, mint_amount, secret_recipient).call( - &mut env.private(), - ); + Token::at(token_contract_address).redeem_shield(recipient, mint_amount, secret_recipient).call(&mut env.private()); utils::check_private_balance(token_contract_address, owner, mint_amount); utils::check_private_balance(token_contract_address, recipient, mint_amount); diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/reading_constants.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/reading_constants.nr index c96bd9613be..822d3158242 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/reading_constants.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/reading_constants.nr @@ -7,7 +7,7 @@ use crate::Token; #[test] unconstrained fn check_decimals_private() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, _, _) = utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, _, _) = utils::setup(/* with_account_contracts */ false); // Check decimals let result = Token::at(token_contract_address).private_get_decimals().view(&mut env.private()); @@ -18,7 +18,7 @@ unconstrained fn check_decimals_private() { #[test] unconstrained fn check_decimals_public() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, _, _) = utils::setup( /* with_account_contracts */ false); + let (env, token_contract_address, _, _) = utils::setup(/* with_account_contracts */ false); // Check decimals let result = Token::at(token_contract_address).public_get_decimals().view(&mut env.public()); diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/refunds.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/refunds.nr index a8f48973acb..8a599d834a4 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/refunds.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/refunds.nr @@ -2,7 +2,7 @@ use crate::{test::utils, Token, types::token_note::TokenNote}; use dep::aztec::{ prelude::NoteHeader, protocol_types::storage::map::derive_storage_slot_in_map, - keys::getters::get_public_keys, + keys::getters::get_public_keys }; use dep::authwit::cheatcodes as authwit_cheatcodes; use std::test::OracleMock; @@ -23,14 +23,9 @@ unconstrained fn setup_refund_success() { let _ = OracleMock::mock("getRandomField").returns(fee_payer_randomness); - let setup_refund_from_call_interface = - Token::at(token_contract_address).setup_refund(fee_payer, user, funded_amount); + let setup_refund_from_call_interface = Token::at(token_contract_address).setup_refund(fee_payer, user, funded_amount); - authwit_cheatcodes::add_private_authwit_from_call_interface( - user, - fee_payer, - setup_refund_from_call_interface, - ); + authwit_cheatcodes::add_private_authwit_from_call_interface(user, fee_payer, setup_refund_from_call_interface); env.impersonate(fee_payer); @@ -38,10 +33,8 @@ unconstrained fn setup_refund_success() { let user_npk_m_hash = get_public_keys(user).npk_m.hash(); let fee_payer_npk_m_hash = get_public_keys(fee_payer).npk_m.hash(); - let fee_payer_balances_slot = - derive_storage_slot_in_map(Token::storage_layout().balances.slot, fee_payer); - let user_balances_slot = - derive_storage_slot_in_map(Token::storage_layout().balances.slot, user); + let fee_payer_balances_slot = derive_storage_slot_in_map(Token::storage_layout().balances.slot, fee_payer); + let user_balances_slot = derive_storage_slot_in_map(Token::storage_layout().balances.slot, user); // When the refund was set up, we would've spent the note worth mint_amount, and inserted a note worth //`mint_amount - funded_amount`. When completing the refund, we would've constructed a hash corresponding to a note @@ -49,23 +42,23 @@ unconstrained fn setup_refund_success() { // `executePublicFunction` TXE oracle) but we need to notify TXE of the note (preimage). env.add_note( &mut TokenNote { - amount: U128::from_integer(funded_amount - 1), - npk_m_hash: user_npk_m_hash, - randomness: user_randomness, - header: NoteHeader::empty(), - }, + amount: U128::from_integer(funded_amount - 1), + npk_m_hash: user_npk_m_hash, + randomness: user_randomness, + header: NoteHeader::empty() + }, user_balances_slot, - token_contract_address, + token_contract_address ); env.add_note( &mut TokenNote { - amount: U128::from_integer(1), - npk_m_hash: fee_payer_npk_m_hash, - randomness: fee_payer_randomness, - header: NoteHeader::empty(), - }, + amount: U128::from_integer(1), + npk_m_hash: fee_payer_npk_m_hash, + randomness: fee_payer_randomness, + header: NoteHeader::empty() + }, fee_payer_balances_slot, - token_contract_address, + token_contract_address ); utils::check_private_balance(token_contract_address, user, mint_amount - 1); @@ -86,14 +79,9 @@ unconstrained fn setup_refund_insufficient_funded_amount() { // We set funded amount to 0 to make the transaction fee higher than the funded amount let funded_amount = 0; - let setup_refund_from_call_interface = - Token::at(token_contract_address).setup_refund(fee_payer, user, funded_amount); + let setup_refund_from_call_interface = Token::at(token_contract_address).setup_refund(fee_payer, user, funded_amount); - authwit_cheatcodes::add_private_authwit_from_call_interface( - user, - fee_payer, - setup_refund_from_call_interface, - ); + authwit_cheatcodes::add_private_authwit_from_call_interface(user, fee_payer, setup_refund_from_call_interface); env.impersonate(fee_payer); diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/shielding.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/shielding.nr index 5abf58a7328..51b06e83ed1 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/shielding.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/shielding.nr @@ -6,27 +6,22 @@ use crate::{types::transparent_note::TransparentNote, Token}; #[test] unconstrained fn shielding_on_behalf_of_self() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); let secret = random(); let secret_hash = compute_secret_hash(secret); // Shield tokens let shield_amount = mint_amount / 10; - Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0).call( - &mut env.public(), - ); + Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0).call(&mut env.public()); // We need to manually add the note to TXE because `TransparentNote` does not support automatic note log delivery. env.add_note( &mut TransparentNote::new(shield_amount, secret_hash), Token::storage_layout().pending_shields.slot, - token_contract_address, + token_contract_address ); // Redeem our shielded tokens - Token::at(token_contract_address).redeem_shield(owner, shield_amount, secret).call( - &mut env.private(), - ); + Token::at(token_contract_address).redeem_shield(owner, shield_amount, secret).call(&mut env.private()); // Check balances utils::check_public_balance(token_contract_address, owner, mint_amount - shield_amount); @@ -35,20 +30,14 @@ unconstrained fn shielding_on_behalf_of_self() { #[test] unconstrained fn shielding_on_behalf_of_other() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let secret = random(); let secret_hash = compute_secret_hash(secret); // Shield tokens on behalf of owner let shield_amount = 1000; - let shield_call_interface = - Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); - authwit_cheatcodes::add_public_authwit_from_call_interface( - owner, - recipient, - shield_call_interface, - ); + let shield_call_interface = Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); + authwit_cheatcodes::add_public_authwit_from_call_interface(owner, recipient, shield_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Shield tokens @@ -60,13 +49,11 @@ unconstrained fn shielding_on_behalf_of_other() { env.add_note( &mut TransparentNote::new(shield_amount, secret_hash), Token::storage_layout().pending_shields.slot, - token_contract_address, + token_contract_address ); // Redeem our shielded tokens - Token::at(token_contract_address).redeem_shield(owner, shield_amount, secret).call( - &mut env.private(), - ); + Token::at(token_contract_address).redeem_shield(owner, shield_amount, secret).call(&mut env.private()); // Check balances utils::check_public_balance(token_contract_address, owner, mint_amount - shield_amount); @@ -76,14 +63,12 @@ unconstrained fn shielding_on_behalf_of_other() { #[test] unconstrained fn shielding_failure_on_behalf_of_self_more_than_balance() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let secret = random(); let secret_hash = compute_secret_hash(secret); // Shield tokens let shield_amount = mint_amount + 1; - let shield_call_interface = - Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); + let shield_call_interface = Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); env.assert_public_call_fails(shield_call_interface); // Check balances @@ -94,14 +79,12 @@ unconstrained fn shielding_failure_on_behalf_of_self_more_than_balance() { #[test] unconstrained fn shielding_failure_on_behalf_of_self_invalid_nonce() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let secret = random(); let secret_hash = compute_secret_hash(secret); // Shield tokens let shield_amount = mint_amount / 10; - let shield_call_interface = - Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, random()); + let shield_call_interface = Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, random()); env.assert_public_call_fails(shield_call_interface); // Check balances @@ -112,19 +95,13 @@ unconstrained fn shielding_failure_on_behalf_of_self_invalid_nonce() { #[test] unconstrained fn shielding_failure_on_behalf_of_other_more_than_balance() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let secret = random(); let secret_hash = compute_secret_hash(secret); // Shield tokens on behalf of owner let shield_amount = mint_amount + 1; - let shield_call_interface = - Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); - authwit_cheatcodes::add_public_authwit_from_call_interface( - owner, - recipient, - shield_call_interface, - ); + let shield_call_interface = Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); + authwit_cheatcodes::add_public_authwit_from_call_interface(owner, recipient, shield_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Shield tokens @@ -138,14 +115,12 @@ unconstrained fn shielding_failure_on_behalf_of_other_more_than_balance() { #[test] unconstrained fn shielding_failure_on_behalf_of_other_wrong_caller() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let secret = random(); let secret_hash = compute_secret_hash(secret); // Shield tokens on behalf of owner let shield_amount = mint_amount + 1; - let shield_call_interface = - Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); + let shield_call_interface = Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); authwit_cheatcodes::add_public_authwit_from_call_interface(owner, owner, shield_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); @@ -160,14 +135,12 @@ unconstrained fn shielding_failure_on_behalf_of_other_wrong_caller() { #[test] unconstrained fn shielding_failure_on_behalf_of_other_without_approval() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let secret = random(); let secret_hash = compute_secret_hash(secret); // Shield tokens on behalf of owner let shield_amount = mint_amount + 1; - let shield_call_interface = - Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); + let shield_call_interface = Token::at(token_contract_address).shield(owner, shield_amount, secret_hash, 0); // Impersonate recipient to perform the call env.impersonate(recipient); // Shield tokens diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_private.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_private.nr index feaa922200a..9c683453e1a 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_private.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_private.nr @@ -6,8 +6,7 @@ use crate::Token; #[test] unconstrained fn transfer_private() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // docs:start:txe_test_transfer_private // Transfer tokens @@ -22,8 +21,7 @@ unconstrained fn transfer_private() { #[test] unconstrained fn transfer_private_to_self() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Transfer tokens let transfer_amount = 1000; Token::at(token_contract_address).transfer(owner, transfer_amount).call(&mut env.private()); @@ -35,39 +33,26 @@ unconstrained fn transfer_private_to_self() { #[test] unconstrained fn transfer_private_to_non_deployed_account() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); let not_deployed = cheatcodes::create_account(); // Transfer tokens let transfer_amount = 1000; - Token::at(token_contract_address).transfer(not_deployed.address, transfer_amount).call( - &mut env.private(), - ); + Token::at(token_contract_address).transfer(not_deployed.address, transfer_amount).call(&mut env.private()); // Check balances utils::check_private_balance(token_contract_address, owner, mint_amount - transfer_amount); - utils::check_private_balance( - token_contract_address, - not_deployed.address, - transfer_amount, - ); + utils::check_private_balance(token_contract_address, not_deployed.address, transfer_amount); } #[test] unconstrained fn transfer_private_on_behalf_of_other() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); // Add authwit // docs:start:private_authwit let transfer_amount = 1000; - let transfer_private_from_call_interface = - Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); - authwit_cheatcodes::add_private_authwit_from_call_interface( - owner, - recipient, - transfer_private_from_call_interface, - ); + let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); + authwit_cheatcodes::add_private_authwit_from_call_interface(owner, recipient, transfer_private_from_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Transfer tokens @@ -81,8 +66,7 @@ unconstrained fn transfer_private_on_behalf_of_other() { #[test(should_fail_with = "Balance too low")] unconstrained fn transfer_private_failure_more_than_balance() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, _, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, _, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Transfer tokens let transfer_amount = mint_amount + 1; Token::at(token_contract_address).transfer(recipient, transfer_amount).call(&mut env.private()); @@ -92,17 +76,11 @@ unconstrained fn transfer_private_failure_more_than_balance() { #[test(should_fail_with = "invalid nonce")] unconstrained fn transfer_private_failure_on_behalf_of_self_non_zero_nonce() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient, _) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient, _) = utils::setup_and_mint(/* with_account_contracts */ false); // Add authwit let transfer_amount = 1000; - let transfer_private_from_call_interface = - Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); - authwit_cheatcodes::add_private_authwit_from_call_interface( - owner, - recipient, - transfer_private_from_call_interface, - ); + let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); + authwit_cheatcodes::add_private_authwit_from_call_interface(owner, recipient, transfer_private_from_call_interface); // Transfer tokens transfer_private_from_call_interface.call(&mut env.private()); } @@ -111,17 +89,11 @@ unconstrained fn transfer_private_failure_on_behalf_of_self_non_zero_nonce() { #[test(should_fail_with = "Balance too low")] unconstrained fn transfer_private_failure_on_behalf_of_more_than_balance() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); // Add authwit let transfer_amount = mint_amount + 1; - let transfer_private_from_call_interface = - Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); - authwit_cheatcodes::add_private_authwit_from_call_interface( - owner, - recipient, - transfer_private_from_call_interface, - ); + let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); + authwit_cheatcodes::add_private_authwit_from_call_interface(owner, recipient, transfer_private_from_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Transfer tokens @@ -131,12 +103,10 @@ unconstrained fn transfer_private_failure_on_behalf_of_more_than_balance() { #[test(should_fail_with = "Authorization not found for message hash")] unconstrained fn transfer_private_failure_on_behalf_of_other_without_approval() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, token_contract_address, owner, recipient, _) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, _) = utils::setup_and_mint(/* with_account_contracts */ true); // Add authwit let transfer_amount = 1000; - let transfer_private_from_call_interface = - Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); + let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); // Impersonate recipient to perform the call env.impersonate(recipient); // Transfer tokens @@ -146,17 +116,11 @@ unconstrained fn transfer_private_failure_on_behalf_of_other_without_approval() #[test(should_fail_with = "Authorization not found for message hash")] unconstrained fn transfer_private_failure_on_behalf_of_other_wrong_caller() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, token_contract_address, owner, recipient, _) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, _) = utils::setup_and_mint(/* with_account_contracts */ true); // Add authwit let transfer_amount = 1000; - let transfer_private_from_call_interface = - Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); - authwit_cheatcodes::add_private_authwit_from_call_interface( - owner, - owner, - transfer_private_from_call_interface, - ); + let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_from(owner, recipient, transfer_amount, 1); + authwit_cheatcodes::add_private_authwit_from_call_interface(owner, owner, transfer_private_from_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Transfer tokens diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_public.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_public.nr index 600f1e92ed4..a47194a2617 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_public.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/transfer_public.nr @@ -6,13 +6,10 @@ use crate::Token; #[test] unconstrained fn public_transfer() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Transfer tokens let transfer_amount = mint_amount / 10; - Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 0).call( - &mut env.public(), - ); + Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 0).call(&mut env.public()); // Check balances utils::check_public_balance(token_contract_address, owner, mint_amount - transfer_amount); @@ -22,14 +19,11 @@ unconstrained fn public_transfer() { #[test] unconstrained fn public_transfer_to_self() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Transfer tokens let transfer_amount = mint_amount / 10; // docs:start:call_public - Token::at(token_contract_address).transfer_public(owner, owner, transfer_amount, 0).call( - &mut env.public(), - ); + Token::at(token_contract_address).transfer_public(owner, owner, transfer_amount, 0).call(&mut env.public()); // docs:end:call_public // Check balances utils::check_public_balance(token_contract_address, owner, mint_amount); @@ -38,16 +32,10 @@ unconstrained fn public_transfer_to_self() { #[test] unconstrained fn public_transfer_on_behalf_of_other() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let transfer_amount = mint_amount / 10; - let public_transfer_from_call_interface = - Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 1); - authwit_cheatcodes::add_public_authwit_from_call_interface( - owner, - recipient, - public_transfer_from_call_interface, - ); + let public_transfer_from_call_interface = Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 1); + authwit_cheatcodes::add_public_authwit_from_call_interface(owner, recipient, public_transfer_from_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Transfer tokens @@ -60,12 +48,10 @@ unconstrained fn public_transfer_on_behalf_of_other() { #[test(should_fail_with = "attempt to subtract with underflow")] unconstrained fn public_transfer_failure_more_than_balance() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Transfer tokens let transfer_amount = mint_amount + 1; - let public_transfer_call_interface = - Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 0); + let public_transfer_call_interface = Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 0); // Try to transfer tokens public_transfer_call_interface.call(&mut env.public()); } @@ -73,21 +59,11 @@ unconstrained fn public_transfer_failure_more_than_balance() { #[test(should_fail_with = "invalid nonce")] unconstrained fn public_transfer_failure_on_behalf_of_self_non_zero_nonce() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); // Transfer tokens let transfer_amount = mint_amount / 10; - let public_transfer_call_interface = Token::at(token_contract_address).transfer_public( - owner, - recipient, - transfer_amount, - random(), - ); - authwit_cheatcodes::add_public_authwit_from_call_interface( - owner, - recipient, - public_transfer_call_interface, - ); + let public_transfer_call_interface = Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, random()); + authwit_cheatcodes::add_public_authwit_from_call_interface(owner, recipient, public_transfer_call_interface); // Try to transfer tokens public_transfer_call_interface.call(&mut env.public()); } @@ -95,11 +71,9 @@ unconstrained fn public_transfer_failure_on_behalf_of_self_non_zero_nonce() { #[test(should_fail_with = "unauthorized")] unconstrained fn public_transfer_failure_on_behalf_of_other_without_approval() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let transfer_amount = mint_amount / 10; - let public_transfer_from_call_interface = - Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 1); + let public_transfer_from_call_interface = Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 1); // Impersonate recipient to perform the call env.impersonate(recipient); // Try to transfer tokens @@ -109,17 +83,11 @@ unconstrained fn public_transfer_failure_on_behalf_of_other_without_approval() { #[test(should_fail_with = "attempt to subtract with underflow")] unconstrained fn public_transfer_failure_on_behalf_of_other_more_than_balance() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let transfer_amount = mint_amount + 1; // docs:start:public_authwit - let public_transfer_from_call_interface = - Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 1); - authwit_cheatcodes::add_public_authwit_from_call_interface( - owner, - recipient, - public_transfer_from_call_interface, - ); + let public_transfer_from_call_interface = Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 1); + authwit_cheatcodes::add_public_authwit_from_call_interface(owner, recipient, public_transfer_from_call_interface); // docs:end:public_authwit // Impersonate recipient to perform the call env.impersonate(recipient); @@ -130,16 +98,10 @@ unconstrained fn public_transfer_failure_on_behalf_of_other_more_than_balance() #[test(should_fail_with = "unauthorized")] unconstrained fn public_transfer_failure_on_behalf_of_other_wrong_caller() { // Setup with account contracts. Slower since we actually deploy them, but needed for authwits. - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let transfer_amount = mint_amount / 10; - let public_transfer_from_call_interface = - Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 1); - authwit_cheatcodes::add_public_authwit_from_call_interface( - owner, - owner, - public_transfer_from_call_interface, - ); + let public_transfer_from_call_interface = Token::at(token_contract_address).transfer_public(owner, recipient, transfer_amount, 1); + authwit_cheatcodes::add_public_authwit_from_call_interface(owner, owner, public_transfer_from_call_interface); // Impersonate recipient to perform the call env.impersonate(recipient); // Try to transfer tokens diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/unshielding.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/unshielding.nr index 8e4063561a7..7ec866a3a32 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/unshielding.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/unshielding.nr @@ -6,30 +6,21 @@ use crate::Token; #[test] unconstrained fn unshield_on_behalf_of_self() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); let unshield_amount = mint_amount / 10; - Token::at(token_contract_address).unshield(owner, owner, unshield_amount, 0).call( - &mut env.private(), - ); + Token::at(token_contract_address).unshield(owner, owner, unshield_amount, 0).call(&mut env.private()); utils::check_private_balance(token_contract_address, owner, mint_amount - unshield_amount); utils::check_public_balance(token_contract_address, owner, mint_amount + unshield_amount); } #[test] unconstrained fn unshield_on_behalf_of_other() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let unshield_amount = mint_amount / 10; - let unshield_call_interface = - Token::at(token_contract_address).unshield(owner, recipient, unshield_amount, 0); - authwit_cheatcodes::add_private_authwit_from_call_interface( - owner, - recipient, - unshield_call_interface, - ); + let unshield_call_interface = Token::at(token_contract_address).unshield(owner, recipient, unshield_amount, 0); + authwit_cheatcodes::add_private_authwit_from_call_interface(owner, recipient, unshield_call_interface); // Impersonate recipient env.impersonate(recipient); // Unshield tokens @@ -41,40 +32,28 @@ unconstrained fn unshield_on_behalf_of_other() { #[test(should_fail_with = "Balance too low")] unconstrained fn unshield_failure_more_than_balance() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); let unshield_amount = mint_amount + 1; - Token::at(token_contract_address).unshield(owner, owner, unshield_amount, 0).call( - &mut env.private(), - ); + Token::at(token_contract_address).unshield(owner, owner, unshield_amount, 0).call(&mut env.private()); } #[test(should_fail_with = "invalid nonce")] unconstrained fn unshield_failure_on_behalf_of_self_non_zero_nonce() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough - let (env, token_contract_address, owner, _, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ false); + let (env, token_contract_address, owner, _, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ false); let unshield_amount = mint_amount + 1; - Token::at(token_contract_address).unshield(owner, owner, unshield_amount, random()).call( - &mut env.private(), - ); + Token::at(token_contract_address).unshield(owner, owner, unshield_amount, random()).call(&mut env.private()); } #[test(should_fail_with = "Balance too low")] unconstrained fn unshield_failure_on_behalf_of_other_more_than_balance() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let unshield_amount = mint_amount + 1; - let unshield_call_interface = - Token::at(token_contract_address).unshield(owner, recipient, unshield_amount, 0); - authwit_cheatcodes::add_private_authwit_from_call_interface( - owner, - recipient, - unshield_call_interface, - ); + let unshield_call_interface = Token::at(token_contract_address).unshield(owner, recipient, unshield_amount, 0); + authwit_cheatcodes::add_private_authwit_from_call_interface(owner, recipient, unshield_call_interface); // Impersonate recipient env.impersonate(recipient); // Unshield tokens @@ -83,17 +62,11 @@ unconstrained fn unshield_failure_on_behalf_of_other_more_than_balance() { #[test(should_fail_with = "Authorization not found for message hash")] unconstrained fn unshield_failure_on_behalf_of_other_invalid_designated_caller() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let unshield_amount = mint_amount + 1; - let unshield_call_interface = - Token::at(token_contract_address).unshield(owner, recipient, unshield_amount, 0); - authwit_cheatcodes::add_private_authwit_from_call_interface( - owner, - owner, - unshield_call_interface, - ); + let unshield_call_interface = Token::at(token_contract_address).unshield(owner, recipient, unshield_amount, 0); + authwit_cheatcodes::add_private_authwit_from_call_interface(owner, owner, unshield_call_interface); // Impersonate recipient env.impersonate(recipient); // Unshield tokens @@ -102,12 +75,10 @@ unconstrained fn unshield_failure_on_behalf_of_other_invalid_designated_caller() #[test(should_fail_with = "Authorization not found for message hash")] unconstrained fn unshield_failure_on_behalf_of_other_no_approval() { - let (env, token_contract_address, owner, recipient, mint_amount) = - utils::setup_and_mint( /* with_account_contracts */ true); + let (env, token_contract_address, owner, recipient, mint_amount) = utils::setup_and_mint(/* with_account_contracts */ true); let unshield_amount = mint_amount + 1; - let unshield_call_interface = - Token::at(token_contract_address).unshield(owner, recipient, unshield_amount, 0); + let unshield_call_interface = Token::at(token_contract_address).unshield(owner, recipient, unshield_amount, 0); // Impersonate recipient env.impersonate(recipient); // Unshield tokens diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/test/utils.nr b/noir-projects/noir-contracts/contracts/token_contract/src/test/utils.nr index 082cb882370..0faf640191f 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/test/utils.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/test/utils.nr @@ -2,16 +2,12 @@ use dep::aztec::{ hash::compute_secret_hash, prelude::AztecAddress, test::helpers::{cheatcodes, test_environment::TestEnvironment}, protocol_types::storage::map::derive_storage_slot_in_map, - oracle::{ - execution::{get_block_number, get_contract_address}, random::random, storage::storage_read, - }, + oracle::{execution::{get_block_number, get_contract_address}, random::random, storage::storage_read} }; use crate::{types::transparent_note::TransparentNote, Token}; -pub unconstrained fn setup( - with_account_contracts: bool, -) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress) { +pub unconstrained fn setup(with_account_contracts: bool) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress) { // Setup env, generate keys let mut env = TestEnvironment::new(); let (owner, recipient) = if with_account_contracts { @@ -32,18 +28,15 @@ pub unconstrained fn setup( owner, "TestToken0000000000000000000000", "TT00000000000000000000000000000", - 18, + 18 ); - let token_contract = - env.deploy_self("Token").with_public_void_initializer(initializer_call_interface); + let token_contract = env.deploy_self("Token").with_public_void_initializer(initializer_call_interface); let token_contract_address = token_contract.to_address(); env.advance_block_by(1); (&mut env, token_contract_address, owner, recipient) } -pub unconstrained fn setup_and_mint( - with_account_contracts: bool, -) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress, Field) { +pub unconstrained fn setup_and_mint(with_account_contracts: bool) -> (&mut TestEnvironment, AztecAddress, AztecAddress, AztecAddress, Field) { // Setup let (env, token_contract_address, owner, recipient) = setup(with_account_contracts); let mint_amount = 10000; @@ -61,13 +54,11 @@ pub unconstrained fn setup_and_mint( env.add_note( &mut TransparentNote::new(mint_amount, secret_hash), Token::storage_layout().pending_shields.slot, - token_contract_address, + token_contract_address ); // docs:end:txe_test_add_note // Redeem our shielded tokens - Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret).call( - &mut env.private(), - ); + Token::at(token_contract_address).redeem_shield(owner, mint_amount, secret).call(&mut env.private()); (env, token_contract_address, owner, recipient, mint_amount) } @@ -76,7 +67,7 @@ pub unconstrained fn setup_and_mint( pub unconstrained fn check_public_balance( token_contract_address: AztecAddress, address: AztecAddress, - address_amount: Field, + address_amount: Field ) { let current_contract_address = get_contract_address(); cheatcodes::set_contract_address(token_contract_address); @@ -94,7 +85,7 @@ pub unconstrained fn check_public_balance( pub unconstrained fn check_private_balance( token_contract_address: AztecAddress, address: AztecAddress, - address_amount: Field, + address_amount: Field ) { let current_contract_address = get_contract_address(); cheatcodes::set_contract_address(token_contract_address); diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/types/balance_set.nr b/noir-projects/noir-contracts/contracts/token_contract/src/types/balance_set.nr index 2bb1a34b5cb..c0626036296 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/types/balance_set.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/types/balance_set.nr @@ -2,9 +2,8 @@ use dep::aztec::prelude::{NoteGetterOptions, NoteViewerOptions, NoteInterface, P use dep::aztec::{ context::{PrivateContext, UnconstrainedContext}, protocol_types::{constants::MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, public_keys::NpkM}, - note::{ - note_interface::NullifiableNote, note_getter::view_notes, note_emission::OuterNoteEmission, - }, keys::getters::get_public_keys, + note::{note_interface::NullifiableNote, note_getter::view_notes, note_emission::OuterNoteEmission}, + keys::getters::get_public_keys }; use crate::types::token_note::OwnedNote; @@ -22,18 +21,16 @@ impl BalanceSet { impl BalanceSet { pub unconstrained fn balance_of(self: Self) -> U128 where - T: NoteInterface + NullifiableNote + OwnedNote, - { + T: NoteInterface + NullifiableNote + OwnedNote, { self.balance_of_with_offset(0) } pub unconstrained fn balance_of_with_offset( self: Self, - offset: u32, + offset: u32 ) -> U128 where - T: NoteInterface + NullifiableNote + OwnedNote, - { + T: NoteInterface + NullifiableNote + OwnedNote, { let mut balance = U128::from_integer(0); // docs:start:view_notes let mut options = NoteViewerOptions::new(); @@ -56,11 +53,10 @@ impl BalanceSet { pub fn add( self: Self, owner_npk_m: NpkM, - addend: U128, + addend: U128 ) -> OuterNoteEmission where - T: NoteInterface + NullifiableNote + OwnedNote + Eq, - { + T: NoteInterface + NullifiableNote + OwnedNote + Eq, { if addend == U128::from_integer(0) { OuterNoteEmission::new(Option::none()) } else { @@ -76,11 +72,10 @@ impl BalanceSet { pub fn sub( self: Self, owner_npk_m: NpkM, - amount: U128, + amount: U128 ) -> OuterNoteEmission where - T: NoteInterface + NullifiableNote + OwnedNote + Eq, - { + T: NoteInterface + NullifiableNote + OwnedNote + Eq, { let subtracted = self.try_sub(amount, MAX_NOTE_HASH_READ_REQUESTS_PER_CALL); // try_sub may have substracted more or less than amount. We must ensure that we subtracted at least as much as @@ -101,18 +96,16 @@ impl BalanceSet { pub fn try_sub( self: Self, target_amount: U128, - max_notes: u32, + max_notes: u32 ) -> U128 where - T: NoteInterface + NullifiableNote + OwnedNote + Eq, - { + T: NoteInterface + NullifiableNote + OwnedNote + Eq, { // We are using a preprocessor here (filter applied in an unconstrained context) instead of a filter because // we do not need to prove correct execution of the preprocessor. // Because the `min_sum` notes is not constrained, users could choose to e.g. not call it. However, all this // might result in is simply higher DA costs due to more nullifiers being emitted. Since we don't care // about proving optimal note usage, we can save these constraints and make the circuit smaller. - let options = NoteGetterOptions::with_preprocessor(preprocess_notes_min_sum, target_amount) - .set_limit(max_notes); + let options = NoteGetterOptions::with_preprocessor(preprocess_notes_min_sum, target_amount).set_limit(max_notes); let notes = self.set.pop_notes(options); let mut subtracted = U128::from_integer(0); @@ -134,11 +127,10 @@ impl BalanceSet { // Note that proper usage of this preprocessor requires for notes to be sorted in descending order. pub fn preprocess_notes_min_sum( notes: [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - min_sum: U128, + min_sum: U128 ) -> [Option; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] where - T: NoteInterface + NullifiableNote + OwnedNote, -{ + T: NoteInterface + NullifiableNote + OwnedNote, { let mut selected = [Option::none(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL]; let mut sum = U128::from_integer(0); for i in 0..notes.len() { diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/types/token_note.nr b/noir-projects/noir-contracts/contracts/token_contract/src/types/token_note.nr index ace732b7c72..6e3bf659742 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/types/token_note.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/types/token_note.nr @@ -1,9 +1,8 @@ use dep::aztec::{ prelude::{NoteHeader, NullifiableNote, PrivateContext}, - protocol_types::{ - constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator, - }, note::utils::compute_note_hash_for_nullify, oracle::random::random, - keys::getters::get_nsk_app, macros::notes::partial_note, + protocol_types::{constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + note::utils::compute_note_hash_for_nullify, oracle::random::random, keys::getters::get_nsk_app, + macros::notes::partial_note }; trait OwnedNote { @@ -25,15 +24,11 @@ pub struct TokenNote { impl NullifiableNote for TokenNote { // docs:start:nullifier - fn compute_nullifier( - self, - context: &mut PrivateContext, - note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, context: &mut PrivateContext, note_hash_for_nullify: Field) -> Field { let secret = context.request_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } // docs:end:nullifier @@ -43,7 +38,7 @@ impl NullifiableNote for TokenNote { let secret = get_nsk_app(self.npk_m_hash); poseidon2_hash_with_separator( [note_hash_for_nullify, secret], - GENERATOR_INDEX__NOTE_NULLIFIER, + GENERATOR_INDEX__NOTE_NULLIFIER ) } } @@ -62,7 +57,9 @@ impl OwnedNote for TokenNote { // malicious sender could use non-random values to make the note less private. But they already know the full // note pre-image anyway, and so the recipient already trusts them to not disclose this information. We can // therefore assume that the sender will cooperate in the random value generation. - let randomness = unsafe { random() }; + let randomness = unsafe { + random() + }; Self { amount, npk_m_hash: owner_npk_m_hash, randomness, header: NoteHeader::empty() } } diff --git a/noir-projects/noir-contracts/contracts/token_contract/src/types/transparent_note.nr b/noir-projects/noir-contracts/contracts/token_contract/src/types/transparent_note.nr index b89920a82ec..19ec7ac1812 100644 --- a/noir-projects/noir-contracts/contracts/token_contract/src/types/transparent_note.nr +++ b/noir-projects/noir-contracts/contracts/token_contract/src/types/transparent_note.nr @@ -1,10 +1,8 @@ // docs:start:token_types_all use dep::aztec::{ - note::utils::compute_note_hash_for_nullify, - prelude::{NoteHeader, NullifiableNote, PrivateContext}, - protocol_types::{ - constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator, - }, macros::notes::note, + note::utils::compute_note_hash_for_nullify, prelude::{NoteHeader, NullifiableNote, PrivateContext}, + protocol_types::{constants::GENERATOR_INDEX__NOTE_NULLIFIER, hash::poseidon2_hash_with_separator}, + macros::notes::note }; use dep::std::mem::zeroed; @@ -28,15 +26,11 @@ impl NullifiableNote for TransparentNote { // 3) the "get_notes" oracle constrains that the secret hash in the returned note matches the one computed in // circuit. // This achieves that the note can only be spent by the party that knows the secret. - fn compute_nullifier( - self, - _context: &mut PrivateContext, - _note_hash_for_nullify: Field, - ) -> Field { + fn compute_nullifier(self, _context: &mut PrivateContext, _note_hash_for_nullify: Field) -> Field { let note_hash_for_nullify = compute_note_hash_for_nullify(self); poseidon2_hash_with_separator( [note_hash_for_nullify], - GENERATOR_INDEX__NOTE_NULLIFIER as Field, + GENERATOR_INDEX__NOTE_NULLIFIER as Field ) } diff --git a/noir-projects/noir-contracts/contracts/uniswap_contract/src/main.nr b/noir-projects/noir-contracts/contracts/uniswap_contract/src/main.nr index 4e488288226..0b1aeb7cd55 100644 --- a/noir-projects/noir-contracts/contracts/uniswap_contract/src/main.nr +++ b/noir-projects/noir-contracts/contracts/uniswap_contract/src/main.nr @@ -10,17 +10,12 @@ use dep::aztec::macros::aztec; contract Uniswap { use dep::aztec::prelude::{FunctionSelector, AztecAddress, EthAddress, SharedImmutable}; - use dep::authwit::auth::{ - assert_current_call_valid_authwit_public, compute_authwit_message_hash_from_call, - set_authorized, - }; + use dep::authwit::auth::{assert_current_call_valid_authwit_public, compute_authwit_message_hash_from_call, set_authorized}; use dep::token::Token; use dep::token_bridge::TokenBridge; use crate::util::{compute_swap_private_content_hash, compute_swap_public_content_hash}; - use dep::aztec::macros::{ - storage::storage, functions::{public, initializer, view, internal, private}, - }; + use dep::aztec::macros::{storage::storage, functions::{public, initializer, view, internal, private}}; #[storage] struct Storage { @@ -51,7 +46,7 @@ contract Uniswap { secret_hash_for_L1_to_l2_message: Field, caller_on_L1: EthAddress, // nonce for someone to call swap on sender's behalf - nonce_for_swap_approval: Field, + nonce_for_swap_approval: Field ) { if (!sender.eq(context.msg_sender())) { assert_current_call_valid_authwit_public(&mut context, sender); @@ -60,37 +55,25 @@ contract Uniswap { let input_asset = TokenBridge::at(input_asset_bridge).get_token().view(&mut context); // Transfer funds to this contract - Token::at(input_asset) - .transfer_public( - sender, - context.this_address(), - input_amount, - nonce_for_transfer_approval, - ) - .call(&mut context); + Token::at(input_asset).transfer_public( + sender, + context.this_address(), + input_amount, + nonce_for_transfer_approval + ).call(&mut context); // Approve bridge to burn this contract's funds and exit to L1 Uniswap Portal - Uniswap::at(context.this_address()) - ._approve_bridge_and_exit_input_asset_to_L1( - input_asset, - input_asset_bridge, - input_amount, - ) - .call(&mut context); + Uniswap::at(context.this_address())._approve_bridge_and_exit_input_asset_to_L1(input_asset, input_asset_bridge, input_amount).call(&mut context); // Create swap message and send to Outbox for Uniswap Portal // this ensures the integrity of what the user originally intends to do on L1. - let input_asset_bridge_portal_address = - TokenBridge::at(input_asset_bridge).get_portal_address_public().view(&mut context); - let output_asset_bridge_portal_address = - TokenBridge::at(output_asset_bridge).get_portal_address_public().view(&mut context); + let input_asset_bridge_portal_address = TokenBridge::at(input_asset_bridge).get_portal_address_public().view(&mut context); + let output_asset_bridge_portal_address = TokenBridge::at(output_asset_bridge).get_portal_address_public().view(&mut context); // ensure portal exists - else funds might be lost assert( - !input_asset_bridge_portal_address.is_zero(), - "L1 portal address of input_asset's bridge is 0", + !input_asset_bridge_portal_address.is_zero(), "L1 portal address of input_asset's bridge is 0" ); assert( - !output_asset_bridge_portal_address.is_zero(), - "L1 portal address of output_asset's bridge is 0", + !output_asset_bridge_portal_address.is_zero(), "L1 portal address of output_asset's bridge is 0" ); let content_hash = compute_swap_public_content_hash( @@ -101,7 +84,7 @@ contract Uniswap { minimum_output_amount, recipient, secret_hash_for_L1_to_l2_message, - caller_on_L1, + caller_on_L1 ); context.message_portal(storage.portal_address.read_public(), content_hash); } @@ -117,52 +100,38 @@ contract Uniswap { // params for using the unshield approval nonce_for_unshield_approval: Field, // params for the swap - uniswap_fee_tier: Field, // which uniswap tier to use (eg 3000 for 0.3% fee) + uniswap_fee_tier: Field,// which uniswap tier to use (eg 3000 for 0.3% fee) minimum_output_amount: Field, // minimum output amount to receive (slippage protection for the swap) // params for the depositing output_asset back to Aztec - secret_hash_for_redeeming_minted_notes: Field, // secret hash used to redeem minted notes at a later time. This enables anyone to call this function and mint tokens to a user on their behalf + secret_hash_for_redeeming_minted_notes: Field,// secret hash used to redeem minted notes at a later time. This enables anyone to call this function and mint tokens to a user on their behalf secret_hash_for_L1_to_l2_message: Field, // for when l1 uniswap portal inserts the message to consume output assets on L2 - caller_on_L1: EthAddress, // ethereum address that can call this function on the L1 portal (0x0 if anyone can call) + caller_on_L1: EthAddress // ethereum address that can call this function on the L1 portal (0x0 if anyone can call) ) { // Assert that user provided token address is same as expected by token bridge. // we can't directly use `input_asset_bridge.token` because that is a public method and public can't return data to private - Uniswap::at(context.this_address()) - ._assert_token_is_same(input_asset, input_asset_bridge) - .enqueue_view(&mut context); + Uniswap::at(context.this_address())._assert_token_is_same(input_asset, input_asset_bridge).enqueue_view(&mut context); // Transfer funds to this contract - Token::at(input_asset) - .unshield( - context.msg_sender(), - context.this_address(), - input_amount, - nonce_for_unshield_approval, - ) - .call(&mut context); + Token::at(input_asset).unshield( + context.msg_sender(), + context.this_address(), + input_amount, + nonce_for_unshield_approval + ).call(&mut context); // Approve bridge to burn this contract's funds and exit to L1 Uniswap Portal - Uniswap::at(context.this_address()) - ._approve_bridge_and_exit_input_asset_to_L1( - input_asset, - input_asset_bridge, - input_amount, - ) - .enqueue(&mut context); + Uniswap::at(context.this_address())._approve_bridge_and_exit_input_asset_to_L1(input_asset, input_asset_bridge, input_amount).enqueue(&mut context); // Create swap message and send to Outbox for Uniswap Portal // this ensures the integrity of what the user originally intends to do on L1. - let input_asset_bridge_portal_address = - TokenBridge::at(input_asset_bridge).get_portal_address().view(&mut context); - let output_asset_bridge_portal_address = - TokenBridge::at(output_asset_bridge).get_portal_address().view(&mut context); + let input_asset_bridge_portal_address = TokenBridge::at(input_asset_bridge).get_portal_address().view(&mut context); + let output_asset_bridge_portal_address = TokenBridge::at(output_asset_bridge).get_portal_address().view(&mut context); // ensure portal exists - else funds might be lost assert( - !input_asset_bridge_portal_address.is_zero(), - "L1 portal address of input_asset's bridge is 0", + !input_asset_bridge_portal_address.is_zero(), "L1 portal address of input_asset's bridge is 0" ); assert( - !output_asset_bridge_portal_address.is_zero(), - "L1 portal address of output_asset's bridge is 0", + !output_asset_bridge_portal_address.is_zero(), "L1 portal address of output_asset's bridge is 0" ); let content_hash = compute_swap_private_content_hash( @@ -173,7 +142,7 @@ contract Uniswap { minimum_output_amount, secret_hash_for_redeeming_minted_notes, secret_hash_for_L1_to_l2_message, - caller_on_L1, + caller_on_L1 ); context.message_portal(storage.portal_address.read_private(), content_hash); } @@ -187,11 +156,7 @@ contract Uniswap { // this method is used for both private and public swaps. #[public] #[internal] - fn _approve_bridge_and_exit_input_asset_to_L1( - token: AztecAddress, - token_bridge: AztecAddress, - amount: Field, - ) { + fn _approve_bridge_and_exit_input_asset_to_L1(token: AztecAddress, token_bridge: AztecAddress, amount: Field) { // Since we will authorize and instantly spend the funds, all in public, we can use the same nonce // every interaction. In practice, the authwit should be squashed, so this is also cheap! let nonce = 0xdeadbeef; @@ -203,7 +168,7 @@ contract Uniswap { context.chain_id(), context.version(), selector, - [context.this_address().to_field(), amount, nonce], + [context.this_address().to_field(), amount, nonce] ); // We need to make a call to update it. @@ -211,9 +176,7 @@ contract Uniswap { let this_portal_address = storage.portal_address.read_public(); // Exit to L1 Uniswap Portal ! - TokenBridge::at(token_bridge) - .exit_to_l1_public(this_portal_address, amount, this_portal_address, nonce) - .call(&mut context) + TokenBridge::at(token_bridge).exit_to_l1_public(this_portal_address, amount, this_portal_address, nonce).call(&mut context) } // docs:end:authwit_uniswap_set @@ -223,8 +186,7 @@ contract Uniswap { #[view] fn _assert_token_is_same(token: AztecAddress, token_bridge: AztecAddress) { assert( - token.eq(TokenBridge::at(token_bridge).get_token().view(&mut context)), - "input_asset address is not the same as seen in the bridge contract", + token.eq(TokenBridge::at(token_bridge).get_token().view(&mut context)), "input_asset address is not the same as seen in the bridge contract" ); } // docs:end:assert_token_is_same diff --git a/noir-projects/noir-contracts/contracts/uniswap_contract/src/util.nr b/noir-projects/noir-contracts/contracts/uniswap_contract/src/util.nr index 8d93994d624..1ea5a51ad21 100644 --- a/noir-projects/noir-contracts/contracts/uniswap_contract/src/util.nr +++ b/noir-projects/noir-contracts/contracts/uniswap_contract/src/util.nr @@ -12,19 +12,16 @@ pub fn compute_swap_public_content_hash( minimum_output_amount: Field, aztec_recipient: AztecAddress, secret_hash_for_L1_to_l2_message: Field, - caller_on_L1: EthAddress, + caller_on_L1: EthAddress ) -> Field { let mut hash_bytes = [0; 260]; // 8 fields of 32 bytes each + 4 bytes fn selector - let input_token_portal_bytes: [u8; 32] = - input_asset_bridge_portal_address.to_field().to_be_bytes(); + let input_token_portal_bytes: [u8; 32] = input_asset_bridge_portal_address.to_field().to_be_bytes(); let in_amount_bytes: [u8; 32] = input_amount.to_be_bytes(); let uniswap_fee_tier_bytes: [u8; 32] = uniswap_fee_tier.to_be_bytes(); - let output_token_portal_bytes: [u8; 32] = - output_asset_bridge_portal_address.to_field().to_be_bytes(); + let output_token_portal_bytes: [u8; 32] = output_asset_bridge_portal_address.to_field().to_be_bytes(); let amount_out_min_bytes: [u8; 32] = minimum_output_amount.to_be_bytes(); let aztec_recipient_bytes: [u8; 32] = aztec_recipient.to_field().to_be_bytes(); - let secret_hash_for_L1_to_l2_message_bytes: [u8; 32] = - secret_hash_for_L1_to_l2_message.to_be_bytes(); + let secret_hash_for_L1_to_l2_message_bytes: [u8; 32] = secret_hash_for_L1_to_l2_message.to_be_bytes(); let caller_on_L1_bytes: [u8; 32] = caller_on_L1.to_field().to_be_bytes(); // function selector: 0xf18186d8 keccak256("swap_public(address,uint256,uint24,address,uint256,bytes32,bytes32,address)") @@ -60,20 +57,16 @@ pub fn compute_swap_private_content_hash( minimum_output_amount: Field, secret_hash_for_redeeming_minted_notes: Field, secret_hash_for_L1_to_l2_message: Field, - caller_on_L1: EthAddress, + caller_on_L1: EthAddress ) -> Field { let mut hash_bytes = [0; 260]; // 8 fields of 32 bytes each + 4 bytes fn selector - let input_token_portal_bytes: [u8; 32] = - input_asset_bridge_portal_address.to_field().to_be_bytes(); + let input_token_portal_bytes: [u8; 32] = input_asset_bridge_portal_address.to_field().to_be_bytes(); let in_amount_bytes: [u8; 32] = input_amount.to_be_bytes(); let uniswap_fee_tier_bytes: [u8; 32] = uniswap_fee_tier.to_be_bytes(); - let output_token_portal_bytes: [u8; 32] = - output_asset_bridge_portal_address.to_field().to_be_bytes(); + let output_token_portal_bytes: [u8; 32] = output_asset_bridge_portal_address.to_field().to_be_bytes(); let amount_out_min_bytes: [u8; 32] = minimum_output_amount.to_be_bytes(); - let secret_hash_for_redeeming_minted_notes_bytes: [u8; 32] = - secret_hash_for_redeeming_minted_notes.to_be_bytes(); - let secret_hash_for_L1_to_l2_message_bytes: [u8; 32] = - secret_hash_for_L1_to_l2_message.to_be_bytes(); + let secret_hash_for_redeeming_minted_notes_bytes: [u8; 32] = secret_hash_for_redeeming_minted_notes.to_be_bytes(); + let secret_hash_for_L1_to_l2_message_bytes: [u8; 32] = secret_hash_for_L1_to_l2_message.to_be_bytes(); let caller_on_L1_bytes: [u8; 32] = caller_on_L1.to_field().to_be_bytes(); // function selector: 0x16f416eb keccak256("swap_private(address,uint256,uint24,address,uint256,bytes32,bytes32,address)") diff --git a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/base/base_parity_inputs.nr b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/base/base_parity_inputs.nr index 0684362547b..d9bbcdab794 100644 --- a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/base/base_parity_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/base/base_parity_inputs.nr @@ -14,7 +14,7 @@ impl BaseParityInputs { ParityPublicInputs { sha_root: sha_tree.get_root(), converted_root: poseidon_tree.get_root(), - vk_tree_root: self.vk_tree_root, + vk_tree_root: self.vk_tree_root } } } @@ -26,7 +26,7 @@ fn test_sha_root_matches_frontier_tree() { 0x151de48ca3efbae39f180fe00b8f472ec9f25be10b4f283a87c6d783935370, 0x14c2ea9dedf77698d4afe23bc663263eed0bf9aa3a8b17d9b74812f185610f, 0x1570cc6641699e3ae87fa258d80a6d853f7b8ccb211dc244d017e2ca6530f8, - 0x2806c860af67e9cd50000378411b8c4c4db172ceb2daa862b259b689ccbdc1, + 0x2806c860af67e9cd50000378411b8c4c4db172ceb2daa862b259b689ccbdc1 ]; let base_parity_inputs = BaseParityInputs { msgs, vk_tree_root: 42 }; diff --git a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/parity_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/parity_public_inputs.nr index 3b7b286020c..c2f6930a955 100644 --- a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/parity_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/parity_public_inputs.nr @@ -24,10 +24,6 @@ impl Serialize<3> for ParityPublicInputs { impl Deserialize<3> for ParityPublicInputs { fn deserialize(fields: [Field; 3]) -> Self { - ParityPublicInputs { - sha_root: fields[0], - converted_root: fields[1], - vk_tree_root: fields[2], - } + ParityPublicInputs { sha_root: fields[0], converted_root: fields[1], vk_tree_root: fields[2] } } } diff --git a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_parity_input.nr b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_parity_input.nr index 1999eff165e..66b9884a315 100644 --- a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_parity_input.nr +++ b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_parity_input.nr @@ -1,10 +1,7 @@ use dep::types::{ traits::Empty, - recursion::{ - verification_key::{VerificationKey, HonkVerificationKey}, proof::RecursiveProof, - traits::Verifiable, - }, constants::{BASE_PARITY_INDEX, VK_TREE_HEIGHT}, - merkle_tree::membership::assert_check_membership, + recursion::{verification_key::{VerificationKey, HonkVerificationKey}, proof::RecursiveProof, traits::Verifiable}, + constants::{BASE_PARITY_INDEX, VK_TREE_HEIGHT}, merkle_tree::membership::assert_check_membership }; use crate::parity_public_inputs::ParityPublicInputs; @@ -21,7 +18,7 @@ impl Empty for RootParityInput { proof: RecursiveProof::empty(), verification_key: VerificationKey::empty(), vk_path: [0; VK_TREE_HEIGHT], - public_inputs: ParityPublicInputs::empty(), + public_inputs: ParityPublicInputs::empty() } } } @@ -33,7 +30,7 @@ impl Verifiable for RootParityInput { self.verification_key.key, self.proof.fields, inputs, - self.verification_key.hash, + self.verification_key.hash ); } } @@ -45,7 +42,7 @@ impl RootParityInput { self.verification_key.hash, BASE_PARITY_INDEX as Field, self.vk_path, - self.public_inputs.vk_tree_root, + self.public_inputs.vk_tree_root ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_parity_inputs.nr b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_parity_inputs.nr index 50bc3edc4ce..e765f5e3137 100644 --- a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_parity_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_parity_inputs.nr @@ -1,7 +1,7 @@ use dep::types::merkle_tree::MerkleTree; use crate::{ parity_public_inputs::ParityPublicInputs, root::root_parity_input::RootParityInput, - utils::sha256_merkle_tree::Sha256MerkleTree, + utils::sha256_merkle_tree::Sha256MerkleTree }; global NUM_BASE_PARITY_PER_ROOT_PARITY: u32 = 4; @@ -16,8 +16,7 @@ impl RootParityInputs { let vk_tree_root = self.children[0].public_inputs.vk_tree_root; for i in 0..NUM_BASE_PARITY_PER_ROOT_PARITY { assert( - self.children[i].public_inputs.vk_tree_root == vk_tree_root, - "Inconsistent vk tree roots across base parity circuits", + self.children[i].public_inputs.vk_tree_root == vk_tree_root, "Inconsistent vk tree roots across base parity circuits" ); } @@ -31,22 +30,16 @@ impl RootParityInputs { let sha_tree = Sha256MerkleTree::new(sha_roots); let poseidon_tree = MerkleTree::new(converted_roots); - ParityPublicInputs { - sha_root: sha_tree.get_root(), - converted_root: poseidon_tree.get_root(), - vk_tree_root, - } + ParityPublicInputs { sha_root: sha_tree.get_root(), converted_root: poseidon_tree.get_root(), vk_tree_root } } fn verify_child_proofs(self) { for i in 0..NUM_BASE_PARITY_PER_ROOT_PARITY { assert( - self.children[i].verification_key.hash == self.children[0].verification_key.hash, - "Inconsistent vk hashes across base parity circuits", + self.children[i].verification_key.hash == self.children[0].verification_key.hash, "Inconsistent vk hashes across base parity circuits" ); assert( - self.children[i].vk_path == self.children[0].vk_path, - "Inconsistent vk paths across base parity circuits", + self.children[i].vk_path == self.children[0].vk_path, "Inconsistent vk paths across base parity circuits" ); self.children[i].verify(); self.children[i].validate_in_vk_tree(); @@ -57,7 +50,7 @@ impl RootParityInputs { mod tests { use crate::{ parity_public_inputs::ParityPublicInputs, - root::{root_parity_input::RootParityInput, root_parity_inputs::RootParityInputs}, + root::{root_parity_input::RootParityInput, root_parity_inputs::RootParityInputs} }; use dep::types::recursion::{verification_key::VerificationKey, proof::RecursiveProof}; use dep::types::tests::fixtures; @@ -73,7 +66,7 @@ mod tests { 0xb3a3fc1968999f2c2d798b900bdf0de41311be2a4d20496a7e792a521fc8ab, 0x43f78e0ebc9633ce336a8c086064d898c32fb5d7d6011f5427459c0b8d14e9, 0x024259b6404280addcc9319bc5a32c9a5d56af5c93b2f941fa326064fbe963, - 0x53042d820859d80c474d4694e03778f8dc0ac88fc1c3a97b4369c1096e904a, + 0x53042d820859d80c474d4694e03778f8dc0ac88fc1c3a97b4369c1096e904a ]; let vk_tree = fixtures::vk_tree::get_vk_merkle_tree(); @@ -88,42 +81,26 @@ mod tests { proof: RecursiveProof::empty(), verification_key: vk1, vk_path, - public_inputs: ParityPublicInputs { - sha_root: children_sha_roots[0], - converted_root: 0, - vk_tree_root, - }, + public_inputs: ParityPublicInputs { sha_root: children_sha_roots[0], converted_root: 0, vk_tree_root } }, RootParityInput { proof: RecursiveProof::empty(), verification_key: vk1, vk_path, - public_inputs: ParityPublicInputs { - sha_root: children_sha_roots[1], - converted_root: 0, - vk_tree_root, - }, + public_inputs: ParityPublicInputs { sha_root: children_sha_roots[1], converted_root: 0, vk_tree_root } }, RootParityInput { proof: RecursiveProof::empty(), verification_key: vk1, vk_path, - public_inputs: ParityPublicInputs { - sha_root: children_sha_roots[2], - converted_root: 0, - vk_tree_root, - }, + public_inputs: ParityPublicInputs { sha_root: children_sha_roots[2], converted_root: 0, vk_tree_root } }, RootParityInput { proof: RecursiveProof::empty(), verification_key: vk1, vk_path, - public_inputs: ParityPublicInputs { - sha_root: children_sha_roots[3], - converted_root: 0, - vk_tree_root, - }, - }, + public_inputs: ParityPublicInputs { sha_root: children_sha_roots[3], converted_root: 0, vk_tree_root } + } ]; children } diff --git a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_rollup_parity_input.nr b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_rollup_parity_input.nr index 23f082d38f9..018541f82a2 100644 --- a/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_rollup_parity_input.nr +++ b/noir-projects/noir-protocol-circuits/crates/parity-lib/src/root/root_rollup_parity_input.nr @@ -1,10 +1,10 @@ use dep::types::{ traits::Empty, recursion::{ - verification_key::{VerificationKey, HonkVerificationKey}, proof::NestedRecursiveProof, - traits::Verifiable, - }, constants::{ROOT_PARITY_INDEX, VK_TREE_HEIGHT}, - merkle_tree::membership::assert_check_membership, + verification_key::{VerificationKey, HonkVerificationKey}, proof::NestedRecursiveProof, + traits::Verifiable +}, + constants::{ROOT_PARITY_INDEX, VK_TREE_HEIGHT}, merkle_tree::membership::assert_check_membership }; use crate::parity_public_inputs::ParityPublicInputs; @@ -21,7 +21,7 @@ impl Empty for RootRollupParityInput { proof: NestedRecursiveProof::empty(), verification_key: VerificationKey::empty(), vk_path: [0; VK_TREE_HEIGHT], - public_inputs: ParityPublicInputs::empty(), + public_inputs: ParityPublicInputs::empty() } } } @@ -33,7 +33,7 @@ impl Verifiable for RootRollupParityInput { self.verification_key.key, self.proof.fields, inputs, - self.verification_key.hash, + self.verification_key.hash ); } } @@ -45,7 +45,7 @@ impl RootRollupParityInput { self.verification_key.hash, ROOT_PARITY_INDEX as Field, self.vk_path, - self.public_inputs.vk_tree_root, + self.public_inputs.vk_tree_root ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-init-simulated/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-init-simulated/src/main.nr index 8d34da7efff..d1d89b9c862 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-init-simulated/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-init-simulated/src/main.nr @@ -9,14 +9,14 @@ unconstrained fn main( vk_tree_root: Field, protocol_contract_tree_root: Field, private_call: PrivateCallDataWithoutPublicInputs, - app_public_inputs: PrivateCircuitPublicInputs, + app_public_inputs: PrivateCircuitPublicInputs ) -> pub PrivateKernelCircuitPublicInputs { let private_inputs = PrivateKernelInitCircuitPrivateInputs::new( tx_request, vk_tree_root, protocol_contract_tree_root, private_call, - app_public_inputs, + app_public_inputs ); private_inputs.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-init/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-init/src/main.nr index 8ed70c84e56..011337bb55c 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-init/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-init/src/main.nr @@ -9,14 +9,14 @@ fn main( vk_tree_root: Field, protocol_contract_tree_root: Field, private_call: PrivateCallDataWithoutPublicInputs, - app_public_inputs: call_data(1) PrivateCircuitPublicInputs, + app_public_inputs: call_data(1) PrivateCircuitPublicInputs ) -> return_data PrivateKernelCircuitPublicInputs { let private_inputs = PrivateKernelInitCircuitPrivateInputs::new( tx_request, vk_tree_root, protocol_contract_tree_root, private_call, - app_public_inputs, + app_public_inputs ); private_inputs.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-inner-simulated/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-inner-simulated/src/main.nr index 930117c4bcc..5f4180f1571 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-inner-simulated/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-inner-simulated/src/main.nr @@ -8,13 +8,13 @@ unconstrained fn main( previous_kernel: PrivateKernelDataWithoutPublicInputs, previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs, private_call: PrivateCallDataWithoutPublicInputs, - app_public_inputs: PrivateCircuitPublicInputs, + app_public_inputs: PrivateCircuitPublicInputs ) -> pub PrivateKernelCircuitPublicInputs { let private_inputs = PrivateKernelInnerCircuitPrivateInputs::new( previous_kernel, previous_kernel_public_inputs, private_call, - app_public_inputs, + app_public_inputs ); private_inputs.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-inner/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-inner/src/main.nr index 54a3ae66fb5..e9d4e26f921 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-inner/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-inner/src/main.nr @@ -8,13 +8,13 @@ fn main( previous_kernel: PrivateKernelDataWithoutPublicInputs, previous_kernel_public_inputs: call_data(0) PrivateKernelCircuitPublicInputs, private_call: PrivateCallDataWithoutPublicInputs, - app_public_inputs: call_data(1) PrivateCircuitPublicInputs, + app_public_inputs: call_data(1) PrivateCircuitPublicInputs ) -> return_data PrivateKernelCircuitPublicInputs { let private_inputs = PrivateKernelInnerCircuitPrivateInputs::new( previous_kernel, previous_kernel_public_inputs, private_call, - app_public_inputs, + app_public_inputs ); private_inputs.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/previous_kernel_validator.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/previous_kernel_validator.nr index fdadacfe1ad..83b1a88401c 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/previous_kernel_validator.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/previous_kernel_validator.nr @@ -1,11 +1,9 @@ mod previous_kernel_validator_hints; -use crate::components::previous_kernel_validator::previous_kernel_validator_hints::{ - generate_previous_kernel_validator_hints, PreviousKernelValidatorHints, -}; +use crate::components::previous_kernel_validator::previous_kernel_validator_hints::{generate_previous_kernel_validator_hints, PreviousKernelValidatorHints}; use dep::types::{ abis::{log_hash::ScopedEncryptedLogHash, private_kernel_data::PrivateKernelData}, - address::AztecAddress, traits::is_empty, utils::arrays::array_length, + address::AztecAddress, traits::is_empty, utils::arrays::array_length }; pub struct PreviousKernelValidator { @@ -15,8 +13,9 @@ pub struct PreviousKernelValidator { impl PreviousKernelValidator { pub fn new(previous_kernel: PrivateKernelData) -> Self { - let hints = - unsafe { generate_previous_kernel_validator_hints(previous_kernel.public_inputs) }; + let hints = unsafe { + generate_previous_kernel_validator_hints(previous_kernel.public_inputs) + }; PreviousKernelValidator { previous_kernel, hints } } @@ -46,93 +45,55 @@ impl PreviousKernelValidator { fn validate_empty_private_call_stack(self) { // Only need to check the first item as the kernel circuits always append items to the arrays properly. assert( - is_empty(self.previous_kernel.public_inputs.end.private_call_stack[0]), - "Private call stack must be empty when executing the tail circuit", + is_empty(self.previous_kernel.public_inputs.end.private_call_stack[0]), "Private call stack must be empty when executing the tail circuit" ); } fn validate_empty_data(self) { assert( - is_empty( - self.previous_kernel.public_inputs.end.public_call_requests[0], - ), - "Public call stack must be empty when executing the tail circuit", + is_empty(self.previous_kernel.public_inputs.end.public_call_requests[0]), "Public call stack must be empty when executing the tail circuit" ); assert( - is_empty( - self.previous_kernel.public_inputs.public_teardown_call_request, - ), - "Public teardown call request must be empty when executing the tail circuit", + is_empty(self.previous_kernel.public_inputs.public_teardown_call_request), "Public teardown call request must be empty when executing the tail circuit" ); if self.previous_kernel.public_inputs.validation_requests.split_counter.is_some() { // Even when min_revertible_side_effect_counter could be non-zero in a pure private tx. // The split counter must be 0 to ensure that all the transient data are squashed. assert_eq( - self - .previous_kernel - .public_inputs - .validation_requests - .split_counter - .unwrap_unchecked(), - 0, - "split_counter must be 0 for pure private tx", + self.previous_kernel.public_inputs.validation_requests.split_counter.unwrap_unchecked(), 0, "split_counter must be 0 for pure private tx" ); } } fn validate_non_empty_data(self) { assert( - !is_empty( - self.previous_kernel.public_inputs.end.public_call_requests[0], - ) - | !is_empty( - self.previous_kernel.public_inputs.public_teardown_call_request, - ), - "Must have public calls when exporting public kernel data from the tail circuit", + !is_empty(self.previous_kernel.public_inputs.end.public_call_requests[0]) + | !is_empty(self.previous_kernel.public_inputs.public_teardown_call_request), "Must have public calls when exporting public kernel data from the tail circuit" ); assert( - self.previous_kernel.public_inputs.min_revertible_side_effect_counter != 0, - "min_revertible_side_effect_counter must not be 0", + self.previous_kernel.public_inputs.min_revertible_side_effect_counter != 0, "min_revertible_side_effect_counter must not be 0" ); if self.previous_kernel.public_inputs.validation_requests.split_counter.is_some() { assert_eq( - self - .previous_kernel - .public_inputs - .validation_requests - .split_counter - .unwrap_unchecked(), - self.previous_kernel.public_inputs.min_revertible_side_effect_counter, - "split_counter does not match min_revertible_side_effect_counter", + self.previous_kernel.public_inputs.validation_requests.split_counter.unwrap_unchecked(), self.previous_kernel.public_inputs.min_revertible_side_effect_counter, "split_counter does not match min_revertible_side_effect_counter" ); } } fn verify_empty_validation_requests(self) { assert( - is_empty( - self.previous_kernel.public_inputs.validation_requests.note_hash_read_requests[0], - ), - "Non empty note hash read requests", + is_empty(self.previous_kernel.public_inputs.validation_requests.note_hash_read_requests[0]), "Non empty note hash read requests" ); assert( - is_empty( - self.previous_kernel.public_inputs.validation_requests.nullifier_read_requests[0], - ), - "Non empty nullifier read requests", + is_empty(self.previous_kernel.public_inputs.validation_requests.nullifier_read_requests[0]), "Non empty nullifier read requests" ); assert( is_empty( - self - .previous_kernel - .public_inputs - .validation_requests - .scoped_key_validation_requests_and_generators[0], - ), - "Non empty key validation requests", + self.previous_kernel.public_inputs.validation_requests.scoped_key_validation_requests_and_generators[0] + ), "Non empty key validation requests" ); } @@ -143,37 +104,26 @@ impl PreviousKernelValidator { if num_note_hashes != 0 { let note_hash = self.previous_kernel.public_inputs.end.note_hashes[num_note_hashes - 1]; assert_eq( - note_hash.contract_address, - AztecAddress::zero(), - "note hashes have not been siloed in a reset", + note_hash.contract_address, AztecAddress::zero(), "note hashes have not been siloed in a reset" ); } let num_nullifiers = array_length(self.previous_kernel.public_inputs.end.nullifiers); let nullifier = self.previous_kernel.public_inputs.end.nullifiers[num_nullifiers - 1]; // - 1 without checking because there's at least 1 nullifier. assert_eq( - nullifier.contract_address, - AztecAddress::zero(), - "nullifiers have not been siloed in a reset", + nullifier.contract_address, AztecAddress::zero(), "nullifiers have not been siloed in a reset" ); // Note logs are not siloed, but they are sorted and their note_hash_counter should've been set to 0 in the reset circuit. - let num_note_logs = array_length( - self.previous_kernel.public_inputs.end.note_encrypted_logs_hashes, - ); + let num_note_logs = array_length(self.previous_kernel.public_inputs.end.note_encrypted_logs_hashes); if num_note_logs != 0 { - let note_log = self.previous_kernel.public_inputs.end.note_encrypted_logs_hashes[ - num_note_logs - - 1]; + let note_log = self.previous_kernel.public_inputs.end.note_encrypted_logs_hashes[num_note_logs - 1]; assert_eq(note_log.note_hash_counter, 0, "note logs have not been sorted in a reset"); } // We need to check the entire array because randomness can be 0 for encrypted logs if the app wants to reveal the actual contract address. assert( - self.previous_kernel.public_inputs.end.encrypted_logs_hashes.all( - |h: ScopedEncryptedLogHash| h.log_hash.randomness == 0, - ), - "encrypted logs have not been siloed in a reset", + self.previous_kernel.public_inputs.end.encrypted_logs_hashes.all(|h: ScopedEncryptedLogHash| h.log_hash.randomness == 0), "encrypted logs have not been siloed in a reset" ); } @@ -187,13 +137,10 @@ impl PreviousKernelValidator { if nullified_note_hash != 0 { let note_hash = note_hashes[note_hash_indexes_for_nullifiers[i]]; assert_eq( - note_hash.value(), - nullified_note_hash, - "Hinted siloed note hash does not match nullified note hash", + note_hash.value(), nullified_note_hash, "Hinted siloed note hash does not match nullified note hash" ); assert( - note_hash.counter() < nullifier.counter(), - "Cannot link a note hash emitted after a nullifier", + note_hash.counter() < nullifier.counter(), "Cannot link a note hash emitted after a nullifier" ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/previous_kernel_validator/previous_kernel_validator_hints.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/previous_kernel_validator/previous_kernel_validator_hints.nr index 28719890ab0..b106bc1a3e0 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/previous_kernel_validator/previous_kernel_validator_hints.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/previous_kernel_validator/previous_kernel_validator_hints.nr @@ -1,16 +1,13 @@ use dep::types::{ - abis::{ - kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, note_hash::ScopedNoteHash, - }, constants::{MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX}, utils::arrays::find_index_hint, + abis::{kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, note_hash::ScopedNoteHash}, + constants::{MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX}, utils::arrays::find_index_hint }; pub struct PreviousKernelValidatorHints { note_hash_indexes_for_nullifiers: [u32; MAX_NULLIFIERS_PER_TX], } -pub unconstrained fn generate_previous_kernel_validator_hints( - previous_kernel: PrivateKernelCircuitPublicInputs, -) -> PreviousKernelValidatorHints { +pub unconstrained fn generate_previous_kernel_validator_hints(previous_kernel: PrivateKernelCircuitPublicInputs) -> PreviousKernelValidatorHints { let mut note_hash_indexes_for_nullifiers = [0; MAX_NULLIFIERS_PER_TX]; let note_hashes = previous_kernel.end.note_hashes; let nullifiers = previous_kernel.end.nullifiers; @@ -18,7 +15,7 @@ pub unconstrained fn generate_previous_kernel_validator_hints( let nullified_note_hash = nullifiers[i].nullifier.note_hash; let note_hash_index = find_index_hint( note_hashes, - |n: ScopedNoteHash| n.value() == nullified_note_hash, + |n: ScopedNoteHash| n.value() == nullified_note_hash ); if (nullified_note_hash != 0) & (note_hash_index != MAX_NOTE_HASHES_PER_TX) { note_hash_indexes_for_nullifiers[i] = note_hash_index; diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator.nr index 2fa422b6c00..0e6e2a29a23 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator.nr @@ -4,24 +4,22 @@ mod validate_split_ranges; use crate::components::private_call_data_validator::{ find_first_revertible_item_index::find_first_revertible_item_index, - validate_contract_address::validate_contract_address, - validate_split_ranges::validate_split_ranges, + validate_contract_address::validate_contract_address, validate_split_ranges::validate_split_ranges }; use dep::types::{ abis::{ - call_context::CallContext, kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, - note_hash::ScopedNoteHash, private_call_request::PrivateCallRequest, - private_circuit_public_inputs::PrivateCircuitPublicInputsArrayLengths, - private_kernel::private_call_data::PrivateCallData, side_effect::{Ordered, RangeOrdered}, - }, address::AztecAddress, constants::MAX_FIELD_VALUE, transaction::tx_request::TxRequest, - utils::arrays::find_index_hint, + call_context::CallContext, kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, + note_hash::ScopedNoteHash, private_call_request::PrivateCallRequest, + private_circuit_public_inputs::PrivateCircuitPublicInputsArrayLengths, + private_kernel::private_call_data::PrivateCallData, side_effect::{Ordered, RangeOrdered} +}, + address::AztecAddress, constants::MAX_FIELD_VALUE, transaction::tx_request::TxRequest, + utils::arrays::find_index_hint }; fn validate_call_context(target_context: CallContext, this_context: CallContext) { assert_eq( - target_context.msg_sender, - this_context.contract_address, - "incorrect msg_sender for call request", + target_context.msg_sender, this_context.contract_address, "incorrect msg_sender for call request" ); if !target_context.is_static_call { assert(this_context.is_static_call == false, "static call cannot make non-static calls"); @@ -32,11 +30,10 @@ fn validate_incrementing_counters_within_range( counter_start: u32, counter_end: u32, items: [T; N], - num_items: u32, + num_items: u32 ) where - T: Ordered, -{ + T: Ordered, { let mut prev_counter = counter_start; let mut should_check = true; for i in 0..N { @@ -44,8 +41,7 @@ where if should_check { let item = items[i]; assert( - item.counter() > prev_counter, - "counter must be larger than the counter of the previous item", + item.counter() > prev_counter, "counter must be larger than the counter of the previous item" ); prev_counter = item.counter(); } @@ -57,11 +53,10 @@ fn validate_incrementing_counter_ranges_within_range( counter_start: u32, counter_end: u32, items: [T; N], - num_items: u32, + num_items: u32 ) where - T: RangeOrdered, -{ + T: RangeOrdered, { let mut prev_counter = counter_start; let mut should_check = true; for i in 0..N { @@ -69,19 +64,14 @@ where if should_check { let item = items[i]; assert( - item.counter_start() > prev_counter, - "start counter must be larger than the end counter of the previous call", - ); - assert( - item.counter_end() > item.counter_start(), - "nested call has incorrect counter range", + item.counter_start() > prev_counter, "start counter must be larger than the end counter of the previous call" ); + assert(item.counter_end() > item.counter_start(), "nested call has incorrect counter range"); prev_counter = item.counter_end(); } } assert( - prev_counter < counter_end, - "end counter must be smaller than the end counter of the parent call", + prev_counter < counter_end, "end counter must be smaller than the end counter of the parent call" ); } @@ -99,7 +89,7 @@ impl PrivateCallDataValidator { pub fn validate( self, accumulated_note_hashes: [ScopedNoteHash; N], - protocol_contract_tree_root: Field, + protocol_contract_tree_root: Field ) { validate_contract_address(self.data, protocol_contract_tree_root); self.validate_call(); @@ -115,8 +105,7 @@ impl PrivateCallDataValidator { let call_context = public_inputs.call_context; assert(call_context.is_static_call == false, "Users cannot make a static call"); assert( - call_context.msg_sender == AztecAddress::from_field(MAX_FIELD_VALUE), - "Users cannot set msg_sender in first call", + call_context.msg_sender == AztecAddress::from_field(MAX_FIELD_VALUE), "Users cannot set msg_sender in first call" ); } @@ -124,71 +113,39 @@ impl PrivateCallDataValidator { pub fn validate_against_tx_request(self, tx_request: TxRequest) { let public_inputs = self.data.public_inputs; assert_eq( - tx_request.origin, - public_inputs.call_context.contract_address, - "contract address does not match origin", + tx_request.origin, public_inputs.call_context.contract_address, "contract address does not match origin" ); assert_eq( - tx_request.function_data.selector, - public_inputs.call_context.function_selector, - "function_selector in call_context does not match the value in tx_request", + tx_request.function_data.selector, public_inputs.call_context.function_selector, "function_selector in call_context does not match the value in tx_request" ); assert( - tx_request.function_data.is_private, - "tx_request does not indicate the first function is private", + tx_request.function_data.is_private, "tx_request does not indicate the first function is private" ); assert_eq( - tx_request.args_hash, - public_inputs.args_hash, - "args_hash in private call does not match the value in tx_request", + tx_request.args_hash, public_inputs.args_hash, "args_hash in private call does not match the value in tx_request" ); assert_eq( - tx_request.tx_context, - public_inputs.tx_context, - "tx_context in private call does not match the value in tx_request", + tx_request.tx_context, public_inputs.tx_context, "tx_context in private call does not match the value in tx_request" ); } pub fn validate_against_call_request(self, request: PrivateCallRequest) { let public_inputs = self.data.public_inputs; + assert_eq(request.call_context, public_inputs.call_context, "call_context does not match call request"); + assert_eq(request.args_hash, public_inputs.args_hash, "args_hash does not match call request"); + assert_eq(request.returns_hash, public_inputs.returns_hash, "returns_hash does not match call request"); assert_eq( - request.call_context, - public_inputs.call_context, - "call_context does not match call request", - ); - assert_eq( - request.args_hash, - public_inputs.args_hash, - "args_hash does not match call request", + request.start_side_effect_counter, public_inputs.start_side_effect_counter, "start_side_effect_counter does not match call request" ); assert_eq( - request.returns_hash, - public_inputs.returns_hash, - "returns_hash does not match call request", - ); - assert_eq( - request.start_side_effect_counter, - public_inputs.start_side_effect_counter, - "start_side_effect_counter does not match call request", - ); - assert_eq( - request.end_side_effect_counter, - public_inputs.end_side_effect_counter, - "end_side_effect_counter does not match call request", + request.end_side_effect_counter, public_inputs.end_side_effect_counter, "end_side_effect_counter does not match call request" ); } - pub fn validate_against_previous_kernel( - self, - previous_kernel: PrivateKernelCircuitPublicInputs, - ) { + pub fn validate_against_previous_kernel(self, previous_kernel: PrivateKernelCircuitPublicInputs) { let constants = previous_kernel.constants; let public_inputs = self.data.public_inputs; - assert_eq( - public_inputs.historical_header, - constants.historical_header, - "mismatch historical header", - ); + assert_eq(public_inputs.historical_header, constants.historical_header, "mismatch historical header"); assert_eq(public_inputs.tx_context, constants.tx_context, "mismatch tx context"); // constants.global_variables is not relevant to private functions and is ensured to be empty in PrivateKernelCircuitOutputValidator. } @@ -197,35 +154,17 @@ impl PrivateCallDataValidator { let call_context = self.data.public_inputs.call_context; if call_context.is_static_call { // No state changes are allowed for static calls: + assert_eq(self.array_lengths.note_hashes, 0, "note_hashes must be empty for static calls"); + assert_eq(self.array_lengths.nullifiers, 0, "nullifiers must be empty for static calls"); + assert_eq(self.array_lengths.l2_to_l1_msgs, 0, "l2_to_l1_msgs must be empty for static calls"); assert_eq( - self.array_lengths.note_hashes, - 0, - "note_hashes must be empty for static calls", - ); - assert_eq( - self.array_lengths.nullifiers, - 0, - "nullifiers must be empty for static calls", - ); - assert_eq( - self.array_lengths.l2_to_l1_msgs, - 0, - "l2_to_l1_msgs must be empty for static calls", + self.array_lengths.note_encrypted_logs_hashes, 0, "note_encrypted_logs_hashes must be empty for static calls" ); assert_eq( - self.array_lengths.note_encrypted_logs_hashes, - 0, - "note_encrypted_logs_hashes must be empty for static calls", + self.array_lengths.encrypted_logs_hashes, 0, "encrypted_logs_hashes must be empty for static calls" ); assert_eq( - self.array_lengths.encrypted_logs_hashes, - 0, - "encrypted_logs_hashes must be empty for static calls", - ); - assert_eq( - self.array_lengths.unencrypted_logs_hashes, - 0, - "unencrypted_logs_hashes must be empty for static calls", + self.array_lengths.unencrypted_logs_hashes, 0, "unencrypted_logs_hashes must be empty for static calls" ); } } @@ -255,14 +194,14 @@ impl PrivateCallDataValidator { let first_revertible_index = unsafe { find_first_revertible_item_index( public_inputs.min_revertible_side_effect_counter, - public_inputs.private_call_requests, + public_inputs.private_call_requests ) }; validate_split_ranges( min_revertible_side_effect_counter, first_revertible_index, public_inputs.private_call_requests, - self.array_lengths.private_call_requests, + self.array_lengths.private_call_requests ); } @@ -298,49 +237,49 @@ impl PrivateCallDataValidator { counter_start, counter_end, public_inputs.note_hash_read_requests, - self.array_lengths.note_hash_read_requests, + self.array_lengths.note_hash_read_requests ); validate_incrementing_counters_within_range( counter_start, counter_end, public_inputs.nullifier_read_requests, - self.array_lengths.nullifier_read_requests, + self.array_lengths.nullifier_read_requests ); validate_incrementing_counters_within_range( counter_start, counter_end, public_inputs.note_hashes, - self.array_lengths.note_hashes, + self.array_lengths.note_hashes ); validate_incrementing_counters_within_range( counter_start, counter_end, public_inputs.nullifiers, - self.array_lengths.nullifiers, + self.array_lengths.nullifiers ); validate_incrementing_counters_within_range( counter_start, counter_end, public_inputs.l2_to_l1_msgs, - self.array_lengths.l2_to_l1_msgs, + self.array_lengths.l2_to_l1_msgs ); validate_incrementing_counters_within_range( counter_start, counter_end, public_inputs.encrypted_logs_hashes, - self.array_lengths.encrypted_logs_hashes, + self.array_lengths.encrypted_logs_hashes ); validate_incrementing_counters_within_range( counter_start, counter_end, public_inputs.unencrypted_logs_hashes, - self.array_lengths.unencrypted_logs_hashes, + self.array_lengths.unencrypted_logs_hashes ); validate_incrementing_counter_ranges_within_range( counter_start, counter_end, public_inputs.private_call_requests, - self.array_lengths.private_call_requests, + self.array_lengths.private_call_requests ); // Validate the public call requests by checking their start counters only, as their end counters are unknown. @@ -348,22 +287,21 @@ impl PrivateCallDataValidator { counter_start, counter_end, public_inputs.public_call_requests, - self.array_lengths.public_call_requests, + self.array_lengths.public_call_requests ); - let teardown_call_request_count = if public_inputs.public_teardown_call_request.counter == 0 - { - 0 - } else { - 1 - }; - validate_incrementing_counters_within_range( - counter_start, - counter_end, - [public_inputs.public_teardown_call_request], - teardown_call_request_count, - ); - } + let teardown_call_request_count = if public_inputs.public_teardown_call_request.counter == 0 { + 0 + } else { + 1 + }; + validate_incrementing_counters_within_range( + counter_start, + counter_end, + [public_inputs.public_teardown_call_request], + teardown_call_request_count + ); + } fn validate_note_logs(self, accumulated_note_hashes: [ScopedNoteHash; N]) { let note_logs = self.data.public_inputs.note_encrypted_logs_hashes; @@ -377,20 +315,16 @@ impl PrivateCallDataValidator { let note_index = unsafe { find_index_hint( accumulated_note_hashes, - |n: ScopedNoteHash| n.counter() == note_log.note_hash_counter, + |n: ScopedNoteHash| n.counter() == note_log.note_hash_counter ) }; assert(note_index != N, "could not find note hash linked to note log"); assert_eq( - note_log.note_hash_counter, - accumulated_note_hashes[note_index].counter(), - "could not find note hash linked to note log", + note_log.note_hash_counter, accumulated_note_hashes[note_index].counter(), "could not find note hash linked to note log" ); // If the note_index points to an empty note hash, the following check will fail. assert_eq( - accumulated_note_hashes[note_index].contract_address, - contract_address, - "could not link a note log to a note hash in another contract", + accumulated_note_hashes[note_index].contract_address, contract_address, "could not link a note log to a note hash in another contract" ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/find_first_revertible_item_index.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/find_first_revertible_item_index.nr index 8651114f4a2..e85754258f2 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/find_first_revertible_item_index.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/find_first_revertible_item_index.nr @@ -2,11 +2,10 @@ use dep::types::{abis::side_effect::Ordered, traits::Empty, utils::arrays::array pub unconstrained fn find_first_revertible_item_index( min_revertible_side_effect_counter: u32, - items: [T; N], + items: [T; N] ) -> u32 where - T: Ordered + Empty + Eq, -{ + T: Ordered + Empty + Eq, { let mut index = N; for i in 0..N { let item = items[i]; @@ -39,7 +38,7 @@ mod tests { let index = unsafe { find_first_revertible_item_index( private_call.min_revertible_side_effect_counter, - private_call.private_call_requests, + private_call.private_call_requests ) }; assert_eq(index, expected); diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/validate_contract_address.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/validate_contract_address.nr index 8d0eec386ed..d96536d7766 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/validate_contract_address.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/validate_contract_address.nr @@ -1,19 +1,15 @@ use dep::types::{ abis::private_kernel::private_call_data::PrivateCallData, address::AztecAddress, constants::MAX_PROTOCOL_CONTRACTS, hash::stdlib_recursion_verification_key_compress_native_vk, - merkle_tree::root::root_from_sibling_path, + merkle_tree::root::root_from_sibling_path }; -pub fn validate_contract_address( - private_call_data: PrivateCallData, - protocol_contract_tree_root: Field, -) { +pub fn validate_contract_address(private_call_data: PrivateCallData, protocol_contract_tree_root: Field) { let contract_address = private_call_data.public_inputs.call_context.contract_address; assert(!contract_address.is_zero(), "contract address cannot be zero"); // TODO(https://github.com/AztecProtocol/aztec-packages/issues/3062): Why is this using a hash function from the stdlib::recursion namespace - let private_call_vk_hash = - stdlib_recursion_verification_key_compress_native_vk(private_call_data.vk); + let private_call_vk_hash = stdlib_recursion_verification_key_compress_native_vk(private_call_data.vk); let computed_address = AztecAddress::compute_from_private_function( private_call_data.public_inputs.call_context.function_selector, @@ -22,25 +18,22 @@ pub fn validate_contract_address( private_call_data.contract_class_artifact_hash, private_call_data.contract_class_public_bytecode_commitment, private_call_data.salted_initialization_hash, - private_call_data.public_keys.hash(), + private_call_data.public_keys.hash() ); let protocol_contract_index = contract_address.to_field(); - let computed_protocol_contract_tree_root = if (MAX_PROTOCOL_CONTRACTS as Field).lt( - protocol_contract_index, - ) { + let computed_protocol_contract_tree_root = if (MAX_PROTOCOL_CONTRACTS as Field).lt(protocol_contract_index) { 0 } else { root_from_sibling_path( computed_address.to_field(), protocol_contract_index, - private_call_data.protocol_contract_sibling_path, + private_call_data.protocol_contract_sibling_path ) }; assert( computed_address.eq(contract_address) - | computed_protocol_contract_tree_root.eq(protocol_contract_tree_root), - "computed contract address does not match expected one", + | computed_protocol_contract_tree_root.eq(protocol_contract_tree_root), "computed contract address does not match expected one" ); } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/validate_split_ranges.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/validate_split_ranges.nr index b1fb0854863..3790edaa61b 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/validate_split_ranges.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_call_data_validator/validate_split_ranges.nr @@ -4,24 +4,21 @@ pub fn validate_split_ranges( min_revertible_side_effect_counter: u32, first_revertible_item_index: u32, items: [T; N], - num_items: u32, + num_items: u32 ) where - T: RangeOrdered, -{ + T: RangeOrdered, { if first_revertible_item_index != 0 { let last_non_revertible_item_index = first_revertible_item_index - 1; let item = items[last_non_revertible_item_index]; assert( - min_revertible_side_effect_counter > item.counter_end(), - "min_revertible_side_effect_counter must be greater than the end counter of the last non revertible item", + min_revertible_side_effect_counter > item.counter_end(), "min_revertible_side_effect_counter must be greater than the end counter of the last non revertible item" ); } if first_revertible_item_index != num_items { let item = items[first_revertible_item_index]; assert( - min_revertible_side_effect_counter <= item.counter_start(), - "min_revertible_side_effect_counter must be less than or equal to the start counter of the first revertible item", + min_revertible_side_effect_counter <= item.counter_start(), "min_revertible_side_effect_counter must be less than or equal to the start counter of the first revertible item" ); } } @@ -62,7 +59,7 @@ mod tests { self.private_call.min_revertible_side_effect_counter, self.first_revertible_private_call_request_index, self.private_call.private_call_requests.storage, - self.private_call.private_call_requests.len(), + self.private_call.private_call_requests.len() ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_kernel_circuit_output_validator.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_kernel_circuit_output_validator.nr index fcc7ed1819e..9fa956e45f3 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_kernel_circuit_output_validator.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_kernel_circuit_output_validator.nr @@ -1,17 +1,15 @@ use crate::components::private_kernel_circuit_public_inputs_composer::create_first_nullifier; use dep::types::{ abis::{ - kernel_circuit_public_inputs::{ - PrivateKernelCircuitPublicInputs, PrivateKernelCircuitPublicInputsArrayLengths, - }, max_block_number::MaxBlockNumber, - private_circuit_public_inputs::{ - PrivateCircuitPublicInputs, PrivateCircuitPublicInputsArrayLengths, - }, - }, address::AztecAddress, traits::is_empty, transaction::tx_request::TxRequest, + kernel_circuit_public_inputs::{PrivateKernelCircuitPublicInputs, PrivateKernelCircuitPublicInputsArrayLengths}, + max_block_number::MaxBlockNumber, + private_circuit_public_inputs::{PrivateCircuitPublicInputs, PrivateCircuitPublicInputsArrayLengths} +}, + address::AztecAddress, traits::is_empty, transaction::tx_request::TxRequest, utils::arrays::{ - assert_array_appended, assert_array_appended_reversed, assert_array_appended_scoped, - assert_array_prepended, - }, + assert_array_appended, assert_array_appended_reversed, assert_array_appended_scoped, + assert_array_prepended +} }; pub struct PrivateKernelCircuitOutputValidator { @@ -29,13 +27,13 @@ impl PrivateKernelCircuitOutputValidator { private_call: PrivateCircuitPublicInputs, private_call_array_lengths: PrivateCircuitPublicInputsArrayLengths, vk_tree_root: Field, - protocol_contract_tree_root: Field, + protocol_contract_tree_root: Field ) { self.validate_initial_values( tx_request, private_call, vk_tree_root, - protocol_contract_tree_root, + protocol_contract_tree_root ); let mut offsets = PrivateKernelCircuitPublicInputsArrayLengths::empty(); offsets.nullifiers = 1; // The first nullifier is not propagated from the private call. @@ -43,7 +41,7 @@ impl PrivateKernelCircuitOutputValidator { private_call, private_call_array_lengths, offsets, - 0, // num_popped_call + 0 // num_popped_call ); } @@ -52,18 +50,15 @@ impl PrivateKernelCircuitOutputValidator { previous_kernel: PrivateKernelCircuitPublicInputs, previous_kernel_array_lengths: PrivateKernelCircuitPublicInputsArrayLengths, private_call: PrivateCircuitPublicInputs, - private_call_array_lengths: PrivateCircuitPublicInputsArrayLengths, + private_call_array_lengths: PrivateCircuitPublicInputsArrayLengths ) { self.validate_aggregated_values(previous_kernel, private_call); - self.validate_propagated_from_previous_kernel( - previous_kernel, - previous_kernel_array_lengths, - ); + self.validate_propagated_from_previous_kernel(previous_kernel, previous_kernel_array_lengths); self.validate_propagated_from_private_call( private_call, private_call_array_lengths, previous_kernel_array_lengths, - 1, // num_popped_call + 1 // num_popped_call ); } @@ -72,49 +67,34 @@ impl PrivateKernelCircuitOutputValidator { tx_request: TxRequest, private_call: PrivateCircuitPublicInputs, vk_tree_root: Field, - protocol_contract_tree_root: Field, + protocol_contract_tree_root: Field ) { // Constants. assert_eq(self.output.constants.tx_context, tx_request.tx_context, "mismatch tx_context"); assert_eq( - self.output.constants.historical_header, - private_call.historical_header, - "mismatch historical_header", - ); - assert( - is_empty(self.output.constants.global_variables), - "constants.global_variables must be empty", + self.output.constants.historical_header, private_call.historical_header, "mismatch historical_header" ); + assert(is_empty(self.output.constants.global_variables), "constants.global_variables must be empty"); assert_eq(self.output.constants.vk_tree_root, vk_tree_root, "mismatch vk_tree_root"); assert_eq( - self.output.constants.protocol_contract_tree_root, - protocol_contract_tree_root, - "mismatch protocol_contract_tree_root", + self.output.constants.protocol_contract_tree_root, protocol_contract_tree_root, "mismatch protocol_contract_tree_root" ); // First nullifier. let first_nullifier = create_first_nullifier(tx_request); assert_eq( - self.output.end.nullifiers[0], - first_nullifier, - "first nullifier must be the tx request nullifier", + self.output.end.nullifiers[0], first_nullifier, "first nullifier must be the tx request nullifier" ); // Others. assert_eq( - self.output.min_revertible_side_effect_counter, - private_call.min_revertible_side_effect_counter, - "incorrect initial min_revertible_side_effect_counter", + self.output.min_revertible_side_effect_counter, private_call.min_revertible_side_effect_counter, "incorrect initial min_revertible_side_effect_counter" ); assert_eq( - self.output.validation_requests.for_rollup.max_block_number, - private_call.max_block_number, - "incorrect initial max_block_number", + self.output.validation_requests.for_rollup.max_block_number, private_call.max_block_number, "incorrect initial max_block_number" ); assert_eq( - self.output.public_teardown_call_request, - private_call.public_teardown_call_request, - "incorrect initial public_teardown_call_request", + self.output.public_teardown_call_request, private_call.public_teardown_call_request, "incorrect initial public_teardown_call_request" ); let initial_fee_payer = if private_call.is_fee_payer { private_call.call_context.contract_address @@ -127,53 +107,41 @@ impl PrivateKernelCircuitOutputValidator { fn validate_aggregated_values( self, previous_kernel: PrivateKernelCircuitPublicInputs, - private_call: PrivateCircuitPublicInputs, + private_call: PrivateCircuitPublicInputs ) { // min_revertible_side_effect_counter - let propagated_min_revertible_counter = if previous_kernel - .min_revertible_side_effect_counter - != 0 { + let propagated_min_revertible_counter = if previous_kernel.min_revertible_side_effect_counter != 0 { assert( - private_call.min_revertible_side_effect_counter == 0, - "cannot overwrite min_revertible_side_effect_counter", + private_call.min_revertible_side_effect_counter == 0, "cannot overwrite min_revertible_side_effect_counter" ); previous_kernel.min_revertible_side_effect_counter } else { private_call.min_revertible_side_effect_counter }; assert_eq( - self.output.min_revertible_side_effect_counter, - propagated_min_revertible_counter, - "incorrect output min_revertible_side_effect_counter", + self.output.min_revertible_side_effect_counter, propagated_min_revertible_counter, "incorrect output min_revertible_side_effect_counter" ); // max_block_number let max_block_number = MaxBlockNumber::min( previous_kernel.validation_requests.for_rollup.max_block_number, - private_call.max_block_number, + private_call.max_block_number ); assert_eq( - self.output.validation_requests.for_rollup.max_block_number, - max_block_number, - "incorrect output max_block_number", + self.output.validation_requests.for_rollup.max_block_number, max_block_number, "incorrect output max_block_number" ); // public_teardown_call_request - let propagated_public_teardown_call_request = if !is_empty( - previous_kernel.public_teardown_call_request, - ) { + let propagated_public_teardown_call_request = if !is_empty(previous_kernel.public_teardown_call_request) { assert( - is_empty(private_call.public_teardown_call_request), - "cannot overwrite public_teardown_call_request", + is_empty(private_call.public_teardown_call_request), "cannot overwrite public_teardown_call_request" ); previous_kernel.public_teardown_call_request } else { private_call.public_teardown_call_request }; assert_eq( - self.output.public_teardown_call_request, - propagated_public_teardown_call_request, - "incorrect output public_teardown_call_request", + self.output.public_teardown_call_request, propagated_public_teardown_call_request, "incorrect output public_teardown_call_request" ); // fee_payer @@ -191,72 +159,70 @@ impl PrivateKernelCircuitOutputValidator { fn validate_propagated_from_previous_kernel( self, previous_kernel: PrivateKernelCircuitPublicInputs, - array_lengths: PrivateKernelCircuitPublicInputsArrayLengths, + array_lengths: PrivateKernelCircuitPublicInputsArrayLengths ) { assert_eq(self.output.constants, previous_kernel.constants, "mismatch constants"); assert_eq( - self.output.validation_requests.split_counter, - previous_kernel.validation_requests.split_counter, - "mismatch validation requests split counter", + self.output.validation_requests.split_counter, previous_kernel.validation_requests.split_counter, "mismatch validation requests split counter" ); assert_array_prepended( self.output.validation_requests.note_hash_read_requests, previous_kernel.validation_requests.note_hash_read_requests, - array_lengths.note_hash_read_requests, + array_lengths.note_hash_read_requests ); assert_array_prepended( self.output.validation_requests.nullifier_read_requests, previous_kernel.validation_requests.nullifier_read_requests, - array_lengths.nullifier_read_requests, + array_lengths.nullifier_read_requests ); assert_array_prepended( self.output.validation_requests.scoped_key_validation_requests_and_generators, previous_kernel.validation_requests.scoped_key_validation_requests_and_generators, - array_lengths.scoped_key_validation_requests_and_generators, + array_lengths.scoped_key_validation_requests_and_generators ); assert_array_prepended( self.output.end.note_hashes, previous_kernel.end.note_hashes, - array_lengths.note_hashes, + array_lengths.note_hashes ); assert_array_prepended( self.output.end.nullifiers, previous_kernel.end.nullifiers, - array_lengths.nullifiers, + array_lengths.nullifiers ); assert_array_prepended( self.output.end.l2_to_l1_msgs, previous_kernel.end.l2_to_l1_msgs, - array_lengths.l2_to_l1_msgs, + array_lengths.l2_to_l1_msgs ); assert_array_prepended( self.output.end.note_encrypted_logs_hashes, previous_kernel.end.note_encrypted_logs_hashes, - array_lengths.note_encrypted_logs_hashes, + array_lengths.note_encrypted_logs_hashes ); assert_array_prepended( self.output.end.encrypted_logs_hashes, previous_kernel.end.encrypted_logs_hashes, - array_lengths.encrypted_logs_hashes, + array_lengths.encrypted_logs_hashes ); assert_array_prepended( self.output.end.unencrypted_logs_hashes, previous_kernel.end.unencrypted_logs_hashes, - array_lengths.unencrypted_logs_hashes, + array_lengths.unencrypted_logs_hashes ); assert_array_prepended( self.output.end.public_call_requests, previous_kernel.end.public_call_requests, - array_lengths.public_call_requests, + array_lengths.public_call_requests ); // array_lengths.private_call_stack is guaranteed to be greater than 0. // It's checked in private_kernel_inner when comparing the top item in the stack with the current private call. assert_array_prepended( self.output.end.private_call_stack, previous_kernel.end.private_call_stack, - array_lengths.private_call_stack - 1, // Do not copy the top item in the stack. + array_lengths.private_call_stack - 1 // Do not copy the top item in the stack. ); } @@ -265,7 +231,7 @@ impl PrivateKernelCircuitOutputValidator { private_call: PrivateCircuitPublicInputs, array_lengths: PrivateCircuitPublicInputsArrayLengths, offsets: PrivateKernelCircuitPublicInputsArrayLengths, - num_popped_call: u32, + num_popped_call: u32 ) { let contract_address = private_call.call_context.contract_address; assert_array_appended_scoped( @@ -273,74 +239,74 @@ impl PrivateKernelCircuitOutputValidator { private_call.note_hash_read_requests, array_lengths.note_hash_read_requests, offsets.note_hash_read_requests, - contract_address, + contract_address ); assert_array_appended_scoped( self.output.validation_requests.nullifier_read_requests, private_call.nullifier_read_requests, array_lengths.nullifier_read_requests, offsets.nullifier_read_requests, - contract_address, + contract_address ); assert_array_appended_scoped( self.output.validation_requests.scoped_key_validation_requests_and_generators, private_call.key_validation_requests_and_generators, array_lengths.key_validation_requests_and_generators, offsets.scoped_key_validation_requests_and_generators, - contract_address, + contract_address ); assert_array_appended_scoped( self.output.end.note_hashes, private_call.note_hashes, array_lengths.note_hashes, offsets.note_hashes, - contract_address, + contract_address ); assert_array_appended_scoped( self.output.end.nullifiers, private_call.nullifiers, array_lengths.nullifiers, offsets.nullifiers, - contract_address, + contract_address ); assert_array_appended_scoped( self.output.end.l2_to_l1_msgs, private_call.l2_to_l1_msgs, array_lengths.l2_to_l1_msgs, offsets.l2_to_l1_msgs, - contract_address, + contract_address ); assert_array_appended( self.output.end.note_encrypted_logs_hashes, private_call.note_encrypted_logs_hashes, array_lengths.note_encrypted_logs_hashes, - offsets.note_encrypted_logs_hashes, + offsets.note_encrypted_logs_hashes ); assert_array_appended_scoped( self.output.end.encrypted_logs_hashes, private_call.encrypted_logs_hashes, array_lengths.encrypted_logs_hashes, offsets.encrypted_logs_hashes, - contract_address, + contract_address ); assert_array_appended_scoped( self.output.end.unencrypted_logs_hashes, private_call.unencrypted_logs_hashes, array_lengths.unencrypted_logs_hashes, offsets.unencrypted_logs_hashes, - contract_address, + contract_address ); assert_array_appended( self.output.end.public_call_requests, private_call.public_call_requests, array_lengths.public_call_requests, - offsets.public_call_requests, + offsets.public_call_requests ); assert_array_appended_reversed( self.output.end.private_call_stack, private_call.private_call_requests, array_lengths.private_call_requests, - offsets.private_call_stack - num_popped_call, + offsets.private_call_stack - num_popped_call ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_kernel_circuit_public_inputs_composer.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_kernel_circuit_public_inputs_composer.nr index 67cfffefe28..6e78ee43235 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_kernel_circuit_public_inputs_composer.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/private_kernel_circuit_public_inputs_composer.nr @@ -1,12 +1,12 @@ use dep::types::{ abis::{ - combined_constant_data::CombinedConstantData, - kernel_circuit_public_inputs::{ - PrivateKernelCircuitPublicInputs, PrivateKernelCircuitPublicInputsBuilder, - }, max_block_number::MaxBlockNumber, nullifier::{Nullifier, ScopedNullifier}, - private_circuit_public_inputs::PrivateCircuitPublicInputs, - }, address::AztecAddress, traits::is_empty, transaction::tx_request::TxRequest, - utils::arrays::{array_length, array_to_bounded_vec, sort_by_counter_asc, sort_by_counter_desc}, + combined_constant_data::CombinedConstantData, + kernel_circuit_public_inputs::{PrivateKernelCircuitPublicInputs, PrivateKernelCircuitPublicInputsBuilder}, + max_block_number::MaxBlockNumber, nullifier::{Nullifier, ScopedNullifier}, + private_circuit_public_inputs::PrivateCircuitPublicInputs +}, + address::AztecAddress, traits::is_empty, transaction::tx_request::TxRequest, + utils::arrays::{array_length, array_to_bounded_vec, sort_by_counter_asc, sort_by_counter_desc} }; pub fn create_first_nullifier(tx_request: TxRequest) -> ScopedNullifier { @@ -22,7 +22,7 @@ impl PrivateKernelCircuitPublicInputsComposer { tx_request: TxRequest, private_call_public_inputs: PrivateCircuitPublicInputs, vk_tree_root: Field, - protocol_contract_tree_root: Field, + protocol_contract_tree_root: Field ) -> Self { let mut public_inputs = PrivateKernelCircuitPublicInputsBuilder::empty(); @@ -42,9 +42,7 @@ impl PrivateKernelCircuitPublicInputsComposer { PrivateKernelCircuitPublicInputsComposer { public_inputs } } - pub fn new_from_previous_kernel( - previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs, - ) -> Self { + pub fn new_from_previous_kernel(previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs) -> Self { let mut public_inputs = PrivateKernelCircuitPublicInputsBuilder::empty(); public_inputs.constants = previous_kernel_public_inputs.constants; @@ -85,10 +83,7 @@ impl PrivateKernelCircuitPublicInputsComposer { *self } - pub fn with_private_call( - &mut self, - private_call_public_inputs: PrivateCircuitPublicInputs, - ) -> Self { + pub fn with_private_call(&mut self, private_call_public_inputs: PrivateCircuitPublicInputs) -> Self { self.propagate_from_private_call(private_call_public_inputs); *self } @@ -123,14 +118,10 @@ impl PrivateKernelCircuitPublicInputsComposer { self.propagate_min_revertible_side_effect_counter(private_call); } - fn propagate_min_revertible_side_effect_counter( - &mut self, - private_call: PrivateCircuitPublicInputs, - ) { + fn propagate_min_revertible_side_effect_counter(&mut self, private_call: PrivateCircuitPublicInputs) { if self.public_inputs.min_revertible_side_effect_counter != 0 { assert( - private_call.min_revertible_side_effect_counter == 0, - "cannot overwrite non-zero min_revertible_side_effect_counter", + private_call.min_revertible_side_effect_counter == 0, "cannot overwrite non-zero min_revertible_side_effect_counter" ); } else { self.public_inputs.min_revertible_side_effect_counter = @@ -151,9 +142,7 @@ impl PrivateKernelCircuitPublicInputsComposer { for i in 0..read_requests.len() { let request = read_requests[i]; if !is_empty(request) { - self.public_inputs.validation_requests.note_hash_read_requests.push(request.scope( - private_call.call_context.contract_address, - )); + self.public_inputs.validation_requests.note_hash_read_requests.push(request.scope(private_call.call_context.contract_address)); } } } @@ -163,24 +152,17 @@ impl PrivateKernelCircuitPublicInputsComposer { for i in 0..nullifier_read_requests.len() { let request = nullifier_read_requests[i]; if !is_empty(request) { - self.public_inputs.validation_requests.nullifier_read_requests.push(request.scope( - private_call.call_context.contract_address, - )); + self.public_inputs.validation_requests.nullifier_read_requests.push(request.scope(private_call.call_context.contract_address)); } } } fn propagate_key_validation_requests(&mut self, private_call: PrivateCircuitPublicInputs) { - let key_validation_requests_and_generators = - private_call.key_validation_requests_and_generators; + let key_validation_requests_and_generators = private_call.key_validation_requests_and_generators; for i in 0..key_validation_requests_and_generators.len() { let request = key_validation_requests_and_generators[i]; if !is_empty(request) { - self - .public_inputs - .validation_requests - .scoped_key_validation_requests_and_generators - .push(request.scope(private_call.call_context.contract_address)); + self.public_inputs.validation_requests.scoped_key_validation_requests_and_generators.push(request.scope(private_call.call_context.contract_address)); } } } @@ -190,9 +172,7 @@ impl PrivateKernelCircuitPublicInputsComposer { for i in 0..note_hashes.len() { let note_hash = note_hashes[i]; if note_hash.value != 0 { - self.public_inputs.end.note_hashes.push(note_hash.scope( - private_call.call_context.contract_address, - )); + self.public_inputs.end.note_hashes.push(note_hash.scope(private_call.call_context.contract_address)); } } } @@ -202,9 +182,7 @@ impl PrivateKernelCircuitPublicInputsComposer { for i in 0..nullifiers.len() { let nullifier = nullifiers[i]; if nullifier.value != 0 { - self.public_inputs.end.nullifiers.push(nullifier.scope( - private_call.call_context.contract_address, - )); + self.public_inputs.end.nullifiers.push(nullifier.scope(private_call.call_context.contract_address)); } } } @@ -214,9 +192,7 @@ impl PrivateKernelCircuitPublicInputsComposer { for i in 0..l2_to_l1_msgs.len() { let msg = l2_to_l1_msgs[i]; if !is_empty(msg) { - self.public_inputs.end.l2_to_l1_msgs.push(msg.scope( - private_call.call_context.contract_address, - )); + self.public_inputs.end.l2_to_l1_msgs.push(msg.scope(private_call.call_context.contract_address)); } } } @@ -226,9 +202,7 @@ impl PrivateKernelCircuitPublicInputsComposer { for i in 0..encrypted_logs.len() { let log = encrypted_logs[i]; if !is_empty(log) { - self.public_inputs.end.encrypted_logs_hashes.push(log.scope( - private_call.call_context.contract_address, - )); + self.public_inputs.end.encrypted_logs_hashes.push(log.scope(private_call.call_context.contract_address)); } } @@ -236,9 +210,7 @@ impl PrivateKernelCircuitPublicInputsComposer { for i in 0..unencrypted_logs.len() { let log = unencrypted_logs[i]; if !is_empty(log) { - self.public_inputs.end.unencrypted_logs_hashes.push(log.scope( - private_call.call_context.contract_address, - )); + self.public_inputs.end.unencrypted_logs_hashes.push(log.scope(private_call.call_context.contract_address)); } } @@ -275,8 +247,7 @@ impl PrivateKernelCircuitPublicInputsComposer { let call_request = private_call.public_teardown_call_request; if !is_empty(call_request) { assert( - is_empty(self.public_inputs.public_teardown_call_request), - "Public teardown call request already set", + is_empty(self.public_inputs.public_teardown_call_request), "Public teardown call request already set" ); self.public_inputs.public_teardown_call_request = call_request; } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer.nr index 747f6594245..d2c2975838f 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer.nr @@ -6,15 +6,16 @@ use crate::components::reset_output_composer::reset_output_hints::generate_reset use dep::reset_kernel_lib::{TransientDataIndexHint, PrivateValidationRequestProcessor}; use dep::types::{ abis::{ - kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, - log_hash::{NoteLogHash, ScopedEncryptedLogHash}, note_hash::ScopedNoteHash, - nullifier::ScopedNullifier, - }, address::AztecAddress, + kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, + log_hash::{NoteLogHash, ScopedEncryptedLogHash}, note_hash::ScopedNoteHash, + nullifier::ScopedNullifier +}, + address::AztecAddress, constants::{ - MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASHES_PER_TX, - MAX_NULLIFIERS_PER_TX, - }, hash::{mask_encrypted_log_hash, silo_note_hash, silo_nullifier}, - utils::arrays::sort_by_counter_asc, + MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASHES_PER_TX, + MAX_NULLIFIERS_PER_TX +}, + hash::{mask_encrypted_log_hash, silo_note_hash, silo_nullifier}, utils::arrays::sort_by_counter_asc }; pub struct ResetOutputComposer { @@ -33,7 +34,7 @@ impl Self { let hints = generate_reset_output_hints(previous_kernel, transient_data_index_hints); ResetOutputComposer { @@ -42,7 +43,7 @@ impl [ScopedNoteHash; MAX_NOTE_HASHES_PER_TX] { + unconstrained fn get_sorted_siloed_note_hashes(self) -> [ScopedNoteHash; MAX_NOTE_HASHES_PER_TX] { let mut note_hashes = sort_by_counter_asc(self.hints.kept_note_hashes); let first_nullifier = self.previous_kernel.end.nullifiers[0].value(); for i in 0..note_hashes.len() { @@ -90,9 +89,7 @@ impl [ScopedNullifier; MAX_NULLIFIERS_PER_TX] { + unconstrained fn get_sorted_siloed_nullifiers(self) -> [ScopedNullifier; MAX_NULLIFIERS_PER_TX] { let mut nullifiers = sort_by_counter_asc(self.hints.kept_nullifiers); for i in 0..nullifiers.len() { nullifiers[i].nullifier.value = silo_nullifier(nullifiers[i]); @@ -101,9 +98,7 @@ impl [NoteLogHash; MAX_NOTE_ENCRYPTED_LOGS_PER_TX] { + unconstrained fn get_sorted_note_encrypted_log_hashes(self) -> [NoteLogHash; MAX_NOTE_ENCRYPTED_LOGS_PER_TX] { let mut log_hashes = sort_by_counter_asc(self.hints.kept_note_encrypted_log_hashes); for i in 0..log_hashes.len() { log_hashes[i].note_hash_counter = 0; @@ -111,9 +106,7 @@ impl [ScopedEncryptedLogHash; MAX_ENCRYPTED_LOGS_PER_TX] { + unconstrained fn get_sorted_masked_encrypted_log_hashes(self) -> [ScopedEncryptedLogHash; MAX_ENCRYPTED_LOGS_PER_TX] { let mut log_hashes = sort_by_counter_asc(self.previous_kernel.end.encrypted_logs_hashes); for i in 0..log_hashes.len() { log_hashes[i].contract_address = mask_encrypted_log_hash(log_hashes[i]); diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer/reset_output_hints.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer/reset_output_hints.nr index 9a669dd1701..10dedc2a4af 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer/reset_output_hints.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer/reset_output_hints.nr @@ -3,18 +3,19 @@ mod squash_transient_data; use crate::components::reset_output_composer::reset_output_hints::{ get_transient_or_propagated_note_hash_indexes_for_logs::get_transient_or_propagated_note_hash_indexes_for_logs, - squash_transient_data::squash_transient_data, + squash_transient_data::squash_transient_data }; use dep::reset_kernel_lib::TransientDataIndexHint; use dep::types::{ abis::{ - kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, log_hash::NoteLogHash, - note_hash::ScopedNoteHash, nullifier::ScopedNullifier, - }, + kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, log_hash::NoteLogHash, + note_hash::ScopedNoteHash, nullifier::ScopedNullifier +}, constants::{ - MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASHES_PER_TX, - MAX_NULLIFIERS_PER_TX, - }, utils::arrays::{OrderHint, get_order_hints_asc}, + MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASHES_PER_TX, + MAX_NULLIFIERS_PER_TX +}, + utils::arrays::{OrderHint, get_order_hints_asc} }; pub struct ResetOutputHints { @@ -34,38 +35,32 @@ pub struct ResetOutputHints { pub unconstrained fn generate_reset_output_hints( previous_kernel: PrivateKernelCircuitPublicInputs, - transient_data_index_hints: [TransientDataIndexHint; NUM_TRANSIENT_DATA_INDEX_HINTS], + transient_data_index_hints: [TransientDataIndexHint; NUM_TRANSIENT_DATA_INDEX_HINTS] ) -> ResetOutputHints { let (kept_note_hashes, kept_nullifiers, kept_note_encrypted_log_hashes) = squash_transient_data( previous_kernel.end.note_hashes, previous_kernel.end.nullifiers, previous_kernel.end.note_encrypted_logs_hashes, - transient_data_index_hints, + transient_data_index_hints ); // note_hashes - let sorted_note_hash_indexes = - get_order_hints_asc(kept_note_hashes).map(|h: OrderHint| h.sorted_index); + let sorted_note_hash_indexes = get_order_hints_asc(kept_note_hashes).map(|h: OrderHint| h.sorted_index); // nullifiers - let sorted_nullifier_indexes = - get_order_hints_asc(kept_nullifiers).map(|h: OrderHint| h.sorted_index); + let sorted_nullifier_indexes = get_order_hints_asc(kept_nullifiers).map(|h: OrderHint| h.sorted_index); // note_encrypted_log_hashes - let sorted_note_encrypted_log_hash_indexes = - get_order_hints_asc(kept_note_encrypted_log_hashes).map(|h: OrderHint| h.sorted_index); + let sorted_note_encrypted_log_hash_indexes = get_order_hints_asc(kept_note_encrypted_log_hashes).map(|h: OrderHint| h.sorted_index); let transient_or_propagated_note_hash_indexes_for_logs = get_transient_or_propagated_note_hash_indexes_for_logs( previous_kernel.end.note_encrypted_logs_hashes, previous_kernel.end.note_hashes, kept_note_hashes, - transient_data_index_hints, + transient_data_index_hints ); // encrypted_log_hashes - let sorted_encrypted_log_hash_indexes = get_order_hints_asc( - previous_kernel.end.encrypted_logs_hashes, - ) - .map(|h: OrderHint| h.sorted_index); + let sorted_encrypted_log_hash_indexes = get_order_hints_asc(previous_kernel.end.encrypted_logs_hashes).map(|h: OrderHint| h.sorted_index); ResetOutputHints { kept_note_hashes, @@ -75,6 +70,6 @@ pub unconstrained fn generate_reset_output_hints( note_logs: [NoteLogHash; NUM_LOGS], note_hashes: [ScopedNoteHash; NUM_NOTE_HASHES], expected_note_hashes: [ScopedNoteHash; NUM_NOTE_HASHES], - transient_data_index_hints: [TransientDataIndexHint; NUM_INDEX_HINTS], + transient_data_index_hints: [TransientDataIndexHint; NUM_INDEX_HINTS] ) -> [u32; NUM_LOGS] { let mut indexes = [0; NUM_LOGS]; for i in 0..note_logs.len() { diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer/reset_output_hints/squash_transient_data.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer/reset_output_hints/squash_transient_data.nr index f6f17f626d2..6f8848b71db 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer/reset_output_hints/squash_transient_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/reset_output_composer/reset_output_hints/squash_transient_data.nr @@ -1,13 +1,11 @@ use dep::reset_kernel_lib::TransientDataIndexHint; -use dep::types::abis::{ - note_hash::ScopedNoteHash, nullifier::ScopedNullifier, log_hash::NoteLogHash, -}; +use dep::types::abis::{note_hash::ScopedNoteHash, nullifier::ScopedNullifier, log_hash::NoteLogHash}; pub unconstrained fn squash_transient_data( note_hashes: [ScopedNoteHash; M], nullifiers: [ScopedNullifier; N], logs: [NoteLogHash; P], - transient_data_index_hints: [TransientDataIndexHint; NUM_TRANSIENT_DATA_INDEX_HINTS], + transient_data_index_hints: [TransientDataIndexHint; NUM_TRANSIENT_DATA_INDEX_HINTS] ) -> ([ScopedNoteHash; M], [ScopedNullifier; N], [NoteLogHash; P]) { let mut transient_nullifier_indexes_for_note_hashes = [N; M]; let mut transient_note_hash_indexes_for_nullifiers = [M; N]; @@ -37,9 +35,11 @@ pub unconstrained fn squash_transient_data { @@ -33,7 +30,7 @@ impl Self { ResetOutputValidator { output, @@ -43,7 +40,7 @@ impl Self { - let mut output_composer = - PrivateKernelCircuitPublicInputsComposer::new_from_previous_kernel(previous_kernel); + let mut output_composer = PrivateKernelCircuitPublicInputsComposer::new_from_previous_kernel(previous_kernel); output_composer.sort_ordered_values(); TailOutputComposer { output_composer } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_composer/meter_gas_used.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_composer/meter_gas_used.nr index cbe17a44eb0..350c9d69f7f 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_composer/meter_gas_used.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_composer/meter_gas_used.nr @@ -1,12 +1,10 @@ use dep::types::{ abis::{ - accumulated_data::combined_accumulated_data::CombinedAccumulatedData, gas::Gas, - gas_settings::GasSettings, - }, - constants::{ - DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, L2_GAS_PER_NOTE_HASH, L2_GAS_PER_NULLIFIER, - L2_GAS_PER_LOG_BYTE, - }, utils::arrays::array_length, + accumulated_data::combined_accumulated_data::CombinedAccumulatedData, gas::Gas, + gas_settings::GasSettings +}, + constants::{DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, L2_GAS_PER_NOTE_HASH, L2_GAS_PER_NULLIFIER, L2_GAS_PER_LOG_BYTE}, + utils::arrays::array_length }; pub fn meter_gas_used(data: CombinedAccumulatedData, gas_settings: GasSettings) -> Gas { diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_validator.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_validator.nr index 87b11475ae8..2feaac1c511 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_validator.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_validator.nr @@ -2,14 +2,15 @@ mod tail_output_hints; use crate::components::{ tail_output_composer::meter_gas_used::meter_gas_used, - tail_output_validator::tail_output_hints::{generate_tail_output_hints, TailOutputHints}, + tail_output_validator::tail_output_hints::{generate_tail_output_hints, TailOutputHints} }; use dep::types::{ abis::{ - kernel_circuit_public_inputs::{KernelCircuitPublicInputs, PrivateKernelCircuitPublicInputs}, - log_hash::{NoteLogHash, ScopedEncryptedLogHash, ScopedLogHash}, - }, messaging::l2_to_l1_message::ScopedL2ToL1Message, traits::is_empty, - utils::arrays::assert_exposed_sorted_transformed_value_array, + kernel_circuit_public_inputs::{KernelCircuitPublicInputs, PrivateKernelCircuitPublicInputs}, + log_hash::{NoteLogHash, ScopedEncryptedLogHash, ScopedLogHash} +}, + messaging::l2_to_l1_message::ScopedL2ToL1Message, traits::is_empty, + utils::arrays::assert_exposed_sorted_transformed_value_array }; pub struct TailOutputValidator { @@ -21,9 +22,11 @@ pub struct TailOutputValidator { impl TailOutputValidator { pub fn new( output: KernelCircuitPublicInputs, - previous_kernel: PrivateKernelCircuitPublicInputs, + previous_kernel: PrivateKernelCircuitPublicInputs ) -> Self { - let hints = unsafe { generate_tail_output_hints(previous_kernel) }; + let hints = unsafe { + generate_tail_output_hints(previous_kernel) + }; TailOutputValidator { output, previous_kernel, hints } } @@ -43,9 +46,7 @@ impl TailOutputValidator { assert_eq(self.output.constants, self.previous_kernel.constants, "mismatch constants"); assert_eq( - self.output.rollup_validation_requests, - self.previous_kernel.validation_requests.for_rollup, - "mismatch rollup_validation_requests", + self.output.rollup_validation_requests, self.previous_kernel.validation_requests.for_rollup, "mismatch rollup_validation_requests" ); assert_eq(self.output.fee_payer, self.previous_kernel.fee_payer, "mismatch fee_payer"); @@ -53,11 +54,7 @@ impl TailOutputValidator { // note_hashes let note_hashes = self.previous_kernel.end.note_hashes; for i in 0..note_hashes.len() { - assert_eq( - note_hashes[i].value(), - self.output.end.note_hashes[i], - "mismatch note_hashes", - ); + assert_eq(note_hashes[i].value(), self.output.end.note_hashes[i], "mismatch note_hashes"); } // nullifiers @@ -68,20 +65,20 @@ impl TailOutputValidator { // note_encrypted_logs_hashes assert_eq( - self.previous_kernel.end.note_encrypted_logs_hashes.map(|log: NoteLogHash| { + self.previous_kernel.end.note_encrypted_logs_hashes.map( + |log: NoteLogHash| { log.expose_to_public() - }), - self.output.end.note_encrypted_logs_hashes, - "mismatch note_encrypted_logs_hashes", + } + ), self.output.end.note_encrypted_logs_hashes, "mismatch note_encrypted_logs_hashes" ); // encrypted_logs_hashes assert_eq( - self.previous_kernel.end.encrypted_logs_hashes.map(|log: ScopedEncryptedLogHash| { + self.previous_kernel.end.encrypted_logs_hashes.map( + |log: ScopedEncryptedLogHash| { log.expose_to_public() - }), - self.output.end.encrypted_logs_hashes, - "mismatch encrypted_logs_hashes", + } + ), self.output.end.encrypted_logs_hashes, "mismatch encrypted_logs_hashes" ); } @@ -91,7 +88,7 @@ impl TailOutputValidator { self.previous_kernel.end.l2_to_l1_msgs, self.output.end.l2_to_l1_msgs, |prev: ScopedL2ToL1Message, out: ScopedL2ToL1Message| out == prev.expose_to_public(), - self.hints.sorted_l2_to_l1_msg_hints, + self.hints.sorted_l2_to_l1_msg_hints ); // unencrypted_log_hashes @@ -99,14 +96,14 @@ impl TailOutputValidator { self.previous_kernel.end.unencrypted_logs_hashes, self.output.end.unencrypted_logs_hashes, |prev: ScopedLogHash, out: ScopedLogHash| out == prev.expose_to_public(), - self.hints.sorted_unencrypted_log_hash_hints, + self.hints.sorted_unencrypted_log_hash_hints ); } fn validate_gas_used(self) { let gas_used = meter_gas_used( self.output.end, - self.output.constants.tx_context.gas_settings, + self.output.constants.tx_context.gas_settings ); assert(self.output.end.gas_used == gas_used, "incorrect metered gas used"); diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_validator/tail_output_hints.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_validator/tail_output_hints.nr index 171a5547035..beecc52bc9f 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_validator/tail_output_hints.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_output_validator/tail_output_hints.nr @@ -1,7 +1,7 @@ use dep::types::{ abis::{kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, log_hash::ScopedLogHash}, constants::{MAX_L2_TO_L1_MSGS_PER_TX, MAX_UNENCRYPTED_LOGS_PER_TX}, - utils::arrays::{OrderHint, sort_by_counter_asc, get_order_hints_asc}, + utils::arrays::{OrderHint, sort_by_counter_asc, get_order_hints_asc} }; pub struct TailOutputHints { @@ -12,21 +12,13 @@ pub struct TailOutputHints { sorted_unencrypted_log_hash_hints: [OrderHint; MAX_UNENCRYPTED_LOGS_PER_TX], } -pub unconstrained fn generate_tail_output_hints( - previous_kernel: PrivateKernelCircuitPublicInputs, -) -> TailOutputHints { +pub unconstrained fn generate_tail_output_hints(previous_kernel: PrivateKernelCircuitPublicInputs) -> TailOutputHints { // l2_to_l1_msgs let sorted_l2_to_l1_msg_hints = get_order_hints_asc(previous_kernel.end.l2_to_l1_msgs); // unencrypted_logs - let sorted_unencrypted_log_hashes = - sort_by_counter_asc(previous_kernel.end.unencrypted_logs_hashes); - let sorted_unencrypted_log_hash_hints = - get_order_hints_asc(previous_kernel.end.unencrypted_logs_hashes); + let sorted_unencrypted_log_hashes = sort_by_counter_asc(previous_kernel.end.unencrypted_logs_hashes); + let sorted_unencrypted_log_hash_hints = get_order_hints_asc(previous_kernel.end.unencrypted_logs_hashes); - TailOutputHints { - sorted_l2_to_l1_msg_hints, - sorted_unencrypted_log_hashes, - sorted_unencrypted_log_hash_hints, - } + TailOutputHints { sorted_l2_to_l1_msg_hints, sorted_unencrypted_log_hashes, sorted_unencrypted_log_hash_hints } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer.nr index 241256003e7..568ce3e745d 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer.nr @@ -4,14 +4,13 @@ mod split_to_public; use crate::components::{ private_kernel_circuit_public_inputs_composer::PrivateKernelCircuitPublicInputsComposer, tail_to_public_output_composer::{ - meter_gas_used::{meter_gas_used_non_revertible, meter_gas_used_revertible}, - split_to_public::split_to_public, - }, + meter_gas_used::{meter_gas_used_non_revertible, meter_gas_used_revertible}, + split_to_public::split_to_public +} }; use dep::types::abis::{ - kernel_circuit_public_inputs::{ - PrivateKernelCircuitPublicInputs, PublicKernelCircuitPublicInputs, - }, validation_requests::PublicValidationRequests, + kernel_circuit_public_inputs::{PrivateKernelCircuitPublicInputs, PublicKernelCircuitPublicInputs}, + validation_requests::PublicValidationRequests }; pub struct TailToPublicOutputComposer { @@ -20,8 +19,7 @@ pub struct TailToPublicOutputComposer { impl TailToPublicOutputComposer { pub unconstrained fn new(previous_kernel: PrivateKernelCircuitPublicInputs) -> Self { - let mut output_composer = - PrivateKernelCircuitPublicInputsComposer::new_from_previous_kernel(previous_kernel); + let mut output_composer = PrivateKernelCircuitPublicInputsComposer::new_from_previous_kernel(previous_kernel); output_composer.sort_ordered_values(); TailToPublicOutputComposer { output_composer } @@ -40,8 +38,7 @@ impl TailToPublicOutputComposer { source.public_teardown_call_request.expose_to_public(); output.fee_payer = source.fee_payer; - let mut (end_non_revertible, end) = - split_to_public(source.end, source.min_revertible_side_effect_counter); + let mut (end_non_revertible, end) = split_to_public(source.end, source.min_revertible_side_effect_counter); end_non_revertible.gas_used = meter_gas_used_non_revertible(end_non_revertible); let teardown_gas = source.constants.tx_context.gas_settings.teardown_gas_limits; end.gas_used = meter_gas_used_revertible(end, teardown_gas); diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer/meter_gas_used.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer/meter_gas_used.nr index cc56b9bac00..0f3d2a7183a 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer/meter_gas_used.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer/meter_gas_used.nr @@ -1,9 +1,10 @@ use dep::types::{ abis::{accumulated_data::PublicAccumulatedData, gas::Gas, log_hash::{LogHash, ScopedLogHash}}, constants::{ - DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, FIXED_AVM_STARTUP_L2_GAS, L2_GAS_PER_NOTE_HASH, - L2_GAS_PER_NULLIFIER, L2_GAS_PER_LOG_BYTE, - }, utils::arrays::array_length, + DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, FIXED_AVM_STARTUP_L2_GAS, L2_GAS_PER_NOTE_HASH, + L2_GAS_PER_NULLIFIER, L2_GAS_PER_LOG_BYTE +}, + utils::arrays::array_length }; fn meter_gas_used(data: PublicAccumulatedData) -> Gas { @@ -20,18 +21,15 @@ fn meter_gas_used(data: PublicAccumulatedData) -> Gas { metered_da_bytes += array_length(data.l2_to_l1_msgs) * DA_BYTES_PER_FIELD; - let note_encrypted_log_preimages_length = - data.note_encrypted_logs_hashes.fold(0, |len, l: LogHash| len + l.length); + let note_encrypted_log_preimages_length = data.note_encrypted_logs_hashes.fold(0, |len, l: LogHash| len + l.length); metered_da_bytes += note_encrypted_log_preimages_length as u32; metered_l2_gas += note_encrypted_log_preimages_length as u32 * L2_GAS_PER_LOG_BYTE; - let encrypted_log_preimages_length = - data.encrypted_logs_hashes.fold(0, |len, l: ScopedLogHash| len + l.log_hash.length); + let encrypted_log_preimages_length = data.encrypted_logs_hashes.fold(0, |len, l: ScopedLogHash| len + l.log_hash.length); metered_da_bytes += encrypted_log_preimages_length as u32; metered_l2_gas += encrypted_log_preimages_length as u32 * L2_GAS_PER_LOG_BYTE; - let unencrypted_log_preimages_length = - data.unencrypted_logs_hashes.fold(0, |len, l: ScopedLogHash| len + l.log_hash.length); + let unencrypted_log_preimages_length = data.unencrypted_logs_hashes.fold(0, |len, l: ScopedLogHash| len + l.log_hash.length); metered_da_bytes += unencrypted_log_preimages_length as u32; metered_l2_gas += unencrypted_log_preimages_length as u32 * L2_GAS_PER_LOG_BYTE; diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer/split_to_public.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer/split_to_public.nr index 702e6a330da..8c99a893db6 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer/split_to_public.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_composer/split_to_public.nr @@ -1,12 +1,12 @@ use dep::types::abis::accumulated_data::{ private_accumulated_data_builder::PrivateAccumulatedDataBuilder, public_accumulated_data::PublicAccumulatedData, - public_accumulated_data_builder::PublicAccumulatedDataBuilder, + public_accumulated_data_builder::PublicAccumulatedDataBuilder }; pub unconstrained fn split_to_public( data: PrivateAccumulatedDataBuilder, - min_revertible_side_effect_counter: u32, + min_revertible_side_effect_counter: u32 ) -> (PublicAccumulatedData, PublicAccumulatedData) { let mut non_revertible_builder = PublicAccumulatedDataBuilder::empty(); let mut revertible_builder = PublicAccumulatedDataBuilder::empty(); diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_validator.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_validator.nr index 2a80338180d..bbb1058d44f 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_validator.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_validator.nr @@ -1,25 +1,20 @@ mod tail_to_public_output_hints; use crate::components::{ - tail_to_public_output_composer::meter_gas_used::{ - meter_gas_used_non_revertible, meter_gas_used_revertible, - }, - tail_to_public_output_validator::tail_to_public_output_hints::{ - generate_tail_to_public_output_hints, TailToPublicOutputHints, - }, + tail_to_public_output_composer::meter_gas_used::{meter_gas_used_non_revertible, meter_gas_used_revertible}, + tail_to_public_output_validator::tail_to_public_output_hints::{generate_tail_to_public_output_hints, TailToPublicOutputHints} }; use dep::types::{ abis::{ - kernel_circuit_public_inputs::{ - PrivateKernelCircuitPublicInputs, PublicKernelCircuitPublicInputs, - }, log_hash::{LogHash, ScopedEncryptedLogHash, NoteLogHash, ScopedLogHash}, - note_hash::ScopedNoteHash, nullifier::{Nullifier, ScopedNullifier}, - public_call_request::PublicCallRequest, - }, messaging::l2_to_l1_message::ScopedL2ToL1Message, traits::is_empty_array, + kernel_circuit_public_inputs::{PrivateKernelCircuitPublicInputs, PublicKernelCircuitPublicInputs}, + log_hash::{LogHash, ScopedEncryptedLogHash, NoteLogHash, ScopedLogHash}, note_hash::ScopedNoteHash, + nullifier::{Nullifier, ScopedNullifier}, public_call_request::PublicCallRequest +}, + messaging::l2_to_l1_message::ScopedL2ToL1Message, traits::is_empty_array, utils::arrays::{ - assert_split_sorted_transformed_value_arrays_asc, - assert_split_sorted_transformed_value_arrays_desc, assert_split_transformed_value_arrays, - }, + assert_split_sorted_transformed_value_arrays_asc, assert_split_sorted_transformed_value_arrays_desc, + assert_split_transformed_value_arrays +} }; pub struct TailToPublicOutputValidator { @@ -31,9 +26,11 @@ pub struct TailToPublicOutputValidator { impl TailToPublicOutputValidator { pub fn new( output: PublicKernelCircuitPublicInputs, - previous_kernel: PrivateKernelCircuitPublicInputs, + previous_kernel: PrivateKernelCircuitPublicInputs ) -> Self { - let hints = unsafe { generate_tail_to_public_output_hints(previous_kernel) }; + let hints = unsafe { + generate_tail_to_public_output_hints(previous_kernel) + }; TailToPublicOutputValidator { output, previous_kernel, hints } } @@ -49,22 +46,18 @@ impl TailToPublicOutputValidator { assert_eq(self.output.revert_code, 0, "revert_code must be empty"); assert( - is_empty_array(self.output.end_non_revertible.public_data_update_requests), - "non-revertible public_data_update_requests must be empty", + is_empty_array(self.output.end_non_revertible.public_data_update_requests), "non-revertible public_data_update_requests must be empty" ); assert( - is_empty_array(self.output.end.public_data_update_requests), - "revertible public_data_update_requests must be empty", + is_empty_array(self.output.end.public_data_update_requests), "revertible public_data_update_requests must be empty" ); // public_data_update_requests assert( - is_empty_array(self.output.end_non_revertible.public_data_update_requests), - "unexpected non-revertible public_data_update_requests", + is_empty_array(self.output.end_non_revertible.public_data_update_requests), "unexpected non-revertible public_data_update_requests" ); assert( - is_empty_array(self.output.end.public_data_update_requests), - "unexpected revertible public_data_update_requests", + is_empty_array(self.output.end.public_data_update_requests), "unexpected revertible public_data_update_requests" ); } @@ -72,17 +65,13 @@ impl TailToPublicOutputValidator { assert_eq(self.output.constants, self.previous_kernel.constants, "mismatch constants"); assert_eq( - self.output.validation_requests.for_rollup, - self.previous_kernel.validation_requests.for_rollup, - "mismatch rollup_validation_requests", + self.output.validation_requests.for_rollup, self.previous_kernel.validation_requests.for_rollup, "mismatch rollup_validation_requests" ); assert_eq(self.output.fee_payer, self.previous_kernel.fee_payer, "mismatch fee_payer"); assert_eq( - self.output.public_teardown_call_request, - self.previous_kernel.public_teardown_call_request.expose_to_public(), - "mismatch public_teardown_call_request", + self.output.public_teardown_call_request, self.previous_kernel.public_teardown_call_request.expose_to_public(), "mismatch public_teardown_call_request" ); } @@ -98,7 +87,7 @@ impl TailToPublicOutputValidator { output_non_revertible.note_hashes, output_revertible.note_hashes, |prev: ScopedNoteHash, out: ScopedNoteHash| out == prev.expose_to_public(), - split_counter, + split_counter ); // nullifiers @@ -107,7 +96,7 @@ impl TailToPublicOutputValidator { output_non_revertible.nullifiers, output_revertible.nullifiers, |prev: ScopedNullifier, out: Nullifier| out == prev.expose_to_public(), - split_counter, + split_counter ); // note_encrypted_logs_hashes @@ -116,7 +105,7 @@ impl TailToPublicOutputValidator { output_non_revertible.note_encrypted_logs_hashes, output_revertible.note_encrypted_logs_hashes, |prev: NoteLogHash, out: LogHash| out == prev.expose_to_public(), - split_counter, + split_counter ); // encrypted_logs_hashes @@ -125,7 +114,7 @@ impl TailToPublicOutputValidator { output_non_revertible.encrypted_logs_hashes, output_revertible.encrypted_logs_hashes, |prev: ScopedEncryptedLogHash, out: ScopedLogHash| out == prev.expose_to_public(), - split_counter, + split_counter ); } @@ -143,7 +132,7 @@ impl TailToPublicOutputValidator { split_counter, output_non_revertible.l2_to_l1_msgs, output_revertible.l2_to_l1_msgs, - hints.sorted_l2_to_l1_msg_hints, + hints.sorted_l2_to_l1_msg_hints ); // unencrypted_logs_hashes @@ -153,7 +142,7 @@ impl TailToPublicOutputValidator { split_counter, output_non_revertible.unencrypted_logs_hashes, output_revertible.unencrypted_logs_hashes, - hints.sorted_unencrypted_log_hash_hints, + hints.sorted_unencrypted_log_hash_hints ); // public_call_requests @@ -163,20 +152,19 @@ impl TailToPublicOutputValidator { split_counter, output_non_revertible.public_call_stack, output_revertible.public_call_stack, - hints.sorted_public_call_request_hints, + hints.sorted_public_call_request_hints ) } fn validate_gas_used(self) { let gas_used = meter_gas_used_non_revertible(self.output.end_non_revertible); assert( - self.output.end_non_revertible.gas_used == gas_used, - "incorrect metered non-revertible gas used", + self.output.end_non_revertible.gas_used == gas_used, "incorrect metered non-revertible gas used" ); let gas_used = meter_gas_used_revertible( self.output.end, - self.output.constants.tx_context.gas_settings.teardown_gas_limits, + self.output.constants.tx_context.gas_settings.teardown_gas_limits ); assert(self.output.end.gas_used == gas_used, "incorrect metered revertible gas used"); diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_validator/tail_to_public_output_hints.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_validator/tail_to_public_output_hints.nr index f46f0af3422..43550df1ea6 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_validator/tail_to_public_output_hints.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/components/tail_to_public_output_validator/tail_to_public_output_hints.nr @@ -1,8 +1,7 @@ use dep::types::{ abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, - constants::{ - MAX_L2_TO_L1_MSGS_PER_TX, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, MAX_UNENCRYPTED_LOGS_PER_TX, - }, utils::arrays::{get_split_order_hints_asc, get_split_order_hints_desc, SplitOrderHints}, + constants::{MAX_L2_TO_L1_MSGS_PER_TX, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, MAX_UNENCRYPTED_LOGS_PER_TX}, + utils::arrays::{get_split_order_hints_asc, get_split_order_hints_desc, SplitOrderHints} }; pub struct TailToPublicOutputHints { @@ -14,26 +13,17 @@ pub struct TailToPublicOutputHints { sorted_public_call_request_hints: SplitOrderHints, } -pub unconstrained fn generate_tail_to_public_output_hints( - previous_kernel: PrivateKernelCircuitPublicInputs, -) -> TailToPublicOutputHints { +pub unconstrained fn generate_tail_to_public_output_hints(previous_kernel: PrivateKernelCircuitPublicInputs) -> TailToPublicOutputHints { let split_counter = previous_kernel.min_revertible_side_effect_counter; // l2_to_l1_msgss - let sorted_l2_to_l1_msg_hints = - get_split_order_hints_asc(previous_kernel.end.l2_to_l1_msgs, split_counter); + let sorted_l2_to_l1_msg_hints = get_split_order_hints_asc(previous_kernel.end.l2_to_l1_msgs, split_counter); // unencrypted_logs - let sorted_unencrypted_log_hash_hints = - get_split_order_hints_asc(previous_kernel.end.unencrypted_logs_hashes, split_counter); + let sorted_unencrypted_log_hash_hints = get_split_order_hints_asc(previous_kernel.end.unencrypted_logs_hashes, split_counter); // public_call_requests - let sorted_public_call_request_hints = - get_split_order_hints_desc(previous_kernel.end.public_call_requests, split_counter); + let sorted_public_call_request_hints = get_split_order_hints_desc(previous_kernel.end.public_call_requests, split_counter); - TailToPublicOutputHints { - sorted_l2_to_l1_msg_hints, - sorted_unencrypted_log_hash_hints, - sorted_public_call_request_hints, - } + TailToPublicOutputHints { sorted_l2_to_l1_msg_hints, sorted_unencrypted_log_hash_hints, sorted_public_call_request_hints } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_empty.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_empty.nr index e13bee75379..2456ea79062 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_empty.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_empty.nr @@ -1,9 +1,6 @@ use dep::types::{ header::Header, KernelCircuitPublicInputs, traits::Empty, - recursion::{ - verification_key::{VerificationKey, HonkVerificationKey}, proof::RecursiveProof, - traits::Verifiable, - }, + recursion::{verification_key::{VerificationKey, HonkVerificationKey}, proof::RecursiveProof, traits::Verifiable} }; pub struct EmptyNestedCircuitPublicInputs { @@ -55,15 +52,13 @@ impl Empty for PrivateKernelEmptyPrivateInputs { chain_id: 0, version: 0, vk_tree_root: 0, - protocol_contract_tree_root: 0, + protocol_contract_tree_root: 0 } } } mod tests { - use crate::private_kernel_empty::{ - PrivateKernelEmptyPrivateInputs, EmptyNestedCircuitPublicInputs, - }; + use crate::private_kernel_empty::{PrivateKernelEmptyPrivateInputs, EmptyNestedCircuitPublicInputs}; use dep::types::header::Header; #[test] @@ -74,7 +69,7 @@ mod tests { chain_id: 1, version: 2, vk_tree_root: 3, - protocol_contract_tree_root: 4, + protocol_contract_tree_root: 4 }; let public_inputs = private_inputs.execute(); assert_eq(public_inputs.constants.tx_context.chain_id, 1); diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_init.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_init.nr index d794b3f92af..00214931551 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_init.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_init.nr @@ -1,14 +1,15 @@ use crate::components::{ private_call_data_validator::PrivateCallDataValidator, private_kernel_circuit_output_validator::PrivateKernelCircuitOutputValidator, - private_kernel_circuit_public_inputs_composer::PrivateKernelCircuitPublicInputsComposer, + private_kernel_circuit_public_inputs_composer::PrivateKernelCircuitPublicInputsComposer }; use dep::types::{ abis::{ - kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, - private_kernel::private_call_data::{PrivateCallData, PrivateCallDataWithoutPublicInputs}, - private_circuit_public_inputs::PrivateCircuitPublicInputs, - }, transaction::tx_request::TxRequest, + kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, + private_kernel::private_call_data::{PrivateCallData, PrivateCallDataWithoutPublicInputs}, + private_circuit_public_inputs::PrivateCircuitPublicInputs +}, + transaction::tx_request::TxRequest }; // Initialization struct for private inputs to the private kernel @@ -25,13 +26,13 @@ impl PrivateKernelInitCircuitPrivateInputs { vk_tree_root: Field, protocol_contract_tree_root: Field, private_call: PrivateCallDataWithoutPublicInputs, - app_public_inputs: PrivateCircuitPublicInputs, + app_public_inputs: PrivateCircuitPublicInputs ) -> Self { Self { tx_request, vk_tree_root, protocol_contract_tree_root, - private_call: private_call.to_private_call_data(app_public_inputs), + private_call: private_call.to_private_call_data(app_public_inputs) } } @@ -41,24 +42,21 @@ impl PrivateKernelInitCircuitPrivateInputs { self.tx_request, private_call_public_inputs, self.vk_tree_root, - self.protocol_contract_tree_root, - ) - .with_private_call(private_call_public_inputs) - .finish() + self.protocol_contract_tree_root + ).with_private_call(private_call_public_inputs).finish() } pub fn execute(self) -> PrivateKernelCircuitPublicInputs { // Generate output. - let output = unsafe { self.generate_output() }; + let output = unsafe { + self.generate_output() + }; // Validate inputs. let private_call_data_validator = PrivateCallDataValidator::new(self.private_call); private_call_data_validator.validate_as_first_call(); private_call_data_validator.validate_against_tx_request(self.tx_request); - private_call_data_validator.validate( - output.end.note_hashes, - self.protocol_contract_tree_root, - ); + private_call_data_validator.validate(output.end.note_hashes, self.protocol_contract_tree_root); // Validate output. if dep::types::validate::should_validate_output() { @@ -67,7 +65,7 @@ impl PrivateKernelInitCircuitPrivateInputs { self.private_call.public_inputs, private_call_data_validator.array_lengths, self.vk_tree_root, - self.protocol_contract_tree_root, + self.protocol_contract_tree_root ); } output @@ -79,7 +77,7 @@ mod tests { use dep::types::{ abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, tests::{fixture_builder::FixtureBuilder, utils::assert_array_eq}, - transaction::tx_request::TxRequest, + transaction::tx_request::TxRequest }; struct PrivateKernelInitInputsBuilder { @@ -100,9 +98,8 @@ mod tests { tx_request: self.tx_request, private_call, vk_tree_root: FixtureBuilder::vk_tree_root(), - protocol_contract_tree_root: 0, - } - .execute() + protocol_contract_tree_root: 0 + }.execute() } } @@ -121,11 +118,11 @@ mod tests { let public_inputs = builder.execute(); assert_array_eq( public_inputs.validation_requests.note_hash_read_requests, - [note_hash_read_requests[0], note_hash_read_requests[1]], + [note_hash_read_requests[0], note_hash_read_requests[1]] ); assert_array_eq( public_inputs.end.encrypted_logs_hashes, - [encrypted_log_hashes[0]], + [encrypted_log_hashes[0]] ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_inner.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_inner.nr index 40321bb4cb1..e9502463ae6 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_inner.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_inner.nr @@ -2,17 +2,16 @@ use crate::components::{ previous_kernel_validator::PreviousKernelValidator, private_call_data_validator::PrivateCallDataValidator, private_kernel_circuit_output_validator::PrivateKernelCircuitOutputValidator, - private_kernel_circuit_public_inputs_composer::PrivateKernelCircuitPublicInputsComposer, + private_kernel_circuit_public_inputs_composer::PrivateKernelCircuitPublicInputsComposer }; use dep::types::{ abis::{ - kernel_circuit_public_inputs::{ - PrivateKernelCircuitPublicInputs, PrivateKernelCircuitPublicInputsArrayLengths, - }, private_kernel_data::{PrivateKernelData, PrivateKernelDataWithoutPublicInputs}, - private_kernel::private_call_data::{PrivateCallData, PrivateCallDataWithoutPublicInputs}, - private_circuit_public_inputs::PrivateCircuitPublicInputs, - }, - constants::{PRIVATE_KERNEL_INIT_INDEX, PRIVATE_KERNEL_INNER_INDEX, PRIVATE_KERNEL_RESET_INDEX}, + kernel_circuit_public_inputs::{PrivateKernelCircuitPublicInputs, PrivateKernelCircuitPublicInputsArrayLengths}, + private_kernel_data::{PrivateKernelData, PrivateKernelDataWithoutPublicInputs}, + private_kernel::private_call_data::{PrivateCallData, PrivateCallDataWithoutPublicInputs}, + private_circuit_public_inputs::PrivateCircuitPublicInputs +}, + constants::{PRIVATE_KERNEL_INIT_INDEX, PRIVATE_KERNEL_INNER_INDEX, PRIVATE_KERNEL_RESET_INDEX} }; global ALLOWED_PREVIOUS_CIRCUITS = @@ -28,44 +27,37 @@ impl PrivateKernelInnerCircuitPrivateInputs { previous_kernel: PrivateKernelDataWithoutPublicInputs, previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs, private_call: PrivateCallDataWithoutPublicInputs, - app_public_inputs: PrivateCircuitPublicInputs, + app_public_inputs: PrivateCircuitPublicInputs ) -> Self { Self { previous_kernel: previous_kernel.to_private_kernel_data(previous_kernel_public_inputs), - private_call: private_call.to_private_call_data(app_public_inputs), + private_call: private_call.to_private_call_data(app_public_inputs) } } unconstrained fn generate_output(self) -> PrivateKernelCircuitPublicInputs { - PrivateKernelCircuitPublicInputsComposer::new_from_previous_kernel( - self.previous_kernel.public_inputs, - ) - .pop_top_call_request() - .with_private_call(self.private_call.public_inputs) - .finish() + PrivateKernelCircuitPublicInputsComposer::new_from_previous_kernel(self.previous_kernel.public_inputs).pop_top_call_request().with_private_call(self.private_call.public_inputs).finish() } pub fn execute(self) -> PrivateKernelCircuitPublicInputs { // Generate output. - let output = unsafe { self.generate_output() }; + let output = unsafe { + self.generate_output() + }; // Validate inputs. let previous_kernel_validator = PreviousKernelValidator::new(self.previous_kernel); previous_kernel_validator.validate_proof(ALLOWED_PREVIOUS_CIRCUITS); let private_call_data_validator = PrivateCallDataValidator::new(self.private_call); - let previous_kernel_array_lengths = - PrivateKernelCircuitPublicInputsArrayLengths::new(self.previous_kernel.public_inputs); + let previous_kernel_array_lengths = PrivateKernelCircuitPublicInputsArrayLengths::new(self.previous_kernel.public_inputs); let private_call_stack_size = previous_kernel_array_lengths.private_call_stack; - let call_request = - self.previous_kernel.public_inputs.end.private_call_stack[private_call_stack_size - 1]; + let call_request = self.previous_kernel.public_inputs.end.private_call_stack[private_call_stack_size - 1]; private_call_data_validator.validate_against_call_request(call_request); - private_call_data_validator.validate_against_previous_kernel( - self.previous_kernel.public_inputs, - ); + private_call_data_validator.validate_against_previous_kernel(self.previous_kernel.public_inputs); private_call_data_validator.validate( output.end.note_hashes, - self.previous_kernel.public_inputs.constants.protocol_contract_tree_root, + self.previous_kernel.public_inputs.constants.protocol_contract_tree_root ); // Validate output. @@ -74,7 +66,7 @@ impl PrivateKernelInnerCircuitPrivateInputs { self.previous_kernel.public_inputs, previous_kernel_array_lengths, self.private_call.public_inputs, - private_call_data_validator.array_lengths, + private_call_data_validator.array_lengths ); } output @@ -82,13 +74,11 @@ impl PrivateKernelInnerCircuitPrivateInputs { } mod tests { - use crate::private_kernel_inner::{ - PrivateKernelInnerCircuitPrivateInputs, ALLOWED_PREVIOUS_CIRCUITS, - }; + use crate::private_kernel_inner::{PrivateKernelInnerCircuitPrivateInputs, ALLOWED_PREVIOUS_CIRCUITS}; use dep::types::{ abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, constants::{PRIVATE_KERNEL_INIT_INDEX, BASE_ROLLUP_INDEX}, - tests::{fixture_builder::FixtureBuilder, utils::assert_array_eq}, + tests::{fixture_builder::FixtureBuilder, utils::assert_array_eq} }; struct PrivateKernelInnerInputsBuilder { @@ -98,9 +88,7 @@ mod tests { impl PrivateKernelInnerInputsBuilder { pub fn new() -> Self { - let mut previous_kernel = FixtureBuilder::new_from_counter(15) - .in_vk_tree(PRIVATE_KERNEL_INIT_INDEX) - .as_parent_contract(); + let mut previous_kernel = FixtureBuilder::new_from_counter(15).in_vk_tree(PRIVATE_KERNEL_INIT_INDEX).as_parent_contract(); let private_call = FixtureBuilder::new_from_counter(200); // 0th nullifier must be non-zero. @@ -140,18 +128,18 @@ mod tests { assert_array_eq( public_inputs.validation_requests.note_hash_read_requests, [ - prev_note_hash_read_requests[0], - curr_note_hash_read_requests[0], - curr_note_hash_read_requests[1], - ], + prev_note_hash_read_requests[0], + curr_note_hash_read_requests[0], + curr_note_hash_read_requests[1] + ] ); assert_array_eq( public_inputs.end.encrypted_logs_hashes, [ - prev_encrypted_log_hashes[0], - prev_encrypted_log_hashes[1], - curr_encrypted_log_hashes[0], - ], + prev_encrypted_log_hashes[0], + prev_encrypted_log_hashes[1], + curr_encrypted_log_hashes[0] + ] ); } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_reset.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_reset.nr index d862f5c3eb0..d93b6f0ea40 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_reset.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_reset.nr @@ -1,16 +1,16 @@ use crate::components::{ previous_kernel_validator::PreviousKernelValidator, reset_output_composer::{ResetOutputComposer, ResetOutputHints}, - reset_output_validator::ResetOutputValidator, + reset_output_validator::ResetOutputValidator }; use dep::reset_kernel_lib::{ KeyValidationHint, NoteHashReadRequestHints, NullifierReadRequestHints, - PrivateValidationRequestProcessor, TransientDataIndexHint, + PrivateValidationRequestProcessor, TransientDataIndexHint }; use dep::types::{ abis::private_kernel_data::{PrivateKernelData, PrivateKernelDataWithoutPublicInputs}, constants::{PRIVATE_KERNEL_INIT_INDEX, PRIVATE_KERNEL_INNER_INDEX, PRIVATE_KERNEL_RESET_INDEX}, - PrivateKernelCircuitPublicInputs, + PrivateKernelCircuitPublicInputs }; global ALLOWED_PREVIOUS_CIRCUITS = @@ -33,12 +33,9 @@ impl, + hints: PrivateKernelResetHints ) -> Self { - Self { - previous_kernel: previous_kernel.to_private_kernel_data(previous_kernel_public_inputs), - hints, - } + Self { previous_kernel: previous_kernel.to_private_kernel_data(previous_kernel_public_inputs), hints } } unconstrained fn generate_output( @@ -46,7 +43,7 @@ impl, note_hash_siloing_amount: u32, nullifier_siloing_amount: u32, - encrypted_log_siloing_amount: u32, + encrypted_log_siloing_amount: u32 ) -> (PrivateKernelCircuitPublicInputs, ResetOutputHints) { let composer = ResetOutputComposer::new( self.previous_kernel.public_inputs, @@ -54,7 +51,7 @@ impl PrivateKernelCircuitPublicInputs { let previous_public_inputs = self.previous_kernel.public_inputs; let validation_request_processor = PrivateValidationRequestProcessor { validation_requests: previous_public_inputs.validation_requests, note_hash_read_request_hints: self.hints.note_hash_read_request_hints, pending_note_hashes: previous_public_inputs.end.note_hashes, - note_hash_tree_root: previous_public_inputs - .constants - .historical_header - .state - .partial - .note_hash_tree - .root, + note_hash_tree_root: previous_public_inputs.constants.historical_header.state.partial.note_hash_tree.root, nullifier_read_request_hints: self.hints.nullifier_read_request_hints, pending_nullifiers: previous_public_inputs.end.nullifiers, - nullifier_tree_root: previous_public_inputs - .constants - .historical_header - .state - .partial - .nullifier_tree - .root, + nullifier_tree_root: previous_public_inputs.constants.historical_header.state.partial.nullifier_tree.root, key_validation_hints: self.hints.key_validation_hints, - validation_requests_split_counter: self.hints.validation_requests_split_counter, + validation_requests_split_counter: self.hints.validation_requests_split_counter }; // Generate output. @@ -96,7 +81,7 @@ impl { @@ -169,15 +153,13 @@ mod tests { Self { previous_kernel, - transient_data_index_hints: [ - TransientDataIndexHint::nada(MAX_NULLIFIERS_PER_TX, MAX_NOTE_HASHES_PER_TX); 6 - ], + transient_data_index_hints: [TransientDataIndexHint::nada(MAX_NULLIFIERS_PER_TX, MAX_NOTE_HASHES_PER_TX); 6], note_hash_read_request_hints_builder: NoteHashReadRequestHintsBuilder::new(), nullifier_read_request_hints_builder: NullifierReadRequestHintsBuilder::new(), validation_requests_split_counter: 0, note_hash_siloing_amount: 0, nullifier_siloing_amount: 0, - encrypted_log_siloing_amount: 0, + encrypted_log_siloing_amount: 0 } } } @@ -191,8 +173,7 @@ mod tests { } pub fn add_pending_note_hash_read_request(&mut self, note_hash_index: u32) { - let read_request_index = - self.previous_kernel.add_read_request_for_pending_note_hash(note_hash_index); + let read_request_index = self.previous_kernel.add_read_request_for_pending_note_hash(note_hash_index); let hint_index = self.note_hash_read_request_hints_builder.pending_read_hints.len(); let hint = PendingReadHint { read_request_index, pending_value_index: note_hash_index }; self.note_hash_read_request_hints_builder.pending_read_hints.push(hint); @@ -202,8 +183,7 @@ mod tests { pub fn add_pending_nullifier_read_request(&mut self, nullifier_index_offset_one: u32) { let nullifier_index = nullifier_index_offset_one + 1; // + 1 is for the first nullifier - let read_request_index = - self.previous_kernel.add_read_request_for_pending_nullifier(nullifier_index); + let read_request_index = self.previous_kernel.add_read_request_for_pending_nullifier(nullifier_index); let hint_index = self.nullifier_read_request_hints_builder.pending_read_hints.len(); let hint = PendingReadHint { read_request_index, pending_value_index: nullifier_index }; self.nullifier_read_request_hints_builder.pending_read_hints.push(hint); @@ -218,17 +198,14 @@ mod tests { let num_hints = unsafe { find_index_hint( self.transient_data_index_hints, - |hint: TransientDataIndexHint| hint.nullifier_index == MAX_NULLIFIERS_PER_TX, + |hint: TransientDataIndexHint| hint.nullifier_index == MAX_NULLIFIERS_PER_TX ) }; self.transient_data_index_hints[num_hints] = TransientDataIndexHint { nullifier_index, note_hash_index }; } - pub fn compute_output_note_hashes( - self, - note_hashes: [ScopedNoteHash; N], - ) -> [ScopedNoteHash; N] { + pub fn compute_output_note_hashes(self, note_hashes: [ScopedNoteHash; N]) -> [ScopedNoteHash; N] { // First nullifier is tx hash. let tx_hash = self.previous_kernel.nullifiers.get_unchecked(0).value(); let mut output = note_hashes; @@ -239,10 +216,7 @@ mod tests { output } - pub fn compute_output_nullifiers( - _self: Self, - nullifiers: [ScopedNullifier; N], - ) -> [ScopedNullifier; N] { + pub fn compute_output_nullifiers(_self: Self, nullifiers: [ScopedNullifier; N]) -> [ScopedNullifier; N] { let mut output = nullifiers; for i in 1..N { output[i].nullifier.value = silo_nullifier(nullifiers[i]); @@ -251,10 +225,7 @@ mod tests { output } - pub fn compute_output_note_logs( - _self: Self, - logs: [NoteLogHash; N], - ) -> [NoteLogHash; N] { + pub fn compute_output_note_logs(_self: Self, logs: [NoteLogHash; N]) -> [NoteLogHash; N] { let mut output = logs; for i in 0..N { output[i].note_hash_counter = 0; @@ -264,7 +235,7 @@ mod tests { pub fn compute_output_encrypted_logs( _self: Self, - logs: [ScopedEncryptedLogHash; N], + logs: [ScopedEncryptedLogHash; N] ) -> [ScopedEncryptedLogHash; N] { let mut output = logs; for i in 0..N { @@ -275,28 +246,25 @@ mod tests { } pub fn execute(&mut self) -> PrivateKernelCircuitPublicInputs { - let note_hash_read_request_hints = - unsafe { self.note_hash_read_request_hints_builder.to_hints() }; - let nullifier_read_request_hints = - unsafe { self.nullifier_read_request_hints_builder.to_hints() }; + let note_hash_read_request_hints = unsafe { + self.note_hash_read_request_hints_builder.to_hints() + }; + let nullifier_read_request_hints = unsafe { + self.nullifier_read_request_hints_builder.to_hints() + }; let hints = PrivateKernelResetHints { note_hash_read_request_hints, nullifier_read_request_hints, - key_validation_hints: [ - KeyValidationHint::nada(MAX_KEY_VALIDATION_REQUESTS_PER_TX); 2 - ], + key_validation_hints: [KeyValidationHint::nada(MAX_KEY_VALIDATION_REQUESTS_PER_TX); 2], transient_data_index_hints: self.transient_data_index_hints, - validation_requests_split_counter: self.validation_requests_split_counter, + validation_requests_split_counter: self.validation_requests_split_counter }; - let kernel = PrivateKernelResetCircuitPrivateInputs { - previous_kernel: self.previous_kernel.to_private_kernel_data(), - hints, - }; + let kernel = PrivateKernelResetCircuitPrivateInputs { previous_kernel: self.previous_kernel.to_private_kernel_data(), hints }; kernel.execute( self.note_hash_siloing_amount, self.nullifier_siloing_amount, - self.encrypted_log_siloing_amount, + self.encrypted_log_siloing_amount ) } @@ -408,35 +376,25 @@ mod tests { builder.add_pending_nullifier_read_request(1); // Now add some read requests that will be propagated - let remaining_note_hash_rr_index = - builder.previous_kernel.add_read_request_for_pending_note_hash(1); - let note_hash_rr = - builder.previous_kernel.note_hash_read_requests.storage[remaining_note_hash_rr_index]; + let remaining_note_hash_rr_index = builder.previous_kernel.add_read_request_for_pending_note_hash(1); + let note_hash_rr = builder.previous_kernel.note_hash_read_requests.storage[remaining_note_hash_rr_index]; - let remaining_nullifier_rr_index = - builder.previous_kernel.add_read_request_for_pending_nullifier(1); - let nullifier_rr = - builder.previous_kernel.nullifier_read_requests.storage[remaining_nullifier_rr_index]; + let remaining_nullifier_rr_index = builder.previous_kernel.add_read_request_for_pending_nullifier(1); + let nullifier_rr = builder.previous_kernel.nullifier_read_requests.storage[remaining_nullifier_rr_index]; let key_validation_index = builder.previous_kernel.add_request_for_key_validation( Point { x: 1, y: 2, is_infinite: false }, 27, - GENERATOR_INDEX__OVSK_M as Field, + GENERATOR_INDEX__OVSK_M as Field ); - let key_validation = builder - .previous_kernel - .scoped_key_validation_requests_and_generators - .storage[key_validation_index]; + let key_validation = builder.previous_kernel.scoped_key_validation_requests_and_generators.storage[key_validation_index]; // Check that they have been propagated to the next kernel let result = builder.execute(); assert_eq(result.validation_requests.note_hash_read_requests[0], note_hash_rr); assert_eq(result.validation_requests.nullifier_read_requests[0], nullifier_rr); - assert_eq( - result.validation_requests.scoped_key_validation_requests_and_generators[0], - key_validation, - ); + assert_eq(result.validation_requests.scoped_key_validation_requests_and_generators[0], key_validation); } #[test] @@ -591,11 +549,7 @@ mod tests { swap_items(&mut builder.previous_kernel.note_hashes, 1, 0); swap_items(&mut builder.previous_kernel.note_hashes, 3, 2); swap_items(&mut builder.previous_kernel.nullifiers, 2, 3); - swap_items( - &mut builder.previous_kernel.note_encrypted_logs_hashes, - 1, - 3, - ); + swap_items(&mut builder.previous_kernel.note_encrypted_logs_hashes, 1, 3); swap_items(&mut builder.previous_kernel.encrypted_logs_hashes, 1, 2); // The nullifier at index 1 is nullifying the note hash at index 3 (original index 2). builder.nullify_pending_note_hash(1, 3); @@ -603,28 +557,27 @@ mod tests { let public_inputs = builder.execute(); // The note hash at index 2 is chopped. - let output_note_hashes = - builder.compute_output_note_hashes([note_hashes[0], note_hashes[1], note_hashes[3]]); + let output_note_hashes = builder.compute_output_note_hashes([note_hashes[0], note_hashes[1], note_hashes[3]]); assert_array_eq(public_inputs.end.note_hashes, output_note_hashes); // The nullifier at index 1 is chopped. - let output_nullifiers = - builder.compute_output_nullifiers([nullifiers[0], nullifiers[2], nullifiers[3]]); + let output_nullifiers = builder.compute_output_nullifiers([nullifiers[0], nullifiers[2], nullifiers[3]]); assert_array_eq(public_inputs.end.nullifiers, output_nullifiers); // The note log at index 2 is chopped. - let output_note_logs = - builder.compute_output_note_logs([note_logs[0], note_logs[1], note_logs[3]]); + let output_note_logs = builder.compute_output_note_logs([note_logs[0], note_logs[1], note_logs[3]]); assert_array_eq( public_inputs.end.note_encrypted_logs_hashes, - output_note_logs, + output_note_logs ); - let output_logs = builder.compute_output_encrypted_logs([ + let output_logs = builder.compute_output_encrypted_logs( + [ encrypted_logs[0], encrypted_logs[1], - encrypted_logs[2], - ]); + encrypted_logs[2] + ] + ); assert_array_eq(public_inputs.end.encrypted_logs_hashes, output_logs); } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_tail.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_tail.nr index d1fecb668cc..f7490f03b80 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_tail.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_tail.nr @@ -1,14 +1,14 @@ use crate::components::{ previous_kernel_validator::PreviousKernelValidator, tail_output_composer::TailOutputComposer, - tail_output_validator::TailOutputValidator, + tail_output_validator::TailOutputValidator }; use dep::types::{ abis::{ - private_kernel_data::{PrivateKernelData, PrivateKernelDataWithoutPublicInputs}, - kernel_circuit_public_inputs::KernelCircuitPublicInputs, - }, + private_kernel_data::{PrivateKernelData, PrivateKernelDataWithoutPublicInputs}, + kernel_circuit_public_inputs::KernelCircuitPublicInputs +}, constants::{PRIVATE_KERNEL_INIT_INDEX, PRIVATE_KERNEL_INNER_INDEX, PRIVATE_KERNEL_RESET_INDEX}, - PrivateKernelCircuitPublicInputs, + PrivateKernelCircuitPublicInputs }; global ALLOWED_PREVIOUS_CIRCUITS = @@ -21,11 +21,9 @@ pub struct PrivateKernelTailCircuitPrivateInputs { impl PrivateKernelTailCircuitPrivateInputs { pub fn new( previous_kernel: PrivateKernelDataWithoutPublicInputs, - previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs, + previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs ) -> Self { - Self { - previous_kernel: previous_kernel.to_private_kernel_data(previous_kernel_public_inputs), - } + Self { previous_kernel: previous_kernel.to_private_kernel_data(previous_kernel_public_inputs) } } unconstrained fn generate_output(self) -> KernelCircuitPublicInputs { @@ -34,7 +32,9 @@ impl PrivateKernelTailCircuitPrivateInputs { pub fn execute(self) -> KernelCircuitPublicInputs { // Generate output. - let output = unsafe { self.generate_output() }; + let output = unsafe { + self.generate_output() + }; // Validate inputs. let previous_kernel_validator = PreviousKernelValidator::new(self.previous_kernel); @@ -51,19 +51,18 @@ impl PrivateKernelTailCircuitPrivateInputs { } mod tests { - use crate::private_kernel_tail::{ - PrivateKernelTailCircuitPrivateInputs, ALLOWED_PREVIOUS_CIRCUITS, - }; + use crate::private_kernel_tail::{PrivateKernelTailCircuitPrivateInputs, ALLOWED_PREVIOUS_CIRCUITS}; use dep::types::constants::{ DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, GENERATOR_INDEX__IVSK_M, L2_GAS_PER_LOG_BYTE, - L2_GAS_PER_NULLIFIER, PRIVATE_KERNEL_INNER_INDEX, BASE_ROLLUP_INDEX, + L2_GAS_PER_NULLIFIER, PRIVATE_KERNEL_INNER_INDEX, BASE_ROLLUP_INDEX }; use dep::types::{ abis::{ - kernel_circuit_public_inputs::KernelCircuitPublicInputs, - max_block_number::MaxBlockNumber, gas::Gas, log_hash::ScopedLogHash, - }, address::{AztecAddress, EthAddress}, tests::fixture_builder::FixtureBuilder, - traits::is_empty, point::Point, + kernel_circuit_public_inputs::KernelCircuitPublicInputs, max_block_number::MaxBlockNumber, + gas::Gas, log_hash::ScopedLogHash + }, + address::{AztecAddress, EthAddress}, tests::fixture_builder::FixtureBuilder, traits::is_empty, + point::Point }; // TODO: Reduce the duplicated code/tests for PrivateKernelTailInputs and PrivateKernelTailToPublicInputs. @@ -81,9 +80,7 @@ mod tests { } pub fn execute(&mut self) -> KernelCircuitPublicInputs { - let kernel = PrivateKernelTailCircuitPrivateInputs { - previous_kernel: self.previous_kernel.to_private_kernel_data(), - }; + let kernel = PrivateKernelTailCircuitPrivateInputs { previous_kernel: self.previous_kernel.to_private_kernel_data() }; kernel.execute() } @@ -121,31 +118,21 @@ mod tests { let prev_encrypted_log_preimages_length = 13; let prev_unencrypted_logs_hash = 956; let prev_unencrypted_log_preimages_length = 24; - builder.previous_kernel.add_masked_encrypted_log_hash( - prev_encrypted_logs_hash, - prev_encrypted_log_preimages_length, - ); + builder.previous_kernel.add_masked_encrypted_log_hash(prev_encrypted_logs_hash, prev_encrypted_log_preimages_length); builder.previous_kernel.add_unencrypted_log_hash( prev_unencrypted_logs_hash, - prev_unencrypted_log_preimages_length, + prev_unencrypted_log_preimages_length ); // Logs for the current call stack. let unencrypted_logs_hash = 26; let unencrypted_log_preimages_length = 50; - builder.previous_kernel.add_unencrypted_log_hash( - unencrypted_logs_hash, - unencrypted_log_preimages_length, - ); + builder.previous_kernel.add_unencrypted_log_hash(unencrypted_logs_hash, unencrypted_log_preimages_length); let public_inputs = builder.execute(); + assert_eq(public_inputs.end.encrypted_log_preimages_length, prev_encrypted_log_preimages_length); assert_eq( - public_inputs.end.encrypted_log_preimages_length, - prev_encrypted_log_preimages_length, - ); - assert_eq( - public_inputs.end.unencrypted_log_preimages_length, - unencrypted_log_preimages_length + prev_unencrypted_log_preimages_length, + public_inputs.end.unencrypted_log_preimages_length, unencrypted_log_preimages_length + prev_unencrypted_log_preimages_length ); } @@ -168,11 +155,12 @@ mod tests { let resulting_encrypted_logs = public_inputs.end.unencrypted_logs_hashes; assert_eq( - resulting_encrypted_logs, - original_logs.map(|mut log: ScopedLogHash| { + resulting_encrypted_logs, original_logs.map( + |mut log: ScopedLogHash| { log.log_hash.counter = 0; log - }), + } + ) ); } @@ -226,7 +214,7 @@ mod tests { let _void = builder.previous_kernel.add_request_for_key_validation( Point { x: 1, y: 2, is_infinite: false }, 27, - GENERATOR_INDEX__IVSK_M as Field, + GENERATOR_INDEX__IVSK_M as Field ); builder.failed(); } @@ -241,12 +229,10 @@ mod tests { // teardown gas // tx overhead // tx nullifier (which has DA and L2 gas) - let expected_gas_consumed = Gas::new(300, 300) - + Gas::tx_overhead() - + Gas::new( - DA_GAS_PER_BYTE * DA_BYTES_PER_FIELD * 1, - L2_GAS_PER_NULLIFIER * 1, - ); + let expected_gas_consumed = Gas::new(300, 300) + Gas::tx_overhead() + Gas::new( + DA_GAS_PER_BYTE * DA_BYTES_PER_FIELD * 1, + L2_GAS_PER_NULLIFIER * 1 + ); assert_eq(public_inputs.end.gas_used, expected_gas_consumed); } @@ -262,12 +248,10 @@ mod tests { let public_inputs = builder.execute(); assert_eq( - Gas::tx_overhead() - + Gas::new( - 4 * DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE, - 1 * L2_GAS_PER_NULLIFIER, - ), - public_inputs.end.gas_used, + Gas::tx_overhead() + Gas::new( + 4 * DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE, + 1 * L2_GAS_PER_NULLIFIER + ), public_inputs.end.gas_used ); } @@ -284,12 +268,10 @@ mod tests { let public_inputs = builder.execute(); assert_eq( - Gas::tx_overhead() - + Gas::new( - (1 * DA_BYTES_PER_FIELD + 25) * DA_GAS_PER_BYTE, - 1 * L2_GAS_PER_NULLIFIER + 25 * L2_GAS_PER_LOG_BYTE, - ), - public_inputs.end.gas_used, + Gas::tx_overhead() + Gas::new( + (1 * DA_BYTES_PER_FIELD + 25) * DA_GAS_PER_BYTE, + 1 * L2_GAS_PER_NULLIFIER + 25 * L2_GAS_PER_LOG_BYTE + ), public_inputs.end.gas_used ); } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_tail_to_public.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_tail_to_public.nr index 93023d588c7..529d1a0f08d 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_tail_to_public.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/private_kernel_tail_to_public.nr @@ -1,15 +1,15 @@ use crate::components::{ previous_kernel_validator::PreviousKernelValidator, tail_to_public_output_composer::TailToPublicOutputComposer, - tail_to_public_output_validator::TailToPublicOutputValidator, + tail_to_public_output_validator::TailToPublicOutputValidator }; use dep::types::{ abis::{ - private_kernel_data::{PrivateKernelData, PrivateKernelDataWithoutPublicInputs}, - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - }, + private_kernel_data::{PrivateKernelData, PrivateKernelDataWithoutPublicInputs}, + kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs +}, constants::{PRIVATE_KERNEL_INIT_INDEX, PRIVATE_KERNEL_INNER_INDEX, PRIVATE_KERNEL_RESET_INDEX}, - PrivateKernelCircuitPublicInputs, + PrivateKernelCircuitPublicInputs }; global ALLOWED_PREVIOUS_CIRCUITS = @@ -22,11 +22,9 @@ pub struct PrivateKernelTailToPublicCircuitPrivateInputs { impl PrivateKernelTailToPublicCircuitPrivateInputs { pub fn new( previous_kernel: PrivateKernelDataWithoutPublicInputs, - previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs, + previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs ) -> Self { - Self { - previous_kernel: previous_kernel.to_private_kernel_data(previous_kernel_public_inputs), - } + Self { previous_kernel: previous_kernel.to_private_kernel_data(previous_kernel_public_inputs) } } unconstrained fn generate_output(self) -> PublicKernelCircuitPublicInputs { @@ -35,7 +33,9 @@ impl PrivateKernelTailToPublicCircuitPrivateInputs { pub fn execute(self) -> PublicKernelCircuitPublicInputs { // Generate output. - let output = unsafe { self.generate_output() }; + let output = unsafe { + self.generate_output() + }; // Validate inputs. let previous_kernel_validator = PreviousKernelValidator::new(self.previous_kernel); @@ -52,21 +52,20 @@ impl PrivateKernelTailToPublicCircuitPrivateInputs { } mod tests { - use crate::private_kernel_tail_to_public::{ - PrivateKernelTailToPublicCircuitPrivateInputs, ALLOWED_PREVIOUS_CIRCUITS, - }; + use crate::private_kernel_tail_to_public::{PrivateKernelTailToPublicCircuitPrivateInputs, ALLOWED_PREVIOUS_CIRCUITS}; use dep::types::constants::{ DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, GENERATOR_INDEX__TSK_M, L2_GAS_PER_LOG_BYTE, - L2_GAS_PER_NOTE_HASH, L2_GAS_PER_NULLIFIER, FIXED_AVM_STARTUP_L2_GAS, + L2_GAS_PER_NOTE_HASH, L2_GAS_PER_NULLIFIER, FIXED_AVM_STARTUP_L2_GAS }; use dep::types::{ abis::{ - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, gas::Gas, - note_hash::ScopedNoteHash, nullifier::{Nullifier, ScopedNullifier}, - log_hash::{LogHash, NoteLogHash}, - }, address::{AztecAddress, EthAddress}, + kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, gas::Gas, + note_hash::ScopedNoteHash, nullifier::{Nullifier, ScopedNullifier}, + log_hash::{LogHash, NoteLogHash} + }, + address::{AztecAddress, EthAddress}, tests::{fixture_builder::FixtureBuilder, utils::assert_array_eq}, point::Point, - constants::PRIVATE_KERNEL_INNER_INDEX, + constants::PRIVATE_KERNEL_INNER_INDEX }; // TODO: Reduce the duplicated code/tests for PrivateKernelTailToPublicInputs and PrivateKernelTailInputs. @@ -87,10 +86,7 @@ mod tests { // A helper function that uses the first nullifer in the previous kernel to compute the unique siloed // note_hashes for the given note_hashes. - pub fn compute_output_note_hashes( - _self: Self, - note_hashes: [ScopedNoteHash; N], - ) -> [ScopedNoteHash; N] { + pub fn compute_output_note_hashes(_self: Self, note_hashes: [ScopedNoteHash; N]) -> [ScopedNoteHash; N] { let mut output = [ScopedNoteHash::empty(); N]; for i in 0..N { output[i].note_hash.value = note_hashes[i].value(); @@ -98,10 +94,7 @@ mod tests { output } - pub fn compute_output_nullifiers( - _self: Self, - nullifiers: [ScopedNullifier; N], - ) -> [Nullifier; N] { + pub fn compute_output_nullifiers(_self: Self, nullifiers: [ScopedNullifier; N]) -> [Nullifier; N] { let mut output = [Nullifier::empty(); N]; for i in 0..N { output[i].value = nullifiers[i].value(); @@ -109,10 +102,7 @@ mod tests { output } - pub fn compute_output_note_logs( - _self: Self, - logs: [NoteLogHash; N], - ) -> [LogHash; N] { + pub fn compute_output_note_logs(_self: Self, logs: [NoteLogHash; N]) -> [LogHash; N] { let mut output = [LogHash::empty(); N]; for i in 0..N { if logs[i].value != 0 { @@ -123,9 +113,7 @@ mod tests { } pub fn execute(&mut self) -> PublicKernelCircuitPublicInputs { - let kernel = PrivateKernelTailToPublicCircuitPrivateInputs { - previous_kernel: self.previous_kernel.to_private_kernel_data(), - }; + let kernel = PrivateKernelTailToPublicCircuitPrivateInputs { previous_kernel: self.previous_kernel.to_private_kernel_data() }; kernel.execute() } @@ -195,28 +183,26 @@ mod tests { assert_array_eq( public_inputs.end_non_revertible.nullifiers, - [output_nullifiers[0], output_nullifiers[1], output_nullifiers[2]], + [output_nullifiers[0], output_nullifiers[1], output_nullifiers[2]] ); assert_array_eq( public_inputs.end.nullifiers, - [output_nullifiers[3], output_nullifiers[4]], + [output_nullifiers[3], output_nullifiers[4]] ); assert_eq( - public_inputs.end.gas_used, - Gas::new( + public_inputs.end.gas_used, Gas::new( 2 * DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE, - 2 * L2_GAS_PER_NULLIFIER, - ), + 2 * L2_GAS_PER_NULLIFIER + ) ); assert_eq( - public_inputs.end_non_revertible.gas_used, - Gas::new( - 3 * DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE, - FIXED_AVM_STARTUP_L2_GAS + 3 * L2_GAS_PER_NULLIFIER, - ) - + Gas::tx_overhead(), + public_inputs.end_non_revertible.gas_used, Gas::new( + 3 * DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE, + FIXED_AVM_STARTUP_L2_GAS + 3 * L2_GAS_PER_NULLIFIER + ) + + Gas::tx_overhead() ); } @@ -238,28 +224,26 @@ mod tests { assert_array_eq( public_inputs.end_non_revertible.note_hashes, - [exposed_note_hashes[0], exposed_note_hashes[1]], + [exposed_note_hashes[0], exposed_note_hashes[1]] ); assert_array_eq( public_inputs.end.note_hashes, - [exposed_note_hashes[2], exposed_note_hashes[3]], + [exposed_note_hashes[2], exposed_note_hashes[3]] ); assert_eq( - public_inputs.end.gas_used, - Gas::new( + public_inputs.end.gas_used, Gas::new( (2 * DA_BYTES_PER_FIELD) * DA_GAS_PER_BYTE, - 2 * L2_GAS_PER_NOTE_HASH, - ), + 2 * L2_GAS_PER_NOTE_HASH + ) ); assert_eq( - public_inputs.end_non_revertible.gas_used, - Gas::new( - (3 * DA_BYTES_PER_FIELD) * DA_GAS_PER_BYTE, - FIXED_AVM_STARTUP_L2_GAS + L2_GAS_PER_NULLIFIER + 2 * L2_GAS_PER_NOTE_HASH, - ) - + Gas::tx_overhead(), + public_inputs.end_non_revertible.gas_used, Gas::new( + (3 * DA_BYTES_PER_FIELD) * DA_GAS_PER_BYTE, + FIXED_AVM_STARTUP_L2_GAS + L2_GAS_PER_NULLIFIER + 2 * L2_GAS_PER_NOTE_HASH + ) + + Gas::tx_overhead() ); } @@ -285,7 +269,7 @@ mod tests { let _void = builder.previous_kernel.add_request_for_key_validation( Point { x: 1, y: 2, is_infinite: false }, 27, - GENERATOR_INDEX__TSK_M as Field, + GENERATOR_INDEX__TSK_M as Field ); builder.failed(); } @@ -300,10 +284,9 @@ mod tests { let expected_revertible_gas_used = Gas::new(300, 300); assert_eq(public_inputs.end.gas_used, expected_revertible_gas_used); - let expected_non_revertible_gas_used = Gas::tx_overhead() - + Gas::new( + let expected_non_revertible_gas_used = Gas::tx_overhead() + Gas::new( DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE * 1, - L2_GAS_PER_NULLIFIER * 1 + FIXED_AVM_STARTUP_L2_GAS, + L2_GAS_PER_NULLIFIER * 1 + FIXED_AVM_STARTUP_L2_GAS ); assert_eq(public_inputs.end_non_revertible.gas_used, expected_non_revertible_gas_used); @@ -322,10 +305,9 @@ mod tests { let expected_revertible_gas_used = Gas::new(0, 3 * FIXED_AVM_STARTUP_L2_GAS); assert_eq(public_inputs.end.gas_used, expected_revertible_gas_used); - let expected_non_revertible_gas_used = Gas::tx_overhead() - + Gas::new( + let expected_non_revertible_gas_used = Gas::tx_overhead() + Gas::new( DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE * 1, - L2_GAS_PER_NULLIFIER * 1 + 2 * FIXED_AVM_STARTUP_L2_GAS, + L2_GAS_PER_NULLIFIER * 1 + 2 * FIXED_AVM_STARTUP_L2_GAS ); assert_eq(public_inputs.end_non_revertible.gas_used, expected_non_revertible_gas_used); @@ -342,17 +324,12 @@ mod tests { let public_inputs = builder.execute(); + assert_eq(Gas::new(1 * DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE, 0), public_inputs.end.gas_used); assert_eq( - Gas::new(1 * DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE, 0), - public_inputs.end.gas_used, - ); - assert_eq( - Gas::tx_overhead() - + Gas::new( - 3 * DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE, - FIXED_AVM_STARTUP_L2_GAS + 1 * L2_GAS_PER_NULLIFIER, - ), - public_inputs.end_non_revertible.gas_used, + Gas::tx_overhead() + Gas::new( + 3 * DA_BYTES_PER_FIELD * DA_GAS_PER_BYTE, + FIXED_AVM_STARTUP_L2_GAS + 1 * L2_GAS_PER_NULLIFIER + ), public_inputs.end_non_revertible.gas_used ); } @@ -368,18 +345,13 @@ mod tests { let public_inputs = builder.execute(); - assert_eq( - Gas::new(13 * DA_GAS_PER_BYTE, 13 * L2_GAS_PER_LOG_BYTE), - public_inputs.end.gas_used, - ); + assert_eq(Gas::new(13 * DA_GAS_PER_BYTE, 13 * L2_GAS_PER_LOG_BYTE), public_inputs.end.gas_used); assert_eq( - Gas::tx_overhead() - + Gas::new( - (1 * DA_BYTES_PER_FIELD + 12) * DA_GAS_PER_BYTE, - FIXED_AVM_STARTUP_L2_GAS + 1 * L2_GAS_PER_NULLIFIER + 12 * L2_GAS_PER_LOG_BYTE, - ), - public_inputs.end_non_revertible.gas_used, + Gas::tx_overhead() + Gas::new( + (1 * DA_BYTES_PER_FIELD + 12) * DA_GAS_PER_BYTE, + FIXED_AVM_STARTUP_L2_GAS + 1 * L2_GAS_PER_NULLIFIER + 12 * L2_GAS_PER_LOG_BYTE + ), public_inputs.end_non_revertible.gas_used ); } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/mod.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/mod.nr index 5f0d70f292b..07828f8beac 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/mod.nr @@ -13,9 +13,10 @@ mod validate_private_call_requests; use crate::components::private_call_data_validator::PrivateCallDataValidator; use dep::types::{ abis::{ - note_hash::ScopedNoteHash, private_call_request::PrivateCallRequest, - private_kernel::private_call_data::PrivateCallData, - }, tests::fixture_builder::FixtureBuilder, transaction::tx_request::TxRequest, + note_hash::ScopedNoteHash, private_call_request::PrivateCallRequest, + private_kernel::private_call_data::PrivateCallData +}, + tests::fixture_builder::FixtureBuilder, transaction::tx_request::TxRequest }; pub struct PrivateCallDataValidatorBuilder { @@ -55,7 +56,7 @@ impl PrivateCallDataValidatorBuilder { accumulated_note_hashes.extend_from_bounded_vec(self.private_call.note_hashes); PrivateCallDataValidator::new(private_call).validate( accumulated_note_hashes.storage, - self.private_call.protocol_contract_tree_root, + self.private_call.protocol_contract_tree_root ); } @@ -78,7 +79,7 @@ impl PrivateCallDataValidatorBuilder { let accumulated_note_hashes = self.previous_note_hashes; PrivateCallDataValidator::new(data).validate( accumulated_note_hashes.storage, - self.private_call.protocol_contract_tree_root, + self.private_call.protocol_contract_tree_root ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/validate_against_previous_kernel.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/validate_against_previous_kernel.nr index 6878159ee2e..e8a547d4a1b 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/validate_against_previous_kernel.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/validate_against_previous_kernel.nr @@ -1,21 +1,16 @@ use crate::{ components::private_call_data_validator::PrivateCallDataValidator, - tests::private_call_data_validator_builder::PrivateCallDataValidatorBuilder, + tests::private_call_data_validator_builder::PrivateCallDataValidatorBuilder }; use dep::types::{ abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, - tests::fixture_builder::FixtureBuilder, + tests::fixture_builder::FixtureBuilder }; impl PrivateCallDataValidatorBuilder { - pub fn validate_against_previous_kernel( - self, - previous_kernel: PrivateKernelCircuitPublicInputs, - ) { + pub fn validate_against_previous_kernel(self, previous_kernel: PrivateKernelCircuitPublicInputs) { let private_call = self.private_call.to_private_call_data(); - PrivateCallDataValidator::new(private_call).validate_against_previous_kernel( - previous_kernel, - ); + PrivateCallDataValidator::new(private_call).validate_against_previous_kernel(previous_kernel); } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/validate_arrays.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/validate_arrays.nr index 4e376e0f635..34eac0ae3b7 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/validate_arrays.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_call_data_validator_builder/validate_arrays.nr @@ -33,9 +33,7 @@ fn validate_arrays_malformed_key_validation_requests_fails() { let mut builder = PrivateCallDataValidatorBuilder::new(); builder.private_call.append_key_validation_requests(1); - unshift_empty_item( - &mut builder.private_call.scoped_key_validation_requests_and_generators, - ); + unshift_empty_item(&mut builder.private_call.scoped_key_validation_requests_and_generators); builder.validate(); } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_output_validator_builder/mod.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_output_validator_builder/mod.nr index f614d5ed1e4..e4fb0614a91 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_output_validator_builder/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_output_validator_builder/mod.nr @@ -5,15 +5,16 @@ mod validate_propagated_from_private_call; use crate::components::{ private_kernel_circuit_output_validator::PrivateKernelCircuitOutputValidator, - private_kernel_circuit_public_inputs_composer::create_first_nullifier, + private_kernel_circuit_public_inputs_composer::create_first_nullifier }; use dep::types::{ abis::{ - private_call_request::PrivateCallRequest, - kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputsArrayLengths, - private_circuit_public_inputs::PrivateCircuitPublicInputsArrayLengths, - }, tests::fixture_builder::FixtureBuilder, transaction::tx_request::TxRequest, - constants::PRIVATE_KERNEL_INIT_INDEX, + private_call_request::PrivateCallRequest, + kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputsArrayLengths, + private_circuit_public_inputs::PrivateCircuitPublicInputsArrayLengths +}, + tests::fixture_builder::FixtureBuilder, transaction::tx_request::TxRequest, + constants::PRIVATE_KERNEL_INIT_INDEX }; pub struct PrivateKernelCircuitOutputValidatorBuilder { @@ -34,12 +35,7 @@ impl PrivateKernelCircuitOutputValidatorBuilder { previous_kernel.nullifiers.push(first_nullifier); previous_kernel = previous_kernel.in_vk_tree(PRIVATE_KERNEL_INIT_INDEX); - PrivateKernelCircuitOutputValidatorBuilder { - previous_kernel, - private_call, - output, - tx_request, - } + PrivateKernelCircuitOutputValidatorBuilder { previous_kernel, private_call, output, tx_request } } pub fn with_previous_kernel_vk_index(&mut self, vk_index: u32) { @@ -63,7 +59,7 @@ impl PrivateKernelCircuitOutputValidatorBuilder { private_call.public_inputs, array_lengths, FixtureBuilder::vk_tree_root(), - self.private_call.protocol_contract_tree_root, + self.private_call.protocol_contract_tree_root ); } @@ -75,17 +71,15 @@ impl PrivateKernelCircuitOutputValidatorBuilder { PrivateCallRequest::empty(); previous_kernel.end.private_call_stack[num_private_call_requests].args_hash = 98765432; - let previous_kernel_array_lengths = - PrivateKernelCircuitPublicInputsArrayLengths::new(previous_kernel); + let previous_kernel_array_lengths = PrivateKernelCircuitPublicInputsArrayLengths::new(previous_kernel); let private_call = self.private_call.to_private_call_data(); - let private_call_array_lengths = - PrivateCircuitPublicInputsArrayLengths::new(private_call.public_inputs); + let private_call_array_lengths = PrivateCircuitPublicInputsArrayLengths::new(private_call.public_inputs); let output = self.output.to_private_kernel_circuit_public_inputs(); PrivateKernelCircuitOutputValidator::new(output).validate_as_inner_call( previous_kernel, previous_kernel_array_lengths, private_call.public_inputs, - private_call_array_lengths, + private_call_array_lengths ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_output_validator_builder/validate_propagated_from_private_call.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_output_validator_builder/validate_propagated_from_private_call.nr index 897267ba89f..751dab429d2 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_output_validator_builder/validate_propagated_from_private_call.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_output_validator_builder/validate_propagated_from_private_call.nr @@ -84,10 +84,7 @@ fn validate_propagated_from_private_call_note_hash_read_requests_output_extra_no * note_hash_read_requests * With previous kernel. */ -fn append_note_hash_read_requests_to_previous_kernel( - builder: &mut PrivateKernelCircuitOutputValidatorBuilder, - num_requests: u32, -) { +fn append_note_hash_read_requests_to_previous_kernel(builder: &mut PrivateKernelCircuitOutputValidatorBuilder, num_requests: u32) { builder.previous_kernel.append_note_hash_read_requests(num_requests); builder.output.append_note_hash_read_requests(num_requests); builder.offset_values(num_requests as Field); diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/mod.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/mod.nr index adc4b05947d..9bad340f643 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/mod.nr @@ -5,9 +5,10 @@ mod propagate_from_private_call; use crate::components::private_kernel_circuit_public_inputs_composer::PrivateKernelCircuitPublicInputsComposer; use dep::types::{ abis::{ - kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, - private_call_request::PrivateCallRequest, - }, tests::fixture_builder::FixtureBuilder, transaction::tx_request::TxRequest, + kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, + private_call_request::PrivateCallRequest +}, + tests::fixture_builder::FixtureBuilder, transaction::tx_request::TxRequest }; pub struct PrivateKernelCircuitPublicInputsComposerBuilder { @@ -25,11 +26,7 @@ impl PrivateKernelCircuitPublicInputsComposerBuilder { private_call.value_offset = 9999; let tx_request = private_call.build_tx_request(); - PrivateKernelCircuitPublicInputsComposerBuilder { - tx_request, - previous_kernel, - private_call, - } + PrivateKernelCircuitPublicInputsComposerBuilder { tx_request, previous_kernel, private_call } } pub fn new_from_tx_request(self) -> PrivateKernelCircuitPublicInputsComposer { @@ -38,7 +35,7 @@ impl PrivateKernelCircuitPublicInputsComposerBuilder { self.tx_request, private_call, FixtureBuilder::vk_tree_root(), - self.private_call.protocol_contract_tree_root, + self.private_call.protocol_contract_tree_root ) } @@ -62,9 +59,6 @@ impl PrivateKernelCircuitPublicInputsComposerBuilder { let private_call = self.private_call.to_private_call_data(); - PrivateKernelCircuitPublicInputsComposer::new_from_previous_kernel(previous_kernel) - .pop_top_call_request() - .with_private_call(private_call.public_inputs) - .finish() + PrivateKernelCircuitPublicInputsComposer::new_from_previous_kernel(previous_kernel).pop_top_call_request().with_private_call(private_call.public_inputs).finish() } } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/new_from_previous_kernel_with_private_call.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/new_from_previous_kernel_with_private_call.nr index 092cf5a2529..dd3027ae1b1 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/new_from_previous_kernel_with_private_call.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/new_from_previous_kernel_with_private_call.nr @@ -1,7 +1,7 @@ use crate::tests::private_kernel_circuit_public_inputs_composer_builder::PrivateKernelCircuitPublicInputsComposerBuilder; use dep::types::{ - abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputsArrayLengths, - traits::is_empty, tests::utils::assert_array_eq, + abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputsArrayLengths, traits::is_empty, + tests::utils::assert_array_eq }; #[test] @@ -110,7 +110,7 @@ fn new_from_previous_kernel_with_private_call_note_hash_read_requests_succeeds() assert_array_eq( output.validation_requests.note_hash_read_requests, - [prev[0], prev[1], curr[0], curr[1]], + [prev[0], prev[1], curr[0], curr[1]] ); } @@ -127,7 +127,7 @@ fn new_from_previous_kernel_with_private_call_nullifier_read_requests_succeeds() assert_array_eq( output.validation_requests.nullifier_read_requests, - [prev[0], prev[1], curr[0], curr[1]], + [prev[0], prev[1], curr[0], curr[1]] ); } @@ -144,7 +144,7 @@ fn new_from_previous_kernel_with_private_call_key_validation_requests_succeeds() assert_array_eq( output.validation_requests.scoped_key_validation_requests_and_generators, - [prev[0], prev[1], curr[0], curr[1]], + [prev[0], prev[1], curr[0], curr[1]] ); } @@ -203,7 +203,7 @@ fn new_from_previous_kernel_with_private_call_note_encrypted_log_hashes_succeeds assert_array_eq( output.end.note_encrypted_logs_hashes, - [prev[0], prev[1], curr[0], curr[1]], + [prev[0], prev[1], curr[0], curr[1]] ); } @@ -220,7 +220,7 @@ fn new_from_previous_kernel_with_private_call_encrypted_log_hashes_succeeds() { assert_array_eq( output.end.encrypted_logs_hashes, - [prev[0], prev[1], curr[0], curr[1]], + [prev[0], prev[1], curr[0], curr[1]] ); } @@ -237,7 +237,7 @@ fn new_from_previous_kernel_with_private_call_unencrypted_log_hashes_succeeds() assert_array_eq( output.end.unencrypted_logs_hashes, - [prev[0], prev[1], curr[0], curr[1]], + [prev[0], prev[1], curr[0], curr[1]] ); } @@ -255,7 +255,7 @@ fn new_from_previous_kernel_with_private_call_private_call_requests_succeeds() { // Call requests from private call will be propagated in reversed order. assert_array_eq( output.end.private_call_stack, - [prev[1], prev[0], curr[1], curr[0]], + [prev[1], prev[0], curr[1], curr[0]] ); } @@ -272,7 +272,7 @@ fn new_from_previous_kernel_with_private_call_public_call_requests_succeeds() { assert_array_eq( output.end.public_call_requests, - [prev[0], prev[1], curr[0], curr[1]], + [prev[0], prev[1], curr[0], curr[1]] ); } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/new_from_tx_request.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/new_from_tx_request.nr index 16dcce34eae..9fdca3bce25 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/new_from_tx_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/new_from_tx_request.nr @@ -1,11 +1,8 @@ use crate::{ components::private_kernel_circuit_public_inputs_composer::create_first_nullifier, - tests::private_kernel_circuit_public_inputs_composer_builder::PrivateKernelCircuitPublicInputsComposerBuilder, -}; -use dep::types::{ - abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputsArrayLengths, - traits::is_empty, + tests::private_kernel_circuit_public_inputs_composer_builder::PrivateKernelCircuitPublicInputsComposerBuilder }; +use dep::types::{abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputsArrayLengths, traits::is_empty}; #[test] fn new_from_tx_request_succeeds() { diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/propagate_from_private_call.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/propagate_from_private_call.nr index 75f70cad1ac..c84c936d5e3 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/propagate_from_private_call.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/private_kernel_circuit_public_inputs_composer_builder/propagate_from_private_call.nr @@ -1,10 +1,10 @@ use crate::{ components::private_kernel_circuit_public_inputs_composer::create_first_nullifier, - tests::private_kernel_circuit_public_inputs_composer_builder::PrivateKernelCircuitPublicInputsComposerBuilder, + tests::private_kernel_circuit_public_inputs_composer_builder::PrivateKernelCircuitPublicInputsComposerBuilder }; use dep::types::{ - abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputsArrayLengths, - traits::is_empty, tests::utils::assert_array_eq, + abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputsArrayLengths, traits::is_empty, + tests::utils::assert_array_eq }; #[test] @@ -63,7 +63,7 @@ fn propagate_from_private_call_note_hash_read_requests_succeeds() { assert_array_eq( output.validation_requests.note_hash_read_requests, - [res[0], res[1]], + [res[0], res[1]] ); } @@ -78,7 +78,7 @@ fn propagate_from_private_call_nullifier_read_requests_succeeds() { assert_array_eq( output.validation_requests.nullifier_read_requests, - [res[0], res[1]], + [res[0], res[1]] ); } @@ -93,7 +93,7 @@ fn propagate_from_private_call_key_validation_requests_succeeds() { assert_array_eq( output.validation_requests.scoped_key_validation_requests_and_generators, - [res[0], res[1]], + [res[0], res[1]] ); } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/reset_output_validator_builder/mod.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/reset_output_validator_builder/mod.nr index 46fbe569a48..0c624109c8e 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/reset_output_validator_builder/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/reset_output_validator_builder/mod.nr @@ -3,16 +3,15 @@ mod validate_sorted_siloed_nullifiers; use crate::components::{ reset_output_composer::reset_output_hints::{generate_reset_output_hints, ResetOutputHints}, - reset_output_validator::ResetOutputValidator, + reset_output_validator::ResetOutputValidator }; use dep::reset_kernel_lib::{ KeyValidationHint, PrivateValidationRequestProcessor, - tests::{NoteHashReadRequestHintsBuilder, NullifierReadRequestHintsBuilder}, - TransientDataIndexHint, + tests::{NoteHashReadRequestHintsBuilder, NullifierReadRequestHintsBuilder}, TransientDataIndexHint }; use dep::types::{ constants::{MAX_KEY_VALIDATION_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX}, - tests::fixture_builder::FixtureBuilder, + tests::fixture_builder::FixtureBuilder }; pub struct ResetOutputValidatorBuilder { @@ -39,8 +38,7 @@ impl ResetOutputValidatorBuilder { let note_hash_read_request_hints_builder = NoteHashReadRequestHintsBuilder::new(); let nullifier_read_request_hints_builder = NullifierReadRequestHintsBuilder::new(); let key_validation_hints = [KeyValidationHint::nada(MAX_KEY_VALIDATION_REQUESTS_PER_TX); 2]; - let transient_data_index_hints = - [TransientDataIndexHint::nada(MAX_NULLIFIERS_PER_TX, MAX_NOTE_HASHES_PER_TX); 5]; + let transient_data_index_hints = [TransientDataIndexHint::nada(MAX_NULLIFIERS_PER_TX, MAX_NOTE_HASHES_PER_TX); 5]; ResetOutputValidatorBuilder { output, @@ -51,18 +49,18 @@ impl ResetOutputValidatorBuilder { transient_data_index_hints, note_hash_siloing_amount: 0, nullifier_siloing_amount: 0, - encrypted_log_siloing_amount: 0, + encrypted_log_siloing_amount: 0 } } - pub fn get_validation_request_processor( - self, - ) -> PrivateValidationRequestProcessor<6, 3, 5, 2, 2> { + pub fn get_validation_request_processor(self) -> PrivateValidationRequestProcessor<6, 3, 5, 2, 2> { let previous_kernel = self.previous_kernel.to_private_kernel_circuit_public_inputs(); - let note_hash_read_request_hints = - unsafe { self.note_hash_read_request_hints_builder.to_hints() }; - let nullifier_read_request_hints = - unsafe { self.nullifier_read_request_hints_builder.to_hints() }; + let note_hash_read_request_hints = unsafe { + self.note_hash_read_request_hints_builder.to_hints() + }; + let nullifier_read_request_hints = unsafe { + self.nullifier_read_request_hints_builder.to_hints() + }; PrivateValidationRequestProcessor { validation_requests: previous_kernel.validation_requests, @@ -73,7 +71,7 @@ impl ResetOutputValidatorBuilder { pending_nullifiers: previous_kernel.end.nullifiers, nullifier_tree_root: 0, key_validation_hints: self.key_validation_hints, - validation_requests_split_counter: previous_kernel.min_revertible_side_effect_counter, + validation_requests_split_counter: previous_kernel.min_revertible_side_effect_counter } } @@ -96,9 +94,8 @@ impl ResetOutputValidatorBuilder { self.note_hash_siloing_amount, self.nullifier_siloing_amount, self.encrypted_log_siloing_amount, - hints, - ) - .validate(); + hints + ).validate(); } pub fn validate(self) { diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_composer_builder/meter_gas_used.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_composer_builder/meter_gas_used.nr index ff5644f9c26..4450cb2cd2f 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_composer_builder/meter_gas_used.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_composer_builder/meter_gas_used.nr @@ -1,10 +1,8 @@ use crate::components::tail_output_composer::meter_gas_used::meter_gas_used; use dep::types::{ abis::gas::Gas, - constants::{ - DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, L2_GAS_PER_NOTE_HASH, L2_GAS_PER_NULLIFIER, - L2_GAS_PER_LOG_BYTE, - }, tests::fixture_builder::FixtureBuilder, + constants::{DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, L2_GAS_PER_NOTE_HASH, L2_GAS_PER_NULLIFIER, L2_GAS_PER_LOG_BYTE}, + tests::fixture_builder::FixtureBuilder }; fn new_builder() -> FixtureBuilder { @@ -68,9 +66,8 @@ fn meter_gas_used_everything_succeeds() { let gas = meter_gas_used(data, gas_settings); assert_eq( - gas, - Gas::new(metered_da_bytes * DA_GAS_PER_BYTE, computed_l2_gas) - + Gas::tx_overhead() - + gas_settings.teardown_gas_limits, + gas, Gas::new(metered_da_bytes * DA_GAS_PER_BYTE, computed_l2_gas) + + Gas::tx_overhead() + + gas_settings.teardown_gas_limits ); } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_composer_builder/mod.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_composer_builder/mod.nr index 3f9b6ef8043..0e82c914a67 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_composer_builder/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_composer_builder/mod.nr @@ -1,10 +1,7 @@ mod meter_gas_used; use crate::components::tail_output_composer::TailOutputComposer; -use dep::types::{ - abis::kernel_circuit_public_inputs::KernelCircuitPublicInputs, - tests::fixture_builder::FixtureBuilder, -}; +use dep::types::{abis::kernel_circuit_public_inputs::KernelCircuitPublicInputs, tests::fixture_builder::FixtureBuilder}; pub struct TailOutputComposerBuilder { previous_kernel: FixtureBuilder, diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_validator_builder/mod.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_validator_builder/mod.nr index e3a784e5081..98f146d5288 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_validator_builder/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_output_validator_builder/mod.nr @@ -5,13 +5,11 @@ mod validate_propagated_values; use crate::components::{ tail_output_composer::meter_gas_used::meter_gas_used, - tail_output_validator::{ - tail_output_hints::{generate_tail_output_hints, TailOutputHints}, TailOutputValidator, - }, + tail_output_validator::{tail_output_hints::{generate_tail_output_hints, TailOutputHints}, TailOutputValidator} }; use dep::types::{ abis::{gas_settings::GasSettings, kernel_circuit_public_inputs::KernelCircuitPublicInputs}, - tests::fixture_builder::FixtureBuilder, + tests::fixture_builder::FixtureBuilder }; pub struct TailOutputValidatorBuilder { diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/meter_gas_used.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/meter_gas_used.nr index 2c6fb1d2e23..e73d2fcd4e0 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/meter_gas_used.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/meter_gas_used.nr @@ -1,12 +1,11 @@ -use crate::components::tail_to_public_output_composer::meter_gas_used::{ - meter_gas_used_non_revertible, meter_gas_used_revertible, -}; +use crate::components::tail_to_public_output_composer::meter_gas_used::{meter_gas_used_non_revertible, meter_gas_used_revertible}; use dep::types::{ abis::gas::Gas, constants::{ - DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, FIXED_AVM_STARTUP_L2_GAS, L2_GAS_PER_NOTE_HASH, - L2_GAS_PER_NULLIFIER, L2_GAS_PER_LOG_BYTE, - }, tests::fixture_builder::FixtureBuilder, + DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, FIXED_AVM_STARTUP_L2_GAS, L2_GAS_PER_NOTE_HASH, + L2_GAS_PER_NULLIFIER, L2_GAS_PER_LOG_BYTE +}, + tests::fixture_builder::FixtureBuilder }; #[test] @@ -43,8 +42,7 @@ fn meter_gas_used_non_revertible_everything_succeeds() { + 2 + 6 // encrypted_log_hash + 51; // unencrypted_log_hash - let computed_da_gas = - (total_num_side_effects * DA_BYTES_PER_FIELD + total_log_length) * DA_GAS_PER_BYTE; + let computed_da_gas = (total_num_side_effects * DA_BYTES_PER_FIELD + total_log_length) * DA_GAS_PER_BYTE; let computed_l2_gas = 4 * L2_GAS_PER_NOTE_HASH + 3 * L2_GAS_PER_NULLIFIER + total_log_length * L2_GAS_PER_LOG_BYTE @@ -89,8 +87,7 @@ fn meter_gas_used_revertible_everything_succeeds() { + 2 + 6 // encrypted_log_hash + 51; // unencrypted_log_hash - let computed_da_gas = - (total_num_side_effects * DA_BYTES_PER_FIELD + total_log_length) * DA_GAS_PER_BYTE; + let computed_da_gas = (total_num_side_effects * DA_BYTES_PER_FIELD + total_log_length) * DA_GAS_PER_BYTE; let computed_l2_gas = 4 * L2_GAS_PER_NOTE_HASH + 3 * L2_GAS_PER_NULLIFIER + total_log_length * L2_GAS_PER_LOG_BYTE diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/mod.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/mod.nr index c7daddc987e..db217294f16 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/mod.nr @@ -5,7 +5,7 @@ mod tail_to_public_output_composer; use crate::components::tail_to_public_output_composer::TailToPublicOutputComposer; use dep::types::{ abis::kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - tests::fixture_builder::FixtureBuilder, + tests::fixture_builder::FixtureBuilder }; pub struct TailToPublicOutputComposerBuilder { diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/split_to_public.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/split_to_public.nr index f81f0ef541e..67b368e0dee 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/split_to_public.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/split_to_public.nr @@ -27,7 +27,7 @@ fn split_to_public_succeeds() { let (non_revertible, revertible) = unsafe { split_to_public( builder.to_private_accumulated_data_builder(), - builder.min_revertible_side_effect_counter, + builder.min_revertible_side_effect_counter ) }; @@ -36,7 +36,7 @@ fn split_to_public_succeeds() { assert_array_eq(non_revertible.note_hashes, [expected[0], expected[1]]); assert_array_eq( revertible.note_hashes, - [expected[2], expected[3], expected[4]], + [expected[2], expected[3], expected[4]] ); // nullifiers @@ -53,7 +53,7 @@ fn split_to_public_succeeds() { let expected = combined_data.note_encrypted_logs_hashes; assert_array_eq( non_revertible.note_encrypted_logs_hashes, - [expected[0], expected[1], expected[2]], + [expected[0], expected[1], expected[2]] ); assert_array_eq(revertible.note_encrypted_logs_hashes, [expected[3]]); @@ -61,7 +61,7 @@ fn split_to_public_succeeds() { let expected = combined_data.encrypted_logs_hashes; assert_array_eq( non_revertible.encrypted_logs_hashes, - [expected[0], expected[1]], + [expected[0], expected[1]] ); assert_array_eq(revertible.encrypted_logs_hashes, [expected[2], expected[3]]); diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/tail_to_public_output_composer.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/tail_to_public_output_composer.nr index ba858cbe75d..8a0214adee6 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/tail_to_public_output_composer.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-lib/src/tests/tail_to_public_output_composer_builder/tail_to_public_output_composer.nr @@ -2,9 +2,10 @@ use crate::tests::tail_to_public_output_composer_builder::TailToPublicOutputComp use dep::types::{ abis::gas::Gas, constants::{ - DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, FIXED_AVM_STARTUP_L2_GAS, L2_GAS_PER_NOTE_HASH, - L2_GAS_PER_NULLIFIER, L2_GAS_PER_LOG_BYTE, - }, tests::utils::{assert_array_eq, swap_items}, + DA_BYTES_PER_FIELD, DA_GAS_PER_BYTE, FIXED_AVM_STARTUP_L2_GAS, L2_GAS_PER_NOTE_HASH, + L2_GAS_PER_NULLIFIER, L2_GAS_PER_LOG_BYTE +}, + tests::utils::{assert_array_eq, swap_items} }; #[test] @@ -64,7 +65,7 @@ fn tail_to_public_output_composer_succeeds() { let note_hashes = data.note_hashes; assert_array_eq( output.end_non_revertible.note_hashes, - [note_hashes[0], note_hashes[1], note_hashes[2], note_hashes[3]], + [note_hashes[0], note_hashes[1], note_hashes[2], note_hashes[3]] ); assert_array_eq(output.end.note_hashes, [note_hashes[4], note_hashes[5]]); @@ -72,7 +73,7 @@ fn tail_to_public_output_composer_succeeds() { let nullifiers = data.nullifiers; assert_array_eq( output.end_non_revertible.nullifiers, - [nullifiers[0], nullifiers[1], nullifiers[2]], + [nullifiers[0], nullifiers[1], nullifiers[2]] ); assert_array_eq(output.end.nullifiers, [nullifiers[3]]); @@ -85,7 +86,7 @@ fn tail_to_public_output_composer_succeeds() { let log_hashes = data.note_encrypted_logs_hashes; assert_array_eq( output.end_non_revertible.note_encrypted_logs_hashes, - [log_hashes[0], log_hashes[1]], + [log_hashes[0], log_hashes[1]] ); assert_array_eq(output.end.note_encrypted_logs_hashes, [log_hashes[2]]); @@ -93,18 +94,18 @@ fn tail_to_public_output_composer_succeeds() { let log_hashes = data.encrypted_logs_hashes; assert_array_eq( output.end_non_revertible.encrypted_logs_hashes, - [log_hashes[0]], + [log_hashes[0]] ); assert_array_eq( output.end.encrypted_logs_hashes, - [log_hashes[1], log_hashes[2]], + [log_hashes[1], log_hashes[2]] ); // unencrypted_logs_hashes let log_hashes = data.unencrypted_logs_hashes; assert_array_eq( output.end_non_revertible.unencrypted_logs_hashes, - [log_hashes[0], log_hashes[1]], + [log_hashes[0], log_hashes[1]] ); assert_array_eq(output.end.unencrypted_logs_hashes, [log_hashes[2]]); @@ -112,11 +113,11 @@ fn tail_to_public_output_composer_succeeds() { let call_requests = data.public_call_stack; assert_array_eq( output.end_non_revertible.public_call_stack, - [call_requests[1], call_requests[0]], + [call_requests[1], call_requests[0]] ); assert_array_eq( output.end.public_call_stack, - [call_requests[4], call_requests[3], call_requests[2]], + [call_requests[4], call_requests[3], call_requests[2]] ); // Gas: non-revertible @@ -126,15 +127,13 @@ fn tail_to_public_output_composer_succeeds() { + 2 // encrypted_log_hash + 51 + 9; // unencrypted_log_hash - let computed_da_gas = - (total_num_side_effects * DA_BYTES_PER_FIELD + total_log_length) * DA_GAS_PER_BYTE; + let computed_da_gas = (total_num_side_effects * DA_BYTES_PER_FIELD + total_log_length) * DA_GAS_PER_BYTE; let computed_l2_gas = 4 * L2_GAS_PER_NOTE_HASH + 3 * L2_GAS_PER_NULLIFIER + total_log_length * L2_GAS_PER_LOG_BYTE + 2 * FIXED_AVM_STARTUP_L2_GAS; assert_eq( - output.end_non_revertible.gas_used, - Gas::new(computed_da_gas, computed_l2_gas) + Gas::tx_overhead(), + output.end_non_revertible.gas_used, Gas::new(computed_da_gas, computed_l2_gas) + Gas::tx_overhead() ); // Gas: revertible @@ -143,8 +142,7 @@ fn tail_to_public_output_composer_succeeds() { + 6 + 24 // encrypted_log_hash + 4; // unencrypted_log_hash - let computed_da_gas = - (total_num_side_effects * DA_BYTES_PER_FIELD + total_log_length) * DA_GAS_PER_BYTE; + let computed_da_gas = (total_num_side_effects * DA_BYTES_PER_FIELD + total_log_length) * DA_GAS_PER_BYTE; let computed_l2_gas = 2 * L2_GAS_PER_NOTE_HASH + 1 * L2_GAS_PER_NULLIFIER + total_log_length * L2_GAS_PER_LOG_BYTE diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-reset-simulated/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-reset-simulated/src/main.nr index 7884b49de77..3df55379852 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-reset-simulated/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-reset-simulated/src/main.nr @@ -1,13 +1,10 @@ -use dep::private_kernel_lib::private_kernel_reset::{ - PrivateKernelResetHints, PrivateKernelResetCircuitPrivateInputs, -}; +use dep::private_kernel_lib::private_kernel_reset::{PrivateKernelResetHints, PrivateKernelResetCircuitPrivateInputs}; use dep::types::{ PrivateKernelCircuitPublicInputs, constants::{ - MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, - MAX_KEY_VALIDATION_REQUESTS_PER_TX, - }, + MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, + MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_KEY_VALIDATION_REQUESTS_PER_TX +} }; use types::abis::private_kernel_data::PrivateKernelDataWithoutPublicInputs; @@ -24,17 +21,13 @@ global ENCRYPTED_LOG_SILOING_AMOUNT = MAX_ENCRYPTED_LOGS_PER_TX; // 8 unconstrained fn main( previous_kernel: PrivateKernelDataWithoutPublicInputs, previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs, - hints: PrivateKernelResetHints, + hints: PrivateKernelResetHints ) -> pub PrivateKernelCircuitPublicInputs { - let private_inputs = PrivateKernelResetCircuitPrivateInputs::new( - previous_kernel, - previous_kernel_public_inputs, - hints, - ); + let private_inputs = PrivateKernelResetCircuitPrivateInputs::new(previous_kernel, previous_kernel_public_inputs, hints); private_inputs.execute( NOTE_HASH_SILOING_AMOUNT, NULLIFIER_SILOING_AMOUNT, - ENCRYPTED_LOG_SILOING_AMOUNT, + ENCRYPTED_LOG_SILOING_AMOUNT ) } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-reset/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-reset/src/main.nr index dc6185015d9..c898f14e10c 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-reset/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-reset/src/main.nr @@ -1,13 +1,10 @@ -use dep::private_kernel_lib::private_kernel_reset::{ - PrivateKernelResetHints, PrivateKernelResetCircuitPrivateInputs, -}; +use dep::private_kernel_lib::private_kernel_reset::{PrivateKernelResetHints, PrivateKernelResetCircuitPrivateInputs}; use dep::types::{ PrivateKernelCircuitPublicInputs, constants::{ - MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, - MAX_KEY_VALIDATION_REQUESTS_PER_TX, - }, + MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, + MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_KEY_VALIDATION_REQUESTS_PER_TX +} }; use types::abis::private_kernel_data::PrivateKernelDataWithoutPublicInputs; @@ -24,17 +21,13 @@ global ENCRYPTED_LOG_SILOING_AMOUNT = MAX_ENCRYPTED_LOGS_PER_TX; // 8 fn main( previous_kernel: PrivateKernelDataWithoutPublicInputs, previous_kernel_public_inputs: call_data(0) PrivateKernelCircuitPublicInputs, - hints: PrivateKernelResetHints, + hints: PrivateKernelResetHints ) -> return_data PrivateKernelCircuitPublicInputs { - let private_inputs = PrivateKernelResetCircuitPrivateInputs::new( - previous_kernel, - previous_kernel_public_inputs, - hints, - ); + let private_inputs = PrivateKernelResetCircuitPrivateInputs::new(previous_kernel, previous_kernel_public_inputs, hints); private_inputs.execute( NOTE_HASH_SILOING_AMOUNT, NULLIFIER_SILOING_AMOUNT, - ENCRYPTED_LOG_SILOING_AMOUNT, + ENCRYPTED_LOG_SILOING_AMOUNT ) } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-simulated/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-simulated/src/main.nr index fa99dc2bea4..2d9ebe6ea0e 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-simulated/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-simulated/src/main.nr @@ -5,9 +5,8 @@ use types::abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs; unconstrained fn main( previous_kernel: PrivateKernelDataWithoutPublicInputs, - previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs, + previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs ) -> pub KernelCircuitPublicInputs { - let private_inputs = - PrivateKernelTailCircuitPrivateInputs::new(previous_kernel, previous_kernel_public_inputs); + let private_inputs = PrivateKernelTailCircuitPrivateInputs::new(previous_kernel, previous_kernel_public_inputs); private_inputs.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-to-public-simulated/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-to-public-simulated/src/main.nr index dbbc22e0df6..6716b11f017 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-to-public-simulated/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-to-public-simulated/src/main.nr @@ -5,11 +5,8 @@ use types::abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs; unconstrained fn main( previous_kernel: PrivateKernelDataWithoutPublicInputs, - previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs, + previous_kernel_public_inputs: PrivateKernelCircuitPublicInputs ) -> pub PublicKernelCircuitPublicInputs { - let private_inputs = PrivateKernelTailToPublicCircuitPrivateInputs::new( - previous_kernel, - previous_kernel_public_inputs, - ); + let private_inputs = PrivateKernelTailToPublicCircuitPrivateInputs::new(previous_kernel, previous_kernel_public_inputs); private_inputs.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-to-public/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-to-public/src/main.nr index ea2bd39412e..57bf8c74c43 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-to-public/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-tail-to-public/src/main.nr @@ -5,11 +5,8 @@ use types::abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs; fn main( previous_kernel: PrivateKernelDataWithoutPublicInputs, - previous_kernel_public_inputs: call_data(0) PrivateKernelCircuitPublicInputs, + previous_kernel_public_inputs: call_data(0) PrivateKernelCircuitPublicInputs ) -> pub PublicKernelCircuitPublicInputs { - let private_inputs = PrivateKernelTailToPublicCircuitPrivateInputs::new( - previous_kernel, - previous_kernel_public_inputs, - ); + let private_inputs = PrivateKernelTailToPublicCircuitPrivateInputs::new(previous_kernel, previous_kernel_public_inputs); private_inputs.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/private-kernel-tail/src/main.nr b/noir-projects/noir-protocol-circuits/crates/private-kernel-tail/src/main.nr index 675e7f082a6..8383ed5c782 100644 --- a/noir-projects/noir-protocol-circuits/crates/private-kernel-tail/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/private-kernel-tail/src/main.nr @@ -5,9 +5,8 @@ use types::abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs; fn main( previous_kernel: PrivateKernelDataWithoutPublicInputs, - previous_kernel_public_inputs: call_data(0) PrivateKernelCircuitPublicInputs, + previous_kernel_public_inputs: call_data(0) PrivateKernelCircuitPublicInputs ) -> pub KernelCircuitPublicInputs { - let private_inputs = - PrivateKernelTailCircuitPrivateInputs::new(previous_kernel, previous_kernel_public_inputs); + let private_inputs = PrivateKernelTailCircuitPrivateInputs::new(previous_kernel, previous_kernel_public_inputs); private_inputs.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/enqueued_call_data_validator.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/enqueued_call_data_validator.nr index 13f96c95651..aef13b5b4f4 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/enqueued_call_data_validator.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/enqueued_call_data_validator.nr @@ -1,11 +1,11 @@ use crate::public_kernel_phase::PublicKernelPhase; use dep::types::{ abis::{ - accumulated_data::PublicAccumulatedDataArrayLengths, - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - enqueued_call_data::EnqueuedCallData, public_call_request::PublicCallRequest, - validation_requests::PublicValidationRequestArrayLengths, - }, constants::MAX_L2_GAS_PER_ENQUEUED_CALL, utils::arrays::array_length, + accumulated_data::PublicAccumulatedDataArrayLengths, + kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, enqueued_call_data::EnqueuedCallData, + public_call_request::PublicCallRequest, validation_requests::PublicValidationRequestArrayLengths +}, + constants::MAX_L2_GAS_PER_ENQUEUED_CALL, utils::arrays::array_length }; pub struct EnqueuedCallDataValidator { @@ -31,7 +31,7 @@ impl EnqueuedCallDataValidator { previous_kernel: PublicKernelCircuitPublicInputs, previous_validation_request_array_lengths: PublicValidationRequestArrayLengths, previous_non_revertible_data_array_lengths: PublicAccumulatedDataArrayLengths, - previous_revertible_data_array_lengths: PublicAccumulatedDataArrayLengths, + previous_revertible_data_array_lengths: PublicAccumulatedDataArrayLengths ) { self.validate_global_variables(previous_kernel); self.validate_against_call_request(previous_kernel); @@ -41,7 +41,7 @@ impl EnqueuedCallDataValidator { self.validate_array_lengths( previous_validation_request_array_lengths, previous_non_revertible_data_array_lengths, - previous_revertible_data_array_lengths, + previous_revertible_data_array_lengths ); } @@ -57,9 +57,7 @@ impl EnqueuedCallDataValidator { // It's empty when the previous kernel is from private_kernel_tail_to_pubic. let enqueued_call_globals = self.enqueued_call.data.constants.global_variables; assert_eq( - enqueued_call_globals, - prev_global_variables, - "Global variables injected into the public call do not match constants", + enqueued_call_globals, prev_global_variables, "Global variables injected into the public call do not match constants" ); } } @@ -79,16 +77,13 @@ impl EnqueuedCallDataValidator { }; assert( - self.enqueued_call.data.call_request == call_request, - "enqueued call does not match item at the top of the call stack", + self.enqueued_call.data.call_request == call_request, "enqueued call does not match item at the top of the call stack" ); } fn validate_counters(self, previous_kernel: PublicKernelCircuitPublicInputs) { assert_eq( - self.enqueued_call.data.start_side_effect_counter, - previous_kernel.end_side_effect_counter + 1, - "enqueued call must start from the end counter of the previous call", + self.enqueued_call.data.start_side_effect_counter, previous_kernel.end_side_effect_counter + 1, "enqueued call must start from the end counter of the previous call" ); } @@ -100,27 +95,20 @@ impl EnqueuedCallDataValidator { if self.phase != PublicKernelPhase.TEARDOWN { // An enqueued call's start gas is the remaining gas left in the transaction after the previous kernel. let tx_gas_limits = previous_kernel.constants.tx_context.gas_settings.gas_limits; - let mut computed_start_gas = tx_gas_limits.sub(previous_kernel.end.gas_used).sub( - previous_kernel.end_non_revertible.gas_used, - ); + let mut computed_start_gas = tx_gas_limits.sub(previous_kernel.end.gas_used).sub(previous_kernel.end_non_revertible.gas_used); // Keep L2 gas below max computed_start_gas.l2_gas = std::cmp::min(computed_start_gas.l2_gas, MAX_L2_GAS_PER_ENQUEUED_CALL); assert_eq( - enqueued_call_start_gas, - computed_start_gas, - "Start gas for enqueued call does not match transaction gas left (with MAX_L2_GAS_PER_ENQUEUED_CALL applied)", + enqueued_call_start_gas, computed_start_gas, "Start gas for enqueued call does not match transaction gas left (with MAX_L2_GAS_PER_ENQUEUED_CALL applied)" ); } else { - let mut teardown_gas_limit = - previous_kernel.constants.tx_context.gas_settings.teardown_gas_limits; + let mut teardown_gas_limit = previous_kernel.constants.tx_context.gas_settings.teardown_gas_limits; // Keep L2 gas below max teardown_gas_limit.l2_gas = std::cmp::min(teardown_gas_limit.l2_gas, MAX_L2_GAS_PER_ENQUEUED_CALL); assert_eq( - enqueued_call_start_gas, - teardown_gas_limit, - "Start gas for enqueued call does not match teardown gas allocation (with MAX_L2_GAS_PER_ENQUEUED_CALL applied)", + enqueued_call_start_gas, teardown_gas_limit, "Start gas for enqueued call does not match teardown gas allocation (with MAX_L2_GAS_PER_ENQUEUED_CALL applied)" ); } } @@ -131,15 +119,12 @@ impl EnqueuedCallDataValidator { assert_eq(transaction_fee, 0, "Transaction fee must be zero on setup and app phases"); } else { // Note that teardown_gas is already included in end.gas_used as it was injected by the private kernel - let total_gas_used = - previous_kernel.end.gas_used + previous_kernel.end_non_revertible.gas_used; + let total_gas_used = previous_kernel.end.gas_used + previous_kernel.end_non_revertible.gas_used; let block_gas_fees = self.enqueued_call.data.constants.global_variables.gas_fees; let inclusion_fee = previous_kernel.constants.tx_context.gas_settings.inclusion_fee; - let computed_transaction_fee = - total_gas_used.compute_fee(block_gas_fees) + inclusion_fee; + let computed_transaction_fee = total_gas_used.compute_fee(block_gas_fees) + inclusion_fee; assert( - transaction_fee == computed_transaction_fee, - "Transaction fee on teardown phase does not match expected value", + transaction_fee == computed_transaction_fee, "Transaction fee on teardown phase does not match expected value" ); } } @@ -148,12 +133,10 @@ impl EnqueuedCallDataValidator { self, previous_validation_request_array_lengths: PublicValidationRequestArrayLengths, previous_non_revertible_data_array_lengths: PublicAccumulatedDataArrayLengths, - previous_revertible_data_array_lengths: PublicAccumulatedDataArrayLengths, + previous_revertible_data_array_lengths: PublicAccumulatedDataArrayLengths ) { assert_eq( - self.enqueued_call.data.previous_validation_request_array_lengths, - previous_validation_request_array_lengths, - "mismatch previous_validation_request_array_lengths", + self.enqueued_call.data.previous_validation_request_array_lengths, previous_validation_request_array_lengths, "mismatch previous_validation_request_array_lengths" ); let prev_lengths = if self.phase == PublicKernelPhase.SETUP { previous_non_revertible_data_array_lengths @@ -161,9 +144,7 @@ impl EnqueuedCallDataValidator { previous_revertible_data_array_lengths }; assert_eq( - self.enqueued_call.data.previous_accumulated_data_array_lengths, - prev_lengths, - "mismatch previoius_accumulated_data_array_lengths", + self.enqueued_call.data.previous_accumulated_data_array_lengths, prev_lengths, "mismatch previoius_accumulated_data_array_lengths" ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/previous_kernel_validator.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/previous_kernel_validator.nr index 4d3bf25508f..3e8725df2e1 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/previous_kernel_validator.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/previous_kernel_validator.nr @@ -21,48 +21,33 @@ impl PreviousKernelValidator { pub fn validate_phase(self, phase: u8) { let public_inputs = self.previous_kernel.public_inputs; - let needs_setup = !public_inputs.end_non_revertible.public_call_stack[0] - .call_context - .contract_address - .is_zero(); + let needs_setup = !public_inputs.end_non_revertible.public_call_stack[0].call_context.contract_address.is_zero(); if phase == PublicKernelPhase.SETUP { assert_eq(needs_setup, true, "Cannot run unnecessary setup circuit"); } - let needs_app_logic = - !public_inputs.end.public_call_stack[0].call_context.contract_address.is_zero(); + let needs_app_logic = !public_inputs.end.public_call_stack[0].call_context.contract_address.is_zero(); if phase == PublicKernelPhase.APP_LOGIC { assert_eq(needs_setup, false, "Cannot run app logic circuit before setup circuit"); assert_eq(needs_app_logic, true, "Cannot run unnecessary app logic circuit"); } - let needs_teardown = - !public_inputs.public_teardown_call_request.call_context.contract_address.is_zero(); + let needs_teardown = !public_inputs.public_teardown_call_request.call_context.contract_address.is_zero(); if phase == PublicKernelPhase.TEARDOWN { assert_eq(needs_setup, false, "Cannot run teardown circuit before setup circuit"); - assert_eq( - needs_app_logic, - false, - "Cannot run teardown circuit before app logic circuit", - ); + assert_eq(needs_app_logic, false, "Cannot run teardown circuit before app logic circuit"); assert_eq(needs_teardown, true, "Cannot run unnecessary teardown circuit"); } if phase == PublicKernelPhase.TAIL { assert_eq( - needs_setup, - false, - "Revertible call stack must be empty when executing the tail circuit", + needs_setup, false, "Revertible call stack must be empty when executing the tail circuit" ); assert_eq( - needs_app_logic, - false, - "Non-revertible call stack must be empty when executing the tail circuit", + needs_app_logic, false, "Non-revertible call stack must be empty when executing the tail circuit" ); assert_eq( - needs_teardown, - false, - "Teardown call stack must be empty when executing the tail circuit", + needs_teardown, false, "Teardown call stack must be empty when executing the tail circuit" ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer.nr index e073a9d9bc5..406b005a54c 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer.nr @@ -2,16 +2,15 @@ mod propagate_accumulated_data; use crate::{ components::public_kernel_output_composer::propagate_accumulated_data::propagate_accumulated_data, - public_kernel_phase::PublicKernelPhase, + public_kernel_phase::PublicKernelPhase }; use dep::types::{ abis::{ - accumulated_data::PublicAccumulatedDataBuilder, - kernel_circuit_public_inputs::{ - PublicKernelCircuitPublicInputs, PublicKernelCircuitPublicInputsBuilder, - VMCircuitPublicInputs, - }, public_call_request::PublicCallRequest, - }, traits::is_empty, + accumulated_data::PublicAccumulatedDataBuilder, + kernel_circuit_public_inputs::{PublicKernelCircuitPublicInputs, PublicKernelCircuitPublicInputsBuilder, VMCircuitPublicInputs}, + public_call_request::PublicCallRequest +}, + traits::is_empty }; pub struct PublicKernelOutputComposer { @@ -37,11 +36,7 @@ impl PublicKernelOutputComposer { *self } - pub fn propagate_from_enqueued_call( - &mut self, - enqueued_call: VMCircuitPublicInputs, - phase: u8, - ) -> Self { + pub fn propagate_from_enqueued_call(&mut self, enqueued_call: VMCircuitPublicInputs, phase: u8) -> Self { self.output_builder.constants.global_variables = enqueued_call.constants.global_variables; self.propagate_revert_code(enqueued_call, phase); self.propagate_validation_requests(enqueued_call); @@ -100,9 +95,7 @@ impl PublicKernelOutputComposer { for i in 0..nullifier_non_existent_read_requests.len() { let request = nullifier_non_existent_read_requests[i]; if !is_empty(request) { - self.output_builder.validation_requests.nullifier_non_existent_read_requests.push( - request, - ); + self.output_builder.validation_requests.nullifier_non_existent_read_requests.push(request); } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer/propagate_accumulated_data.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer/propagate_accumulated_data.nr index 2024caf0444..2f54822fd9f 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer/propagate_accumulated_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer/propagate_accumulated_data.nr @@ -2,7 +2,7 @@ use dep::types::abis::accumulated_data::{PublicAccumulatedData, PublicAccumulate pub fn propagate_accumulated_data( data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, + from_data: PublicAccumulatedData ) -> PublicAccumulatedDataBuilder { propagate_note_hashes(data, from_data); propagate_nullifiers(data, from_data); @@ -12,10 +12,7 @@ pub fn propagate_accumulated_data( *data } -fn propagate_note_hashes( - data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, -) { +fn propagate_note_hashes(data: &mut PublicAccumulatedDataBuilder, from_data: PublicAccumulatedData) { let note_hashes = from_data.note_hashes; for i in 0..note_hashes.len() { let note_hash = note_hashes[i]; @@ -37,7 +34,7 @@ fn propagate_nullifiers(data: &mut PublicAccumulatedDataBuilder, from_data: Publ fn propagate_l2_to_l1_messages( data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, + from_data: PublicAccumulatedData ) { let msgs = from_data.l2_to_l1_msgs; for i in 0..msgs.len() { @@ -50,7 +47,7 @@ fn propagate_l2_to_l1_messages( fn propagate_unencrypted_logs( data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, + from_data: PublicAccumulatedData ) { let logs = from_data.unencrypted_logs_hashes; for i in 0..logs.len() { @@ -63,7 +60,7 @@ fn propagate_unencrypted_logs( fn propagate_public_data_writes( data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, + from_data: PublicAccumulatedData ) { let writes = from_data.public_data_update_requests; for i in 0..writes.len() { diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_validator.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_validator.nr index 52e0af2d111..b2a63b9c082 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_validator.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_validator.nr @@ -1,12 +1,11 @@ use crate::public_kernel_phase::PublicKernelPhase; use dep::types::{ abis::{ - accumulated_data::public_accumulated_data::{ - PublicAccumulatedData, PublicAccumulatedDataArrayLengths, - }, kernel_circuit_public_inputs::{PublicKernelCircuitPublicInputs, VMCircuitPublicInputs}, - validation_requests::public_validation_requests::PublicValidationRequestArrayLengths, - }, traits::is_empty, - utils::arrays::{array_length, assert_array_appended, assert_array_prepended}, + accumulated_data::public_accumulated_data::{PublicAccumulatedData, PublicAccumulatedDataArrayLengths}, + kernel_circuit_public_inputs::{PublicKernelCircuitPublicInputs, VMCircuitPublicInputs}, + validation_requests::public_validation_requests::PublicValidationRequestArrayLengths +}, + traits::is_empty, utils::arrays::{array_length, assert_array_appended, assert_array_prepended} }; pub struct PublicKernelOutputValidator { @@ -25,15 +24,12 @@ impl PublicKernelOutputValidator { output: PublicKernelCircuitPublicInputs, previous_kernel: PublicKernelCircuitPublicInputs, enqueued_call: VMCircuitPublicInputs, - phase: u8, + phase: u8 ) -> Self { let revertible = phase != PublicKernelPhase.SETUP; - let previous_validation_request_array_lengths = - PublicValidationRequestArrayLengths::new(previous_kernel.validation_requests); - let previous_non_revertible_data_array_lengths = - PublicAccumulatedDataArrayLengths::new(previous_kernel.end_non_revertible); - let previous_revertible_data_array_lengths = - PublicAccumulatedDataArrayLengths::new(previous_kernel.end); + let previous_validation_request_array_lengths = PublicValidationRequestArrayLengths::new(previous_kernel.validation_requests); + let previous_non_revertible_data_array_lengths = PublicAccumulatedDataArrayLengths::new(previous_kernel.end_non_revertible); + let previous_revertible_data_array_lengths = PublicAccumulatedDataArrayLengths::new(previous_kernel.end); PublicKernelOutputValidator { output, previous_kernel, @@ -42,7 +38,7 @@ impl PublicKernelOutputValidator { revertible, previous_validation_request_array_lengths, previous_non_revertible_data_array_lengths, - previous_revertible_data_array_lengths, + previous_revertible_data_array_lengths } } @@ -63,14 +59,10 @@ impl PublicKernelOutputValidator { assert_eq(out.tx_context, prev.tx_context, "mismatch tx_context"); assert_eq(out.vk_tree_root, prev.vk_tree_root, "mismatch vk_tree_root"); assert_eq( - out.protocol_contract_tree_root, - prev.protocol_contract_tree_root, - "mismatch protocol_contract_tree_root", + out.protocol_contract_tree_root, prev.protocol_contract_tree_root, "mismatch protocol_contract_tree_root" ); assert_eq( - out.global_variables, - self.enqueued_call.constants.global_variables, - "mismatch global_variables", + out.global_variables, self.enqueued_call.constants.global_variables, "mismatch global_variables" ); } @@ -80,9 +72,7 @@ impl PublicKernelOutputValidator { assert(is_empty(out), "public_teardown_call_request must be empty after teardown"); } else { assert_eq( - out, - self.previous_kernel.public_teardown_call_request, - "mismatch public_teardown_call_request", + out, self.previous_kernel.public_teardown_call_request, "mismatch public_teardown_call_request" ); } } @@ -106,31 +96,31 @@ impl PublicKernelOutputValidator { assert_array_prepended( out.note_hash_read_requests, prev.note_hash_read_requests, - prev_lengths.note_hash_read_requests, + prev_lengths.note_hash_read_requests ); assert_array_prepended( out.nullifier_read_requests, prev.nullifier_read_requests, - prev_lengths.nullifier_read_requests, + prev_lengths.nullifier_read_requests ); assert_array_prepended( out.nullifier_non_existent_read_requests, prev.nullifier_non_existent_read_requests, - prev_lengths.nullifier_non_existent_read_requests, + prev_lengths.nullifier_non_existent_read_requests ); assert_array_prepended( out.l1_to_l2_msg_read_requests, prev.l1_to_l2_msg_read_requests, - prev_lengths.l1_to_l2_msg_read_requests, + prev_lengths.l1_to_l2_msg_read_requests ); assert_array_prepended( out.public_data_reads, prev.public_data_reads, - prev_lengths.public_data_reads, + prev_lengths.public_data_reads ); } @@ -145,35 +135,35 @@ impl PublicKernelOutputValidator { out.note_hash_read_requests, curr.note_hash_read_requests, curr_lengths.note_hash_read_requests, - prev_lengths.note_hash_read_requests, + prev_lengths.note_hash_read_requests ); assert_array_appended( out.nullifier_read_requests, curr.nullifier_read_requests, curr_lengths.nullifier_read_requests, - prev_lengths.nullifier_read_requests, + prev_lengths.nullifier_read_requests ); assert_array_appended( out.nullifier_non_existent_read_requests, curr.nullifier_non_existent_read_requests, curr_lengths.nullifier_non_existent_read_requests, - prev_lengths.nullifier_non_existent_read_requests, + prev_lengths.nullifier_non_existent_read_requests ); assert_array_appended( out.l1_to_l2_msg_read_requests, curr.l1_to_l2_msg_read_requests, curr_lengths.l1_to_l2_msg_read_requests, - prev_lengths.l1_to_l2_msg_read_requests, + prev_lengths.l1_to_l2_msg_read_requests ); assert_array_appended( out.public_data_reads, curr.public_data_reads, curr_lengths.public_data_reads, - prev_lengths.public_data_reads, + prev_lengths.public_data_reads ); } @@ -190,39 +180,27 @@ impl PublicKernelOutputValidator { let out = self.output.end_non_revertible; let prev = self.previous_kernel.end_non_revertible; assert_eq( - out.note_encrypted_logs_hashes, - prev.note_encrypted_logs_hashes, - "mismatch non-revertible note_encrypted_logs_hashes", + out.note_encrypted_logs_hashes, prev.note_encrypted_logs_hashes, "mismatch non-revertible note_encrypted_logs_hashes" ); assert_eq( - out.encrypted_logs_hashes, - prev.encrypted_logs_hashes, - "mismatch non-revertible encrypted_logs_hashes", + out.encrypted_logs_hashes, prev.encrypted_logs_hashes, "mismatch non-revertible encrypted_logs_hashes" ); let out = self.output.end; let prev = self.previous_kernel.end; if revert_in_phase { assert_eq( - array_length(out.note_encrypted_logs_hashes), - 0, - "revertible note_encrypted_logs_hashes must be cleared after revert", + array_length(out.note_encrypted_logs_hashes), 0, "revertible note_encrypted_logs_hashes must be cleared after revert" ); assert_eq( - array_length(out.encrypted_logs_hashes), - 0, - "revertible encrypted_logs_hashes must be cleared after revert", + array_length(out.encrypted_logs_hashes), 0, "revertible encrypted_logs_hashes must be cleared after revert" ); } else { assert_eq( - out.note_encrypted_logs_hashes, - prev.note_encrypted_logs_hashes, - "mismatch revertible note_encrypted_logs_hashes", + out.note_encrypted_logs_hashes, prev.note_encrypted_logs_hashes, "mismatch revertible note_encrypted_logs_hashes" ); assert_eq( - out.encrypted_logs_hashes, - prev.encrypted_logs_hashes, - "mismatch revertible encrypted_logs_hashes", + out.encrypted_logs_hashes, prev.encrypted_logs_hashes, "mismatch revertible encrypted_logs_hashes" ); } } @@ -246,18 +224,14 @@ impl PublicKernelOutputValidator { self.validate_prepended_accumulated_data( out_non_revertible, prev_non_revertible, - prev_non_revertible_lengths, + prev_non_revertible_lengths ); let prepended_revertible_lengths = if revert_in_phase { empty_lengths } else { prev_revertible_lengths }; - self.validate_prepended_accumulated_data( - out_revertible, - prev_revertible, - prepended_revertible_lengths, - ); + self.validate_prepended_accumulated_data(out_revertible, prev_revertible, prepended_revertible_lengths); // Appended from enqueued call. let curr_data = self.enqueued_call.accumulated_data; @@ -276,13 +250,13 @@ impl PublicKernelOutputValidator { out_non_revertible, curr_data, prev_non_revertible_lengths, - appended_non_revertible_lengths, + appended_non_revertible_lengths ); self.validate_appended_accumulated_data( out_revertible, curr_data, prev_revertible_lengths, - appended_revertible_lengths, + appended_revertible_lengths ); } @@ -290,7 +264,7 @@ impl PublicKernelOutputValidator { _self: Self, out: PublicAccumulatedData, prev: PublicAccumulatedData, - lengths: PublicAccumulatedDataArrayLengths, + lengths: PublicAccumulatedDataArrayLengths ) { assert_array_prepended(out.note_hashes, prev.note_hashes, lengths.note_hashes); assert_array_prepended(out.nullifiers, prev.nullifiers, lengths.nullifiers); @@ -298,17 +272,17 @@ impl PublicKernelOutputValidator { assert_array_prepended( out.unencrypted_logs_hashes, prev.unencrypted_logs_hashes, - lengths.unencrypted_logs_hashes, + lengths.unencrypted_logs_hashes ); assert_array_prepended( out.public_data_update_requests, prev.public_data_update_requests, - lengths.public_data_update_requests, + lengths.public_data_update_requests ); assert_array_prepended( out.public_call_stack, prev.public_call_stack, - lengths.public_call_stack, + lengths.public_call_stack ); } @@ -317,37 +291,37 @@ impl PublicKernelOutputValidator { out: PublicAccumulatedData, curr: PublicAccumulatedData, prev_lengths: PublicAccumulatedDataArrayLengths, - curr_lengths: PublicAccumulatedDataArrayLengths, + curr_lengths: PublicAccumulatedDataArrayLengths ) { assert_array_appended( out.note_hashes, curr.note_hashes, curr_lengths.note_hashes, - prev_lengths.note_hashes, + prev_lengths.note_hashes ); assert_array_appended( out.nullifiers, curr.nullifiers, curr_lengths.nullifiers, - prev_lengths.nullifiers, + prev_lengths.nullifiers ); assert_array_appended( out.l2_to_l1_msgs, curr.l2_to_l1_msgs, curr_lengths.l2_to_l1_msgs, - prev_lengths.l2_to_l1_msgs, + prev_lengths.l2_to_l1_msgs ); assert_array_appended( out.unencrypted_logs_hashes, curr.unencrypted_logs_hashes, curr_lengths.unencrypted_logs_hashes, - prev_lengths.unencrypted_logs_hashes, + prev_lengths.unencrypted_logs_hashes ); assert_array_appended( out.public_data_update_requests, curr.public_data_update_requests, curr_lengths.public_data_update_requests, - prev_lengths.public_data_update_requests, + prev_lengths.public_data_update_requests ); } @@ -363,22 +337,14 @@ impl PublicKernelOutputValidator { expected_revertible_gas_used += curr_gas_used; } assert_eq( - out_non_revertible_gas_used, - expected_non_revertible_gas_used, - "wrong non-revertible gas used", - ); - assert_eq( - out_revertible_gas_used, - expected_revertible_gas_used, - "wrong revertible gas used", + out_non_revertible_gas_used, expected_non_revertible_gas_used, "wrong non-revertible gas used" ); + assert_eq(out_revertible_gas_used, expected_revertible_gas_used, "wrong revertible gas used"); } fn validate_end_side_effect_counter(self) { assert_eq( - self.output.end_side_effect_counter, - self.enqueued_call.end_side_effect_counter, - "mismatch end_side_effect_counter", + self.output.end_side_effect_counter, self.enqueued_call.end_side_effect_counter, "mismatch end_side_effect_counter" ); } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer.nr index 61a302e5187..7160686b142 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer.nr @@ -6,13 +6,10 @@ mod generate_public_data_leaves; pub use generate_output_hints::{OutputHints, SiloedNoteHashHint}; pub use generate_overridable_public_data_writes::LinkedIndexHint; -use crate::components::public_tail_output_composer::{ - combine_data::combine_data, generate_output_hints::generate_output_hints, -}; +use crate::components::public_tail_output_composer::{combine_data::combine_data, generate_output_hints::generate_output_hints}; use dep::types::{ - abis::kernel_circuit_public_inputs::{ - KernelCircuitPublicInputs, PublicKernelCircuitPublicInputs, - }, data::PublicDataLeafHint, partial_state_reference::PartialStateReference, + abis::kernel_circuit_public_inputs::{KernelCircuitPublicInputs, PublicKernelCircuitPublicInputs}, + data::PublicDataLeafHint, partial_state_reference::PartialStateReference }; pub struct PublicTailOutputComposer { @@ -25,31 +22,27 @@ impl PublicTailOutputComposer Self { PublicTailOutputComposer { previous_kernel, start_state, public_data_leaf_hints } } - pub unconstrained fn finish( - self, - ) -> (KernelCircuitPublicInputs, OutputHints) { + pub unconstrained fn finish(self) -> (KernelCircuitPublicInputs, OutputHints) { let output_hints = generate_output_hints(self.previous_kernel, self.public_data_leaf_hints); let end = combine_data( self.previous_kernel.end_non_revertible, self.previous_kernel.end, - output_hints, + output_hints ); - ( - KernelCircuitPublicInputs { - rollup_validation_requests: self.previous_kernel.validation_requests.for_rollup, - end, - constants: self.previous_kernel.constants, - start_state: self.start_state, - revert_code: self.previous_kernel.revert_code, - fee_payer: self.previous_kernel.fee_payer, - }, output_hints, - ) + (KernelCircuitPublicInputs { + rollup_validation_requests: self.previous_kernel.validation_requests.for_rollup, + end, + constants: self.previous_kernel.constants, + start_state: self.start_state, + revert_code: self.previous_kernel.revert_code, + fee_payer: self.previous_kernel.fee_payer + }, output_hints) } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/combine_data.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/combine_data.nr index 01c537cf41f..896616409ab 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/combine_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/combine_data.nr @@ -1,49 +1,46 @@ use crate::components::public_tail_output_composer::generate_output_hints::OutputHints; use dep::types::{ abis::{ - accumulated_data::{CombinedAccumulatedData, PublicAccumulatedData}, - log_hash::{LogHash, ScopedLogHash}, nullifier::Nullifier, - }, utils::arrays::{array_merge, dedupe_array, sort_by_counter_asc}, + accumulated_data::{CombinedAccumulatedData, PublicAccumulatedData}, + log_hash::{LogHash, ScopedLogHash}, nullifier::Nullifier +}, + utils::arrays::{array_merge, dedupe_array, sort_by_counter_asc} }; pub unconstrained fn combine_data( non_revertible: PublicAccumulatedData, revertible: PublicAccumulatedData, - output_hints: OutputHints, + output_hints: OutputHints ) -> CombinedAccumulatedData { - let nullifiers = sort_by_counter_asc(array_merge( - non_revertible.nullifiers, - revertible.nullifiers, - )) - .map(|n: Nullifier| n.value); + let nullifiers = sort_by_counter_asc(array_merge(non_revertible.nullifiers, revertible.nullifiers)).map(|n: Nullifier| n.value); - let l2_to_l1_msgs = sort_by_counter_asc(array_merge( - non_revertible.l2_to_l1_msgs, - revertible.l2_to_l1_msgs, - )); + let l2_to_l1_msgs = sort_by_counter_asc(array_merge(non_revertible.l2_to_l1_msgs, revertible.l2_to_l1_msgs)); let public_data_update_requests = dedupe_array(output_hints.public_data_writes); - let note_encrypted_logs_hashes = sort_by_counter_asc(array_merge( - non_revertible.note_encrypted_logs_hashes, - revertible.note_encrypted_logs_hashes, - )); - let note_encrypted_log_preimages_length = - note_encrypted_logs_hashes.fold(0, |a, b: LogHash| a + b.length); + let note_encrypted_logs_hashes = sort_by_counter_asc( + array_merge( + non_revertible.note_encrypted_logs_hashes, + revertible.note_encrypted_logs_hashes + ) + ); + let note_encrypted_log_preimages_length = note_encrypted_logs_hashes.fold(0, |a, b: LogHash| a + b.length); - let encrypted_logs_hashes = sort_by_counter_asc(array_merge( - non_revertible.encrypted_logs_hashes, - revertible.encrypted_logs_hashes, - )); - let encrypted_log_preimages_length = - encrypted_logs_hashes.fold(0, |a, b: ScopedLogHash| a + b.log_hash.length); + let encrypted_logs_hashes = sort_by_counter_asc( + array_merge( + non_revertible.encrypted_logs_hashes, + revertible.encrypted_logs_hashes + ) + ); + let encrypted_log_preimages_length = encrypted_logs_hashes.fold(0, |a, b: ScopedLogHash| a + b.log_hash.length); - let unencrypted_logs_hashes = sort_by_counter_asc(array_merge( - non_revertible.unencrypted_logs_hashes, - revertible.unencrypted_logs_hashes, - )); - let unencrypted_log_preimages_length = - unencrypted_logs_hashes.fold(0, |a, b: ScopedLogHash| a + b.log_hash.length); + let unencrypted_logs_hashes = sort_by_counter_asc( + array_merge( + non_revertible.unencrypted_logs_hashes, + revertible.unencrypted_logs_hashes + ) + ); + let unencrypted_log_preimages_length = unencrypted_logs_hashes.fold(0, |a, b: ScopedLogHash| a + b.log_hash.length); CombinedAccumulatedData { note_hashes: output_hints.siloed_note_hashes, @@ -56,6 +53,6 @@ pub unconstrained fn combine_data( encrypted_log_preimages_length, unencrypted_log_preimages_length, public_data_update_requests, - gas_used: revertible.gas_used + non_revertible.gas_used, + gas_used: revertible.gas_used + non_revertible.gas_used } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_output_hints.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_output_hints.nr index 17d38d69f39..7de87149d65 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_output_hints.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_output_hints.nr @@ -1,23 +1,19 @@ use crate::components::public_tail_output_composer::{ - generate_overridable_public_data_writes::{ - generate_overridable_public_data_writes, LinkedIndexHint, - }, generate_public_data_leaves::generate_public_data_leaves, + generate_overridable_public_data_writes::{generate_overridable_public_data_writes, LinkedIndexHint}, + generate_public_data_leaves::generate_public_data_leaves }; use dep::types::{ abis::{ - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - public_data_write::OverridablePublicDataWrite, - }, + kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, + public_data_write::OverridablePublicDataWrite +}, constants::{ - MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, - MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - }, data::{OverridablePublicDataTreeLeaf, PublicDataLeafHint}, hash::silo_note_hash, - traits::Empty, - utils::arrays::{ - array_merge, CombinedOrderHint, get_combined_order_hints_asc, sort_by_counter_asc, - SortedResult, - }, + MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, + MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, + MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX +}, + data::{OverridablePublicDataTreeLeaf, PublicDataLeafHint}, hash::silo_note_hash, traits::Empty, + utils::arrays::{array_merge, CombinedOrderHint, get_combined_order_hints_asc, sort_by_counter_asc, SortedResult} }; pub struct SiloedNoteHashHint { @@ -54,7 +50,7 @@ pub struct OutputHints { pub unconstrained fn generate_output_hints( previous_kernel: PublicKernelCircuitPublicInputs, - public_data_leaf_hints: [PublicDataLeafHint; NUM_PUBLIC_DATA_LEAVES], + public_data_leaf_hints: [PublicDataLeafHint; NUM_PUBLIC_DATA_LEAVES] ) -> OutputHints { let non_revertible = previous_kernel.end_non_revertible; let revertible = previous_kernel.end; @@ -62,10 +58,7 @@ pub unconstrained fn generate_output_hints( // Note hashes. let mut siloed_note_hashes = [0; MAX_NOTE_HASHES_PER_TX]; let mut siloed_note_hash_hints = [SiloedNoteHashHint::empty(); MAX_NOTE_HASHES_PER_TX]; - let sorted_unsiloed_note_hashes = sort_by_counter_asc(array_merge( - non_revertible.note_hashes, - revertible.note_hashes, - )); + let sorted_unsiloed_note_hashes = sort_by_counter_asc(array_merge(non_revertible.note_hashes, revertible.note_hashes)); let tx_hash = non_revertible.nullifiers[0].value; for i in 0..sorted_unsiloed_note_hashes.len() { let note_hash = sorted_unsiloed_note_hashes[i]; @@ -84,46 +77,36 @@ pub unconstrained fn generate_output_hints( // Public data. let combined_writes = array_merge( previous_kernel.end_non_revertible.public_data_update_requests, - previous_kernel.end.public_data_update_requests, + previous_kernel.end.public_data_update_requests ); let (public_data_leaves, unique_slot_index_hints) = generate_public_data_leaves( previous_kernel.validation_requests.public_data_reads, combined_writes, - public_data_leaf_hints, + public_data_leaf_hints ); - let (public_data_writes, public_data_linked_index_hints) = - generate_overridable_public_data_writes(combined_writes, public_data_leaves); + let (public_data_writes, public_data_linked_index_hints) = generate_overridable_public_data_writes(combined_writes, public_data_leaves); OutputHints { siloed_note_hashes, siloed_note_hash_hints, - sorted_note_hash_hints: get_combined_order_hints_asc( - non_revertible.note_hashes, - revertible.note_hashes, - ), - sorted_nullifier_hints: get_combined_order_hints_asc( - non_revertible.nullifiers, - revertible.nullifiers, - ), - sorted_l2_to_l1_msg_hints: get_combined_order_hints_asc( - non_revertible.l2_to_l1_msgs, - revertible.l2_to_l1_msgs, - ), + sorted_note_hash_hints: get_combined_order_hints_asc(non_revertible.note_hashes, revertible.note_hashes), + sorted_nullifier_hints: get_combined_order_hints_asc(non_revertible.nullifiers, revertible.nullifiers), + sorted_l2_to_l1_msg_hints: get_combined_order_hints_asc(non_revertible.l2_to_l1_msgs, revertible.l2_to_l1_msgs), sorted_note_encrypted_log_hash_hints: get_combined_order_hints_asc( non_revertible.note_encrypted_logs_hashes, - revertible.note_encrypted_logs_hashes, + revertible.note_encrypted_logs_hashes ), sorted_encrypted_log_hash_hints: get_combined_order_hints_asc( non_revertible.encrypted_logs_hashes, - revertible.encrypted_logs_hashes, + revertible.encrypted_logs_hashes ), sorted_unencrypted_log_hash_hints: get_combined_order_hints_asc( non_revertible.unencrypted_logs_hashes, - revertible.unencrypted_logs_hashes, + revertible.unencrypted_logs_hashes ), public_data_writes, public_data_leaves, unique_slot_index_hints, - public_data_linked_index_hints, + public_data_linked_index_hints } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_overridable_public_data_writes.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_overridable_public_data_writes.nr index f67768f322c..f7fca732af2 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_overridable_public_data_writes.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_overridable_public_data_writes.nr @@ -1,9 +1,6 @@ use dep::types::{ - abis::{ - public_data_update_request::PublicDataUpdateRequest, - public_data_write::OverridablePublicDataWrite, - }, data::OverridablePublicDataTreeLeaf, traits::Empty, - utils::arrays::{array_length, find_index_hint}, + abis::{public_data_update_request::PublicDataUpdateRequest, public_data_write::OverridablePublicDataWrite}, + data::OverridablePublicDataTreeLeaf, traits::Empty, utils::arrays::{array_length, find_index_hint} }; pub struct LinkedIndexHint { @@ -19,7 +16,7 @@ impl Empty for LinkedIndexHint { pub unconstrained fn generate_overridable_public_data_writes( public_data_writes: [PublicDataUpdateRequest; NUM_WRITES], - public_data_leaves: [OverridablePublicDataTreeLeaf; NUM_LEAVES], + public_data_leaves: [OverridablePublicDataTreeLeaf; NUM_LEAVES] ) -> ([OverridablePublicDataWrite; NUM_WRITES], [LinkedIndexHint; NUM_WRITES]) { let mut overridable_public_data_writes = [OverridablePublicDataWrite::empty(); NUM_WRITES]; let mut hints = [LinkedIndexHint::empty(); NUM_WRITES]; diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_public_data_leaves.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_public_data_leaves.nr index 7f73cccfe48..cdb031824e2 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_public_data_leaves.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_public_data_leaves.nr @@ -1,7 +1,7 @@ use dep::types::{ abis::{public_data_read::PublicDataRead, public_data_update_request::PublicDataUpdateRequest}, data::{OverridablePublicDataTreeLeaf, PublicDataLeafHint, PublicDataTreeLeaf}, traits::Empty, - utils::arrays::{get_sorted_result, SortedResult}, + utils::arrays::{get_sorted_result, SortedResult} }; pub struct SlotIndex { @@ -37,7 +37,7 @@ fn compare_by_index(a: SlotIndex, b: SlotIndex) -> bool { pub unconstrained fn generate_public_data_leaves( reads: [PublicDataRead; NUM_READS], writes: [PublicDataUpdateRequest; NUM_WRITES], - hints: [PublicDataLeafHint; NUM_HINTS], + hints: [PublicDataLeafHint; NUM_HINTS] ) -> ([OverridablePublicDataTreeLeaf; NUM_HINTS], SortedResult) { // Combine reads and writes. The combined data has the slots and original indexes. // Original indexes for writes are modified to have an offset of NUM_READS, ensuring that writes are placed after reads. @@ -51,9 +51,7 @@ pub unconstrained fn generate_public_data_leaves { @@ -38,15 +38,9 @@ impl PublicTailOutputValidator, - public_data_leaf_hints: [PublicDataLeafHint; NUM_PUBLIC_DATA_LEAVES], + public_data_leaf_hints: [PublicDataLeafHint; NUM_PUBLIC_DATA_LEAVES] ) -> Self { - PublicTailOutputValidator { - output, - previous_kernel, - start_state, - hints, - public_data_leaf_hints, - } + PublicTailOutputValidator { output, previous_kernel, start_state, hints, public_data_leaf_hints } } pub fn validate(self) { @@ -61,17 +55,11 @@ impl PublicTailOutputValidator PublicTailOutputValidator PublicTailOutputValidator PublicTailOutputValidator PublicTailOutputValidator PublicTailOutputValidator PublicTailOutputValidator PublicTailOutputValidator( public_data_writes: [OverridablePublicDataWrite; NUM_WRITES], public_data_leaves: [OverridablePublicDataTreeLeaf; NUM_LEAVES], - hints: [LinkedIndexHint; NUM_WRITES], + hints: [LinkedIndexHint; NUM_WRITES] ) { for i in 0..public_data_writes.len() { let write = public_data_writes[i]; @@ -18,32 +16,17 @@ pub fn validate_linked_public_data_writes Self { let public_data_writes = pad_end( [ - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 33, - new_value: 300, - counter: 30, - }, - override_counter: 0, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 22, - new_value: 202, - counter: 40, - }, - override_counter: 50, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 11, - new_value: 100, - counter: 10, - }, - override_counter: 0, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 22, - new_value: 201, - counter: 20, - }, - override_counter: 40, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 22, - new_value: 203, - counter: 50, - }, - override_counter: 0, - }, - ], - OverridablePublicDataWrite::empty(), + OverridablePublicDataWrite { write: PublicDataUpdateRequest { leaf_slot: 33, new_value: 300, counter: 30 }, override_counter: 0 }, + OverridablePublicDataWrite { write: PublicDataUpdateRequest { leaf_slot: 22, new_value: 202, counter: 40 }, override_counter: 50 }, + OverridablePublicDataWrite { write: PublicDataUpdateRequest { leaf_slot: 11, new_value: 100, counter: 10 }, override_counter: 0 }, + OverridablePublicDataWrite { write: PublicDataUpdateRequest { leaf_slot: 22, new_value: 201, counter: 20 }, override_counter: 40 }, + OverridablePublicDataWrite { write: PublicDataUpdateRequest { leaf_slot: 22, new_value: 203, counter: 50 }, override_counter: 0 } + ], + OverridablePublicDataWrite::empty() ); let public_data_leaves = pad_end( [ - OverridablePublicDataTreeLeaf { - leaf: PublicDataTreeLeaf { slot: 0, value: 0 }, - override_counter: 0, - }, - OverridablePublicDataTreeLeaf { - leaf: PublicDataTreeLeaf { slot: 22, value: 200 }, - override_counter: 20, - }, - OverridablePublicDataTreeLeaf { - leaf: PublicDataTreeLeaf { slot: 44, value: 0 }, - override_counter: 0, - }, - OverridablePublicDataTreeLeaf { - leaf: PublicDataTreeLeaf { slot: 11, value: 0 }, - override_counter: 10, - }, - OverridablePublicDataTreeLeaf { - leaf: PublicDataTreeLeaf { slot: 33, value: 0 }, - override_counter: 30, - }, - ], - OverridablePublicDataTreeLeaf::empty(), + OverridablePublicDataTreeLeaf { leaf: PublicDataTreeLeaf { slot: 0, value: 0 }, override_counter: 0 }, + OverridablePublicDataTreeLeaf { leaf: PublicDataTreeLeaf { slot: 22, value: 200 }, override_counter: 20 }, + OverridablePublicDataTreeLeaf { leaf: PublicDataTreeLeaf { slot: 44, value: 0 }, override_counter: 0 }, + OverridablePublicDataTreeLeaf { leaf: PublicDataTreeLeaf { slot: 11, value: 0 }, override_counter: 10 }, + OverridablePublicDataTreeLeaf { leaf: PublicDataTreeLeaf { slot: 33, value: 0 }, override_counter: 30 } + ], + OverridablePublicDataTreeLeaf::empty() ); let hints = pad_end( [ - LinkedIndexHint { is_first_write: true, prev_index: 4 }, - LinkedIndexHint { is_first_write: false, prev_index: 3 }, - LinkedIndexHint { is_first_write: true, prev_index: 3 }, - LinkedIndexHint { is_first_write: true, prev_index: 1 }, - LinkedIndexHint { is_first_write: false, prev_index: 1 }, - ], - LinkedIndexHint::empty(), + LinkedIndexHint { is_first_write: true, prev_index: 4 }, + LinkedIndexHint { is_first_write: false, prev_index: 3 }, + LinkedIndexHint { is_first_write: true, prev_index: 3 }, + LinkedIndexHint { is_first_write: true, prev_index: 1 }, + LinkedIndexHint { is_first_write: false, prev_index: 1 } + ], + LinkedIndexHint::empty() ); TestBuilder { public_data_writes, public_data_leaves, hints } } pub fn execute(self) { - validate_linked_public_data_writes( - self.public_data_writes, - self.public_data_leaves, - self.hints, - ); + validate_linked_public_data_writes(self.public_data_writes, self.public_data_leaves, self.hints); } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_validator/validate_public_data_leaf_memberships.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_validator/validate_public_data_leaf_memberships.nr index c5c184ff8c2..1bd7f6b3c2d 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_validator/validate_public_data_leaf_memberships.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_validator/validate_public_data_leaf_memberships.nr @@ -1,6 +1,6 @@ use dep::types::{ data::{OverridablePublicDataTreeLeaf, PublicDataLeafHint}, - merkle_tree::conditionally_assert_check_membership, + merkle_tree::conditionally_assert_check_membership }; // Perform membership check for all non-zero leaf slots, ensuring that the values being read are correct and the public data tree is updated with the correct low leaves. @@ -8,7 +8,7 @@ use dep::types::{ pub fn validate_public_data_leaf_memberships( leaves: [OverridablePublicDataTreeLeaf; N], leaf_hints: [PublicDataLeafHint; N], - tree_root: Field, + tree_root: Field ) { for i in 0..leaves.len() { let leaf = leaves[i].leaf; @@ -17,8 +17,7 @@ pub fn validate_public_data_leaf_memberships( let exists_in_tree = leaf.slot == hint.preimage.slot; if exists_in_tree { assert( - leaf.value == hint.preimage.value, - "Hinted public data value does not match the value in leaf preimage", + leaf.value == hint.preimage.value, "Hinted public data value does not match the value in leaf preimage" ); } else { assert(leaf.value == 0, "Value must be 0 for non-existent public data"); @@ -29,7 +28,7 @@ pub fn validate_public_data_leaf_memberships( exists_in_tree, hint.preimage, hint.membership_witness, - tree_root, + tree_root ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_validator/validate_unique_leaf_slots.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_validator/validate_unique_leaf_slots.nr index 63fd9ffea1e..2b259bcff8c 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_validator/validate_unique_leaf_slots.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_validator/validate_unique_leaf_slots.nr @@ -3,7 +3,7 @@ use dep::types::{data::OverridablePublicDataTreeLeaf, utils::arrays::SortedResul // Validate that every non-zero slot in leaves is unique. pub fn validate_unique_leaf_slots( leaves: [OverridablePublicDataTreeLeaf; N], - unique_slot_index_hints: SortedResult, + unique_slot_index_hints: SortedResult ) { let sorted_leaf_slots = unique_slot_index_hints.sorted_array; let sorted_leaf_slot_indexes = unique_slot_index_hints.sorted_index_hints; @@ -31,7 +31,7 @@ mod tests { use crate::components::public_tail_output_validator::validate_unique_leaf_slots::validate_unique_leaf_slots; use dep::types::{ data::{OverridablePublicDataTreeLeaf, PublicDataTreeLeaf}, tests::utils::pad_end, - utils::arrays::SortedResult, + utils::arrays::SortedResult }; global NUM_TEST_LEAVES = 10; @@ -56,12 +56,14 @@ mod tests { } pub fn update_leaves(&mut self, slots: [Field; N]) { - let leaves = slots.map(|slot: Field| { + let leaves = slots.map( + |slot: Field| { OverridablePublicDataTreeLeaf { leaf: PublicDataTreeLeaf { slot, value: 1 }, override_counter: 0, } - }); + } + ); self.leaves = pad_end(leaves, OverridablePublicDataTreeLeaf::empty()); } @@ -85,7 +87,7 @@ mod tests { let hints = SortedResult { sorted_array: self.sorted_array, sorted_index_hints: self.sorted_index_hints, - original_index_hints: self.original_index_hints, + original_index_hints: self.original_index_hints }; validate_unique_leaf_slots(self.leaves, hints); } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/vm_circuit_output_composer.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/vm_circuit_output_composer.nr index 8318a02c6c3..d297aa65076 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/vm_circuit_output_composer.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/vm_circuit_output_composer.nr @@ -3,18 +3,18 @@ mod propagate_accumulated_data; use crate::components::vm_circuit_output_composer::propagate_accumulated_data::propagate_accumulated_data; use dep::types::{ abis::{ - accumulated_data::{PublicAccumulatedDataArrayLengths, PublicAccumulatedDataBuilder}, - combined_constant_data::CombinedConstantData, gas::Gas, - kernel_circuit_public_inputs::vm_circuit_public_inputs::VMCircuitPublicInputs, - public_call_request::PublicCallRequest, - public_circuit_public_inputs::PublicCircuitPublicInputs, public_data_read::PublicDataRead, - public_inner_call_request::PublicInnerCallRequest, - validation_requests::{ - PublicValidationRequestArrayLengths, - public_validation_requests_builder::PublicValidationRequestsBuilder, - }, - }, constants::MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, traits::is_empty, - utils::arrays::array_to_bounded_vec, + accumulated_data::{PublicAccumulatedDataArrayLengths, PublicAccumulatedDataBuilder}, + combined_constant_data::CombinedConstantData, gas::Gas, + kernel_circuit_public_inputs::vm_circuit_public_inputs::VMCircuitPublicInputs, + public_call_request::PublicCallRequest, public_circuit_public_inputs::PublicCircuitPublicInputs, + public_data_read::PublicDataRead, public_inner_call_request::PublicInnerCallRequest, + validation_requests::{ + PublicValidationRequestArrayLengths, + public_validation_requests_builder::PublicValidationRequestsBuilder +} +}, + constants::MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, traits::is_empty, + utils::arrays::array_to_bounded_vec }; // TODO(#7124): To be deprecated. @@ -37,24 +37,21 @@ impl VMCircuitOutputComposer { pub fn new_from_previous_kernel(previous_kernel: VMCircuitPublicInputs) -> Self { let mut public_call_stack = array_to_bounded_vec(previous_kernel.public_call_stack); let _ = public_call_stack.pop(); - let validation_requests = - PublicValidationRequestsBuilder::new(previous_kernel.validation_requests); + let validation_requests = PublicValidationRequestsBuilder::new(previous_kernel.validation_requests); let accumulated_data = PublicAccumulatedDataBuilder::new(previous_kernel.accumulated_data); VMCircuitOutputComposer { constants: previous_kernel.constants, call_request: previous_kernel.call_request, public_call_stack, - previous_validation_request_array_lengths: previous_kernel - .previous_validation_request_array_lengths, + previous_validation_request_array_lengths: previous_kernel.previous_validation_request_array_lengths, validation_requests, - previous_accumulated_data_array_lengths: previous_kernel - .previous_accumulated_data_array_lengths, + previous_accumulated_data_array_lengths: previous_kernel.previous_accumulated_data_array_lengths, accumulated_data, start_side_effect_counter: previous_kernel.start_side_effect_counter, end_side_effect_counter: previous_kernel.end_side_effect_counter, start_gas_left: previous_kernel.start_gas_left, transaction_fee: previous_kernel.transaction_fee, - reverted: previous_kernel.reverted, + reverted: previous_kernel.reverted } } @@ -73,8 +70,7 @@ impl VMCircuitOutputComposer { constants: self.constants, call_request: self.call_request, public_call_stack: self.public_call_stack.storage, - previous_validation_request_array_lengths: self - .previous_validation_request_array_lengths, + previous_validation_request_array_lengths: self.previous_validation_request_array_lengths, validation_requests: self.validation_requests.finish(), previous_accumulated_data_array_lengths: self.previous_accumulated_data_array_lengths, accumulated_data: self.accumulated_data.finish(), @@ -82,7 +78,7 @@ impl VMCircuitOutputComposer { end_side_effect_counter: self.end_side_effect_counter, start_gas_left: self.start_gas_left, transaction_fee: self.transaction_fee, - reverted: self.reverted, + reverted: self.reverted } } @@ -108,9 +104,7 @@ impl VMCircuitOutputComposer { for i in 0..nullifier_read_requests.len() { let request = nullifier_read_requests[i]; if !is_empty(request) { - self.validation_requests.nullifier_read_requests.push(request.scope( - contract_address, - )); + self.validation_requests.nullifier_read_requests.push(request.scope(contract_address)); } } @@ -118,9 +112,7 @@ impl VMCircuitOutputComposer { for i in 0..nullifier_non_existent_read_requests.len() { let request = nullifier_non_existent_read_requests[i]; if !is_empty(request) { - self.validation_requests.nullifier_non_existent_read_requests.push(request.scope( - contract_address, - )); + self.validation_requests.nullifier_non_existent_read_requests.push(request.scope(contract_address)); } } @@ -136,9 +128,7 @@ impl VMCircuitOutputComposer { for i in 0..read_requests.len() { let read_request = read_requests[i]; if !is_empty(read_request) { - self.validation_requests.public_data_reads.push( - PublicDataRead::from_contract_storage_read(contract_address, read_request), - ); + self.validation_requests.public_data_reads.push(PublicDataRead::from_contract_storage_read(contract_address, read_request)); } } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/vm_circuit_output_composer/propagate_accumulated_data.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/vm_circuit_output_composer/propagate_accumulated_data.nr index 3c1df8c3fbf..1c396c03eb8 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/vm_circuit_output_composer/propagate_accumulated_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/vm_circuit_output_composer/propagate_accumulated_data.nr @@ -1,14 +1,15 @@ use dep::types::{ abis::{ - accumulated_data::PublicAccumulatedDataBuilder, nullifier::Nullifier, - public_circuit_public_inputs::PublicCircuitPublicInputs, - public_data_update_request::PublicDataUpdateRequest, - }, hash::compute_siloed_nullifier, + accumulated_data::PublicAccumulatedDataBuilder, nullifier::Nullifier, + public_circuit_public_inputs::PublicCircuitPublicInputs, + public_data_update_request::PublicDataUpdateRequest +}, + hash::compute_siloed_nullifier }; pub fn propagate_accumulated_data( data: &mut PublicAccumulatedDataBuilder, - public_call: PublicCircuitPublicInputs, + public_call: PublicCircuitPublicInputs ) -> PublicAccumulatedDataBuilder { propagate_note_hashes(data, public_call); propagate_nullifiers(data, public_call); @@ -18,10 +19,7 @@ pub fn propagate_accumulated_data( *data } -fn propagate_note_hashes( - data: &mut PublicAccumulatedDataBuilder, - public_call: PublicCircuitPublicInputs, -) { +fn propagate_note_hashes(data: &mut PublicAccumulatedDataBuilder, public_call: PublicCircuitPublicInputs) { let contract_address = public_call.call_context.contract_address; let note_hashes = public_call.note_hashes; for i in 0..note_hashes.len() { @@ -32,10 +30,7 @@ fn propagate_note_hashes( } } -fn propagate_nullifiers( - data: &mut PublicAccumulatedDataBuilder, - public_call: PublicCircuitPublicInputs, -) { +fn propagate_nullifiers(data: &mut PublicAccumulatedDataBuilder, public_call: PublicCircuitPublicInputs) { let contract_address = public_call.call_context.contract_address; let nullifiers = public_call.nullifiers; for i in 0..nullifiers.len() { @@ -43,20 +38,13 @@ fn propagate_nullifiers( if nullifier.counter != 0 { let siloed_value = compute_siloed_nullifier(contract_address, nullifier.value); data.nullifiers.push( - Nullifier { - value: siloed_value, - counter: nullifier.counter, - note_hash: nullifier.note_hash, - }, + Nullifier { value: siloed_value, counter: nullifier.counter, note_hash: nullifier.note_hash } ); } } } -fn propagate_l2_to_l1_messages( - data: &mut PublicAccumulatedDataBuilder, - public_call: PublicCircuitPublicInputs, -) { +fn propagate_l2_to_l1_messages(data: &mut PublicAccumulatedDataBuilder, public_call: PublicCircuitPublicInputs) { let contract_address = public_call.call_context.contract_address; let msgs = public_call.l2_to_l1_msgs; for i in 0..msgs.len() { @@ -67,10 +55,7 @@ fn propagate_l2_to_l1_messages( } } -fn propagate_unencrypted_logs( - data: &mut PublicAccumulatedDataBuilder, - public_call: PublicCircuitPublicInputs, -) { +fn propagate_unencrypted_logs(data: &mut PublicAccumulatedDataBuilder, public_call: PublicCircuitPublicInputs) { let contract_address = public_call.call_context.contract_address; let logs = public_call.unencrypted_logs_hashes; for i in 0..logs.len() { @@ -81,21 +66,13 @@ fn propagate_unencrypted_logs( } } -fn propagate_public_data_writes( - data: &mut PublicAccumulatedDataBuilder, - public_call: PublicCircuitPublicInputs, -) { +fn propagate_public_data_writes(data: &mut PublicAccumulatedDataBuilder, public_call: PublicCircuitPublicInputs) { let contract_address = public_call.call_context.contract_address; let writes = public_call.contract_storage_update_requests; for i in 0..writes.len() { let write = writes[i]; if write.counter != 0 { - data.public_data_update_requests.push( - PublicDataUpdateRequest::from_contract_storage_update_request( - contract_address, - write, - ), - ); + data.public_data_update_requests.push(PublicDataUpdateRequest::from_contract_storage_update_request(contract_address, write)); } } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_inner.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_inner.nr index 82790088d16..f78dae00e3c 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_inner.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_inner.nr @@ -1,7 +1,7 @@ use crate::components::vm_circuit_output_composer::VMCircuitOutputComposer; use dep::types::abis::{ kernel_circuit_public_inputs::VMCircuitPublicInputs, - public_kernel_inner_data::PublicKernelInnerData, public_call_data::PublicCallData, + public_kernel_inner_data::PublicKernelInnerData, public_call_data::PublicCallData }; // TODO(#7124): To be deprecated. @@ -12,8 +12,6 @@ pub struct PublicKernelInnerCircuitPrivateInputs { impl PublicKernelInnerCircuitPrivateInputs { fn execute(self) -> VMCircuitPublicInputs { - VMCircuitOutputComposer::new_from_previous_kernel(self.previous_kernel.public_inputs) - .propagate_from_public_call(self.public_call.public_inputs) - .finish() + VMCircuitOutputComposer::new_from_previous_kernel(self.previous_kernel.public_inputs).propagate_from_public_call(self.public_call.public_inputs).finish() } } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_merge.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_merge.nr index 6fa7f50fd1c..a893faae3aa 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_merge.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_merge.nr @@ -1,17 +1,18 @@ use crate::{ components::{ - enqueued_call_data_validator::EnqueuedCallDataValidator, - previous_kernel_validator::PreviousKernelValidator, - public_kernel_output_composer::PublicKernelOutputComposer, - public_kernel_output_validator::PublicKernelOutputValidator, - }, public_kernel_phase::PublicKernelPhase, + enqueued_call_data_validator::EnqueuedCallDataValidator, + previous_kernel_validator::PreviousKernelValidator, + public_kernel_output_composer::PublicKernelOutputComposer, + public_kernel_output_validator::PublicKernelOutputValidator +}, + public_kernel_phase::PublicKernelPhase }; use dep::types::{ abis::{ - enqueued_call_data::EnqueuedCallData, - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - public_kernel_data::PublicKernelData, - }, constants::{TUBE_INDEX, PUBLIC_KERNEL_MERGE_INDEX}, + enqueued_call_data::EnqueuedCallData, kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, + public_kernel_data::PublicKernelData +}, + constants::{TUBE_INDEX, PUBLIC_KERNEL_MERGE_INDEX} }; global ALLOWED_PREVIOUS_CIRCUITS = [TUBE_INDEX, PUBLIC_KERNEL_MERGE_INDEX]; @@ -32,12 +33,8 @@ impl PublicKernelMergeCircuitPrivateInputs { fn get_phase(self) -> u8 { let public_inputs = self.previous_kernel.public_inputs; - let needs_setup = !public_inputs.end_non_revertible.public_call_stack[0] - .call_context - .contract_address - .is_zero(); - let needs_app_logic = - !public_inputs.end.public_call_stack[0].call_context.contract_address.is_zero(); + let needs_setup = !public_inputs.end_non_revertible.public_call_stack[0].call_context.contract_address.is_zero(); + let needs_app_logic = !public_inputs.end.public_call_stack[0].call_context.contract_address.is_zero(); if needs_setup { PublicKernelPhase.SETUP } else if needs_app_logic { @@ -50,26 +47,27 @@ impl PublicKernelMergeCircuitPrivateInputs { fn execute(self) -> PublicKernelCircuitPublicInputs { let phase = self.get_phase(); - let output = unsafe { self.generate_output(phase) }; + let output = unsafe { + self.generate_output(phase) + }; let output_validator = PublicKernelOutputValidator::new( output, self.previous_kernel.public_inputs, self.enqueued_call.data, - phase, + phase ); let previous_kernel_validator = PreviousKernelValidator::new(self.previous_kernel); previous_kernel_validator.validate_proof(ALLOWED_PREVIOUS_CIRCUITS); - let enqueued_call_data_validator = - EnqueuedCallDataValidator::new(self.enqueued_call, phase); + let enqueued_call_data_validator = EnqueuedCallDataValidator::new(self.enqueued_call, phase); enqueued_call_data_validator.validate_proof(); enqueued_call_data_validator.validate_against_previous_kernel( self.previous_kernel.public_inputs, output_validator.previous_validation_request_array_lengths, output_validator.previous_non_revertible_data_array_lengths, - output_validator.previous_revertible_data_array_lengths, + output_validator.previous_revertible_data_array_lengths ); output_validator.validate(); @@ -81,16 +79,16 @@ impl PublicKernelMergeCircuitPrivateInputs { mod tests { use crate::{ public_kernel_phase::PublicKernelPhase, - public_kernel_merge::{ALLOWED_PREVIOUS_CIRCUITS, PublicKernelMergeCircuitPrivateInputs}, + public_kernel_merge::{ALLOWED_PREVIOUS_CIRCUITS, PublicKernelMergeCircuitPrivateInputs} }; use dep::types::{ abis::{ - accumulated_data::PublicAccumulatedDataArrayLengths, gas::Gas, - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - max_block_number::MaxBlockNumber, - validation_requests::PublicValidationRequestArrayLengths, - }, constants::{PRIVATE_KERNEL_TAIL_TO_PUBLIC_INDEX, BASE_ROLLUP_INDEX}, - tests::{fixture_builder::FixtureBuilder, utils::assert_array_eq}, + accumulated_data::PublicAccumulatedDataArrayLengths, gas::Gas, + kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, max_block_number::MaxBlockNumber, + validation_requests::PublicValidationRequestArrayLengths + }, + constants::{PRIVATE_KERNEL_TAIL_TO_PUBLIC_INDEX, BASE_ROLLUP_INDEX}, + tests::{fixture_builder::FixtureBuilder, utils::assert_array_eq} }; struct PublicKernelMergeCircuitPrivateInputsBuilder { @@ -102,9 +100,7 @@ mod tests { impl PublicKernelMergeCircuitPrivateInputsBuilder { pub fn new() -> Self { - let previous_kernel = FixtureBuilder::new().as_parent_contract().in_vk_tree( - PRIVATE_KERNEL_TAIL_TO_PUBLIC_INDEX, - ); + let previous_kernel = FixtureBuilder::new().as_parent_contract().in_vk_tree(PRIVATE_KERNEL_TAIL_TO_PUBLIC_INDEX); let mut previous_revertible = FixtureBuilder::new(); let mut enqueued_call = FixtureBuilder::new().is_public_function(); // Add an offset so that the mock data won't be the same as the values in previous_kernel. @@ -114,12 +110,7 @@ mod tests { let phase = PublicKernelPhase.SETUP; - PublicKernelMergeCircuitPrivateInputsBuilder { - previous_kernel, - previous_revertible, - enqueued_call, - phase, - } + PublicKernelMergeCircuitPrivateInputsBuilder { previous_kernel, previous_revertible, enqueued_call, phase } } pub fn execute(&mut self) -> PublicKernelCircuitPublicInputs { @@ -207,17 +198,17 @@ mod tests { assert_array_eq( public_inputs.validation_requests.public_data_reads, - [prev_reads[0], prev_reads[1], curr_reads[0]], + [prev_reads[0], prev_reads[1], curr_reads[0]] ); assert_array_eq( public_inputs.end_non_revertible.note_hashes, - [prev_note_hashes[0], curr_note_hashes[0], curr_note_hashes[1]], + [prev_note_hashes[0], curr_note_hashes[0], curr_note_hashes[1]] ); assert_array_eq( public_inputs.end_non_revertible.public_call_stack, - [prev_calls[0]], // Public call requests can only be propagated from previous kernel. + [prev_calls[0]] // Public call requests can only be propagated from previous kernel. ); } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_tail.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_tail.nr index fc4ec877a16..b3d27e26313 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_tail.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_tail.nr @@ -1,28 +1,24 @@ use crate::{ components::{ - previous_kernel_validator::PreviousKernelValidator, - public_tail_output_composer::{OutputHints, PublicTailOutputComposer}, - public_tail_output_validator::PublicTailOutputValidator, - }, public_kernel_phase::PublicKernelPhase, + previous_kernel_validator::PreviousKernelValidator, + public_tail_output_composer::{OutputHints, PublicTailOutputComposer}, + public_tail_output_validator::PublicTailOutputValidator +}, + public_kernel_phase::PublicKernelPhase }; use dep::reset_kernel_lib::{ - NullifierReadRequestHints, NullifierNonExistentReadRequestHints, - PublicValidationRequestProcessor, - public_data_read_request_hints::{ - build_public_data_read_request_hints, PublicDataReadRequestHints, - }, TreeLeafReadRequestHint, + NullifierReadRequestHints, NullifierNonExistentReadRequestHints, PublicValidationRequestProcessor, + public_data_read_request_hints::{build_public_data_read_request_hints, PublicDataReadRequestHints}, + TreeLeafReadRequestHint }; use dep::types::{ - abis::{ - kernel_circuit_public_inputs::KernelCircuitPublicInputs, - public_kernel_data::PublicKernelData, - }, + abis::{kernel_circuit_public_inputs::KernelCircuitPublicInputs, public_kernel_data::PublicKernelData}, constants::{ - L1_TO_L2_MSG_TREE_HEIGHT, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_PUBLIC_DATA_HINTS, MAX_PUBLIC_DATA_READS_PER_TX, NOTE_HASH_TREE_HEIGHT, - PUBLIC_KERNEL_MERGE_INDEX, - }, data::PublicDataLeafHint, partial_state_reference::PartialStateReference, + L1_TO_L2_MSG_TREE_HEIGHT, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, + MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_PUBLIC_DATA_HINTS, MAX_PUBLIC_DATA_READS_PER_TX, + NOTE_HASH_TREE_HEIGHT, PUBLIC_KERNEL_MERGE_INDEX +}, + data::PublicDataLeafHint, partial_state_reference::PartialStateReference }; global ALLOWED_PREVIOUS_CIRCUITS = [PUBLIC_KERNEL_MERGE_INDEX]; @@ -38,20 +34,17 @@ pub struct PublicKernelTailCircuitPrivateInputs { } impl PublicKernelTailCircuitPrivateInputs { - unconstrained fn generate_output_and_hints( - self, - ) -> (KernelCircuitPublicInputs, OutputHints, PublicDataReadRequestHints) { + unconstrained fn generate_output_and_hints(self) -> (KernelCircuitPublicInputs, OutputHints, PublicDataReadRequestHints) { let (output, output_hints) = PublicTailOutputComposer::new( self.previous_kernel.public_inputs, self.start_state, - self.public_data_hints, - ) - .finish(); + self.public_data_hints + ).finish(); let public_data_read_request_hints = build_public_data_read_request_hints( self.previous_kernel.public_inputs.validation_requests.public_data_reads, output_hints.public_data_writes, - output_hints.public_data_leaves, + output_hints.public_data_leaves ); (output, output_hints, public_data_read_request_hints) @@ -62,8 +55,9 @@ impl PublicKernelTailCircuitPrivateInputs { previous_kernel_validator.validate_phase(PublicKernelPhase.TAIL); previous_kernel_validator.validate_proof(ALLOWED_PREVIOUS_CIRCUITS); - let (output, output_hints, public_data_read_request_hints) = - unsafe { self.generate_output_and_hints() }; + let (output, output_hints, public_data_read_request_hints) = unsafe { + self.generate_output_and_hints() + }; PublicValidationRequestProcessor::new( self.previous_kernel.public_inputs, @@ -74,18 +68,16 @@ impl PublicKernelTailCircuitPrivateInputs { self.l1_to_l2_msg_read_request_hints, output_hints.public_data_writes, output_hints.public_data_leaves, - public_data_read_request_hints, - ) - .validate(); + public_data_read_request_hints + ).validate(); PublicTailOutputValidator::new( output, self.previous_kernel.public_inputs, self.start_state, output_hints, - self.public_data_hints, - ) - .validate(); + self.public_data_hints + ).validate(); output } @@ -95,43 +87,44 @@ mod tests { use crate::public_kernel_tail::PublicKernelTailCircuitPrivateInputs; use dep::reset_kernel_lib::{ tests::{ - nullifier_non_existent_read_request_hints_builder::NullifierNonExistentReadRequestHintsBuilder, - nullifier_read_request_hints_builder::NullifierReadRequestHintsBuilder, - }, reset::read_request::{PendingReadHint, ReadRequestState, ReadRequestStatus}, - TreeLeafReadRequestHint, + nullifier_non_existent_read_request_hints_builder::NullifierNonExistentReadRequestHintsBuilder, + nullifier_read_request_hints_builder::NullifierReadRequestHintsBuilder + }, + reset::read_request::{PendingReadHint, ReadRequestState, ReadRequestStatus}, + TreeLeafReadRequestHint }; use dep::types::{ abis::{ - kernel_circuit_public_inputs::KernelCircuitPublicInputs, nullifier::ScopedNullifier, - nullifier_leaf_preimage::NullifierLeafPreimage, - public_data_update_request::PublicDataUpdateRequest, - }, address::AztecAddress, + kernel_circuit_public_inputs::KernelCircuitPublicInputs, nullifier::ScopedNullifier, + nullifier_leaf_preimage::NullifierLeafPreimage, + public_data_update_request::PublicDataUpdateRequest + }, + address::AztecAddress, constants::{ - L1_TO_L2_MSG_TREE_HEIGHT, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_PUBLIC_DATA_HINTS, NOTE_HASH_SUBTREE_HEIGHT, - NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_TREE_HEIGHT, - NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_SUBTREE_HEIGHT, - PUBLIC_DATA_SUBTREE_HEIGHT, PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, - PUBLIC_DATA_TREE_HEIGHT, MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - NOTE_HASH_TREE_HEIGHT, PUBLIC_KERNEL_MERGE_INDEX, BASE_ROLLUP_INDEX, - }, data::{PublicDataLeafHint, PublicDataTreeLeafPreimage}, + L1_TO_L2_MSG_TREE_HEIGHT, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, + MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, + MAX_PUBLIC_DATA_HINTS, NOTE_HASH_SUBTREE_HEIGHT, NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, + NULLIFIER_TREE_HEIGHT, NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_SUBTREE_HEIGHT, + PUBLIC_DATA_SUBTREE_HEIGHT, PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, PUBLIC_DATA_TREE_HEIGHT, + MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, NOTE_HASH_TREE_HEIGHT, PUBLIC_KERNEL_MERGE_INDEX, + BASE_ROLLUP_INDEX + }, + data::{PublicDataLeafHint, PublicDataTreeLeafPreimage}, hash::{compute_siloed_nullifier, silo_note_hash}, tests::{ - fixture_builder::FixtureBuilder, merkle_tree_utils::NonEmptyMerkleTree, - utils::{assert_array_eq, pad_end, swap_items}, - }, traits::is_empty, partial_state_reference::PartialStateReference, - utils::arrays::{array_merge, find_index_hint}, merkle_tree::MembershipWitness, + fixture_builder::FixtureBuilder, merkle_tree_utils::NonEmptyMerkleTree, + utils::{assert_array_eq, pad_end, swap_items} + }, + traits::is_empty, partial_state_reference::PartialStateReference, + utils::arrays::{array_merge, find_index_hint}, merkle_tree::MembershipWitness }; - fn build_note_hash_tree( - leaf_preimages: [Field; N], - ) -> NonEmptyMerkleTree { + fn build_note_hash_tree(leaf_preimages: [Field; N]) -> NonEmptyMerkleTree { NonEmptyMerkleTree::new( pad_end(leaf_preimages, 0), [0; NOTE_HASH_TREE_HEIGHT], [0; NOTE_HASH_TREE_HEIGHT - NOTE_HASH_SUBTREE_HEIGHT], - [0; NOTE_HASH_SUBTREE_HEIGHT], + [0; NOTE_HASH_SUBTREE_HEIGHT] ) } @@ -145,21 +138,19 @@ mod tests { pre_existing_nullifiers.map(|preimage: NullifierLeafPreimage| preimage.hash()), [0; NULLIFIER_TREE_HEIGHT], [0; NULLIFIER_TREE_HEIGHT - NULLIFIER_SUBTREE_HEIGHT], - [0; NULLIFIER_SUBTREE_HEIGHT], + [0; NULLIFIER_SUBTREE_HEIGHT] ) } - fn build_public_data_tree( - leaf_preimages: [PublicDataTreeLeafPreimage; N], - ) -> NonEmptyMerkleTree { + fn build_public_data_tree(leaf_preimages: [PublicDataTreeLeafPreimage; N]) -> NonEmptyMerkleTree { NonEmptyMerkleTree::new( pad_end( leaf_preimages.map(|preimage: PublicDataTreeLeafPreimage| preimage.hash()), - 0, + 0 ), [0; PUBLIC_DATA_TREE_HEIGHT], [0; PUBLIC_DATA_TREE_HEIGHT - PUBLIC_DATA_SUBTREE_HEIGHT], - [0; PUBLIC_DATA_SUBTREE_HEIGHT], + [0; PUBLIC_DATA_SUBTREE_HEIGHT] ) } @@ -181,8 +172,7 @@ mod tests { pub fn new() -> PublicKernelTailCircuitPrivateInputsBuilder { let previous_kernel = FixtureBuilder::new().in_vk_tree(PUBLIC_KERNEL_MERGE_INDEX); let previous_revertible = FixtureBuilder::new(); - let nullifier_non_existent_read_request_hints_builder = - NullifierNonExistentReadRequestHintsBuilder::new(); + let nullifier_non_existent_read_request_hints_builder = NullifierNonExistentReadRequestHintsBuilder::new(); PublicKernelTailCircuitPrivateInputsBuilder { previous_kernel, @@ -195,7 +185,7 @@ mod tests { note_hash_leaf_preimages: [598589, 714714], public_data_tree: NonEmptyMerkleTree::empty(), public_data_leaf_preimages: pad_end([], PublicDataTreeLeafPreimage::empty()), - start_state: PartialStateReference::empty(), + start_state: PartialStateReference::empty() } } @@ -208,9 +198,7 @@ mod tests { pub fn with_nullifier_tree(&mut self) -> Self { let nullifier_tree = build_nullifier_tree(); - self.nullifier_non_existent_read_request_hints_builder.set_nullifier_tree( - nullifier_tree, - ); + self.nullifier_non_existent_read_request_hints_builder.set_nullifier_tree(nullifier_tree); self.start_state.nullifier_tree.root = nullifier_tree.get_root(); self.previous_kernel.historical_header.state.partial.nullifier_tree.root = 22222; *self @@ -219,19 +207,9 @@ mod tests { pub fn with_public_data_tree(&mut self) -> Self { let public_data_leaf_preimages = [ PublicDataTreeLeafPreimage { slot: 0, value: 0, next_slot: 1111, next_index: 3 }, - PublicDataTreeLeafPreimage { - slot: 2222, - value: 200, - next_slot: 3333, - next_index: 2, - }, + PublicDataTreeLeafPreimage { slot: 2222, value: 200, next_slot: 3333, next_index: 2 }, PublicDataTreeLeafPreimage { slot: 3333, value: 300, next_slot: 0, next_index: 0 }, - PublicDataTreeLeafPreimage { - slot: 1111, - value: 100, - next_slot: 2222, - next_index: 1, - }, + PublicDataTreeLeafPreimage { slot: 1111, value: 100, next_slot: 2222, next_index: 1 } ]; let public_data_tree = build_public_data_tree(public_data_leaf_preimages); self.public_data_leaf_preimages = pad_end( @@ -246,7 +224,7 @@ mod tests { pub fn add_note_hash_read_request(&mut self, leaf_index: u32) { self.previous_kernel.add_note_hash_tree_leaf_read_requests( self.note_hash_leaf_preimages[leaf_index], - leaf_index as Field, + leaf_index as Field ); let sibling_path = self.note_hash_tree.get_sibling_path(leaf_index); self.note_hash_read_request_hints.push(TreeLeafReadRequestHint { sibling_path }); @@ -273,15 +251,13 @@ mod tests { fn set_nullifiers_for_non_existent_read_request_hints(&mut self) { let nullifiers = array_merge( self.previous_kernel.nullifiers.storage, - self.previous_revertible.nullifiers.storage, - ) - .map(|n: ScopedNullifier| n.nullifier); + self.previous_revertible.nullifiers.storage + ).map(|n: ScopedNullifier| n.nullifier); self.nullifier_non_existent_read_request_hints_builder.set_nullifiers(nullifiers); } pub fn add_pending_revertible_nullifier_read_request(&mut self, nullifier_index: u32) { - let read_request_index = - self.previous_kernel.add_read_request_for_pending_nullifier(nullifier_index); + let read_request_index = self.previous_kernel.add_read_request_for_pending_nullifier(nullifier_index); self.sync_counters(); let hint_index = self.nullifier_read_request_hints_builder.pending_read_hints.len(); let pending_value_index = nullifier_index + self.previous_kernel.nullifiers.len(); @@ -292,8 +268,7 @@ mod tests { } pub fn add_pending_non_revertible_nullifier_read_request(&mut self, nullifier_index: u32) { - let read_request_index = - self.previous_kernel.add_read_request_for_pending_nullifier(nullifier_index); + let read_request_index = self.previous_kernel.add_read_request_for_pending_nullifier(nullifier_index); self.sync_counters(); let hint_index = self.nullifier_read_request_hints_builder.pending_read_hints.len(); let hint = PendingReadHint { read_request_index, pending_value_index: nullifier_index }; @@ -305,8 +280,7 @@ mod tests { pub fn read_non_existent_nullifier(&mut self, unsiloed_nullifier: Field) { self.previous_kernel.add_non_existent_read_request_for_nullifier(unsiloed_nullifier); self.sync_counters(); - let siloed_nullifier = - compute_siloed_nullifier(self.previous_kernel.contract_address, unsiloed_nullifier); + let siloed_nullifier = compute_siloed_nullifier(self.previous_kernel.contract_address, unsiloed_nullifier); self.nullifier_non_existent_read_request_hints_builder.add_value_read(siloed_nullifier); } @@ -316,22 +290,20 @@ mod tests { self.public_data_leaf_preimages, |p: PublicDataTreeLeafPreimage| { !leaf_slot.lt(p.slot) & (p.next_slot.eq(0) | leaf_slot.lt(p.next_slot)) - }, + } ) }; let preimage = self.public_data_leaf_preimages[low_leaf_index]; let membership_witness = MembershipWitness { leaf_index: low_leaf_index as Field, - sibling_path: self.public_data_tree.get_sibling_path(low_leaf_index), + sibling_path: self.public_data_tree.get_sibling_path(low_leaf_index) }; PublicDataLeafHint { preimage, membership_witness } } - fn generate_public_data_leaf_hints( - &mut self, - ) -> [PublicDataLeafHint; MAX_PUBLIC_DATA_HINTS] { + fn generate_public_data_leaf_hints(&mut self) -> [PublicDataLeafHint; MAX_PUBLIC_DATA_HINTS] { let mut public_data_hints = BoundedVec::new(); let mut unique_slots: BoundedVec = BoundedVec::new(); @@ -372,11 +344,13 @@ mod tests { self.set_nullifiers_for_non_existent_read_request_hints(); let public_data_hints = self.generate_public_data_leaf_hints(); - let nullifier_read_request_hints = - unsafe { self.nullifier_read_request_hints_builder.to_hints() }; + let nullifier_read_request_hints = unsafe { + self.nullifier_read_request_hints_builder.to_hints() + }; - let nullifier_non_existent_read_request_hints = - unsafe { self.nullifier_non_existent_read_request_hints_builder.to_hints() }; + let nullifier_non_existent_read_request_hints = unsafe { + self.nullifier_non_existent_read_request_hints_builder.to_hints() + }; let kernel = PublicKernelTailCircuitPrivateInputs { previous_kernel, @@ -385,7 +359,7 @@ mod tests { nullifier_non_existent_read_request_hints, l1_to_l2_msg_read_request_hints: self.l1_to_l2_msg_read_request_hints.storage, public_data_hints, - start_state: self.start_state, + start_state: self.start_state }; kernel.execute() @@ -415,36 +389,25 @@ mod tests { let prev_encrypted_log_preimages_length = 13; let prev_unencrypted_logs_hash = 956; let prev_unencrypted_log_preimages_length = 24; - builder.previous_revertible.add_encrypted_log_hash( - prev_encrypted_logs_hash, - prev_encrypted_log_preimages_length, - ); + builder.previous_revertible.add_encrypted_log_hash(prev_encrypted_logs_hash, prev_encrypted_log_preimages_length); builder.previous_revertible.add_unencrypted_log_hash( prev_unencrypted_logs_hash, - prev_unencrypted_log_preimages_length, + prev_unencrypted_log_preimages_length ); // Logs for the current call stack. let unencrypted_logs_hash = 26; let unencrypted_log_preimages_length = 50; - builder.previous_revertible.add_unencrypted_log_hash( - unencrypted_logs_hash, - unencrypted_log_preimages_length, - ); + builder.previous_revertible.add_unencrypted_log_hash(unencrypted_logs_hash, unencrypted_log_preimages_length); let public_inputs = builder.execute(); + assert_eq(public_inputs.end.encrypted_log_preimages_length, prev_encrypted_log_preimages_length); assert_eq( - public_inputs.end.encrypted_log_preimages_length, - prev_encrypted_log_preimages_length, - ); - assert_eq( - public_inputs.end.unencrypted_log_preimages_length, - unencrypted_log_preimages_length + prev_unencrypted_log_preimages_length, + public_inputs.end.unencrypted_log_preimages_length, unencrypted_log_preimages_length + prev_unencrypted_log_preimages_length ); assert_eq( - public_inputs.end.unencrypted_logs_hashes, - builder.previous_revertible.unencrypted_logs_hashes.storage, + public_inputs.end.unencrypted_logs_hashes, builder.previous_revertible.unencrypted_logs_hashes.storage ); } @@ -543,8 +506,7 @@ mod tests { #[test] unconstrained fn public_data_reads_and_writes_succeeds() { - let mut builder = - PublicKernelTailCircuitPrivateInputsBuilder::new().with_public_data_tree(); + let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new().with_public_data_tree(); builder.previous_kernel.add_public_data_read_request(22, 0); @@ -568,16 +530,8 @@ mod tests { let prev_writes = builder.previous_kernel.public_data_update_requests.storage; // Shuffle the items so that they are not sorted by counter. - swap_items( - &mut builder.previous_kernel.public_data_update_requests, - 0, - 3, - ); - swap_items( - &mut builder.previous_kernel.public_data_update_requests, - 1, - 3, - ); + swap_items(&mut builder.previous_kernel.public_data_update_requests, 0, 3); + swap_items(&mut builder.previous_kernel.public_data_update_requests, 1, 3); swap_items(&mut builder.previous_kernel.public_data_reads, 1, 4); swap_items(&mut builder.previous_kernel.public_data_reads, 0, 3); @@ -585,29 +539,16 @@ mod tests { assert_array_eq( public_inputs.end.public_data_update_requests, [ - PublicDataUpdateRequest { - leaf_slot: 3333, - new_value: 301, - counter: prev_writes[4].counter, - }, - PublicDataUpdateRequest { - leaf_slot: 11, - new_value: 500, - counter: prev_writes[1].counter, - }, - PublicDataUpdateRequest { - leaf_slot: 22, - new_value: 701, - counter: prev_writes[3].counter, - }, - ], + PublicDataUpdateRequest { leaf_slot: 3333, new_value: 301, counter: prev_writes[4].counter }, + PublicDataUpdateRequest { leaf_slot: 11, new_value: 500, counter: prev_writes[1].counter }, + PublicDataUpdateRequest { leaf_slot: 22, new_value: 701, counter: prev_writes[3].counter } + ] ); } #[test(should_fail_with = "value in OverridablePublicDataTreeLeaf does not match read request")] unconstrained fn reading_uninitialized_public_data_non_zero_value_fails() { - let mut builder = - PublicKernelTailCircuitPrivateInputsBuilder::new().with_public_data_tree(); + let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new().with_public_data_tree(); builder.previous_kernel.add_public_data_read_request(1234, 1); @@ -661,7 +602,7 @@ mod tests { silo_note_hash(non_rev[2], tx_hash, 4), silo_note_hash(rev[2], tx_hash, 5), silo_note_hash(rev[3], tx_hash, 6), - silo_note_hash(rev[4], tx_hash, 7), + silo_note_hash(rev[4], tx_hash, 7) ]; assert_array_eq(public_inputs.end.note_hashes, expected); } @@ -687,8 +628,7 @@ mod tests { let public_inputs = builder.execute(); - let expected = [non_rev[0], rev[0], rev[1], non_rev[1], non_rev[2], rev[2], rev[3], rev[4]] - .map(|n: ScopedNullifier| n.nullifier.value); + let expected = [non_rev[0], rev[0], rev[1], non_rev[1], non_rev[2], rev[2], rev[3], rev[4]].map(|n: ScopedNullifier| n.nullifier.value); assert_array_eq(public_inputs.end.nullifiers, expected); } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/src/main.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/src/main.nr index c131d7dda9e..8f37b525057 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/src/main.nr @@ -1,8 +1,6 @@ use dep::public_kernel_lib::PublicKernelMergeCircuitPrivateInputs; use dep::types::PublicKernelCircuitPublicInputs; -unconstrained fn main( - input: PublicKernelMergeCircuitPrivateInputs, -) -> pub PublicKernelCircuitPublicInputs { +unconstrained fn main(input: PublicKernelMergeCircuitPrivateInputs) -> pub PublicKernelCircuitPublicInputs { input.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/src/main.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/src/main.nr index d30846be377..d387581d4aa 100644 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/src/main.nr +++ b/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/src/main.nr @@ -1,8 +1,6 @@ use dep::public_kernel_lib::PublicKernelTailCircuitPrivateInputs; use dep::types::KernelCircuitPublicInputs; -unconstrained fn main( - input: PublicKernelTailCircuitPrivateInputs, -) -> pub KernelCircuitPublicInputs { +unconstrained fn main(input: PublicKernelTailCircuitPrivateInputs) -> pub KernelCircuitPublicInputs { input.execute() } diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/lib.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/lib.nr index ef1eacbc177..7e2624a7fae 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/lib.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/lib.nr @@ -15,5 +15,5 @@ pub use public_validation_request_processor::PublicValidationRequestProcessor; pub use reset::{ key_validation_hint::KeyValidationHint, transient_data::{TransientDataIndexHint, verify_squashed_transient_data}, - tree_leaf_read_request::TreeLeafReadRequestHint, + tree_leaf_read_request::TreeLeafReadRequestHint }; diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/note_hash_read_request_reset.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/note_hash_read_request_reset.nr index 41e52c15b7d..2484aaf8bb3 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/note_hash_read_request_reset.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/note_hash_read_request_reset.nr @@ -1,11 +1,9 @@ // This will be moved to a separate Read Request Reset Circuit. -use crate::reset::read_request::{ - PendingReadHint, ReadRequestStatus, ReadValueHint, SettledReadHint, -}; +use crate::reset::read_request::{PendingReadHint, ReadRequestStatus, ReadValueHint, SettledReadHint}; use dep::types::{ abis::note_hash_leaf_preimage::NoteHashLeafPreimage, constants::{MAX_NOTE_HASH_READ_REQUESTS_PER_TX, NOTE_HASH_TREE_HEIGHT}, - merkle_tree::MembershipWitness, + merkle_tree::MembershipWitness }; pub struct NoteHashSettledReadHint { @@ -33,7 +31,7 @@ impl SettledReadHint for NoteHashSe NoteHashSettledReadHint { read_request_index: read_request_len, membership_witness: MembershipWitness::empty(), - leaf_preimage: NoteHashLeafPreimage::empty(), + leaf_preimage: NoteHashLeafPreimage::empty() } } } @@ -48,16 +46,16 @@ mod tests { use crate::note_hash_read_request_reset::NoteHashSettledReadHint; use crate::reset::read_request::{ get_unverified_read_requests, PendingReadHint, ReadRequestState, ReadRequestStatus, - verify_reset_read_requests, + verify_reset_read_requests }; use dep::types::{ address::AztecAddress, merkle_tree::MembershipWitness, abis::{ - note_hash::{NoteHash, ScopedNoteHash}, note_hash_leaf_preimage::NoteHashLeafPreimage, - read_request::{ReadRequest, ScopedReadRequest}, - }, constants::NOTE_HASH_TREE_HEIGHT, hash::compute_siloed_note_hash, - tests::{merkle_tree_utils::NonEmptyMerkleTree, utils::assert_array_eq}, - traits::is_empty_array, + note_hash::{NoteHash, ScopedNoteHash}, note_hash_leaf_preimage::NoteHashLeafPreimage, + read_request::{ReadRequest, ScopedReadRequest} + }, + constants::NOTE_HASH_TREE_HEIGHT, hash::compute_siloed_note_hash, + tests::{merkle_tree_utils::NonEmptyMerkleTree, utils::assert_array_eq}, traits::is_empty_array }; struct TestBuilder { @@ -75,16 +73,15 @@ mod tests { // Create 4 note hashes. 10 and 11 are settled. 12 and 13 are pending. let note_hashes = [10, 11, 12, 13]; - let siloed_note_hashes = - note_hashes.map(|n| compute_siloed_note_hash(contract_address, n)); + let siloed_note_hashes = note_hashes.map(|n| compute_siloed_note_hash(contract_address, n)); // Create 5 read requests. 0 and 3 are reading settled note hashes. 1, 2 and 4 are reading pending note hashes. let read_requests = [ - ReadRequest { value: note_hashes[1], counter: 11 }.scope(contract_address), // settled - ReadRequest { value: note_hashes[3], counter: 13 }.scope(contract_address), // pending - ReadRequest { value: note_hashes[2], counter: 39 }.scope(contract_address), // pending - ReadRequest { value: note_hashes[0], counter: 46 }.scope(contract_address), // settled - ReadRequest { value: note_hashes[3], counter: 78 }.scope(contract_address), // pending + ReadRequest { value: note_hashes[1], counter: 11 }.scope(contract_address),// settled + ReadRequest { value: note_hashes[3], counter: 13 }.scope(contract_address),// pending + ReadRequest { value: note_hashes[2], counter: 39 }.scope(contract_address),// pending + ReadRequest { value: note_hashes[0], counter: 46 }.scope(contract_address),// settled + ReadRequest { value: note_hashes[3], counter: 78 }.scope(contract_address) // pending ]; let read_request_statuses = [ @@ -92,25 +89,25 @@ mod tests { ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 0 }, ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 1 }, ReadRequestStatus { state: ReadRequestState.SETTLED, hint_index: 1 }, - ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 2 }, + ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 2 } ]; let pending_values = [ NoteHash { value: note_hashes[2], counter: 2 }.scope(contract_address), NoteHash { value: note_hashes[3], counter: 8 }.scope(contract_address), ScopedNoteHash::empty(), - ScopedNoteHash::empty(), + ScopedNoteHash::empty() ]; let pending_read_hints = [ PendingReadHint { read_request_index: 1, pending_value_index: 1 }, PendingReadHint { read_request_index: 2, pending_value_index: 0 }, - PendingReadHint { read_request_index: 4, pending_value_index: 1 }, + PendingReadHint { read_request_index: 4, pending_value_index: 1 } ]; let leaf_preimages = [ NoteHashLeafPreimage { value: siloed_note_hashes[0] }, - NoteHashLeafPreimage { value: siloed_note_hashes[1] }, + NoteHashLeafPreimage { value: siloed_note_hashes[1] } ]; TestBuilder { @@ -119,21 +116,19 @@ mod tests { read_request_statuses, pending_values, pending_read_hints, - leaf_preimages, + leaf_preimages } } } impl TestBuilder { - fn build_tree( - self, - ) -> NonEmptyMerkleTree<2, NOTE_HASH_TREE_HEIGHT, NOTE_HASH_TREE_HEIGHT - 1, 1> { + fn build_tree(self) -> NonEmptyMerkleTree<2, NOTE_HASH_TREE_HEIGHT, NOTE_HASH_TREE_HEIGHT - 1, 1> { NonEmptyMerkleTree::new( [self.leaf_preimages[0].as_leaf(), self.leaf_preimages[1].as_leaf()], [0; NOTE_HASH_TREE_HEIGHT], [0; NOTE_HASH_TREE_HEIGHT - 1], - [0; 1], + [0; 1] ) } @@ -142,34 +137,28 @@ mod tests { let hints = [ NoteHashSettledReadHint { read_request_index: 0, - membership_witness: MembershipWitness { - leaf_index: 1, - sibling_path: tree.get_sibling_path(1), - }, - leaf_preimage: self.leaf_preimages[1], + membership_witness: MembershipWitness { leaf_index: 1, sibling_path: tree.get_sibling_path(1) }, + leaf_preimage: self.leaf_preimages[1] }, NoteHashSettledReadHint { read_request_index: 3, - membership_witness: MembershipWitness { - leaf_index: 0, - sibling_path: tree.get_sibling_path(0), - }, - leaf_preimage: self.leaf_preimages[0], - }, + membership_witness: MembershipWitness { leaf_index: 0, sibling_path: tree.get_sibling_path(0) }, + leaf_preimage: self.leaf_preimages[0] + } ]; let tree_root = tree.get_root(); (hints, tree_root) } - pub unconstrained fn get_unverified_read_requests( - self, - ) -> [ScopedReadRequest; READ_REQUEST_LEN] { + pub unconstrained fn get_unverified_read_requests(self) -> [ScopedReadRequest; READ_REQUEST_LEN] { get_unverified_read_requests(self.read_requests, self.read_request_statuses) } pub fn verify(self) { let (settled_hints, tree_root) = self.get_settled_read_hints(); - let unverified_read_requests = unsafe { self.get_unverified_read_requests() }; + let unverified_read_requests = unsafe { + self.get_unverified_read_requests() + }; verify_reset_read_requests( self.read_requests, self.pending_values, @@ -177,7 +166,7 @@ mod tests { self.pending_read_hints, settled_hints, tree_root, - unverified_read_requests, + unverified_read_requests ); } } @@ -186,7 +175,9 @@ mod tests { fn verify_reset_note_hash_read_requests_clears_all_succeeds() { let builder = TestBuilder::new(); - let unverified_read_requests = unsafe { builder.get_unverified_read_requests() }; + let unverified_read_requests = unsafe { + builder.get_unverified_read_requests() + }; assert(is_empty_array(unverified_read_requests)); builder.verify(); @@ -200,10 +191,12 @@ mod tests { builder.read_request_statuses[4] = ReadRequestStatus::empty(); let read_requests = builder.read_requests; - let unverified_read_requests = unsafe { builder.get_unverified_read_requests() }; + let unverified_read_requests = unsafe { + builder.get_unverified_read_requests() + }; assert_array_eq( unverified_read_requests, - [read_requests[2], read_requests[4]], + [read_requests[2], read_requests[4]] ); builder.verify(); diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_non_existent_read_request_reset.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_non_existent_read_request_reset.nr index 3c6bf8c74f3..82fe8c04b55 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_non_existent_read_request_reset.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_non_existent_read_request_reset.nr @@ -2,10 +2,7 @@ use crate::reset::non_existent_read_request::NonMembershipHint; use dep::types::{ abis::{nullifier::Nullifier, nullifier_leaf_preimage::NullifierLeafPreimage}, merkle_tree::MembershipWitness, - constants::{ - MAX_NULLIFIERS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - NULLIFIER_TREE_HEIGHT, - }, + constants::{MAX_NULLIFIERS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, NULLIFIER_TREE_HEIGHT} }; pub struct NullifierNonMembershipHint { diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_read_request_reset.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_read_request_reset.nr index 04c6d5a5d36..9139947a6cf 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_read_request_reset.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_read_request_reset.nr @@ -1,11 +1,9 @@ // This will be moved to a separate Read Request Reset Circuit. -use crate::reset::read_request::{ - PendingReadHint, ReadRequestStatus, ReadValueHint, SettledReadHint, -}; +use crate::reset::read_request::{PendingReadHint, ReadRequestStatus, ReadValueHint, SettledReadHint}; use dep::types::{ abis::nullifier_leaf_preimage::NullifierLeafPreimage, constants::{MAX_NULLIFIER_READ_REQUESTS_PER_TX, NULLIFIER_TREE_HEIGHT}, - merkle_tree::MembershipWitness, + merkle_tree::MembershipWitness }; pub struct NullifierSettledReadHint { @@ -33,7 +31,7 @@ impl SettledReadHint for Nullifier NullifierSettledReadHint { read_request_index: read_request_len, membership_witness: MembershipWitness::empty(), - leaf_preimage: NullifierLeafPreimage::empty(), + leaf_preimage: NullifierLeafPreimage::empty() } } } @@ -48,17 +46,17 @@ mod tests { use crate::nullifier_read_request_reset::NullifierSettledReadHint; use crate::reset::read_request::{ get_unverified_read_requests, PendingReadHint, ReadRequestState, ReadRequestStatus, - verify_reset_read_requests, + verify_reset_read_requests }; use dep::types::{ address::AztecAddress, abis::{ - nullifier::{Nullifier, ScopedNullifier}, nullifier_leaf_preimage::NullifierLeafPreimage, - read_request::{ReadRequest, ScopedReadRequest}, - }, constants::NULLIFIER_TREE_HEIGHT, hash::compute_siloed_nullifier, + nullifier::{Nullifier, ScopedNullifier}, nullifier_leaf_preimage::NullifierLeafPreimage, + read_request::{ReadRequest, ScopedReadRequest} + }, + constants::NULLIFIER_TREE_HEIGHT, hash::compute_siloed_nullifier, merkle_tree::MembershipWitness, - tests::{merkle_tree_utils::NonEmptyMerkleTree, utils::assert_array_eq}, - traits::is_empty_array, + tests::{merkle_tree_utils::NonEmptyMerkleTree, utils::assert_array_eq}, traits::is_empty_array }; struct TestBuilder { @@ -75,46 +73,33 @@ mod tests { // Create 4 nullifiers. 10 and 11 are settled. 12 and 13 are pending. let inner_nullifiers = [10, 11, 12, 13]; - let nullifiers = - inner_nullifiers.map(|n| compute_siloed_nullifier(contract_address, n)); + let nullifiers = inner_nullifiers.map(|n| compute_siloed_nullifier(contract_address, n)); // Create 5 read requests. 0 and 3 are reading settled nullifiers. 1, 2 and 4 are reading pending nullifiers. let read_requests = [ - ReadRequest { value: inner_nullifiers[1], counter: 11 }.scope(contract_address), // settled - ReadRequest { value: inner_nullifiers[3], counter: 13 }.scope(contract_address), // pending - ReadRequest { value: inner_nullifiers[2], counter: 39 }.scope(contract_address), // pending - ReadRequest { value: inner_nullifiers[0], counter: 46 }.scope(contract_address), // settled - ReadRequest { value: inner_nullifiers[3], counter: 78 }.scope(contract_address), // pending + ReadRequest { value: inner_nullifiers[1], counter: 11 }.scope(contract_address),// settled + ReadRequest { value: inner_nullifiers[3], counter: 13 }.scope(contract_address),// pending + ReadRequest { value: inner_nullifiers[2], counter: 39 }.scope(contract_address),// pending + ReadRequest { value: inner_nullifiers[0], counter: 46 }.scope(contract_address),// settled + ReadRequest { value: inner_nullifiers[3], counter: 78 }.scope(contract_address) // pending ]; let pending_values = [ - Nullifier { value: inner_nullifiers[2], counter: 2, note_hash: 0 }.scope( - contract_address, - ), - Nullifier { value: inner_nullifiers[3], counter: 8, note_hash: 0 }.scope( - contract_address, - ), - ScopedNullifier::empty(), + Nullifier { value: inner_nullifiers[2], counter: 2, note_hash: 0 }.scope(contract_address), + Nullifier { value: inner_nullifiers[3], counter: 8, note_hash: 0 }.scope(contract_address), ScopedNullifier::empty(), + ScopedNullifier::empty() ]; let pending_read_hints = [ PendingReadHint { read_request_index: 1, pending_value_index: 1 }, PendingReadHint { read_request_index: 2, pending_value_index: 0 }, - PendingReadHint { read_request_index: 4, pending_value_index: 1 }, + PendingReadHint { read_request_index: 4, pending_value_index: 1 } ]; let leaf_preimages = [ - NullifierLeafPreimage { - nullifier: nullifiers[0], - next_nullifier: nullifiers[1], - next_index: 1, - }, - NullifierLeafPreimage { - nullifier: nullifiers[1], - next_nullifier: 0, - next_index: 0, - }, + NullifierLeafPreimage { nullifier: nullifiers[0], next_nullifier: nullifiers[1], next_index: 1 }, + NullifierLeafPreimage { nullifier: nullifiers[1], next_nullifier: 0, next_index: 0 } ]; let read_request_statuses = [ @@ -122,28 +107,20 @@ mod tests { ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 0 }, ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 1 }, ReadRequestStatus { state: ReadRequestState.SETTLED, hint_index: 1 }, - ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 2 }, + ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 2 } ]; - TestBuilder { - read_requests, - read_request_statuses, - pending_values, - pending_read_hints, - leaf_preimages, - } + TestBuilder { read_requests, read_request_statuses, pending_values, pending_read_hints, leaf_preimages } } } impl TestBuilder { - fn build_tree( - self, - ) -> NonEmptyMerkleTree<2, NULLIFIER_TREE_HEIGHT, NULLIFIER_TREE_HEIGHT - 1, 1> { + fn build_tree(self) -> NonEmptyMerkleTree<2, NULLIFIER_TREE_HEIGHT, NULLIFIER_TREE_HEIGHT - 1, 1> { NonEmptyMerkleTree::new( [self.leaf_preimages[0].hash(), self.leaf_preimages[1].hash()], [0; NULLIFIER_TREE_HEIGHT], [0; NULLIFIER_TREE_HEIGHT - 1], - [0; 1], + [0; 1] ) } @@ -152,34 +129,28 @@ mod tests { let hints = [ NullifierSettledReadHint { read_request_index: 0, - membership_witness: MembershipWitness { - leaf_index: 1, - sibling_path: tree.get_sibling_path(1), - }, - leaf_preimage: self.leaf_preimages[1], + membership_witness: MembershipWitness { leaf_index: 1, sibling_path: tree.get_sibling_path(1) }, + leaf_preimage: self.leaf_preimages[1] }, NullifierSettledReadHint { read_request_index: 3, - membership_witness: MembershipWitness { - leaf_index: 0, - sibling_path: tree.get_sibling_path(0), - }, - leaf_preimage: self.leaf_preimages[0], - }, + membership_witness: MembershipWitness { leaf_index: 0, sibling_path: tree.get_sibling_path(0) }, + leaf_preimage: self.leaf_preimages[0] + } ]; let tree_root = tree.get_root(); (hints, tree_root) } - pub unconstrained fn get_unverified_read_requests( - self, - ) -> [ScopedReadRequest; READ_REQUEST_LEN] { + pub unconstrained fn get_unverified_read_requests(self) -> [ScopedReadRequest; READ_REQUEST_LEN] { get_unverified_read_requests(self.read_requests, self.read_request_statuses) } pub fn verify(self) { let (settled_hints, tree_root) = self.get_settled_read_hints(); - let unverified_read_requests = unsafe { self.get_unverified_read_requests() }; + let unverified_read_requests = unsafe { + self.get_unverified_read_requests() + }; verify_reset_read_requests( self.read_requests, self.pending_values, @@ -187,7 +158,7 @@ mod tests { self.pending_read_hints, settled_hints, tree_root, - unverified_read_requests, + unverified_read_requests ); } } @@ -196,7 +167,9 @@ mod tests { fn verify_reset_nullifier_read_requests_clears_all_succeeds() { let builder = TestBuilder::new(); - let unverified_read_requests = unsafe { builder.get_unverified_read_requests() }; + let unverified_read_requests = unsafe { + builder.get_unverified_read_requests() + }; assert(is_empty_array(unverified_read_requests)); builder.verify(); @@ -210,10 +183,12 @@ mod tests { builder.read_request_statuses[4] = ReadRequestStatus::empty(); let read_requests = builder.read_requests; - let unverified_read_requests = unsafe { builder.get_unverified_read_requests() }; + let unverified_read_requests = unsafe { + builder.get_unverified_read_requests() + }; assert_array_eq( unverified_read_requests, - [read_requests[2], read_requests[4]], + [read_requests[2], read_requests[4]] ); builder.verify(); diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/private_validation_request_processor.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/private_validation_request_processor.nr index c2a429d7382..e6d77af37fe 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/private_validation_request_processor.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/private_validation_request_processor.nr @@ -2,16 +2,11 @@ use crate::{ note_hash_read_request_reset::NoteHashReadRequestHints, nullifier_read_request_reset::NullifierReadRequestHints, reset::read_request::{get_unverified_read_requests, verify_reset_read_requests}, - reset::key_validation_hint::{ - get_unverified_key_validation_requests, KeyValidationHint, - verify_reset_key_validation_requests, - }, + reset::key_validation_hint::{get_unverified_key_validation_requests, KeyValidationHint, verify_reset_key_validation_requests} }; use dep::types::{ - abis::{ - note_hash::ScopedNoteHash, nullifier::ScopedNullifier, - validation_requests::PrivateValidationRequests, - }, constants::{MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX}, + abis::{note_hash::ScopedNoteHash, nullifier::ScopedNullifier, validation_requests::PrivateValidationRequests}, + constants::{MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX} }; pub struct PrivateValidationRequestProcessor { @@ -30,17 +25,17 @@ impl PrivateValidationRequests { let note_hash_read_requests = get_unverified_read_requests( self.validation_requests.note_hash_read_requests, - self.note_hash_read_request_hints.read_request_statuses, + self.note_hash_read_request_hints.read_request_statuses ); let nullifier_read_requests = get_unverified_read_requests( self.validation_requests.nullifier_read_requests, - self.nullifier_read_request_hints.read_request_statuses, + self.nullifier_read_request_hints.read_request_statuses ); let scoped_key_validation_requests_and_generators = get_unverified_key_validation_requests( self.validation_requests.scoped_key_validation_requests_and_generators, - self.key_validation_hints, + self.key_validation_hints ); PrivateValidationRequests { @@ -48,15 +43,13 @@ impl { @@ -13,7 +13,7 @@ pub struct PublicDataReadRequestHints { pub unconstrained fn build_public_data_read_request_hints( reads: [PublicDataRead; NUM_READS], writes: [OverridablePublicDataWrite; NUM_WRITES], - leaf_data: [OverridablePublicDataTreeLeaf; NUM_LEAVES], + leaf_data: [OverridablePublicDataTreeLeaf; NUM_LEAVES] ) -> PublicDataReadRequestHints { let mut read_request_statuses = [ReadRequestStatus::empty(); NUM_READS]; let mut pending_read_hints = [ReadIndexHint::nada(NUM_READS); NUM_READS]; @@ -29,7 +29,7 @@ pub unconstrained fn build_public_data_read_request_hints w.counter()) & ((read.counter < w.override_counter) | (w.override_counter == 0)) - }, + } ); if write_index != writes.len() { pending_read_hints[num_pending_reads] = @@ -39,11 +39,10 @@ pub unconstrained fn build_public_data_read_request_hints { @@ -50,16 +50,17 @@ impl PublicVal l1_to_l2_msg_read_request_hints: [TreeLeafReadRequestHint; MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX], pending_public_data_writes: [OverridablePublicDataWrite; NUN_PUBLIC_DATA_WRITES], public_data_leaves: [OverridablePublicDataTreeLeaf; NUM_PUBLIC_DATA_LEAVES], - public_data_read_request_hints: PublicDataReadRequestHints, + public_data_read_request_hints: PublicDataReadRequestHints ) -> Self { let non_revertible_nullifiers = public_inputs.end_non_revertible.nullifiers; let revertible_nullifiers = public_inputs.end.nullifiers; - let pending_nullifiers = - unsafe { combine_arrays(non_revertible_nullifiers, revertible_nullifiers) }; + let pending_nullifiers = unsafe { + combine_arrays(non_revertible_nullifiers, revertible_nullifiers) + }; assert_combined_array( non_revertible_nullifiers, revertible_nullifiers, - pending_nullifiers, + pending_nullifiers ); PublicValidationRequestProcessor { @@ -71,15 +72,10 @@ impl PublicVal nullifier_non_existent_read_request_hints, nullifier_tree_root: start_state.nullifier_tree.root, l1_to_l2_msg_read_request_hints, - l1_to_l2_msg_tree_root: public_inputs - .constants - .historical_header - .state - .l1_to_l2_message_tree - .root, + l1_to_l2_msg_tree_root: public_inputs.constants.historical_header.state.l1_to_l2_message_tree.root, pending_public_data_writes, public_data_leaves, - public_data_read_request_hints, + public_data_read_request_hints } } @@ -95,15 +91,14 @@ impl PublicVal validate_tree_leaf_read_requests( self.validation_requests.note_hash_read_requests, self.note_hash_read_request_hints, - self.note_hash_tree_root, + self.note_hash_tree_root ); } fn validate_nullifier_read_requests(self) { let requests = self.validation_requests.nullifier_read_requests; let hints = self.nullifier_read_request_hints; - let unverified_nullifier_read_requests = - [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX]; // All nullifier read requests must be verified. + let unverified_nullifier_read_requests = [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX]; // All nullifier read requests must be verified. verify_reset_read_requests( requests, self.pending_nullifiers, @@ -111,7 +106,7 @@ impl PublicVal hints.pending_read_hints, hints.settled_read_hints, self.nullifier_tree_root, - unverified_nullifier_read_requests, + unverified_nullifier_read_requests ); } @@ -133,7 +128,7 @@ impl PublicVal self.pending_nullifiers, hints.sorted_pending_values, hints.sorted_pending_value_index_hints, - |a: Nullifier, b: Nullifier| a.value.lt(b.value), + |a: Nullifier, b: Nullifier| a.value.lt(b.value) ); let sorted_pending_nullifiers = array_to_bounded_vec(hints.sorted_pending_values); @@ -142,7 +137,7 @@ impl PublicVal hints.non_membership_hints, self.nullifier_tree_root, sorted_pending_nullifiers, - hints.next_pending_value_indices, + hints.next_pending_value_indices ); } @@ -150,7 +145,7 @@ impl PublicVal validate_tree_leaf_read_requests( self.validation_requests.l1_to_l2_msg_read_requests, self.l1_to_l2_msg_read_request_hints, - self.l1_to_l2_msg_tree_root, + self.l1_to_l2_msg_tree_root ); } @@ -163,7 +158,7 @@ impl PublicVal self.pending_public_data_writes, self.public_data_leaves, hints.pending_read_hints, - hints.leaf_data_read_hints, + hints.leaf_data_read_hints ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/key_validation_hint.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/key_validation_hint.nr index 167c6b97803..5a9b6879176 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/key_validation_hint.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/key_validation_hint.nr @@ -1,6 +1,6 @@ use dep::types::{ - traits::Empty, abis::validation_requests::ScopedKeyValidationRequestAndGenerator, - scalar::Scalar, hash::poseidon2_hash_with_separator, + traits::Empty, abis::validation_requests::ScopedKeyValidationRequestAndGenerator, scalar::Scalar, + hash::poseidon2_hash_with_separator }; use std::embedded_curve_ops::fixed_base_scalar_mul as derive_public_key; @@ -27,10 +27,7 @@ impl KeyValidationHint { } } -fn verify_key_validation_request( - scoped_request: ScopedKeyValidationRequestAndGenerator, - sk_m: Scalar, -) { +fn verify_key_validation_request(scoped_request: ScopedKeyValidationRequestAndGenerator, sk_m: Scalar) { let contract_address = scoped_request.contract_address; let request_and_generator = scoped_request.request; let request = request_and_generator.request; @@ -38,27 +35,17 @@ fn verify_key_validation_request( // First we check that derived public key matches master public key from request. let pk_m = derive_public_key(sk_m); - assert_eq( - pk_m, - request.pk_m, - "Failed to derive matching master public key from the secret key.", - ); + assert_eq(pk_m, request.pk_m, "Failed to derive matching master public key from the secret key."); // Then we check that siloing the master secret key with the contract address gives the app secret key. let sk_app = poseidon2_hash_with_separator( [sk_m.hi, sk_m.lo, contract_address.to_field()], - sk_app_generator, - ); - assert_eq( - sk_app, - request.sk_app, - "Failed to derive matching app secret key from the secret key.", + sk_app_generator ); + assert_eq(sk_app, request.sk_app, "Failed to derive matching app secret key from the secret key."); } -unconstrained fn get_hint_indexes( - hints: [KeyValidationHint; NUM_HINTS], -) -> [u32; REQUEST_LEN] { +unconstrained fn get_hint_indexes(hints: [KeyValidationHint; NUM_HINTS]) -> [u32; REQUEST_LEN] { let mut hint_indexes = [NUM_HINTS; REQUEST_LEN]; for i in 0..NUM_HINTS { let hint = hints[i]; @@ -72,7 +59,7 @@ unconstrained fn get_hint_indexes( pub fn verify_reset_key_validation_requests( key_validation_requests: [ScopedKeyValidationRequestAndGenerator; REQUEST_LEN], hints: [KeyValidationHint; NUM_HINTS], - unverified_requests: [ScopedKeyValidationRequestAndGenerator; REQUEST_LEN], + unverified_requests: [ScopedKeyValidationRequestAndGenerator; REQUEST_LEN] ) { for i in 0..NUM_HINTS { let hint = hints[i]; @@ -84,7 +71,9 @@ pub fn verify_reset_key_validation_requests( key_validation_requests: [ScopedKeyValidationRequestAndGenerator; REQUEST_LEN], - hints: [KeyValidationHint; NUM_HINTS], + hints: [KeyValidationHint; NUM_HINTS] ) -> [ScopedKeyValidationRequestAndGenerator; REQUEST_LEN] { let mut should_propagate = [true; REQUEST_LEN]; for i in 0..NUM_HINTS { diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mutable_data_read_request.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mutable_data_read_request.nr index 2b7b3bcdef6..db3a9e1cc54 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mutable_data_read_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mutable_data_read_request.nr @@ -15,12 +15,11 @@ impl ReadIndexHint { fn validate_pending_read_requests( read_requests: [R; READ_REQUEST_LEN], pending_values: [V; PENDING_VALUE_LEN], - index_hints: [ReadIndexHint; NUM_HINTS], + index_hints: [ReadIndexHint; NUM_HINTS] ) where R: Ordered, - V: Readable + Ordered + Overridable, -{ + V: Readable + Ordered + Overridable, { for i in 0..index_hints.len() { let index_hint = index_hints[i]; let read_request_index = index_hint.read_request_index; @@ -29,13 +28,11 @@ where let pending_value = pending_values[index_hint.value_index]; pending_value.assert_match_read_request(read_request); assert( - read_request.counter() > pending_value.counter(), - "Read request counter must be greater than the counter of the data write", + read_request.counter() > pending_value.counter(), "Read request counter must be greater than the counter of the data write" ); assert( (read_request.counter() < pending_value.override_counter()) - | (pending_value.override_counter() == 0), - "Read request counter must be less than the counter of the next data write", + | (pending_value.override_counter() == 0), "Read request counter must be less than the counter of the next data write" ); } } @@ -44,12 +41,11 @@ where fn validate_leaf_data_read_requests( read_requests: [R; READ_REQUEST_LEN], leaf_data: [L; LEAF_DATA_LEN], - index_hints: [ReadIndexHint; NUM_HINTS], + index_hints: [ReadIndexHint; NUM_HINTS] ) where R: Ordered, - L: Readable + Overridable, -{ + L: Readable + Overridable, { for i in 0..index_hints.len() { let index_hint = index_hints[i]; let read_request_index = index_hint.read_request_index; @@ -58,8 +54,7 @@ where let data = leaf_data[index_hint.value_index]; data.assert_match_read_request(read_request); assert( - (read_request.counter() < data.override_counter()) | (data.override_counter() == 0), - "Hinted leaf is overridden before the read request", + (read_request.counter() < data.override_counter()) | (data.override_counter() == 0), "Hinted leaf is overridden before the read request" ); } } @@ -69,43 +64,48 @@ fn ensure_all_read_requests_are_verified( +pub fn reset_mutable_data_read_requests< + R, + let READ_REQUEST_LEN: u32, + V, + let PENDING_VALUE_LEN: u32, + L, + let NUM_LEAF_DATA_HINTS: u32, + let NUM_PENDING_READS: u32, + let NUM_LEAF_DATA_READS: u32 +>( read_requests: [R; READ_REQUEST_LEN], read_request_statuses: [ReadRequestStatus; READ_REQUEST_LEN], pending_values: [V; PENDING_VALUE_LEN], leaf_data: [L; NUM_LEAF_DATA_HINTS], pending_read_hints: [ReadIndexHint; NUM_PENDING_READS], - leaf_data_read_hints: [ReadIndexHint; NUM_LEAF_DATA_READS], + leaf_data_read_hints: [ReadIndexHint; NUM_LEAF_DATA_READS] ) where R: Ordered, V: Readable + Ordered + Overridable, - L: Readable + Overridable, -{ + L: Readable + Overridable, { validate_pending_read_requests(read_requests, pending_values, pending_read_hints); validate_leaf_data_read_requests(read_requests, leaf_data, leaf_data_read_hints); @@ -114,22 +114,24 @@ where read_requests, read_request_statuses, pending_read_hints, - leaf_data_read_hints, + leaf_data_read_hints ); } mod tests { use crate::reset::{ mutable_data_read_request::{ - ensure_all_read_requests_are_verified, ReadIndexHint, reset_mutable_data_read_requests, - validate_pending_read_requests, validate_leaf_data_read_requests, - }, read_request::{ReadRequestState, ReadRequestStatus}, + ensure_all_read_requests_are_verified, ReadIndexHint, reset_mutable_data_read_requests, + validate_pending_read_requests, validate_leaf_data_read_requests + }, + read_request::{ReadRequestState, ReadRequestStatus} }; use dep::types::{ abis::{ - public_data_read::PublicDataRead, public_data_update_request::PublicDataUpdateRequest, - public_data_write::OverridablePublicDataWrite, side_effect::{Overridable, Readable}, - }, tests::utils::pad_end, traits::Empty, + public_data_read::PublicDataRead, public_data_update_request::PublicDataUpdateRequest, + public_data_write::OverridablePublicDataWrite, side_effect::{Overridable, Readable} + }, + tests::utils::pad_end, traits::Empty }; struct TestLeafData { @@ -152,11 +154,7 @@ mod tests { impl Readable for TestLeafData { fn assert_match_read_request(self, read_request: PublicDataRead) { - assert_eq( - self.leaf_index, - read_request.leaf_slot, - "leaf_index in TestLeafData does not match", - ); + assert_eq(self.leaf_index, read_request.leaf_slot, "leaf_index in TestLeafData does not match"); assert_eq(self.value, read_request.value, "value in TestLeafData does not match"); } } @@ -182,53 +180,25 @@ mod tests { let leaf_data = pad_end( [ - TestLeafData { leaf_index: 44, value: 0, override_counter: 40 }, - TestLeafData { leaf_index: 77, value: 700, override_counter: 0 }, - TestLeafData { leaf_index: 11, value: 0, override_counter: 20 }, - TestLeafData { leaf_index: 33, value: 300, override_counter: 30 }, - TestLeafData { leaf_index: 66, value: 600, override_counter: 0 }, - TestLeafData { leaf_index: 22, value: 200, override_counter: 10 }, - TestLeafData { leaf_index: 55, value: 500, override_counter: 0 }, - ], - TestLeafData::empty(), + TestLeafData { leaf_index: 44, value: 0, override_counter: 40 }, + TestLeafData { leaf_index: 77, value: 700, override_counter: 0 }, + TestLeafData { leaf_index: 11, value: 0, override_counter: 20 }, + TestLeafData { leaf_index: 33, value: 300, override_counter: 30 }, + TestLeafData { leaf_index: 66, value: 600, override_counter: 0 }, + TestLeafData { leaf_index: 22, value: 200, override_counter: 10 }, + TestLeafData { leaf_index: 55, value: 500, override_counter: 0 } + ], + TestLeafData::empty() ); let data_writes = pad_end( [ - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 22, - new_value: 201, - counter: 10, - }, - override_counter: 40, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 11, - new_value: 100, - counter: 20, - }, - override_counter: 0, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 33, - new_value: 301, - counter: 30, - }, - override_counter: 0, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 22, - new_value: 202, - counter: 40, - }, - override_counter: 0, - }, - ], - OverridablePublicDataWrite::empty(), + OverridablePublicDataWrite { write: PublicDataUpdateRequest { leaf_slot: 22, new_value: 201, counter: 10 }, override_counter: 40 }, + OverridablePublicDataWrite { write: PublicDataUpdateRequest { leaf_slot: 11, new_value: 100, counter: 20 }, override_counter: 0 }, + OverridablePublicDataWrite { write: PublicDataUpdateRequest { leaf_slot: 33, new_value: 301, counter: 30 }, override_counter: 0 }, + OverridablePublicDataWrite { write: PublicDataUpdateRequest { leaf_slot: 22, new_value: 202, counter: 40 }, override_counter: 0 } + ], + OverridablePublicDataWrite::empty() ); let pending_read_hints = pad_end([], ReadIndexHint::nada(READ_REQUEST_LEN)); @@ -244,7 +214,7 @@ mod tests { leaf_data_read_hints, num_pending_reads: 0, num_leaf_data_reads: 0, - counter: 50, + counter: 50 } } @@ -281,19 +251,11 @@ mod tests { } pub fn validate_pending_read_requests(self) { - validate_pending_read_requests( - self.read_requests, - self.data_writes, - self.pending_read_hints, - ); + validate_pending_read_requests(self.read_requests, self.data_writes, self.pending_read_hints); } pub fn validate_leaf_data_read_requests(self) { - validate_leaf_data_read_requests( - self.read_requests, - self.leaf_data, - self.leaf_data_read_hints, - ) + validate_leaf_data_read_requests(self.read_requests, self.leaf_data, self.leaf_data_read_hints) } pub fn ensure_all_read_requests_are_verified(self) { @@ -301,7 +263,7 @@ mod tests { self.read_requests, self.read_request_statuses, self.pending_read_hints, - self.leaf_data_read_hints, + self.leaf_data_read_hints ) } @@ -312,7 +274,7 @@ mod tests { self.data_writes, self.leaf_data, self.pending_read_hints, - self.leaf_data_read_hints, + self.leaf_data_read_hints ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/non_existent_read_request.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/non_existent_read_request.nr index 55aab06e6fb..17b1a26ac4f 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/non_existent_read_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/non_existent_read_request.nr @@ -1,7 +1,7 @@ use dep::types::{ abis::{side_effect::OrderedValue, read_request::ScopedReadRequest}, merkle_tree::{assert_check_non_membership, IndexedTreeLeafPreimage, MembershipWitness}, - traits::is_empty, + traits::is_empty }; trait NonMembershipHint @@ -15,14 +15,12 @@ where fn check_no_matching_pending_value( read_request: ScopedReadRequest, sorted_pending_values: BoundedVec, - next_value_index: u32, + next_value_index: u32 ) -> bool where - T: OrderedValue, -{ + T: OrderedValue, { if next_value_index == sorted_pending_values.len() { - let highest_value = - sorted_pending_values.get_unchecked(sorted_pending_values.len() - 1).value(); + let highest_value = sorted_pending_values.get_unchecked(sorted_pending_values.len() - 1).value(); highest_value.lt(read_request.value()) } else { let next_value = sorted_pending_values.get_unchecked(next_value_index).value(); @@ -40,11 +38,10 @@ where fn check_is_read_before_pending_value( read_request: ScopedReadRequest, sorted_pending_values: BoundedVec, - next_value_index: u32, + next_value_index: u32 ) -> bool where - T: OrderedValue, -{ + T: OrderedValue, { if next_value_index == sorted_pending_values.len() { false } else { @@ -66,13 +63,12 @@ pub fn reset_non_existent_read_requests, - next_pending_value_indices: [u32; N], + next_pending_value_indices: [u32; N] ) where T: OrderedValue, NON_MEMBERSHIP_HINT: NonMembershipHint, - LEAF_PREIMAGE: IndexedTreeLeafPreimage, -{ + LEAF_PREIMAGE: IndexedTreeLeafPreimage, { for i in 0..siloed_read_requests.len() { let read_request = siloed_read_requests[i]; if !is_empty(read_request) { @@ -82,39 +78,28 @@ where read_request.value(), hint.low_leaf_preimage(), hint.membership_witness(), - tree_root, + tree_root ); // Verify that its value is either not in the pending set, or is created after the read. let next_value_index = next_pending_value_indices[i]; assert( - next_value_index <= sorted_pending_values.len(), - "Next pending value index out of bounds", - ); - let no_matching_value = check_no_matching_pending_value( - read_request, - sorted_pending_values, - next_value_index, - ); - let is_read_before_value = check_is_read_before_pending_value( - read_request, - sorted_pending_values, - next_value_index, + next_value_index <= sorted_pending_values.len(), "Next pending value index out of bounds" ); + let no_matching_value = check_no_matching_pending_value(read_request, sorted_pending_values, next_value_index); + let is_read_before_value = check_is_read_before_pending_value(read_request, sorted_pending_values, next_value_index); assert(no_matching_value | is_read_before_value, "Invalid next pending value index"); } } } mod tests { - use crate::reset::non_existent_read_request::{ - NonMembershipHint, reset_non_existent_read_requests, - }; + use crate::reset::non_existent_read_request::{NonMembershipHint, reset_non_existent_read_requests}; use dep::types::{ address::AztecAddress, abis::{read_request::ReadRequest, side_effect::OrderedValue}, merkle_tree::{leaf_preimage::IndexedTreeLeafPreimage, membership::MembershipWitness}, - tests::merkle_tree_utils::NonEmptyMerkleTree, + tests::merkle_tree_utils::NonEmptyMerkleTree }; struct TestValue { @@ -194,15 +179,14 @@ mod tests { leaf_preimages.map(|leaf_preimage: TestLeafPreimage| leaf_preimage.as_leaf()), [0; 3], [0; 1], - [0; 2], + [0; 2] ) } - fn get_non_membership_hints( - leaf_indices: [Field; N], - ) -> ([TestNonMembershipHint; N], Field) { + fn get_non_membership_hints(leaf_indices: [Field; N]) -> ([TestNonMembershipHint; N], Field) { let tree = build_tree(); - let hints = leaf_indices.map(|leaf_index| { + let hints = leaf_indices.map( + |leaf_index| { TestNonMembershipHint { low_leaf_preimage: leaf_preimages[leaf_index], membership_witness: MembershipWitness { @@ -210,7 +194,8 @@ mod tests { sibling_path: tree.get_sibling_path(leaf_index as u32), }, } - }); + } + ); let tree_root = tree.get_root(); (hints, tree_root) } @@ -220,7 +205,7 @@ mod tests { let read_requests = [ ReadRequest { value: 11, counter: 50 }.scope(AztecAddress::zero()), ReadRequest { value: 22, counter: 51 }.scope(AztecAddress::zero()), - ReadRequest { value: 6, counter: 52 }.scope(AztecAddress::zero()), + ReadRequest { value: 6, counter: 52 }.scope(AztecAddress::zero()) ]; let (non_membership_hints, root) = get_non_membership_hints([3, 1, 0]); let next_pending_value_indices = [1, 2, 1]; @@ -229,7 +214,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -237,7 +222,7 @@ mod tests { fn test_reset_non_existent_read_requests_less_than_min() { let read_requests = [ ReadRequest { value: 3, counter: 50 }.scope(AztecAddress::zero()), - ReadRequest { value: 2, counter: 51 }.scope(AztecAddress::zero()), + ReadRequest { value: 2, counter: 51 }.scope(AztecAddress::zero()) ]; let (non_membership_hints, root) = get_non_membership_hints([0, 0]); let next_pending_value_indices = [0, 0]; @@ -246,7 +231,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -254,7 +239,7 @@ mod tests { fn test_reset_non_existent_read_requests_greater_than_max() { let read_requests = [ ReadRequest { value: 35, counter: 50 }.scope(AztecAddress::zero()), - ReadRequest { value: 31, counter: 51 }.scope(AztecAddress::zero()), + ReadRequest { value: 31, counter: 51 }.scope(AztecAddress::zero()) ]; let (non_membership_hints, root) = get_non_membership_hints([2, 2]); let next_pending_value_indices = [3, 3]; @@ -263,7 +248,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -271,7 +256,7 @@ mod tests { fn test_reset_non_existent_read_requests_read_before_pending_emitted() { let read_requests = [ ReadRequest { value: 25, counter: 10 }.scope(AztecAddress::zero()), - ReadRequest { value: 5, counter: 11 }.scope(AztecAddress::zero()), + ReadRequest { value: 5, counter: 11 }.scope(AztecAddress::zero()) ]; let (non_membership_hints, root) = get_non_membership_hints([1, 0]); let next_pending_value_indices = [2, 0]; @@ -280,7 +265,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -296,7 +281,7 @@ mod tests { [hint], root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -310,7 +295,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -324,7 +309,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -338,7 +323,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -352,7 +337,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -366,7 +351,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } @@ -380,7 +365,7 @@ mod tests { non_membership_hints, root, sorted_pending_values, - next_pending_value_indices, + next_pending_value_indices ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/read_request.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/read_request.nr index 4b2d07b93f7..297af845290 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/read_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/read_request.nr @@ -1,7 +1,7 @@ // This will be moved to a separate Read Request Reset Circuit. use dep::types::{ abis::{read_request::ScopedReadRequest, side_effect::Readable}, - merkle_tree::{assert_check_membership, LeafPreimage, MembershipWitness}, traits::Empty, + merkle_tree::{assert_check_membership, LeafPreimage, MembershipWitness}, traits::Empty }; pub struct ReadRequestStateEnum { @@ -70,11 +70,10 @@ where fn validate_pending_read_requests( read_requests: [ScopedReadRequest; READ_REQUEST_LEN], pending_values: [T; PENDING_VALUE_LEN], - hints: [PendingReadHint; NUM_PENDING_READS], + hints: [PendingReadHint; NUM_PENDING_READS] ) where - T: Readable, -{ + T: Readable, { for i in 0..NUM_PENDING_READS { let hint = hints[i]; let read_request_index = hint.read_request_index; @@ -88,15 +87,20 @@ where // Validate read requests against the historical tree root, for reading settled notes. // Use their membership witnesses to do so. -fn validate_settled_read_requests( +fn validate_settled_read_requests< + let READ_REQUEST_LEN: u32, + let NUM_SETTLED_READS: u32, + H, + let TREE_HEIGHT: u32, + LEAF_PREIMAGE +>( read_requests: [ScopedReadRequest; READ_REQUEST_LEN], hints: [H; NUM_SETTLED_READS], - tree_root: Field, + tree_root: Field ) where H: SettledReadHint + ReadValueHint, - LEAF_PREIMAGE: LeafPreimage + Readable, -{ + LEAF_PREIMAGE: LeafPreimage + Readable, { for i in 0..NUM_SETTLED_READS { let hint = hints[i]; let read_request_index = hint.read_request_index(); @@ -117,53 +121,54 @@ fn verify_propagated_read_requests( +pub fn verify_reset_read_requests< + let READ_REQUEST_LEN: u32, + P, + let PENDING_VALUE_LEN: u32, + let NUM_PENDING_READS: u32, + let NUM_SETTLED_READS: u32, + H, + let TREE_HEIGHT: u32, + LEAF_PREIMAGE +>( read_requests: [ScopedReadRequest; READ_REQUEST_LEN], pending_values: [P; PENDING_VALUE_LEN], read_request_statuses: [ReadRequestStatus; READ_REQUEST_LEN], pending_read_hints: [PendingReadHint; NUM_PENDING_READS], settled_read_hints: [H; NUM_SETTLED_READS], tree_root: Field, - propagated_read_requests: [ScopedReadRequest; READ_REQUEST_LEN], + propagated_read_requests: [ScopedReadRequest; READ_REQUEST_LEN] ) where P: Readable, H: SettledReadHint + ReadValueHint, - LEAF_PREIMAGE: LeafPreimage + Readable, -{ + LEAF_PREIMAGE: LeafPreimage + Readable, { validate_pending_read_requests(read_requests, pending_values, pending_read_hints); validate_settled_read_requests(read_requests, settled_read_hints, tree_root); @@ -173,13 +178,13 @@ where read_request_statuses, pending_read_hints, settled_read_hints, - propagated_read_requests, + propagated_read_requests ); } pub unconstrained fn get_unverified_read_requests( read_requests: [ScopedReadRequest; READ_REQUEST_LEN], - read_request_statuses: [ReadRequestStatus; READ_REQUEST_LEN], + read_request_statuses: [ReadRequestStatus; READ_REQUEST_LEN] ) -> [ScopedReadRequest; READ_REQUEST_LEN] { let mut propagated_read_requests = BoundedVec::new(); for i in 0..READ_REQUEST_LEN { @@ -194,15 +199,15 @@ pub unconstrained fn get_unverified_read_requests( mod tests { use crate::reset::read_request::{ PendingReadHint, ReadRequestState, ReadRequestStatus, ReadValueHint, SettledReadHint, - get_unverified_read_requests, validate_pending_read_requests, - validate_settled_read_requests, verify_reset_read_requests, + get_unverified_read_requests, validate_pending_read_requests, validate_settled_read_requests, + verify_reset_read_requests }; use dep::types::{ address::AztecAddress, abis::{read_request::{ReadRequest, ScopedReadRequest}, side_effect::Readable}, merkle_tree::{LeafPreimage, MembershipWitness}, tests::{merkle_tree_utils::NonEmptyMerkleTree, utils::assert_array_eq}, - traits::{Empty, is_empty_array}, + traits::{Empty, is_empty_array} }; fn silo_test_value(value: Field) -> Field { @@ -273,7 +278,7 @@ mod tests { TestSettledReadHint { read_request_index: read_request_len, membership_witness: MembershipWitness::empty(), - leaf_preimage: TestLeafPreimage::empty(), + leaf_preimage: TestLeafPreimage::empty() } } } @@ -296,40 +301,34 @@ mod tests { // Create 4 read requests. 0 and 3 are reading settled values. 1 and 2 are reading pending values. let read_requests = [ - ReadRequest { value: values[1], counter: 11 }.scope(contract_address), // settled - ReadRequest { value: values[3], counter: 13 }.scope(contract_address), // pending - ReadRequest { value: values[2], counter: 39 }.scope(contract_address), // pending - ReadRequest { value: values[0], counter: 46 }.scope(contract_address), // settled + ReadRequest { value: values[1], counter: 11 }.scope(contract_address),// settled + ReadRequest { value: values[3], counter: 13 }.scope(contract_address),// pending + ReadRequest { value: values[2], counter: 39 }.scope(contract_address),// pending + ReadRequest { value: values[0], counter: 46 }.scope(contract_address) // settled ]; let pending_values = [ TestValue { value: siloed_values[2], counter: 2 }, - TestValue { value: siloed_values[3], counter: 8 }, + TestValue { value: siloed_values[3], counter: 8 } ]; let pending_read_hints = [ PendingReadHint { read_request_index: 1, pending_value_index: 1 }, - PendingReadHint { read_request_index: 2, pending_value_index: 0 }, + PendingReadHint { read_request_index: 2, pending_value_index: 0 } ]; let leaf_preimages = [ TestLeafPreimage { value: siloed_values[0] }, - TestLeafPreimage { value: siloed_values[1] }, + TestLeafPreimage { value: siloed_values[1] } ]; let read_request_statuses = [ ReadRequestStatus { state: ReadRequestState.SETTLED, hint_index: 0 }, ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 0 }, ReadRequestStatus { state: ReadRequestState.PENDING, hint_index: 1 }, - ReadRequestStatus { state: ReadRequestState.SETTLED, hint_index: 1 }, + ReadRequestStatus { state: ReadRequestState.SETTLED, hint_index: 1 } ]; - TestBuilder { - read_requests, - read_request_statuses, - pending_values, - pending_read_hints, - leaf_preimages, - } + TestBuilder { read_requests, read_request_statuses, pending_values, pending_read_hints, leaf_preimages } } } @@ -339,7 +338,7 @@ mod tests { [self.leaf_preimages[0].as_leaf(), self.leaf_preimages[1].as_leaf()], [0; 3], [0; 2], - [0; 1], + [0; 1] ) } @@ -348,20 +347,14 @@ mod tests { let hints = [ TestSettledReadHint { read_request_index: 0, - membership_witness: MembershipWitness { - leaf_index: 1, - sibling_path: tree.get_sibling_path(1), - }, - leaf_preimage: self.leaf_preimages[1], + membership_witness: MembershipWitness { leaf_index: 1, sibling_path: tree.get_sibling_path(1) }, + leaf_preimage: self.leaf_preimages[1] }, TestSettledReadHint { read_request_index: 3, - membership_witness: MembershipWitness { - leaf_index: 0, - sibling_path: tree.get_sibling_path(0), - }, - leaf_preimage: self.leaf_preimages[0], - }, + membership_witness: MembershipWitness { leaf_index: 0, sibling_path: tree.get_sibling_path(0) }, + leaf_preimage: self.leaf_preimages[0] + } ]; let tree_root = tree.get_root(); (hints, tree_root) @@ -375,9 +368,7 @@ mod tests { TestSettledReadHint::nada(self.read_requests.len()) } - pub unconstrained fn get_unverified_read_requests( - self, - ) -> [ScopedReadRequest; READ_REQUEST_LEN] { + pub unconstrained fn get_unverified_read_requests(self) -> [ScopedReadRequest; READ_REQUEST_LEN] { get_unverified_read_requests(self.read_requests, self.read_request_statuses) } @@ -385,7 +376,7 @@ mod tests { validate_pending_read_requests( self.read_requests, self.pending_values, - self.pending_read_hints, + self.pending_read_hints ); } @@ -397,14 +388,16 @@ mod tests { pub fn validate_settled_read_requests_with_hints( self, settled_hints: [TestSettledReadHint; 2], - tree_root: Field, + tree_root: Field ) { validate_settled_read_requests(self.read_requests, settled_hints, tree_root); } pub fn verify_with_settled_hints(self, settled_hints: [TestSettledReadHint; 2]) { let tree = self.build_tree(); - let unverified = unsafe { self.get_unverified_read_requests() }; + let unverified = unsafe { + self.get_unverified_read_requests() + }; verify_reset_read_requests( self.read_requests, self.pending_values, @@ -412,13 +405,15 @@ mod tests { self.pending_read_hints, settled_hints, tree.get_root(), - unverified, + unverified ); } pub fn verify(self) { let (settled_hints, tree_root) = self.get_settled_read_hints(); - let unverified = unsafe { self.get_unverified_read_requests() }; + let unverified = unsafe { + self.get_unverified_read_requests() + }; verify_reset_read_requests( self.read_requests, self.pending_values, @@ -426,7 +421,7 @@ mod tests { self.pending_read_hints, settled_hints, tree_root, - unverified, + unverified ); } } @@ -525,7 +520,9 @@ mod tests { fn verify_read_requests_clears_all_succeeds() { let builder = TestBuilder::new(); - let unverified_read_requests = unsafe { builder.get_unverified_read_requests() }; + let unverified_read_requests = unsafe { + builder.get_unverified_read_requests() + }; assert(is_empty_array(unverified_read_requests)); builder.verify(); @@ -543,10 +540,12 @@ mod tests { settled_hints[0] = builder.get_nada_settled_read_hint(); let read_requests = builder.read_requests; - let unverified_read_requests = unsafe { builder.get_unverified_read_requests() }; + let unverified_read_requests = unsafe { + builder.get_unverified_read_requests() + }; assert_array_eq( unverified_read_requests, - [read_requests[0], read_requests[2]], + [read_requests[0], read_requests[2]] ); builder.verify_with_settled_hints(settled_hints); diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/transient_data.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/transient_data.nr index 7d970eaf2fb..fad2acf2962 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/transient_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/transient_data.nr @@ -1,6 +1,6 @@ use dep::types::{ abis::{note_hash::ScopedNoteHash, nullifier::ScopedNullifier, log_hash::NoteLogHash}, - traits::is_empty, + traits::is_empty }; pub struct TransientDataIndexHint { @@ -14,7 +14,12 @@ impl TransientDataIndexHint { } } -pub fn verify_squashed_transient_data_with_hint_indexes( +pub fn verify_squashed_transient_data_with_hint_indexes< + let NUM_NOTE_HASHES: u32, + let NUM_NULLIFIERS: u32, + let NUM_LOGS: u32, + let NUM_INDEX_HINTS: u32 +>( note_hashes: [ScopedNoteHash; NUM_NOTE_HASHES], nullifiers: [ScopedNullifier; NUM_NULLIFIERS], note_logs: [NoteLogHash; NUM_LOGS], @@ -25,7 +30,7 @@ pub fn verify_squashed_transient_data_with_hint_indexes note_hash.counter(), - "Cannot nullify a note hash created afterwards", + nullifier.counter() > note_hash.counter(), "Cannot nullify a note hash created afterwards" ); if nullifier.counter() >= split_counter { assert( - note_hash.counter() >= split_counter, - "Cannot squash a non-revertible note hash with a revertible nullifier", + note_hash.counter() >= split_counter, "Cannot squash a non-revertible note hash with a revertible nullifier" ); // Since the nullifier counter must be larger than the note hash counter, it's not possible to squash a revertible note hash with a non-revertible nullifier. } @@ -74,26 +73,18 @@ pub fn verify_squashed_transient_data_with_hint_indexes( - transient_data_index_hints: [TransientDataIndexHint; NUM_INDEX_HINTS], -) -> [bool; NUM_NOTE_HASHES] { +pub unconstrained fn get_squashed_note_hash_hints(transient_data_index_hints: [TransientDataIndexHint; NUM_INDEX_HINTS]) -> [bool; NUM_NOTE_HASHES] { let mut hints = [false; NUM_NOTE_HASHES]; for i in 0..transient_data_index_hints.len() { let note_hash_index = transient_data_index_hints[i].note_hash_index; @@ -148,9 +135,7 @@ pub unconstrained fn get_squashed_note_hash_hints( - transient_data_index_hints: [TransientDataIndexHint; NUM_INDEX_HINTS], -) -> [bool; NUM_NULLIFIERS] { +pub unconstrained fn get_squashed_nullifier_hints(transient_data_index_hints: [TransientDataIndexHint; NUM_INDEX_HINTS]) -> [bool; NUM_NULLIFIERS] { let mut hints = [false; NUM_NULLIFIERS]; for i in 0..transient_data_index_hints.len() { let nullifier_index = transient_data_index_hints[i].nullifier_index; @@ -161,7 +146,12 @@ pub unconstrained fn get_squashed_nullifier_hints( +pub fn verify_squashed_transient_data< + let NUM_NOTE_HASHES: u32, + let NUM_NULLIFIERS: u32, + let NUM_LOGS: u32, + let NUM_INDEX_HINTS: u32 +>( note_hashes: [ScopedNoteHash; NUM_NOTE_HASHES], nullifiers: [ScopedNullifier; NUM_NULLIFIERS], note_logs: [NoteLogHash; NUM_LOGS], @@ -170,12 +160,14 @@ pub fn verify_squashed_transient_data TestDataBuilder { pub fn get_nada_index_hint(_self: Self) -> TransientDataIndexHint { - TransientDataIndexHint { - nullifier_index: NUM_NULLIFIERS, - note_hash_index: NUM_NOTE_HASHES, - } + TransientDataIndexHint { nullifier_index: NUM_NULLIFIERS, note_hash_index: NUM_NOTE_HASHES } } pub fn get_hint_indexes(self) -> ([bool; NUM_NOTE_HASHES], [bool; NUM_NULLIFIERS]) { - let squashed_note_hash_hints = - unsafe { get_squashed_note_hash_hints(self.transient_data_index_hints) }; - let squashed_nullifier_hints = - unsafe { get_squashed_nullifier_hints(self.transient_data_index_hints) }; + let squashed_note_hash_hints = unsafe { + get_squashed_note_hash_hints(self.transient_data_index_hints) + }; + let squashed_nullifier_hints = unsafe { + get_squashed_nullifier_hints(self.transient_data_index_hints) + }; (squashed_note_hash_hints, squashed_nullifier_hints) } @@ -390,14 +376,14 @@ mod tests { self.expected_note_logs, self.transient_data_index_hints, self.transient_or_propagated_note_hash_indexes_for_logs, - self.split_counter, + self.split_counter ); } pub fn verify_with_hint_indexes( self, squashed_note_hash_hints: [bool; NUM_NOTE_HASHES], - squashed_nullifier_hints: [bool; NUM_NULLIFIERS], + squashed_nullifier_hints: [bool; NUM_NULLIFIERS] ) { verify_squashed_transient_data_with_hint_indexes( self.note_hashes, @@ -410,7 +396,7 @@ mod tests { self.transient_or_propagated_note_hash_indexes_for_logs, self.split_counter, squashed_note_hash_hints, - squashed_nullifier_hints, + squashed_nullifier_hints ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/tree_leaf_read_request.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/tree_leaf_read_request.nr index a5dd79f6c4f..738e9695d67 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/tree_leaf_read_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/tree_leaf_read_request.nr @@ -1,6 +1,6 @@ use dep::types::{ abis::tree_leaf_read_request::TreeLeafReadRequest, traits::is_empty, - merkle_tree::assert_check_membership, + merkle_tree::assert_check_membership }; pub struct TreeLeafReadRequestHint { @@ -10,7 +10,7 @@ pub struct TreeLeafReadRequestHint { pub fn validate_tree_leaf_read_requests( read_requests: [TreeLeafReadRequest; READ_REQUEST_LEN], hints: [TreeLeafReadRequestHint; READ_REQUEST_LEN], - tree_root: Field, + tree_root: Field ) { for i in 0..READ_REQUEST_LEN { let read_request = read_requests[i]; @@ -19,7 +19,7 @@ pub fn validate_tree_leaf_read_requests NoteHashReadRequest pub fn new() -> Self { NoteHashReadRequestHintsBuilder { read_request_statuses: [ReadRequestStatus::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX], - pending_read_hints: BoundedVec { - storage: [ - PendingReadHint::nada(MAX_NOTE_HASH_READ_REQUESTS_PER_TX); NUM_PENDING_HINTS - ], - len: 0, - }, + pending_read_hints: BoundedVec { storage: [PendingReadHint::nada(MAX_NOTE_HASH_READ_REQUESTS_PER_TX); NUM_PENDING_HINTS], len: 0 }, settled_read_hints: BoundedVec { - storage: [ - NoteHashSettledReadHint::nada(MAX_NOTE_HASH_READ_REQUESTS_PER_TX); - NUM_SETTLED_HINTS - ], - len: 0, - }, + storage: [NoteHashSettledReadHint::nada(MAX_NOTE_HASH_READ_REQUESTS_PER_TX); NUM_SETTLED_HINTS], + len: 0 } } + } - pub unconstrained fn to_hints( - self, - ) -> NoteHashReadRequestHints { + pub unconstrained fn to_hints(self) -> NoteHashReadRequestHints { NoteHashReadRequestHints { read_request_statuses: self.read_request_statuses, pending_read_hints: self.pending_read_hints.storage, - settled_read_hints: self.settled_read_hints.storage, + settled_read_hints: self.settled_read_hints.storage } } } diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_non_existent_read_request_hints_builder.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_non_existent_read_request_hints_builder.nr index 3fd0579ca1d..8359d08229b 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_non_existent_read_request_hints_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_non_existent_read_request_hints_builder.nr @@ -1,13 +1,12 @@ -use crate::nullifier_non_existent_read_request_reset::{ - NullifierNonMembershipHint, NullifierNonExistentReadRequestHints, -}; +use crate::nullifier_non_existent_read_request_reset::{NullifierNonMembershipHint, NullifierNonExistentReadRequestHints}; use dep::types::{ abis::{nullifier::Nullifier, nullifier_leaf_preimage::NullifierLeafPreimage}, constants::{ - MAX_NULLIFIERS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - NULLIFIER_TREE_HEIGHT, NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_SUBTREE_HEIGHT, - }, merkle_tree::MembershipWitness, tests::merkle_tree_utils::NonEmptyMerkleTree, - utils::arrays::{find_index_hint, get_sorted_result}, + MAX_NULLIFIERS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, NULLIFIER_TREE_HEIGHT, + NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_SUBTREE_HEIGHT +}, + merkle_tree::MembershipWitness, tests::merkle_tree_utils::NonEmptyMerkleTree, + utils::arrays::{find_index_hint, get_sorted_result} }; pub struct NullifierNonExistentReadRequestHintsBuilder { @@ -23,13 +22,13 @@ impl NullifierNonExistentReadRequestHintsBuilder { nullifier_tree: NonEmptyMerkleTree::empty(), non_membership_hints: BoundedVec::new(), read_values: BoundedVec::new(), - pending_nullifiers: [Nullifier::empty(); MAX_NULLIFIERS_PER_TX], + pending_nullifiers: [Nullifier::empty(); MAX_NULLIFIERS_PER_TX] } } pub fn set_nullifier_tree( &mut self, - tree: NonEmptyMerkleTree, + tree: NonEmptyMerkleTree ) { self.nullifier_tree = tree; } @@ -44,15 +43,8 @@ impl NullifierNonExistentReadRequestHintsBuilder { // There are only two pre-existing nullifiers in the tree: [0, 100], generated in public_kernel_tail::tests. // Assuming the siloed_value is always greater than 100. let hint = NullifierNonMembershipHint { - low_leaf_preimage: NullifierLeafPreimage { - nullifier: 100, - next_nullifier: 0, - next_index: 0, - }, - membership_witness: MembershipWitness { - leaf_index: 1, - sibling_path: self.nullifier_tree.get_sibling_path(1), - }, + low_leaf_preimage: NullifierLeafPreimage { nullifier: 100, next_nullifier: 0, next_index: 0 }, + membership_witness: MembershipWitness { leaf_index: 1, sibling_path: self.nullifier_tree.get_sibling_path(1) } }; self.non_membership_hints.push(hint); } @@ -60,7 +52,7 @@ impl NullifierNonExistentReadRequestHintsBuilder { pub unconstrained fn to_hints(self) -> NullifierNonExistentReadRequestHints { let sorted_result = get_sorted_result( self.pending_nullifiers, - |a: Nullifier, b: Nullifier| (b.value == 0) | ((a.value != 0) & a.value.lt(b.value)), + |a: Nullifier, b: Nullifier| (b.value == 0) | ((a.value != 0) & a.value.lt(b.value)) ); let sorted_pending_values = sorted_result.sorted_array; let sorted_pending_value_index_hints = sorted_result.sorted_index_hints; @@ -78,7 +70,7 @@ impl NullifierNonExistentReadRequestHintsBuilder { non_membership_hints: self.non_membership_hints.storage, sorted_pending_values, sorted_pending_value_index_hints, - next_pending_value_indices, + next_pending_value_indices } } } diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_read_request_hints_builder.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_read_request_hints_builder.nr index b3a4717bcf3..0a24622d9eb 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_read_request_hints_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_read_request_hints_builder.nr @@ -1,6 +1,6 @@ use crate::{ nullifier_read_request_reset::{NullifierSettledReadHint, NullifierReadRequestHints}, - reset::read_request::{PendingReadHint, ReadRequestStatus}, + reset::read_request::{PendingReadHint, ReadRequestStatus} }; use dep::types::constants::MAX_NULLIFIER_READ_REQUESTS_PER_TX; @@ -14,29 +14,19 @@ impl NullifierReadReques pub fn new() -> Self { NullifierReadRequestHintsBuilder { read_request_statuses: [ReadRequestStatus::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX], - pending_read_hints: BoundedVec { - storage: [ - PendingReadHint::nada(MAX_NULLIFIER_READ_REQUESTS_PER_TX); NUM_PENDING_HINTS - ], - len: 0, - }, + pending_read_hints: BoundedVec { storage: [PendingReadHint::nada(MAX_NULLIFIER_READ_REQUESTS_PER_TX); NUM_PENDING_HINTS], len: 0 }, settled_read_hints: BoundedVec { - storage: [ - NullifierSettledReadHint::nada(MAX_NULLIFIER_READ_REQUESTS_PER_TX); - NUM_SETTLED_HINTS - ], - len: 0, - }, + storage: [NullifierSettledReadHint::nada(MAX_NULLIFIER_READ_REQUESTS_PER_TX); NUM_SETTLED_HINTS], + len: 0 } } + } - pub unconstrained fn to_hints( - self, - ) -> NullifierReadRequestHints { + pub unconstrained fn to_hints(self) -> NullifierReadRequestHints { NullifierReadRequestHints { read_request_statuses: self.read_request_statuses, pending_read_hints: self.pending_read_hints.storage, - settled_read_hints: self.settled_read_hints.storage, + settled_read_hints: self.settled_read_hints.storage } } } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/base_or_merge_rollup_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/base_or_merge_rollup_public_inputs.nr index cf844edcfe4..9af2926f324 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/base_or_merge_rollup_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/base_or_merge_rollup_public_inputs.nr @@ -1,6 +1,6 @@ use dep::types::{ constants::BASE_OR_MERGE_PUBLIC_INPUTS_LENGTH, partial_state_reference::PartialStateReference, - traits::{Empty, Serialize, Deserialize}, utils::reader::Reader, + traits::{Empty, Serialize, Deserialize}, utils::reader::Reader }; use crate::abis::constant_rollup_data::ConstantRollupData; @@ -38,7 +38,7 @@ impl Empty for BaseOrMergeRollupPublicInputs { end: PartialStateReference::empty(), txs_effects_hash: 0, out_hash: 0, - accumulated_fees: 0, + accumulated_fees: 0 } } } @@ -76,9 +76,7 @@ impl Serialize for BaseOrMergeRollupPublicIn } impl Deserialize for BaseOrMergeRollupPublicInputs { - fn deserialize( - fields: [Field; BASE_OR_MERGE_PUBLIC_INPUTS_LENGTH], - ) -> BaseOrMergeRollupPublicInputs { + fn deserialize(fields: [Field; BASE_OR_MERGE_PUBLIC_INPUTS_LENGTH]) -> BaseOrMergeRollupPublicInputs { let mut reader = Reader::new(fields); let item = Self { rollup_type: reader.read() as u32, @@ -88,7 +86,7 @@ impl Deserialize for BaseOrMergeRollupPublic end: reader.read_struct(PartialStateReference::deserialize), txs_effects_hash: reader.read(), out_hash: reader.read(), - accumulated_fees: reader.read(), + accumulated_fees: reader.read() }; reader.finish(); diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/block_root_or_block_merge_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/block_root_or_block_merge_public_inputs.nr index a8fea926e2c..4e013dcd7de 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/block_root_or_block_merge_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/block_root_or_block_merge_public_inputs.nr @@ -1,8 +1,7 @@ use dep::types::{ abis::{append_only_tree_snapshot::AppendOnlyTreeSnapshot, global_variables::GlobalVariables}, - constants::{ - AZTEC_EPOCH_DURATION, BLOCK_ROOT_OR_BLOCK_MERGE_PUBLIC_INPUTS_LENGTH, FEE_RECIPIENT_LENGTH, - }, traits::{Empty, Serialize, Deserialize}, utils::reader::Reader, address::EthAddress, + constants::{AZTEC_EPOCH_DURATION, BLOCK_ROOT_OR_BLOCK_MERGE_PUBLIC_INPUTS_LENGTH, FEE_RECIPIENT_LENGTH}, + traits::{Empty, Serialize, Deserialize}, utils::reader::Reader, address::EthAddress }; pub struct FeeRecipient { @@ -70,7 +69,7 @@ impl Empty for BlockRootOrBlockMergePublicInputs { fees: [FeeRecipient::empty(); AZTEC_EPOCH_DURATION], vk_tree_root: 0, protocol_contract_tree_root: 0, - prover_id: 0, + prover_id: 0 } } } @@ -86,15 +85,15 @@ impl Eq for BlockRootOrBlockMergePublicInputs { & (self.out_hash == other.out_hash) & (self.fees.eq(other.fees)) & (self.vk_tree_root == other.vk_tree_root) - & (self.protocol_contract_tree_root == other.protocol_contract_tree_root) + & (self.protocol_contract_tree_root + == other.protocol_contract_tree_root) & (self.prover_id == other.prover_id) } } impl Serialize for BlockRootOrBlockMergePublicInputs { fn serialize(self) -> [Field; BLOCK_ROOT_OR_BLOCK_MERGE_PUBLIC_INPUTS_LENGTH] { - let mut fields: BoundedVec = - BoundedVec::new(); + let mut fields: BoundedVec = BoundedVec::new(); fields.extend_from_array(self.previous_archive.serialize()); fields.extend_from_array(self.new_archive.serialize()); @@ -116,9 +115,7 @@ impl Serialize for BlockRootOrBl } impl Deserialize for BlockRootOrBlockMergePublicInputs { - fn deserialize( - fields: [Field; BLOCK_ROOT_OR_BLOCK_MERGE_PUBLIC_INPUTS_LENGTH], - ) -> BlockRootOrBlockMergePublicInputs { + fn deserialize(fields: [Field; BLOCK_ROOT_OR_BLOCK_MERGE_PUBLIC_INPUTS_LENGTH]) -> BlockRootOrBlockMergePublicInputs { let mut reader = Reader::new(fields); let item = Self { previous_archive: reader.read_struct(AppendOnlyTreeSnapshot::deserialize), @@ -130,11 +127,11 @@ impl Deserialize for BlockRootOr out_hash: reader.read(), fees: reader.read_struct_array( FeeRecipient::deserialize, - [FeeRecipient::empty(); AZTEC_EPOCH_DURATION], + [FeeRecipient::empty(); AZTEC_EPOCH_DURATION] ), vk_tree_root: reader.read(), protocol_contract_tree_root: reader.read(), - prover_id: reader.read(), + prover_id: reader.read() }; reader.finish(); diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/constant_rollup_data.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/constant_rollup_data.nr index 6c5380cc42e..ba4bbae335e 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/constant_rollup_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/constant_rollup_data.nr @@ -1,7 +1,7 @@ use dep::types::{ abis::{global_variables::GlobalVariables, append_only_tree_snapshot::AppendOnlyTreeSnapshot}, traits::{Empty, Serialize, Deserialize}, constants::CONSTANT_ROLLUP_DATA_LENGTH, - utils::reader::Reader, + utils::reader::Reader }; pub struct ConstantRollupData { @@ -27,7 +27,7 @@ impl Empty for ConstantRollupData { last_archive: AppendOnlyTreeSnapshot::zero(), vk_tree_root: 0, protocol_contract_tree_root: 0, - global_variables: GlobalVariables::empty(), + global_variables: GlobalVariables::empty() } } } @@ -54,7 +54,7 @@ impl Deserialize for ConstantRollupData { last_archive: reader.read_struct(AppendOnlyTreeSnapshot::deserialize), vk_tree_root: reader.read(), protocol_contract_tree_root: reader.read(), - global_variables: reader.read_struct(GlobalVariables::deserialize), + global_variables: reader.read_struct(GlobalVariables::deserialize) }; reader.finish(); diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/previous_rollup_block_data.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/previous_rollup_block_data.nr index 100233dcb6b..94f4ef54add 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/previous_rollup_block_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/previous_rollup_block_data.nr @@ -2,10 +2,11 @@ use crate::abis::block_root_or_block_merge_public_inputs::BlockRootOrBlockMergeP use dep::types::{ constants::VK_TREE_HEIGHT, recursion::{ - proof::NestedRecursiveProof, verification_key::{HonkVerificationKey, VerificationKey}, - traits::Verifiable, - }, traits::Empty, merkle_tree::MembershipWitness, - merkle_tree::membership::assert_check_membership, utils::arrays::find_index_hint, + proof::NestedRecursiveProof, verification_key::{HonkVerificationKey, VerificationKey}, + traits::Verifiable +}, + traits::Empty, merkle_tree::MembershipWitness, merkle_tree::membership::assert_check_membership, + utils::arrays::find_index_hint }; pub struct PreviousRollupBlockData { @@ -17,9 +18,7 @@ pub struct PreviousRollupBlockData { impl Verifiable for PreviousRollupBlockData { fn verify(self) { - let inputs = BlockRootOrBlockMergePublicInputs::serialize( - self.block_root_or_block_merge_public_inputs, - ); + let inputs = BlockRootOrBlockMergePublicInputs::serialize(self.block_root_or_block_merge_public_inputs); std::verify_proof(self.vk.key, self.proof.fields, inputs, self.vk.hash); } } @@ -30,7 +29,7 @@ impl Empty for PreviousRollupBlockData { block_root_or_block_merge_public_inputs: BlockRootOrBlockMergePublicInputs::empty(), proof: NestedRecursiveProof::empty(), vk: VerificationKey::empty(), - vk_witness: MembershipWitness::empty(), + vk_witness: MembershipWitness::empty() } } } @@ -40,8 +39,9 @@ impl PreviousRollupBlockData { self.vk.check_hash(); let leaf_index = self.vk_witness.leaf_index as u32; - let index_hint = - unsafe { find_index_hint(allowed_indices, |index: u32| index == leaf_index) }; + let index_hint = unsafe { + find_index_hint(allowed_indices, |index: u32| index == leaf_index) + }; assert(index_hint < N, "Invalid vk index"); assert_eq(allowed_indices[index_hint], leaf_index, "Invalid vk index"); @@ -49,7 +49,7 @@ impl PreviousRollupBlockData { self.vk.hash, self.vk_witness.leaf_index, self.vk_witness.sibling_path, - self.block_root_or_block_merge_public_inputs.vk_tree_root, + self.block_root_or_block_merge_public_inputs.vk_tree_root ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/previous_rollup_data.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/previous_rollup_data.nr index 1b7e4867811..12798294baa 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/previous_rollup_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/abis/previous_rollup_data.nr @@ -2,10 +2,11 @@ use crate::abis::base_or_merge_rollup_public_inputs::BaseOrMergeRollupPublicInpu use dep::types::{ constants::VK_TREE_HEIGHT, recursion::{ - proof::NestedRecursiveProof, verification_key::{VerificationKey, HonkVerificationKey}, - traits::Verifiable, - }, traits::Empty, merkle_tree::MembershipWitness, - merkle_tree::membership::assert_check_membership, utils::arrays::find_index_hint, + proof::NestedRecursiveProof, verification_key::{VerificationKey, HonkVerificationKey}, + traits::Verifiable +}, + traits::Empty, merkle_tree::MembershipWitness, merkle_tree::membership::assert_check_membership, + utils::arrays::find_index_hint }; pub struct PreviousRollupData { @@ -17,8 +18,7 @@ pub struct PreviousRollupData { impl Verifiable for PreviousRollupData { fn verify(self) { - let inputs = - BaseOrMergeRollupPublicInputs::serialize(self.base_or_merge_rollup_public_inputs); + let inputs = BaseOrMergeRollupPublicInputs::serialize(self.base_or_merge_rollup_public_inputs); std::verify_proof(self.vk.key, self.proof.fields, inputs, self.vk.hash); } } @@ -29,7 +29,7 @@ impl Empty for PreviousRollupData { base_or_merge_rollup_public_inputs: BaseOrMergeRollupPublicInputs::empty(), proof: NestedRecursiveProof::empty(), vk: VerificationKey::empty(), - vk_witness: MembershipWitness::empty(), + vk_witness: MembershipWitness::empty() } } } @@ -39,8 +39,9 @@ impl PreviousRollupData { self.vk.check_hash(); let leaf_index = self.vk_witness.leaf_index as u32; - let index_hint = - unsafe { find_index_hint(allowed_indices, |index: u32| index == leaf_index) }; + let index_hint = unsafe { + find_index_hint(allowed_indices, |index: u32| index == leaf_index) + }; assert(index_hint < N, "Invalid vk index"); assert_eq(allowed_indices[index_hint], leaf_index, "Invalid vk index"); @@ -48,7 +49,7 @@ impl PreviousRollupData { self.vk.hash, self.vk_witness.leaf_index, self.vk_witness.sibling_path, - self.base_or_merge_rollup_public_inputs.constants.vk_tree_root, + self.base_or_merge_rollup_public_inputs.constants.vk_tree_root ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/base_rollup_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/base_rollup_inputs.nr index dd9d49aaec1..d3641e93080 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/base_rollup_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/base_rollup_inputs.nr @@ -1,34 +1,37 @@ use crate::{ abis::{ - constant_rollup_data::ConstantRollupData, - base_or_merge_rollup_public_inputs::{BaseOrMergeRollupPublicInputs, BASE_ROLLUP_TYPE}, - }, base::state_diff_hints::StateDiffHints, - components::{compute_tx_effects_hash, compute_kernel_out_hash}, + constant_rollup_data::ConstantRollupData, + base_or_merge_rollup_public_inputs::{BaseOrMergeRollupPublicInputs, BASE_ROLLUP_TYPE} +}, + base::state_diff_hints::StateDiffHints, + components::{compute_tx_effects_hash, compute_kernel_out_hash} }; use dep::types::{ hash::silo_l2_to_l1_message, data::{ - public_data_hint::PublicDataHint, - hash::{compute_public_data_tree_index, compute_public_data_tree_value}, - }, storage::map::derive_storage_slot_in_map, address::AztecAddress, + public_data_hint::PublicDataHint, + hash::{compute_public_data_tree_index, compute_public_data_tree_value} +}, + storage::map::derive_storage_slot_in_map, address::AztecAddress, abis::{ - append_only_tree_snapshot::AppendOnlyTreeSnapshot, - nullifier_leaf_preimage::NullifierLeafPreimage, - public_data_update_request::PublicDataUpdateRequest, kernel_data::KernelData, - }, messaging::l2_to_l1_message::ScopedL2ToL1Message, + append_only_tree_snapshot::AppendOnlyTreeSnapshot, nullifier_leaf_preimage::NullifierLeafPreimage, + public_data_update_request::PublicDataUpdateRequest, kernel_data::KernelData +}, + messaging::l2_to_l1_message::ScopedL2ToL1Message, constants::{ - PUBLIC_DATA_TREE_HEIGHT, NOTE_HASH_SUBTREE_HEIGHT, MAX_NOTE_HASHES_PER_TX, - MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, NULLIFIER_SUBTREE_HEIGHT, - NULLIFIER_TREE_HEIGHT, PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, PUBLIC_DATA_SUBTREE_HEIGHT, - ARCHIVE_HEIGHT, FEE_JUICE_ADDRESS, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - PUBLIC_KERNEL_TAIL_INDEX, PRIVATE_KERNEL_EMPTY_INDEX, TUBE_INDEX, - }, + PUBLIC_DATA_TREE_HEIGHT, NOTE_HASH_SUBTREE_HEIGHT, MAX_NOTE_HASHES_PER_TX, + MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, NULLIFIER_SUBTREE_HEIGHT, NULLIFIER_TREE_HEIGHT, + PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, PUBLIC_DATA_SUBTREE_HEIGHT, ARCHIVE_HEIGHT, + FEE_JUICE_ADDRESS, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, PUBLIC_KERNEL_TAIL_INDEX, + PRIVATE_KERNEL_EMPTY_INDEX, TUBE_INDEX +}, merkle_tree::{ - append_only_tree, assert_check_membership, calculate_empty_tree_root, - calculate_subtree_root, indexed_tree, MembershipWitness, - }, partial_state_reference::PartialStateReference, + append_only_tree, assert_check_membership, calculate_empty_tree_root, calculate_subtree_root, + indexed_tree, MembershipWitness +}, + partial_state_reference::PartialStateReference, data::{PublicDataTreeLeaf, PublicDataTreeLeafPreimage}, traits::is_empty, - utils::field::{full_field_less_than, full_field_greater_than}, + utils::field::{full_field_less_than, full_field_greater_than} }; global ALLOWED_PREVIOUS_CIRCUITS = @@ -63,33 +66,26 @@ impl BaseRollupInputs { // Verify the kernel chain_id and versions assert( self.kernel_data.public_inputs.constants.tx_context.chain_id - == self.constants.global_variables.chain_id, - "kernel chain_id does not match the rollup chain_id", + == self.constants.global_variables.chain_id, "kernel chain_id does not match the rollup chain_id" ); assert( self.kernel_data.public_inputs.constants.tx_context.version - == self.constants.global_variables.version, - "kernel version does not match the rollup version", + == self.constants.global_variables.version, "kernel version does not match the rollup version" ); assert( - self.kernel_data.public_inputs.constants.vk_tree_root == self.constants.vk_tree_root, - "kernel vk_tree_root does not match the rollup vk_tree_root", + self.kernel_data.public_inputs.constants.vk_tree_root == self.constants.vk_tree_root, "kernel vk_tree_root does not match the rollup vk_tree_root" ); assert( self.kernel_data.public_inputs.constants.protocol_contract_tree_root - == self.constants.protocol_contract_tree_root, - "kernel protocol_contract_tree_root does not match the rollup protocol_contract_tree_root", + == self.constants.protocol_contract_tree_root, "kernel protocol_contract_tree_root does not match the rollup protocol_contract_tree_root" ); // Verify the kernel global variables if set, note these can be empty if this is a request coming directly from the private kernel tail. // TODO(@spalladino) How can we check that this is a request coming from the private kernel tail? assert( self.kernel_data.public_inputs.constants.global_variables.is_empty() - | ( - self.kernel_data.public_inputs.constants.global_variables - == self.constants.global_variables - ), - "kernel global variables do not match the rollup global variables", + | (self.kernel_data.public_inputs.constants.global_variables + == self.constants.global_variables), "kernel global variables do not match the rollup global variables" ); self.validate_kernel_start_state(); @@ -101,8 +97,7 @@ impl BaseRollupInputs { if rollup_validation_requests.max_block_number.is_some() { assert( self.constants.global_variables.block_number as u32 - <= rollup_validation_requests.max_block_number.unwrap_unchecked(), - "kernel max_block_number is smaller than block number", + <= rollup_validation_requests.max_block_number.unwrap_unchecked(), "kernel max_block_number is smaller than block number" ); } @@ -115,22 +110,19 @@ impl BaseRollupInputs { self.state_diff_hints.note_hash_subtree_sibling_path, empty_commitments_subtree_root, commitments_tree_subroot, - NOTE_HASH_SUBTREE_HEIGHT as u8, + NOTE_HASH_SUBTREE_HEIGHT as u8 ); // Insert nullifiers: - let end_nullifier_tree_snapshot = - self.check_nullifier_tree_non_membership_and_insert_to_tree(); + let end_nullifier_tree_snapshot = self.check_nullifier_tree_non_membership_and_insert_to_tree(); // Inject protocol update requests for deducting tx_fee from fee_payer's balance let gas_fees = self.constants.global_variables.gas_fees; let transaction_fee = self.kernel_data.public_inputs.compute_transaction_fee(gas_fees); - let all_public_data_update_requests = - self.calculate_all_public_data_update_requests(transaction_fee); + let all_public_data_update_requests = self.calculate_all_public_data_update_requests(transaction_fee); // Validate public data update requests and update public data tree - let end_public_data_tree_snapshot = - self.validate_and_process_public_state(all_public_data_update_requests); + let end_public_data_tree_snapshot = self.validate_and_process_public_state(all_public_data_update_requests); // Calculate the tx effects hash of the transaction let siloed_l2_to_l1_msgs = self.kernel_data.public_inputs.end.l2_to_l1_msgs.map( @@ -138,7 +130,7 @@ impl BaseRollupInputs { message, self.kernel_data.public_inputs.constants.tx_context.version, self.kernel_data.public_inputs.constants.tx_context.chain_id, - ), + ) ); let out_hash = compute_kernel_out_hash(siloed_l2_to_l1_msgs); let tx_effects_hash = compute_tx_effects_hash( @@ -146,7 +138,7 @@ impl BaseRollupInputs { self.kernel_data.public_inputs.revert_code, transaction_fee, all_public_data_update_requests, - out_hash, + out_hash ); // Perform membership checks that the notes provided exist within the historical trees data @@ -160,11 +152,11 @@ impl BaseRollupInputs { end: PartialStateReference { note_hash_tree: end_note_hash_tree_snapshot, nullifier_tree: end_nullifier_tree_snapshot, - public_data_tree: end_public_data_tree_snapshot, + public_data_tree: end_public_data_tree_snapshot }, txs_effects_hash: tx_effects_hash, out_hash, - accumulated_fees: transaction_fee, + accumulated_fees: transaction_fee } } @@ -188,7 +180,7 @@ impl BaseRollupInputs { leaf_index: witness.leaf_index, sibling_path: witness.sibling_path, } - }, + } ), |low_leaf: NullifierLeafPreimage, nullifier: Field| { // Is valid low leaf @@ -219,7 +211,7 @@ impl BaseRollupInputs { } }, [0; NULLIFIER_SUBTREE_HEIGHT], - [0; NULLIFIER_TREE_HEIGHT], + [0; NULLIFIER_TREE_HEIGHT] ) } @@ -231,23 +223,20 @@ impl BaseRollupInputs { let kernel_state = self.kernel_data.public_inputs.start_state; if !is_empty(kernel_state) { assert( - kernel_state.note_hash_tree.eq(self.start.note_hash_tree), - "Mismatch start state for note hash tree", + kernel_state.note_hash_tree.eq(self.start.note_hash_tree), "Mismatch start state for note hash tree" ); assert( - kernel_state.nullifier_tree.eq(self.start.nullifier_tree), - "Mismatch start state for nullifier tree", + kernel_state.nullifier_tree.eq(self.start.nullifier_tree), "Mismatch start state for nullifier tree" ); assert( - kernel_state.public_data_tree.eq(self.start.public_data_tree), - "Mismatch start state for public data tree", + kernel_state.public_data_tree.eq(self.start.public_data_tree), "Mismatch start state for public data tree" ); } } fn validate_and_process_public_state( self, - all_update_requests: [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], + all_update_requests: [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX] ) -> AppendOnlyTreeSnapshot { let end_public_data_tree_snapshot = insert_public_data_update_requests( self.start.public_data_tree, @@ -256,7 +245,7 @@ impl BaseRollupInputs { self.sorted_public_data_writes_indexes, self.low_public_data_writes_preimages, self.low_public_data_writes_witnesses, - self.state_diff_hints.public_data_sibling_path, + self.state_diff_hints.public_data_sibling_path ); end_public_data_tree_snapshot @@ -267,17 +256,15 @@ impl BaseRollupInputs { // update request we have at the time of this writing is deducting the tx_fee from the fee_payer balance. fn calculate_all_public_data_update_requests( self, - tx_fee: Field, + tx_fee: Field ) -> [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX] { - let mut all_update_requests: [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX] = - [PublicDataUpdateRequest::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; + let mut all_update_requests: [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX] = [PublicDataUpdateRequest::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; for i in 0..MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX { all_update_requests[i] = self.kernel_data.public_inputs.end.public_data_update_requests[i]; } - let (payment_update_request, payment_update_index) = - self.build_or_patch_payment_update_request(tx_fee); + let (payment_update_request, payment_update_index) = self.build_or_patch_payment_update_request(tx_fee); all_update_requests[payment_update_index] = payment_update_request; all_update_requests @@ -289,10 +276,7 @@ impl BaseRollupInputs { // from the balance of the fee_payer, using the fee_payer_fee_juice_balance_read_hint to read the current balance. // Returns the data update request that subtracts the tx_fee from the fee_payer's balance, and the index where it // should be inserted in the public data update requests array. - fn build_or_patch_payment_update_request( - self, - tx_fee: Field, - ) -> (PublicDataUpdateRequest, u32) { + fn build_or_patch_payment_update_request(self, tx_fee: Field) -> (PublicDataUpdateRequest, u32) { let fee_payer = self.kernel_data.public_inputs.fee_payer; // TODO(@spalladino) Eventually remove the is_zero condition as we should always charge fees to every tx @@ -302,48 +286,37 @@ impl BaseRollupInputs { if read_hint.leaf_slot == 0 { // Is there a balance update already in this tx? If so, update it and return its index. - let existing_update_index = - unsafe { self.find_fee_payer_fee_juice_update_index(leaf_slot) }; - let existing_update = self.kernel_data.public_inputs.end.public_data_update_requests - [existing_update_index]; - assert( - existing_update.leaf_slot == leaf_slot, - "Wrong leaf slot for Fee Juice balance update request", - ); - assert( - !existing_update.new_value.lt(tx_fee), - "Not enough balance for fee payer after claim to pay for transaction", - ); + let existing_update_index = unsafe { + self.find_fee_payer_fee_juice_update_index(leaf_slot) + }; + let existing_update = self.kernel_data.public_inputs.end.public_data_update_requests[existing_update_index]; + assert( + existing_update.leaf_slot == leaf_slot, "Wrong leaf slot for Fee Juice balance update request" + ); + assert( + !existing_update.new_value.lt(tx_fee), "Not enough balance for fee payer after claim to pay for transaction" + ); - let new_value = - compute_public_data_tree_value(existing_update.new_value - tx_fee); - let protocol_update_request = - PublicDataUpdateRequest { leaf_slot, new_value, counter: 0 }; - (protocol_update_request, existing_update_index as u32) - } else { - // Otherwise, build a new one to be inserted into the protocol update requests at the end of the array. - read_hint.validate(self.start.public_data_tree.root); + let new_value = compute_public_data_tree_value(existing_update.new_value - tx_fee); + let protocol_update_request = PublicDataUpdateRequest { leaf_slot, new_value, counter: 0 }; + (protocol_update_request, existing_update_index as u32) + } else { + // Otherwise, build a new one to be inserted into the protocol update requests at the end of the array. + read_hint.validate(self.start.public_data_tree.root); - let balance = read_hint.value; - assert( - read_hint.leaf_slot == leaf_slot, - "Wrong leaf slot for Fee Juice balance read hint", - ); - assert( - !balance.lt(tx_fee), - "Not enough balance for fee payer to pay for transaction", - ); + let balance = read_hint.value; + assert(read_hint.leaf_slot == leaf_slot, "Wrong leaf slot for Fee Juice balance read hint"); + assert(!balance.lt(tx_fee), "Not enough balance for fee payer to pay for transaction"); - let new_value = compute_public_data_tree_value(balance - tx_fee); - let protocol_update_request = - PublicDataUpdateRequest { leaf_slot, new_value, counter: 0 }; - (protocol_update_request, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX) - } - } else { - // Nothing to do, just place an empty update request at the end of the array - (PublicDataUpdateRequest::empty(), MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX) + let new_value = compute_public_data_tree_value(balance - tx_fee); + let protocol_update_request = PublicDataUpdateRequest { leaf_slot, new_value, counter: 0 }; + (protocol_update_request, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX) } + } else { + // Nothing to do, just place an empty update request at the end of the array + (PublicDataUpdateRequest::empty(), MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX) } + } // Check that the block header used by each kernel is a member of the blocks tree --> since the block header // contains roots of all the trees this is sufficient to verify that the tree roots used by kernels are correct @@ -363,21 +336,19 @@ impl BaseRollupInputs { previous_block_hash, previous_block_hash_witness.leaf_index, previous_block_hash_witness.sibling_path, - archive_root, + archive_root ); } unconstrained fn find_fee_payer_fee_juice_update_index(self, leaf_slot: Field) -> u32 { let mut update_index = MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX + 1; for i in 0..MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX { - if self.kernel_data.public_inputs.end.public_data_update_requests[i].leaf_slot - == leaf_slot { + if self.kernel_data.public_inputs.end.public_data_update_requests[i].leaf_slot == leaf_slot { update_index = i; } } assert( - update_index < MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - "Could not find fee payer Fee Juice update request", + update_index < MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, "Could not find fee payer Fee Juice update request" ); update_index } @@ -390,7 +361,7 @@ fn insert_public_data_update_requests( sorted_public_data_writes_indexes: [u32; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], low_public_data_writes_preimages: [PublicDataTreeLeafPreimage; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], low_public_data_writes_witnesses: [MembershipWitness; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], - public_data_writes_subtree_sibling_path: [Field; PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH], + public_data_writes_subtree_sibling_path: [Field; PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH] ) -> AppendOnlyTreeSnapshot { indexed_tree::batch_insert( prev_snapshot, @@ -405,7 +376,7 @@ fn insert_public_data_update_requests( leaf_index: witness.leaf_index, sibling_path: witness.sibling_path, } - }, + } ), |low_preimage: PublicDataTreeLeafPreimage, write: PublicDataTreeLeaf| { // Is valid low preimage @@ -456,26 +427,23 @@ fn insert_public_data_update_requests( } }, [0; PUBLIC_DATA_SUBTREE_HEIGHT], - [0; PUBLIC_DATA_TREE_HEIGHT], + [0; PUBLIC_DATA_TREE_HEIGHT] ) } fn compute_fee_payer_fee_juice_balance_leaf_slot(fee_payer: AztecAddress) -> Field { let balances_slot_in_fee_juice_contract = 1; - let fee_payer_balance_slot_in_fee_juice_contract = - derive_storage_slot_in_map(balances_slot_in_fee_juice_contract, fee_payer); + let fee_payer_balance_slot_in_fee_juice_contract = derive_storage_slot_in_map(balances_slot_in_fee_juice_contract, fee_payer); compute_public_data_tree_index( FEE_JUICE_ADDRESS, - fee_payer_balance_slot_in_fee_juice_contract, + fee_payer_balance_slot_in_fee_juice_contract ) } #[test] fn consistent_not_hash_subtree_width() { assert_eq( - MAX_NOTE_HASHES_PER_TX as Field, - 2.pow_32(NOTE_HASH_SUBTREE_HEIGHT as Field), - "note hash subtree width is incorrect", + MAX_NOTE_HASHES_PER_TX as Field, 2.pow_32(NOTE_HASH_SUBTREE_HEIGHT as Field), "note hash subtree width is incorrect" ); } @@ -500,38 +468,39 @@ fn test_u256_greater_than() { mod tests { use crate::{ abis::{ - constant_rollup_data::ConstantRollupData, - base_or_merge_rollup_public_inputs::BaseOrMergeRollupPublicInputs, - }, + constant_rollup_data::ConstantRollupData, + base_or_merge_rollup_public_inputs::BaseOrMergeRollupPublicInputs + }, base::{ - state_diff_hints::StateDiffHints, - base_rollup_inputs::{BaseRollupInputs, compute_fee_payer_fee_juice_balance_leaf_slot}, - }, components::TX_EFFECTS_HASH_INPUT_FIELDS, + state_diff_hints::StateDiffHints, + base_rollup_inputs::{BaseRollupInputs, compute_fee_payer_fee_juice_balance_leaf_slot} + }, + components::TX_EFFECTS_HASH_INPUT_FIELDS }; use dep::types::{ abis::{ - append_only_tree_snapshot::AppendOnlyTreeSnapshot, - nullifier_leaf_preimage::NullifierLeafPreimage, - public_data_update_request::PublicDataUpdateRequest, kernel_data::KernelData, - }, messaging::l2_to_l1_message::ScopedL2ToL1Message, merkle_tree::MembershipWitness, + append_only_tree_snapshot::AppendOnlyTreeSnapshot, + nullifier_leaf_preimage::NullifierLeafPreimage, + public_data_update_request::PublicDataUpdateRequest, kernel_data::KernelData + }, + messaging::l2_to_l1_message::ScopedL2ToL1Message, merkle_tree::MembershipWitness, hash::silo_l2_to_l1_message, data::public_data_hint::PublicDataHint, address::{AztecAddress, EthAddress}, constants::{ - ARCHIVE_HEIGHT, MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, - MAX_NULLIFIERS_PER_TX, NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, NOTE_HASH_TREE_HEIGHT, - NOTE_HASH_SUBTREE_HEIGHT, NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_TREE_HEIGHT, - NULLIFIER_SUBTREE_HEIGHT, PUBLIC_DATA_TREE_HEIGHT, PUBLIC_DATA_SUBTREE_HEIGHT, - PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, MAX_L2_TO_L1_MSGS_PER_TX, - PROTOCOL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - PRIVATE_KERNEL_EMPTY_INDEX, PRIVATE_KERNEL_TAIL_INDEX, PUBLIC_KERNEL_TAIL_INDEX, - BASE_ROLLUP_INDEX, TUBE_INDEX, - }, partial_state_reference::PartialStateReference, + ARCHIVE_HEIGHT, MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, + MAX_NULLIFIERS_PER_TX, NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, NOTE_HASH_TREE_HEIGHT, + NOTE_HASH_SUBTREE_HEIGHT, NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_TREE_HEIGHT, + NULLIFIER_SUBTREE_HEIGHT, PUBLIC_DATA_TREE_HEIGHT, PUBLIC_DATA_SUBTREE_HEIGHT, + PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, MAX_L2_TO_L1_MSGS_PER_TX, + PROTOCOL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, + PRIVATE_KERNEL_EMPTY_INDEX, PRIVATE_KERNEL_TAIL_INDEX, PUBLIC_KERNEL_TAIL_INDEX, + BASE_ROLLUP_INDEX, TUBE_INDEX + }, + partial_state_reference::PartialStateReference, data::{PublicDataTreeLeaf, PublicDataTreeLeafPreimage}, tests::{fixtures, fixture_builder::FixtureBuilder, merkle_tree_utils::NonEmptyMerkleTree}, - utils::{ - arrays::get_sorted_tuple::get_sorted_tuple, - field::{full_field_less_than, field_from_bytes_32_trunc}, - }, traits::Empty, + utils::{arrays::get_sorted_tuple::get_sorted_tuple, field::{full_field_less_than, field_from_bytes_32_trunc}}, + traits::Empty }; struct NullifierInsertion { @@ -549,19 +518,14 @@ mod tests { user_public_data_writes: BoundedVec<(u32, PublicDataTreeLeaf), MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX>, protocol_public_data_writes: BoundedVec<(u32, PublicDataTreeLeaf), PROTOCOL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX>, mut final_public_data_writes: BoundedVec<(u32, PublicDataTreeLeaf), MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX>, - mut pre_existing_public_data: [PublicDataTreeLeafPreimage; EXISTING_LEAVES], + mut pre_existing_public_data: [PublicDataTreeLeafPreimage; EXISTING_LEAVES] ) -> ([Field; PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH], [PublicDataTreeLeaf; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], [u32; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], [PublicDataTreeLeafPreimage; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], [MembershipWitness; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], [PublicDataTreeLeafPreimage; EXISTING_LEAVES]) { let mut subtree_path = [0; PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH]; - let mut sorted_public_data_writes = - [PublicDataTreeLeaf::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; - let mut sorted_public_data_writes_indexes = - [0 as u32; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; - let mut low_public_data_writes_preimages = - [PublicDataTreeLeafPreimage::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; - let mut low_public_data_writes_witnesses = - [MembershipWitness::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; - let mut new_subtree = - [PublicDataTreeLeafPreimage::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; + let mut sorted_public_data_writes = [PublicDataTreeLeaf::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; + let mut sorted_public_data_writes_indexes = [0 as u32; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; + let mut low_public_data_writes_preimages = [PublicDataTreeLeafPreimage::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; + let mut low_public_data_writes_witnesses = [MembershipWitness::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; + let mut new_subtree = [PublicDataTreeLeafPreimage::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]; for i in 0..MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX { if i < (user_public_data_writes.len()) { @@ -586,7 +550,7 @@ mod tests { final_public_data_writes.storage, |(_, leaf_a): (u32, PublicDataTreeLeaf), (_, leaf_b): (u32, PublicDataTreeLeaf)| { full_field_less_than(leaf_b.slot, leaf_a.slot) - }, + } ) }; @@ -623,7 +587,7 @@ mod tests { public_data_tree.update_leaf( low_leaf_index, - pre_existing_public_data[low_leaf_index].hash(), + pre_existing_public_data[low_leaf_index].hash() ); } } else { @@ -638,9 +602,7 @@ mod tests { ); ( - subtree_path, sorted_public_data_writes, sorted_public_data_writes_indexes, - low_public_data_writes_preimages, low_public_data_writes_witnesses, - pre_existing_public_data, + subtree_path, sorted_public_data_writes, sorted_public_data_writes_indexes, low_public_data_writes_preimages, low_public_data_writes_witnesses, pre_existing_public_data ) } @@ -686,7 +648,7 @@ mod tests { fn build_fee_payer_fee_juice_balance_read_hint( self, - start_public_data_tree: NonEmptyMerkleTree, + start_public_data_tree: NonEmptyMerkleTree ) -> PublicDataHint { self.fee_payer_fee_juice_balance_pre_existing_public_data_index.map_or( PublicDataHint::empty(), @@ -704,13 +666,13 @@ mod tests { membership_witness, leaf_preimage, } - }, + } ) } fn extract_subtree_sibling_path( path: [Field; FULL_HEIGHT], - mut sibling_path: [Field; SIBLING_PATH_LENGTH], + mut sibling_path: [Field; SIBLING_PATH_LENGTH] ) -> [Field; SIBLING_PATH_LENGTH] { let subtree_height = FULL_HEIGHT - SIBLING_PATH_LENGTH; for i in subtree_height..FULL_HEIGHT { @@ -723,17 +685,15 @@ mod tests { mut self, nullifier_tree: &mut NonEmptyMerkleTree, kernel_data: &mut KernelData, - start_nullifier_tree_snapshot: AppendOnlyTreeSnapshot, + start_nullifier_tree_snapshot: AppendOnlyTreeSnapshot ) -> ([NullifierLeafPreimage; MAX_NULLIFIERS_PER_TX], [MembershipWitness; MAX_NULLIFIERS_PER_TX], [Field; MAX_NULLIFIERS_PER_TX], [u32; MAX_NULLIFIERS_PER_TX]) { - let mut nullifier_predecessor_preimages = - [NullifierLeafPreimage::empty(); MAX_NULLIFIERS_PER_TX]; - let mut low_nullifier_membership_witness = - [MembershipWitness::empty(); MAX_NULLIFIERS_PER_TX]; + let mut nullifier_predecessor_preimages = [NullifierLeafPreimage::empty(); MAX_NULLIFIERS_PER_TX]; + let mut low_nullifier_membership_witness = [MembershipWitness::empty(); MAX_NULLIFIERS_PER_TX]; let sorted_new_nullifier_tuples = unsafe { get_sorted_tuple( self.nullifiers.storage.map(|insertion: NullifierInsertion| insertion.value), - |a, b| full_field_less_than(b, a), + |a, b| full_field_less_than(b, a) ) }; @@ -780,8 +740,7 @@ mod tests { } ( - nullifier_predecessor_preimages, low_nullifier_membership_witness, - sorted_nullifiers, sorted_nullifiers_indexes, + nullifier_predecessor_preimages, low_nullifier_membership_witness, sorted_nullifiers, sorted_nullifiers_indexes ) } @@ -792,66 +751,66 @@ mod tests { self.pre_existing_notes, [0; NOTE_HASH_TREE_HEIGHT], [0; NOTE_HASH_TREE_HEIGHT - NOTE_HASH_SUBTREE_HEIGHT], - [0; NOTE_HASH_SUBTREE_HEIGHT], + [0; NOTE_HASH_SUBTREE_HEIGHT] ); let start_note_hash_tree_snapshot = AppendOnlyTreeSnapshot { root: start_note_hash_tree.get_root(), - next_available_leaf_index: start_note_hash_tree.get_next_available_index() as u32, + next_available_leaf_index: start_note_hash_tree.get_next_available_index() as u32 }; let note_hash_subtree_sibling_path = BaseRollupInputsBuilder::extract_subtree_sibling_path( start_note_hash_tree.get_sibling_path(self.pre_existing_notes.len()), - [0; NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH], + [0; NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH] ); let mut start_nullifier_tree = NonEmptyMerkleTree::new( self.pre_existing_nullifiers.map(|preimage: NullifierLeafPreimage| preimage.hash()), [0; NULLIFIER_TREE_HEIGHT], [0; NULLIFIER_TREE_HEIGHT - NULLIFIER_SUBTREE_HEIGHT], - [0; NULLIFIER_SUBTREE_HEIGHT], + [0; NULLIFIER_SUBTREE_HEIGHT] ); let start_nullifier_tree_snapshot = AppendOnlyTreeSnapshot { root: start_nullifier_tree.get_root(), - next_available_leaf_index: start_nullifier_tree.get_next_available_index() as u32, + next_available_leaf_index: start_nullifier_tree.get_next_available_index() as u32 }; let mut start_public_data_tree = NonEmptyMerkleTree::new( - self.pre_existing_public_data.map(|preimage: PublicDataTreeLeafPreimage| { + self.pre_existing_public_data.map( + |preimage: PublicDataTreeLeafPreimage| { preimage.hash() - }), + } + ), [0; PUBLIC_DATA_TREE_HEIGHT], [0; PUBLIC_DATA_TREE_HEIGHT - PUBLIC_DATA_SUBTREE_HEIGHT], - [0; PUBLIC_DATA_SUBTREE_HEIGHT], + [0; PUBLIC_DATA_SUBTREE_HEIGHT] ); let start_public_data_tree_snapshot = AppendOnlyTreeSnapshot { root: start_public_data_tree.get_root(), - next_available_leaf_index: start_public_data_tree.get_next_available_index() as u32, + next_available_leaf_index: start_public_data_tree.get_next_available_index() as u32 }; - let fee_payer_fee_juice_balance_read_hint = - self.build_fee_payer_fee_juice_balance_read_hint(start_public_data_tree); + let fee_payer_fee_juice_balance_read_hint = self.build_fee_payer_fee_juice_balance_read_hint(start_public_data_tree); let start_archive = NonEmptyMerkleTree::new( self.pre_existing_blocks, [0; ARCHIVE_HEIGHT], [0; ARCHIVE_HEIGHT - 1], - [0; 1], + [0; 1] ); self.constants.last_archive = AppendOnlyTreeSnapshot { root: start_archive.get_root(), next_available_leaf_index: start_archive.get_next_available_index() as u32, }; - let (nullifier_predecessor_preimages, nullifier_predecessor_membership_witnesses, sorted_nullifiers, sorted_nullifier_indexes) = self - .update_nullifier_tree_with_new_leaves( - &mut start_nullifier_tree, - &mut kernel_data, - start_nullifier_tree_snapshot, - ); + let (nullifier_predecessor_preimages, nullifier_predecessor_membership_witnesses, sorted_nullifiers, sorted_nullifier_indexes) = self.update_nullifier_tree_with_new_leaves( + &mut start_nullifier_tree, + &mut kernel_data, + start_nullifier_tree_snapshot + ); let nullifier_subtree_sibling_path = BaseRollupInputsBuilder::extract_subtree_sibling_path( start_nullifier_tree.get_sibling_path(self.pre_existing_nullifiers.len()), - [0; NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH], + [0; NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH] ); let (public_data_sibling_path, sorted_public_data_writes, sorted_public_data_writes_indexes, low_public_data_writes_preimages, low_public_data_writes_witnesses, _new_subtree) = update_public_data_tree( @@ -861,13 +820,13 @@ mod tests { self.public_data_writes, self.protocol_public_data_writes, self.final_public_data_writes, - self.pre_existing_public_data, + self.pre_existing_public_data ); let start = PartialStateReference { note_hash_tree: start_note_hash_tree_snapshot, nullifier_tree: start_nullifier_tree_snapshot, - public_data_tree: start_public_data_tree_snapshot, + public_data_tree: start_public_data_tree_snapshot }; let state_diff_hints = StateDiffHints { @@ -877,7 +836,7 @@ mod tests { sorted_nullifier_indexes, note_hash_subtree_sibling_path, nullifier_subtree_sibling_path, - public_data_sibling_path, + public_data_sibling_path }; BaseRollupInputs { @@ -888,17 +847,16 @@ mod tests { sorted_public_data_writes_indexes, low_public_data_writes_preimages, low_public_data_writes_witnesses, - archive_root_membership_witness: MembershipWitness { - leaf_index: 0, - sibling_path: start_archive.get_sibling_path(0), - }, + archive_root_membership_witness: MembershipWitness { leaf_index: 0, sibling_path: start_archive.get_sibling_path(0) }, constants: self.constants, - fee_payer_fee_juice_balance_read_hint, + fee_payer_fee_juice_balance_read_hint } } fn execute(self) -> BaseOrMergeRollupPublicInputs { - let inputs = unsafe { self.build_inputs() }; + let inputs = unsafe { + self.build_inputs() + }; inputs.base_rollup_circuit() } @@ -918,20 +876,17 @@ mod tests { pre_existing_notes: [0; MAX_NOTE_HASHES_PER_TX], pre_existing_nullifiers: [NullifierLeafPreimage::empty(); MAX_NULLIFIERS_PER_TX], pre_existing_contracts: [0; 2], - pre_existing_public_data: [ - PublicDataTreeLeafPreimage::empty(); - MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX - ], - pre_existing_blocks: [0; 2], - public_data_reads: BoundedVec::new(), - public_data_writes: BoundedVec::new(), - protocol_public_data_writes: BoundedVec::new(), - final_public_data_writes: BoundedVec::new(), - nullifiers: BoundedVec::new(), - constants: ConstantRollupData::empty(), - fee_payer_fee_juice_balance_pre_existing_public_data_index: Option::none(), - } + pre_existing_public_data: [PublicDataTreeLeafPreimage::empty(); MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], + pre_existing_blocks: [0; 2], + public_data_reads: BoundedVec::new(), + public_data_writes: BoundedVec::new(), + protocol_public_data_writes: BoundedVec::new(), + final_public_data_writes: BoundedVec::new(), + nullifiers: BoundedVec::new(), + constants: ConstantRollupData::empty(), + fee_payer_fee_juice_balance_pre_existing_public_data_index: Option::none() } + } } #[test] @@ -946,14 +901,11 @@ mod tests { [0; MAX_NOTE_HASHES_PER_TX * 2], [0; NOTE_HASH_TREE_HEIGHT], [0; NOTE_HASH_TREE_HEIGHT - NOTE_HASH_SUBTREE_HEIGHT - 1], - [0; NOTE_HASH_SUBTREE_HEIGHT + 1], + [0; NOTE_HASH_SUBTREE_HEIGHT + 1] ); let outputs = builder.execute(); - let expected_start_note_hash_tree_snapshot = AppendOnlyTreeSnapshot { - root: expected_commitments_tree.get_root(), - next_available_leaf_index: MAX_NOTE_HASHES_PER_TX as u32, - }; + let expected_start_note_hash_tree_snapshot = AppendOnlyTreeSnapshot { root: expected_commitments_tree.get_root(), next_available_leaf_index: MAX_NOTE_HASHES_PER_TX as u32 }; assert(outputs.start.note_hash_tree.eq(expected_start_note_hash_tree_snapshot)); for i in 0..note_hashes.len() { @@ -961,7 +913,7 @@ mod tests { } let expected_end_note_hash_tree_snapshot = AppendOnlyTreeSnapshot { root: expected_commitments_tree.get_root(), - next_available_leaf_index: (MAX_NOTE_HASHES_PER_TX * 2) as u32, + next_available_leaf_index: (MAX_NOTE_HASHES_PER_TX * 2) as u32 }; assert(outputs.end.note_hash_tree.eq(expected_end_note_hash_tree_snapshot)); } @@ -1006,17 +958,16 @@ mod tests { tree_nullifiers.map(|preimage: NullifierLeafPreimage| preimage.hash()), [0; NULLIFIER_TREE_HEIGHT], [0; NULLIFIER_TREE_HEIGHT - NULLIFIER_SUBTREE_HEIGHT - 1], - [0; NULLIFIER_SUBTREE_HEIGHT + 1], + [0; NULLIFIER_SUBTREE_HEIGHT + 1] ); let output = builder.execute(); - assert(output.end.nullifier_tree.eq( - AppendOnlyTreeSnapshot { - root: end_nullifier_tree.get_root(), - next_available_leaf_index: 2 * MAX_NULLIFIERS_PER_TX as u32, - }, - )); + assert( + output.end.nullifier_tree.eq( + AppendOnlyTreeSnapshot { root: end_nullifier_tree.get_root(), next_available_leaf_index: 2 * MAX_NULLIFIERS_PER_TX as u32 } + ) + ); } #[test] @@ -1030,9 +981,7 @@ mod tests { builder.nullifiers.push(NullifierInsertion { existing_index: 1, value: 8 }); for i in 1..builder.nullifiers.max_len() { - builder.nullifiers.push( - NullifierInsertion { existing_index: 1, value: (8 + i) as Field }, - ); + builder.nullifiers.push(NullifierInsertion { existing_index: 1, value: (8 + i) as Field }); } let output = builder.execute(); @@ -1063,15 +1012,14 @@ mod tests { tree_nullifiers.map(|preimage: NullifierLeafPreimage| preimage.hash()), [0; NULLIFIER_TREE_HEIGHT], [0; NULLIFIER_TREE_HEIGHT - NULLIFIER_SUBTREE_HEIGHT - 1], - [0; NULLIFIER_SUBTREE_HEIGHT + 1], + [0; NULLIFIER_SUBTREE_HEIGHT + 1] ); - assert(output.end.nullifier_tree.eq( - AppendOnlyTreeSnapshot { - root: end_nullifier_tree.get_root(), - next_available_leaf_index: 2 * MAX_NULLIFIERS_PER_TX as u32, - }, - )); + assert( + output.end.nullifier_tree.eq( + AppendOnlyTreeSnapshot { root: end_nullifier_tree.get_root(), next_available_leaf_index: 2 * MAX_NULLIFIERS_PER_TX as u32 } + ) + ); } #[test(should_fail_with = "Invalid low leaf")] @@ -1125,10 +1073,7 @@ mod tests { let mut builder = BaseRollupInputsBuilder::new(); for i in 0..MAX_L2_TO_L1_MSGS_PER_TX { - builder.kernel_data.add_exposed_l2_to_l1_message( - i as Field, - EthAddress::from_field(1 + i as Field), - ); + builder.kernel_data.add_exposed_l2_to_l1_message(i as Field, EthAddress::from_field(1 + i as Field)); } let out_hash = builder.execute().out_hash; @@ -1137,13 +1082,11 @@ mod tests { l2_to_l1_message, builder.constants.global_variables.version, builder.constants.global_variables.chain_id, - ), + ) ); // Since we fill the tree completely, we know to expect a full tree as below - let expected_tree = dep::types::merkle_tree::variable_merkle_tree::tests::generate_full_sha_tree( - siloed_l2_to_l1_msgs.storage, - ); + let expected_tree = dep::types::merkle_tree::variable_merkle_tree::tests::generate_full_sha_tree(siloed_l2_to_l1_msgs.storage); assert_eq(out_hash, expected_tree.get_root()); } @@ -1224,14 +1167,13 @@ mod tests { builder.public_data_writes.push((0, PublicDataTreeLeaf { slot: 27, value: 29 })); let outputs = builder.execute(); - let updated_leaf = - PublicDataTreeLeafPreimage { slot: 27, value: 29, next_slot: 0, next_index: 0 }; + let updated_leaf = PublicDataTreeLeafPreimage { slot: 27, value: 29, next_slot: 0, next_index: 0 }; let mut expected_public_data_tree = NonEmptyMerkleTree::new( [updated_leaf.hash(), 0], [0; PUBLIC_DATA_TREE_HEIGHT], [0; PUBLIC_DATA_TREE_HEIGHT - 1], - [0; 1], + [0; 1] ); assert_eq(outputs.end.public_data_tree.root, expected_public_data_tree.get_root()); @@ -1277,7 +1219,7 @@ mod tests { public_data_leaves, [0; PUBLIC_DATA_TREE_HEIGHT], [0; PUBLIC_DATA_TREE_HEIGHT - PUBLIC_DATA_SUBTREE_HEIGHT - 1], - [0; PUBLIC_DATA_SUBTREE_HEIGHT + 1], + [0; PUBLIC_DATA_SUBTREE_HEIGHT + 1] ); assert_eq(outputs.end.public_data_tree.root, expected_public_data_tree.get_root()); @@ -1309,24 +1251,17 @@ mod tests { builder.kernel_data.tx_context.gas_settings.inclusion_fee = tx_fee; // Set expected protocol data update - builder.protocol_public_data_writes.push(( - 0, PublicDataTreeLeaf { slot: balance_slot, value: expected_balance }, - )); + builder.protocol_public_data_writes.push((0, PublicDataTreeLeaf { slot: balance_slot, value: expected_balance })); let outputs = builder.execute(); // The new public data tree should have updated the balance of the fee payer - let updated_leaf = PublicDataTreeLeafPreimage { - slot: balance_slot, - value: expected_balance, - next_slot: 0, - next_index: 0, - }; + let updated_leaf = PublicDataTreeLeafPreimage { slot: balance_slot, value: expected_balance, next_slot: 0, next_index: 0 }; let mut expected_public_data_tree = NonEmptyMerkleTree::new( [updated_leaf.hash(), 0], [0; PUBLIC_DATA_TREE_HEIGHT], [0; PUBLIC_DATA_TREE_HEIGHT - 1], - [0; 1], + [0; 1] ); assert_eq(outputs.end.public_data_tree.root, expected_public_data_tree.get_root()); @@ -1358,30 +1293,21 @@ mod tests { builder.kernel_data.tx_context.gas_settings.inclusion_fee = tx_fee; // Create an existing data update that corresponds to a claim - builder.public_data_writes.push(( - 0, PublicDataTreeLeaf { slot: balance_slot, value: after_claim_balance }, - )); + builder.public_data_writes.push((0, PublicDataTreeLeaf { slot: balance_slot, value: after_claim_balance })); // Set expected data updates after base rollup runs // Note that we tweak the final_public_data_writes directly, since we need to overwrite the output of the user public_data_writes - builder.final_public_data_writes.push(( - 0, PublicDataTreeLeaf { slot: balance_slot, value: expected_balance }, - )); + builder.final_public_data_writes.push((0, PublicDataTreeLeaf { slot: balance_slot, value: expected_balance })); let outputs = builder.execute(); // The new public data tree should have updated the balance of the fee payer - let updated_leaf = PublicDataTreeLeafPreimage { - slot: balance_slot, - value: expected_balance, - next_slot: 0, - next_index: 0, - }; + let updated_leaf = PublicDataTreeLeafPreimage { slot: balance_slot, value: expected_balance, next_slot: 0, next_index: 0 }; let mut expected_public_data_tree = NonEmptyMerkleTree::new( [updated_leaf.hash(), 0], [0; PUBLIC_DATA_TREE_HEIGHT], [0; PUBLIC_DATA_TREE_HEIGHT - 1], - [0; 1], + [0; 1] ); assert_eq(outputs.end.public_data_tree.root, expected_public_data_tree.get_root()); @@ -1413,9 +1339,7 @@ mod tests { builder.kernel_data.tx_context.gas_settings.inclusion_fee = tx_fee; // Set expected protocol data update - builder.protocol_public_data_writes.push(( - 0, PublicDataTreeLeaf { slot: balance_slot, value: -90_000 }, - )); + builder.protocol_public_data_writes.push((0, PublicDataTreeLeaf { slot: balance_slot, value: -90_000 })); builder.fails(); } @@ -1455,9 +1379,7 @@ mod tests { builder.kernel_data.tx_context.gas_settings.inclusion_fee = tx_fee; // Set expected protocol data update - builder.protocol_public_data_writes.push(( - 0, PublicDataTreeLeaf { slot: balance_slot, value: expected_balance }, - )); + builder.protocol_public_data_writes.push((0, PublicDataTreeLeaf { slot: balance_slot, value: expected_balance })); builder.fails(); } @@ -1473,15 +1395,18 @@ mod tests { #[test] fn valid_previous_kernel_tube() { - let builder = unsafe { BaseRollupInputsBuilder::new_with_previous_kernel(TUBE_INDEX) }; + let builder = unsafe { + BaseRollupInputsBuilder::new_with_previous_kernel(TUBE_INDEX) + }; let _res = builder.execute(); } #[test] fn valid_previous_kernel_public_tail() { - let builder = - unsafe { BaseRollupInputsBuilder::new_with_previous_kernel(PUBLIC_KERNEL_TAIL_INDEX) }; + let builder = unsafe { + BaseRollupInputsBuilder::new_with_previous_kernel(PUBLIC_KERNEL_TAIL_INDEX) + }; let _res = builder.execute(); } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/state_diff_hints.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/state_diff_hints.nr index 00bcc9e0986..d27a8081f44 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/state_diff_hints.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/state_diff_hints.nr @@ -1,10 +1,10 @@ use dep::types::{ abis::nullifier_leaf_preimage::NullifierLeafPreimage, constants::{ - MAX_NULLIFIERS_PER_TX, NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, - NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, - NULLIFIER_TREE_HEIGHT, - }, merkle_tree::MembershipWitness, + MAX_NULLIFIERS_PER_TX, NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, + PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_TREE_HEIGHT +}, + merkle_tree::MembershipWitness }; pub struct StateDiffHints { diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_merge/block_merge_rollup_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_merge/block_merge_rollup_inputs.nr index 66f52d9e0b1..7f9da74857d 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_merge/block_merge_rollup_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_merge/block_merge_rollup_inputs.nr @@ -55,7 +55,7 @@ impl BlockMergeRollupInputs { fees, vk_tree_root: left.vk_tree_root, protocol_contract_tree_root: left.protocol_contract_tree_root, - prover_id: left.prover_id, // TODO(#7346): Temporarily added prover_id while we verify block-root proofs on L1 + prover_id: left.prover_id // TODO(#7346): Temporarily added prover_id while we verify block-root proofs on L1 } } } @@ -63,9 +63,7 @@ impl BlockMergeRollupInputs { mod tests { use crate::tests::block_merge_rollup_inputs::default_block_merge_rollup_inputs; use dep::types::hash::accumulate_sha256; - use dep::types::constants::{ - BLOCK_ROOT_ROLLUP_INDEX, BLOCK_MERGE_ROLLUP_INDEX, ROOT_PARITY_INDEX, - }; + use dep::types::constants::{BLOCK_ROOT_ROLLUP_INDEX, BLOCK_MERGE_ROLLUP_INDEX, ROOT_PARITY_INDEX}; use types::merkle_tree::merkle_tree::MerkleTree; use dep::types::tests::fixtures; @@ -137,20 +135,19 @@ mod tests { // inputs.previous_rollup_data[0].block_root_or_block_merge_public_inputs.fees[0].recipient = EthAddress::from_field(2); // let outputs = inputs.block_merge_rollup_circuit(); assert_eq( - outputs.fees[0], - inputs.previous_rollup_data[0].block_root_or_block_merge_public_inputs.fees[0], + outputs.fees[0], inputs.previous_rollup_data[0].block_root_or_block_merge_public_inputs.fees[0] ); assert_eq( - outputs.fees[1], - inputs.previous_rollup_data[1].block_root_or_block_merge_public_inputs.fees[0], + outputs.fees[1], inputs.previous_rollup_data[1].block_root_or_block_merge_public_inputs.fees[0] ); } #[test] fn valid_previous_circuit_block_root() { let mut inputs = default_block_merge_rollup_inputs(); - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; inputs.previous_rollup_data[0].vk = fixtures::vk_tree::generate_fake_honk_vk_for_index(BLOCK_ROOT_ROLLUP_INDEX); inputs.previous_rollup_data[0].vk_witness.leaf_index = BLOCK_ROOT_ROLLUP_INDEX as Field; @@ -162,8 +159,9 @@ mod tests { #[test] fn valid_previous_circuit_block_merge() { let mut inputs = default_block_merge_rollup_inputs(); - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; inputs.previous_rollup_data[0].vk = fixtures::vk_tree::generate_fake_honk_vk_for_index(BLOCK_MERGE_ROLLUP_INDEX); inputs.previous_rollup_data[0].vk_witness.leaf_index = BLOCK_MERGE_ROLLUP_INDEX as Field; @@ -175,8 +173,9 @@ mod tests { #[test(should_fail_with = "Invalid vk index")] fn invalid_previous_circuit() { let mut inputs = default_block_merge_rollup_inputs(); - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; inputs.previous_rollup_data[0].vk = fixtures::vk_tree::generate_fake_honk_vk_for_index(ROOT_PARITY_INDEX); inputs.previous_rollup_data[0].vk_witness.leaf_index = ROOT_PARITY_INDEX as Field; diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/block_root_rollup_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/block_root_rollup_inputs.nr index 0b0ee32a8ee..2f8b23a6ec3 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/block_root_rollup_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/block_root_rollup_inputs.nr @@ -1,19 +1,20 @@ use crate::{ abis::{ - previous_rollup_data::PreviousRollupData, - block_root_or_block_merge_public_inputs::{BlockRootOrBlockMergePublicInputs, FeeRecipient}, - }, components, + previous_rollup_data::PreviousRollupData, + block_root_or_block_merge_public_inputs::{BlockRootOrBlockMergePublicInputs, FeeRecipient} +}, + components }; use parity_lib::root::root_rollup_parity_input::RootRollupParityInput; use types::{ abis::append_only_tree_snapshot::AppendOnlyTreeSnapshot, constants::{ - AZTEC_EPOCH_DURATION, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, L1_TO_L2_MSG_SUBTREE_HEIGHT, - L1_TO_L2_MSG_SUBTREE_SIBLING_PATH_LENGTH, ARCHIVE_HEIGHT, BASE_ROLLUP_INDEX, - MERGE_ROLLUP_INDEX, - }, header::Header, content_commitment::ContentCommitment, + AZTEC_EPOCH_DURATION, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, L1_TO_L2_MSG_SUBTREE_HEIGHT, + L1_TO_L2_MSG_SUBTREE_SIBLING_PATH_LENGTH, ARCHIVE_HEIGHT, BASE_ROLLUP_INDEX, MERGE_ROLLUP_INDEX +}, + header::Header, content_commitment::ContentCommitment, merkle_tree::{append_only_tree, calculate_empty_tree_root}, state_reference::StateReference, - traits::Empty, + traits::Empty }; use types::debug_log::debug_log_format; @@ -74,19 +75,16 @@ impl BlockRootRollupInputs { self.l1_to_l2_roots.public_inputs.converted_root, // TODO(Kev): For now we can add a test that this fits inside of // a u8. - L1_TO_L2_MSG_SUBTREE_HEIGHT as u8, + L1_TO_L2_MSG_SUBTREE_HEIGHT as u8 ); - let state = StateReference { - l1_to_l2_message_tree: new_l1_to_l2_message_tree_snapshot, - partial: right.end, - }; + let state = StateReference { l1_to_l2_message_tree: new_l1_to_l2_message_tree_snapshot, partial: right.end }; let content_commitment = ContentCommitment { num_txs: (left.num_txs + right.num_txs) as Field, txs_effects_hash: components::compute_txs_effects_hash(self.previous_rollup_data), in_hash: self.l1_to_l2_roots.public_inputs.sha_root, - out_hash: components::compute_out_hash(self.previous_rollup_data), + out_hash: components::compute_out_hash(self.previous_rollup_data) }; let total_fees = components::accumulate_fees(left, right); @@ -113,7 +111,7 @@ impl BlockRootRollupInputs { content_commitment, state, global_variables: left.constants.global_variables, - total_fees, + total_fees }; // Build the block hash for this by hashing the header and then insert the new leaf to archive tree. @@ -125,7 +123,7 @@ impl BlockRootRollupInputs { self.new_archive_sibling_path, 0, block_hash, - 0, + 0 ); let mut fee_arr = [FeeRecipient::empty(); AZTEC_EPOCH_DURATION]; @@ -143,7 +141,7 @@ impl BlockRootRollupInputs { fees: fee_arr, vk_tree_root: left.constants.vk_tree_root, protocol_contract_tree_root: left.constants.protocol_contract_tree_root, - prover_id: self.prover_id, + prover_id: self.prover_id } } } @@ -159,7 +157,7 @@ impl Empty for BlockRootRollupInputs { start_archive_snapshot: AppendOnlyTreeSnapshot::zero(), new_archive_sibling_path: [0; ARCHIVE_HEIGHT], previous_block_hash: 0, - prover_id: 0, + prover_id: 0 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/empty_block_root_rollup_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/empty_block_root_rollup_inputs.nr index 7d431741163..bdfb8896996 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/empty_block_root_rollup_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/empty_block_root_rollup_inputs.nr @@ -1,7 +1,5 @@ use crate::abis::block_root_or_block_merge_public_inputs::BlockRootOrBlockMergePublicInputs; -use types::abis::{ - append_only_tree_snapshot::AppendOnlyTreeSnapshot, global_variables::GlobalVariables, -}; +use types::abis::{append_only_tree_snapshot::AppendOnlyTreeSnapshot, global_variables::GlobalVariables}; use types::constants::AZTEC_EPOCH_DURATION; use crate::abis::block_root_or_block_merge_public_inputs::FeeRecipient; @@ -28,7 +26,7 @@ impl EmptyBlockRootRollupInputs { fees: [FeeRecipient::empty(); AZTEC_EPOCH_DURATION], vk_tree_root: self.vk_tree_root, protocol_contract_tree_root: self.protocol_contract_tree_root, - prover_id: self.prover_id, + prover_id: self.prover_id } } } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/mod.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/mod.nr index 51065ad968c..2c66ed17d6a 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/block_root/mod.nr @@ -26,17 +26,11 @@ mod tests { let inputs = default_block_root_rollup_inputs(); let outputs = inputs.block_root_rollup_circuit(); - assert(outputs.previous_archive.eq( - inputs.previous_rollup_data[0] - .base_or_merge_rollup_public_inputs - .constants - .last_archive, - )); - assert(outputs.start_global_variables.eq( - inputs.previous_rollup_data[1] - .base_or_merge_rollup_public_inputs - .constants - .global_variables, - )); + assert( + outputs.previous_archive.eq(inputs.previous_rollup_data[0].base_or_merge_rollup_public_inputs.constants.last_archive) + ); + assert( + outputs.start_global_variables.eq(inputs.previous_rollup_data[1].base_or_merge_rollup_public_inputs.constants.global_variables) + ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/components.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/components.nr index b25f9fef8bc..cea9980f60f 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/components.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/components.nr @@ -1,24 +1,23 @@ use crate::abis::{ base_or_merge_rollup_public_inputs::BaseOrMergeRollupPublicInputs, - block_root_or_block_merge_public_inputs::{BlockRootOrBlockMergePublicInputs, FeeRecipient}, -}; -use crate::abis::{ - previous_rollup_data::PreviousRollupData, previous_rollup_block_data::PreviousRollupBlockData, + block_root_or_block_merge_public_inputs::{BlockRootOrBlockMergePublicInputs, FeeRecipient} }; +use crate::abis::{previous_rollup_data::PreviousRollupData, previous_rollup_block_data::PreviousRollupBlockData}; use dep::types::{ hash::{ - accumulate_sha256, silo_unencrypted_log_hash, compute_tx_logs_hash, silo_encrypted_log_hash, - compute_tx_note_logs_hash, - }, merkle_tree::VariableMerkleTree, + accumulate_sha256, silo_unencrypted_log_hash, compute_tx_logs_hash, silo_encrypted_log_hash, + compute_tx_note_logs_hash +}, + merkle_tree::VariableMerkleTree, constants::{ - AZTEC_EPOCH_DURATION, MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, - MAX_L2_TO_L1_MSGS_PER_TX, MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - MAX_UNENCRYPTED_LOGS_PER_TX, - }, utils::arrays::{array_length, array_merge}, + AZTEC_EPOCH_DURATION, MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, + MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_UNENCRYPTED_LOGS_PER_TX +}, + utils::arrays::{array_length, array_merge}, abis::{ - accumulated_data::CombinedAccumulatedData, - public_data_update_request::PublicDataUpdateRequest, log_hash::{LogHash, ScopedLogHash}, - }, + accumulated_data::CombinedAccumulatedData, public_data_update_request::PublicDataUpdateRequest, + log_hash::{LogHash, ScopedLogHash} +} }; /** @@ -27,7 +26,7 @@ use dep::types::{ */ pub fn assert_txs_filled_from_left( left: BaseOrMergeRollupPublicInputs, - right: BaseOrMergeRollupPublicInputs, + right: BaseOrMergeRollupPublicInputs ) { // assert that the left rollup is either a base (1 tx) or a balanced tree (num txs = power of 2) if (left.rollup_type == 1) { @@ -35,17 +34,14 @@ pub fn assert_txs_filled_from_left( let right_txs = right.num_txs; // See https://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 assert( - (left_txs) & (left_txs - 1) == 0, - "The rollup should be filled greedily from L to R, but received an unbalanced left subtree", + (left_txs) & (left_txs - 1) == 0, "The rollup should be filled greedily from L to R, but received an unbalanced left subtree" ); assert( - right_txs <= left_txs, - "The rollup should be filled greedily from L to R, but received a L txs < R txs", + right_txs <= left_txs, "The rollup should be filled greedily from L to R, but received a L txs < R txs" ); } else { assert( - right.rollup_type == 0, - "The rollup should be filled greedily from L to R, but received a L base and R merge", + right.rollup_type == 0, "The rollup should be filled greedily from L to R, but received a L base and R merge" ); } } @@ -56,7 +52,7 @@ pub fn assert_txs_filled_from_left( */ pub fn assert_equal_constants( left: BaseOrMergeRollupPublicInputs, - right: BaseOrMergeRollupPublicInputs, + right: BaseOrMergeRollupPublicInputs ) { assert(left.constants.eq(right.constants), "input proofs have different constants"); } @@ -65,86 +61,70 @@ pub fn assert_equal_constants( // follow on from one-another). Ensures that right uses the tres that was updated by left. pub fn assert_prev_rollups_follow_on_from_each_other( left: BaseOrMergeRollupPublicInputs, - right: BaseOrMergeRollupPublicInputs, + right: BaseOrMergeRollupPublicInputs ) { assert( - left.end.note_hash_tree.eq(right.start.note_hash_tree), - "input proofs have different note hash tree snapshots", + left.end.note_hash_tree.eq(right.start.note_hash_tree), "input proofs have different note hash tree snapshots" ); assert( - left.end.nullifier_tree.eq(right.start.nullifier_tree), - "input proofs have different nullifier tree snapshots", + left.end.nullifier_tree.eq(right.start.nullifier_tree), "input proofs have different nullifier tree snapshots" ); assert( - left.end.public_data_tree.eq(right.start.public_data_tree), - "input proofs have different public data tree snapshots", + left.end.public_data_tree.eq(right.start.public_data_tree), "input proofs have different public data tree snapshots" ); } // TODO(Miranda): split out? pub fn assert_prev_block_rollups_follow_on_from_each_other( left: BlockRootOrBlockMergePublicInputs, - right: BlockRootOrBlockMergePublicInputs, + right: BlockRootOrBlockMergePublicInputs ) { assert(left.vk_tree_root == right.vk_tree_root, "input blocks have different vk tree roots"); assert( - left.protocol_contract_tree_root == right.protocol_contract_tree_root, - "input blocks have different protocol contract tree roots", + left.protocol_contract_tree_root == right.protocol_contract_tree_root, "input blocks have different protocol contract tree roots" ); assert( - left.new_archive.eq(right.previous_archive), - "input blocks have different archive tree snapshots", + left.new_archive.eq(right.previous_archive), "input blocks have different archive tree snapshots" ); assert( - left.end_block_hash.eq(right.previous_block_hash), - "input block hashes do not follow on from each other", + left.end_block_hash.eq(right.previous_block_hash), "input block hashes do not follow on from each other" ); assert( - left.end_global_variables.chain_id == right.start_global_variables.chain_id, - "input blocks have different chain id", + left.end_global_variables.chain_id == right.start_global_variables.chain_id, "input blocks have different chain id" ); assert( - left.end_global_variables.version == right.start_global_variables.version, - "input blocks have different chain version", + left.end_global_variables.version == right.start_global_variables.version, "input blocks have different chain version" ); if right.is_padding() { assert( - left.end_global_variables.block_number == right.start_global_variables.block_number, - "input block numbers do not match", + left.end_global_variables.block_number == right.start_global_variables.block_number, "input block numbers do not match" ); assert( - left.end_global_variables.timestamp == right.start_global_variables.timestamp, - "input block timestamps do not match", + left.end_global_variables.timestamp == right.start_global_variables.timestamp, "input block timestamps do not match" ); } else { assert( - left.end_global_variables.block_number + 1 == right.start_global_variables.block_number, - "input block numbers do not follow on from each other", + left.end_global_variables.block_number + 1 == right.start_global_variables.block_number, "input block numbers do not follow on from each other" ); assert( - left.end_global_variables.timestamp < right.start_global_variables.timestamp, - "input block timestamps do not follow on from each other", + left.end_global_variables.timestamp < right.start_global_variables.timestamp, "input block timestamps do not follow on from each other" ); } } -pub fn accumulate_fees( - left: BaseOrMergeRollupPublicInputs, - right: BaseOrMergeRollupPublicInputs, -) -> Field { +pub fn accumulate_fees(left: BaseOrMergeRollupPublicInputs, right: BaseOrMergeRollupPublicInputs) -> Field { left.accumulated_fees + right.accumulated_fees } pub fn accumulate_blocks_fees( left: BlockRootOrBlockMergePublicInputs, - right: BlockRootOrBlockMergePublicInputs, + right: BlockRootOrBlockMergePublicInputs ) -> [FeeRecipient; AZTEC_EPOCH_DURATION] { let left_len = array_length(left.fees); let right_len = array_length(right.fees); assert( - left_len + right_len <= AZTEC_EPOCH_DURATION, - "too many fee payment structs accumulated in rollup", + left_len + right_len <= AZTEC_EPOCH_DURATION, "too many fee payment structs accumulated in rollup" ); // TODO(Miranda): combine fees with same recipient depending on rollup structure // Assuming that the final rollup tree (block root -> block merge -> root) has max 32 leaves (TODO: constrain in root), then @@ -160,20 +140,24 @@ pub fn accumulate_blocks_fees( * @return out hash stored in 2 fields */ pub fn compute_out_hash(previous_rollup_data: [PreviousRollupData; 2]) -> Field { - accumulate_sha256([ + accumulate_sha256( + [ previous_rollup_data[0].base_or_merge_rollup_public_inputs.out_hash, - previous_rollup_data[1].base_or_merge_rollup_public_inputs.out_hash, - ]) + previous_rollup_data[1].base_or_merge_rollup_public_inputs.out_hash + ] + ) } // TODO(Miranda): combine fns? pub fn compute_blocks_out_hash(previous_rollup_data: [PreviousRollupBlockData; 2]) -> Field { if previous_rollup_data[1].block_root_or_block_merge_public_inputs.is_padding() { previous_rollup_data[0].block_root_or_block_merge_public_inputs.out_hash } else { - accumulate_sha256([ + accumulate_sha256( + [ previous_rollup_data[0].block_root_or_block_merge_public_inputs.out_hash, - previous_rollup_data[1].block_root_or_block_merge_public_inputs.out_hash, - ]) + previous_rollup_data[1].block_root_or_block_merge_public_inputs.out_hash + ] + ) } } @@ -190,35 +174,37 @@ pub fn compute_kernel_out_hash(l2_to_l1_msgs: [Field; MAX_L2_TO_L1_MSGS_PER_TX]) * @return The hash of the transaction effects stored in 2 fields */ pub fn compute_txs_effects_hash(previous_rollup_data: [PreviousRollupData; 2]) -> Field { - accumulate_sha256([ + accumulate_sha256( + [ previous_rollup_data[0].base_or_merge_rollup_public_inputs.txs_effects_hash, - previous_rollup_data[1].base_or_merge_rollup_public_inputs.txs_effects_hash, - ]) + previous_rollup_data[1].base_or_merge_rollup_public_inputs.txs_effects_hash + ] + ) } -fn silo_and_hash_unencrypted_logs( - unencrypted_logs_hashes: [ScopedLogHash; MAX_UNENCRYPTED_LOGS_PER_TX], -) -> Field { - let siloed_logs = unencrypted_logs_hashes.map(|log: ScopedLogHash| { +fn silo_and_hash_unencrypted_logs(unencrypted_logs_hashes: [ScopedLogHash; MAX_UNENCRYPTED_LOGS_PER_TX]) -> Field { + let siloed_logs = unencrypted_logs_hashes.map( + |log: ScopedLogHash| { LogHash { value: silo_unencrypted_log_hash(log), counter: log.log_hash.counter, length: log.log_hash.length, } - }); + } + ); compute_tx_logs_hash(siloed_logs) } -fn silo_and_hash_encrypted_logs( - encrypted_logs_hashes: [ScopedLogHash; MAX_UNENCRYPTED_LOGS_PER_TX], -) -> Field { - let siloed_encrypted_logs = encrypted_logs_hashes.map(|log: ScopedLogHash| { +fn silo_and_hash_encrypted_logs(encrypted_logs_hashes: [ScopedLogHash; MAX_UNENCRYPTED_LOGS_PER_TX]) -> Field { + let siloed_encrypted_logs = encrypted_logs_hashes.map( + |log: ScopedLogHash| { LogHash { value: silo_encrypted_log_hash(log), counter: log.log_hash.counter, length: log.log_hash.length, } - }); + } + ); compute_tx_logs_hash(siloed_encrypted_logs) } @@ -252,7 +238,7 @@ pub fn compute_tx_effects_hash( revert_code: u8, transaction_fee: Field, all_public_data_update_requests: [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], - out_hash: Field, + out_hash: Field ) -> Field { let mut tx_effects_hash_input = [0; TX_EFFECTS_HASH_INPUT_FIELDS]; @@ -261,8 +247,7 @@ pub fn compute_tx_effects_hash( // Public writes are the concatenation of all non-empty user update requests and protocol update requests, then padded with zeroes. // The incoming all_public_data_update_requests may have empty update requests in the middle, so we move those to the end of the array. - let public_data_update_requests = - get_all_update_requests_for_tx_effects(all_public_data_update_requests); + let public_data_update_requests = get_all_update_requests_for_tx_effects(all_public_data_update_requests); let note_logs_length = combined.note_encrypted_log_preimages_length; let encrypted_logs_length = combined.encrypted_log_preimages_length; let unencrypted_logs_length = combined.unencrypted_log_preimages_length; @@ -342,11 +327,8 @@ pub fn compute_tx_effects_hash( sha_digest } -fn get_all_update_requests_for_tx_effects( - all_public_data_update_requests: [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], -) -> [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX] { - let mut all_update_requests: BoundedVec = - BoundedVec::new(); +fn get_all_update_requests_for_tx_effects(all_public_data_update_requests: [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX]) -> [PublicDataUpdateRequest; MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX] { + let mut all_update_requests: BoundedVec = BoundedVec::new(); for update_request in all_public_data_update_requests { if !update_request.is_empty() { all_update_requests.push(update_request); @@ -365,8 +347,5 @@ fn consistent_TX_EFFECTS_HASH_INPUT_FIELDS() { + 1 // out hash + 3 // logs lengths + 3; // logs hashes - assert( - TX_EFFECTS_HASH_INPUT_FIELDS == expected_size, - "tx effects hash input size is incorrect", - ); + assert(TX_EFFECTS_HASH_INPUT_FIELDS == expected_size, "tx effects hash input size is incorrect"); } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/merge/merge_rollup_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/merge/merge_rollup_inputs.nr index fdcc1ce5d1a..f5468715062 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/merge/merge_rollup_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/merge/merge_rollup_inputs.nr @@ -1,8 +1,6 @@ use dep::types::{traits::Empty, constants::{BASE_ROLLUP_INDEX, MERGE_ROLLUP_INDEX}}; use crate::abis::previous_rollup_data::PreviousRollupData; -use crate::abis::base_or_merge_rollup_public_inputs::{ - BaseOrMergeRollupPublicInputs, MERGE_ROLLUP_TYPE, -}; +use crate::abis::base_or_merge_rollup_public_inputs::{BaseOrMergeRollupPublicInputs, MERGE_ROLLUP_TYPE}; use crate::components; global ALLOWED_PREVIOUS_CIRCUITS = [BASE_ROLLUP_INDEX, MERGE_ROLLUP_INDEX]; @@ -52,7 +50,7 @@ impl MergeRollupInputs { end: right.end, txs_effects_hash, out_hash, - accumulated_fees, + accumulated_fees }; public_inputs @@ -154,9 +152,7 @@ mod tests { let mut inputs = default_merge_rollup_inputs(); let outputs = inputs.merge_rollup_circuit(); - assert(outputs.start.eq( - inputs.previous_rollup_data[0].base_or_merge_rollup_public_inputs.start, - )); + assert(outputs.start.eq(inputs.previous_rollup_data[0].base_or_merge_rollup_public_inputs.start)); assert(outputs.end.eq(inputs.previous_rollup_data[1].base_or_merge_rollup_public_inputs.end)); } @@ -174,20 +170,21 @@ mod tests { let mut inputs = default_merge_rollup_inputs(); let outputs = inputs.merge_rollup_circuit(); - assert(inputs.previous_rollup_data[0].base_or_merge_rollup_public_inputs.constants.eq( - outputs.constants, - )); - assert(inputs.previous_rollup_data[1].base_or_merge_rollup_public_inputs.constants.eq( - outputs.constants, - )); + assert( + inputs.previous_rollup_data[0].base_or_merge_rollup_public_inputs.constants.eq(outputs.constants) + ); + assert( + inputs.previous_rollup_data[1].base_or_merge_rollup_public_inputs.constants.eq(outputs.constants) + ); } #[test] fn valid_previous_circuit_base() { let mut inputs = default_merge_rollup_inputs(); - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; inputs.previous_rollup_data[0].vk = fixtures::vk_tree::generate_fake_honk_vk_for_index(BASE_ROLLUP_INDEX); @@ -202,8 +199,9 @@ mod tests { fn valid_previous_circuit_merge() { let mut inputs = default_merge_rollup_inputs(); - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; inputs.previous_rollup_data[0].vk = fixtures::vk_tree::generate_fake_honk_vk_for_index(MERGE_ROLLUP_INDEX); @@ -217,8 +215,9 @@ mod tests { #[test(should_fail_with = "Invalid vk index")] fn invalid_previous_circuit() { let mut inputs = default_merge_rollup_inputs(); - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; inputs.previous_rollup_data[0].vk = fixtures::vk_tree::generate_fake_honk_vk_for_index(ROOT_PARITY_INDEX); inputs.previous_rollup_data[0].vk_witness.leaf_index = ROOT_PARITY_INDEX as Field; diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/root/mod.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/root/mod.nr index acc9b715235..da358b0841e 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/root/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/root/mod.nr @@ -25,25 +25,22 @@ mod tests { let inputs = default_root_rollup_inputs(); let outputs = inputs.root_rollup_circuit(); - assert(outputs.previous_archive.eq( - inputs.previous_rollup_data[0] - .block_root_or_block_merge_public_inputs - .previous_archive, - )); - - assert(outputs.end_archive.eq( - inputs.previous_rollup_data[1].block_root_or_block_merge_public_inputs.new_archive, - )); - - assert(outputs.end_timestamp.eq( - inputs.previous_rollup_data[1] - .block_root_or_block_merge_public_inputs - .end_global_variables - .timestamp, - )); - - assert(outputs.end_block_hash.eq( - inputs.previous_rollup_data[1].block_root_or_block_merge_public_inputs.end_block_hash, - )); + assert( + outputs.previous_archive.eq(inputs.previous_rollup_data[0].block_root_or_block_merge_public_inputs.previous_archive) + ); + + assert( + outputs.end_archive.eq(inputs.previous_rollup_data[1].block_root_or_block_merge_public_inputs.new_archive) + ); + + assert( + outputs.end_timestamp.eq( + inputs.previous_rollup_data[1].block_root_or_block_merge_public_inputs.end_global_variables.timestamp + ) + ); + + assert( + outputs.end_block_hash.eq(inputs.previous_rollup_data[1].block_root_or_block_merge_public_inputs.end_block_hash) + ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/root/root_rollup_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/root/root_rollup_inputs.nr index 5711b1bb5ed..69a603ff753 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/root/root_rollup_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/root/root_rollup_inputs.nr @@ -1,10 +1,10 @@ use crate::{ abis::previous_rollup_block_data::PreviousRollupBlockData, components, - root::root_rollup_public_inputs::RootRollupPublicInputs, + root::root_rollup_public_inputs::RootRollupPublicInputs }; use types::{ traits::Empty, - constants::{BLOCK_ROOT_ROLLUP_INDEX, BLOCK_MERGE_ROLLUP_INDEX, BLOCK_ROOT_ROLLUP_EMPTY_INDEX}, + constants::{BLOCK_ROOT_ROLLUP_INDEX, BLOCK_MERGE_ROLLUP_INDEX, BLOCK_ROOT_ROLLUP_EMPTY_INDEX} }; // TODO(#7346): Currently unused! Will be used when batch rollup circuits are integrated. global ALLOWED_PREVIOUS_CIRCUITS = @@ -17,10 +17,7 @@ pub struct RootRollupInputs { impl Empty for RootRollupInputs { fn empty() -> Self { - RootRollupInputs { - previous_rollup_data: [PreviousRollupBlockData::empty(); 2], - prover_id: 0, - } + RootRollupInputs { previous_rollup_data: [PreviousRollupBlockData::empty(); 2], prover_id: 0 } } } @@ -62,7 +59,7 @@ impl RootRollupInputs { fees, vk_tree_root: left.vk_tree_root, protocol_contract_tree_root: left.protocol_contract_tree_root, - prover_id: self.prover_id, + prover_id: self.prover_id } } } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/block_root_rollup_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/block_root_rollup_inputs.nr index 85007c7a404..e56eba2da25 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/block_root_rollup_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/block_root_rollup_inputs.nr @@ -2,9 +2,10 @@ use crate::block_root::block_root_rollup_inputs::BlockRootRollupInputs; use dep::types::{ abis::append_only_tree_snapshot::AppendOnlyTreeSnapshot, constants::{ - L1_TO_L2_MSG_TREE_HEIGHT, L1_TO_L2_MSG_SUBTREE_SIBLING_PATH_LENGTH, - L1_TO_L2_MSG_SUBTREE_HEIGHT, ARCHIVE_HEIGHT, - }, tests::merkle_tree_utils::compute_zero_hashes, + L1_TO_L2_MSG_TREE_HEIGHT, L1_TO_L2_MSG_SUBTREE_SIBLING_PATH_LENGTH, L1_TO_L2_MSG_SUBTREE_HEIGHT, + ARCHIVE_HEIGHT +}, + tests::merkle_tree_utils::compute_zero_hashes }; use crate::tests::previous_rollup_data::default_previous_rollup_data; use crate::tests::l1_to_l2_roots::default_root_rollup_parity_input; @@ -19,10 +20,7 @@ pub fn compute_l1_l2_empty_snapshot() -> (AppendOnlyTreeSnapshot, [Field; L1_TO_ } ( - AppendOnlyTreeSnapshot { - root: zero_hashes[zero_hashes.len() - 1], - next_available_leaf_index: 0, - }, l1_to_l2_message_subtree_sibling_path, + AppendOnlyTreeSnapshot { root: zero_hashes[zero_hashes.len() - 1], next_available_leaf_index: 0 }, l1_to_l2_message_subtree_sibling_path ) } @@ -33,10 +31,7 @@ pub fn compute_archive_snapshot() -> (AppendOnlyTreeSnapshot, [Field; ARCHIVE_HE sibling_path[i] = zero_hashes[i - 1]; } ( - AppendOnlyTreeSnapshot { - root: zero_hashes[zero_hashes.len() - 1], - next_available_leaf_index: 0, - }, sibling_path, + AppendOnlyTreeSnapshot { root: zero_hashes[zero_hashes.len() - 1], next_available_leaf_index: 0 }, sibling_path ) } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/l1_to_l2_roots.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/l1_to_l2_roots.nr index f67fc7637c5..65d93d2503a 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/l1_to_l2_roots.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/l1_to_l2_roots.nr @@ -7,8 +7,9 @@ pub fn default_root_rollup_parity_input() -> RootRollupParityInput { let mut input = RootRollupParityInput::empty(); let vk_index = ROOT_PARITY_INDEX; - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; let vk_path = vk_tree.get_sibling_path(vk_index); let vk_tree_root = vk_tree.get_root(); diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/previous_rollup_block_data.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/previous_rollup_block_data.nr index d34e5b3c08f..041498a2b26 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/previous_rollup_block_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/previous_rollup_block_data.nr @@ -9,8 +9,9 @@ pub fn default_previous_rollup_block_data() -> [PreviousRollupBlockData; 2] { let mut previous_rollup_data = [PreviousRollupBlockData::empty(); 2]; let vk_index = BLOCK_ROOT_ROLLUP_INDEX; - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; let vk_path = vk_tree.get_sibling_path(vk_index); let vk_tree_root = vk_tree.get_root(); diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/previous_rollup_data.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/previous_rollup_data.nr index 1bccb203cc4..0053bb5b4d2 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/previous_rollup_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/tests/previous_rollup_data.nr @@ -10,8 +10,9 @@ pub fn default_previous_rollup_data() -> [PreviousRollupData; 2] { let mut previous_rollup_data = [PreviousRollupData::empty(); 2]; let vk_index = BASE_ROLLUP_INDEX; - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; let vk_path = vk_tree.get_sibling_path(vk_index); let vk_tree_root = vk_tree.get_root(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/combined_accumulated_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/combined_accumulated_data.nr index aabd69b5316..6d712c88add 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/combined_accumulated_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/combined_accumulated_data.nr @@ -1,13 +1,12 @@ use crate::{ - abis::{ - public_data_update_request::PublicDataUpdateRequest, log_hash::{LogHash, ScopedLogHash}, - gas::Gas, - }, messaging::l2_to_l1_message::ScopedL2ToL1Message, + abis::{public_data_update_request::PublicDataUpdateRequest, log_hash::{LogHash, ScopedLogHash}, gas::Gas}, + messaging::l2_to_l1_message::ScopedL2ToL1Message, constants::{ - MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, COMBINED_ACCUMULATED_DATA_LENGTH, - MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, - }, utils::reader::Reader, traits::{Empty, Serialize, Deserialize}, + MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, + MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, COMBINED_ACCUMULATED_DATA_LENGTH, + MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX +}, + utils::reader::Reader, traits::{Empty, Serialize, Deserialize} }; pub struct CombinedAccumulatedData { @@ -42,10 +41,8 @@ impl Empty for CombinedAccumulatedData { note_encrypted_log_preimages_length: 0, encrypted_log_preimages_length: 0, unencrypted_log_preimages_length: 0, - public_data_update_requests: [ - PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX - ], - gas_used: Gas::empty(), + public_data_update_requests: [PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], + gas_used: Gas::empty() } } } @@ -93,28 +90,28 @@ impl Deserialize for CombinedAccumulatedData { nullifiers: reader.read_array([0; MAX_NULLIFIERS_PER_TX]), l2_to_l1_msgs: reader.read_struct_array( ScopedL2ToL1Message::deserialize, - [ScopedL2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_TX], + [ScopedL2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_TX] ), note_encrypted_logs_hashes: reader.read_struct_array( LogHash::deserialize, - [LogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_TX], + [LogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_TX] ), encrypted_logs_hashes: reader.read_struct_array( ScopedLogHash::deserialize, - [ScopedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX], + [ScopedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX] ), unencrypted_logs_hashes: reader.read_struct_array( ScopedLogHash::deserialize, - [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX], + [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX] ), note_encrypted_log_preimages_length: reader.read(), encrypted_log_preimages_length: reader.read(), unencrypted_log_preimages_length: reader.read(), public_data_update_requests: reader.read_struct_array( PublicDataUpdateRequest::deserialize, - [PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], + [PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX] ), - gas_used: reader.read_struct(Gas::deserialize), + gas_used: reader.read_struct(Gas::deserialize) }; reader.finish(); item @@ -129,13 +126,14 @@ impl Eq for CombinedAccumulatedData { & (self.note_encrypted_logs_hashes == other.note_encrypted_logs_hashes) & (self.encrypted_logs_hashes == other.encrypted_logs_hashes) & (self.unencrypted_logs_hashes == other.unencrypted_logs_hashes) - & ( - self.note_encrypted_log_preimages_length - == other.note_encrypted_log_preimages_length - ) - & (self.encrypted_log_preimages_length == other.encrypted_log_preimages_length) - & (self.unencrypted_log_preimages_length == other.unencrypted_log_preimages_length) - & (self.public_data_update_requests == other.public_data_update_requests) + & (self.note_encrypted_log_preimages_length + == other.note_encrypted_log_preimages_length) + & (self.encrypted_log_preimages_length + == other.encrypted_log_preimages_length) + & (self.unencrypted_log_preimages_length + == other.unencrypted_log_preimages_length) + & (self.public_data_update_requests + == other.public_data_update_requests) & (self.gas_used == other.gas_used) } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/private_accumulated_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/private_accumulated_data.nr index 421e7c815eb..75d0abd27ba 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/private_accumulated_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/private_accumulated_data.nr @@ -1,15 +1,16 @@ use crate::{ abis::{ - note_hash::ScopedNoteHash, nullifier::ScopedNullifier, - private_call_request::PrivateCallRequest, public_call_request::PublicCallRequest, - log_hash::{ScopedEncryptedLogHash, NoteLogHash, ScopedLogHash}, - }, traits::{Serialize, Deserialize, Empty}, messaging::l2_to_l1_message::ScopedL2ToL1Message, - utils::reader::Reader, + note_hash::ScopedNoteHash, nullifier::ScopedNullifier, private_call_request::PrivateCallRequest, + public_call_request::PublicCallRequest, + log_hash::{ScopedEncryptedLogHash, NoteLogHash, ScopedLogHash} +}, + traits::{Serialize, Deserialize, Empty}, messaging::l2_to_l1_message::ScopedL2ToL1Message, + utils::reader::Reader }; use crate::constants::{ MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, - MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, PRIVATE_ACCUMULATED_DATA_LENGTH, + MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, PRIVATE_ACCUMULATED_DATA_LENGTH }; pub struct PrivateAccumulatedData { @@ -74,36 +75,36 @@ impl Deserialize for PrivateAccumulatedData { let item = PrivateAccumulatedData { note_hashes: reader.read_struct_array( ScopedNoteHash::deserialize, - [ScopedNoteHash::empty(); MAX_NOTE_HASHES_PER_TX], + [ScopedNoteHash::empty(); MAX_NOTE_HASHES_PER_TX] ), nullifiers: reader.read_struct_array( ScopedNullifier::deserialize, - [ScopedNullifier::empty(); MAX_NULLIFIERS_PER_TX], + [ScopedNullifier::empty(); MAX_NULLIFIERS_PER_TX] ), l2_to_l1_msgs: reader.read_struct_array( ScopedL2ToL1Message::deserialize, - [ScopedL2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_TX], + [ScopedL2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_TX] ), note_encrypted_logs_hashes: reader.read_struct_array( NoteLogHash::deserialize, - [NoteLogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_TX], + [NoteLogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_TX] ), encrypted_logs_hashes: reader.read_struct_array( ScopedEncryptedLogHash::deserialize, - [ScopedEncryptedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX], + [ScopedEncryptedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX] ), unencrypted_logs_hashes: reader.read_struct_array( ScopedLogHash::deserialize, - [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX], + [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX] ), public_call_requests: reader.read_struct_array( PublicCallRequest::deserialize, - [PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX], + [PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX] ), private_call_stack: reader.read_struct_array( PrivateCallRequest::deserialize, - [PrivateCallRequest::empty(); MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX], - ), + [PrivateCallRequest::empty(); MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX] + ) }; reader.finish(); item @@ -133,7 +134,7 @@ impl Empty for PrivateAccumulatedData { encrypted_logs_hashes: [ScopedEncryptedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX], unencrypted_logs_hashes: [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX], public_call_requests: [PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX], - private_call_stack: [PrivateCallRequest::empty(); MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX], + private_call_stack: [PrivateCallRequest::empty(); MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX] } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/private_accumulated_data_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/private_accumulated_data_builder.nr index 34933ce092f..62f0065b6da 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/private_accumulated_data_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/private_accumulated_data_builder.nr @@ -1,15 +1,16 @@ use crate::{ abis::{ - accumulated_data::private_accumulated_data::PrivateAccumulatedData, - note_hash::ScopedNoteHash, nullifier::ScopedNullifier, - private_call_request::PrivateCallRequest, public_call_request::PublicCallRequest, - log_hash::{ScopedEncryptedLogHash, NoteLogHash, ScopedLogHash}, - }, + accumulated_data::private_accumulated_data::PrivateAccumulatedData, note_hash::ScopedNoteHash, + nullifier::ScopedNullifier, private_call_request::PrivateCallRequest, + public_call_request::PublicCallRequest, + log_hash::{ScopedEncryptedLogHash, NoteLogHash, ScopedLogHash} +}, constants::{ - MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, - MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, - MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, - }, messaging::l2_to_l1_message::ScopedL2ToL1Message, traits::Empty, + MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, + MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, + MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX +}, + messaging::l2_to_l1_message::ScopedL2ToL1Message, traits::Empty }; pub struct PrivateAccumulatedDataBuilder { @@ -35,7 +36,7 @@ impl PrivateAccumulatedDataBuilder { encrypted_logs_hashes: self.encrypted_logs_hashes.storage, unencrypted_logs_hashes: self.unencrypted_logs_hashes.storage, public_call_requests: self.public_call_requests.storage, - private_call_stack: self.private_call_stack.storage, + private_call_stack: self.private_call_stack.storage } } } @@ -50,7 +51,7 @@ impl Empty for PrivateAccumulatedDataBuilder { encrypted_logs_hashes: BoundedVec::new(), unencrypted_logs_hashes: BoundedVec::new(), public_call_requests: BoundedVec::new(), - private_call_stack: BoundedVec::new(), + private_call_stack: BoundedVec::new() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data.nr index 56fdeb8565a..1eec6ab169e 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data.nr @@ -1,15 +1,16 @@ use crate::{ abis::{ - public_data_update_request::PublicDataUpdateRequest, gas::Gas, note_hash::ScopedNoteHash, - nullifier::Nullifier, log_hash::{LogHash, ScopedLogHash}, - public_call_request::PublicCallRequest, - }, messaging::l2_to_l1_message::ScopedL2ToL1Message, + public_data_update_request::PublicDataUpdateRequest, gas::Gas, note_hash::ScopedNoteHash, + nullifier::Nullifier, log_hash::{LogHash, ScopedLogHash}, public_call_request::PublicCallRequest +}, + messaging::l2_to_l1_message::ScopedL2ToL1Message, constants::{ - MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, - MAX_L2_TO_L1_MSGS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, - MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, - NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS, PUBLIC_ACCUMULATED_DATA_LENGTH, - }, traits::{Empty, Serialize, Deserialize}, utils::{arrays::array_length, reader::Reader}, + MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, + MAX_L2_TO_L1_MSGS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, + MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS, + PUBLIC_ACCUMULATED_DATA_LENGTH +}, + traits::{Empty, Serialize, Deserialize}, utils::{arrays::array_length, reader::Reader} }; pub struct PublicAccumulatedData { @@ -37,11 +38,9 @@ impl Empty for PublicAccumulatedData { note_encrypted_logs_hashes: [LogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_TX], encrypted_logs_hashes: [ScopedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX], unencrypted_logs_hashes: [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX], - public_data_update_requests: [ - PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX - ], + public_data_update_requests: [PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], public_call_stack: [PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX], - gas_used: Gas::empty(), + gas_used: Gas::empty() } } } @@ -97,37 +96,37 @@ impl Deserialize for PublicAccumulatedData { let item = PublicAccumulatedData { note_hashes: reader.read_struct_array( ScopedNoteHash::deserialize, - [ScopedNoteHash::empty(); MAX_NOTE_HASHES_PER_TX], + [ScopedNoteHash::empty(); MAX_NOTE_HASHES_PER_TX] ), nullifiers: reader.read_struct_array( Nullifier::deserialize, - [Nullifier::empty(); MAX_NULLIFIERS_PER_TX], + [Nullifier::empty(); MAX_NULLIFIERS_PER_TX] ), l2_to_l1_msgs: reader.read_struct_array( ScopedL2ToL1Message::deserialize, - [ScopedL2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_TX], + [ScopedL2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_TX] ), note_encrypted_logs_hashes: reader.read_struct_array( LogHash::deserialize, - [LogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_TX], + [LogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_TX] ), encrypted_logs_hashes: reader.read_struct_array( ScopedLogHash::deserialize, - [ScopedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX], + [ScopedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX] ), unencrypted_logs_hashes: reader.read_struct_array( ScopedLogHash::deserialize, - [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX], + [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX] ), public_data_update_requests: reader.read_struct_array( PublicDataUpdateRequest::deserialize, - [PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], + [PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX] ), public_call_stack: reader.read_struct_array( PublicCallRequest::deserialize, - [PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX], + [PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX] ), - gas_used: reader.read_struct(Gas::deserialize), + gas_used: reader.read_struct(Gas::deserialize) }; reader.finish(); item @@ -142,7 +141,8 @@ impl Eq for PublicAccumulatedData { & (self.note_encrypted_logs_hashes == other.note_encrypted_logs_hashes) & (self.encrypted_logs_hashes == other.encrypted_logs_hashes) & (self.unencrypted_logs_hashes == other.unencrypted_logs_hashes) - & (self.public_data_update_requests == other.public_data_update_requests) + & (self.public_data_update_requests + == other.public_data_update_requests) & (self.public_call_stack == other.public_call_stack) & (self.gas_used == other.gas_used) } @@ -169,7 +169,7 @@ impl PublicAccumulatedDataArrayLengths { encrypted_logs_hashes: array_length(data.encrypted_logs_hashes), unencrypted_logs_hashes: array_length(data.unencrypted_logs_hashes), public_data_update_requests: array_length(data.public_data_update_requests), - public_call_stack: array_length(data.public_call_stack), + public_call_stack: array_length(data.public_call_stack) } } } @@ -184,7 +184,7 @@ impl Empty for PublicAccumulatedDataArrayLengths { encrypted_logs_hashes: 0, unencrypted_logs_hashes: 0, public_data_update_requests: 0, - public_call_stack: 0, + public_call_stack: 0 } } } @@ -197,7 +197,8 @@ impl Eq for PublicAccumulatedDataArrayLengths { & (self.note_encrypted_logs_hashes == other.note_encrypted_logs_hashes) & (self.encrypted_logs_hashes == other.encrypted_logs_hashes) & (self.unencrypted_logs_hashes == other.unencrypted_logs_hashes) - & (self.public_data_update_requests == other.public_data_update_requests) + & (self.public_data_update_requests + == other.public_data_update_requests) & (self.public_call_stack == other.public_call_stack) } } @@ -220,9 +221,7 @@ impl Serialize for PublicAccumulatedDataArra } impl Deserialize for PublicAccumulatedDataArrayLengths { - fn deserialize( - fields: [Field; NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS], - ) -> PublicAccumulatedDataArrayLengths { + fn deserialize(fields: [Field; NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS]) -> PublicAccumulatedDataArrayLengths { let mut reader = Reader::new(fields); let item = Self { @@ -233,7 +232,7 @@ impl Deserialize for PublicAccumulatedDataAr encrypted_logs_hashes: reader.read_u32(), unencrypted_logs_hashes: reader.read_u32(), public_data_update_requests: reader.read_u32(), - public_call_stack: reader.read_u32(), + public_call_stack: reader.read_u32() }; reader.finish(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data_builder.nr index ea5958c89e9..e69d6dc7432 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data_builder.nr @@ -1,14 +1,16 @@ use crate::{ abis::{ - gas::Gas, accumulated_data::public_accumulated_data::PublicAccumulatedData, - note_hash::ScopedNoteHash, nullifier::Nullifier, public_call_request::PublicCallRequest, - public_data_update_request::PublicDataUpdateRequest, log_hash::{LogHash, ScopedLogHash}, - }, messaging::l2_to_l1_message::ScopedL2ToL1Message, + gas::Gas, accumulated_data::public_accumulated_data::PublicAccumulatedData, + note_hash::ScopedNoteHash, nullifier::Nullifier, public_call_request::PublicCallRequest, + public_data_update_request::PublicDataUpdateRequest, log_hash::{LogHash, ScopedLogHash} +}, + messaging::l2_to_l1_message::ScopedL2ToL1Message, constants::{ - MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, - MAX_L2_TO_L1_MSGS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, - MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, - }, traits::Empty, utils::arrays::array_to_bounded_vec, + MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, + MAX_L2_TO_L1_MSGS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, + MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX +}, + traits::Empty, utils::arrays::array_to_bounded_vec }; pub struct PublicAccumulatedDataBuilder { @@ -38,7 +40,7 @@ impl PublicAccumulatedDataBuilder { unencrypted_logs_hashes: array_to_bounded_vec(data.unencrypted_logs_hashes), public_data_update_requests: array_to_bounded_vec(data.public_data_update_requests), public_call_stack: array_to_bounded_vec(data.public_call_stack), - gas_used: data.gas_used, + gas_used: data.gas_used } } @@ -52,7 +54,7 @@ impl PublicAccumulatedDataBuilder { unencrypted_logs_hashes: self.unencrypted_logs_hashes.storage, public_data_update_requests: self.public_data_update_requests.storage, public_call_stack: self.public_call_stack.storage, - gas_used: self.gas_used, + gas_used: self.gas_used } } } @@ -68,7 +70,7 @@ impl Empty for PublicAccumulatedDataBuilder { unencrypted_logs_hashes: BoundedVec::new(), public_data_update_requests: BoundedVec::new(), public_call_stack: BoundedVec::new(), - gas_used: Gas::empty(), + gas_used: Gas::empty() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/append_only_tree_snapshot.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/append_only_tree_snapshot.nr index 793b5dc4dc2..d553f451f88 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/append_only_tree_snapshot.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/append_only_tree_snapshot.nr @@ -11,13 +11,8 @@ impl AppendOnlyTreeSnapshot { [self.root, self.next_available_leaf_index as Field] } - pub fn deserialize( - serialized: [Field; APPEND_ONLY_TREE_SNAPSHOT_LENGTH], - ) -> AppendOnlyTreeSnapshot { - AppendOnlyTreeSnapshot { - root: serialized[0], - next_available_leaf_index: serialized[1] as u32, - } + pub fn deserialize(serialized: [Field; APPEND_ONLY_TREE_SNAPSHOT_LENGTH]) -> AppendOnlyTreeSnapshot { + AppendOnlyTreeSnapshot { root: serialized[0], next_available_leaf_index: serialized[1] as u32 } } pub fn zero() -> Self { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/call_context.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/call_context.nr index 88cd270c42e..83cddfbd6cb 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/call_context.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/call_context.nr @@ -1,6 +1,6 @@ use crate::{ - abis::function_selector::FunctionSelector, address::AztecAddress, - constants::CALL_CONTEXT_LENGTH, traits::{Deserialize, Serialize, Empty}, utils::reader::Reader, + abis::function_selector::FunctionSelector, address::AztecAddress, constants::CALL_CONTEXT_LENGTH, + traits::{Deserialize, Serialize, Empty}, utils::reader::Reader }; // docs:start:call-context @@ -41,7 +41,7 @@ impl Deserialize for CallContext { msg_sender: AztecAddress::from_field(reader.read()), contract_address: AztecAddress::from_field(reader.read()), function_selector: FunctionSelector::from_field(reader.read()), - is_static_call: reader.read() as bool, + is_static_call: reader.read() as bool } } } @@ -52,7 +52,7 @@ impl Empty for CallContext { msg_sender: AztecAddress::empty(), contract_address: AztecAddress::empty(), function_selector: FunctionSelector::empty(), - is_static_call: false, + is_static_call: false } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/combined_constant_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/combined_constant_data.nr index 40d0e8b05ae..09ed2675779 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/combined_constant_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/combined_constant_data.nr @@ -25,14 +25,14 @@ impl CombinedConstantData { historical_header: Header, tx_context: TxContext, vk_tree_root: Field, - protocol_contract_tree_root: Field, + protocol_contract_tree_root: Field ) -> CombinedConstantData { CombinedConstantData { historical_header, tx_context, vk_tree_root, protocol_contract_tree_root, - global_variables: GlobalVariables::empty(), + global_variables: GlobalVariables::empty() } } } @@ -44,7 +44,7 @@ impl Empty for CombinedConstantData { tx_context: TxContext::empty(), vk_tree_root: 0, protocol_contract_tree_root: 0, - global_variables: GlobalVariables::empty(), + global_variables: GlobalVariables::empty() } } } @@ -74,7 +74,7 @@ impl Deserialize for CombinedConstantData { tx_context: reader.read_struct(TxContext::deserialize), vk_tree_root: reader.read(), protocol_contract_tree_root: reader.read(), - global_variables: reader.read_struct(GlobalVariables::deserialize), + global_variables: reader.read_struct(GlobalVariables::deserialize) }; reader.finish(); item diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/contract_class_function_leaf_preimage.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/contract_class_function_leaf_preimage.nr index 2e82f407044..8c78469433e 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/contract_class_function_leaf_preimage.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/contract_class_function_leaf_preimage.nr @@ -12,7 +12,7 @@ impl Hash for ContractClassFunctionLeafPreimage { fn hash(self) -> Field { poseidon2_hash_with_separator( [self.selector.to_field(), self.vk_hash], - GENERATOR_INDEX__FUNCTION_LEAF, + GENERATOR_INDEX__FUNCTION_LEAF ) } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/function_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/function_data.nr index 66a337f675f..ef12c36c7e3 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/function_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/function_data.nr @@ -1,6 +1,6 @@ use crate::{ abis::function_selector::FunctionSelector, constants::FUNCTION_DATA_LENGTH, - traits::{Serialize, Deserialize, Empty}, + traits::{Serialize, Deserialize, Empty} }; pub struct FunctionData { @@ -25,10 +25,7 @@ impl Serialize for FunctionData { impl Deserialize for FunctionData { fn deserialize(serialized: [Field; FUNCTION_DATA_LENGTH]) -> Self { - Self { - selector: FunctionSelector::from_field(serialized[0]), - is_private: serialized[1] as bool, - } + Self { selector: FunctionSelector::from_field(serialized[0]), is_private: serialized[1] as bool } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/function_selector.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/function_selector.nr index 7e742dba38d..6722a8f25e9 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/function_selector.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/function_selector.nr @@ -67,7 +67,6 @@ fn test_is_valid_selector() { #[test] fn test_long_selector() { - let selector = - FunctionSelector::from_signature("foo_and_bar_and_baz_and_foo_bar_baz_and_bar_foo"); + let selector = FunctionSelector::from_signature("foo_and_bar_and_baz_and_foo_bar_baz_and_bar_foo"); assert_eq(selector.to_field(), 0x7590a997); } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/gas.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/gas.nr index a485eb7cd14..3225fdbc51d 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/gas.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/gas.nr @@ -1,6 +1,6 @@ use crate::{ constants::{GAS_LENGTH, FIXED_DA_GAS, FIXED_L2_GAS}, traits::{Deserialize, Serialize, Empty}, - abis::gas_fees::GasFees, + abis::gas_fees::GasFees }; use std::ops::{Add, Sub}; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/gas_settings.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/gas_settings.nr index 212875f1580..004e7321a27 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/gas_settings.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/gas_settings.nr @@ -1,9 +1,10 @@ use crate::{ abis::{gas::Gas, gas_fees::GasFees}, constants::{ - GAS_SETTINGS_LENGTH, DEFAULT_GAS_LIMIT, DEFAULT_TEARDOWN_GAS_LIMIT, DEFAULT_MAX_FEE_PER_GAS, - DEFAULT_INCLUSION_FEE, - }, traits::{Deserialize, Serialize, Empty}, utils::reader::Reader, + GAS_SETTINGS_LENGTH, DEFAULT_GAS_LIMIT, DEFAULT_TEARDOWN_GAS_LIMIT, DEFAULT_MAX_FEE_PER_GAS, + DEFAULT_INCLUSION_FEE +}, + traits::{Deserialize, Serialize, Empty}, utils::reader::Reader }; pub struct GasSettings { @@ -18,7 +19,7 @@ impl GasSettings { gas_limits: Gas, teardown_gas_limits: Gas, max_fees_per_gas: GasFees, - inclusion_fee: Field, + inclusion_fee: Field ) -> Self { Self { gas_limits, teardown_gas_limits, max_fees_per_gas, inclusion_fee } } @@ -28,7 +29,7 @@ impl GasSettings { Gas::new(DEFAULT_GAS_LIMIT, DEFAULT_GAS_LIMIT), Gas::new(DEFAULT_TEARDOWN_GAS_LIMIT, DEFAULT_TEARDOWN_GAS_LIMIT), GasFees::new(DEFAULT_MAX_FEE_PER_GAS, DEFAULT_MAX_FEE_PER_GAS), - DEFAULT_INCLUSION_FEE, + DEFAULT_INCLUSION_FEE ) } } @@ -68,7 +69,7 @@ impl Deserialize for GasSettings { reader.read_struct(Gas::deserialize), reader.read_struct(Gas::deserialize), reader.read_struct(GasFees::deserialize), - reader.read(), + reader.read() ) } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/global_variables.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/global_variables.nr index 8980b18b01f..481a37a85ba 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/global_variables.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/global_variables.nr @@ -1,7 +1,6 @@ use crate::{ - address::{AztecAddress, EthAddress}, abis::gas_fees::GasFees, - constants::GLOBAL_VARIABLES_LENGTH, traits::{Deserialize, Empty, Serialize}, - utils::reader::Reader, + address::{AztecAddress, EthAddress}, abis::gas_fees::GasFees, constants::GLOBAL_VARIABLES_LENGTH, + traits::{Deserialize, Empty, Serialize}, utils::reader::Reader }; // docs:start:global-variables @@ -58,7 +57,7 @@ impl Deserialize for GlobalVariables { timestamp: reader.read() as u64, coinbase: EthAddress::from_field(reader.read()), fee_recipient: AztecAddress::from_field(reader.read()), - gas_fees: reader.read_struct(GasFees::deserialize), + gas_fees: reader.read_struct(GasFees::deserialize) } } } @@ -86,7 +85,7 @@ impl Empty for GlobalVariables { timestamp: 0, coinbase: EthAddress::empty(), fee_recipient: AztecAddress::empty(), - gas_fees: GasFees::empty(), + gas_fees: GasFees::empty() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/kernel_circuit_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/kernel_circuit_public_inputs.nr index 20aa177237d..97f721f481c 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/kernel_circuit_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/kernel_circuit_public_inputs.nr @@ -1,10 +1,11 @@ use crate::{ abis::{ - accumulated_data::CombinedAccumulatedData, combined_constant_data::CombinedConstantData, - validation_requests::RollupValidationRequests, gas_fees::GasFees, - }, address::AztecAddress, partial_state_reference::PartialStateReference, + accumulated_data::CombinedAccumulatedData, combined_constant_data::CombinedConstantData, + validation_requests::RollupValidationRequests, gas_fees::GasFees +}, + address::AztecAddress, partial_state_reference::PartialStateReference, traits::{Empty, Serialize, Deserialize}, constants::KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH, - utils::reader::Reader, + utils::reader::Reader }; pub struct KernelCircuitPublicInputs { @@ -31,7 +32,7 @@ impl Empty for KernelCircuitPublicInputs { constants: CombinedConstantData::empty(), start_state: PartialStateReference::empty(), revert_code: 0, - fee_payer: AztecAddress::empty(), + fee_payer: AztecAddress::empty() } } } @@ -65,9 +66,7 @@ impl Serialize for KernelCircuitPublicInput } impl Deserialize for KernelCircuitPublicInputs { - fn deserialize( - fields: [Field; KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH], - ) -> KernelCircuitPublicInputs { + fn deserialize(fields: [Field; KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH]) -> KernelCircuitPublicInputs { let mut reader = Reader::new(fields); let item = Self { rollup_validation_requests: reader.read_struct(RollupValidationRequests::deserialize), @@ -75,7 +74,7 @@ impl Deserialize for KernelCircuitPublicInp constants: reader.read_struct(CombinedConstantData::deserialize), start_state: reader.read_struct(PartialStateReference::deserialize), revert_code: reader.read() as u8, - fee_payer: reader.read_struct(AztecAddress::deserialize), + fee_payer: reader.read_struct(AztecAddress::deserialize) }; reader.finish(); @@ -87,7 +86,7 @@ mod tests { use crate::abis::{ kernel_circuit_public_inputs::kernel_circuit_public_inputs::KernelCircuitPublicInputs, accumulated_data::CombinedAccumulatedData, combined_constant_data::CombinedConstantData, - validation_requests::RollupValidationRequests, gas::Gas, gas_fees::GasFees, + validation_requests::RollupValidationRequests, gas::Gas, gas_fees::GasFees }; use crate::address::AztecAddress; use crate::partial_state_reference::PartialStateReference; @@ -106,7 +105,7 @@ mod tests { constants: CombinedConstantData::empty(), start_state: PartialStateReference::empty(), revert_code: 0, - fee_payer: AztecAddress::empty(), + fee_payer: AztecAddress::empty() }; inputs.end.gas_used = Gas { da_gas: 10, l2_gas: 20 }; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/mod.nr index cc3ba303c15..9ae785af23c 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/mod.nr @@ -6,9 +6,7 @@ mod public_kernel_circuit_public_inputs_builder; mod vm_circuit_public_inputs; pub use kernel_circuit_public_inputs::KernelCircuitPublicInputs; -pub use private_kernel_circuit_public_inputs::{ - PrivateKernelCircuitPublicInputs, PrivateKernelCircuitPublicInputsArrayLengths, -}; +pub use private_kernel_circuit_public_inputs::{PrivateKernelCircuitPublicInputs, PrivateKernelCircuitPublicInputsArrayLengths}; pub use private_kernel_circuit_public_inputs_builder::PrivateKernelCircuitPublicInputsBuilder; pub use public_kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs; pub use public_kernel_circuit_public_inputs_builder::PublicKernelCircuitPublicInputsBuilder; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/private_kernel_circuit_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/private_kernel_circuit_public_inputs.nr index 992fb75c8f2..a2e208e68bd 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/private_kernel_circuit_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/private_kernel_circuit_public_inputs.nr @@ -1,9 +1,10 @@ use crate::{ abis::{ - accumulated_data::PrivateAccumulatedData, combined_constant_data::CombinedConstantData, - public_call_request::PublicCallRequest, validation_requests::PrivateValidationRequests, - }, address::AztecAddress, constants::PRIVATE_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH, - traits::{Serialize, Deserialize, Empty}, utils::{arrays::array_length, reader::Reader}, + accumulated_data::PrivateAccumulatedData, combined_constant_data::CombinedConstantData, + public_call_request::PublicCallRequest, validation_requests::PrivateValidationRequests +}, + address::AztecAddress, constants::PRIVATE_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH, + traits::{Serialize, Deserialize, Empty}, utils::{arrays::array_length, reader::Reader} }; pub struct PrivateKernelCircuitPublicInputsArrayLengths { @@ -23,15 +24,9 @@ pub struct PrivateKernelCircuitPublicInputsArrayLengths { impl PrivateKernelCircuitPublicInputsArrayLengths { pub fn new(public_inputs: PrivateKernelCircuitPublicInputs) -> Self { PrivateKernelCircuitPublicInputsArrayLengths { - note_hash_read_requests: array_length( - public_inputs.validation_requests.note_hash_read_requests, - ), - nullifier_read_requests: array_length( - public_inputs.validation_requests.nullifier_read_requests, - ), - scoped_key_validation_requests_and_generators: array_length( - public_inputs.validation_requests.scoped_key_validation_requests_and_generators, - ), + note_hash_read_requests: array_length(public_inputs.validation_requests.note_hash_read_requests), + nullifier_read_requests: array_length(public_inputs.validation_requests.nullifier_read_requests), + scoped_key_validation_requests_and_generators: array_length(public_inputs.validation_requests.scoped_key_validation_requests_and_generators), note_hashes: array_length(public_inputs.end.note_hashes), nullifiers: array_length(public_inputs.end.nullifiers), l2_to_l1_msgs: array_length(public_inputs.end.l2_to_l1_msgs), @@ -39,7 +34,7 @@ impl PrivateKernelCircuitPublicInputsArrayLengths { encrypted_logs_hashes: array_length(public_inputs.end.encrypted_logs_hashes), unencrypted_logs_hashes: array_length(public_inputs.end.unencrypted_logs_hashes), public_call_requests: array_length(public_inputs.end.public_call_requests), - private_call_stack: array_length(public_inputs.end.private_call_stack), + private_call_stack: array_length(public_inputs.end.private_call_stack) } } @@ -55,7 +50,7 @@ impl PrivateKernelCircuitPublicInputsArrayLengths { encrypted_logs_hashes: 0, unencrypted_logs_hashes: 0, public_call_requests: 0, - private_call_stack: 0, + private_call_stack: 0 } } } @@ -64,16 +59,15 @@ impl Eq for PrivateKernelCircuitPublicInputsArrayLengths { fn eq(self, other: Self) -> bool { (self.note_hash_read_requests == other.note_hash_read_requests) & (self.nullifier_read_requests == other.nullifier_read_requests) - & ( - self.scoped_key_validation_requests_and_generators - == other.scoped_key_validation_requests_and_generators - ) + & (self.scoped_key_validation_requests_and_generators + == other.scoped_key_validation_requests_and_generators) & (self.note_hashes == other.note_hashes) & (self.nullifiers == other.nullifiers) & (self.l2_to_l1_msgs == other.l2_to_l1_msgs) & (self.note_encrypted_logs_hashes == other.note_encrypted_logs_hashes) & (self.encrypted_logs_hashes == other.encrypted_logs_hashes) - & (self.unencrypted_logs_hashes == other.unencrypted_logs_hashes) + & (self.unencrypted_logs_hashes + == other.unencrypted_logs_hashes) & (self.public_call_requests == other.public_call_requests) & (self.private_call_stack == other.private_call_stack) } @@ -90,8 +84,7 @@ pub struct PrivateKernelCircuitPublicInputs { impl Serialize for PrivateKernelCircuitPublicInputs { fn serialize(self) -> [Field; PRIVATE_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH] { - let mut fields: BoundedVec = - BoundedVec::new(); + let mut fields: BoundedVec = BoundedVec::new(); fields.push(self.min_revertible_side_effect_counter as Field); fields.extend_from_array(self.validation_requests.serialize()); @@ -107,9 +100,7 @@ impl Serialize for PrivateKernelCir } impl Deserialize for PrivateKernelCircuitPublicInputs { - fn deserialize( - fields: [Field; PRIVATE_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH], - ) -> PrivateKernelCircuitPublicInputs { + fn deserialize(fields: [Field; PRIVATE_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH]) -> PrivateKernelCircuitPublicInputs { let mut reader = Reader::new(fields); let item = Self { min_revertible_side_effect_counter: reader.read() as u32, @@ -117,7 +108,7 @@ impl Deserialize for PrivateKernelC end: reader.read_struct(PrivateAccumulatedData::deserialize), constants: reader.read_struct(CombinedConstantData::deserialize), public_teardown_call_request: reader.read_struct(PublicCallRequest::deserialize), - fee_payer: reader.read_struct(AztecAddress::deserialize), + fee_payer: reader.read_struct(AztecAddress::deserialize) }; reader.finish(); @@ -143,7 +134,7 @@ impl Empty for PrivateKernelCircuitPublicInputs { end: PrivateAccumulatedData::empty(), constants: CombinedConstantData::empty(), public_teardown_call_request: PublicCallRequest::empty(), - fee_payer: AztecAddress::empty(), + fee_payer: AztecAddress::empty() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/private_kernel_circuit_public_inputs_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/private_kernel_circuit_public_inputs_builder.nr index 94a770fbf9d..7f92cb880f9 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/private_kernel_circuit_public_inputs_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/private_kernel_circuit_public_inputs_builder.nr @@ -1,11 +1,10 @@ use crate::{ abis::{ - accumulated_data::PrivateAccumulatedDataBuilder, - combined_constant_data::CombinedConstantData, - kernel_circuit_public_inputs::private_kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, - public_call_request::PublicCallRequest, - validation_requests::PrivateValidationRequestsBuilder, - }, address::AztecAddress, traits::Empty, + accumulated_data::PrivateAccumulatedDataBuilder, combined_constant_data::CombinedConstantData, + kernel_circuit_public_inputs::private_kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, + public_call_request::PublicCallRequest, validation_requests::PrivateValidationRequestsBuilder +}, + address::AztecAddress, traits::Empty }; pub struct PrivateKernelCircuitPublicInputsBuilder { @@ -25,7 +24,7 @@ impl PrivateKernelCircuitPublicInputsBuilder { end: self.end.finish(), constants: self.constants, public_teardown_call_request: self.public_teardown_call_request, - fee_payer: self.fee_payer, + fee_payer: self.fee_payer } } } @@ -38,7 +37,7 @@ impl Empty for PrivateKernelCircuitPublicInputsBuilder { end: PrivateAccumulatedDataBuilder::empty(), constants: CombinedConstantData::empty(), public_teardown_call_request: PublicCallRequest::empty(), - fee_payer: AztecAddress::empty(), + fee_payer: AztecAddress::empty() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs.nr index 341a839e2bc..5f3351423e5 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs.nr @@ -1,9 +1,10 @@ use crate::{ abis::{ - accumulated_data::PublicAccumulatedData, combined_constant_data::CombinedConstantData, - public_call_request::PublicCallRequest, validation_requests::PublicValidationRequests, - }, address::AztecAddress, constants::PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH, - traits::{Empty, Serialize, Deserialize}, utils::reader::Reader, + accumulated_data::PublicAccumulatedData, combined_constant_data::CombinedConstantData, + public_call_request::PublicCallRequest, validation_requests::PublicValidationRequests +}, + address::AztecAddress, constants::PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH, + traits::{Empty, Serialize, Deserialize}, utils::reader::Reader }; pub struct PublicKernelCircuitPublicInputs { @@ -27,15 +28,14 @@ impl Empty for PublicKernelCircuitPublicInputs { end_side_effect_counter: 0, public_teardown_call_request: PublicCallRequest::empty(), fee_payer: AztecAddress::empty(), - revert_code: 0, + revert_code: 0 } } } impl Serialize for PublicKernelCircuitPublicInputs { fn serialize(self) -> [Field; PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH] { - let mut fields: BoundedVec = - BoundedVec::new(); + let mut fields: BoundedVec = BoundedVec::new(); fields.extend_from_array(self.constants.serialize()); fields.extend_from_array(self.validation_requests.serialize()); @@ -53,9 +53,7 @@ impl Serialize for PublicKernelCircu } impl Deserialize for PublicKernelCircuitPublicInputs { - fn deserialize( - fields: [Field; PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH], - ) -> PublicKernelCircuitPublicInputs { + fn deserialize(fields: [Field; PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH]) -> PublicKernelCircuitPublicInputs { let mut reader = Reader::new(fields); let item = PublicKernelCircuitPublicInputs { @@ -66,7 +64,7 @@ impl Deserialize for PublicKernelCir end_side_effect_counter: reader.read_u32(), public_teardown_call_request: reader.read_struct(PublicCallRequest::deserialize), fee_payer: reader.read_struct(AztecAddress::deserialize), - revert_code: reader.read() as u8, + revert_code: reader.read() as u8 }; reader.finish(); item diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs_builder.nr index 87d4a1f7e37..4d690d4cb5d 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs_builder.nr @@ -1,11 +1,10 @@ use crate::{ abis::{ - accumulated_data::PublicAccumulatedDataBuilder, - combined_constant_data::CombinedConstantData, - kernel_circuit_public_inputs::public_kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - public_call_request::PublicCallRequest, - validation_requests::PublicValidationRequestsBuilder, - }, address::AztecAddress, traits::Empty, + accumulated_data::PublicAccumulatedDataBuilder, combined_constant_data::CombinedConstantData, + kernel_circuit_public_inputs::public_kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, + public_call_request::PublicCallRequest, validation_requests::PublicValidationRequestsBuilder +}, + address::AztecAddress, traits::Empty }; pub struct PublicKernelCircuitPublicInputsBuilder { @@ -29,7 +28,7 @@ impl PublicKernelCircuitPublicInputsBuilder { end_side_effect_counter: data.end_side_effect_counter, public_teardown_call_request: data.public_teardown_call_request, fee_payer: data.fee_payer, - revert_code: data.revert_code, + revert_code: data.revert_code } } @@ -45,7 +44,7 @@ impl PublicKernelCircuitPublicInputsBuilder { end_side_effect_counter: self.end_side_effect_counter, public_teardown_call_request: self.public_teardown_call_request, fee_payer: self.fee_payer, - revert_code: self.revert_code, + revert_code: self.revert_code } } } @@ -60,7 +59,7 @@ impl Empty for PublicKernelCircuitPublicInputsBuilder { end_side_effect_counter: 0, public_teardown_call_request: PublicCallRequest::empty(), fee_payer: AztecAddress::empty(), - revert_code: 0 as u8, + revert_code: 0 as u8 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/vm_circuit_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/vm_circuit_public_inputs.nr index 0c56f0f34bb..8aec60ac157 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/vm_circuit_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/vm_circuit_public_inputs.nr @@ -1,11 +1,12 @@ use crate::{ abis::{ - accumulated_data::{PublicAccumulatedData, PublicAccumulatedDataArrayLengths}, - combined_constant_data::CombinedConstantData, gas::Gas, - public_call_request::PublicCallRequest, public_inner_call_request::PublicInnerCallRequest, - validation_requests::{PublicValidationRequests, PublicValidationRequestArrayLengths}, - }, constants::{MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, VM_CIRCUIT_PUBLIC_INPUTS_LENGTH}, - traits::{Deserialize, Empty, Serialize}, utils::reader::Reader, + accumulated_data::{PublicAccumulatedData, PublicAccumulatedDataArrayLengths}, + combined_constant_data::CombinedConstantData, gas::Gas, public_call_request::PublicCallRequest, + public_inner_call_request::PublicInnerCallRequest, + validation_requests::{PublicValidationRequests, PublicValidationRequestArrayLengths} +}, + constants::{MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, VM_CIRCUIT_PUBLIC_INPUTS_LENGTH}, + traits::{Deserialize, Empty, Serialize}, utils::reader::Reader }; pub struct VMCircuitPublicInputs { @@ -31,9 +32,7 @@ impl Empty for VMCircuitPublicInputs { VMCircuitPublicInputs { constants: CombinedConstantData::empty(), call_request: PublicCallRequest::empty(), - public_call_stack: [ - PublicInnerCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX - ], + public_call_stack: [PublicInnerCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX], previous_validation_request_array_lengths: PublicValidationRequestArrayLengths::empty(), validation_requests: PublicValidationRequests::empty(), previous_accumulated_data_array_lengths: PublicAccumulatedDataArrayLengths::empty(), @@ -42,7 +41,7 @@ impl Empty for VMCircuitPublicInputs { end_side_effect_counter: 0, start_gas_left: Gas::empty(), transaction_fee: 0, - reverted: false, + reverted: false } } } @@ -52,18 +51,16 @@ impl Eq for VMCircuitPublicInputs { (self.constants == other.constants) & (self.call_request == other.call_request) & (self.public_call_stack == other.public_call_stack) - & ( - self.previous_validation_request_array_lengths - == other.previous_validation_request_array_lengths - ) + & (self.previous_validation_request_array_lengths + == other.previous_validation_request_array_lengths) & (self.validation_requests == other.validation_requests) - & ( - self.previous_accumulated_data_array_lengths - == other.previous_accumulated_data_array_lengths - ) + & (self.previous_accumulated_data_array_lengths + == other.previous_accumulated_data_array_lengths) & (self.accumulated_data == other.accumulated_data) - & (self.start_side_effect_counter == other.start_side_effect_counter) - & (self.end_side_effect_counter == other.end_side_effect_counter) + & (self.start_side_effect_counter + == other.start_side_effect_counter) + & (self.end_side_effect_counter + == other.end_side_effect_counter) & (self.start_gas_left == other.start_gas_left) & (self.transaction_fee == other.transaction_fee) & (self.reverted == other.reverted) @@ -103,21 +100,17 @@ impl Deserialize for VMCircuitPublicInputs { call_request: reader.read_struct(PublicCallRequest::deserialize), public_call_stack: reader.read_struct_array( PublicInnerCallRequest::deserialize, - [PublicInnerCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX], - ), - previous_validation_request_array_lengths: reader.read_struct( - PublicValidationRequestArrayLengths::deserialize, + [PublicInnerCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX] ), + previous_validation_request_array_lengths: reader.read_struct(PublicValidationRequestArrayLengths::deserialize), validation_requests: reader.read_struct(PublicValidationRequests::deserialize), - previous_accumulated_data_array_lengths: reader.read_struct( - PublicAccumulatedDataArrayLengths::deserialize, - ), + previous_accumulated_data_array_lengths: reader.read_struct(PublicAccumulatedDataArrayLengths::deserialize), accumulated_data: reader.read_struct(PublicAccumulatedData::deserialize), start_side_effect_counter: reader.read_u32(), end_side_effect_counter: reader.read_u32(), start_gas_left: reader.read_struct(Gas::deserialize), transaction_fee: reader.read(), - reverted: reader.read() as bool, + reverted: reader.read() as bool }; reader.finish(); item diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_data.nr index 92dc2b13ef2..e4fd5d86ce2 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_data.nr @@ -1,9 +1,8 @@ use crate::{ abis::kernel_circuit_public_inputs::KernelCircuitPublicInputs, constants::{VK_TREE_HEIGHT, TUBE_INDEX}, merkle_tree::membership::check_membership, - recursion::{ - proof::NestedRecursiveProof, verification_key::HonkVerificationKey, traits::Verifiable, - }, utils::arrays::find_index_hint, + recursion::{proof::NestedRecursiveProof, verification_key::HonkVerificationKey, traits::Verifiable}, + utils::arrays::find_index_hint }; pub struct KernelData { @@ -25,20 +24,21 @@ impl KernelData { fn validate_in_vk_tree(self, allowed_indices: [u32; N]) { self.vk.check_hash(); - let index_hint = - unsafe { find_index_hint(allowed_indices, |index: u32| index == self.vk_index) }; + let index_hint = unsafe { + find_index_hint(allowed_indices, |index: u32| index == self.vk_index) + }; assert(index_hint < N, "Invalid vk index"); assert_eq(allowed_indices[index_hint], self.vk_index, "Invalid vk index"); // TODO(#7410) Remove the exception for the tube index assert( check_membership( - self.vk.hash, - self.vk_index as Field, - self.vk_path, - self.public_inputs.constants.vk_tree_root, - ) - | (self.vk_index == TUBE_INDEX), + self.vk.hash, + self.vk_index as Field, + self.vk_path, + self.public_inputs.constants.vk_tree_root + ) + | (self.vk_index == TUBE_INDEX) ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/log_hash.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/log_hash.nr index bacd96d4503..48de98abbc5 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/log_hash.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/log_hash.nr @@ -1,9 +1,10 @@ use crate::{ abis::side_effect::{Ordered, OrderedValue, Scoped}, address::AztecAddress, constants::{ - LOG_HASH_LENGTH, NOTE_LOG_HASH_LENGTH, ENCRYPTED_LOG_HASH_LENGTH, SCOPED_LOG_HASH_LENGTH, - SCOPED_ENCRYPTED_LOG_HASH_LENGTH, - }, traits::{Empty, Serialize, Deserialize}, utils::{arrays::array_concat, reader::Reader}, + LOG_HASH_LENGTH, NOTE_LOG_HASH_LENGTH, ENCRYPTED_LOG_HASH_LENGTH, SCOPED_LOG_HASH_LENGTH, + SCOPED_ENCRYPTED_LOG_HASH_LENGTH +}, + traits::{Empty, Serialize, Deserialize}, utils::{arrays::array_concat, reader::Reader} }; pub struct LogHash { @@ -102,10 +103,7 @@ impl Empty for ScopedLogHash { impl Serialize for ScopedLogHash { fn serialize(self) -> [Field; SCOPED_LOG_HASH_LENGTH] { - array_concat( - self.log_hash.serialize(), - [self.contract_address.to_field()], - ) + array_concat(self.log_hash.serialize(), [self.contract_address.to_field()]) } } @@ -114,7 +112,7 @@ impl Deserialize for ScopedLogHash { let mut reader = Reader::new(values); let res = Self { log_hash: reader.read_struct(LogHash::deserialize), - contract_address: reader.read_struct(AztecAddress::deserialize), + contract_address: reader.read_struct(AztecAddress::deserialize) }; reader.finish(); res @@ -125,12 +123,8 @@ impl ScopedLogHash { pub fn expose_to_public(self) -> Self { // Hide the counter when exposing to public. Self { - log_hash: LogHash { - value: self.log_hash.value, - counter: 0, - length: self.log_hash.length, - }, - contract_address: self.contract_address, + log_hash: LogHash { value: self.log_hash.value, counter: 0, length: self.log_hash.length }, + contract_address: self.contract_address } } } @@ -180,12 +174,7 @@ impl Serialize for EncryptedLogHash { impl Deserialize for EncryptedLogHash { fn deserialize(values: [Field; ENCRYPTED_LOG_HASH_LENGTH]) -> Self { - Self { - value: values[0], - counter: values[1] as u32, - length: values[2], - randomness: values[3], - } + Self { value: values[0], counter: values[1] as u32, length: values[2], randomness: values[3] } } } @@ -215,11 +204,7 @@ impl ScopedEncryptedLogHash { // Expose as a ScopedLogHash. The contract address is assumed to be masked before calling this. ScopedLogHash { contract_address: self.contract_address, - log_hash: LogHash { - value: self.log_hash.value, - counter: 0, - length: self.log_hash.length, - }, + log_hash: LogHash { value: self.log_hash.value, counter: 0, length: self.log_hash.length } } } } @@ -247,19 +232,13 @@ impl Eq for ScopedEncryptedLogHash { impl Empty for ScopedEncryptedLogHash { fn empty() -> Self { - ScopedEncryptedLogHash { - log_hash: EncryptedLogHash::empty(), - contract_address: AztecAddress::empty(), - } + ScopedEncryptedLogHash { log_hash: EncryptedLogHash::empty(), contract_address: AztecAddress::empty() } } } impl Serialize for ScopedEncryptedLogHash { fn serialize(self) -> [Field; SCOPED_ENCRYPTED_LOG_HASH_LENGTH] { - array_concat( - self.log_hash.serialize(), - [self.contract_address.to_field()], - ) + array_concat(self.log_hash.serialize(), [self.contract_address.to_field()]) } } @@ -268,7 +247,7 @@ impl Deserialize for ScopedEncryptedLogHash { let mut reader = Reader::new(values); let res = Self { log_hash: reader.read_struct(EncryptedLogHash::deserialize), - contract_address: reader.read_struct(AztecAddress::deserialize), + contract_address: reader.read_struct(AztecAddress::deserialize) }; reader.finish(); res @@ -329,11 +308,6 @@ impl Serialize for NoteLogHash { impl Deserialize for NoteLogHash { fn deserialize(values: [Field; NOTE_LOG_HASH_LENGTH]) -> Self { - Self { - value: values[0], - counter: values[1] as u32, - length: values[2], - note_hash_counter: values[3] as u32, - } + Self { value: values[0], counter: values[1] as u32, length: values[2], note_hash_counter: values[3] as u32 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/max_block_number.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/max_block_number.nr index c2df0f417c9..0b282e48fcb 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/max_block_number.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/max_block_number.nr @@ -24,9 +24,7 @@ impl Serialize for MaxBlockNumber { impl Deserialize for MaxBlockNumber { fn deserialize(serialized: [Field; MAX_BLOCK_NUMBER_LENGTH]) -> MaxBlockNumber { - MaxBlockNumber { - _opt: Option { _is_some: serialized[0] as bool, _value: serialized[1] as u32 }, - } + MaxBlockNumber { _opt: Option { _is_some: serialized[0] as bool, _value: serialized[1] as u32 } } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/note_hash.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/note_hash.nr index e7096bf0175..22a2c7e5238 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/note_hash.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/note_hash.nr @@ -2,7 +2,7 @@ use crate::{ abis::read_request::ScopedReadRequest, address::AztecAddress, abis::side_effect::{Ordered, OrderedValue, Readable, Scoped}, constants::{NOTE_HASH_LENGTH, SCOPED_NOTE_HASH_LENGTH}, traits::{Empty, Serialize, Deserialize}, - utils::{arrays::array_concat, reader::Reader}, + utils::{arrays::array_concat, reader::Reader} }; pub struct NoteHash { @@ -91,7 +91,7 @@ impl Serialize for ScopedNoteHash { fn serialize(self) -> [Field; SCOPED_NOTE_HASH_LENGTH] { array_concat( self.note_hash.serialize(), - [self.contract_address.to_field()], + [self.contract_address.to_field()] ) } } @@ -101,7 +101,7 @@ impl Deserialize for ScopedNoteHash { let mut reader = Reader::new(values); let res = Self { note_hash: reader.read_struct(NoteHash::deserialize), - contract_address: reader.read_struct(AztecAddress::deserialize), + contract_address: reader.read_struct(AztecAddress::deserialize) }; reader.finish(); res @@ -111,18 +111,13 @@ impl Deserialize for ScopedNoteHash { impl Readable for ScopedNoteHash { fn assert_match_read_request(self, read_request: ScopedReadRequest) { assert_eq( - self.note_hash.value, - read_request.value(), - "Value of the note hash does not match read request", + self.note_hash.value, read_request.value(), "Value of the note hash does not match read request" ); assert_eq( - self.contract_address, - read_request.contract_address, - "Contract address of the note hash does not match read request", + self.contract_address, read_request.contract_address, "Contract address of the note hash does not match read request" ); assert( - read_request.counter() > self.note_hash.counter, - "Read request counter must be greater than the counter of the note hash", + read_request.counter() > self.note_hash.counter, "Read request counter must be greater than the counter of the note hash" ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/note_hash_leaf_preimage.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/note_hash_leaf_preimage.nr index 1c0cedca919..0365e41f7c5 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/note_hash_leaf_preimage.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/note_hash_leaf_preimage.nr @@ -2,7 +2,7 @@ global NOTE_HASH_LEAF_PREIMAGE_LENGTH: u32 = 1; use crate::{ abis::{read_request::ScopedReadRequest, side_effect::Readable}, hash::compute_siloed_note_hash, - merkle_tree::leaf_preimage::LeafPreimage, traits::Empty, + merkle_tree::leaf_preimage::LeafPreimage, traits::Empty }; pub struct NoteHashLeafPreimage { @@ -27,13 +27,8 @@ impl LeafPreimage for NoteHashLeafPreimage { impl Readable for NoteHashLeafPreimage { fn assert_match_read_request(self, read_request: ScopedReadRequest) { - let siloed_value = - compute_siloed_note_hash(read_request.contract_address, read_request.value()); - assert_eq( - self.value, - siloed_value, - "Value of the note hash leaf does not match read request", - ); + let siloed_value = compute_siloed_note_hash(read_request.contract_address, read_request.value()); + assert_eq(self.value, siloed_value, "Value of the note hash leaf does not match read request"); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/nullifier.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/nullifier.nr index 834247cec8e..93bf2cfec28 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/nullifier.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/nullifier.nr @@ -2,7 +2,7 @@ use crate::{ abis::{side_effect::{Ordered, OrderedValue, Readable, Scoped}, read_request::ScopedReadRequest}, address::AztecAddress, constants::{NULLIFIER_LENGTH, SCOPED_NULLIFIER_LENGTH}, hash::compute_siloed_nullifier, traits::{Empty, Serialize, Deserialize}, - utils::{arrays::array_concat, reader::Reader}, + utils::{arrays::array_concat, reader::Reader} }; pub struct Nullifier { @@ -56,16 +56,10 @@ impl Readable for Nullifier { fn assert_match_read_request(self, read_request: ScopedReadRequest) { // Public kernels output Nullifier instead of ScopedNullifier. // The nullifier value has been siloed. - let siloed_request_value = - compute_siloed_nullifier(read_request.contract_address, read_request.value()); - assert_eq( - self.value, - siloed_request_value, - "Value of the nullifier does not match read request", - ); + let siloed_request_value = compute_siloed_nullifier(read_request.contract_address, read_request.value()); + assert_eq(self.value, siloed_request_value, "Value of the nullifier does not match read request"); assert( - read_request.counter() > self.counter, - "Read request counter must be greater than the counter of the nullifier", + read_request.counter() > self.counter, "Read request counter must be greater than the counter of the nullifier" ); } } @@ -121,7 +115,7 @@ impl Serialize for ScopedNullifier { fn serialize(self) -> [Field; SCOPED_NULLIFIER_LENGTH] { array_concat( self.nullifier.serialize(), - [self.contract_address.to_field()], + [self.contract_address.to_field()] ) } } @@ -131,7 +125,7 @@ impl Deserialize for ScopedNullifier { let mut reader = Reader::new(values); let res = Self { nullifier: reader.read_struct(Nullifier::deserialize), - contract_address: reader.read_struct(AztecAddress::deserialize), + contract_address: reader.read_struct(AztecAddress::deserialize) }; reader.finish(); res @@ -141,18 +135,13 @@ impl Deserialize for ScopedNullifier { impl Readable for ScopedNullifier { fn assert_match_read_request(self, read_request: ScopedReadRequest) { assert_eq( - self.nullifier.value, - read_request.value(), - "Value of the nullifier does not match read request", + self.nullifier.value, read_request.value(), "Value of the nullifier does not match read request" ); assert_eq( - self.contract_address, - read_request.contract_address, - "Contract address of the nullifier does not match read request", + self.contract_address, read_request.contract_address, "Contract address of the nullifier does not match read request" ); assert( - read_request.counter() > self.nullifier.counter, - "Read request counter must be greater than the counter of the nullifier", + read_request.counter() > self.nullifier.counter, "Read request counter must be greater than the counter of the nullifier" ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/nullifier_leaf_preimage.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/nullifier_leaf_preimage.nr index 9a957395e6a..d974b27d1c3 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/nullifier_leaf_preimage.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/nullifier_leaf_preimage.nr @@ -2,7 +2,7 @@ global NULLIFIER_LEAF_PREIMAGE_LENGTH: u32 = 3; use crate::{ abis::{read_request::ScopedReadRequest, side_effect::Readable}, hash::compute_siloed_nullifier, - merkle_tree::leaf_preimage::{LeafPreimage, IndexedTreeLeafPreimage}, traits::{Empty, Hash}, + merkle_tree::leaf_preimage::{LeafPreimage, IndexedTreeLeafPreimage}, traits::{Empty, Hash} }; pub struct NullifierLeafPreimage { @@ -53,13 +53,8 @@ impl IndexedTreeLeafPreimage for NullifierLeafPreimage { impl Readable for NullifierLeafPreimage { fn assert_match_read_request(self, read_request: ScopedReadRequest) { - let siloed_value = - compute_siloed_nullifier(read_request.contract_address, read_request.value()); - assert_eq( - self.nullifier, - siloed_value, - "Value of the nullifier leaf does not match read request", - ); + let siloed_value = compute_siloed_nullifier(read_request.contract_address, read_request.value()); + assert_eq(self.nullifier, siloed_value, "Value of the nullifier leaf does not match read request"); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_call_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_call_request.nr index 5165d1ad434..e9953d474cb 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_call_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_call_request.nr @@ -1,7 +1,7 @@ use crate::{ abis::{call_context::CallContext, side_effect::{Ordered, RangeOrdered}}, constants::PRIVATE_CALL_REQUEST_LENGTH, traits::{Empty, Serialize, Deserialize}, - utils::reader::Reader, + utils::reader::Reader }; pub struct PrivateCallRequest { @@ -44,7 +44,7 @@ impl Empty for PrivateCallRequest { args_hash: 0, returns_hash: 0, start_side_effect_counter: 0, - end_side_effect_counter: 0, + end_side_effect_counter: 0 } } } @@ -73,7 +73,7 @@ impl Deserialize for PrivateCallRequest { args_hash: reader.read(), returns_hash: reader.read(), start_side_effect_counter: reader.read_u32(), - end_side_effect_counter: reader.read_u32(), + end_side_effect_counter: reader.read_u32() }; reader.finish(); item diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_circuit_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_circuit_public_inputs.nr index 52361319969..8656eacaa60 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_circuit_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_circuit_public_inputs.nr @@ -1,21 +1,19 @@ use crate::{ abis::{ - call_context::CallContext, max_block_number::MaxBlockNumber, - validation_requests::KeyValidationRequestAndGenerator, note_hash::NoteHash, - nullifier::Nullifier, private_call_request::PrivateCallRequest, - public_call_request::PublicCallRequest, read_request::ReadRequest, - log_hash::{LogHash, NoteLogHash, EncryptedLogHash}, - }, + call_context::CallContext, max_block_number::MaxBlockNumber, + validation_requests::KeyValidationRequestAndGenerator, note_hash::NoteHash, nullifier::Nullifier, + private_call_request::PrivateCallRequest, public_call_request::PublicCallRequest, + read_request::ReadRequest, log_hash::{LogHash, NoteLogHash, EncryptedLogHash} +}, constants::{ - MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, MAX_NULLIFIER_READ_REQUESTS_PER_CALL, - MAX_KEY_VALIDATION_REQUESTS_PER_CALL, MAX_NOTE_HASHES_PER_CALL, MAX_NULLIFIERS_PER_CALL, - MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL, MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, - MAX_L2_TO_L1_MSGS_PER_CALL, PRIVATE_CIRCUIT_PUBLIC_INPUTS_LENGTH, - MAX_ENCRYPTED_LOGS_PER_CALL, MAX_UNENCRYPTED_LOGS_PER_CALL, - MAX_NOTE_ENCRYPTED_LOGS_PER_CALL, - }, header::Header, messaging::l2_to_l1_message::L2ToL1Message, - traits::{Deserialize, Serialize, Empty}, utils::reader::Reader, - transaction::tx_context::TxContext, utils::arrays::validate_array, + MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, MAX_NULLIFIER_READ_REQUESTS_PER_CALL, + MAX_KEY_VALIDATION_REQUESTS_PER_CALL, MAX_NOTE_HASHES_PER_CALL, MAX_NULLIFIERS_PER_CALL, + MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL, MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, + MAX_L2_TO_L1_MSGS_PER_CALL, PRIVATE_CIRCUIT_PUBLIC_INPUTS_LENGTH, MAX_ENCRYPTED_LOGS_PER_CALL, + MAX_UNENCRYPTED_LOGS_PER_CALL, MAX_NOTE_ENCRYPTED_LOGS_PER_CALL +}, + header::Header, messaging::l2_to_l1_message::L2ToL1Message, traits::{Deserialize, Serialize, Empty}, + utils::reader::Reader, transaction::tx_context::TxContext, utils::arrays::validate_array }; pub struct PrivateCircuitPublicInputsArrayLengths { @@ -37,9 +35,7 @@ impl PrivateCircuitPublicInputsArrayLengths { PrivateCircuitPublicInputsArrayLengths { note_hash_read_requests: validate_array(public_inputs.note_hash_read_requests), nullifier_read_requests: validate_array(public_inputs.nullifier_read_requests), - key_validation_requests_and_generators: validate_array( - public_inputs.key_validation_requests_and_generators, - ), + key_validation_requests_and_generators: validate_array(public_inputs.key_validation_requests_and_generators), note_hashes: validate_array(public_inputs.note_hashes), nullifiers: validate_array(public_inputs.nullifiers), l2_to_l1_msgs: validate_array(public_inputs.l2_to_l1_msgs), @@ -47,7 +43,7 @@ impl PrivateCircuitPublicInputsArrayLengths { public_call_requests: validate_array(public_inputs.public_call_requests), note_encrypted_logs_hashes: validate_array(public_inputs.note_encrypted_logs_hashes), encrypted_logs_hashes: validate_array(public_inputs.encrypted_logs_hashes), - unencrypted_logs_hashes: validate_array(public_inputs.unencrypted_logs_hashes), + unencrypted_logs_hashes: validate_array(public_inputs.unencrypted_logs_hashes) } } } @@ -95,27 +91,38 @@ impl Eq for PrivateCircuitPublicInputs { self.call_context.eq(other.call_context) & self.args_hash.eq(other.args_hash) & (self.returns_hash == other.returns_hash) - & (self.min_revertible_side_effect_counter == other.min_revertible_side_effect_counter) + & (self.min_revertible_side_effect_counter + == other.min_revertible_side_effect_counter) & (self.is_fee_payer == other.is_fee_payer) & (self.max_block_number == other.max_block_number) & (self.note_hash_read_requests == other.note_hash_read_requests) & (self.nullifier_read_requests == other.nullifier_read_requests) - & ( - self.key_validation_requests_and_generators - == other.key_validation_requests_and_generators - ) + & (self.key_validation_requests_and_generators + == other.key_validation_requests_and_generators) & (self.note_hashes == other.note_hashes) & (self.nullifiers == other.nullifiers) - & (self.private_call_requests == other.private_call_requests) - & (self.public_call_requests == other.public_call_requests) - & (self.l2_to_l1_msgs == other.l2_to_l1_msgs) - & (self.start_side_effect_counter == other.start_side_effect_counter) - & (self.end_side_effect_counter == other.end_side_effect_counter) - & (self.note_encrypted_logs_hashes == other.note_encrypted_logs_hashes) - & (self.encrypted_logs_hashes == other.encrypted_logs_hashes) - & (self.unencrypted_logs_hashes == other.unencrypted_logs_hashes) - & self.historical_header.eq(other.historical_header) - & self.tx_context.eq(other.tx_context) + & (self.private_call_requests + == other.private_call_requests) + & (self.public_call_requests + == other.public_call_requests) + & (self.l2_to_l1_msgs + == other.l2_to_l1_msgs) + & (self.start_side_effect_counter + == other.start_side_effect_counter) + & (self.end_side_effect_counter + == other.end_side_effect_counter) + & (self.note_encrypted_logs_hashes + == other.note_encrypted_logs_hashes) + & (self.encrypted_logs_hashes + == other.encrypted_logs_hashes) + & (self.unencrypted_logs_hashes + == other.unencrypted_logs_hashes) + & self.historical_header.eq( + other.historical_header + ) + & self.tx_context.eq( + other.tx_context + ) } } @@ -189,53 +196,53 @@ impl Deserialize for PrivateCircuitPublicI max_block_number: reader.read_struct(MaxBlockNumber::deserialize), note_hash_read_requests: reader.read_struct_array( ReadRequest::deserialize, - [ReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], + [ReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] ), nullifier_read_requests: reader.read_struct_array( ReadRequest::deserialize, - [ReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_CALL], + [ReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_CALL] ), key_validation_requests_and_generators: reader.read_struct_array( KeyValidationRequestAndGenerator::deserialize, - [KeyValidationRequestAndGenerator::empty(); MAX_KEY_VALIDATION_REQUESTS_PER_CALL], + [KeyValidationRequestAndGenerator::empty(); MAX_KEY_VALIDATION_REQUESTS_PER_CALL] ), note_hashes: reader.read_struct_array( NoteHash::deserialize, - [NoteHash::empty(); MAX_NOTE_HASHES_PER_CALL], + [NoteHash::empty(); MAX_NOTE_HASHES_PER_CALL] ), nullifiers: reader.read_struct_array( Nullifier::deserialize, - [Nullifier::empty(); MAX_NULLIFIERS_PER_CALL], + [Nullifier::empty(); MAX_NULLIFIERS_PER_CALL] ), private_call_requests: reader.read_struct_array( PrivateCallRequest::deserialize, - [PrivateCallRequest::empty(); MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL], + [PrivateCallRequest::empty(); MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL] ), public_call_requests: reader.read_struct_array( PublicCallRequest::deserialize, - [PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL], + [PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL] ), public_teardown_call_request: reader.read_struct(PublicCallRequest::deserialize), l2_to_l1_msgs: reader.read_struct_array( L2ToL1Message::deserialize, - [L2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_CALL], + [L2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_CALL] ), start_side_effect_counter: reader.read() as u32, end_side_effect_counter: reader.read() as u32, note_encrypted_logs_hashes: reader.read_struct_array( NoteLogHash::deserialize, - [NoteLogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_CALL], + [NoteLogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_CALL] ), encrypted_logs_hashes: reader.read_struct_array( EncryptedLogHash::deserialize, - [EncryptedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_CALL], + [EncryptedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_CALL] ), unencrypted_logs_hashes: reader.read_struct_array( LogHash::deserialize, - [LogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_CALL], + [LogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_CALL] ), historical_header: reader.read_struct(Header::deserialize), - tx_context: reader.read_struct(TxContext::deserialize), + tx_context: reader.read_struct(TxContext::deserialize) }; reader.finish(); @@ -254,17 +261,11 @@ impl Empty for PrivateCircuitPublicInputs { max_block_number: MaxBlockNumber::empty(), note_hash_read_requests: [ReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], nullifier_read_requests: [ReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_CALL], - key_validation_requests_and_generators: [ - KeyValidationRequestAndGenerator::empty(); MAX_KEY_VALIDATION_REQUESTS_PER_CALL - ], + key_validation_requests_and_generators: [KeyValidationRequestAndGenerator::empty(); MAX_KEY_VALIDATION_REQUESTS_PER_CALL], note_hashes: [NoteHash::empty(); MAX_NOTE_HASHES_PER_CALL], nullifiers: [Nullifier::empty(); MAX_NULLIFIERS_PER_CALL], - private_call_requests: [ - PrivateCallRequest::empty(); MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL - ], - public_call_requests: [ - PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL - ], + private_call_requests: [PrivateCallRequest::empty(); MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL], + public_call_requests: [PublicCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL], public_teardown_call_request: PublicCallRequest::empty(), l2_to_l1_msgs: [L2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_CALL], start_side_effect_counter: 0 as u32, @@ -273,7 +274,7 @@ impl Empty for PrivateCircuitPublicInputs { encrypted_logs_hashes: [EncryptedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_CALL], unencrypted_logs_hashes: [LogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_CALL], historical_header: Header::empty(), - tx_context: TxContext::empty(), + tx_context: TxContext::empty() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_kernel/private_call_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_kernel/private_call_data.nr index 8ac455d134f..004d7bc1310 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_kernel/private_call_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_kernel/private_call_data.nr @@ -1,9 +1,7 @@ use crate::{ - abis::private_circuit_public_inputs::PrivateCircuitPublicInputs, - address::SaltedInitializationHash, public_keys::PublicKeys, - constants::{FUNCTION_TREE_HEIGHT, PROTOCOL_CONTRACT_TREE_HEIGHT}, - merkle_tree::membership::MembershipWitness, - recursion::verification_key::ClientIVCVerificationKey, + abis::private_circuit_public_inputs::PrivateCircuitPublicInputs, address::SaltedInitializationHash, + public_keys::PublicKeys, constants::{FUNCTION_TREE_HEIGHT, PROTOCOL_CONTRACT_TREE_HEIGHT}, + merkle_tree::membership::MembershipWitness, recursion::verification_key::ClientIVCVerificationKey }; pub struct PrivateCallData { @@ -35,21 +33,17 @@ pub struct PrivateCallDataWithoutPublicInputs { } impl PrivateCallDataWithoutPublicInputs { - pub fn to_private_call_data( - self, - public_inputs: PrivateCircuitPublicInputs, - ) -> PrivateCallData { + pub fn to_private_call_data(self, public_inputs: PrivateCircuitPublicInputs) -> PrivateCallData { PrivateCallData { public_inputs, vk: self.vk, salted_initialization_hash: self.salted_initialization_hash, public_keys: self.public_keys, contract_class_artifact_hash: self.contract_class_artifact_hash, - contract_class_public_bytecode_commitment: self - .contract_class_public_bytecode_commitment, + contract_class_public_bytecode_commitment: self.contract_class_public_bytecode_commitment, function_leaf_membership_witness: self.function_leaf_membership_witness, protocol_contract_sibling_path: self.protocol_contract_sibling_path, - acir_hash: self.acir_hash, + acir_hash: self.acir_hash } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_kernel_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_kernel_data.nr index 813f04794b3..e228fcd057a 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_kernel_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/private_kernel_data.nr @@ -2,7 +2,7 @@ use crate::{ abis::kernel_circuit_public_inputs::PrivateKernelCircuitPublicInputs, constants::{PRIVATE_KERNEL_RESET_INDEX, VK_TREE_HEIGHT}, merkle_tree::membership::assert_check_membership, - recursion::verification_key::ClientIVCVerificationKey, utils::arrays::find_index_hint, + recursion::verification_key::ClientIVCVerificationKey, utils::arrays::find_index_hint }; pub struct PrivateKernelData { @@ -32,7 +32,7 @@ impl PrivateKernelData { self.vk.hash, self.vk_index as Field, self.vk_path, - self.public_inputs.constants.vk_tree_root, + self.public_inputs.constants.vk_tree_root ); } } @@ -44,15 +44,7 @@ pub struct PrivateKernelDataWithoutPublicInputs { } impl PrivateKernelDataWithoutPublicInputs { - pub fn to_private_kernel_data( - self, - public_inputs: PrivateKernelCircuitPublicInputs, - ) -> PrivateKernelData { - PrivateKernelData { - public_inputs, - vk: self.vk, - vk_index: self.vk_index, - vk_path: self.vk_path, - } + pub fn to_private_kernel_data(self, public_inputs: PrivateKernelCircuitPublicInputs) -> PrivateKernelData { + PrivateKernelData { public_inputs, vk: self.vk, vk_index: self.vk_index, vk_path: self.vk_path } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_request.nr index dd0472b4f29..f7a12a6c949 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_request.nr @@ -1,7 +1,7 @@ use crate::{ abis::{call_context::CallContext, side_effect::Ordered}, address::AztecAddress, constants::PUBLIC_CALL_REQUEST_LENGTH, traits::{Empty, Serialize, Deserialize}, - utils::reader::Reader, + utils::reader::Reader }; pub struct PublicCallRequest { @@ -57,7 +57,7 @@ impl Deserialize for PublicCallRequest { let request = PublicCallRequest { call_context: reader.read_struct(CallContext::deserialize), args_hash: reader.read(), - counter: reader.read_u32(), + counter: reader.read_u32() }; reader.finish(); request diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_stack_item_compressed.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_stack_item_compressed.nr index c3348f0e107..42efa7eb2fb 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_stack_item_compressed.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_stack_item_compressed.nr @@ -49,15 +49,14 @@ impl Empty for PublicCallStackItemCompressed { returns_hash: 0, revert_code: 0, start_gas_left: Gas::empty(), - end_gas_left: Gas::empty(), + end_gas_left: Gas::empty() } } } impl Serialize for PublicCallStackItemCompressed { fn serialize(self) -> [Field; PUBLIC_CALL_STACK_ITEM_COMPRESSED_LENGTH] { - let mut fields: BoundedVec = - BoundedVec::new(); + let mut fields: BoundedVec = BoundedVec::new(); fields.push(self.contract_address.to_field()); fields.extend_from_array(self.call_context.serialize()); @@ -74,9 +73,7 @@ impl Serialize for PublicCallStackItem } impl Deserialize for PublicCallStackItemCompressed { - fn deserialize( - fields: [Field; PUBLIC_CALL_STACK_ITEM_COMPRESSED_LENGTH], - ) -> PublicCallStackItemCompressed { + fn deserialize(fields: [Field; PUBLIC_CALL_STACK_ITEM_COMPRESSED_LENGTH]) -> PublicCallStackItemCompressed { let mut reader = Reader::new(fields); let item = PublicCallStackItemCompressed { @@ -86,7 +83,7 @@ impl Deserialize for PublicCallStackIt returns_hash: reader.read(), revert_code: reader.read() as u8, start_gas_left: reader.read_struct(Gas::deserialize), - end_gas_left: reader.read_struct(Gas::deserialize), + end_gas_left: reader.read_struct(Gas::deserialize) }; reader.finish(); item diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_circuit_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_circuit_public_inputs.nr index dd2da003f28..294406aeb10 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_circuit_public_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_circuit_public_inputs.nr @@ -1,20 +1,21 @@ use crate::{ abis::{ - call_context::CallContext, note_hash::NoteHash, nullifier::Nullifier, - read_request::ReadRequest, tree_leaf_read_request::TreeLeafReadRequest, gas::Gas, - global_variables::GlobalVariables, log_hash::LogHash, - public_inner_call_request::PublicInnerCallRequest, - }, address::AztecAddress, + call_context::CallContext, note_hash::NoteHash, nullifier::Nullifier, read_request::ReadRequest, + tree_leaf_read_request::TreeLeafReadRequest, gas::Gas, global_variables::GlobalVariables, + log_hash::LogHash, public_inner_call_request::PublicInnerCallRequest +}, + address::AztecAddress, constants::{ - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL, MAX_L2_TO_L1_MSGS_PER_CALL, - MAX_NULLIFIERS_PER_CALL, MAX_NOTE_HASHES_PER_CALL, MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, - MAX_NULLIFIER_READ_REQUESTS_PER_CALL, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL, - MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, MAX_PUBLIC_DATA_READS_PER_CALL, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH, - MAX_UNENCRYPTED_LOGS_PER_CALL, - }, contrakt::{storage_read::StorageRead, storage_update_request::StorageUpdateRequest}, - header::Header, messaging::l2_to_l1_message::L2ToL1Message, - traits::{Serialize, Deserialize, Empty}, utils::reader::Reader, + MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL, MAX_L2_TO_L1_MSGS_PER_CALL, MAX_NULLIFIERS_PER_CALL, + MAX_NOTE_HASHES_PER_CALL, MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, + MAX_NULLIFIER_READ_REQUESTS_PER_CALL, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL, + MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL, MAX_PUBLIC_DATA_READS_PER_CALL, + MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH, + MAX_UNENCRYPTED_LOGS_PER_CALL +}, + contrakt::{storage_read::StorageRead, storage_update_request::StorageUpdateRequest}, header::Header, + messaging::l2_to_l1_message::L2ToL1Message, traits::{Serialize, Deserialize, Empty}, + utils::reader::Reader }; // Public inputs to public app circuit. @@ -128,49 +129,49 @@ impl Deserialize for PublicCircuitPublicInp returns_hash: reader.read(), note_hash_read_requests: reader.read_struct_array( TreeLeafReadRequest::deserialize, - [TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], + [TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL] ), nullifier_read_requests: reader.read_struct_array( ReadRequest::deserialize, - [ReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_CALL], + [ReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_CALL] ), nullifier_non_existent_read_requests: reader.read_struct_array( ReadRequest::deserialize, - [ReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL], + [ReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL] ), l1_to_l2_msg_read_requests: reader.read_struct_array( TreeLeafReadRequest::deserialize, - [TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL], + [TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL] ), contract_storage_update_requests: reader.read_struct_array( StorageUpdateRequest::deserialize, - [StorageUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL], + [StorageUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL] ), contract_storage_reads: reader.read_struct_array( StorageRead::deserialize, - [StorageRead::empty(); MAX_PUBLIC_DATA_READS_PER_CALL], + [StorageRead::empty(); MAX_PUBLIC_DATA_READS_PER_CALL] ), public_call_requests: reader.read_struct_array( PublicInnerCallRequest::deserialize, - [PublicInnerCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL], + [PublicInnerCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL] ), note_hashes: reader.read_struct_array( NoteHash::deserialize, - [NoteHash::empty(); MAX_NOTE_HASHES_PER_CALL], + [NoteHash::empty(); MAX_NOTE_HASHES_PER_CALL] ), nullifiers: reader.read_struct_array( Nullifier::deserialize, - [Nullifier::empty(); MAX_NULLIFIERS_PER_CALL], + [Nullifier::empty(); MAX_NULLIFIERS_PER_CALL] ), l2_to_l1_msgs: reader.read_struct_array( L2ToL1Message::deserialize, - [L2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_CALL], + [L2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_CALL] ), start_side_effect_counter: reader.read() as u32, end_side_effect_counter: reader.read() as u32, unencrypted_logs_hashes: reader.read_struct_array( LogHash::deserialize, - [LogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_CALL], + [LogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_CALL] ), historical_header: reader.read_struct(Header::deserialize), global_variables: reader.read_struct(GlobalVariables::deserialize), @@ -178,7 +179,7 @@ impl Deserialize for PublicCircuitPublicInp revert_code: reader.read() as u8, start_gas_left: reader.read_struct(Gas::deserialize), end_gas_left: reader.read_struct(Gas::deserialize), - transaction_fee: reader.read(), + transaction_fee: reader.read() }; reader.finish(); @@ -192,23 +193,13 @@ impl Empty for PublicCircuitPublicInputs { call_context: CallContext::empty(), args_hash: 0, returns_hash: 0, - note_hash_read_requests: [ - TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL - ], + note_hash_read_requests: [TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], nullifier_read_requests: [ReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_CALL], - nullifier_non_existent_read_requests: [ - ReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL - ], - l1_to_l2_msg_read_requests: [ - TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL - ], - contract_storage_update_requests: [ - StorageUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL - ], + nullifier_non_existent_read_requests: [ReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL], + l1_to_l2_msg_read_requests: [TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL], + contract_storage_update_requests: [StorageUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL], contract_storage_reads: [StorageRead::empty(); MAX_PUBLIC_DATA_READS_PER_CALL], - public_call_requests: [ - PublicInnerCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL - ], + public_call_requests: [PublicInnerCallRequest::empty(); MAX_PUBLIC_CALL_STACK_LENGTH_PER_CALL], note_hashes: [NoteHash::empty(); MAX_NOTE_HASHES_PER_CALL], nullifiers: [Nullifier::empty(); MAX_NULLIFIERS_PER_CALL], l2_to_l1_msgs: [L2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_CALL], @@ -221,7 +212,7 @@ impl Empty for PublicCircuitPublicInputs { revert_code: 0 as u8, start_gas_left: Gas::empty(), end_gas_left: Gas::empty(), - transaction_fee: 0, + transaction_fee: 0 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_read.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_read.nr index 1b45465e30a..7ba5ce28f44 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_read.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_read.nr @@ -2,7 +2,7 @@ use crate::{ abis::side_effect::Ordered, address::AztecAddress, constants::PUBLIC_DATA_READ_LENGTH, contrakt::storage_read::StorageRead, data::hash::{compute_public_data_tree_value, compute_public_data_tree_index}, - traits::{Empty, Serialize, Deserialize}, + traits::{Empty, Serialize, Deserialize} }; pub struct PublicDataRead { @@ -12,14 +12,11 @@ pub struct PublicDataRead { } impl PublicDataRead { - pub fn from_contract_storage_read( - contract_address: AztecAddress, - read_request: StorageRead, - ) -> PublicDataRead { + pub fn from_contract_storage_read(contract_address: AztecAddress, read_request: StorageRead) -> PublicDataRead { PublicDataRead { leaf_slot: compute_public_data_tree_index(contract_address, read_request.storage_slot), value: compute_public_data_tree_value(read_request.current_value), - counter: read_request.counter, + counter: read_request.counter } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_update_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_update_request.nr index 7dd85276626..8c8f7561002 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_update_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_update_request.nr @@ -2,9 +2,10 @@ use crate::{ abis::side_effect::Ordered, address::AztecAddress, constants::PUBLIC_DATA_UPDATE_REQUEST_LENGTH, contrakt::storage_update_request::StorageUpdateRequest, data::{ - hash::{compute_public_data_tree_value, compute_public_data_tree_index}, - public_data_tree_leaf::PublicDataTreeLeaf, - }, traits::{Empty, Serialize, Deserialize}, + hash::{compute_public_data_tree_value, compute_public_data_tree_index}, + public_data_tree_leaf::PublicDataTreeLeaf +}, + traits::{Empty, Serialize, Deserialize} }; // TODO: Rename to PublicDataWrite @@ -17,15 +18,12 @@ pub struct PublicDataUpdateRequest { impl PublicDataUpdateRequest { pub fn from_contract_storage_update_request( contract_address: AztecAddress, - update_request: StorageUpdateRequest, + update_request: StorageUpdateRequest ) -> PublicDataUpdateRequest { PublicDataUpdateRequest { - leaf_slot: compute_public_data_tree_index( - contract_address, - update_request.storage_slot, - ), + leaf_slot: compute_public_data_tree_index(contract_address, update_request.storage_slot), new_value: compute_public_data_tree_value(update_request.new_value), - counter: update_request.counter, + counter: update_request.counter } } } @@ -68,11 +66,7 @@ impl Serialize for PublicDataUpdateRequest { impl Deserialize for PublicDataUpdateRequest { fn deserialize(fields: [Field; PUBLIC_DATA_UPDATE_REQUEST_LENGTH]) -> PublicDataUpdateRequest { - PublicDataUpdateRequest { - leaf_slot: fields[0], - new_value: fields[1], - counter: fields[2] as u32, - } + PublicDataUpdateRequest { leaf_slot: fields[0], new_value: fields[1], counter: fields[2] as u32 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_write.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_write.nr index b829d06d7b4..134e00f7b30 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_write.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_write.nr @@ -1,8 +1,9 @@ use crate::{ abis::{ - public_data_read::PublicDataRead, public_data_update_request::PublicDataUpdateRequest, - side_effect::{Inner, Ordered, Overridable, Readable}, - }, traits::Empty, + public_data_read::PublicDataRead, public_data_update_request::PublicDataUpdateRequest, + side_effect::{Inner, Ordered, Overridable, Readable} +}, + traits::Empty }; pub struct OverridablePublicDataWrite { @@ -31,14 +32,10 @@ impl Ordered for OverridablePublicDataWrite { impl Readable for OverridablePublicDataWrite { fn assert_match_read_request(self, read_request: PublicDataRead) { assert_eq( - self.write.leaf_slot, - read_request.leaf_slot, - "leaf_slot in OverridablePublicDataWrite does not match read request", + self.write.leaf_slot, read_request.leaf_slot, "leaf_slot in OverridablePublicDataWrite does not match read request" ); assert_eq( - self.write.new_value, - read_request.value, - "value in OverridablePublicDataWrite does not match read request", + self.write.new_value, read_request.value, "value in OverridablePublicDataWrite does not match read request" ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_inner_call_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_inner_call_request.nr index cdabed4663e..ab77f5aca60 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_inner_call_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_inner_call_request.nr @@ -1,7 +1,7 @@ use crate::{ abis::{public_call_stack_item_compressed::PublicCallStackItemCompressed, side_effect::Ordered}, constants::PUBLIC_INNER_CALL_REQUEST_LENGTH, traits::{Empty, Serialize, Deserialize}, - utils::reader::Reader, + utils::reader::Reader }; // TODO(#7124): To be deprecated. @@ -45,10 +45,7 @@ impl Deserialize for PublicInnerCallRequest { fn deserialize(fields: [Field; PUBLIC_INNER_CALL_REQUEST_LENGTH]) -> PublicInnerCallRequest { let mut reader = Reader::new(fields); - let request = PublicInnerCallRequest { - item: reader.read_struct(PublicCallStackItemCompressed::deserialize), - counter: reader.read_u32(), - }; + let request = PublicInnerCallRequest { item: reader.read_struct(PublicCallStackItemCompressed::deserialize), counter: reader.read_u32() }; reader.finish(); request } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_data.nr index 13c68e9d82b..3277655de97 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_data.nr @@ -1,9 +1,8 @@ use crate::{ abis::kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, constants::{VK_TREE_HEIGHT, TUBE_INDEX}, merkle_tree::membership::check_membership, - recursion::{ - proof::NestedRecursiveProof, verification_key::HonkVerificationKey, traits::Verifiable, - }, utils::arrays::find_index_hint, + recursion::{proof::NestedRecursiveProof, verification_key::HonkVerificationKey, traits::Verifiable}, + utils::arrays::find_index_hint }; pub struct PublicKernelData { @@ -25,20 +24,21 @@ impl PublicKernelData { fn validate_in_vk_tree(self, allowed_indices: [u32; N]) { self.vk.check_hash(); - let index_hint = - unsafe { find_index_hint(allowed_indices, |index: u32| index == self.vk_index) }; + let index_hint = unsafe { + find_index_hint(allowed_indices, |index: u32| index == self.vk_index) + }; assert(index_hint < N, "Invalid vk index"); assert_eq(allowed_indices[index_hint], self.vk_index, "Invalid vk index"); // TODO(#7410) Remove the exception for the tube index assert( check_membership( - self.vk.hash, - self.vk_index as Field, - self.vk_path, - self.public_inputs.constants.vk_tree_root, - ) - | (self.vk_index == TUBE_INDEX), + self.vk.hash, + self.vk_index as Field, + self.vk_path, + self.public_inputs.constants.vk_tree_root + ) + | (self.vk_index == TUBE_INDEX) ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_inner_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_inner_data.nr index 491abeb3169..d1979110ba5 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_inner_data.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_inner_data.nr @@ -1,8 +1,6 @@ use crate::{ abis::kernel_circuit_public_inputs::VMCircuitPublicInputs, - recursion::{ - proof::NestedRecursiveProof, verification_key::HonkVerificationKey, traits::Verifiable, - }, + recursion::{proof::NestedRecursiveProof, verification_key::HonkVerificationKey, traits::Verifiable} }; pub struct PublicKernelInnerData { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/read_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/read_request.nr index fc7742e4eb4..6497dba6419 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/read_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/read_request.nr @@ -1,7 +1,7 @@ use crate::{ abis::side_effect::{Ordered, Scoped}, traits::{Empty, Serialize, Deserialize}, address::AztecAddress, constants::{READ_REQUEST_LENGTH, SCOPED_READ_REQUEST_LEN}, - utils::{arrays::array_concat, reader::Reader}, + utils::{arrays::array_concat, reader::Reader} }; pub struct ReadRequest { @@ -68,10 +68,7 @@ impl Eq for ScopedReadRequest { impl Empty for ScopedReadRequest { fn empty() -> Self { - ScopedReadRequest { - read_request: ReadRequest::empty(), - contract_address: AztecAddress::empty(), - } + ScopedReadRequest { read_request: ReadRequest::empty(), contract_address: AztecAddress::empty() } } } @@ -79,7 +76,7 @@ impl Serialize for ScopedReadRequest { fn serialize(self) -> [Field; SCOPED_READ_REQUEST_LEN] { array_concat( self.read_request.serialize(), - [self.contract_address.to_field()], + [self.contract_address.to_field()] ) } } @@ -89,7 +86,7 @@ impl Deserialize for ScopedReadRequest { let mut reader = Reader::new(values); let res = Self { read_request: reader.read_struct(ReadRequest::deserialize), - contract_address: reader.read_struct(AztecAddress::deserialize), + contract_address: reader.read_struct(AztecAddress::deserialize) }; reader.finish(); res diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/key_validation_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/key_validation_request.nr index 2929f3a15ca..dfde415c627 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/key_validation_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/key_validation_request.nr @@ -26,9 +26,6 @@ impl Serialize for KeyValidationRequest { impl Deserialize for KeyValidationRequest { fn deserialize(fields: [Field; KEY_VALIDATION_REQUEST_LENGTH]) -> Self { - Self { - pk_m: Point { x: fields[0], y: fields[1], is_infinite: fields[2] as bool }, - sk_app: fields[3], - } + Self { pk_m: Point { x: fields[0], y: fields[1], is_infinite: fields[2] as bool }, sk_app: fields[3] } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/key_validation_request_and_generator.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/key_validation_request_and_generator.nr index 604a0d3aa5f..184fa47535e 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/key_validation_request_and_generator.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/key_validation_request_and_generator.nr @@ -1,10 +1,11 @@ use crate::{ address::AztecAddress, abis::validation_requests::{ - key_validation_request::KeyValidationRequest, - scoped_key_validation_request_and_generator::ScopedKeyValidationRequestAndGenerator, - }, constants::KEY_VALIDATION_REQUEST_AND_GENERATOR_LENGTH, - traits::{Empty, Serialize, Deserialize}, utils::{arrays::array_concat, reader::Reader}, + key_validation_request::KeyValidationRequest, + scoped_key_validation_request_and_generator::ScopedKeyValidationRequestAndGenerator +}, + constants::KEY_VALIDATION_REQUEST_AND_GENERATOR_LENGTH, traits::{Empty, Serialize, Deserialize}, + utils::{arrays::array_concat, reader::Reader} }; pub struct KeyValidationRequestAndGenerator { @@ -20,10 +21,7 @@ impl Eq for KeyValidationRequestAndGenerator { impl Empty for KeyValidationRequestAndGenerator { fn empty() -> Self { - KeyValidationRequestAndGenerator { - request: KeyValidationRequest::empty(), - sk_app_generator: 0, - } + KeyValidationRequestAndGenerator { request: KeyValidationRequest::empty(), sk_app_generator: 0 } } } @@ -36,10 +34,7 @@ impl Serialize for KeyValidationReq impl Deserialize for KeyValidationRequestAndGenerator { fn deserialize(fields: [Field; KEY_VALIDATION_REQUEST_AND_GENERATOR_LENGTH]) -> Self { let mut reader = Reader::new(fields); - let res = Self { - request: reader.read_struct(KeyValidationRequest::deserialize), - sk_app_generator: reader.read(), - }; + let res = Self { request: reader.read_struct(KeyValidationRequest::deserialize), sk_app_generator: reader.read() }; reader.finish(); res } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/private_validation_requests.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/private_validation_requests.nr index 6025c64900d..4b8ceeef053 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/private_validation_requests.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/private_validation_requests.nr @@ -1,15 +1,16 @@ use crate::{ abis::{ - read_request::ScopedReadRequest, - validation_requests::{ - rollup_validation_requests::RollupValidationRequests, - scoped_key_validation_request_and_generator::ScopedKeyValidationRequestAndGenerator, - }, - }, + read_request::ScopedReadRequest, + validation_requests::{ + rollup_validation_requests::RollupValidationRequests, + scoped_key_validation_request_and_generator::ScopedKeyValidationRequestAndGenerator +} +}, constants::{ - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_KEY_VALIDATION_REQUESTS_PER_TX, PRIVATE_VALIDATION_REQUESTS_LENGTH, - }, traits::{Serialize, Deserialize, Empty}, utils::reader::Reader, + MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, + MAX_KEY_VALIDATION_REQUESTS_PER_TX, PRIVATE_VALIDATION_REQUESTS_LENGTH +}, + traits::{Serialize, Deserialize, Empty}, utils::reader::Reader }; pub struct PrivateValidationRequests { @@ -35,8 +36,7 @@ impl Serialize for PrivateValidationRequests } for i in 0..MAX_KEY_VALIDATION_REQUESTS_PER_TX { - fields.extend_from_array(self.scoped_key_validation_requests_and_generators[i] - .serialize()); + fields.extend_from_array(self.scoped_key_validation_requests_and_generators[i].serialize()); } fields.push(self.split_counter.is_some() as Field); @@ -55,20 +55,17 @@ impl Deserialize for PrivateValidationReques for_rollup: reader.read_struct(RollupValidationRequests::deserialize), note_hash_read_requests: reader.read_struct_array( ScopedReadRequest::deserialize, - [ScopedReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX], + [ScopedReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX] ), nullifier_read_requests: reader.read_struct_array( ScopedReadRequest::deserialize, - [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX], + [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX] ), scoped_key_validation_requests_and_generators: reader.read_struct_array( ScopedKeyValidationRequestAndGenerator::deserialize, - [ - ScopedKeyValidationRequestAndGenerator::empty(); - MAX_KEY_VALIDATION_REQUESTS_PER_TX - ], - ), - split_counter: Option { _is_some: reader.read_bool(), _value: reader.read_u32() }, + [ScopedKeyValidationRequestAndGenerator::empty(); MAX_KEY_VALIDATION_REQUESTS_PER_TX] + ), + split_counter: Option { _is_some: reader.read_bool(), _value: reader.read_u32() } }; reader.finish(); @@ -80,16 +77,10 @@ impl Empty for PrivateValidationRequests { fn empty() -> Self { PrivateValidationRequests { for_rollup: RollupValidationRequests::empty(), - note_hash_read_requests: [ - ScopedReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX - ], - nullifier_read_requests: [ - ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX - ], - scoped_key_validation_requests_and_generators: [ - ScopedKeyValidationRequestAndGenerator::empty(); MAX_KEY_VALIDATION_REQUESTS_PER_TX - ], - split_counter: Option::none(), + note_hash_read_requests: [ScopedReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX], + nullifier_read_requests: [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX], + scoped_key_validation_requests_and_generators: [ScopedKeyValidationRequestAndGenerator::empty(); MAX_KEY_VALIDATION_REQUESTS_PER_TX], + split_counter: Option::none() } } } @@ -99,10 +90,8 @@ impl Eq for PrivateValidationRequests { (self.for_rollup.eq(other.for_rollup)) & (self.note_hash_read_requests == other.note_hash_read_requests) & (self.nullifier_read_requests == other.nullifier_read_requests) - & ( - self.scoped_key_validation_requests_and_generators - == other.scoped_key_validation_requests_and_generators - ) + & (self.scoped_key_validation_requests_and_generators + == other.scoped_key_validation_requests_and_generators) & (self.split_counter == other.split_counter) } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/private_validation_requests_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/private_validation_requests_builder.nr index e395c1ff6a7..109eb77956c 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/private_validation_requests_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/private_validation_requests_builder.nr @@ -1,16 +1,17 @@ use crate::{ abis::{ - max_block_number::MaxBlockNumber, read_request::ScopedReadRequest, - validation_requests::{ - private_validation_requests::PrivateValidationRequests, - rollup_validation_requests::RollupValidationRequests, - scoped_key_validation_request_and_generator::ScopedKeyValidationRequestAndGenerator, - }, - }, + max_block_number::MaxBlockNumber, read_request::ScopedReadRequest, + validation_requests::{ + private_validation_requests::PrivateValidationRequests, + rollup_validation_requests::RollupValidationRequests, + scoped_key_validation_request_and_generator::ScopedKeyValidationRequestAndGenerator +} +}, constants::{ - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_KEY_VALIDATION_REQUESTS_PER_TX, - }, traits::Empty, + MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, + MAX_KEY_VALIDATION_REQUESTS_PER_TX +}, + traits::Empty }; pub struct PrivateValidationRequestsBuilder { @@ -27,10 +28,8 @@ impl PrivateValidationRequestsBuilder { for_rollup: self.for_rollup(), note_hash_read_requests: self.note_hash_read_requests.storage, nullifier_read_requests: self.nullifier_read_requests.storage, - scoped_key_validation_requests_and_generators: self - .scoped_key_validation_requests_and_generators - .storage, - split_counter: self.split_counter, + scoped_key_validation_requests_and_generators: self.scoped_key_validation_requests_and_generators.storage, + split_counter: self.split_counter } } @@ -46,7 +45,7 @@ impl Empty for PrivateValidationRequestsBuilder { note_hash_read_requests: BoundedVec::new(), nullifier_read_requests: BoundedVec::new(), scoped_key_validation_requests_and_generators: BoundedVec::new(), - split_counter: Option::none(), + split_counter: Option::none() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests.nr index b0c8ce4a3c4..35d8a99179c 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests.nr @@ -1,15 +1,16 @@ use crate::{ abis::{ - public_data_read::PublicDataRead, read_request::ScopedReadRequest, - tree_leaf_read_request::TreeLeafReadRequest, - validation_requests::rollup_validation_requests::RollupValidationRequests, - }, + public_data_read::PublicDataRead, read_request::ScopedReadRequest, + tree_leaf_read_request::TreeLeafReadRequest, + validation_requests::rollup_validation_requests::RollupValidationRequests +}, constants::{ - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - MAX_PUBLIC_DATA_READS_PER_TX, NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS, - PUBLIC_VALIDATION_REQUESTS_LENGTH, - }, traits::{Serialize, Deserialize, Empty}, utils::{arrays::array_length, reader::Reader}, + MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, + MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, + MAX_PUBLIC_DATA_READS_PER_TX, NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS, + PUBLIC_VALIDATION_REQUESTS_LENGTH +}, + traits::{Serialize, Deserialize, Empty}, utils::{arrays::array_length, reader::Reader} }; pub struct PublicValidationRequests { @@ -61,24 +62,24 @@ impl Deserialize for PublicValidationRequests for_rollup: reader.read_struct(RollupValidationRequests::deserialize), note_hash_read_requests: reader.read_struct_array( TreeLeafReadRequest::deserialize, - [TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX], + [TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX] ), nullifier_read_requests: reader.read_struct_array( ScopedReadRequest::deserialize, - [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX], + [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX] ), nullifier_non_existent_read_requests: reader.read_struct_array( ScopedReadRequest::deserialize, - [ScopedReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX], + [ScopedReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX] ), l1_to_l2_msg_read_requests: reader.read_struct_array( TreeLeafReadRequest::deserialize, - [TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX], + [TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX] ), public_data_reads: reader.read_struct_array( PublicDataRead::deserialize, - [PublicDataRead::empty(); MAX_PUBLIC_DATA_READS_PER_TX], - ), + [PublicDataRead::empty(); MAX_PUBLIC_DATA_READS_PER_TX] + ) }; reader.finish(); @@ -90,19 +91,11 @@ impl Empty for PublicValidationRequests { fn empty() -> Self { PublicValidationRequests { for_rollup: RollupValidationRequests::empty(), - note_hash_read_requests: [ - TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX - ], - nullifier_read_requests: [ - ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX - ], - nullifier_non_existent_read_requests: [ - ScopedReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX - ], - l1_to_l2_msg_read_requests: [ - TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX - ], - public_data_reads: [PublicDataRead::empty(); MAX_PUBLIC_DATA_READS_PER_TX], + note_hash_read_requests: [TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX], + nullifier_read_requests: [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX], + nullifier_non_existent_read_requests: [ScopedReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX], + l1_to_l2_msg_read_requests: [TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX], + public_data_reads: [PublicDataRead::empty(); MAX_PUBLIC_DATA_READS_PER_TX] } } } @@ -112,10 +105,8 @@ impl Eq for PublicValidationRequests { (self.for_rollup.eq(other.for_rollup)) & (self.note_hash_read_requests == other.note_hash_read_requests) & (self.nullifier_read_requests == other.nullifier_read_requests) - & ( - self.nullifier_non_existent_read_requests - == other.nullifier_non_existent_read_requests - ) + & (self.nullifier_non_existent_read_requests + == other.nullifier_non_existent_read_requests) & (self.l1_to_l2_msg_read_requests == other.l1_to_l2_msg_read_requests) & (self.public_data_reads == other.public_data_reads) } @@ -134,11 +125,9 @@ impl PublicValidationRequestArrayLengths { PublicValidationRequestArrayLengths { note_hash_read_requests: array_length(requests.note_hash_read_requests), nullifier_read_requests: array_length(requests.nullifier_read_requests), - nullifier_non_existent_read_requests: array_length( - requests.nullifier_non_existent_read_requests, - ), + nullifier_non_existent_read_requests: array_length(requests.nullifier_non_existent_read_requests), l1_to_l2_msg_read_requests: array_length(requests.l1_to_l2_msg_read_requests), - public_data_reads: array_length(requests.public_data_reads), + public_data_reads: array_length(requests.public_data_reads) } } } @@ -150,7 +139,7 @@ impl Empty for PublicValidationRequestArrayLengths { nullifier_read_requests: 0, nullifier_non_existent_read_requests: 0, l1_to_l2_msg_read_requests: 0, - public_data_reads: 0, + public_data_reads: 0 } } } @@ -159,10 +148,8 @@ impl Eq for PublicValidationRequestArrayLengths { fn eq(self, other: Self) -> bool { (self.note_hash_read_requests == other.note_hash_read_requests) & (self.nullifier_read_requests == other.nullifier_read_requests) - & ( - self.nullifier_non_existent_read_requests - == other.nullifier_non_existent_read_requests - ) + & (self.nullifier_non_existent_read_requests + == other.nullifier_non_existent_read_requests) & (self.l1_to_l2_msg_read_requests == other.l1_to_l2_msg_read_requests) & (self.public_data_reads == other.public_data_reads) } @@ -190,7 +177,7 @@ impl Deserialize for PublicValidationReque nullifier_read_requests: reader.read_u32(), nullifier_non_existent_read_requests: reader.read_u32(), l1_to_l2_msg_read_requests: reader.read_u32(), - public_data_reads: reader.read_u32(), + public_data_reads: reader.read_u32() }; reader.finish(); item diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests_builder.nr index 4fcbe4a6cb9..3b541ca6aa0 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests_builder.nr @@ -1,17 +1,18 @@ use crate::{ abis::{ - max_block_number::MaxBlockNumber, public_data_read::PublicDataRead, - read_request::ScopedReadRequest, tree_leaf_read_request::TreeLeafReadRequest, - validation_requests::{ - public_validation_requests::PublicValidationRequests, - rollup_validation_requests::RollupValidationRequests, - }, - }, + max_block_number::MaxBlockNumber, public_data_read::PublicDataRead, read_request::ScopedReadRequest, + tree_leaf_read_request::TreeLeafReadRequest, + validation_requests::{ + public_validation_requests::PublicValidationRequests, + rollup_validation_requests::RollupValidationRequests +} +}, constants::{ - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - MAX_PUBLIC_DATA_READS_PER_TX, - }, traits::Empty, utils::arrays::array_to_bounded_vec, + MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, + MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, + MAX_PUBLIC_DATA_READS_PER_TX +}, + traits::Empty, utils::arrays::array_to_bounded_vec }; pub struct PublicValidationRequestsBuilder { @@ -29,11 +30,9 @@ impl PublicValidationRequestsBuilder { max_block_number: requests.for_rollup.max_block_number, note_hash_read_requests: array_to_bounded_vec(requests.note_hash_read_requests), nullifier_read_requests: array_to_bounded_vec(requests.nullifier_read_requests), - nullifier_non_existent_read_requests: array_to_bounded_vec( - requests.nullifier_non_existent_read_requests, - ), + nullifier_non_existent_read_requests: array_to_bounded_vec(requests.nullifier_non_existent_read_requests), public_data_reads: array_to_bounded_vec(requests.public_data_reads), - l1_to_l2_msg_read_requests: array_to_bounded_vec(requests.l1_to_l2_msg_read_requests), + l1_to_l2_msg_read_requests: array_to_bounded_vec(requests.l1_to_l2_msg_read_requests) } } @@ -44,7 +43,7 @@ impl PublicValidationRequestsBuilder { nullifier_read_requests: self.nullifier_read_requests.storage, nullifier_non_existent_read_requests: self.nullifier_non_existent_read_requests.storage, public_data_reads: self.public_data_reads.storage, - l1_to_l2_msg_read_requests: self.l1_to_l2_msg_read_requests.storage, + l1_to_l2_msg_read_requests: self.l1_to_l2_msg_read_requests.storage } } @@ -61,7 +60,7 @@ impl Empty for PublicValidationRequestsBuilder { nullifier_read_requests: BoundedVec::new(), nullifier_non_existent_read_requests: BoundedVec::new(), public_data_reads: BoundedVec::new(), - l1_to_l2_msg_read_requests: BoundedVec::new(), + l1_to_l2_msg_read_requests: BoundedVec::new() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/rollup_validation_requests.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/rollup_validation_requests.nr index c29122fbc1f..59921e2103c 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/rollup_validation_requests.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/rollup_validation_requests.nr @@ -1,6 +1,6 @@ use crate::{ abis::max_block_number::MaxBlockNumber, traits::{Empty, Serialize, Deserialize}, - constants::ROLLUP_VALIDATION_REQUESTS_LENGTH, utils::reader::Reader, + constants::ROLLUP_VALIDATION_REQUESTS_LENGTH, utils::reader::Reader }; // These are validation requests that cannot be fulfilled in the current context (private or public), and must be diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/scoped_key_validation_request_and_generator.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/scoped_key_validation_request_and_generator.nr index 259ba94bc9b..d42bf260460 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/scoped_key_validation_request_and_generator.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/scoped_key_validation_request_and_generator.nr @@ -2,9 +2,9 @@ use crate::{ address::AztecAddress, constants::SCOPED_KEY_VALIDATION_REQUEST_AND_GENERATOR_LENGTH, traits::{Empty, Serialize, Deserialize}, utils::{arrays::array_concat, reader::Reader}, abis::{ - side_effect::Scoped, - validation_requests::key_validation_request_and_generator::KeyValidationRequestAndGenerator, - }, + side_effect::Scoped, + validation_requests::key_validation_request_and_generator::KeyValidationRequestAndGenerator +} }; pub struct ScopedKeyValidationRequestAndGenerator { @@ -29,10 +29,7 @@ impl Eq for ScopedKeyValidationRequestAndGenerator { impl Empty for ScopedKeyValidationRequestAndGenerator { fn empty() -> Self { - ScopedKeyValidationRequestAndGenerator { - request: KeyValidationRequestAndGenerator::empty(), - contract_address: AztecAddress::zero(), - } + ScopedKeyValidationRequestAndGenerator { request: KeyValidationRequestAndGenerator::empty(), contract_address: AztecAddress::zero() } } } @@ -47,7 +44,7 @@ impl Deserialize for ScopedK let mut reader = Reader::new(fields); let res = Self { request: reader.read_struct(KeyValidationRequestAndGenerator::deserialize), - contract_address: reader.read_struct(AztecAddress::deserialize), + contract_address: reader.read_struct(AztecAddress::deserialize) }; reader.finish(); res diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/address/aztec_address.nr b/noir-projects/noir-protocol-circuits/crates/types/src/address/aztec_address.nr index c1515da11b0..e33bbdf0606 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/address/aztec_address.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/address/aztec_address.nr @@ -1,14 +1,14 @@ use crate::{ abis::function_selector::FunctionSelector, address::{ - partial_address::PartialAddress, public_keys_hash::PublicKeysHash, - salted_initialization_hash::SaltedInitializationHash, - }, + partial_address::PartialAddress, public_keys_hash::PublicKeysHash, + salted_initialization_hash::SaltedInitializationHash +}, constants::{AZTEC_ADDRESS_LENGTH, FUNCTION_TREE_HEIGHT, GENERATOR_INDEX__CONTRACT_ADDRESS_V1}, contract_class_id::ContractClassId, hash::{poseidon2_hash_with_separator, private_functions_root_from_siblings}, merkle_tree::membership::MembershipWitness, - traits::{Empty, FromField, ToField, Serialize, Deserialize}, utils, + traits::{Empty, FromField, ToField, Serialize, Deserialize}, utils }; // Aztec address @@ -58,10 +58,12 @@ impl AztecAddress { } pub fn compute(pub_keys_hash: PublicKeysHash, partial_address: PartialAddress) -> AztecAddress { - AztecAddress::from_field(poseidon2_hash_with_separator( - [pub_keys_hash.to_field(), partial_address.to_field()], - GENERATOR_INDEX__CONTRACT_ADDRESS_V1, - )) + AztecAddress::from_field( + poseidon2_hash_with_separator( + [pub_keys_hash.to_field(), partial_address.to_field()], + GENERATOR_INDEX__CONTRACT_ADDRESS_V1 + ) + ) } pub fn compute_from_private_function( @@ -71,26 +73,23 @@ impl AztecAddress { contract_class_artifact_hash: Field, contract_class_public_bytecode_commitment: Field, salted_initialization_hash: SaltedInitializationHash, - public_keys_hash: PublicKeysHash, + public_keys_hash: PublicKeysHash ) -> Self { let private_functions_root = private_functions_root_from_siblings( function_selector, functino_vk_hash, function_leaf_membership_witness.leaf_index, - function_leaf_membership_witness.sibling_path, + function_leaf_membership_witness.sibling_path ); let contract_class_id = ContractClassId::compute( contract_class_artifact_hash, private_functions_root, - contract_class_public_bytecode_commitment, + contract_class_public_bytecode_commitment ); // Compute contract address using the preimage which includes the class_id. - let partial_address = PartialAddress::compute_from_salted_initialization_hash( - contract_class_id, - salted_initialization_hash, - ); + let partial_address = PartialAddress::compute_from_salted_initialization_hash(contract_class_id, salted_initialization_hash); AztecAddress::compute(public_keys_hash, partial_address) } @@ -115,8 +114,7 @@ fn compute_address_from_partial_and_pub_keys_hash() { let partial_address = PartialAddress::from_field(2); let address = AztecAddress::compute(pub_keys_hash, partial_address); - let expected_computed_address_from_partial_and_pubkey = - 0x23ce9be3fa3c846b0f9245cc796902e731d04f086e8a42473bb29e405fc98075; + let expected_computed_address_from_partial_and_pubkey = 0x23ce9be3fa3c846b0f9245cc796902e731d04f086e8a42473bb29e405fc98075; assert(address.to_field() == expected_computed_address_from_partial_and_pubkey); } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/address/partial_address.nr b/noir-projects/noir-protocol-circuits/crates/types/src/address/partial_address.nr index d0be0319866..1f13fc52485 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/address/partial_address.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/address/partial_address.nr @@ -1,7 +1,7 @@ use crate::{ address::{salted_initialization_hash::SaltedInitializationHash, aztec_address::AztecAddress}, constants::GENERATOR_INDEX__PARTIAL_ADDRESS, contract_class_id::ContractClassId, - hash::poseidon2_hash_with_separator, traits::{ToField, Serialize, Deserialize}, + hash::poseidon2_hash_with_separator, traits::{ToField, Serialize, Deserialize} }; global PARTIAL_ADDRESS_LENGTH: u32 = 1; @@ -38,22 +38,24 @@ impl PartialAddress { contract_class_id: ContractClassId, salt: Field, initialization_hash: Field, - deployer: AztecAddress, + deployer: AztecAddress ) -> Self { PartialAddress::compute_from_salted_initialization_hash( contract_class_id, - SaltedInitializationHash::compute(salt, initialization_hash, deployer), + SaltedInitializationHash::compute(salt, initialization_hash, deployer) ) } pub fn compute_from_salted_initialization_hash( contract_class_id: ContractClassId, - salted_initialization_hash: SaltedInitializationHash, + salted_initialization_hash: SaltedInitializationHash ) -> Self { - PartialAddress::from_field(poseidon2_hash_with_separator( - [contract_class_id.to_field(), salted_initialization_hash.to_field()], - GENERATOR_INDEX__PARTIAL_ADDRESS, - )) + PartialAddress::from_field( + poseidon2_hash_with_separator( + [contract_class_id.to_field(), salted_initialization_hash.to_field()], + GENERATOR_INDEX__PARTIAL_ADDRESS + ) + ) } pub fn to_field(self) -> Field { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/address/salted_initialization_hash.nr b/noir-projects/noir-protocol-circuits/crates/types/src/address/salted_initialization_hash.nr index 5ef32bae6e8..107ca42f146 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/address/salted_initialization_hash.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/address/salted_initialization_hash.nr @@ -1,6 +1,6 @@ use crate::{ address::aztec_address::AztecAddress, constants::GENERATOR_INDEX__PARTIAL_ADDRESS, - hash::poseidon2_hash_with_separator, traits::ToField, + hash::poseidon2_hash_with_separator, traits::ToField }; // Salted initialization hash. Used in the computation of a partial address. @@ -20,10 +20,12 @@ impl SaltedInitializationHash { } pub fn compute(salt: Field, initialization_hash: Field, deployer: AztecAddress) -> Self { - SaltedInitializationHash::from_field(poseidon2_hash_with_separator( - [salt, initialization_hash, deployer.to_field()], - GENERATOR_INDEX__PARTIAL_ADDRESS, - )) + SaltedInitializationHash::from_field( + poseidon2_hash_with_separator( + [salt, initialization_hash, deployer.to_field()], + GENERATOR_INDEX__PARTIAL_ADDRESS + ) + ) } pub fn assert_is_zero(self) { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/contract_class_id.nr b/noir-projects/noir-protocol-circuits/crates/types/src/contract_class_id.nr index 515c840de60..6afd0ffb3e4 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/contract_class_id.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/contract_class_id.nr @@ -39,11 +39,11 @@ impl ContractClassId { pub fn compute( artifact_hash: Field, private_functions_root: Field, - public_bytecode_commitment: Field, + public_bytecode_commitment: Field ) -> Self { let hash = crate::hash::poseidon2_hash_with_separator( [artifact_hash, private_functions_root, public_bytecode_commitment], - GENERATOR_INDEX__CONTRACT_LEAF, + GENERATOR_INDEX__CONTRACT_LEAF ); // TODO(@spalladino): Update generator index ContractClassId::from_field(hash) } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/contract_instance.nr b/noir-projects/noir-protocol-circuits/crates/types/src/contract_instance.nr index dfe75822aba..c0ebba2f399 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/contract_instance.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/contract_instance.nr @@ -1,9 +1,7 @@ use crate::{ - address::{ - aztec_address::AztecAddress, partial_address::PartialAddress, - public_keys_hash::PublicKeysHash, - }, public_keys::PublicKeys, contract_class_id::ContractClassId, - constants::CONTRACT_INSTANCE_LENGTH, traits::{Deserialize, Hash, Serialize}, + address::{aztec_address::AztecAddress, partial_address::PartialAddress, public_keys_hash::PublicKeysHash}, + public_keys::PublicKeys, contract_class_id::ContractClassId, constants::CONTRACT_INSTANCE_LENGTH, + traits::{Deserialize, Hash, Serialize} }; pub struct ContractInstance { @@ -42,7 +40,7 @@ impl Serialize for ContractInstance { public_keys_serialized[8], public_keys_serialized[9], public_keys_serialized[10], - public_keys_serialized[11], + public_keys_serialized[11] ] } } @@ -54,7 +52,8 @@ impl Deserialize for ContractInstance { deployer: AztecAddress::from_field(serialized[1]), contract_class_id: ContractClassId::from_field(serialized[2]), initialization_hash: serialized[3], - public_keys: PublicKeys::deserialize([ + public_keys: PublicKeys::deserialize( + [ serialized[4], serialized[5], serialized[6], @@ -66,8 +65,9 @@ impl Deserialize for ContractInstance { serialized[12], serialized[13], serialized[14], - serialized[15], - ]), + serialized[15] + ] + ) } } } @@ -86,8 +86,8 @@ impl ContractInstance { self.contract_class_id, self.salt, self.initialization_hash, - self.deployer, - ), + self.deployer + ) ) } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_read.nr b/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_read.nr index c72347be04f..b69bc4915e3 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_read.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_read.nr @@ -28,11 +28,7 @@ impl Serialize for StorageRead { impl Deserialize for StorageRead { fn deserialize(serialized: [Field; CONTRACT_STORAGE_READ_LENGTH]) -> Self { - Self { - storage_slot: serialized[0], - current_value: serialized[1], - counter: serialized[2] as u32, - } + Self { storage_slot: serialized[0], current_value: serialized[1], counter: serialized[2] as u32 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_update_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_update_request.nr index 37cb287f5d2..8ca1db41645 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_update_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_update_request.nr @@ -1,6 +1,4 @@ -use crate::{ - constants::CONTRACT_STORAGE_UPDATE_REQUEST_LENGTH, traits::{Deserialize, Empty, Serialize}, -}; +use crate::{constants::CONTRACT_STORAGE_UPDATE_REQUEST_LENGTH, traits::{Deserialize, Empty, Serialize}}; pub struct StorageUpdateRequest { storage_slot: Field, @@ -28,11 +26,7 @@ impl Serialize for StorageUpdateRequest impl Deserialize for StorageUpdateRequest { fn deserialize(serialized: [Field; CONTRACT_STORAGE_UPDATE_REQUEST_LENGTH]) -> Self { - StorageUpdateRequest { - storage_slot: serialized[0], - new_value: serialized[1], - counter: serialized[2] as u32, - } + StorageUpdateRequest { storage_slot: serialized[0], new_value: serialized[1], counter: serialized[2] as u32 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/data/hash.nr b/noir-projects/noir-protocol-circuits/crates/types/src/data/hash.nr index 76561daabd7..65a2bd036e6 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/data/hash.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/data/hash.nr @@ -1,12 +1,9 @@ use crate::{address::AztecAddress, constants::GENERATOR_INDEX__PUBLIC_LEAF_INDEX}; -pub fn compute_public_data_tree_index( - contract_address: AztecAddress, - storage_slot: Field, -) -> Field { +pub fn compute_public_data_tree_index(contract_address: AztecAddress, storage_slot: Field) -> Field { crate::hash::poseidon2_hash_with_separator( [contract_address.to_field(), storage_slot], - GENERATOR_INDEX__PUBLIC_LEAF_INDEX, + GENERATOR_INDEX__PUBLIC_LEAF_INDEX ) } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_hint.nr b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_hint.nr index 75d40b0e754..7625534119a 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_hint.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_hint.nr @@ -1,7 +1,7 @@ use crate::{ data::public_data_tree_leaf_preimage::PublicDataTreeLeafPreimage, traits::Empty, merkle_tree::{MembershipWitness, conditionally_assert_check_membership}, - constants::PUBLIC_DATA_TREE_HEIGHT, + constants::PUBLIC_DATA_TREE_HEIGHT }; pub struct PublicDataHint { @@ -20,8 +20,7 @@ impl PublicDataHint { let exists_in_tree = self.leaf_slot == self.leaf_preimage.slot; if exists_in_tree { assert( - self.value == self.leaf_preimage.value, - "Hinted public data value does not match the value in leaf preimage", + self.value == self.leaf_preimage.value, "Hinted public data value does not match the value in leaf preimage" ); } else { assert(self.value == 0, "Value must be 0 for non-existent public data"); @@ -32,7 +31,7 @@ impl PublicDataHint { exists_in_tree, self.leaf_preimage, self.membership_witness, - public_data_tree_root, + public_data_tree_root ); } } @@ -45,7 +44,7 @@ impl Empty for PublicDataHint { value: 0, override_counter: 0, membership_witness: MembershipWitness::empty(), - leaf_preimage: PublicDataTreeLeafPreimage::empty(), + leaf_preimage: PublicDataTreeLeafPreimage::empty() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_leaf_hint.nr b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_leaf_hint.nr index a6fb45794a0..f7a544abb4a 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_leaf_hint.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_leaf_hint.nr @@ -1,6 +1,6 @@ use crate::{ data::public_data_tree_leaf_preimage::PublicDataTreeLeafPreimage, traits::Empty, - merkle_tree::MembershipWitness, constants::PUBLIC_DATA_TREE_HEIGHT, + merkle_tree::MembershipWitness, constants::PUBLIC_DATA_TREE_HEIGHT }; pub struct PublicDataLeafHint { @@ -10,9 +10,6 @@ pub struct PublicDataLeafHint { impl Empty for PublicDataLeafHint { fn empty() -> Self { - PublicDataLeafHint { - preimage: PublicDataTreeLeafPreimage::empty(), - membership_witness: MembershipWitness::empty(), - } + PublicDataLeafHint { preimage: PublicDataTreeLeafPreimage::empty(), membership_witness: MembershipWitness::empty() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf.nr b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf.nr index 07c2fd40a6d..5a0cdb28f58 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf.nr @@ -1,6 +1,4 @@ -use crate::{ - abis::{public_data_read::PublicDataRead, side_effect::{Overridable, Readable}}, traits::Empty, -}; +use crate::{abis::{public_data_read::PublicDataRead, side_effect::{Overridable, Readable}}, traits::Empty}; pub struct PublicDataTreeLeaf { slot: Field, @@ -39,14 +37,10 @@ impl Empty for OverridablePublicDataTreeLeaf { impl Readable for OverridablePublicDataTreeLeaf { fn assert_match_read_request(self, read_request: PublicDataRead) { assert_eq( - self.leaf.slot, - read_request.leaf_slot, - "leaf_slot in OverridablePublicDataTreeLeaf does not match read request", + self.leaf.slot, read_request.leaf_slot, "leaf_slot in OverridablePublicDataTreeLeaf does not match read request" ); assert_eq( - self.leaf.value, - read_request.value, - "value in OverridablePublicDataTreeLeaf does not match read request", + self.leaf.value, read_request.value, "value in OverridablePublicDataTreeLeaf does not match read request" ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf_preimage.nr b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf_preimage.nr index 99d9b410412..f63bdeaf121 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf_preimage.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf_preimage.nr @@ -18,12 +18,14 @@ impl Hash for PublicDataTreeLeafPreimage { if self.is_empty() { 0 } else { - crate::hash::poseidon2_hash([ + crate::hash::poseidon2_hash( + [ self.slot, self.value, (self.next_index as Field), - self.next_slot, - ]) + self.next_slot + ] + ) } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/debug_log.nr b/noir-projects/noir-protocol-circuits/crates/types/src/debug_log.nr index 706139c8409..8bf831ced3f 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/debug_log.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/debug_log.nr @@ -12,13 +12,12 @@ pub fn debug_log(msg: str) { /// debug_log_format("whole array: {}", [e1, e2, e3, e4]); pub fn debug_log_format(msg: str, args: [Field; N]) { // This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to call. - unsafe { debug_log_oracle_wrapper(msg, args) }; + unsafe { + debug_log_oracle_wrapper(msg, args) + }; } -pub unconstrained fn debug_log_oracle_wrapper( - msg: str, - args: [Field; N], -) { +pub unconstrained fn debug_log_oracle_wrapper(msg: str, args: [Field; N]) { debug_log_oracle(msg, args.as_slice()); } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr b/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr index 63c14f6966e..49776e75aae 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr @@ -1,18 +1,19 @@ use crate::{ abis::{ - contract_class_function_leaf_preimage::ContractClassFunctionLeafPreimage, - function_selector::FunctionSelector, - log_hash::{LogHash, ScopedLogHash, ScopedEncryptedLogHash}, note_hash::ScopedNoteHash, - nullifier::ScopedNullifier, - }, address::{AztecAddress, EthAddress}, + contract_class_function_leaf_preimage::ContractClassFunctionLeafPreimage, + function_selector::FunctionSelector, log_hash::{LogHash, ScopedLogHash, ScopedEncryptedLogHash}, + note_hash::ScopedNoteHash, nullifier::ScopedNullifier +}, + address::{AztecAddress, EthAddress}, constants::{ - FUNCTION_TREE_HEIGHT, GENERATOR_INDEX__SILOED_NOTE_HASH, GENERATOR_INDEX__OUTER_NULLIFIER, - GENERATOR_INDEX__VK, GENERATOR_INDEX__NOTE_HASH_NONCE, GENERATOR_INDEX__UNIQUE_NOTE_HASH, - MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, - }, merkle_tree::root::root_from_sibling_path, + FUNCTION_TREE_HEIGHT, GENERATOR_INDEX__SILOED_NOTE_HASH, GENERATOR_INDEX__OUTER_NULLIFIER, + GENERATOR_INDEX__VK, GENERATOR_INDEX__NOTE_HASH_NONCE, GENERATOR_INDEX__UNIQUE_NOTE_HASH, + MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX +}, + merkle_tree::root::root_from_sibling_path, messaging::l2_to_l1_message::{L2ToL1Message, ScopedL2ToL1Message}, recursion::verification_key::VerificationKey, traits::{is_empty, ToField}, - utils::field::field_from_bytes_32_trunc, + utils::field::field_from_bytes_32_trunc }; use super::utils::field::field_from_bytes; @@ -27,22 +28,18 @@ pub fn private_functions_root_from_siblings( selector: FunctionSelector, vk_hash: Field, function_leaf_index: Field, - function_leaf_sibling_path: [Field; FUNCTION_TREE_HEIGHT], + function_leaf_sibling_path: [Field; FUNCTION_TREE_HEIGHT] ) -> Field { let function_leaf_preimage = ContractClassFunctionLeafPreimage { selector, vk_hash }; let function_leaf = function_leaf_preimage.hash(); - root_from_sibling_path( - function_leaf, - function_leaf_index, - function_leaf_sibling_path, - ) + root_from_sibling_path(function_leaf, function_leaf_index, function_leaf_sibling_path) } fn compute_note_hash_nonce(tx_hash: Field, note_index_in_tx: u32) -> Field { // Hashing tx hash with note index in tx is guaranteed to be unique poseidon2_hash_with_separator( [tx_hash, note_index_in_tx as Field], - GENERATOR_INDEX__NOTE_HASH_NONCE, + GENERATOR_INDEX__NOTE_HASH_NONCE ) } @@ -54,7 +51,7 @@ pub fn compute_unique_note_hash(nonce: Field, note_hash: Field) -> Field { pub fn compute_siloed_note_hash(app: AztecAddress, unique_note_hash: Field) -> Field { poseidon2_hash_with_separator( [app.to_field(), unique_note_hash], - GENERATOR_INDEX__SILOED_NOTE_HASH, + GENERATOR_INDEX__SILOED_NOTE_HASH ) } @@ -71,10 +68,7 @@ pub fn silo_note_hash(note_hash: ScopedNoteHash, tx_hash: Field, note_index_in_t } pub fn compute_siloed_nullifier(app: AztecAddress, nullifier: Field) -> Field { - poseidon2_hash_with_separator( - [app.to_field(), nullifier], - GENERATOR_INDEX__OUTER_NULLIFIER, - ) + poseidon2_hash_with_separator([app.to_field(), nullifier], GENERATOR_INDEX__OUTER_NULLIFIER) } pub fn silo_nullifier(nullifier: ScopedNullifier) -> Field { @@ -90,9 +84,7 @@ pub fn silo_encrypted_log_hash(log_hash: ScopedLogHash) -> Field { if log_hash.contract_address.is_zero() { 0 } else { - accumulate_sha256( - [log_hash.contract_address.to_field(), log_hash.log_hash.value], - ) + accumulate_sha256([log_hash.contract_address.to_field(), log_hash.log_hash.value]) } } @@ -102,10 +94,12 @@ pub fn mask_encrypted_log_hash(scoped_log: ScopedEncryptedLogHash) -> AztecAddre } else if (scoped_log.log_hash.randomness == 0) { scoped_log.contract_address } else { - AztecAddress::from_field(poseidon2_hash_with_separator( - [scoped_log.contract_address.to_field(), scoped_log.log_hash.randomness], - 0, - )) + AztecAddress::from_field( + poseidon2_hash_with_separator( + [scoped_log.contract_address.to_field(), scoped_log.log_hash.randomness], + 0 + ) + ) } } @@ -125,9 +119,7 @@ pub fn merkle_hash(left: Field, right: Field) -> Field { poseidon2_hash([left, right]) } -pub fn stdlib_recursion_verification_key_compress_native_vk( - _vk: VerificationKey, -) -> Field { +pub fn stdlib_recursion_verification_key_compress_native_vk(_vk: VerificationKey) -> Field { // Original cpp code // stdlib::recursion::verification_key::compress_native(private_call.vk, GeneratorIndex::VK); // The above cpp method is only ever called on verification key, so it has been special cased here @@ -140,12 +132,11 @@ pub fn compute_l2_to_l1_hash( recipient: EthAddress, content: Field, rollup_version_id: Field, - chain_id: Field, + chain_id: Field ) -> Field { let mut bytes: BoundedVec = BoundedVec::new(); - let inputs = - [contract_address.to_field(), rollup_version_id, recipient.to_field(), chain_id, content]; + let inputs = [contract_address.to_field(), rollup_version_id, recipient.to_field(), chain_id, content]; for i in 0..inputs.len() { // TODO are bytes be in fr.to_buffer() ? let item_bytes: [u8; 32] = inputs[i].to_be_bytes(); @@ -157,11 +148,7 @@ pub fn compute_l2_to_l1_hash( sha256_to_field(bytes.storage) } -pub fn silo_l2_to_l1_message( - msg: ScopedL2ToL1Message, - rollup_version_id: Field, - chain_id: Field, -) -> Field { +pub fn silo_l2_to_l1_message(msg: ScopedL2ToL1Message, rollup_version_id: Field, chain_id: Field) -> Field { if msg.contract_address.is_zero() { 0 } else { @@ -170,7 +157,7 @@ pub fn silo_l2_to_l1_message( msg.message.recipient, msg.message.content, rollup_version_id, - chain_id, + chain_id ) } } @@ -266,10 +253,12 @@ pub fn poseidon2_hash(inputs: [Field; N]) -> Field { } #[no_predicates] -pub fn poseidon2_hash_with_separator(inputs: [Field; N], separator: T) -> Field +pub fn poseidon2_hash_with_separator( + inputs: [Field; N], + separator: T +) -> Field where - T: ToField, -{ + T: ToField, { // We manually hash the inputs here, since we cannot express with the type system a constant size inputs array of N + 1 let in_len = N + 1; let two_pow_64 = 18446744073709551616; @@ -286,8 +275,7 @@ where pub fn poseidon2_hash_with_separator_slice(inputs: [Field], separator: T) -> Field where - T: ToField, -{ + T: ToField, { let in_len = inputs.len() + 1; let two_pow_64 = 18446744073709551616; let iv: Field = (in_len as Field) * two_pow_64; @@ -341,7 +329,7 @@ fn smoke_sha256_to_field() { 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, + 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159 ]; let result = sha256_to_field(full_buffer); @@ -358,18 +346,11 @@ fn smoke_sha256_to_field() { #[test] fn compute_l2_l1_hash() { // All zeroes - let hash_result = - compute_l2_to_l1_hash(AztecAddress::from_field(0), EthAddress::zero(), 0, 0, 0); + let hash_result = compute_l2_to_l1_hash(AztecAddress::from_field(0), EthAddress::zero(), 0, 0, 0); assert(hash_result == 0xb393978842a0fa3d3e1470196f098f473f9678e72463cb65ec4ab5581856c2); // Non-zero case - let hash_result = compute_l2_to_l1_hash( - AztecAddress::from_field(1), - EthAddress::from_field(3), - 5, - 2, - 4, - ); + let hash_result = compute_l2_to_l1_hash(AztecAddress::from_field(1), EthAddress::from_field(3), 5, 2, 4); assert(hash_result == 0x3f88c1044a05e5340ed20466276500f6d45ca5603913b9091e957161734e16); } @@ -380,11 +361,11 @@ fn silo_l2_to_l1_message_matches_typescript() { let hash = silo_l2_to_l1_message( ScopedL2ToL1Message { - message: L2ToL1Message { recipient: EthAddress::from_field(1), content: 2, counter: 0 }, - contract_address: AztecAddress::from_field(3), - }, + message: L2ToL1Message { recipient: EthAddress::from_field(1), content: 2, counter: 0 }, + contract_address: AztecAddress::from_field(3) + }, version, - chainId, + chainId ); // The following value was generated by `l2_to_l1_message.test.ts` diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/header.nr b/noir-projects/noir-protocol-circuits/crates/types/src/header.nr index d56fa590b9f..42fd0f0034d 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/header.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/header.nr @@ -1,14 +1,15 @@ use crate::{ abis::{ - append_only_tree_snapshot::{AppendOnlyTreeSnapshot, APPEND_ONLY_TREE_SNAPSHOT_LENGTH}, - global_variables::GlobalVariables, - }, + append_only_tree_snapshot::{AppendOnlyTreeSnapshot, APPEND_ONLY_TREE_SNAPSHOT_LENGTH}, + global_variables::GlobalVariables +}, constants::{ - GENERATOR_INDEX__BLOCK_HASH, GLOBAL_VARIABLES_LENGTH, HEADER_LENGTH, STATE_REFERENCE_LENGTH, - CONTENT_COMMITMENT_LENGTH, - }, hash::poseidon2_hash_with_separator, state_reference::StateReference, + GENERATOR_INDEX__BLOCK_HASH, GLOBAL_VARIABLES_LENGTH, HEADER_LENGTH, STATE_REFERENCE_LENGTH, + CONTENT_COMMITMENT_LENGTH +}, + hash::poseidon2_hash_with_separator, state_reference::StateReference, traits::{Deserialize, Empty, Hash, Serialize}, utils::arr_copy_slice, - content_commitment::ContentCommitment, + content_commitment::ContentCommitment }; // docs:start:header @@ -49,19 +50,16 @@ impl Deserialize for Header { fn deserialize(serialized: [Field; HEADER_LENGTH]) -> Self { let mut offset = 0; - let last_archive_fields = - arr_copy_slice(serialized, [0; APPEND_ONLY_TREE_SNAPSHOT_LENGTH], offset); + let last_archive_fields = arr_copy_slice(serialized, [0; APPEND_ONLY_TREE_SNAPSHOT_LENGTH], offset); offset = offset + APPEND_ONLY_TREE_SNAPSHOT_LENGTH; - let content_commitment_fields = - arr_copy_slice(serialized, [0; CONTENT_COMMITMENT_LENGTH], offset); + let content_commitment_fields = arr_copy_slice(serialized, [0; CONTENT_COMMITMENT_LENGTH], offset); offset = offset + CONTENT_COMMITMENT_LENGTH; let state_fields = arr_copy_slice(serialized, [0; STATE_REFERENCE_LENGTH], offset); offset = offset + STATE_REFERENCE_LENGTH; - let global_variables_fields = - arr_copy_slice(serialized, [0; GLOBAL_VARIABLES_LENGTH], offset); + let global_variables_fields = arr_copy_slice(serialized, [0; GLOBAL_VARIABLES_LENGTH], offset); offset = offset + GLOBAL_VARIABLES_LENGTH; let total_fees = serialized[offset]; @@ -71,7 +69,7 @@ impl Deserialize for Header { content_commitment: ContentCommitment::deserialize(content_commitment_fields), state: StateReference::deserialize(state_fields), global_variables: GlobalVariables::deserialize(global_variables_fields), - total_fees, + total_fees } } } @@ -83,7 +81,7 @@ impl Empty for Header { content_commitment: ContentCommitment::empty(), state: StateReference::empty(), global_variables: GlobalVariables::empty(), - total_fees: 0, + total_fees: 0 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/lib.nr b/noir-projects/noir-protocol-circuits/crates/types/src/lib.nr index 4fa82de35ff..348b531c597 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/lib.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/lib.nr @@ -34,5 +34,5 @@ mod meta; pub use abis::kernel_circuit_public_inputs::{ KernelCircuitPublicInputs, PrivateKernelCircuitPublicInputs, PublicKernelCircuitPublicInputs, - VMCircuitPublicInputs, + VMCircuitPublicInputs }; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/append_only_tree.nr b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/append_only_tree.nr index 61f38065ef8..85c9503593e 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/append_only_tree.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/append_only_tree.nr @@ -1,6 +1,6 @@ use crate::{ abis::append_only_tree_snapshot::AppendOnlyTreeSnapshot, - merkle_tree::{membership::assert_check_membership, root::root_from_sibling_path}, + merkle_tree::{membership::assert_check_membership, root::root_from_sibling_path} }; pub fn insert_subtree_to_snapshot_tree( @@ -8,7 +8,7 @@ pub fn insert_subtree_to_snapshot_tree( sibling_path: [Field; N], empty_subtree_root: Field, subtree_root_to_insert: Field, - subtree_depth: u8, + subtree_depth: u8 ) -> AppendOnlyTreeSnapshot { // TODO(Lasse): Sanity check len of sibling_path > height of subtree // TODO(Lasse): Ensure height of subtree is correct (eg 3 for commitments, 1 for contracts) @@ -19,22 +19,18 @@ pub fn insert_subtree_to_snapshot_tree( empty_subtree_root, leaf_index_at_depth as Field, sibling_path, - snapshot.root, + snapshot.root ); // if index of leaf is x, index of its parent is x/2 or x >> 1. We need to find the parent `subtree_depth` levels up. let new_root = root_from_sibling_path( subtree_root_to_insert, leaf_index_at_depth as Field, - sibling_path, + sibling_path ); // 2^subtree_depth is the number of leaves added. 2^x = 1 << x - let new_next_available_leaf_index = - (snapshot.next_available_leaf_index as u64) + (1 << (subtree_depth as u8)); + let new_next_available_leaf_index = (snapshot.next_available_leaf_index as u64) + (1 << (subtree_depth as u8)); - AppendOnlyTreeSnapshot { - root: new_root, - next_available_leaf_index: new_next_available_leaf_index as u32, - } + AppendOnlyTreeSnapshot { root: new_root, next_available_leaf_index: new_next_available_leaf_index as u32 } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/indexed_tree.nr b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/indexed_tree.nr index aa44d2c84f5..a15c5612a38 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/indexed_tree.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/indexed_tree.nr @@ -3,12 +3,20 @@ mod check_valid_low_leaf; use crate::{ abis::append_only_tree_snapshot::AppendOnlyTreeSnapshot, merkle_tree::{ - membership::{assert_check_membership, MembershipWitness}, - root::{calculate_subtree_root, calculate_empty_tree_root, root_from_sibling_path}, - }, traits::{Empty, Hash, is_empty}, utils::arrays::check_permutation, + membership::{assert_check_membership, MembershipWitness}, + root::{calculate_subtree_root, calculate_empty_tree_root, root_from_sibling_path} +}, + traits::{Empty, Hash, is_empty}, utils::arrays::check_permutation }; -pub fn batch_insert( +pub fn batch_insert< + Value, + Leaf, + let SubtreeWidth: u32, + let SiblingPathLength: u32, + let SubtreeHeight: u32, + let TreeHeight: u32 +>( start_snapshot: AppendOnlyTreeSnapshot, values_to_insert: [Value; SubtreeWidth], sorted_values: [Value; SubtreeWidth], @@ -20,12 +28,11 @@ pub fn batch_insert Leaf, build_insertion_leaf: fn(Value, Leaf) -> Leaf, _subtree_height: [Field; SubtreeHeight], - _tree_height: [Field; TreeHeight], + _tree_height: [Field; TreeHeight] ) -> AppendOnlyTreeSnapshot where Value: Eq + Empty, - Leaf: Hash + Empty, -{ + Leaf: Hash + Empty, { // A permutation to the values is provided to make the insertion use only one insertion strategy check_permutation(values_to_insert, sorted_values, sorted_values_indexes); @@ -47,7 +54,7 @@ where low_leaf_preimage.hash(), witness.leaf_index, witness.sibling_path, - current_tree_root, + current_tree_root ); let value_index = sorted_values_indexes[i]; @@ -56,7 +63,7 @@ where let updated_low_leaf = update_low_leaf( low_leaf_preimage, value, - start_insertion_index as u32 + value_index, + start_insertion_index as u32 + value_index ); current_tree_root = root_from_sibling_path( @@ -76,7 +83,7 @@ where empty_subtree_root, leaf_index_subtree_depth as Field, new_subtree_sibling_path, - current_tree_root, + current_tree_root ); // Create new subtree to insert into the whole indexed tree @@ -85,14 +92,7 @@ where // Calculate the new root // We are inserting a subtree rather than a full tree here let subtree_index = start_insertion_index >> (SubtreeHeight as u8); - let new_root = root_from_sibling_path( - subtree_root, - subtree_index as Field, - new_subtree_sibling_path, - ); + let new_root = root_from_sibling_path(subtree_root, subtree_index as Field, new_subtree_sibling_path); - AppendOnlyTreeSnapshot { - root: new_root, - next_available_leaf_index: start_insertion_index + (values_to_insert.len() as u32), - } + AppendOnlyTreeSnapshot { root: new_root, next_available_leaf_index: start_insertion_index + (values_to_insert.len() as u32) } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/indexed_tree/check_valid_low_leaf.nr b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/indexed_tree/check_valid_low_leaf.nr index f7f625ce836..b6af17c5e94 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/indexed_tree/check_valid_low_leaf.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/indexed_tree/check_valid_low_leaf.nr @@ -1,9 +1,11 @@ use crate::merkle_tree::leaf_preimage::IndexedTreeLeafPreimage; -pub fn assert_check_valid_low_leaf(key: Field, low_leaf_preimage: LEAF_PREIMAGE) +pub fn assert_check_valid_low_leaf( + key: Field, + low_leaf_preimage: LEAF_PREIMAGE +) where - LEAF_PREIMAGE: IndexedTreeLeafPreimage, -{ + LEAF_PREIMAGE: IndexedTreeLeafPreimage, { let low_key = low_leaf_preimage.get_key(); let next_key = low_leaf_preimage.get_next_key(); @@ -14,7 +16,7 @@ where mod tests { use crate::merkle_tree::{ leaf_preimage::IndexedTreeLeafPreimage, - indexed_tree::check_valid_low_leaf::assert_check_valid_low_leaf, + indexed_tree::check_valid_low_leaf::assert_check_valid_low_leaf }; struct TestLeafPreimage { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/membership.nr b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/membership.nr index 62a4ac53bc5..5748eee2966 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/membership.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/membership.nr @@ -1,9 +1,9 @@ use crate::{ merkle_tree::{ - leaf_preimage::IndexedTreeLeafPreimage, - indexed_tree::check_valid_low_leaf::assert_check_valid_low_leaf, - root::root_from_sibling_path, - }, traits::Empty, + leaf_preimage::IndexedTreeLeafPreimage, + indexed_tree::check_valid_low_leaf::assert_check_valid_low_leaf, root::root_from_sibling_path +}, + traits::Empty }; pub struct MembershipWitness { @@ -17,22 +17,12 @@ impl Empty for MembershipWitness { } } -pub fn check_membership( - leaf: Field, - index: Field, - sibling_path: [Field; N], - root: Field, -) -> bool { +pub fn check_membership(leaf: Field, index: Field, sibling_path: [Field; N], root: Field) -> bool { let calculated_root = root_from_sibling_path(leaf, index, sibling_path); calculated_root == root } -pub fn assert_check_membership( - leaf: Field, - index: Field, - sibling_path: [Field; TREE_HEIGHT], - root: Field, -) { +pub fn assert_check_membership(leaf: Field, index: Field, sibling_path: [Field; TREE_HEIGHT], root: Field) { assert(check_membership(leaf, index, sibling_path, root), "membership check failed"); } @@ -40,18 +30,17 @@ pub fn assert_check_non_membership( key: Field, low_leaf_preimage: LEAF_PREIMAGE, low_leaf_membership_witness: MembershipWitness, - tree_root: Field, + tree_root: Field ) where - LEAF_PREIMAGE: IndexedTreeLeafPreimage, -{ + LEAF_PREIMAGE: IndexedTreeLeafPreimage, { assert_check_valid_low_leaf(key, low_leaf_preimage); let low_leaf_exists = check_membership( low_leaf_preimage.as_leaf(), low_leaf_membership_witness.leaf_index, low_leaf_membership_witness.sibling_path, - tree_root, + tree_root ); assert(low_leaf_exists, "Low leaf does not exist"); } @@ -63,11 +52,10 @@ pub fn conditionally_assert_check_membership, - tree_root: Field, + tree_root: Field ) where - LEAF_PREIMAGE: IndexedTreeLeafPreimage, -{ + LEAF_PREIMAGE: IndexedTreeLeafPreimage, { if exists { assert(key == leaf_preimage.get_key(), "Key does not match the key of the leaf preimage"); } else { @@ -78,19 +66,20 @@ where leaf_preimage.as_leaf(), membership_witness.leaf_index, membership_witness.sibling_path, - tree_root, + tree_root ); } mod tests { use crate::{ merkle_tree::{ - leaf_preimage::{IndexedTreeLeafPreimage, LeafPreimage}, - membership::{ - assert_check_membership, assert_check_non_membership, check_membership, - conditionally_assert_check_membership, MembershipWitness, - }, - }, tests::merkle_tree_utils::NonEmptyMerkleTree, + leaf_preimage::{IndexedTreeLeafPreimage, LeafPreimage}, + membership::{ + assert_check_membership, assert_check_non_membership, check_membership, + conditionally_assert_check_membership, MembershipWitness + } + }, + tests::merkle_tree_utils::NonEmptyMerkleTree }; use std::hash::pedersen_hash; @@ -135,7 +124,7 @@ mod tests { leaf_preimages.map(|leaf_preimage: TestLeafPreimage| leaf_preimage.as_leaf()), [0; 3], [0; 1], - [0; 2], + [0; 2] ) } @@ -147,7 +136,7 @@ mod tests { leaf, leaf_index, tree.get_sibling_path(leaf_index as u32), - tree_root, + tree_root ) } @@ -159,7 +148,7 @@ mod tests { leaf, leaf_index, tree.get_sibling_path(leaf_index as u32), - tree_root, + tree_root ); } @@ -175,19 +164,12 @@ mod tests { assert_check_non_membership( key, leaf_preimage, - MembershipWitness { - leaf_index: low_leaf_index as Field, - sibling_path: tree.get_sibling_path(low_leaf_index), - }, - tree_root, + MembershipWitness { leaf_index: low_leaf_index as Field, sibling_path: tree.get_sibling_path(low_leaf_index) }, + tree_root ); } - fn conditionally_assert_check_membership_at_index( - exists: bool, - low_leaf_index: u32, - key: Field, - ) { + fn conditionally_assert_check_membership_at_index(exists: bool, low_leaf_index: u32, key: Field) { let tree = build_tree(); let tree_root = tree.get_root(); let leaf_preimage = if low_leaf_index as u32 < leaf_preimages.len() { @@ -200,11 +182,8 @@ mod tests { key, exists, leaf_preimage, - MembershipWitness { - leaf_index: low_leaf_index as Field, - sibling_path: tree.get_sibling_path(low_leaf_index), - }, - tree_root, + MembershipWitness { leaf_index: low_leaf_index as Field, sibling_path: tree.get_sibling_path(low_leaf_index) }, + tree_root ); } @@ -240,7 +219,7 @@ mod tests { leaf_preimages[0].as_leaf(), 0, tree.get_sibling_path(0), - tree_root, + tree_root ); assert_eq(res, false); } @@ -254,7 +233,7 @@ mod tests { leaf_preimages[0].as_leaf(), 0, tree.get_sibling_path(0), - tree_root, + tree_root ); } @@ -288,7 +267,7 @@ mod tests { 55, fake_leaf, MembershipWitness { leaf_index: 1, sibling_path: tree.get_sibling_path(1) }, - tree_root, + tree_root ); } @@ -328,7 +307,7 @@ mod tests { exists, fake_leaf, MembershipWitness { leaf_index: 1, sibling_path: tree.get_sibling_path(1) }, - tree_root, + tree_root ); } @@ -343,7 +322,7 @@ mod tests { exists, fake_leaf, MembershipWitness { leaf_index: 1, sibling_path: tree.get_sibling_path(1) }, - tree_root, + tree_root ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/merkle_tree.nr b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/merkle_tree.nr index 697d841d82b..682a14a8c02 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/merkle_tree.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/merkle_tree.nr @@ -37,11 +37,7 @@ impl MerkleTree { } pub fn sibling_index(index: u32) -> u32 { - if index % 2 == 0 { - index + 1 - } else { - index - 1 - } + if index % 2 == 0 { index + 1 } else { index - 1 } } fn get_sibling_path(self, leaf_index: u32) -> [Field; K] { @@ -73,9 +69,5 @@ impl MerkleTree { } pub fn sibling_index(index: u32) -> u32 { - if index % 2 == 0 { - index + 1 - } else { - index - 1 - } + if index % 2 == 0 { index + 1 } else { index - 1 } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/mod.nr index 5c306bbc575..a88c4b01e9a 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/mod.nr @@ -9,7 +9,7 @@ mod variable_merkle_tree; pub use leaf_preimage::{IndexedTreeLeafPreimage, LeafPreimage}; pub use membership::{ assert_check_membership, assert_check_non_membership, check_membership, - conditionally_assert_check_membership, MembershipWitness, + conditionally_assert_check_membership, MembershipWitness }; pub use merkle_tree::MerkleTree; pub use variable_merkle_tree::VariableMerkleTree; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/root.nr b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/root.nr index 79f33ca5c0c..c16bfeac356 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/root.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/root.nr @@ -13,7 +13,7 @@ use crate::{hash::merkle_hash, merkle_tree::merkle_tree::MerkleTree}; pub fn root_from_sibling_path( leaf: Field, leaf_index: Field, - sibling_path: [Field; N], + sibling_path: [Field; N] ) -> Field { let mut node = leaf; let indices: [u1; N] = leaf_index.to_le_bits(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/variable_merkle_tree.nr b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/variable_merkle_tree.nr index 483670f475b..dca10040a39 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/variable_merkle_tree.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/merkle_tree/variable_merkle_tree.nr @@ -33,13 +33,15 @@ impl VariableMerkleTree { // pub fn new_sha(leaves: [Field; N], num_non_empty_leaves: u32) -> Self { // Find size of tree required - let height = unsafe { get_height(num_non_empty_leaves, 0) }; + let height = unsafe { + get_height(num_non_empty_leaves, 0) + }; let next_power_2 = 2 << height; let prev_power_2 = next_power_2 / 2; assert( (num_non_empty_leaves == 0) - | (num_non_empty_leaves == 1) - | (num_non_empty_leaves > prev_power_2), + | (num_non_empty_leaves == 1) + | (num_non_empty_leaves > prev_power_2) ); assert(num_non_empty_leaves <= next_power_2); // hash base layer @@ -92,7 +94,7 @@ impl VariableMerkleTree { mod tests { use crate::{ merkle_tree::{variable_merkle_tree::VariableMerkleTree, merkle_tree::MerkleTree}, - hash::accumulate_sha256, + hash::accumulate_sha256 }; fn generate_test_array(non_empty_items: u32) -> [Field; 100] { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/messaging/l2_to_l1_message.nr b/noir-projects/noir-protocol-circuits/crates/types/src/messaging/l2_to_l1_message.nr index 0ff95b3e140..e083d269d50 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/messaging/l2_to_l1_message.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/messaging/l2_to_l1_message.nr @@ -2,7 +2,7 @@ use crate::{ address::{AztecAddress, EthAddress}, constants::{L2_TO_L1_MESSAGE_LENGTH, SCOPED_L2_TO_L1_MESSAGE_LENGTH}, abis::side_effect::{Ordered, Scoped}, traits::{Deserialize, Empty, Serialize}, - utils::{arrays::array_concat, reader::Reader}, + utils::{arrays::array_concat, reader::Reader} }; // Note: Not to be confused with L2ToL1Msg in Solidity @@ -40,11 +40,7 @@ impl Serialize for L2ToL1Message { impl Deserialize for L2ToL1Message { fn deserialize(values: [Field; L2_TO_L1_MESSAGE_LENGTH]) -> Self { - Self { - recipient: EthAddress::from_field(values[0]), - content: values[1], - counter: values[2] as u32, - } + Self { recipient: EthAddress::from_field(values[0]), content: values[1], counter: values[2] as u32 } } } @@ -63,12 +59,8 @@ impl ScopedL2ToL1Message { pub fn expose_to_public(self) -> Self { // Hide the counter when exposing to public. Self { - message: L2ToL1Message { - recipient: self.message.recipient, - content: self.message.content, - counter: 0, - }, - contract_address: self.contract_address, + message: L2ToL1Message { recipient: self.message.recipient, content: self.message.content, counter: 0 }, + contract_address: self.contract_address } } } @@ -96,10 +88,7 @@ impl Eq for ScopedL2ToL1Message { impl Empty for ScopedL2ToL1Message { fn empty() -> Self { - ScopedL2ToL1Message { - message: L2ToL1Message::empty(), - contract_address: AztecAddress::empty(), - } + ScopedL2ToL1Message { message: L2ToL1Message::empty(), contract_address: AztecAddress::empty() } } } @@ -114,7 +103,7 @@ impl Deserialize for ScopedL2ToL1Message { let mut reader = Reader::new(values); let res = Self { message: reader.read_struct(L2ToL1Message::deserialize), - contract_address: reader.read_struct(AztecAddress::deserialize), + contract_address: reader.read_struct(AztecAddress::deserialize) }; reader.finish(); res diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/meta/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/meta/mod.nr index d56ef6d87ee..0fea8efbd7d 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/meta/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/meta/mod.nr @@ -5,7 +5,7 @@ pub comptime fn pack_from_fields( typ: Type, buffer: Quoted, already_consumed: u32, - replacements: [(Quoted, Quoted)], + replacements: [(Quoted, Quoted)] ) -> (Quoted, u32) { let mut result = quote {}; let mut consumed: u32 = 0; @@ -33,7 +33,7 @@ pub comptime fn pack_from_fields( field_type, quote { $buffer }, consumed + already_consumed, - replacements, + replacements ); consumed += consumed_by_field; deserialized_fields_list = @@ -55,7 +55,7 @@ pub comptime fn pack_from_fields( element_type, quote { $buffer }, consumed + already_consumed, - replacements, + replacements ); array_fields_list = array_fields_list.push_back(deserialized_field); consumed += consumed_by_field; @@ -72,7 +72,7 @@ pub comptime fn pack_from_fields( quote { u8}.as_type(), quote { $buffer }, consumed + already_consumed, - replacements, + replacements ); byte_list = byte_list.push_back(deserialized_field); consumed += consumed_by_field; @@ -80,9 +80,7 @@ pub comptime fn pack_from_fields( let bytes = byte_list.join(quote {,}); result = quote { [ $bytes ].as_str_unchecked() }; } else { - panic( - f"Unsupported type for serialization of argument {name} and type {typ}", - ) + panic(f"Unsupported type for serialization of argument {name} and type {typ}") } } else { result = replacement; @@ -104,7 +102,8 @@ pub comptime fn flatten_to_fields(name: Quoted, typ: Type, omit: [Quoted]) -> ([ // For struct we pref let nested_struct = typ.as_struct().unwrap(); let params = nested_struct.0.fields(); - let struct_flattened = params.map(|(param_name, param_type): (Quoted, Type)| { + let struct_flattened = params.map( + |(param_name, param_type): (Quoted, Type)| { let maybe_prefixed_name = if name == quote {} { // Triggered when the param name is of a value available in the current scope (e.g. a function // argument) --> then we don't prefix the name with anything. @@ -115,14 +114,15 @@ pub comptime fn flatten_to_fields(name: Quoted, typ: Type, omit: [Quoted]) -> ([ quote { $name.$param_name } }; flatten_to_fields(quote {$maybe_prefixed_name}, param_type, omit) - }); + } + ); let struct_flattened_fields = struct_flattened.fold( &[], - |acc: [Quoted], (fields, _): (_, [Quoted])| acc.append(fields), + |acc: [Quoted], (fields, _): (_, [Quoted])| acc.append(fields) ); let struct_flattened_aux_vars = struct_flattened.fold( &[], - |acc: [Quoted], (_, aux_vars): ([Quoted], _)| acc.append(aux_vars), + |acc: [Quoted], (_, aux_vars): ([Quoted], _)| acc.append(aux_vars) ); fields = fields.append(struct_flattened_fields); aux_vars = aux_vars.append(struct_flattened_aux_vars); @@ -131,8 +131,7 @@ pub comptime fn flatten_to_fields(name: Quoted, typ: Type, omit: [Quoted]) -> ([ let (element_type, array_len) = typ.as_array().unwrap(); let array_len = array_len.as_constant().unwrap(); for i in 0..array_len { - let (element_fields, element_aux_vars) = - flatten_to_fields(quote { $name[$i] }, element_type, omit); + let (element_fields, element_aux_vars) = flatten_to_fields(quote { $name[$i] }, element_type, omit); fields = fields.append(element_fields); aux_vars = aux_vars.append(element_aux_vars); } @@ -154,9 +153,7 @@ pub comptime fn flatten_to_fields(name: Quoted, typ: Type, omit: [Quoted]) -> ([ } aux_vars = aux_vars.push_back(as_bytes); } else { - panic( - f"Unsupported type for serialization of argument {name} and type {typ}", - ) + panic(f"Unsupported type for serialization of argument {name} and type {typ}") } } (fields, aux_vars) @@ -242,16 +239,13 @@ fn has_array_test() { #[test] fn fancier_test() { - let fancier = - Fancier { a: Smol { a: 1, b: 2 }, b: [0, 1], c: [1, 2, 3], d: "metaprogramming!" }; + let fancier = Fancier { a: Smol { a: 1, b: 2 }, b: [0, 1], c: [1, 2, 3], d: "metaprogramming!" }; let serialized = fancier.serialize(); assert( - serialized - == [ - 1, 2, 0, 1, 1, 2, 3, 0x6d, 0x65, 0x74, 0x61, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, - 0x6d, 0x6d, 0x69, 0x6e, 0x67, 0x21, - ], - serialized, + serialized == [ + 1, 2, 0, 1, 1, 2, 3, 0x6d, 0x65, 0x74, 0x61, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, + 0x6d, 0x6d, 0x69, 0x6e, 0x67, 0x21 + ], serialized ); let deserialized = Fancier::deserialize(serialized); assert(deserialized == fancier); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/partial_state_reference.nr b/noir-projects/noir-protocol-circuits/crates/types/src/partial_state_reference.nr index 0384aa58b94..0390c3d8dc3 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/partial_state_reference.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/partial_state_reference.nr @@ -1,6 +1,6 @@ use crate::{ - abis::append_only_tree_snapshot::AppendOnlyTreeSnapshot, - constants::PARTIAL_STATE_REFERENCE_LENGTH, traits::{Deserialize, Empty, Serialize}, + abis::append_only_tree_snapshot::AppendOnlyTreeSnapshot, constants::PARTIAL_STATE_REFERENCE_LENGTH, + traits::{Deserialize, Empty, Serialize} }; pub struct PartialStateReference { @@ -29,7 +29,7 @@ impl Serialize for PartialStateReference { serialized_nullifier_tree[0], serialized_nullifier_tree[1], serialized_public_data_tree[0], - serialized_public_data_tree[1], + serialized_public_data_tree[1] ] } } @@ -39,7 +39,7 @@ impl Deserialize for PartialStateReference { PartialStateReference { note_hash_tree: AppendOnlyTreeSnapshot::deserialize([serialized[0], serialized[1]]), nullifier_tree: AppendOnlyTreeSnapshot::deserialize([serialized[2], serialized[3]]), - public_data_tree: AppendOnlyTreeSnapshot::deserialize([serialized[4], serialized[5]]), + public_data_tree: AppendOnlyTreeSnapshot::deserialize([serialized[4], serialized[5]]) } } } @@ -49,7 +49,7 @@ impl Empty for PartialStateReference { Self { note_hash_tree: AppendOnlyTreeSnapshot::zero(), nullifier_tree: AppendOnlyTreeSnapshot::zero(), - public_data_tree: AppendOnlyTreeSnapshot::zero(), + public_data_tree: AppendOnlyTreeSnapshot::zero() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/public_keys.nr b/noir-projects/noir-protocol-circuits/crates/types/src/public_keys.nr index 65bb1defab9..6bc3503b280 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/public_keys.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/public_keys.nr @@ -1,10 +1,10 @@ use crate::{ address::public_keys_hash::PublicKeysHash, constants::{ - GENERATOR_INDEX__PUBLIC_KEYS_HASH, DEFAULT_NPK_M_X, DEFAULT_NPK_M_Y, DEFAULT_IVPK_M_X, - DEFAULT_IVPK_M_Y, DEFAULT_OVPK_M_X, DEFAULT_OVPK_M_Y, DEFAULT_TPK_M_X, DEFAULT_TPK_M_Y, - }, hash::poseidon2_hash_with_separator, point::POINT_LENGTH, - traits::{Deserialize, Serialize, Hash}, + GENERATOR_INDEX__PUBLIC_KEYS_HASH, DEFAULT_NPK_M_X, DEFAULT_NPK_M_Y, DEFAULT_IVPK_M_X, + DEFAULT_IVPK_M_Y, DEFAULT_OVPK_M_X, DEFAULT_OVPK_M_Y, DEFAULT_TPK_M_X, DEFAULT_TPK_M_Y +}, + hash::poseidon2_hash_with_separator, point::POINT_LENGTH, traits::{Deserialize, Serialize, Hash} }; use dep::std::embedded_curve_ops::EmbeddedCurvePoint as Point; @@ -105,18 +105,10 @@ impl Serialize for TpkM { impl Default for PublicKeys { fn default() -> Self { PublicKeys { - npk_m: NpkM { - inner: Point { x: DEFAULT_NPK_M_X, y: DEFAULT_NPK_M_Y, is_infinite: false }, - }, - ivpk_m: IvpkM { - inner: Point { x: DEFAULT_IVPK_M_X, y: DEFAULT_IVPK_M_Y, is_infinite: false }, - }, - ovpk_m: OvpkM { - inner: Point { x: DEFAULT_OVPK_M_X, y: DEFAULT_OVPK_M_Y, is_infinite: false }, - }, - tpk_m: TpkM { - inner: Point { x: DEFAULT_TPK_M_X, y: DEFAULT_TPK_M_Y, is_infinite: false }, - }, + npk_m: NpkM { inner: Point { x: DEFAULT_NPK_M_X, y: DEFAULT_NPK_M_Y, is_infinite: false } }, + ivpk_m: IvpkM { inner: Point { x: DEFAULT_IVPK_M_X, y: DEFAULT_IVPK_M_Y, is_infinite: false } }, + ovpk_m: OvpkM { inner: Point { x: DEFAULT_OVPK_M_X, y: DEFAULT_OVPK_M_Y, is_infinite: false } }, + tpk_m: TpkM { inner: Point { x: DEFAULT_TPK_M_X, y: DEFAULT_TPK_M_Y, is_infinite: false } } } } } @@ -132,10 +124,7 @@ impl Eq for PublicKeys { impl PublicKeys { pub fn hash(self) -> PublicKeysHash { - PublicKeysHash::from_field(poseidon2_hash_with_separator( - self.serialize(), - GENERATOR_INDEX__PUBLIC_KEYS_HASH as Field, - )) + PublicKeysHash::from_field(poseidon2_hash_with_separator(self.serialize(), GENERATOR_INDEX__PUBLIC_KEYS_HASH as Field)) } } @@ -153,7 +142,7 @@ impl Serialize for PublicKeys { self.ovpk_m.inner.is_infinite as Field, self.tpk_m.inner.x, self.tpk_m.inner.y, - self.tpk_m.inner.is_infinite as Field, + self.tpk_m.inner.is_infinite as Field ] } } @@ -161,34 +150,10 @@ impl Serialize for PublicKeys { impl Deserialize for PublicKeys { fn deserialize(serialized: [Field; PUBLIC_KEYS_LENGTH]) -> PublicKeys { PublicKeys { - npk_m: NpkM { - inner: Point { - x: serialized[0], - y: serialized[1], - is_infinite: serialized[2] as bool, - }, - }, - ivpk_m: IvpkM { - inner: Point { - x: serialized[3], - y: serialized[4], - is_infinite: serialized[5] as bool, - }, - }, - ovpk_m: OvpkM { - inner: Point { - x: serialized[6], - y: serialized[7], - is_infinite: serialized[8] as bool, - }, - }, - tpk_m: TpkM { - inner: Point { - x: serialized[9], - y: serialized[10], - is_infinite: serialized[11] as bool, - }, - }, + npk_m: NpkM { inner: Point { x: serialized[0], y: serialized[1], is_infinite: serialized[2] as bool } }, + ivpk_m: IvpkM { inner: Point { x: serialized[3], y: serialized[4], is_infinite: serialized[5] as bool } }, + ovpk_m: OvpkM { inner: Point { x: serialized[6], y: serialized[7], is_infinite: serialized[8] as bool } }, + tpk_m: TpkM { inner: Point { x: serialized[9], y: serialized[10], is_infinite: serialized[11] as bool } } } } } @@ -199,12 +164,11 @@ unconstrained fn compute_public_keys_hash() { npk_m: NpkM { inner: Point { x: 1, y: 2, is_infinite: false } }, ivpk_m: IvpkM { inner: Point { x: 3, y: 4, is_infinite: false } }, ovpk_m: OvpkM { inner: Point { x: 5, y: 6, is_infinite: false } }, - tpk_m: TpkM { inner: Point { x: 7, y: 8, is_infinite: false } }, + tpk_m: TpkM { inner: Point { x: 7, y: 8, is_infinite: false } } }; let actual = keys.hash(); - let expected_public_keys_hash = - 0x0fecd9a32db731fec1fded1b9ff957a1625c069245a3613a2538bd527068b0ad; + let expected_public_keys_hash = 0x0fecd9a32db731fec1fded1b9ff957a1625c069245a3613a2538bd527068b0ad; assert(actual.to_field() == expected_public_keys_hash); } @@ -225,7 +189,7 @@ unconstrained fn test_public_keys_serialization() { npk_m: NpkM { inner: Point { x: 1, y: 2, is_infinite: false } }, ivpk_m: IvpkM { inner: Point { x: 3, y: 4, is_infinite: false } }, ovpk_m: OvpkM { inner: Point { x: 5, y: 6, is_infinite: false } }, - tpk_m: TpkM { inner: Point { x: 7, y: 8, is_infinite: false } }, + tpk_m: TpkM { inner: Point { x: 7, y: 8, is_infinite: false } } }; let serialized = keys.serialize(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/recursion/proof.nr b/noir-projects/noir-protocol-circuits/crates/types/src/recursion/proof.nr index 4ebd589b4f0..6dc97c15c9e 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/recursion/proof.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/recursion/proof.nr @@ -1,6 +1,6 @@ use crate::{ traits::{Serialize, Deserialize, Empty}, - constants::{RECURSIVE_PROOF_LENGTH, NESTED_RECURSIVE_PROOF_LENGTH}, + constants::{RECURSIVE_PROOF_LENGTH, NESTED_RECURSIVE_PROOF_LENGTH} }; pub struct RecursiveProof { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/recursion/verification_key.nr b/noir-projects/noir-protocol-circuits/crates/types/src/recursion/verification_key.nr index 20d958d5dc3..eb0eccb2fe3 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/recursion/verification_key.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/recursion/verification_key.nr @@ -1,8 +1,6 @@ use crate::{ traits::{Serialize, Deserialize, Empty}, - constants::{ - HONK_VERIFICATION_KEY_LENGTH_IN_FIELDS, CLIENT_IVC_VERIFICATION_KEY_LENGTH_IN_FIELDS, - }, + constants::{HONK_VERIFICATION_KEY_LENGTH_IN_FIELDS, CLIENT_IVC_VERIFICATION_KEY_LENGTH_IN_FIELDS} }; pub struct VerificationKey { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/state_reference.nr b/noir-projects/noir-protocol-circuits/crates/types/src/state_reference.nr index 1bc4110d32f..b8f7322e98f 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/state_reference.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/state_reference.nr @@ -2,7 +2,7 @@ use crate::{ abis::append_only_tree_snapshot::{AppendOnlyTreeSnapshot, APPEND_ONLY_TREE_SNAPSHOT_LENGTH}, constants::{PARTIAL_STATE_REFERENCE_LENGTH, STATE_REFERENCE_LENGTH}, partial_state_reference::PartialStateReference, traits::{Deserialize, Empty, Serialize}, - utils::arr_copy_slice, + utils::arr_copy_slice }; pub struct StateReference { @@ -31,28 +31,21 @@ impl Deserialize for StateReference { fn deserialize(serialized: [Field; STATE_REFERENCE_LENGTH]) -> StateReference { let mut offset = 0; - let l1_to_l2_message_tree_fields = - arr_copy_slice(serialized, [0; APPEND_ONLY_TREE_SNAPSHOT_LENGTH], offset); + let l1_to_l2_message_tree_fields = arr_copy_slice(serialized, [0; APPEND_ONLY_TREE_SNAPSHOT_LENGTH], offset); offset = offset + APPEND_ONLY_TREE_SNAPSHOT_LENGTH; - let partial_fields = - arr_copy_slice(serialized, [0; PARTIAL_STATE_REFERENCE_LENGTH], offset); + let partial_fields = arr_copy_slice(serialized, [0; PARTIAL_STATE_REFERENCE_LENGTH], offset); StateReference { - l1_to_l2_message_tree: AppendOnlyTreeSnapshot::deserialize( - l1_to_l2_message_tree_fields, - ), - partial: PartialStateReference::deserialize(partial_fields), + l1_to_l2_message_tree: AppendOnlyTreeSnapshot::deserialize(l1_to_l2_message_tree_fields), + partial: PartialStateReference::deserialize(partial_fields) } } } impl Empty for StateReference { fn empty() -> Self { - Self { - l1_to_l2_message_tree: AppendOnlyTreeSnapshot::zero(), - partial: PartialStateReference::empty(), - } + Self { l1_to_l2_message_tree: AppendOnlyTreeSnapshot::zero(), partial: PartialStateReference::empty() } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/storage/map.nr b/noir-projects/noir-protocol-circuits/crates/types/src/storage/map.nr index 849d8a90252..79681f2074e 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/storage/map.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/storage/map.nr @@ -2,8 +2,7 @@ use crate::{hash::poseidon2_hash, traits::ToField}; pub fn derive_storage_slot_in_map(storage_slot: Field, key: K) -> Field where - K: ToField, -{ + K: ToField, { poseidon2_hash([storage_slot, key.to_field()]) } @@ -13,15 +12,12 @@ mod test { #[test] fn test_derive_storage_slot_in_map_matches_typescript() { let map_slot = 0x132258fb6962c4387ba659d9556521102d227549a386d39f0b22d1890d59c2b5; - let key = AztecAddress::from_field( - 0x302dbc2f9b50a73283d5fb2f35bc01eae8935615817a0b4219a057b2ba8a5a3f, - ); + let key = AztecAddress::from_field(0x302dbc2f9b50a73283d5fb2f35bc01eae8935615817a0b4219a057b2ba8a5a3f); let slot = derive_storage_slot_in_map(map_slot, key); // The following value was generated by `map_slot.test.ts` - let slot_from_typescript = - 0x15b9fe39449affd8b377461263e9d2b610b9ad40580553500b4e41d9cbd887ac; + let slot_from_typescript = 0x15b9fe39449affd8b377461263e9d2b610b9ad40580553500b4e41d9cbd887ac; assert_eq(slot, slot_from_typescript); } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixture_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixture_builder.nr index ad244b94ba5..d21fb24d06c 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixture_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixture_builder.nr @@ -1,67 +1,70 @@ use crate::{ abis::{ - gas::Gas, gas_settings::GasSettings, call_context::CallContext, - accumulated_data::{ - CombinedAccumulatedData, PrivateAccumulatedData, PrivateAccumulatedDataBuilder, - PublicAccumulatedData, PublicAccumulatedDataArrayLengths, PublicAccumulatedDataBuilder, - }, function_data::FunctionData, function_selector::FunctionSelector, - global_variables::GlobalVariables, combined_constant_data::CombinedConstantData, - enqueued_call_data::{EnqueuedCallData, Proof}, - kernel_circuit_public_inputs::{ - KernelCircuitPublicInputs, PrivateKernelCircuitPublicInputs, - PublicKernelCircuitPublicInputs, VMCircuitPublicInputs, - }, kernel_data::KernelData, public_kernel_data::PublicKernelData, - max_block_number::MaxBlockNumber, private_kernel_data::PrivateKernelData, - note_hash::{NoteHash, ScopedNoteHash}, nullifier::{Nullifier, ScopedNullifier}, - private_call_request::PrivateCallRequest, - private_circuit_public_inputs::PrivateCircuitPublicInputs, - private_kernel::private_call_data::PrivateCallData, - public_call_data::{Proof as PublicCallDataProof, PublicCallData}, - public_call_request::PublicCallRequest, - public_circuit_public_inputs::PublicCircuitPublicInputs, public_data_read::PublicDataRead, - public_data_update_request::PublicDataUpdateRequest, - public_inner_call_request::PublicInnerCallRequest, - read_request::{ReadRequest, ScopedReadRequest}, tree_leaf_read_request::TreeLeafReadRequest, - log_hash::{LogHash, NoteLogHash, ScopedLogHash, EncryptedLogHash, ScopedEncryptedLogHash}, - validation_requests::{ - KeyValidationRequest, KeyValidationRequestAndGenerator, PrivateValidationRequests, - PublicValidationRequests, PublicValidationRequestArrayLengths, RollupValidationRequests, - ScopedKeyValidationRequestAndGenerator, - }, - }, address::{AztecAddress, EthAddress, SaltedInitializationHash, PublicKeysHash}, + gas::Gas, gas_settings::GasSettings, call_context::CallContext, + accumulated_data::{ + CombinedAccumulatedData, PrivateAccumulatedData, PrivateAccumulatedDataBuilder, + PublicAccumulatedData, PublicAccumulatedDataArrayLengths, PublicAccumulatedDataBuilder +}, + function_data::FunctionData, function_selector::FunctionSelector, global_variables::GlobalVariables, + combined_constant_data::CombinedConstantData, enqueued_call_data::{EnqueuedCallData, Proof}, + kernel_circuit_public_inputs::{ + KernelCircuitPublicInputs, PrivateKernelCircuitPublicInputs, PublicKernelCircuitPublicInputs, + VMCircuitPublicInputs +}, + kernel_data::KernelData, public_kernel_data::PublicKernelData, max_block_number::MaxBlockNumber, + private_kernel_data::PrivateKernelData, note_hash::{NoteHash, ScopedNoteHash}, + nullifier::{Nullifier, ScopedNullifier}, private_call_request::PrivateCallRequest, + private_circuit_public_inputs::PrivateCircuitPublicInputs, + private_kernel::private_call_data::PrivateCallData, + public_call_data::{Proof as PublicCallDataProof, PublicCallData}, + public_call_request::PublicCallRequest, public_circuit_public_inputs::PublicCircuitPublicInputs, + public_data_read::PublicDataRead, public_data_update_request::PublicDataUpdateRequest, + public_inner_call_request::PublicInnerCallRequest, read_request::{ReadRequest, ScopedReadRequest}, + tree_leaf_read_request::TreeLeafReadRequest, + log_hash::{LogHash, NoteLogHash, ScopedLogHash, EncryptedLogHash, ScopedEncryptedLogHash}, + validation_requests::{ + KeyValidationRequest, KeyValidationRequestAndGenerator, PrivateValidationRequests, + PublicValidationRequests, PublicValidationRequestArrayLengths, RollupValidationRequests, + ScopedKeyValidationRequestAndGenerator +} +}, + address::{AztecAddress, EthAddress, SaltedInitializationHash, PublicKeysHash}, public_keys::PublicKeys, constants::{ - FUNCTION_TREE_HEIGHT, MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, - MAX_PUBLIC_DATA_READS_PER_CALL, MAX_PUBLIC_DATA_READS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - MAX_FIELD_VALUE, MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, MAX_KEY_VALIDATION_REQUESTS_PER_TX, - VK_TREE_HEIGHT, MAX_ENCRYPTED_LOGS_PER_TX, MAX_UNENCRYPTED_LOGS_PER_TX, - MAX_NOTE_ENCRYPTED_LOGS_PER_TX, PRIVATE_CALL_REQUEST_LENGTH, PROTOCOL_CONTRACT_TREE_HEIGHT, - PUBLIC_CALL_REQUEST_LENGTH, - }, contrakt::{storage_read::StorageRead, storage_update_request::StorageUpdateRequest}, + FUNCTION_TREE_HEIGHT, MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, + MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, MAX_PUBLIC_DATA_READS_PER_CALL, + MAX_PUBLIC_DATA_READS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, + MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_FIELD_VALUE, MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, + MAX_PUBLIC_CALL_STACK_LENGTH_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, + MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, + MAX_KEY_VALIDATION_REQUESTS_PER_TX, VK_TREE_HEIGHT, MAX_ENCRYPTED_LOGS_PER_TX, + MAX_UNENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, PRIVATE_CALL_REQUEST_LENGTH, + PROTOCOL_CONTRACT_TREE_HEIGHT, PUBLIC_CALL_REQUEST_LENGTH +}, + contrakt::{storage_read::StorageRead, storage_update_request::StorageUpdateRequest}, hash::{ - compute_l2_to_l1_hash, compute_tx_logs_hash, compute_siloed_nullifier, silo_note_hash, - silo_unencrypted_log_hash, mask_encrypted_log_hash, - }, header::Header, merkle_tree::{membership::MembershipWitness, MerkleTree}, + compute_l2_to_l1_hash, compute_tx_logs_hash, compute_siloed_nullifier, silo_note_hash, + silo_unencrypted_log_hash, mask_encrypted_log_hash +}, + header::Header, merkle_tree::{membership::MembershipWitness, MerkleTree}, messaging::l2_to_l1_message::{L2ToL1Message, ScopedL2ToL1Message}, partial_state_reference::PartialStateReference, tests::{ - fixtures, - fixtures::{ - contracts::ContractData, contract_functions::ContractFunction, - vk_tree::{ - generate_fake_honk_vk_for_index, generate_fake_client_ivc_vk_for_index, - get_vk_merkle_tree, VK_TREE_WIDTH, - }, - }, - }, transaction::{tx_context::TxContext, tx_request::TxRequest}, traits::Empty, + fixtures, + fixtures::{ + contracts::ContractData, contract_functions::ContractFunction, + vk_tree::{ + generate_fake_honk_vk_for_index, generate_fake_client_ivc_vk_for_index, get_vk_merkle_tree, + VK_TREE_WIDTH +} +} +}, + transaction::{tx_context::TxContext, tx_request::TxRequest}, traits::Empty, recursion::{ - verification_key::{HonkVerificationKey, ClientIVCVerificationKey, VerificationKey}, - proof::NestedRecursiveProof, - }, point::Point, + verification_key::{HonkVerificationKey, ClientIVCVerificationKey, VerificationKey}, + proof::NestedRecursiveProof +}, + point::Point }; fn subarray(arr: [T; N]) -> [T; M] { @@ -207,8 +210,9 @@ impl FixtureBuilder { pub fn in_vk_tree(&mut self, vk_index: u32) -> Self { self.vk_index = vk_index; - let vk_tree: MerkleTree = - comptime { fixtures::vk_tree::get_vk_merkle_tree() }; + let vk_tree: MerkleTree = comptime { + fixtures::vk_tree::get_vk_merkle_tree() + }; self.honk_vk = fixtures::vk_tree::generate_fake_honk_vk_for_index(vk_index); self.client_ivc_vk = fixtures::vk_tree::generate_fake_client_ivc_vk_for_index(vk_index); @@ -233,8 +237,7 @@ impl FixtureBuilder { self.protocol_contract_sibling_path = tree.get_sibling_path(contract_index); let contract_data = fixtures::contracts::get_protocol_contract(contract_index); - let function_data = - fixtures::contract_functions::get_protocol_contract_function(contract_index); + let function_data = fixtures::contract_functions::get_protocol_contract_function(contract_index); let _ = self.use_contract(contract_data); self.contract_address = AztecAddress::from_field(contract_index as Field); @@ -282,7 +285,7 @@ impl FixtureBuilder { tx_context: self.tx_context, vk_tree_root: self.vk_tree_root, protocol_contract_tree_root: self.protocol_contract_tree_root, - global_variables: self.global_variables, + global_variables: self.global_variables } } @@ -291,7 +294,7 @@ impl FixtureBuilder { origin: self.contract_address, args_hash: self.args_hash, tx_context: self.tx_context, - function_data: self.function_data, + function_data: self.function_data } } @@ -300,7 +303,7 @@ impl FixtureBuilder { msg_sender: self.msg_sender, contract_address: self.contract_address, function_selector: self.function_data.selector, - is_static_call: self.is_static_call, + is_static_call: self.is_static_call } } @@ -310,7 +313,7 @@ impl FixtureBuilder { args_hash: self.args_hash, returns_hash: self.returns_hash, start_side_effect_counter: self.counter_start, - end_side_effect_counter: self.counter, + end_side_effect_counter: self.counter } } @@ -322,39 +325,30 @@ impl FixtureBuilder { min_revertible_side_effect_counter: self.min_revertible_side_effect_counter, is_fee_payer: self.is_fee_payer, max_block_number: self.max_block_number, - note_hash_read_requests: subarray(self.note_hash_read_requests.storage.map( - |r: ScopedReadRequest| r.read_request, - )), - nullifier_read_requests: subarray(self.nullifier_read_requests.storage.map( - |r: ScopedReadRequest| r.read_request, - )), - key_validation_requests_and_generators: subarray(self - .scoped_key_validation_requests_and_generators - .storage - .map(|r: ScopedKeyValidationRequestAndGenerator| r.request)), - note_hashes: subarray( - self.note_hashes.storage.map(|n: ScopedNoteHash| n.note_hash), - ), - nullifiers: subarray( - self.nullifiers.storage.map(|n: ScopedNullifier| n.nullifier), + note_hash_read_requests: subarray(self.note_hash_read_requests.storage.map(|r: ScopedReadRequest| r.read_request)), + nullifier_read_requests: subarray(self.nullifier_read_requests.storage.map(|r: ScopedReadRequest| r.read_request)), + key_validation_requests_and_generators: subarray( + self.scoped_key_validation_requests_and_generators.storage.map(|r: ScopedKeyValidationRequestAndGenerator| r.request) ), + note_hashes: subarray(self.note_hashes.storage.map(|n: ScopedNoteHash| n.note_hash)), + nullifiers: subarray(self.nullifiers.storage.map(|n: ScopedNullifier| n.nullifier)), private_call_requests: subarray(self.private_call_requests.storage), public_call_requests: subarray(self.public_call_requests.storage), public_teardown_call_request: self.public_teardown_call_request, - l2_to_l1_msgs: subarray(self.l2_to_l1_msgs.storage.map(|r: ScopedL2ToL1Message| { + l2_to_l1_msgs: subarray( + self.l2_to_l1_msgs.storage.map( + |r: ScopedL2ToL1Message| { r.message - })), + } + ) + ), start_side_effect_counter: self.counter_start, end_side_effect_counter: self.counter, note_encrypted_logs_hashes: subarray(self.note_encrypted_logs_hashes.storage), - encrypted_logs_hashes: subarray(self.encrypted_logs_hashes.storage.map( - |l: ScopedEncryptedLogHash| l.log_hash, - )), - unencrypted_logs_hashes: subarray(self.unencrypted_logs_hashes.storage.map( - |l: ScopedLogHash| l.log_hash, - )), + encrypted_logs_hashes: subarray(self.encrypted_logs_hashes.storage.map(|l: ScopedEncryptedLogHash| l.log_hash)), + unencrypted_logs_hashes: subarray(self.unencrypted_logs_hashes.storage.map(|l: ScopedLogHash| l.log_hash)), historical_header: self.historical_header, - tx_context: self.tx_context, + tx_context: self.tx_context } } @@ -366,10 +360,9 @@ impl FixtureBuilder { salted_initialization_hash: self.salted_initialization_hash, public_keys: self.public_keys, contract_class_artifact_hash: self.contract_class_artifact_hash, - contract_class_public_bytecode_commitment: self - .contract_class_public_bytecode_commitment, + contract_class_public_bytecode_commitment: self.contract_class_public_bytecode_commitment, protocol_contract_sibling_path: self.protocol_contract_sibling_path, - acir_hash: self.acir_hash, + acir_hash: self.acir_hash } } @@ -382,7 +375,7 @@ impl FixtureBuilder { encrypted_logs_hashes: self.encrypted_logs_hashes, unencrypted_logs_hashes: self.unencrypted_logs_hashes, public_call_requests: self.public_call_requests, - private_call_stack: vec_reverse(self.private_call_requests), + private_call_stack: vec_reverse(self.private_call_requests) } } @@ -391,26 +384,22 @@ impl FixtureBuilder { } pub fn to_public_call_request(self) -> PublicCallRequest { - PublicCallRequest { - call_context: self.build_call_context(), - args_hash: self.args_hash, - counter: 0, - } + PublicCallRequest { call_context: self.build_call_context(), args_hash: self.args_hash, counter: 0 } } pub fn to_public_accumulated_data_builder(self) -> PublicAccumulatedDataBuilder { - let nullifiers = BoundedVec { - storage: self.nullifiers.storage.map(|n: ScopedNullifier| n.nullifier), - len: self.nullifiers.len(), - }; + let nullifiers = BoundedVec { storage: self.nullifiers.storage.map(|n: ScopedNullifier| n.nullifier), len: self.nullifiers.len() }; let note_encrypted_logs_hashes = BoundedVec { - storage: self.note_encrypted_logs_hashes.storage.map(|l: NoteLogHash| { + storage: self.note_encrypted_logs_hashes.storage.map( + |l: NoteLogHash| { LogHash { value: l.value, counter: l.counter, length: l.length } - }), - len: self.note_encrypted_logs_hashes.len(), + } + ), + len: self.note_encrypted_logs_hashes.len() }; let encrypted_logs_hashes = BoundedVec { - storage: self.encrypted_logs_hashes.storage.map(|l: ScopedEncryptedLogHash| { + storage: self.encrypted_logs_hashes.storage.map( + |l: ScopedEncryptedLogHash| { ScopedLogHash { log_hash: LogHash { value: l.log_hash.value, @@ -419,8 +408,9 @@ impl FixtureBuilder { }, contract_address: l.contract_address, } - }), - len: self.encrypted_logs_hashes.len(), + } + ), + len: self.encrypted_logs_hashes.len() }; PublicAccumulatedDataBuilder { @@ -432,7 +422,7 @@ impl FixtureBuilder { unencrypted_logs_hashes: self.unencrypted_logs_hashes, public_data_update_requests: self.public_data_update_requests, public_call_stack: self.public_call_requests, - gas_used: self.gas_used, + gas_used: self.gas_used } } @@ -444,23 +434,25 @@ impl FixtureBuilder { PublicAccumulatedData { note_hashes: self.note_hashes.storage.map(|n: ScopedNoteHash| n.expose_to_public()), nullifiers: self.nullifiers.storage.map(|n: ScopedNullifier| n.expose_to_public()), - l2_to_l1_msgs: self.l2_to_l1_msgs.storage.map(|m: ScopedL2ToL1Message| { + l2_to_l1_msgs: self.l2_to_l1_msgs.storage.map( + |m: ScopedL2ToL1Message| { m.expose_to_public() - }), - note_encrypted_logs_hashes: self.note_encrypted_logs_hashes.storage.map( - |l: NoteLogHash| l.expose_to_public(), - ), - encrypted_logs_hashes: self.encrypted_logs_hashes.storage.map( - |l: ScopedEncryptedLogHash| l.expose_to_public(), + } ), - unencrypted_logs_hashes: self.unencrypted_logs_hashes.storage.map(|l: ScopedLogHash| { + note_encrypted_logs_hashes: self.note_encrypted_logs_hashes.storage.map(|l: NoteLogHash| l.expose_to_public()), + encrypted_logs_hashes: self.encrypted_logs_hashes.storage.map(|l: ScopedEncryptedLogHash| l.expose_to_public()), + unencrypted_logs_hashes: self.unencrypted_logs_hashes.storage.map( + |l: ScopedLogHash| { l.expose_to_public() - }), + } + ), public_data_update_requests: self.public_data_update_requests.storage, - public_call_stack: self.public_call_requests.storage.map(|cr: PublicCallRequest| { + public_call_stack: self.public_call_requests.storage.map( + |cr: PublicCallRequest| { cr.expose_to_public() - }), - gas_used: self.gas_used, + } + ), + gas_used: self.gas_used } } @@ -468,23 +460,23 @@ impl FixtureBuilder { CombinedAccumulatedData { note_hashes: self.note_hashes.storage.map(|n: ScopedNoteHash| n.note_hash.value), nullifiers: self.nullifiers.storage.map(|n: ScopedNullifier| n.nullifier.value), - l2_to_l1_msgs: self.l2_to_l1_msgs.storage.map(|m: ScopedL2ToL1Message| { + l2_to_l1_msgs: self.l2_to_l1_msgs.storage.map( + |m: ScopedL2ToL1Message| { m.expose_to_public() - }), - note_encrypted_logs_hashes: self.note_encrypted_logs_hashes.storage.map( - |l: NoteLogHash| l.expose_to_public(), - ), - encrypted_logs_hashes: self.encrypted_logs_hashes.storage.map( - |l: ScopedEncryptedLogHash| l.expose_to_public(), + } ), - unencrypted_logs_hashes: self.unencrypted_logs_hashes.storage.map(|l: ScopedLogHash| { + note_encrypted_logs_hashes: self.note_encrypted_logs_hashes.storage.map(|l: NoteLogHash| l.expose_to_public()), + encrypted_logs_hashes: self.encrypted_logs_hashes.storage.map(|l: ScopedEncryptedLogHash| l.expose_to_public()), + unencrypted_logs_hashes: self.unencrypted_logs_hashes.storage.map( + |l: ScopedLogHash| { l.expose_to_public() - }), + } + ), note_encrypted_log_preimages_length: self.note_encrypted_log_preimages_length, encrypted_log_preimages_length: self.encrypted_log_preimages_length, unencrypted_log_preimages_length: self.unencrypted_log_preimages_length, public_data_update_requests: self.public_data_update_requests.storage, - gas_used: self.gas_used, + gas_used: self.gas_used } } @@ -493,10 +485,8 @@ impl FixtureBuilder { for_rollup: self.to_rollup_validation_requests(), note_hash_read_requests: self.note_hash_read_requests.storage, nullifier_read_requests: self.nullifier_read_requests.storage, - scoped_key_validation_requests_and_generators: self - .scoped_key_validation_requests_and_generators - .storage, - split_counter: self.validation_requests_split_counter, + scoped_key_validation_requests_and_generators: self.scoped_key_validation_requests_and_generators.storage, + split_counter: self.validation_requests_split_counter } } @@ -512,18 +502,13 @@ impl FixtureBuilder { validation_requests, constants, public_teardown_call_request, - fee_payer: self.fee_payer, + fee_payer: self.fee_payer } } pub fn to_private_kernel_data(self) -> PrivateKernelData { let public_inputs = self.to_private_kernel_circuit_public_inputs(); - PrivateKernelData { - public_inputs, - vk: self.client_ivc_vk, - vk_index: self.vk_index, - vk_path: self.vk_path, - } + PrivateKernelData { public_inputs, vk: self.client_ivc_vk, vk_index: self.vk_index, vk_path: self.vk_path } } pub fn to_public_circuit_public_inputs(self) -> PublicCircuitPublicInputs { @@ -532,40 +517,33 @@ impl FixtureBuilder { args_hash: self.args_hash, returns_hash: self.returns_hash, note_hash_read_requests: subarray(self.note_hash_tree_leaf_read_requests.storage), - nullifier_read_requests: subarray(self.nullifier_read_requests.storage.map( - |r: ScopedReadRequest| r.read_request, - )), - nullifier_non_existent_read_requests: subarray(self - .nullifier_non_existent_read_requests - .storage - .map(|r: ScopedReadRequest| r.read_request)), - l1_to_l2_msg_read_requests: subarray(self.l1_to_l2_msg_read_requests.storage), - contract_storage_update_requests: subarray( - self.contract_storage_update_requests.storage, + nullifier_read_requests: subarray(self.nullifier_read_requests.storage.map(|r: ScopedReadRequest| r.read_request)), + nullifier_non_existent_read_requests: subarray( + self.nullifier_non_existent_read_requests.storage.map(|r: ScopedReadRequest| r.read_request) ), + l1_to_l2_msg_read_requests: subarray(self.l1_to_l2_msg_read_requests.storage), + contract_storage_update_requests: subarray(self.contract_storage_update_requests.storage), contract_storage_reads: self.contract_storage_reads.storage, public_call_requests: subarray(self.public_inner_call_requests.storage), - note_hashes: subarray( - self.note_hashes.storage.map(|n: ScopedNoteHash| n.note_hash), - ), - nullifiers: subarray( - self.nullifiers.storage.map(|n: ScopedNullifier| n.nullifier), - ), - l2_to_l1_msgs: subarray(self.l2_to_l1_msgs.storage.map(|m: ScopedL2ToL1Message| { + note_hashes: subarray(self.note_hashes.storage.map(|n: ScopedNoteHash| n.note_hash)), + nullifiers: subarray(self.nullifiers.storage.map(|n: ScopedNullifier| n.nullifier)), + l2_to_l1_msgs: subarray( + self.l2_to_l1_msgs.storage.map( + |m: ScopedL2ToL1Message| { m.message - })), + } + ) + ), start_side_effect_counter: self.counter_start, end_side_effect_counter: self.counter, - unencrypted_logs_hashes: subarray(self.unencrypted_logs_hashes.storage.map( - |l: ScopedLogHash| l.log_hash, - )), + unencrypted_logs_hashes: subarray(self.unencrypted_logs_hashes.storage.map(|l: ScopedLogHash| l.log_hash)), historical_header: self.historical_header, global_variables: self.global_variables, prover_address: self.prover_address, revert_code: self.revert_code, start_gas_left: self.start_gas_left, end_gas_left: self.end_gas_left, - transaction_fee: self.transaction_fee, + transaction_fee: self.transaction_fee } } @@ -573,7 +551,7 @@ impl FixtureBuilder { PublicCallData { public_inputs: self.to_public_circuit_public_inputs(), proof: PublicCallDataProof {}, - bytecode_hash: self.bytecode_hash, + bytecode_hash: self.bytecode_hash } } @@ -584,7 +562,7 @@ impl FixtureBuilder { nullifier_read_requests: self.nullifier_read_requests.storage, nullifier_non_existent_read_requests: self.nullifier_non_existent_read_requests.storage, public_data_reads: self.public_data_reads.storage, - l1_to_l2_msg_read_requests: self.l1_to_l2_msg_read_requests.storage, + l1_to_l2_msg_read_requests: self.l1_to_l2_msg_read_requests.storage } } @@ -601,7 +579,7 @@ impl FixtureBuilder { end_side_effect_counter: self.counter, start_gas_left: self.start_gas_left, transaction_fee: self.transaction_fee, - reverted: self.revert_code != 0, + reverted: self.revert_code != 0 } } @@ -609,10 +587,7 @@ impl FixtureBuilder { EnqueuedCallData { data: self.to_vm_circuit_public_inputs(), proof: Proof {} } } - pub fn to_public_kernel_circuit_public_inputs( - self, - revertible: bool, - ) -> PublicKernelCircuitPublicInputs { + pub fn to_public_kernel_circuit_public_inputs(self, revertible: bool) -> PublicKernelCircuitPublicInputs { // TODO: Split the data using self.min_revertible_side_effect_counter. let accumulated_data = self.to_public_accumulated_data(); let end_non_revertible = if revertible { @@ -634,19 +609,13 @@ impl FixtureBuilder { end_side_effect_counter: self.counter, public_teardown_call_request: self.public_teardown_call_request, fee_payer: self.fee_payer, - revert_code: self.revert_code, + revert_code: self.revert_code } } pub fn to_public_kernel_data(self, revertible: bool) -> PublicKernelData { let public_inputs = self.to_public_kernel_circuit_public_inputs(revertible); - PublicKernelData { - public_inputs, - proof: self.proof, - vk: self.honk_vk, - vk_index: self.vk_index, - vk_path: self.vk_path, - } + PublicKernelData { public_inputs, proof: self.proof, vk: self.honk_vk, vk_index: self.vk_index, vk_path: self.vk_path } } pub fn to_rollup_validation_requests(self) -> RollupValidationRequests { @@ -664,7 +633,7 @@ impl FixtureBuilder { constants, start_state: self.start_state, revert_code: self.revert_code, - fee_payer: self.fee_payer, + fee_payer: self.fee_payer } } @@ -675,14 +644,12 @@ impl FixtureBuilder { proof: NestedRecursiveProof::empty(), vk: self.honk_vk, vk_index: self.vk_index, - vk_path: self.vk_path, + vk_path: self.vk_path } } pub fn add_new_note_hash(&mut self, value: Field) { - self.note_hashes.push(NoteHash { value, counter: self.next_counter() }.scope( - self.contract_address, - )); + self.note_hashes.push(NoteHash { value, counter: self.next_counter() }.scope(self.contract_address)); } pub fn add_siloed_note_hash(&mut self, value: Field) { @@ -691,9 +658,7 @@ impl FixtureBuilder { let index = self.note_hashes.len(); let note_hash_to_silo = NoteHash { value, counter: 0 }.scope(self.contract_address); let siloed_value = silo_note_hash(note_hash_to_silo, tx_hash, index); - self.note_hashes.push(NoteHash { value: siloed_value, counter: self.next_counter() }.scope( - AztecAddress::zero(), - )); + self.note_hashes.push(NoteHash { value: siloed_value, counter: self.next_counter() }.scope(AztecAddress::zero())); } pub fn append_note_hashes(&mut self, num_note_hashes: u32) { @@ -731,8 +696,7 @@ impl FixtureBuilder { pub fn set_first_nullifier(&mut self) { assert_eq(self.nullifiers.len(), 0, "first nullifier already set"); let value = self.mock_nullifier_value(0); - let first_nullifier = - Nullifier { value, counter: 0, note_hash: 0 }.scope(AztecAddress::zero()); + let first_nullifier = Nullifier { value, counter: 0, note_hash: 0 }.scope(AztecAddress::zero()); self.nullifiers.push(first_nullifier); } @@ -742,9 +706,7 @@ impl FixtureBuilder { } pub fn add_nullifier_for_note_hash(&mut self, value: Field, note_hash: Field) { - self.nullifiers.push(Nullifier { value, counter: self.next_counter(), note_hash }.scope( - self.contract_address, - )); + self.nullifiers.push(Nullifier { value, counter: self.next_counter(), note_hash }.scope(self.contract_address)); } pub fn add_siloed_nullifier(&mut self, value: Field) { @@ -754,12 +716,9 @@ impl FixtureBuilder { pub fn add_siloed_nullifier_for_note_hash(&mut self, value: Field, note_hash: Field) { let siloed_value = compute_siloed_nullifier(self.contract_address, value); - self.nullifiers.push(Nullifier { - value: siloed_value, - counter: self.next_counter(), - note_hash, - } - .scope(AztecAddress::zero())); + self.nullifiers.push( + Nullifier { value: siloed_value, counter: self.next_counter(), note_hash }.scope(AztecAddress::zero()) + ); } pub fn append_nullifiers(&mut self, num_extra_nullifier: u32) { @@ -783,14 +742,13 @@ impl FixtureBuilder { } pub fn add_l2_to_l1_message(&mut self, content: Field, recipient: EthAddress) { - self.l2_to_l1_msgs.push(L2ToL1Message { recipient, content, counter: self.next_counter() } - .scope(self.contract_address)); + self.l2_to_l1_msgs.push( + L2ToL1Message { recipient, content, counter: self.next_counter() }.scope(self.contract_address) + ); } pub fn add_exposed_l2_to_l1_message(&mut self, content: Field, recipient: EthAddress) { - self.l2_to_l1_msgs.push(L2ToL1Message { recipient, content, counter: 0 }.scope( - self.contract_address, - )); + self.l2_to_l1_msgs.push(L2ToL1Message { recipient, content, counter: 0 }.scope(self.contract_address)); } pub fn add_siloed_l2_to_l1_message(&mut self, content: Field, recipient: EthAddress) { @@ -799,7 +757,7 @@ impl FixtureBuilder { recipient, content, self.tx_context.version, - self.tx_context.chain_id, + self.tx_context.chain_id ); self.add_l2_to_l1_message(siloed_content, recipient); } @@ -825,9 +783,7 @@ impl FixtureBuilder { } pub fn add_contract_storage_read_request(&mut self, storage_slot: Field, value: Field) { - self.contract_storage_reads.push( - StorageRead { storage_slot, current_value: value, counter: self.next_counter() }, - ); + self.contract_storage_reads.push(StorageRead { storage_slot, current_value: value, counter: self.next_counter() }); } pub fn append_contract_storage_read_requests(&mut self, num: u32) { @@ -841,8 +797,7 @@ impl FixtureBuilder { } pub fn add_contract_storage_update_request(&mut self, storage_slot: Field, value: Field) { - let update_request = - StorageUpdateRequest { storage_slot, new_value: value, counter: self.next_counter() }; + let update_request = StorageUpdateRequest { storage_slot, new_value: value, counter: self.next_counter() }; self.contract_storage_update_requests.push(update_request); } @@ -857,8 +812,7 @@ impl FixtureBuilder { } pub fn add_public_data_update_request(&mut self, leaf_slot: Field, value: Field) { - let update_request = - PublicDataUpdateRequest { leaf_slot, new_value: value, counter: self.next_counter() }; + let update_request = PublicDataUpdateRequest { leaf_slot, new_value: value, counter: self.next_counter() }; self.public_data_update_requests.push(update_request); } @@ -873,9 +827,7 @@ impl FixtureBuilder { } pub fn add_public_data_read_request(&mut self, leaf_slot: Field, value: Field) { - self.public_data_reads.push( - PublicDataRead { leaf_slot, value, counter: self.next_counter() }, - ); + self.public_data_reads.push(PublicDataRead { leaf_slot, value, counter: self.next_counter() }); } pub fn append_public_data_read_requests(&mut self, num_reads: u32) { @@ -891,8 +843,7 @@ impl FixtureBuilder { pub fn add_read_request_for_pending_note_hash(&mut self, note_hash_index: u32) -> u32 { let read_request_index = self.note_hash_read_requests.len(); let value = self.mock_note_hash_value(note_hash_index); - let read_request = - ReadRequest { value, counter: self.next_counter() }.scope(self.contract_address); + let read_request = ReadRequest { value, counter: self.next_counter() }.scope(self.contract_address); self.note_hash_read_requests.push(read_request); read_request_index } @@ -902,9 +853,7 @@ impl FixtureBuilder { for i in 0..self.note_hash_read_requests.max_len() { if i < num_reads { let value = self.mock_note_hash_read_value(index_offset + i); - let read_request = ReadRequest { value, counter: self.next_counter() }.scope( - self.contract_address, - ); + let read_request = ReadRequest { value, counter: self.next_counter() }.scope(self.contract_address); self.note_hash_read_requests.push(read_request); } } @@ -928,17 +877,13 @@ impl FixtureBuilder { pub fn add_read_request_for_pending_nullifier(&mut self, nullifier_index: u32) -> u32 { let read_request_index = self.nullifier_read_requests.len(); let nullifier = self.mock_nullifier_value(nullifier_index); - let read_request = ReadRequest { value: nullifier, counter: self.next_counter() }.scope( - self.contract_address, - ); + let read_request = ReadRequest { value: nullifier, counter: self.next_counter() }.scope(self.contract_address); self.nullifier_read_requests.push(read_request); read_request_index } pub fn add_non_existent_read_request_for_nullifier(&mut self, nullifier: Field) { - let read_request = ReadRequest { value: nullifier, counter: self.next_counter() }.scope( - self.contract_address, - ); + let read_request = ReadRequest { value: nullifier, counter: self.next_counter() }.scope(self.contract_address); self.nullifier_non_existent_read_requests.push(read_request); } @@ -947,9 +892,7 @@ impl FixtureBuilder { for i in 0..self.nullifier_read_requests.max_len() { if i < num_reads { let value = self.mock_nullifier_read_value(index_offset + i); - let read_request = ReadRequest { value, counter: self.next_counter() }.scope( - self.contract_address, - ); + let read_request = ReadRequest { value, counter: self.next_counter() }.scope(self.contract_address); self.nullifier_read_requests.push(read_request); } } @@ -965,20 +908,12 @@ impl FixtureBuilder { } } - pub fn add_request_for_key_validation( - &mut self, - pk_m: Point, - sk_app: Field, - sk_app_generator: Field, - ) -> u32 { + pub fn add_request_for_key_validation(&mut self, pk_m: Point, sk_app: Field, sk_app_generator: Field) -> u32 { let new_request_index = self.scoped_key_validation_requests_and_generators.len(); let request = KeyValidationRequest { pk_m, sk_app }; let request_and_generator = KeyValidationRequestAndGenerator { request, sk_app_generator }; - let scoped_key_validation_request_and_generator = - request_and_generator.scope(self.contract_address); - self.scoped_key_validation_requests_and_generators.push( - scoped_key_validation_request_and_generator, - ); + let scoped_key_validation_request_and_generator = request_and_generator.scope(self.contract_address); + self.scoped_key_validation_requests_and_generators.push(scoped_key_validation_request_and_generator); new_request_index } @@ -988,21 +923,13 @@ impl FixtureBuilder { for i in 0..self.scoped_key_validation_requests_and_generators.max_len() { if i < num_requests { let request = self.mock_key_validation_request(index_offset + i); - self.scoped_key_validation_requests_and_generators.push(request.scope( - self.contract_address, - )); + self.scoped_key_validation_requests_and_generators.push(request.scope(self.contract_address)); } } } - pub fn add_note_encrypted_log_hash( - &mut self, - value: Field, - length: Field, - note_hash_counter: u32, - ) { - let log_hash = - NoteLogHash { value, counter: self.next_counter(), length, note_hash_counter }; + pub fn add_note_encrypted_log_hash(&mut self, value: Field, length: Field, note_hash_counter: u32) { + let log_hash = NoteLogHash { value, counter: self.next_counter(), length, note_hash_counter }; self.note_encrypted_logs_hashes.push(log_hash); self.encrypted_log_preimages_length += length; } @@ -1018,20 +945,13 @@ impl FixtureBuilder { } pub fn add_encrypted_log_hash(&mut self, hash: Field, length: Field) { - let log_hash = - EncryptedLogHash { value: hash, counter: self.next_counter(), length, randomness: 2 }; + let log_hash = EncryptedLogHash { value: hash, counter: self.next_counter(), length, randomness: 2 }; self.encrypted_logs_hashes.push(log_hash.scope(self.contract_address)); self.encrypted_log_preimages_length += length; } pub fn add_masked_encrypted_log_hash(&mut self, hash: Field, length: Field) { - let mut log_hash = EncryptedLogHash { - value: hash, - counter: self.next_counter(), - length, - randomness: 2, - } - .scope(self.contract_address); + let mut log_hash = EncryptedLogHash { value: hash, counter: self.next_counter(), length, randomness: 2 }.scope(self.contract_address); log_hash.contract_address = mask_encrypted_log_hash(log_hash); log_hash.log_hash.randomness = 0; self.encrypted_logs_hashes.push(log_hash); @@ -1100,12 +1020,12 @@ impl FixtureBuilder { self.private_call_requests.push( PrivateCallRequest { - call_context: public_inputs.call_context, - args_hash: public_inputs.args_hash, - returns_hash: public_inputs.returns_hash, - start_side_effect_counter: start_counter, - end_side_effect_counter: end_counter, - }, + call_context: public_inputs.call_context, + args_hash: public_inputs.args_hash, + returns_hash: public_inputs.returns_hash, + start_side_effect_counter: start_counter, + end_side_effect_counter: end_counter + } ); } @@ -1179,10 +1099,7 @@ impl FixtureBuilder { fn mock_key_validation_request(self, index: u32) -> KeyValidationRequestAndGenerator { let value_offset = 3030 + self.value_offset + index as Field; - let request = KeyValidationRequest { - pk_m: Point { x: value_offset, y: 1 + value_offset, is_infinite: false }, - sk_app: 2 + value_offset, - }; + let request = KeyValidationRequest { pk_m: Point { x: value_offset, y: 1 + value_offset, is_infinite: false }, sk_app: 2 + value_offset }; KeyValidationRequestAndGenerator { request, sk_app_generator: 3 + value_offset } } @@ -1353,7 +1270,7 @@ impl Empty for FixtureBuilder { start_gas_left: Gas::empty(), end_gas_left: Gas::empty(), transaction_fee: 0, - value_offset: 0, + value_offset: 0 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contract_functions.nr b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contract_functions.nr index 3ec6eed50a9..f3649da3470 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contract_functions.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contract_functions.nr @@ -44,10 +44,7 @@ global default_public_function = ContractFunction { pub fn get_protocol_contract_function(contract_index: u32) -> ContractFunction { ContractFunction { - data: FunctionData { - selector: FunctionSelector { inner: 98989 + contract_index }, - is_private: true, - }, + data: FunctionData { selector: FunctionSelector { inner: 98989 + contract_index }, is_private: true }, vk_hash: 0, acir_hash: 5555 + contract_index as Field, membership_witness: MembershipWitness { @@ -57,8 +54,8 @@ pub fn get_protocol_contract_function(contract_index: u32) -> ContractFunction { 0x062d9223c973936f12eacf94db1cfb9499e5aee67c864677e238402006c20d21, 0x26d4cb8f72c0330bbebdb587bf896ce790ec7d091ee6aa3aabcf9bd60b2de307, 0x1d8f5034624cbef3663cf6a73a04bf82d34379e7e65f2b7d29fce4d6987ca7c1, - 0x1758942724d8e39e5a0bc52b58cd80e5b6f26bedcc2a00d4b2f0dc6019fb1bf1, - ], - }, + 0x1758942724d8e39e5a0bc52b58cd80e5b6f26bedcc2a00d4b2f0dc6019fb1bf1 + ] + } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contracts.nr b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contracts.nr index c854adeec7f..39ead662d87 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contracts.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contracts.nr @@ -1,7 +1,7 @@ use crate::{ address::{AztecAddress, PublicKeysHash, SaltedInitializationHash, PartialAddress}, contract_class_id::ContractClassId, hash::private_functions_root_from_siblings, - tests::fixtures::contract_functions::get_protocol_contract_function, public_keys::PublicKeys, + tests::fixtures::contract_functions::get_protocol_contract_function, public_keys::PublicKeys }; pub struct ContractData { @@ -78,19 +78,16 @@ pub fn get_protocol_contract(index: u32) -> ContractData { function.data.selector, function.vk_hash, function.membership_witness.leaf_index, - function.membership_witness.sibling_path, + function.membership_witness.sibling_path ); let contract_class_id = ContractClassId::compute( artifact_hash, private_functions_root, - public_bytecode_commitment, + public_bytecode_commitment ); - let partial_address = PartialAddress::compute_from_salted_initialization_hash( - contract_class_id, - salted_initialization_hash, - ); + let partial_address = PartialAddress::compute_from_salted_initialization_hash(contract_class_id, salted_initialization_hash); let address = AztecAddress::compute(public_keys.hash(), partial_address); @@ -104,6 +101,6 @@ pub fn get_protocol_contract(index: u32) -> ContractData { contract_class_id, public_keys, salted_initialization_hash, - deployer: AztecAddress { inner: 0 }, + deployer: AztecAddress { inner: 0 } } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/protocol_contract_tree.nr b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/protocol_contract_tree.nr index 2a35812fb5f..8dd35497597 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/protocol_contract_tree.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/protocol_contract_tree.nr @@ -1,6 +1,6 @@ use crate::{ constants::PROTOCOL_CONTRACT_TREE_HEIGHT, merkle_tree::merkle_tree::MerkleTree, - tests::fixtures::contracts::get_protocol_contract, + tests::fixtures::contracts::get_protocol_contract }; global PROTOCOL_CONTRACT_TREE_WIDTH: u32 = 1 << PROTOCOL_CONTRACT_TREE_HEIGHT as u8; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/vk_tree.nr b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/vk_tree.nr index e3a9a8b6d62..3a2c634d026 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/vk_tree.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/vk_tree.nr @@ -1,11 +1,11 @@ use crate::constants::{ - VK_TREE_HEIGHT, PRIVATE_KERNEL_INIT_INDEX, PRIVATE_KERNEL_INNER_INDEX, - PRIVATE_KERNEL_RESET_INDEX, PRIVATE_KERNEL_TAIL_INDEX, PRIVATE_KERNEL_TAIL_TO_PUBLIC_INDEX, - EMPTY_NESTED_INDEX, PRIVATE_KERNEL_EMPTY_INDEX, PUBLIC_KERNEL_INNER_INDEX, - PUBLIC_KERNEL_MERGE_INDEX, PUBLIC_KERNEL_TAIL_INDEX, BASE_PARITY_INDEX, ROOT_PARITY_INDEX, - BASE_ROLLUP_INDEX, MERGE_ROLLUP_INDEX, BLOCK_ROOT_ROLLUP_INDEX, BLOCK_MERGE_ROLLUP_INDEX, - ROOT_ROLLUP_INDEX, BLOCK_ROOT_ROLLUP_EMPTY_INDEX, HONK_VERIFICATION_KEY_LENGTH_IN_FIELDS, - CLIENT_IVC_VERIFICATION_KEY_LENGTH_IN_FIELDS, + VK_TREE_HEIGHT, PRIVATE_KERNEL_INIT_INDEX, PRIVATE_KERNEL_INNER_INDEX, PRIVATE_KERNEL_RESET_INDEX, + PRIVATE_KERNEL_TAIL_INDEX, PRIVATE_KERNEL_TAIL_TO_PUBLIC_INDEX, EMPTY_NESTED_INDEX, + PRIVATE_KERNEL_EMPTY_INDEX, PUBLIC_KERNEL_INNER_INDEX, PUBLIC_KERNEL_MERGE_INDEX, + PUBLIC_KERNEL_TAIL_INDEX, BASE_PARITY_INDEX, ROOT_PARITY_INDEX, BASE_ROLLUP_INDEX, + MERGE_ROLLUP_INDEX, BLOCK_ROOT_ROLLUP_INDEX, BLOCK_MERGE_ROLLUP_INDEX, ROOT_ROLLUP_INDEX, + BLOCK_ROOT_ROLLUP_EMPTY_INDEX, HONK_VERIFICATION_KEY_LENGTH_IN_FIELDS, + CLIENT_IVC_VERIFICATION_KEY_LENGTH_IN_FIELDS }; use crate::merkle_tree::merkle_tree::MerkleTree; use crate::recursion::verification_key::VerificationKey; @@ -19,16 +19,12 @@ fn generate_fake_vk_for_index(index: u32) -> [Field; N] { vk } -pub fn generate_fake_honk_vk_for_index( - index: u32, -) -> VerificationKey { +pub fn generate_fake_honk_vk_for_index(index: u32) -> VerificationKey { let key = generate_fake_vk_for_index(index); VerificationKey { key, hash: verification_key_hash(key) } } -pub fn generate_fake_client_ivc_vk_for_index( - index: u32, -) -> VerificationKey { +pub fn generate_fake_client_ivc_vk_for_index(index: u32) -> VerificationKey { let key = generate_fake_vk_for_index(index); VerificationKey { key, hash: verification_key_hash(key) } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/tests/merkle_tree_utils.nr b/noir-projects/noir-protocol-circuits/crates/types/src/tests/merkle_tree_utils.nr index e7cfbd7566d..2783d5bbb9a 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/tests/merkle_tree_utils.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/tests/merkle_tree_utils.nr @@ -1,7 +1,4 @@ -use crate::{ - merkle_tree::{merkle_tree, MerkleTree, calculate_empty_tree_root}, traits::Empty, - hash::merkle_hash, -}; +use crate::{merkle_tree::{merkle_tree, MerkleTree, calculate_empty_tree_root}, traits::Empty, hash::merkle_hash}; pub fn compute_zero_hashes(mut hashes: [Field; N]) -> [Field; N] { hashes[0] = merkle_hash(0, 0); @@ -81,7 +78,7 @@ impl Self { // Hack to get around us converting a u32 to a u8. // TODO: improve this. (SUBTREE_HEIGHT as Field).assert_max_bit_size::<8>(); assert_eq( - TREE_HEIGHT, - SUPERTREE_HEIGHT + SUBTREE_HEIGHT, - "tree height must be the sum of supertree and subtree height", + TREE_HEIGHT, SUPERTREE_HEIGHT + SUBTREE_HEIGHT, "tree height must be the sum of supertree and subtree height" ); assert_eq( - U128::from_integer(SUBTREE_ITEMS), - U128::from_integer(1 << SUBTREE_HEIGHT as u8), - "subtree items must be 2^subtree height", + U128::from_integer(SUBTREE_ITEMS), U128::from_integer(1 << SUBTREE_HEIGHT as u8), "subtree items must be 2^subtree height" ); let subtree = MerkleTree::new(non_zero_leaves); @@ -121,12 +114,7 @@ impl [Field; TREE_HEIGHT] { @@ -165,10 +153,7 @@ impl(array: [T; N], expected: [T; S]) +pub fn assert_array_eq( + array: [T; N], + expected: [T; S] +) where - T: Empty + Eq, -{ + T: Empty + Eq, { assert(expected.all(|elem: T| !is_empty(elem)), "cannot expect empty element in the result"); assert_eq(validate_array(array), S, "mismatch array lengths"); for i in 0..S { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/traits.nr b/noir-projects/noir-protocol-circuits/crates/types/src/traits.nr index 614388f5259..75a515cb8c3 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/traits.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/traits.nr @@ -50,15 +50,13 @@ impl Empty for U128 { pub fn is_empty(item: T) -> bool where - T: Empty + Eq, -{ + T: Empty + Eq, { item.eq(T::empty()) } pub fn is_empty_array(array: [T; N]) -> bool where - T: Empty + Eq, -{ + T: Empty + Eq, { array.all(|elem| is_empty(elem)) } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_context.nr b/noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_context.nr index f7cf4faef7a..959077dcb84 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_context.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_context.nr @@ -1,6 +1,6 @@ use crate::{ constants::TX_CONTEXT_LENGTH, traits::{Deserialize, Serialize, Empty}, utils::reader::Reader, - abis::gas_settings::GasSettings, + abis::gas_settings::GasSettings }; // docs:start:tx-context @@ -53,7 +53,7 @@ impl Deserialize for TxContext { let context = Self { chain_id: reader.read(), version: reader.read(), - gas_settings: reader.read_struct(GasSettings::deserialize), + gas_settings: reader.read_struct(GasSettings::deserialize) }; reader.finish(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_request.nr index fb367b28111..8bc221c8d3c 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_request.nr @@ -1,8 +1,8 @@ use crate::{ address::AztecAddress, abis::function_data::FunctionData, - constants::{GENERATOR_INDEX__TX_REQUEST, TX_REQUEST_LENGTH}, - hash::poseidon2_hash_with_separator, traits::{Hash, Serialize, Deserialize, Empty}, - transaction::tx_context::TxContext, utils::reader::Reader, + constants::{GENERATOR_INDEX__TX_REQUEST, TX_REQUEST_LENGTH}, hash::poseidon2_hash_with_separator, + traits::{Hash, Serialize, Deserialize, Empty}, transaction::tx_context::TxContext, + utils::reader::Reader }; pub struct TxRequest { @@ -18,7 +18,7 @@ impl Empty for TxRequest { origin: AztecAddress::empty(), args_hash: 0, tx_context: TxContext::empty(), - function_data: FunctionData::empty(), + function_data: FunctionData::empty() } } } @@ -62,7 +62,7 @@ impl Deserialize for TxRequest { origin: reader.read_struct(AztecAddress::deserialize), args_hash: reader.read(), tx_context: reader.read_struct(TxContext::deserialize), - function_data: reader.read_struct(FunctionData::deserialize), + function_data: reader.read_struct(FunctionData::deserialize) }; reader.finish(); @@ -73,9 +73,10 @@ impl Deserialize for TxRequest { mod tests { use crate::{ abis::{ - function_selector::FunctionSelector, function_data::FunctionData, - gas_settings::GasSettings, gas::Gas, gas_fees::GasFees, - }, address::AztecAddress, transaction::{tx_request::TxRequest, tx_context::TxContext}, + function_selector::FunctionSelector, function_data::FunctionData, gas_settings::GasSettings, + gas::Gas, gas_fees::GasFees + }, + address::AztecAddress, transaction::{tx_request::TxRequest, tx_context::TxContext} }; #[test] @@ -93,14 +94,10 @@ mod tests { origin: AztecAddress::from_field(1), args_hash: 3, tx_context: TxContext { chain_id: 0, version: 0, gas_settings }, - function_data: FunctionData { - selector: FunctionSelector::from_u32(2), - is_private: true, - }, + function_data: FunctionData { selector: FunctionSelector::from_u32(2), is_private: true } }; // Value from tx_request.test.ts "compute hash" test - let test_data_tx_request_hash = - 0x289d3f85f463f3449e2204433b860574d351e9fbd97a01a722239fdd9ce3ce9b; + let test_data_tx_request_hash = 0x289d3f85f463f3449e2204433b860574d351e9fbd97a01a722239fdd9ce3ce9b; assert(tx_request.hash() == test_data_tx_request_hash); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/type_serialization.nr b/noir-projects/noir-protocol-circuits/crates/types/src/type_serialization.nr index 953ab67b50d..67335a0711b 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/type_serialization.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/type_serialization.nr @@ -146,8 +146,7 @@ impl Deserialize for i64 { impl Serialize for [T; N] where - T: Serialize, -{ + T: Serialize, { fn serialize(self) -> [Field; N * M] { let mut result: [Field; N * M] = std::mem::zeroed(); let mut serialized: [Field; M] = std::mem::zeroed(); @@ -163,8 +162,7 @@ where impl Deserialize for [T; N] where - T: Deserialize, -{ + T: Deserialize, { fn deserialize(fields: [Field; N * M]) -> Self { let mut reader = crate::utils::reader::Reader::new(fields); let mut result: [T; N] = std::mem::zeroed(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays.nr index 52456a02286..f230a4f73e2 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays.nr @@ -15,32 +15,25 @@ mod sort_by; mod sort_by_counter; // Re-exports. -pub use assert_array_appended::{ - assert_array_appended, assert_array_appended_reversed, assert_array_appended_scoped, -}; +pub use assert_array_appended::{assert_array_appended, assert_array_appended_reversed, assert_array_appended_scoped}; pub use assert_array_prepended::assert_array_prepended; pub use assert_combined_array::{assert_combined_array, combine_arrays}; pub use assert_combined_sorted_transformed_value_array::{ assert_combined_sorted_transformed_value_array_asc, - get_combined_order_hints::{CombinedOrderHint, get_combined_order_hints_asc}, -}; -pub use assert_combined_transformed_array::{ - assert_combined_transformed_array, combine_and_transform_arrays, + get_combined_order_hints::{CombinedOrderHint, get_combined_order_hints_asc} }; +pub use assert_combined_transformed_array::{assert_combined_transformed_array, combine_and_transform_arrays}; pub use assert_exposed_sorted_transformed_value_array::{ assert_exposed_sorted_transformed_value_array, - get_order_hints::{get_order_hints_asc, get_order_hints_desc, OrderHint}, + get_order_hints::{get_order_hints_asc, get_order_hints_desc, OrderHint} }; pub use assert_deduped_array::{assert_deduped_array, dedupe_array}; pub use assert_sorted_array::assert_sorted_array; pub use assert_split_sorted_transformed_value_arrays::{ - assert_split_sorted_transformed_value_arrays_asc, - assert_split_sorted_transformed_value_arrays_desc, - get_split_order_hints::{get_split_order_hints_asc, get_split_order_hints_desc, SplitOrderHints}, -}; -pub use assert_sorted_transformed_value_array::{ - assert_sorted_transformed_value_array, assert_sorted_transformed_value_array_capped_size, + assert_split_sorted_transformed_value_arrays_asc, assert_split_sorted_transformed_value_arrays_desc, + get_split_order_hints::{get_split_order_hints_asc, get_split_order_hints_desc, SplitOrderHints} }; +pub use assert_sorted_transformed_value_array::{assert_sorted_transformed_value_array, assert_sorted_transformed_value_array_capped_size}; pub use assert_split_transformed_value_arrays::assert_split_transformed_value_arrays; pub use get_sorted_result::{get_sorted_result, SortedResult}; pub use sort_by_counter::{sort_by_counter_asc, sort_by_counter_desc}; @@ -49,8 +42,7 @@ use crate::traits::{Empty, is_empty}; pub fn array_to_bounded_vec(array: [T; N]) -> BoundedVec where - T: Empty + Eq, -{ + T: Empty + Eq, { let mut len = 0; for elem in array { if !is_empty(elem) { @@ -61,10 +53,7 @@ where BoundedVec { storage: array, len } } -pub unconstrained fn find_index_hint( - array: [T; N], - find: fn[Env](T) -> bool, -) -> u32 { +pub unconstrained fn find_index_hint(array: [T; N], find: fn[Env](T) -> bool) -> u32 { let mut index = N; for i in 0..N { if (index == N) & find(array[i]) { @@ -79,8 +68,7 @@ pub unconstrained fn find_index_hint( // valid. pub fn validate_array(array: [T; N]) -> u32 where - T: Empty + Eq, -{ + T: Empty + Eq, { let mut seen_empty = false; let mut length = 0; for i in 0..N { @@ -98,9 +86,10 @@ where // Important: Only use it for validated arrays: validate_array(array) should be true. pub fn array_length(array: [T; N]) -> u32 where - T: Empty + Eq, -{ - let length = unsafe { find_index_hint(array, |elem: T| is_empty(elem)) }; + T: Empty + Eq, { + let length = unsafe { + find_index_hint(array, |elem: T| is_empty(elem)) + }; if length != 0 { assert(!is_empty(array[length - 1])); } @@ -123,8 +112,7 @@ pub fn array_concat(array1: [T; N], array2: [T; M]) - pub fn array_merge(array1: [T; N], array2: [T; N]) -> [T; N] where - T: Empty + Eq, -{ + T: Empty + Eq, { let mut result: [T; N] = [T::empty(); N]; let mut i = 0; for elem in array1 { @@ -145,11 +133,10 @@ where pub fn check_permutation( original_array: [T; N], permuted_array: [T; N], - original_indexes: [u32; N], + original_indexes: [u32; N] ) where - T: Eq + Empty, -{ + T: Eq + Empty, { let mut seen_value = [false; N]; for i in 0..N { let index = original_indexes[i]; @@ -226,7 +213,9 @@ fn test_array_length_invalid_arrays() { fn find_index_greater_than_min() { let values = [10, 20, 30, 40]; let min = 22; - let index = unsafe { find_index_hint(values, |v: Field| min.lt(v)) }; + let index = unsafe { + find_index_hint(values, |v: Field| min.lt(v)) + }; assert_eq(index, 2); } @@ -234,7 +223,9 @@ fn find_index_greater_than_min() { fn find_index_not_found() { let values = [10, 20, 30, 40]; let min = 100; - let index = unsafe { find_index_hint(values, |v: Field| min.lt(v)) }; + let index = unsafe { + find_index_hint(values, |v: Field| min.lt(v)) + }; assert_eq(index, 4); } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_array_appended.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_array_appended.nr index 1377ada4486..268b4586063 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_array_appended.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_array_appended.nr @@ -1,16 +1,13 @@ -use crate::{ - abis::side_effect::Scoped, address::aztec_address::AztecAddress, traits::{Empty, is_empty}, -}; +use crate::{abis::side_effect::Scoped, address::aztec_address::AztecAddress, traits::{Empty, is_empty}}; pub fn assert_array_appended( dest: [T; N], source: [T; M], num_source_items: u32, - num_prepended_items: u32, + num_prepended_items: u32 ) where - T: Empty + Eq, -{ + T: Empty + Eq, { let items_propagated = num_prepended_items + num_source_items; assert(items_propagated <= N, "number of total items exceeds limit"); let mut should_check = false; @@ -21,11 +18,7 @@ where is_non_empty_item &= i != items_propagated; if should_check { if is_non_empty_item { - assert_eq( - dest[i], - source[i - num_prepended_items], - "source item does not append to dest", - ); + assert_eq(dest[i], source[i - num_prepended_items], "source item does not append to dest"); } else { assert(is_empty(dest[i]), "output should be appended with empty items"); } @@ -38,11 +31,10 @@ pub fn assert_array_appended_reversed( dest: [T; N], source: [T; M], num_source_items: u32, - num_prepended_items: u32, + num_prepended_items: u32 ) where - T: Empty + Eq, -{ + T: Empty + Eq, { let items_propagated = num_prepended_items + num_source_items; assert(items_propagated <= N, "number of total items exceeds limit"); let mut should_check = false; @@ -53,9 +45,7 @@ where if should_check { if is_non_empty_item { assert_eq( - dest[i], - source[items_propagated - i - 1], - "source item does not reversed append to dest", + dest[i], source[items_propagated - i - 1], "source item does not reversed append to dest" ); } else { assert(is_empty(dest[i]), "output should be appended with empty items"); @@ -70,12 +60,11 @@ pub fn assert_array_appended_scoped( source: [T; M], num_source_items: u32, num_prepended_items: u32, - contract_address: AztecAddress, + contract_address: AztecAddress ) where ST: Scoped + Empty + Eq, - T: Eq, -{ + T: Eq, { let items_propagated = num_prepended_items + num_source_items; assert(items_propagated <= N, "number of total items exceeds limit"); let mut should_check = false; @@ -86,14 +75,10 @@ where if should_check { if is_non_empty_item { assert_eq( - dest[i].inner(), - source[i - num_prepended_items], - "source item does not append to dest", + dest[i].inner(), source[i - num_prepended_items], "source item does not append to dest" ); assert_eq( - dest[i].contract_address(), - contract_address, - "propagated contract address does not match", + dest[i].contract_address(), contract_address, "propagated contract address does not match" ); } else { assert(is_empty(dest[i]), "output should be appended with empty items"); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_array_prepended.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_array_prepended.nr index c1b12e9ee59..ae6411b84d3 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_array_prepended.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_array_prepended.nr @@ -1,7 +1,10 @@ -pub fn assert_array_prepended(dest: [T; N], source: [T; N], num_source_items: u32) +pub fn assert_array_prepended( + dest: [T; N], + source: [T; N], + num_source_items: u32 +) where - T: Eq, -{ + T: Eq, { let mut proceed = true; for i in 0..source.len() { proceed &= i != num_source_items; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_array.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_array.nr index f2ad12fd38e..18dd10e0de9 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_array.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_array.nr @@ -1,8 +1,6 @@ use crate::{ traits::Empty, - utils::arrays::assert_combined_transformed_array::{ - assert_combined_transformed_array, combine_and_transform_arrays, - }, + utils::arrays::assert_combined_transformed_array::{assert_combined_transformed_array, combine_and_transform_arrays} }; // original_array(_lt/_gte) must be valid, i.e. validate_array(original_array) == true @@ -10,33 +8,31 @@ use crate::{ pub fn assert_combined_array( original_array_lt: [T; N], original_array_gte: [T; N], - combined_array: [T; N], + combined_array: [T; N] ) where - T: Empty + Eq, -{ + T: Empty + Eq, { assert_combined_transformed_array( original_array_lt, original_array_gte, combined_array, - |from: T, to: T| from == to, + |from: T, to: T| from == to ) } pub unconstrained fn combine_arrays( original_array_lt: [T; N], - original_array_gte: [T; N], + original_array_gte: [T; N] ) -> [T; N] where - T: Empty + Eq, -{ + T: Empty + Eq, { combine_and_transform_arrays(original_array_lt, original_array_gte, |from: T| from) } mod tests { use crate::{ tests::{types::TestValue, utils::pad_end}, - utils::arrays::assert_combined_array::{assert_combined_array, combine_arrays}, + utils::arrays::assert_combined_array::{assert_combined_array, combine_arrays} }; struct TestBuilder { @@ -56,27 +52,27 @@ mod tests { pub fn new() -> Self { let original_array_lt = pad_end( [ - TestValue { value: 11, counter: 2 }, - TestValue { value: 22, counter: 5 }, - TestValue { value: 33, counter: 3 }, - ], - TestValue::empty(), + TestValue { value: 11, counter: 2 }, + TestValue { value: 22, counter: 5 }, + TestValue { value: 33, counter: 3 } + ], + TestValue::empty() ); let original_array_gte = pad_end( [TestValue { value: 44, counter: 1 }, TestValue { value: 55, counter: 4 }], - TestValue::empty(), + TestValue::empty() ); let combined_array = pad_end( [ - TestValue { value: 11, counter: 2 }, - TestValue { value: 22, counter: 5 }, - TestValue { value: 33, counter: 3 }, - TestValue { value: 44, counter: 1 }, - TestValue { value: 55, counter: 4 }, - ], - TestValue::empty(), + TestValue { value: 11, counter: 2 }, + TestValue { value: 22, counter: 5 }, + TestValue { value: 33, counter: 3 }, + TestValue { value: 44, counter: 1 }, + TestValue { value: 55, counter: 4 } + ], + TestValue::empty() ); TestBuilder { original_array_lt, original_array_gte, combined_array } @@ -86,13 +82,14 @@ mod tests { assert_combined_array( self.original_array_lt, self.original_array_gte, - self.combined_array, + self.combined_array ); } pub fn check_and_execute(self) { - let combined = - unsafe { combine_arrays(self.original_array_lt, self.original_array_gte) }; + let combined = unsafe { + combine_arrays(self.original_array_lt, self.original_array_gte) + }; assert_eq(combined, self.combined_array); self.execute(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array.nr index a79a826af90..cf562184251 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array.nr @@ -3,18 +3,17 @@ mod get_combined_order_hints; use crate::{ abis::side_effect::Ordered, traits::{Empty, is_empty}, utils::arrays::{ - array_length, - assert_combined_sorted_transformed_value_array::get_combined_order_hints::{ - CombinedOrderHint, count_private_items, - }, - }, + array_length, + assert_combined_sorted_transformed_value_array::get_combined_order_hints::{CombinedOrderHint, count_private_items} +} }; fn get_num_private_items(array: [T; N]) -> u32 where - T: Ordered + Empty + Eq, -{ - let length = unsafe { count_private_items(array) }; + T: Ordered + Empty + Eq, { + let length = unsafe { + count_private_items(array) + }; if length != 0 { let last_private_item = array[length - 1]; assert(!is_empty(last_private_item) & (last_private_item.counter() == 0)); @@ -35,12 +34,11 @@ pub fn assert_combined_sorted_transformed_value_array_asc original_array_gte: [T; N], sorted_transformed_value_array: [S; N], is_transformed: fn[Env](T, S) -> bool, - hints: [CombinedOrderHint; N], + hints: [CombinedOrderHint; N] ) where T: Ordered + Empty + Eq, - S: Empty + Eq, -{ + S: Empty + Eq, { let num_private_lt = get_num_private_items(original_array_lt); let num_private_gte = get_num_private_items(original_array_gte); let total_private = num_private_lt + num_private_gte; @@ -66,11 +64,7 @@ where assert_eq(hint.original_index, i, "items with a counter of 0 should be prepended"); from_lt } else if should_be_private { - assert_eq( - hint.original_index, - i - num_private_lt, - "items with a counter of 0 should be prepended", - ); + assert_eq(hint.original_index, i - num_private_lt, "items with a counter of 0 should be prepended"); from_gte } else if should_be_public_gte { from_gte @@ -84,8 +78,7 @@ where if !should_be_empty { if !should_be_private { assert( - dest_counter > prev_counter, - "value array must be sorted by counter in ascending order", + dest_counter > prev_counter, "value array must be sorted by counter in ascending order" ); } } else { @@ -98,16 +91,15 @@ where mod tests { use crate::{ tests::utils::pad_end, - tests::types::{ - combine_two_values, is_combined_from_two_values, TestCombinedValue, TestTwoValues, - }, + tests::types::{combine_two_values, is_combined_from_two_values, TestCombinedValue, TestTwoValues}, utils::arrays::{ - array_merge, - assert_combined_sorted_transformed_value_array::{ - assert_combined_sorted_transformed_value_array_asc, - get_combined_order_hints::{CombinedOrderHint, get_combined_order_hints_asc}, - }, sort_by_counter::sort_by_counter_asc, - }, + array_merge, + assert_combined_sorted_transformed_value_array::{ + assert_combined_sorted_transformed_value_array_asc, + get_combined_order_hints::{CombinedOrderHint, get_combined_order_hints_asc} + }, + sort_by_counter::sort_by_counter_asc + } }; struct TestDataBuilder { @@ -121,38 +113,38 @@ mod tests { pub fn new() -> Self { let original_array_lt = pad_end( [ - TestTwoValues { value_1: 40, value_2: 7, counter: 0 }, - TestTwoValues { value_1: 70, value_2: 6, counter: 0 }, - TestTwoValues { value_1: 80, value_2: 1, counter: 22 }, - TestTwoValues { value_1: 30, value_2: 4, counter: 11 }, - ], - TestTwoValues::empty(), + TestTwoValues { value_1: 40, value_2: 7, counter: 0 }, + TestTwoValues { value_1: 70, value_2: 6, counter: 0 }, + TestTwoValues { value_1: 80, value_2: 1, counter: 22 }, + TestTwoValues { value_1: 30, value_2: 4, counter: 11 } + ], + TestTwoValues::empty() ); let original_array_gte = pad_end( [ - TestTwoValues { value_1: 20, value_2: 2, counter: 0 }, - TestTwoValues { value_1: 90, value_2: 3, counter: 0 }, - TestTwoValues { value_1: 50, value_2: 9, counter: 55 }, - TestTwoValues { value_1: 60, value_2: 8, counter: 33 }, - TestTwoValues { value_1: 10, value_2: 5, counter: 44 }, - ], - TestTwoValues::empty(), + TestTwoValues { value_1: 20, value_2: 2, counter: 0 }, + TestTwoValues { value_1: 90, value_2: 3, counter: 0 }, + TestTwoValues { value_1: 50, value_2: 9, counter: 55 }, + TestTwoValues { value_1: 60, value_2: 8, counter: 33 }, + TestTwoValues { value_1: 10, value_2: 5, counter: 44 } + ], + TestTwoValues::empty() ); let sorted_transformed_value_array = pad_end( [ - TestCombinedValue { value: 47 }, - TestCombinedValue { value: 76 }, - TestCombinedValue { value: 22 }, - TestCombinedValue { value: 93 }, - TestCombinedValue { value: 34 }, - TestCombinedValue { value: 81 }, - TestCombinedValue { value: 68 }, - TestCombinedValue { value: 15 }, - TestCombinedValue { value: 59 }, - ], - TestCombinedValue::empty(), + TestCombinedValue { value: 47 }, + TestCombinedValue { value: 76 }, + TestCombinedValue { value: 22 }, + TestCombinedValue { value: 93 }, + TestCombinedValue { value: 34 }, + TestCombinedValue { value: 81 }, + TestCombinedValue { value: 68 }, + TestCombinedValue { value: 15 }, + TestCombinedValue { value: 59 } + ], + TestCombinedValue::empty() ); let hints = [ @@ -167,15 +159,10 @@ mod tests { CombinedOrderHint { counter: 55, original_index: 2 }, CombinedOrderHint { counter: 0, original_index: 5 }, CombinedOrderHint { counter: 0, original_index: 6 }, - CombinedOrderHint { counter: 0, original_index: 7 }, + CombinedOrderHint { counter: 0, original_index: 7 } ]; - TestDataBuilder { - original_array_lt, - original_array_gte, - sorted_transformed_value_array, - hints, - } + TestDataBuilder { original_array_lt, original_array_gte, sorted_transformed_value_array, hints } } } @@ -183,30 +170,30 @@ mod tests { pub fn new_without_prepended() -> Self { let original_array_lt = pad_end( [ - TestTwoValues { value_1: 80, value_2: 1, counter: 22 }, - TestTwoValues { value_1: 30, value_2: 4, counter: 11 }, - ], - TestTwoValues::empty(), + TestTwoValues { value_1: 80, value_2: 1, counter: 22 }, + TestTwoValues { value_1: 30, value_2: 4, counter: 11 } + ], + TestTwoValues::empty() ); let original_array_gte = pad_end( [ - TestTwoValues { value_1: 50, value_2: 9, counter: 55 }, - TestTwoValues { value_1: 60, value_2: 8, counter: 33 }, - TestTwoValues { value_1: 10, value_2: 5, counter: 44 }, - ], - TestTwoValues::empty(), + TestTwoValues { value_1: 50, value_2: 9, counter: 55 }, + TestTwoValues { value_1: 60, value_2: 8, counter: 33 }, + TestTwoValues { value_1: 10, value_2: 5, counter: 44 } + ], + TestTwoValues::empty() ); let sorted_transformed_value_array = pad_end( [ - TestCombinedValue { value: 34 }, - TestCombinedValue { value: 81 }, - TestCombinedValue { value: 68 }, - TestCombinedValue { value: 15 }, - TestCombinedValue { value: 59 }, - ], - TestCombinedValue::empty(), + TestCombinedValue { value: 34 }, + TestCombinedValue { value: 81 }, + TestCombinedValue { value: 68 }, + TestCombinedValue { value: 15 }, + TestCombinedValue { value: 59 } + ], + TestCombinedValue::empty() ); let hints = [ @@ -217,15 +204,10 @@ mod tests { CombinedOrderHint { counter: 55, original_index: 0 }, CombinedOrderHint { counter: 0, original_index: 3 }, CombinedOrderHint { counter: 0, original_index: 4 }, - CombinedOrderHint { counter: 0, original_index: 5 }, + CombinedOrderHint { counter: 0, original_index: 5 } ]; - TestDataBuilder { - original_array_lt, - original_array_gte, - sorted_transformed_value_array, - hints, - } + TestDataBuilder { original_array_lt, original_array_gte, sorted_transformed_value_array, hints } } } @@ -248,7 +230,7 @@ mod tests { self.original_array_gte, self.sorted_transformed_value_array, is_combined_from_two_values, - self.hints, + self.hints ); } @@ -259,8 +241,7 @@ mod tests { assert_eq(hints, self.hints); let sorted = unsafe { - sort_by_counter_asc(array_merge(self.original_array_lt, self.original_array_gte)) - .map(combine_two_values) + sort_by_counter_asc(array_merge(self.original_array_lt, self.original_array_gte)).map(combine_two_values) }; assert_eq(sorted, self.sorted_transformed_value_array); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array/get_combined_order_hints.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array/get_combined_order_hints.nr index 548362fb9df..718b4607fde 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array/get_combined_order_hints.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array/get_combined_order_hints.nr @@ -1,9 +1,6 @@ use crate::{ abis::side_effect::Ordered, traits::{Empty, is_empty}, - utils::arrays::{ - array_length, sort_by_counter::compare_by_counter_empty_padded_asc, - get_sorted_tuple::get_sorted_tuple, - }, + utils::arrays::{array_length, sort_by_counter::compare_by_counter_empty_padded_asc, get_sorted_tuple::get_sorted_tuple} }; pub struct CombinedOrderHint { @@ -25,8 +22,7 @@ impl Eq for CombinedOrderHint { pub unconstrained fn count_private_items(array: [T; N]) -> u32 where - T: Ordered + Empty + Eq, -{ + T: Ordered + Empty + Eq, { let mut length = 0; for item in array { if !is_empty(item) & (item.counter() == 0) { @@ -38,11 +34,10 @@ where pub unconstrained fn get_combined_order_hints_asc( array_lt: [T; N], - array_gte: [T; N], + array_gte: [T; N] ) -> [CombinedOrderHint; N] where - T: Ordered + Eq + Empty, -{ + T: Ordered + Eq + Empty, { let mut hints = [CombinedOrderHint::empty(); N]; let sorted_lt = get_sorted_tuple(array_lt, compare_by_counter_empty_padded_asc); let sorted_gte = get_sorted_tuple(array_gte, compare_by_counter_empty_padded_asc); @@ -70,17 +65,17 @@ where mod tests { use crate::{ tests::{types::TestValue, utils::pad_end}, - utils::arrays::assert_combined_sorted_transformed_value_array::get_combined_order_hints::{ - CombinedOrderHint, get_combined_order_hints_asc, - }, + utils::arrays::assert_combined_sorted_transformed_value_array::get_combined_order_hints::{CombinedOrderHint, get_combined_order_hints_asc} }; fn asc_to_equal( array_lt: [TestValue; N], array_gte: [TestValue; N], - expected: [CombinedOrderHint; N], + expected: [CombinedOrderHint; N] ) { - let hints = unsafe { get_combined_order_hints_asc(array_lt, array_gte) }; + let hints = unsafe { + get_combined_order_hints_asc(array_lt, array_gte) + }; assert_eq(hints, expected); } @@ -88,19 +83,19 @@ mod tests { fn get_combined_order_hints_asc_full_non_empty() { let array_lt = pad_end( [ - TestValue { value: 600, counter: 9 }, - TestValue { value: 400, counter: 3 }, - TestValue { value: 500, counter: 6 }, - ], - TestValue::empty(), + TestValue { value: 600, counter: 9 }, + TestValue { value: 400, counter: 3 }, + TestValue { value: 500, counter: 6 } + ], + TestValue::empty() ); let array_gte = pad_end( [ - TestValue { value: 200, counter: 13 }, - TestValue { value: 100, counter: 19 }, - TestValue { value: 300, counter: 16 }, - ], - TestValue::empty(), + TestValue { value: 200, counter: 13 }, + TestValue { value: 100, counter: 19 }, + TestValue { value: 300, counter: 16 } + ], + TestValue::empty() ); let expected_hints = [ CombinedOrderHint { counter: 3, original_index: 1 }, @@ -108,7 +103,7 @@ mod tests { CombinedOrderHint { counter: 9, original_index: 0 }, CombinedOrderHint { counter: 13, original_index: 0 }, CombinedOrderHint { counter: 16, original_index: 2 }, - CombinedOrderHint { counter: 19, original_index: 1 }, + CombinedOrderHint { counter: 19, original_index: 1 } ]; asc_to_equal(array_lt, array_gte, expected_hints); } @@ -117,7 +112,7 @@ mod tests { fn get_combined_order_hints_asc_padded_empty() { let array_lt = pad_end( [TestValue { value: 500, counter: 6 }, TestValue { value: 400, counter: 3 }], - TestValue::empty(), + TestValue::empty() ); let array_gte = pad_end([TestValue { value: 100, counter: 19 }], TestValue::empty()); let expected_hints = [ @@ -125,7 +120,7 @@ mod tests { CombinedOrderHint { counter: 6, original_index: 0 }, CombinedOrderHint { counter: 19, original_index: 0 }, CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 0, original_index: 2 }, + CombinedOrderHint { counter: 0, original_index: 2 } ]; asc_to_equal(array_lt, array_gte, expected_hints); } @@ -135,13 +130,13 @@ mod tests { let array_lt = [TestValue::empty(); 4]; let array_gte = pad_end( [TestValue { value: 200, counter: 13 }, TestValue { value: 100, counter: 19 }], - TestValue::empty(), + TestValue::empty() ); let expected_hints = [ CombinedOrderHint { counter: 13, original_index: 0 }, CombinedOrderHint { counter: 19, original_index: 1 }, CombinedOrderHint { counter: 0, original_index: 2 }, - CombinedOrderHint { counter: 0, original_index: 3 }, + CombinedOrderHint { counter: 0, original_index: 3 } ]; asc_to_equal(array_lt, array_gte, expected_hints); } @@ -150,14 +145,14 @@ mod tests { fn get_combined_order_hints_asc_gte_empty() { let array_lt = pad_end( [TestValue { value: 400, counter: 3 }, TestValue { value: 500, counter: 6 }], - TestValue::empty(), + TestValue::empty() ); let array_gte = [TestValue::empty(); 4]; let expected_hints = [ CombinedOrderHint { counter: 3, original_index: 0 }, CombinedOrderHint { counter: 6, original_index: 1 }, CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, + CombinedOrderHint { counter: 0, original_index: 1 } ]; asc_to_equal(array_lt, array_gte, expected_hints); } @@ -169,7 +164,7 @@ mod tests { let expected_hints = [ CombinedOrderHint { counter: 0, original_index: 0 }, CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 0, original_index: 2 }, + CombinedOrderHint { counter: 0, original_index: 2 } ]; asc_to_equal(array_lt, array_gte, expected_hints); } @@ -178,20 +173,20 @@ mod tests { fn get_combined_order_hints_asc_prepended_zero_counters() { let array_lt = pad_end( [ - TestValue { value: 700, counter: 0 }, - TestValue { value: 500, counter: 0 }, - TestValue { value: 100, counter: 16 }, - TestValue { value: 400, counter: 13 }, - ], - TestValue::empty(), + TestValue { value: 700, counter: 0 }, + TestValue { value: 500, counter: 0 }, + TestValue { value: 100, counter: 16 }, + TestValue { value: 400, counter: 13 } + ], + TestValue::empty() ); let array_gte = pad_end( [ - TestValue { value: 300, counter: 0 }, - TestValue { value: 600, counter: 0 }, - TestValue { value: 200, counter: 19 }, - ], - TestValue::empty(), + TestValue { value: 300, counter: 0 }, + TestValue { value: 600, counter: 0 }, + TestValue { value: 200, counter: 19 } + ], + TestValue::empty() ); let expected_hints = [ CombinedOrderHint { counter: 0, original_index: 0 }, @@ -203,7 +198,7 @@ mod tests { CombinedOrderHint { counter: 19, original_index: 2 }, CombinedOrderHint { counter: 0, original_index: 3 }, CombinedOrderHint { counter: 0, original_index: 4 }, - CombinedOrderHint { counter: 0, original_index: 5 }, + CombinedOrderHint { counter: 0, original_index: 5 } ]; asc_to_equal(array_lt, array_gte, expected_hints); } @@ -213,12 +208,12 @@ mod tests { let array_lt = [TestValue::empty(); 6]; let array_gte = pad_end( [ - TestValue { value: 300, counter: 0 }, - TestValue { value: 600, counter: 0 }, - TestValue { value: 200, counter: 19 }, - TestValue { value: 400, counter: 13 }, - ], - TestValue::empty(), + TestValue { value: 300, counter: 0 }, + TestValue { value: 600, counter: 0 }, + TestValue { value: 200, counter: 19 }, + TestValue { value: 400, counter: 13 } + ], + TestValue::empty() ); let expected_hints = [ CombinedOrderHint { counter: 0, original_index: 0 }, @@ -226,7 +221,7 @@ mod tests { CombinedOrderHint { counter: 13, original_index: 3 }, CombinedOrderHint { counter: 19, original_index: 2 }, CombinedOrderHint { counter: 0, original_index: 4 }, - CombinedOrderHint { counter: 0, original_index: 5 }, + CombinedOrderHint { counter: 0, original_index: 5 } ]; asc_to_equal(array_lt, array_gte, expected_hints); } @@ -235,12 +230,12 @@ mod tests { fn get_combined_order_hints_asc_prepended_zero_counters_gte_empty() { let array_lt = pad_end( [ - TestValue { value: 300, counter: 0 }, - TestValue { value: 600, counter: 0 }, - TestValue { value: 200, counter: 19 }, - TestValue { value: 400, counter: 13 }, - ], - TestValue::empty(), + TestValue { value: 300, counter: 0 }, + TestValue { value: 600, counter: 0 }, + TestValue { value: 200, counter: 19 }, + TestValue { value: 400, counter: 13 } + ], + TestValue::empty() ); let array_gte = [TestValue::empty(); 6]; let expected_hints = [ @@ -249,7 +244,7 @@ mod tests { CombinedOrderHint { counter: 13, original_index: 3 }, CombinedOrderHint { counter: 19, original_index: 2 }, CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, + CombinedOrderHint { counter: 0, original_index: 1 } ]; asc_to_equal(array_lt, array_gte, expected_hints); } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_transformed_array.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_transformed_array.nr index 082f33ebdd6..0f21ce05667 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_transformed_array.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_transformed_array.nr @@ -6,11 +6,10 @@ pub fn assert_combined_transformed_array( original_array_lt: [T; N], original_array_gte: [T; N], combined_array: [S; N], - is_transformed: fn[Env](T, S) -> bool, + is_transformed: fn[Env](T, S) -> bool ) where - T: Empty + Eq, -{ + T: Empty + Eq, { let num_lt = array_length(original_array_lt); let mut is_lt = true; for i in 0..N { @@ -31,11 +30,10 @@ where pub unconstrained fn combine_and_transform_arrays( original_array_lt: [T; N], original_array_gte: [T; N], - transform: fn[Env](T) -> S, + transform: fn[Env](T) -> S ) -> [S; N] where - T: Empty + Eq, -{ + T: Empty + Eq, { let mut combined = original_array_lt.map(transform); let num_lt = array_length(original_array_lt); @@ -51,13 +49,8 @@ where mod tests { use crate::{ - tests::{ - types::{is_summed_from_two_values, sum_two_values, TestTwoValues, TestValue}, - utils::pad_end, - }, - utils::arrays::assert_combined_transformed_array::{ - assert_combined_transformed_array, combine_and_transform_arrays, - }, + tests::{types::{is_summed_from_two_values, sum_two_values, TestTwoValues, TestValue}, utils::pad_end}, + utils::arrays::assert_combined_transformed_array::{assert_combined_transformed_array, combine_and_transform_arrays} }; struct TestBuilder { @@ -77,30 +70,30 @@ mod tests { pub fn new() -> Self { let original_array_lt = pad_end( [ - TestTwoValues { value_1: 10, value_2: 1, counter: 2 }, - TestTwoValues { value_1: 20, value_2: 2, counter: 5 }, - TestTwoValues { value_1: 30, value_2: 3, counter: 3 }, - ], - TestTwoValues::empty(), + TestTwoValues { value_1: 10, value_2: 1, counter: 2 }, + TestTwoValues { value_1: 20, value_2: 2, counter: 5 }, + TestTwoValues { value_1: 30, value_2: 3, counter: 3 } + ], + TestTwoValues::empty() ); let original_array_gte = pad_end( [ - TestTwoValues { value_1: 40, value_2: 4, counter: 1 }, - TestTwoValues { value_1: 50, value_2: 5, counter: 4 }, - ], - TestTwoValues::empty(), + TestTwoValues { value_1: 40, value_2: 4, counter: 1 }, + TestTwoValues { value_1: 50, value_2: 5, counter: 4 } + ], + TestTwoValues::empty() ); let combined_array = pad_end( [ - TestValue { value: 11, counter: 2 }, - TestValue { value: 22, counter: 5 }, - TestValue { value: 33, counter: 3 }, - TestValue { value: 44, counter: 1 }, - TestValue { value: 55, counter: 4 }, - ], - TestValue::empty(), + TestValue { value: 11, counter: 2 }, + TestValue { value: 22, counter: 5 }, + TestValue { value: 33, counter: 3 }, + TestValue { value: 44, counter: 1 }, + TestValue { value: 55, counter: 4 } + ], + TestValue::empty() ); TestBuilder { original_array_lt, original_array_gte, combined_array } @@ -111,7 +104,7 @@ mod tests { self.original_array_lt, self.original_array_gte, self.combined_array, - is_summed_from_two_values, + is_summed_from_two_values ); } @@ -120,7 +113,7 @@ mod tests { combine_and_transform_arrays( self.original_array_lt, self.original_array_gte, - sum_two_values, + sum_two_values ) }; assert_eq(combined, self.combined_array); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_deduped_array.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_deduped_array.nr index 17460434e88..b83c3ee6f61 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_deduped_array.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_deduped_array.nr @@ -1,11 +1,13 @@ use crate::{abis::side_effect::{Inner, Overridable}, traits::{Empty, is_empty}}; // Check that deduped_array contains values that are not being overriden, i.e. override_counter == 0. -pub fn assert_deduped_array(original_array: [S; N], deduped_array: [T; N]) +pub fn assert_deduped_array( + original_array: [S; N], + deduped_array: [T; N] +) where S: Overridable + Inner, - T: Eq + Empty, -{ + T: Eq + Empty, { let mut num_added = 0; for i in 0..original_array.len() { let original = original_array[i]; @@ -25,8 +27,7 @@ where pub unconstrained fn dedupe_array(original_array: [S; N]) -> [T; N] where - S: Overridable + Inner, -{ + S: Overridable + Inner, { let mut deduped = BoundedVec::new(); for i in 0..original_array.len() { let original = original_array[i]; @@ -40,7 +41,7 @@ where mod tests { use crate::{ abis::side_effect::{Inner, Overridable}, tests::{types::TestValue, utils::pad_end}, - traits::Empty, utils::arrays::assert_deduped_array::{assert_deduped_array, dedupe_array}, + traits::Empty, utils::arrays::assert_deduped_array::{assert_deduped_array, dedupe_array} }; struct TestItem { @@ -93,18 +94,18 @@ mod tests { TestValue { value: 44, counter: 4 }, TestValue { value: 11, counter: 6 }, TestValue { value: 11, counter: 3 }, - TestValue { value: 33, counter: 5 }, + TestValue { value: 33, counter: 5 } ]; let mut original_array = pad_end( values.map(|value: TestValue| TestItem { value, override_by: TestValue::empty() }), - TestItem::empty(), + TestItem::empty() ); original_array[1].override_by = values[4]; original_array[4].override_by = values[3]; let deduped_array = pad_end( [values[0], values[2], values[3], values[5]], - TestValue::empty(), + TestValue::empty() ); TestBuilder { original_array, deduped_array } @@ -115,7 +116,9 @@ mod tests { } pub fn check_and_execute(self) { - let deduped = unsafe { dedupe_array(self.original_array) }; + let deduped = unsafe { + dedupe_array(self.original_array) + }; assert_eq(self.deduped_array, deduped); self.execute(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_exposed_sorted_transformed_value_array.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_exposed_sorted_transformed_value_array.nr index 40f0072676e..9d9d5b8f5d6 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_exposed_sorted_transformed_value_array.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_exposed_sorted_transformed_value_array.nr @@ -2,9 +2,7 @@ mod get_order_hints; use crate::{ abis::side_effect::Ordered, traits::{Empty, is_empty}, - utils::arrays::{ - array_length, assert_exposed_sorted_transformed_value_array::get_order_hints::OrderHint, - }, + utils::arrays::{array_length, assert_exposed_sorted_transformed_value_array::get_order_hints::OrderHint} }; // original_array must be valid, i.e. validate_array(original_array) == true @@ -13,20 +11,18 @@ pub fn assert_exposed_sorted_transformed_value_array( original_array: [T; N], exposed_sorted_transformed_value_array: [S; N], is_transformed: fn[Env](T, S) -> bool, - hints: [OrderHint; N], + hints: [OrderHint; N] ) where T: Ordered + Empty + Eq, - S: Empty + Eq, -{ + S: Empty + Eq, { let num_non_empty_items = array_length(original_array); let mut should_be_empty = false; for i in 0..N { should_be_empty |= i == num_non_empty_items; if should_be_empty { assert( - is_empty(exposed_sorted_transformed_value_array[i]), - "array must be padded with empty items", + is_empty(exposed_sorted_transformed_value_array[i]), "array must be padded with empty items" ); } else { let original = original_array[i]; @@ -36,8 +32,7 @@ where assert_eq(original.counter(), hints[sorted_index].counter, "incorrect hinted counter"); if i != 0 { assert( - hints[i].counter > hints[i - 1].counter, - "value array must be sorted by counter in ascending order", + hints[i].counter > hints[i - 1].counter, "value array must be sorted by counter in ascending order" ); } } @@ -47,9 +42,7 @@ where mod tests { use crate::{ tests::types::{is_combined_from_two_values, TestCombinedValue, TestTwoValues}, - utils::arrays::assert_exposed_sorted_transformed_value_array::{ - assert_exposed_sorted_transformed_value_array, get_order_hints::OrderHint, - }, + utils::arrays::assert_exposed_sorted_transformed_value_array::{assert_exposed_sorted_transformed_value_array, get_order_hints::OrderHint} }; struct TestDataBuilder { @@ -66,7 +59,7 @@ mod tests { TestTwoValues { value_1: 30, value_2: 7, counter: 11 }, TestTwoValues { value_1: 40, value_2: 8, counter: 33 }, TestTwoValues::empty(), - TestTwoValues::empty(), + TestTwoValues::empty() ]; let exposed_sorted_transformed_value_array = [ @@ -75,7 +68,7 @@ mod tests { TestCombinedValue { value: 48 }, TestCombinedValue { value: 15 }, TestCombinedValue::empty(), - TestCombinedValue::empty(), + TestCombinedValue::empty() ]; let hints = [ @@ -84,7 +77,7 @@ mod tests { OrderHint { counter: 33, sorted_index: 0 }, OrderHint { counter: 44, sorted_index: 2 }, OrderHint { counter: 0, sorted_index: 4 }, - OrderHint { counter: 0, sorted_index: 5 }, + OrderHint { counter: 0, sorted_index: 5 } ]; TestDataBuilder { original_array, exposed_sorted_transformed_value_array, hints } @@ -95,7 +88,7 @@ mod tests { self.original_array, self.exposed_sorted_transformed_value_array, is_combined_from_two_values, - self.hints, + self.hints ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_exposed_sorted_transformed_value_array/get_order_hints.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_exposed_sorted_transformed_value_array/get_order_hints.nr index eb2f3c4827c..be2177cdd9c 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_exposed_sorted_transformed_value_array/get_order_hints.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_exposed_sorted_transformed_value_array/get_order_hints.nr @@ -1,10 +1,9 @@ use crate::{ abis::side_effect::Ordered, traits::Empty, utils::arrays::{ - sort_by_counter::{ - compare_by_counter_empty_padded_asc, compare_by_counter_empty_padded_desc, - }, get_sorted_tuple::get_sorted_tuple, - }, + sort_by_counter::{compare_by_counter_empty_padded_asc, compare_by_counter_empty_padded_desc}, + get_sorted_tuple::get_sorted_tuple +} }; pub struct OrderHint { @@ -26,11 +25,10 @@ impl Eq for OrderHint { pub unconstrained fn get_order_hints( array: [T; N], - ordering: fn(T, T) -> bool, + ordering: fn(T, T) -> bool ) -> [OrderHint; N] where - T: Ordered, -{ + T: Ordered, { let sorted_tuples = get_sorted_tuple(array, ordering); let mut hints = [OrderHint::empty(); N]; @@ -46,24 +44,20 @@ where pub unconstrained fn get_order_hints_asc(array: [T; N]) -> [OrderHint; N] where - T: Ordered + Eq + Empty, -{ + T: Ordered + Eq + Empty, { get_order_hints(array, compare_by_counter_empty_padded_asc) } pub unconstrained fn get_order_hints_desc(array: [T; N]) -> [OrderHint; N] where - T: Ordered + Eq + Empty, -{ + T: Ordered + Eq + Empty, { get_order_hints(array, compare_by_counter_empty_padded_desc) } mod tests { use crate::{ tests::{types::TestValue, utils::pad_end}, - utils::arrays::assert_exposed_sorted_transformed_value_array::get_order_hints::{ - get_order_hints_asc, get_order_hints_desc, OrderHint, - }, + utils::arrays::assert_exposed_sorted_transformed_value_array::get_order_hints::{get_order_hints_asc, get_order_hints_desc, OrderHint} }; struct TestBuilder { @@ -75,7 +69,7 @@ mod tests { let array = [ TestValue { value: 100, counter: 9 }, TestValue { value: 200, counter: 3 }, - TestValue { value: 300, counter: 6 }, + TestValue { value: 300, counter: 6 } ]; TestBuilder { array } } @@ -85,11 +79,11 @@ mod tests { pub fn new_padded() -> Self { let array = pad_end( [ - TestValue { value: 100, counter: 9 }, - TestValue { value: 200, counter: 3 }, - TestValue { value: 300, counter: 6 }, - ], - TestValue::empty(), + TestValue { value: 100, counter: 9 }, + TestValue { value: 200, counter: 3 }, + TestValue { value: 300, counter: 6 } + ], + TestValue::empty() ); TestBuilder { array } } @@ -97,12 +91,16 @@ mod tests { impl TestBuilder { pub fn asc_to_equal(self, expected: [OrderHint; N]) { - let hints = unsafe { get_order_hints_asc(self.array) }; + let hints = unsafe { + get_order_hints_asc(self.array) + }; assert_eq(hints, expected); } pub fn desc_to_equal(self, expected: [OrderHint; N]) { - let hints = unsafe { get_order_hints_desc(self.array) }; + let hints = unsafe { + get_order_hints_desc(self.array) + }; assert_eq(hints, expected); } } @@ -113,7 +111,7 @@ mod tests { let expected_hints = [ OrderHint { counter: 3, sorted_index: 2 }, OrderHint { counter: 6, sorted_index: 0 }, - OrderHint { counter: 9, sorted_index: 1 }, + OrderHint { counter: 9, sorted_index: 1 } ]; builder.asc_to_equal(expected_hints); } @@ -126,7 +124,7 @@ mod tests { OrderHint { counter: 6, sorted_index: 0 }, OrderHint { counter: 9, sorted_index: 1 }, OrderHint { counter: 0, sorted_index: 3 }, - OrderHint { counter: 0, sorted_index: 4 }, + OrderHint { counter: 0, sorted_index: 4 } ]; builder.asc_to_equal(expected_hints); } @@ -137,7 +135,7 @@ mod tests { let expected_hints = [ OrderHint { counter: 9, sorted_index: 0 }, OrderHint { counter: 6, sorted_index: 2 }, - OrderHint { counter: 3, sorted_index: 1 }, + OrderHint { counter: 3, sorted_index: 1 } ]; builder.desc_to_equal(expected_hints); } @@ -150,7 +148,7 @@ mod tests { OrderHint { counter: 6, sorted_index: 2 }, OrderHint { counter: 3, sorted_index: 1 }, OrderHint { counter: 0, sorted_index: 3 }, - OrderHint { counter: 0, sorted_index: 4 }, + OrderHint { counter: 0, sorted_index: 4 } ]; builder.desc_to_equal(expected_hints); } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_sorted_array.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_sorted_array.nr index 9877e53be36..4541bde6ec6 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_sorted_array.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_sorted_array.nr @@ -4,11 +4,10 @@ pub fn assert_sorted_array( original_array: [T; N], sorted_array: [T; N], sorted_indexes: [u32; N], - ordering: fn[Env](T, T) -> bool, + ordering: fn[Env](T, T) -> bool ) where - T: Eq + Empty, -{ + T: Eq + Empty, { let mut seen_empty = false; for i in 0..N { let original_value = original_array[i]; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_sorted_transformed_value_array.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_sorted_transformed_value_array.nr index ec64f29f818..2506a11cd63 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_sorted_transformed_value_array.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_sorted_transformed_value_array.nr @@ -4,18 +4,17 @@ pub fn assert_sorted_transformed_value_array( original_array: [T; N], sorted_transformed_value_array: [S; N], is_transformed: fn[Env](T, S) -> bool, - sorted_indexes: [u32; N], + sorted_indexes: [u32; N] ) where T: Eq + Empty, - S: Ordered + Eq + Empty, -{ + S: Ordered + Eq + Empty, { assert_sorted_transformed_value_array_capped_size( original_array, sorted_transformed_value_array, is_transformed, sorted_indexes, - N, + N ); } @@ -26,12 +25,11 @@ pub fn assert_sorted_transformed_value_array_capped_size( sorted_transformed_value_array: [S; N], is_transformed: fn[Env](T, S) -> bool, sorted_indexes: [u32; N], - capped_size: u32, + capped_size: u32 ) where T: Eq + Empty, - S: Ordered + Eq + Empty, -{ + S: Ordered + Eq + Empty, { let num_non_empty_items = array_length(original_array); let mut should_be_empty = false; for i in 0..N { @@ -50,8 +48,7 @@ where assert(is_mapped_item_empty, "unexpected non-empty item"); } else if i != 0 { assert( - mapped_item.counter() > sorted_transformed_value_array[i - 1].counter(), - "value array must be sorted by counter in ascending order", + mapped_item.counter() > sorted_transformed_value_array[i - 1].counter(), "value array must be sorted by counter in ascending order" ); } } else { @@ -63,10 +60,7 @@ where mod tests { use crate::{ tests::types::{is_summed_from_two_values, TestTwoValues, TestValue}, - utils::arrays::assert_sorted_transformed_value_array::{ - assert_sorted_transformed_value_array, - assert_sorted_transformed_value_array_capped_size, - }, + utils::arrays::assert_sorted_transformed_value_array::{assert_sorted_transformed_value_array, assert_sorted_transformed_value_array_capped_size} }; struct TestDataBuilder { @@ -83,7 +77,7 @@ mod tests { TestTwoValues { value_1: 30, value_2: 7, counter: 11 }, TestTwoValues { value_1: 40, value_2: 8, counter: 33 }, TestTwoValues::empty(), - TestTwoValues::empty(), + TestTwoValues::empty() ]; let sorted_transformed_value_array = [ @@ -92,7 +86,7 @@ mod tests { TestValue { value: 48, counter: 33 }, TestValue { value: 15, counter: 44 }, TestValue::empty(), - TestValue::empty(), + TestValue::empty() ]; let sorted_indexes = [3, 1, 0, 2, 4, 5]; @@ -105,7 +99,7 @@ mod tests { self.original_array, self.sorted_transformed_value_array, is_summed_from_two_values, - self.sorted_indexes, + self.sorted_indexes ); } @@ -115,7 +109,7 @@ mod tests { self.sorted_transformed_value_array, is_summed_from_two_values, self.sorted_indexes, - capped_size, + capped_size ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_sorted_transformed_value_arrays.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_sorted_transformed_value_arrays.nr index d5d058e54ea..f608b3f57b8 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_sorted_transformed_value_arrays.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_sorted_transformed_value_arrays.nr @@ -3,10 +3,9 @@ mod get_split_order_hints; use crate::{ abis::side_effect::Ordered, traits::Empty, utils::arrays::{ - array_length, - assert_split_sorted_transformed_value_arrays::get_split_order_hints::SplitOrderHints, - validate_array, - }, + array_length, assert_split_sorted_transformed_value_arrays::get_split_order_hints::SplitOrderHints, + validate_array +} }; // original_array must be valid, i.e. validate_array(original_array) == true @@ -20,12 +19,11 @@ fn assert_split_sorted_transformed_value_arrays( sorted_counters_lt: [u32; N], // Counters of the values in sorted_transformed_value_array_lt. sorted_counters_gte: [u32; N], // Counters of the values in sorted_transformed_value_array_gte. index_hints: [u32; N], // The index of the item in the correspinding sorted_transformed_value_array_(lt/gte) for each item in the original_array. - ascending: bool, // Whether the items in sorted_transformed_value_array_(lt/gte) is in ascending order. + ascending: bool // Whether the items in sorted_transformed_value_array_(lt/gte) is in ascending order. ) where T: Ordered + Empty + Eq, - S: Empty + Eq, -{ + S: Empty + Eq, { // Can use array_length instead of validate_array for the original_array because it's taken from the previous kernel and guaranteed to be valid. let total_num = array_length(original_array); @@ -42,10 +40,7 @@ where let (sorted_value, sorted_counter) = if is_lt { (sorted_transformed_value_array_lt[sorted_index], sorted_counters_lt[sorted_index]) } else { - ( - sorted_transformed_value_array_gte[sorted_index], - sorted_counters_gte[sorted_index], - ) + (sorted_transformed_value_array_gte[sorted_index], sorted_counters_gte[sorted_index]) }; assert_eq(value, sorted_value, "mismatch sorted values"); assert_eq(original.counter(), sorted_counter, "mismatch counters"); @@ -85,12 +80,11 @@ pub fn assert_split_sorted_transformed_value_arrays_asc( split_counter: u32, sorted_transformed_value_array_lt: [S; N], sorted_transformed_value_array_gte: [S; N], - hints: SplitOrderHints, + hints: SplitOrderHints ) where T: Ordered + Empty + Eq, - S: Empty + Eq, -{ + S: Empty + Eq, { assert_split_sorted_transformed_value_arrays( original_array, transformed_value_array, @@ -100,7 +94,7 @@ where hints.sorted_counters_lt, hints.sorted_counters_gte, hints.sorted_indexes, - true, + true ); } @@ -110,12 +104,11 @@ pub fn assert_split_sorted_transformed_value_arrays_desc( split_counter: u32, sorted_transformed_value_array_lt: [S; N], sorted_transformed_value_array_gte: [S; N], - hints: SplitOrderHints, + hints: SplitOrderHints ) where T: Ordered + Empty + Eq, - S: Empty + Eq, -{ + S: Empty + Eq, { assert_split_sorted_transformed_value_arrays( original_array, transformed_value_array, @@ -125,7 +118,7 @@ where hints.sorted_counters_lt, hints.sorted_counters_gte, hints.sorted_indexes, - false, + false ); } @@ -133,10 +126,9 @@ mod tests { use crate::{ tests::types::{combine_two_values, TestCombinedValue, TestTwoValues}, utils::arrays::assert_split_sorted_transformed_value_arrays::{ - assert_split_sorted_transformed_value_arrays_asc, - assert_split_sorted_transformed_value_arrays_desc, - get_split_order_hints::SplitOrderHints, - }, + assert_split_sorted_transformed_value_arrays_asc, + assert_split_sorted_transformed_value_arrays_desc, get_split_order_hints::SplitOrderHints + } }; global original_array = [ @@ -169,13 +161,12 @@ mod tests { sorted_transformed_value_array_gte: [TestCombinedValue::empty(); 8], split_counter: 0, hints: SplitOrderHints::empty(), - ascending: false, + ascending: false } } pub fn new() -> Self { - let transformed_value_array = - original_array.map(|item: TestTwoValues| combine_two_values(item)); + let transformed_value_array = original_array.map(|item: TestTwoValues| combine_two_values(item)); let split_counter = 15; let sorted_transformed_value_array_lt = [ @@ -186,7 +177,7 @@ mod tests { TestCombinedValue::empty(), TestCombinedValue::empty(), TestCombinedValue::empty(), - TestCombinedValue::empty(), + TestCombinedValue::empty() ]; let sorted_transformed_value_array_gte = [ TestCombinedValue { value: 49 }, @@ -196,12 +187,12 @@ mod tests { TestCombinedValue::empty(), TestCombinedValue::empty(), TestCombinedValue::empty(), - TestCombinedValue::empty(), + TestCombinedValue::empty() ]; let hints = SplitOrderHints { sorted_counters_lt: [0, 11, 0, 0, 0, 0, 0, 0], sorted_counters_gte: [22, 33, 44, 0, 0, 0, 0, 0], - sorted_indexes: [1, 2, 1, 0, 0, 0, 0, 0], + sorted_indexes: [1, 2, 1, 0, 0, 0, 0, 0] }; TestDataBuilder { @@ -211,13 +202,12 @@ mod tests { sorted_transformed_value_array_gte, split_counter, hints, - ascending: true, + ascending: true } } pub fn new_desc() -> Self { - let transformed_value_array = - original_array.map(|item: TestTwoValues| combine_two_values(item)); + let transformed_value_array = original_array.map(|item: TestTwoValues| combine_two_values(item)); let split_counter = 15; let sorted_transformed_value_array_lt = [ @@ -228,7 +218,7 @@ mod tests { TestCombinedValue::empty(), TestCombinedValue::empty(), TestCombinedValue::empty(), - TestCombinedValue::empty(), + TestCombinedValue::empty() ]; let sorted_transformed_value_array_gte = [ TestCombinedValue { value: 16 }, @@ -238,12 +228,12 @@ mod tests { TestCombinedValue::empty(), TestCombinedValue::empty(), TestCombinedValue::empty(), - TestCombinedValue::empty(), + TestCombinedValue::empty() ]; let hints = SplitOrderHints { sorted_counters_lt: [11, 0, 0, 0, 0, 0, 0, 0], sorted_counters_gte: [44, 33, 22, 0, 0, 0, 0, 0], - sorted_indexes: [1, 0, 0, 1, 2, 0, 0, 0], + sorted_indexes: [1, 0, 0, 1, 2, 0, 0, 0] }; TestDataBuilder { @@ -253,20 +243,19 @@ mod tests { sorted_transformed_value_array_gte, split_counter, hints, - ascending: false, + ascending: false } } pub fn update_sorted_index(&mut self, counter: u32, new_index: u32) { let mut original_index = original_array.len(); for i in 0..original_array.len() { - if (original_index == original_array.len()) & (original_array[i].counter == counter) - { - original_index = i; - } + if (original_index == original_array.len()) & (original_array[i].counter == counter) { + original_index = i; } - self.hints.sorted_indexes[original_index] = new_index; } + self.hints.sorted_indexes[original_index] = new_index; + } pub fn execute(self) { if self.ascending { @@ -276,7 +265,7 @@ mod tests { self.split_counter, self.sorted_transformed_value_array_lt, self.sorted_transformed_value_array_gte, - self.hints, + self.hints ); } else { assert_split_sorted_transformed_value_arrays_desc( @@ -285,7 +274,7 @@ mod tests { self.split_counter, self.sorted_transformed_value_array_lt, self.sorted_transformed_value_array_gte, - self.hints, + self.hints ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_sorted_transformed_value_arrays/get_split_order_hints.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_sorted_transformed_value_arrays/get_split_order_hints.nr index ebb47835188..ebe43971a37 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_sorted_transformed_value_arrays/get_split_order_hints.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_sorted_transformed_value_arrays/get_split_order_hints.nr @@ -1,10 +1,9 @@ use crate::{ abis::side_effect::Ordered, traits::{Empty, is_empty}, utils::arrays::{ - sort_by_counter::{ - compare_by_counter_empty_padded_asc, compare_by_counter_empty_padded_desc, - }, get_sorted_tuple::get_sorted_tuple, - }, + sort_by_counter::{compare_by_counter_empty_padded_asc, compare_by_counter_empty_padded_desc}, + get_sorted_tuple::get_sorted_tuple +} }; pub struct SplitOrderHints { @@ -15,11 +14,7 @@ pub struct SplitOrderHints { impl SplitOrderHints { pub fn empty() -> SplitOrderHints { - SplitOrderHints { - sorted_counters_lt: [0; N], - sorted_counters_gte: [0; N], - sorted_indexes: [0; N], - } + SplitOrderHints { sorted_counters_lt: [0; N], sorted_counters_gte: [0; N], sorted_indexes: [0; N] } } } @@ -34,11 +29,10 @@ impl Eq for SplitOrderHints { unconstrained fn get_split_order_hints( array: [T; N], split_counter: u32, - ascending: bool, + ascending: bool ) -> SplitOrderHints where - T: Ordered + Eq + Empty, -{ + T: Ordered + Eq + Empty, { let ordering = if ascending { compare_by_counter_empty_padded_asc } else { @@ -77,30 +71,26 @@ where pub unconstrained fn get_split_order_hints_asc( array: [T; N], - split_counter: u32, + split_counter: u32 ) -> SplitOrderHints where - T: Ordered + Eq + Empty, -{ + T: Ordered + Eq + Empty, { get_split_order_hints(array, split_counter, true) } pub unconstrained fn get_split_order_hints_desc( array: [T; N], - split_counter: u32, + split_counter: u32 ) -> SplitOrderHints where - T: Ordered + Eq + Empty, -{ + T: Ordered + Eq + Empty, { get_split_order_hints(array, split_counter, false) } mod tests { use crate::{ tests::{types::TestValue, utils::pad_end}, - utils::arrays::assert_split_sorted_transformed_value_arrays::get_split_order_hints::{ - get_split_order_hints_asc, get_split_order_hints_desc, SplitOrderHints, - }, + utils::arrays::assert_split_sorted_transformed_value_arrays::get_split_order_hints::{get_split_order_hints_asc, get_split_order_hints_desc, SplitOrderHints} }; global full_array = [ @@ -130,12 +120,16 @@ mod tests { impl TestBuilder { pub fn asc_to_equal(self, expected: SplitOrderHints) { - let hints = unsafe { get_split_order_hints_asc(self.array, self.split_counter) }; + let hints = unsafe { + get_split_order_hints_asc(self.array, self.split_counter) + }; assert_eq(hints, expected); } pub fn desc_to_equal(self, expected: SplitOrderHints) { - let hints = unsafe { get_split_order_hints_desc(self.array, self.split_counter) }; + let hints = unsafe { + get_split_order_hints_desc(self.array, self.split_counter) + }; assert_eq(hints, expected); } } @@ -148,7 +142,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [0, 0, 0, 0, 0], sorted_counters_gte: [5, 7, 11, 13, 17], - sorted_indexes: [2, 4, 1, 0, 3], + sorted_indexes: [2, 4, 1, 0, 3] }; builder.asc_to_equal(expected_hints); } @@ -161,7 +155,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [5, 7, 0, 0, 0], sorted_counters_gte: [11, 13, 17, 0, 0], - sorted_indexes: [0, 2, 1, 0, 1], + sorted_indexes: [0, 2, 1, 0, 1] }; builder.asc_to_equal(expected_hints); } @@ -174,7 +168,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [5, 7, 0, 0, 0], sorted_counters_gte: [11, 13, 17, 0, 0], - sorted_indexes: [0, 2, 1, 0, 1], + sorted_indexes: [0, 2, 1, 0, 1] }; builder.asc_to_equal(expected_hints); } @@ -186,7 +180,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [0, 0, 0, 0, 0, 0, 0], sorted_counters_gte: [5, 7, 11, 13, 17, 0, 0], - sorted_indexes: [2, 4, 1, 0, 3, 0, 0], + sorted_indexes: [2, 4, 1, 0, 3, 0, 0] }; builder.asc_to_equal(expected_hints); } @@ -199,7 +193,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [5, 7, 0, 0, 0, 0, 0], sorted_counters_gte: [11, 13, 17, 0, 0, 0, 0], - sorted_indexes: [0, 2, 1, 0, 1, 0, 0], + sorted_indexes: [0, 2, 1, 0, 1, 0, 0] }; builder.asc_to_equal(expected_hints); } @@ -212,7 +206,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [5, 7, 0, 0, 0, 0, 0], sorted_counters_gte: [11, 13, 17, 0, 0, 0, 0], - sorted_indexes: [0, 2, 1, 0, 1, 0, 0], + sorted_indexes: [0, 2, 1, 0, 1, 0, 0] }; builder.asc_to_equal(expected_hints); } @@ -225,7 +219,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [0, 0, 0, 0, 0], sorted_counters_gte: [17, 13, 11, 7, 5], - sorted_indexes: [2, 0, 3, 4, 1], + sorted_indexes: [2, 0, 3, 4, 1] }; builder.desc_to_equal(expected_hints); } @@ -238,7 +232,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [7, 5, 0, 0, 0], sorted_counters_gte: [17, 13, 11, 0, 0], - sorted_indexes: [2, 0, 0, 1, 1], + sorted_indexes: [2, 0, 0, 1, 1] }; builder.desc_to_equal(expected_hints); } @@ -251,7 +245,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [7, 5, 0, 0, 0], sorted_counters_gte: [17, 13, 11, 0, 0], - sorted_indexes: [2, 0, 0, 1, 1], + sorted_indexes: [2, 0, 0, 1, 1] }; builder.desc_to_equal(expected_hints); } @@ -262,7 +256,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [0, 0, 0, 0, 0, 0, 0], sorted_counters_gte: [17, 13, 11, 7, 5, 0, 0], - sorted_indexes: [2, 0, 3, 4, 1, 0, 0], + sorted_indexes: [2, 0, 3, 4, 1, 0, 0] }; builder.desc_to_equal(expected_hints); } @@ -275,7 +269,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [7, 5, 0, 0, 0, 0, 0], sorted_counters_gte: [17, 13, 11, 0, 0, 0, 0], - sorted_indexes: [2, 0, 0, 1, 1, 0, 0], + sorted_indexes: [2, 0, 0, 1, 1, 0, 0] }; builder.desc_to_equal(expected_hints); } @@ -288,7 +282,7 @@ mod tests { let expected_hints = SplitOrderHints { sorted_counters_lt: [7, 5, 0, 0, 0, 0, 0], sorted_counters_gte: [17, 13, 11, 0, 0, 0, 0], - sorted_indexes: [2, 0, 0, 1, 1, 0, 0], + sorted_indexes: [2, 0, 0, 1, 1, 0, 0] }; builder.desc_to_equal(expected_hints); } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_transformed_value_arrays.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_transformed_value_arrays.nr index 105ce5372b6..a1ab17abdf7 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_transformed_value_arrays.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_split_transformed_value_arrays.nr @@ -6,24 +6,21 @@ pub fn assert_split_transformed_value_arrays_with_hint( transformed_value_array_gte: [S; N], // Values whose counters are greater than or equal to the split counter. is_transformed: fn[Env](T, S) -> bool, split_counter: u32, - num_non_revertibles: u32, // Hint. Should check in this function. + num_non_revertibles: u32 // Hint. Should check in this function. ) where T: Ordered + Empty + Eq, - S: Empty + Eq, -{ + S: Empty + Eq, { if num_non_revertibles != 0 { assert( - sorted_array[num_non_revertibles - 1].counter() < split_counter, - "counter of last non-revertible item is not less than the split counter", + sorted_array[num_non_revertibles - 1].counter() < split_counter, "counter of last non-revertible item is not less than the split counter" ); } if num_non_revertibles != N { let first_revertible_counter = sorted_array[num_non_revertibles].counter(); assert( - (first_revertible_counter == 0) | (first_revertible_counter >= split_counter), - "counter of first revertible item is not greater than or equal to the split counter", + (first_revertible_counter == 0) | (first_revertible_counter >= split_counter), "counter of first revertible item is not greater than or equal to the split counter" ); } @@ -53,14 +50,14 @@ pub fn assert_split_transformed_value_arrays( transformed_value_array_lt: [S; N], // Values whose counters are less than the split counter. transformed_value_array_gte: [S; N], // Values whose counters are greater than or equal to the split counter. is_transformed: fn[Env](T, S) -> bool, - split_counter: u32, + split_counter: u32 ) where T: Ordered + Empty + Eq, - S: Empty + Eq, -{ - let num_non_revertibles = - unsafe { find_index_hint(sorted_array, |n: T| n.counter() >= split_counter) }; + S: Empty + Eq, { + let num_non_revertibles = unsafe { + find_index_hint(sorted_array, |n: T| n.counter() >= split_counter) + }; assert_split_transformed_value_arrays_with_hint( sorted_array, @@ -68,16 +65,14 @@ where transformed_value_array_gte, is_transformed, split_counter, - num_non_revertibles, + num_non_revertibles ); } mod tests { use crate::{ tests::{types::TestValue, utils::pad_end}, - utils::arrays::assert_split_transformed_value_arrays::{ - assert_split_transformed_value_arrays, assert_split_transformed_value_arrays_with_hint, - }, + utils::arrays::assert_split_transformed_value_arrays::{assert_split_transformed_value_arrays, assert_split_transformed_value_arrays_with_hint} }; global NUM_TEST_ITEMS: u32 = 5; @@ -100,19 +95,14 @@ mod tests { TestValue { value: 30, counter: 7 }, TestValue { value: 80, counter: 11 }, TestValue { value: 10, counter: 13 }, - TestValue { value: 50, counter: 29 }, + TestValue { value: 50, counter: 29 } ]; let transformed_value_array_lt = pad_end([40, 30, 80], 0); let transformed_value_array_gte = pad_end([10, 50], 0); - TestBuilder { - sorted_array, - transformed_value_array_lt, - transformed_value_array_gte, - split_counter: 12, - } + TestBuilder { sorted_array, transformed_value_array_lt, transformed_value_array_gte, split_counter: 12 } } pub fn execute(self) { @@ -121,7 +111,7 @@ mod tests { self.transformed_value_array_lt, self.transformed_value_array_gte, is_transformed, - self.split_counter, + self.split_counter ); } @@ -132,7 +122,7 @@ mod tests { self.transformed_value_array_gte, is_transformed, self.split_counter, - num_non_revertibles, + num_non_revertibles ); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/get_sorted_result.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/get_sorted_result.nr index 6d0a31443b5..850484891b2 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/get_sorted_result.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/get_sorted_result.nr @@ -8,7 +8,7 @@ pub struct SortedResult { pub unconstrained fn get_sorted_result( values: [T; N], - ordering: fn(T, T) -> bool, + ordering: fn(T, T) -> bool ) -> SortedResult { let sorted = get_sorted_tuple(values, ordering); @@ -26,7 +26,9 @@ pub unconstrained fn get_sorted_result( #[test] fn get_sorted_hints_asc_non_padded() { let values = [40, 60, 20, 50]; - let res = unsafe { get_sorted_result(values, |a: u32, b: u32| a < b) }; + let res = unsafe { + get_sorted_result(values, |a: u32, b: u32| a < b) + }; assert_eq(res.sorted_array, [20, 40, 50, 60]); assert_eq(res.sorted_index_hints, [1, 3, 0, 2]); assert_eq(res.original_index_hints, [2, 0, 3, 1]); @@ -35,7 +37,9 @@ fn get_sorted_hints_asc_non_padded() { #[test] fn get_sorted_hints_desc_non_padded() { let values = [40, 20, 60, 50]; - let res = unsafe { get_sorted_result(values, |a: u32, b: u32| b < a) }; + let res = unsafe { + get_sorted_result(values, |a: u32, b: u32| b < a) + }; assert_eq(res.sorted_array, [60, 50, 40, 20]); assert_eq(res.sorted_index_hints, [2, 3, 0, 1]); } @@ -43,8 +47,9 @@ fn get_sorted_hints_desc_non_padded() { #[test] fn get_sorted_hints_asc_padded() { let values = [40, 60, 20, 50, 0, 0]; - let res = - unsafe { get_sorted_result(values, |a: u32, b: u32| (a != 0) & ((b == 0) | (a < b))) }; + let res = unsafe { + get_sorted_result(values, |a: u32, b: u32| (a != 0) & ((b == 0) | (a < b))) + }; assert_eq(res.sorted_array, [20, 40, 50, 60, 0, 0]); assert_eq(res.sorted_index_hints, [1, 3, 0, 2, 4, 5]); assert_eq(res.original_index_hints, [2, 0, 3, 1, 4, 5]); @@ -53,8 +58,9 @@ fn get_sorted_hints_asc_padded() { #[test] fn get_sorted_hints_desc_padded() { let values = [40, 60, 20, 50, 0, 0]; - let res = - unsafe { get_sorted_result(values, |a: u32, b: u32| (a != 0) & ((b == 0) | (b < a))) }; + let res = unsafe { + get_sorted_result(values, |a: u32, b: u32| (a != 0) & ((b == 0) | (b < a))) + }; assert_eq(res.sorted_array, [60, 50, 40, 20, 0, 0]); assert_eq(res.sorted_index_hints, [2, 0, 3, 1, 4, 5]); assert_eq(res.original_index_hints, [1, 3, 0, 2, 4, 5]); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/get_sorted_tuple.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/get_sorted_tuple.nr index d638e5cf279..e3c1c299467 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/get_sorted_tuple.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/get_sorted_tuple.nr @@ -5,17 +5,14 @@ pub struct SortedTuple { original_index: u32, } -pub unconstrained fn get_sorted_tuple( - array: [T; N], - ordering: fn[Env](T, T) -> bool, -) -> [SortedTuple; N] { +pub unconstrained fn get_sorted_tuple(array: [T; N], ordering: fn[Env](T, T) -> bool) -> [SortedTuple; N] { let mut tuples = [SortedTuple { elem: array[0], original_index: 0 }; N]; for i in 0..N { tuples[i] = SortedTuple { elem: array[i], original_index: i }; } sort_by( tuples, - |a: SortedTuple, b: SortedTuple| ordering(a.elem, b.elem), + |a: SortedTuple, b: SortedTuple| ordering(a.elem, b.elem) ) } @@ -26,9 +23,11 @@ fn get_sorted_tuple_asc() { SortedTuple { elem: 2, original_index: 1 }, SortedTuple { elem: 3, original_index: 0 }, SortedTuple { elem: 5, original_index: 3 }, - SortedTuple { elem: 9, original_index: 2 }, + SortedTuple { elem: 9, original_index: 2 } ]; - let sorted = unsafe { get_sorted_tuple(original, |a: u64, b: u64| a < b) }; + let sorted = unsafe { + get_sorted_tuple(original, |a: u64, b: u64| a < b) + }; for i in 0..4 { assert_eq(sorted[i].elem, expected[i].elem); assert_eq(sorted[i].original_index, expected[i].original_index); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/sort_by.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/sort_by.nr index f8eaddc7a23..ff2d4582fcb 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/sort_by.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/sort_by.nr @@ -3,15 +3,16 @@ use crate::utils::arrays::find_index_hint; // Copied from the stdlib Array.sort_via. // But this one doesn't use `ordering` to check that the array is sorted. // This is to allow preserving the order of equal values. -pub unconstrained fn sort_by( - array: [T; N], - ordering: fn[Env](T, T) -> bool, -) -> [T; N] { +pub unconstrained fn sort_by(array: [T; N], ordering: fn[Env](T, T) -> bool) -> [T; N] { let mut result = array; - let sorted_index = unsafe { get_sorting_index(array, ordering) }; + let sorted_index = unsafe { + get_sorting_index(array, ordering) + }; // Ensure the indexes are correct for i in 0..N { - let pos = unsafe { find_index_hint(sorted_index, |index: u32| index == i) }; + let pos = unsafe { + find_index_hint(sorted_index, |index: u32| index == i) + }; assert(sorted_index[pos] == i); } // Sort the array using the indexes @@ -27,10 +28,7 @@ pub unconstrained fn sort_by( } /// Returns the index of the elements in the array that would sort it, using the provided custom sorting function. -unconstrained fn get_sorting_index( - array: [T; N], - ordering: fn[Env](T, T) -> bool, -) -> [u32; N] { +unconstrained fn get_sorting_index(array: [T; N], ordering: fn[Env](T, T) -> bool) -> [u32; N] { let mut result = [0; N]; let mut a = array; for i in 0..N { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/sort_by_counter.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/sort_by_counter.nr index d4cd7176d87..612092b6b58 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/sort_by_counter.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/sort_by_counter.nr @@ -2,29 +2,25 @@ use crate::{abis::side_effect::Ordered, traits::{Empty, is_empty}, utils::arrays pub fn compare_by_counter_empty_padded_asc(a: T, b: T) -> bool where - T: Ordered + Empty + Eq, -{ + T: Ordered + Empty + Eq, { !is_empty(a) & (is_empty(b) | (a.counter() < b.counter())) } pub fn compare_by_counter_empty_padded_desc(a: T, b: T) -> bool where - T: Ordered + Empty + Eq, -{ + T: Ordered + Empty + Eq, { !is_empty(a) & (is_empty(b) | (a.counter() >= b.counter())) } pub unconstrained fn sort_by_counter_asc(array: [T; N]) -> [T; N] where - T: Ordered + Empty + Eq, -{ + T: Ordered + Empty + Eq, { sort_by(array, compare_by_counter_empty_padded_asc) } pub unconstrained fn sort_by_counter_desc(array: [T; N]) -> [T; N] where - T: Ordered + Empty + Eq, -{ + T: Ordered + Empty + Eq, { sort_by(array, compare_by_counter_empty_padded_desc) } @@ -32,34 +28,38 @@ mod tests { use crate::{ tests::types::TestValue, utils::arrays::sort_by_counter::{ - compare_by_counter_empty_padded_asc, compare_by_counter_empty_padded_desc, - sort_by_counter_asc, sort_by_counter_desc, - }, + compare_by_counter_empty_padded_asc, compare_by_counter_empty_padded_desc, sort_by_counter_asc, + sort_by_counter_desc + } }; fn asc_values_to_equal(values: [u32; N], expected: [u32; N]) { let items = values.map(|value| TestValue { value: value as Field, counter: value }); - let sorted = unsafe { sort_by_counter_asc(items).map(|item: TestValue| item.counter) }; + let sorted = unsafe { + sort_by_counter_asc(items).map(|item: TestValue| item.counter) + }; assert_eq(sorted, expected); } fn desc_values_to_equal(values: [u32; N], expected: [u32; N]) { let items = values.map(|value| TestValue { value: value as Field, counter: value }); - let sorted = unsafe { sort_by_counter_desc(items).map(|item: TestValue| item.counter) }; + let sorted = unsafe { + sort_by_counter_desc(items).map(|item: TestValue| item.counter) + }; assert_eq(sorted, expected); } fn compare_test_items_asc(value_1: u32, value_2: u32) -> bool { compare_by_counter_empty_padded_asc( TestValue { value: value_1 as Field, counter: value_1 }, - TestValue { value: value_2 as Field, counter: value_2 }, + TestValue { value: value_2 as Field, counter: value_2 } ) } fn compare_test_items_desc(value_1: u32, value_2: u32) -> bool { compare_by_counter_empty_padded_desc( TestValue { value: value_1 as Field, counter: value_1 }, - TestValue { value: value_2 as Field, counter: value_2 }, + TestValue { value: value_2 as Field, counter: value_2 } ) } @@ -108,7 +108,7 @@ mod tests { TestValue { value: 44, counter: 0 }, TestValue { value: 22, counter: 0 }, TestValue::empty(), - TestValue::empty(), + TestValue::empty() ]; let expected = [ TestValue { value: 11, counter: 0 }, @@ -117,9 +117,11 @@ mod tests { TestValue { value: 55, counter: 1 }, TestValue { value: 33, counter: 2 }, TestValue::empty(), - TestValue::empty(), + TestValue::empty() ]; - let sorted = unsafe { sort_by_counter_asc(original) }; + let sorted = unsafe { + sort_by_counter_asc(original) + }; assert_eq(sorted, expected); } @@ -132,7 +134,7 @@ mod tests { TestValue { value: 44, counter: 0 }, TestValue { value: 22, counter: 0 }, TestValue::empty(), - TestValue::empty(), + TestValue::empty() ]; let expected = [ TestValue { value: 33, counter: 2 }, @@ -141,9 +143,11 @@ mod tests { TestValue { value: 44, counter: 0 }, TestValue { value: 11, counter: 0 }, TestValue::empty(), - TestValue::empty(), + TestValue::empty() ]; - let sorted = unsafe { sort_by_counter_desc(original) }; + let sorted = unsafe { + sort_by_counter_desc(original) + }; assert_eq(sorted, expected); } } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/field.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/field.nr index 796d0906e77..61923ac6c84 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/field.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/field.nr @@ -49,7 +49,7 @@ unconstrained fn bytes_field_test() { // Bytes representing 0x543e0a6642ffeb8039296861765a53407bba62bd1c97ca43374de950bbe0a7 let inputs = [ 84, 62, 10, 102, 66, 255, 235, 128, 57, 41, 104, 97, 118, 90, 83, 64, 123, 186, 98, 189, 28, - 151, 202, 67, 55, 77, 233, 80, 187, 224, 167, + 151, 202, 67, 55, 77, 233, 80, 187, 224, 167 ]; let field = field_from_bytes(inputs, true); let return_bytes: [u8; 31] = field.to_be_bytes(); @@ -57,7 +57,7 @@ unconstrained fn bytes_field_test() { // 32 bytes - we remove the final byte, and check it matches the field let inputs2 = [ 84, 62, 10, 102, 66, 255, 235, 128, 57, 41, 104, 97, 118, 90, 83, 64, 123, 186, 98, 189, 28, - 151, 202, 67, 55, 77, 233, 80, 187, 224, 167, 158, + 151, 202, 67, 55, 77, 233, 80, 187, 224, 167, 158 ]; let field2 = field_from_bytes_32_trunc(inputs2); let return_bytes2: [u8; 31] = field.to_be_bytes(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/mod.nr index 8c30a510f83..f81cbafdf32 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/mod.nr @@ -9,18 +9,10 @@ mod uint256; // if predicate == true then return lhs, else return rhs pub fn conditional_assign(predicate: bool, lhs: Field, rhs: Field) -> Field { - if predicate { - lhs - } else { - rhs - } + if predicate { lhs } else { rhs } } -pub fn arr_copy_slice( - src: [T; N], - mut dst: [T; M], - offset: u32, -) -> [T; M] { +pub fn arr_copy_slice(src: [T; N], mut dst: [T; M], offset: u32) -> [T; M] { let iterator_len = if N > M { M } else { N }; for i in 0..iterator_len { dst[i] = src[i + offset]; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/reader.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/reader.nr index bde3ed335be..3d8ace278ef 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/reader.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/reader.nr @@ -36,11 +36,7 @@ impl Reader { result } - pub fn read_struct_array( - &mut self, - deserialise: fn([Field; K]) -> T, - mut result: [T; C], - ) -> [T; C] { + pub fn read_struct_array(&mut self, deserialise: fn([Field; K]) -> T, mut result: [T; C]) -> [T; C] { for i in 0..C { result[i] = self.read_struct(deserialise); } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/uint256.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/uint256.nr index bf0fbaf2844..5905e3eecab 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/uint256.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/uint256.nr @@ -86,7 +86,7 @@ fn smoke_u256_from_bytes32_one_zero_zero_zero() { // We want to output [1,0,0,0] let input = [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, + 0 ]; let result = U256::from_bytes32(input); @@ -116,7 +116,7 @@ fn smoke_u256_from_bytes32_test() { let input: [u8; 32] = [ 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, - 0xFF, 0x00, + 0xFF, 0x00 ]; let result = U256::from_bytes32(input);