Aztec 백서

Aztec

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 26쪽

factored into the L2 fee mechanisms. These limits can be seen and iterated on when a transaction is simulated/estimated. ## Examples for private functions (reducing gate count)[​](#examples-for-private-functions-reducing-gate-count "Direct link to Examples for private functions (reducing gate count)") After the first section about generating a flamegraph for an Aztec function, each section shows an example of different optimisation techniques. ### Inspecting with flamegraphs[​](#inspecting-with-flamegraphs "Direct link to Inspecting with flamegraphs") Use the Noir profiler to generate flamegraphs for your contract functions. The profiler is installed automatically with Nargo (starting noirup v0.1.4). ``` # Generate a gates flamegraph (requires bb backend) noir-profiler gates \ --artifact-path ./target/counter-Counter.json \ --backend-path bb \ --output ./target ``` Open the generated `.svg` file in a browser for an interactive view. For more details, see the [profiling guide](/developers/testnet/docs/aztec-nr/framework-description/advanced/how_to_profile_transactions.md). ![](/assets/ideal-img/flamegraph-counter.aeb3d35.640.png) To get a sense of things, here is a table of gate counts for common operations: | Gates | Operation | | ------- | ------------------------------------------------------------------------------ | | \~75 | Hashing 3 fields with Poseidon2 | | 3500 | Reading a value from a tree (public data tree, note hash tree, nullifier tree) | | 4000 | Reading a delayed public mutable read | | \~5,000 | Calculating sha256 (varies by input size) | | Varies | Constrained encryption of a private log (depends on field count) | | Varies | Constrained encryption and tagging of a private log (depends on field count) | ### Optimization: use arithmetic instead of non-arithmetic operations[​](#optimization-use-arithmetic-instead-of-non-arithmetic-operations "Direct link to Optimization: use arithmetic instead of non-arithmetic operations") Because the underlying equation in the proving backend makes use of multiplication and addition, these operations incur less gates than bit-shifting or bit-masking. For example: ``` comptime global TWO_POW_16: Field = 2.pow_32(16); // ... { #[external("private")] fn mul_inefficient(number: Field) -> u128 { number as u128 << 16 as u8 } // 5244 gates #[external("private")] fn mul_efficient(number: Field) -> u128 { (number * TWO_POW_16) as u128 } // 5184 gates (60 gates less) } ``` When comparing the flamegraph of the two functions, the inefficient shift example has a section of gates not present in the multiplication example. This difference equates to a saving of 60 gates. In the same vein bitwise `AND`/`OR`, and inequality relational operators (`>`, `<`) are expensive. Try avoid these in your circuits. For example, use boolean equality effectively instead of `>=`: ``` { #[external("private")] fn sum_from_inefficient(from: u32, array: [u32; 1000]) -> u32 { let mut sum: u32 = 0; for i in 0..1000 { if i >= from { // condition based on `>=` each time (higher gate count) sum += array[i]; } } sum } // 44317 gates #[external("private")] fn sum_from_efficient(from: u32, array: [u32; 1000]) -> u32 { let mut sum: u32 = 0; let mut do_sum = false; for i in 0..1000 { if i == from { // latches boolean at transition (equality comparison) do_sum = true; } if do_sum { // condition based on boolean true (lower gate count) sum += array[i]; } } sum } // 45068 gates (751 gates more due to the boolean operations, but the pattern demonstrates how to avoid range checks) } ``` So for a loop of 1000 iterations, 751 gates were saved by: * Adding an equivalence check and a boolean assignment * Replacing `>=` with a boolean equivalence check Difference with Rust Such designs with boolean flags lend themselves well into logical comparisons too since `&&` and `||` do not exist. With booleans, using `&` and `|` can give you the required logic efficiently. For more points specific to the Noir language, see [this](https://noir-lang.org/docs/guides/thinking_in_circuits#translating-from-rust) section. ### Optimization: Loop design[​](#optimization-loop-design "Direct link to Optimization: Loop design") Since private functions are circuits, their size must be known at compile time, which is equivalent to its execution trace. See [this example](https://github.com/noir-lang/noir-examples/blob/master/noir_by_example/loops/noir/src/main.nr#L11) for how to use loops when dynamic execution lengths (ie variable number of loops) is not possible. ### Optimization: considered use of `unconstrained` functions[​](#optimization-considered-use-of-unconstrained-functions "Direct link to optimization-considered-use-of-unconstrained-functions") #### Example - calculating square root[​](#example---calculating-square-root "Direct link to Example - calculating square root") Consider the following example of an implementation of the `sqrt` function: ``` use aztec::macros::aztec; #[aztec] pub contract OptimisationExample { use aztec::macros::{functions::{external, initializer}, storage::storage}; #[storage] struct Storage<Context> {} #[external("public")] #[initializer] fn constructor() {} #[external("private")] fn sqrt_inefficient(number: Field) -> Field { super::sqrt_constrained(number) } #[external("private")] fn sqrt_efficient(number: Field) -> Field { // Safety: calculate in unconstrained function, then constrain the result let x = unsafe { super::sqrt_unconstrained(number) }; assert(x * x == number, "x*x should be number"); x } } fn sqrt_constrained(number: Field) -> Field { let MAX_LEN = 100; let mut guess = number; let mut guess_squared = guess * guess; for _ in 1..MAX_LEN as u32 + 1 { // only use square root part of circuit when required, otherwise use alternative part of circuit that does nothing // Note: both parts of the circuit exist MAX_LEN times in the circuit, regardless of whether the square root part is used or not if (guess_squared != number) { guess = (guess + number / guess) / 2; guess_squared = guess * guess; } } guess } unconstrained fn sqrt_unconstrained(number: Field) -> Field { let mut guess = number; let mut guess_squared = guess * guess; while guess_squared != number { guess = (guess + number / guess) / 2; guess_squared = guess * guess; } guess } ``` The two implementations after the contract differ in one being constrained vs unconstrained, as well as the loop implementation (which has other design considerations). Measuring the two, we find the `sqrt_inefficient` to require around 1500 extra gates compared to `sqrt_efficient`. To generate flamegraphs for each function: ``` noir-profiler gates \ --artifact-path ./target/optimisation_example-OptimisationExample.json \ --backend-path bb \ --output ./target ``` If you make changes to the code, recompile and regenerate the flamegraph, then refresh the `.svg` file in your browser. Note: this is largely a factor of the loop size choice based on the maximum size of `number` you are required to be calculating the square root of. For larger numbers, the loop would have to be much larger, so perform in an unconstrained way (then constraining the result) is much more efficient. #### Example - sorting an array[​](#example---sorting-an-array "Direct link to Example - sorting an array") Like with sqrt, we have the inefficient function that does the sort with constrained operations, and the efficient function that uses the unconstrained sort function then constrains the result. ``` //... { #[external("private")] fn sort_inefficient(array: [u32; super::ARRAY_SIZE]) -> [u32; super::ARRAY_SIZE] { let mut sorted_array = array; for i in 0..super::ARRAY_SIZE as u32 { for j in 0..super::ARRAY_SIZE as u32 { if sorted_array[i] < sorted_array[j] { let temp = sorted_array[i as u32]; sorted_array[i as u32] = sorted_array[j as u32]; sorted_array[j as u32] = temp; } } } sorted_array } // 6823 gates for 10 elements, 127780 gates for 100 elements #[external("private")] fn sort_efficient(array: [u32; super::ARRAY_SIZE]) -> [u32; super::ARRAY_SIZE] { // Safety: calculate in unconstrained function, then constrain the result let sorted_array = unsafe { super::sort_array(array) }; // constrain that sorted_array elements are sorted for i in 0..super::ARRAY_SIZE as u32 - 1 { assert(sorted_array[i] <= sorted_array[i + 1], "array should be sorted"); } // Note: A production implementation should also verify that sorted_array is a // permutation of the input array to prevent a malicious prover from returning // arbitrary sorted values. sorted_array } // 5870 gates (953 gates less) for 10 elements, 12582 gates for 100 elements (115198 gates less) } unconstrained fn sort_array(array: [u32; ARRAY_SIZE]) -> [u32; ARRAY_SIZE] { let mut sorted_array = array; for i in 0..ARRAY_SIZE as u32 { for j in 0..ARRAY_SIZE as u32 { if sorted_array[i] < sorted_array[j] { let temp = sorted_array[i as u32]; sorted_array[i as u32] = sorted_array[j as u32]; sorted_array[j as u32] = temp; } } } sorted_array } ``` Like before, `noir-profiler` can be used to visualize the gate counts of the private functions, highlighting that 953 gates could be saved. Note: The stdlib provides a highly optimized version of sort on arrays, `array.sort()`, which saves even more gates. ``` #[external("private")] fn sort_stdlib(array: [u32; super::ARRAY_SIZE]) -> [u32; super::ARRAY_SIZE] { array.sort() } // 5943 gates (880 gates less) for 10 elements, 13308 gates for 100 elements (114472 gates less) ``` #### Example - refactoring arrays[​](#example---refactoring-arrays "Direct link to Example - refactoring arrays") In the same vein, refactoring is inefficient when done constrained, and more efficient to do unconstrained then constrain the output. ``` { #[external("private")] fn refactor_inefficient(array: [u32; super::ARRAY_SIZE]) -> [u32; super::ARRAY_SIZE] { let mut compacted_array = [0; super::ARRAY_SIZE]; let mut index = 0; for i in 0..super::ARRAY_SIZE as u32 { if (array[i] != 0) { compacted_array[index] = array[i]; index += 1; } } compacted_array } // 6570 gates for 10 elements, 93071 gates for 100 elements #[external("private")] fn refactor_efficient(array: [u32; super::ARRAY_SIZE]) -> [u32; super::ARRAY_SIZE] { let compacted_array = unsafe { super::refactor_array(array) }; // count non-zero elements in array let mut count = 0; for i in 0..super::ARRAY_SIZE as u32 { if (array[i] != 0) { count += 1; } } // count non-zero elements in compacted_array let mut count_compacted = 0; for i in 0..super::ARRAY_SIZE as u32 { if (compacted_array[i] != 0) { count_compacted += 1; } else { assert(compacted_array[i] == 0, "trailing compacted_array elements should be 0"); } } assert(count == count_compacted, "count should be equal to count_compacted"); compacted_array } // 5825 gates (745 gates less), 12290 gates for 100 elements (80781 gates less) } unconstrained fn refactor_array(array: [u32; ARRAY_SIZE]) -> [u32; ARRAY_SIZE] { let mut compacted_array = [0; ARRAY_SIZE]; let mut index = 0; for i in 0..ARRAY_SIZE as u32 { if (array[i] != 0) { compacted_array[index] = array[i]; index += 1; } } compacted_array } ``` ### Optimizing: Reducing L2 reads[​](#optimizing-reducing-l2-reads "Direct link to Optimizing: Reducing L2 reads") If a struct has many fields to be read, we can design an extra variable maintained as the hash of all values within it (like a checksum). When it comes to reading, we can now do an unconstrained read (incurring no read requests), and then check the hash of the result against that stored for the struct. This final check is thus only one read request rather than one per variable. Leverage unconstrained functions When needing to make use of large private operations (eg private execution or many read requests), use of [unconstrained functions](https://noir-lang.org/docs/guides/thinking_in_circuits#leverage-unconstrained-execution) wisely to reduce the gate count of private functions. --- # Authentication Witnesses Authentication witnesses (authwit) allow other contracts to execute actions on behalf of your account. This guide shows you how to implement and use authwits in your Aztec smart contracts. <!-- --> For a video walkthrough of the concepts and the implementation pattern, watch this explainer (find more on the [video lessons](/developers/testnet/docs/resources/video_lessons.md) page): [How Authorization Works on Aztec](https://www.youtube-nocookie.com/embed/VRZVOCdjGZ4) ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * An Aztec contract project set up with `aztec-nr` dependency * Understanding of private and public functions in Aztec For conceptual background, see [Authentication Witnesses](/developers/testnet/docs/foundational-topics/advanced/authwit.md). ## Import the authwit library[​](#import-the-authwit-library "Direct link to Import the authwit library") The `aztec` library includes authwit functionality. Import the necessary components: ``` use aztec::{ authwit::auth::{compute_authwit_message_hash_from_call, set_authorized}, macros::functions::authorize_once, }; ``` ## Using the `authorize_once` macro[​](#using-the-authorize_once-macro "Direct link to using-the-authorize_once-macro") The `#[authorize_once]` macro validates that a caller has authorization from the `from` address. It handles authwit verification and nullifier emission automatically. ### Private function example[​](#private-function-example "Direct link to Private function example") transfer\_in\_private ``` #[authorize_once("from", "authwit_nonce")] #[external("private")] fn transfer_in_private(from: AztecAddress, to: AztecAddress, amount: u128, authwit_nonce: Field) { self.storage.balances.at(from).sub(amount).deliver(MessageDelivery::onchain_constrained()); self.storage.balances.at(to).add(amount).deliver(MessageDelivery::onchain_constrained()); } ``` > [Source code: noir-projects/noir-contracts/contracts/app/token\_contract/src/main.nr#L284-L291](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L284-L291) ### Public function example[​](#public-function-example "Direct link to Public function example") transfer\_in\_public ``` #[authorize_once("from", "authwit_nonce")] #[external("public")] fn transfer_in_public(from: AztecAddress, to: AztecAddress, amount: u128, authwit_nonce: Field) { let from_balance = self.storage.public_balances.at(from).read().sub(amount); self.storage.public_balances.at(from).write(from_balance); let to_balance = self.storage.public_balances.at(to).read().add(amount); self.storage.public_balances.at(to).write(to_balance); } ``` > [Source code: noir-projects/noir-contracts/contracts/app/token\_contract/src/main.nr#L170-L179](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L170-L179) The macro parameters specify: * `"from"` - the parameter name containing the address that must have authorized the call * `"authwit_nonce"` - the parameter name containing the nonce for replay protection ## Setting authorization from contracts[​](#setting-authorization-from-contracts "Direct link to Setting authorization from contracts") When a contract needs to authorize another contract to act on its behalf, use `set_authorized` to update the auth registry. This is common in bridge contracts where contract A authorizes contract B to perform actions. authwit\_uniswap\_set ``` // This helper method approves the bridge to burn this contract's funds and exits the input asset to L1 // Assumes contract already has funds. // Assume `token` relates to `token_bridge` (ie token_bridge.token == token) // Note that private can't read public return values so created an `only_self` public that handles everything // this method is used for both private and public swaps. #[external("public")] #[only_self] fn _approve_bridge_and_exit_input_asset_to_L1(token: AztecAddress, token_bridge: AztecAddress, amount: u128) { // 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 authwit_nonce = 0xdeadbeef; let selector = FunctionSelector::from_signature("burn_public((Field),u128,Field)"); let message_hash = compute_authwit_message_hash_from_call( token_bridge, token, self.context.chain_id(), self.context.version(), selector, [self.address.to_field(), amount as Field, authwit_nonce], ); // We need to make a call to update it. set_authorized(self.context, message_hash, true); let this_portal_address = self.storage.portal_address.read(); // Exit to L1 Uniswap Portal ! self.call(TokenBridge::at(token_bridge).exit_to_l1_public( this_portal_address, amount, this_portal_address, authwit_nonce, )); } ``` > [Source code: noir-projects/noir-contracts/contracts/app/uniswap\_contract/src/main.nr#L166-L201](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L166-L201) Key steps: 1. Compute the message hash using `compute_authwit_message_hash_from_call` 2. Call `set_authorized` to store the approval in the registry 3. Execute the authorized action When authorization and consumption happen in the same transaction, state changes are squashed, saving gas. ## Canceling authwits[​](#canceling-authwits "Direct link to Canceling authwits") Users can revoke an authwit before it's used by emitting its nullifier: cancel\_authwit ``` #[external("private")] fn cancel_authwit(inner_hash: Field) { let on_behalf_of = self.msg_sender(); let nullifier = compute_authwit_nullifier(on_behalf_of, inner_hash); self.context.push_nullifier_unsafe(nullifier); } ``` > [Source code: noir-projects/noir-contracts/contracts/app/token\_contract/src/main.nr#L275-L282](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L275-L282) note The cancel transaction must be finalized before any transaction attempts to use the authwit. If both are pending simultaneously, the outcome depends on which the sequencer includes first. ## Next steps[​](#next-steps "Direct link to Next steps") * [Using authwits in aztec.js](/developers/testnet/docs/aztec-js/how_to_use_authwit.md) - Create and manage authwits from your client application * [Authentication Witnesses concepts](/developers/testnet/docs/foundational-topics/advanced/authwit.md) - Deeper explanation of the authwit mechanism --- # Calling Other Contracts This guide shows you how to call functions in other contracts from your Aztec smart contracts. ## Add the target contract as a dependency[​](#add-the-target-contract-as-a-dependency "Direct link to Add the target contract as a dependency") Add the contract you want to call to your `Nargo.toml` dependencies: ``` [dependencies] token = { git="https://github.com/aztec-labs-eng/aztec-node/", tag="v6.0.0-rc.1", directory="noir-projects/noir-contracts/contracts/app/token_contract" } ``` Then import the contract interface at the top of your contract file: ``` use token::Token; ``` ## Call contract functions[​](#call-contract-functions "Direct link to Call contract functions") Use `self.call()` to call functions on other contracts: ``` self.call(Token::at(token_address).transfer(recipient, amount)); ``` The pattern is: 1. Form the call: `Contract::at(address).function_name(args)` 2. Execute it: `self.call(...)` or `self.view(...)` for read-only calls ###
프로젝트로 돌아가기