Aztec 백서

Aztec

원문

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

n inputs are reduced to a singular value which can be proven from within the application. The `args_hash` is the result of poseidon2 hashing all of a function's inputs. ### Return Values[​](#return-values "Direct link to Return Values") The return values are a set of values that are returned from an applications execution to be passed to other functions through the kernel. Developers do not need to worry about passing their function return values to the `context` directly as `Aztec.nr` takes care of it for you. See the documentation surrounding `Aztec.nr` [macro expansion](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md#private-functions-externalprivate) for more details. ``` return_hash: Field, ``` ## Expiration Timestamp[​](#expiration-timestamp "Direct link to Expiration Timestamp") Some data structures impose time constraints, e.g. they may make it so that a value can only be changed after a certain delay. Interacting with these in private involves creating proofs that are only valid as long as they are included before a certain future point in time. To achieve this, the `set_expiration_timestamp` function can be used to set this property: expiration-timestamp ``` pub fn set_expiration_timestamp(&mut self, expiration_timestamp: u64) { ``` > [Source code: noir-projects/aztec-nr/aztec/src/context/private\_context.nr#L647-L649](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/aztec-nr/aztec/src/context/private_context.nr#L647-L649) A transaction that sets this value will never be included in a block with a timestamp larger than the requested value, since it would be considered invalid. This can also be used to make transactions automatically expire after some time if not included. ### Read Requests[​](#read-requests "Direct link to Read Requests") Read requests are used to prove that certain notes existed at a specific point in time. When a private function reads a note, it generates a read request that gets validated by the kernel circuit to ensure the note was valid at the time of the transaction. ### New Note Hashes[​](#new-note-hashes "Direct link to New Note Hashes") New note hashes contains an array of all of the note hashes created in the current execution context. ### New Nullifiers[​](#new-nullifiers "Direct link to New Nullifiers") New nullifiers contains an array of the new nullifiers emitted from the current execution context. ### Nullified Note Hashes[​](#nullified-note-hashes "Direct link to Nullified Note Hashes") Nullified note hashes is an optimization for introduced to help reduce state growth. There are often cases where note hashes are created and nullified within the same transaction. In these cases there is no reason that these note hashes should take up space on the node's commitment/nullifier trees. Keeping track of nullified note hashes allows us to "cancel out" and prove these cases. ### Private Call Stack[​](#private-call-stack "Direct link to Private Call Stack") The private call stack contains all of the external private function calls that have been created within the current context. Any function call objects are hashed and then pushed to the execution stack. The kernel circuit will orchestrate dispatching the calls and returning the values to the current context. ### Public Call Stack[​](#public-call-stack "Direct link to Public Call Stack") The public call stack contains all of the external function calls that are created within the current context. Like the private call stack above, the calls are hashed and pushed to this stack. Unlike the private call stack, these calls are not executed client side. Whenever the function is sent to the network, it will have the public call stack attached to it. At this point the sequencer will take over and execute the transactions. ### New L2 to L1 msgs[​](#new-l2-to-l1-msgs "Direct link to New L2 to L1 msgs") New L2 to L1 messages contains messages that are delivered to the l1 outbox on the execution of each rollup. ## Public Context[​](#public-context "Direct link to Public Context") The Public Context includes all of the information passed from the `Public VM` into the execution environment. Its interface is very similar to the [Private Context](#the-private-context), however it has some minor differences (detailed below). ### Public Global Variables[​](#public-global-variables "Direct link to Public Global Variables") The public global variables ([`GlobalVariables`](/aztec-nr-api/testnet/noir_aztec/protocol/abis/global_variables/struct.GlobalVariables.html)) are provided by the rollup sequencer and consequently contain some more values than the private global variables. --- # Inner Workings of Functions This page explains what happens under the hood when you create a function in an Aztec contract. The [next page](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md) covers what the function attributes do. ## Overview[​](#overview "Direct link to Overview") Private functions in Aztec compile to standalone circuits that must conform to the protocol's kernel circuit interface. Public functions compile to AVM bytecode. The transformations described below bridge the gap between developer-friendly Aztec.nr syntax and these underlying requirements. Utility functions (marked with `#[external("utility")]`) do not undergo these transformations—they remain as regular Noir functions. ## Function transformation[​](#function-transformation "Direct link to Function transformation") When you define a private or public function in an Aztec contract, it undergoes several transformations during compilation: * [Creating a context for the function](#context-creation) * [Handling function inputs](#private-and-public-input-injection) * [Processing return values](#return-value-handling) ## Context creation[​](#context-creation "Direct link to Context creation") Every function in an Aztec contract operates within a specific context that provides execution information and functionality. This is either a `PrivateContext` or `PublicContext` object, depending on whether it is a private or public function. ### Private functions[​](#private-functions "Direct link to Private functions") For private functions, context creation involves serializing and hashing all input parameters: ``` // Parameters are serialized into an array let serialized_args: [Field; N] = /* serialized parameters */; // Hash the arguments using poseidon2 let args_hash = aztec::hash::hash_args(serialized_args); // Create the context with the inputs and args hash let mut context = PrivateContext::new(inputs, args_hash); ``` This hashing is important because the kernel circuit uses it to verify the function received the correct parameters without exposing the input data. ### Public functions[​](#public-functions "Direct link to Public functions") For public functions, context creation uses a lazy evaluation pattern: ``` let mut context = PublicContext::new(|| { // compute args hash when needed hash_args(serialized_args) }); ``` ### Using the context[​](#using-the-context "Direct link to Using the context") The context object provides methods for interacting with the blockchain. Storage access and contract calls are handled through a `ContractSelf` wrapper that the macros generate automatically. ## Private and public input injection[​](#private-and-public-input-injection "Direct link to Private and public input injection") An additional parameter is automatically added to every private function. The injected input is always the first parameter of the transformed function and is of type `PrivateContextInputs` for private functions. Original function definition: ``` fn my_function(param1: Type1, param2: Type2) { ... } ``` Transformed function with injected input: ``` fn my_function(inputs: PrivateContextInputs, param1: Type1, param2: Type2) { ... } ``` The `PrivateContextInputs` struct contains: * `call_context` - information about how the function was called (msg\_sender, contract\_address, function\_selector, is\_static\_call) * `anchor_block_header` - the historical block header used during private execution * `tx_context` - transaction-level data (chain\_id, version, gas\_settings) * `start_side_effect_counter` - the side effect counter at function entry These inputs are made available through the `PrivateContext` object within your function. Public functions run in the AVM and access their context data through AVM opcodes rather than injected inputs. ## Return value handling[​](#return-value-handling "Direct link to Return value handling") Return values in Aztec contracts are processed differently from traditional smart contracts. ### Private functions[​](#private-functions-1 "Direct link to Private functions") For private functions, the return value is serialized, hashed, and stored in the context: ``` // The original return value is captured let macro__returned__values = original_return_expression; // The return value is serialized and hashed let serialized_return: [Field; N] = /* serialized return value */; self.context.set_return_hash(serialized_return); ``` The function's return type is changed to `PrivateCircuitPublicInputs`, which is returned by calling `context.finish()` at the end of the function. This process allows the return values to be included in the function's computation result while maintaining privacy. The actual return values are stored in the execution cache and can be retrieved by the caller using the hash. ### Public functions[​](#public-functions-1 "Direct link to Public functions") In public functions, the return value is handled directly by the AVM and the function's return type remains as specified by the developer. ## Function signature generation[​](#function-signature-generation "Direct link to Function signature generation") Each contract function has a unique 4-byte function selector. The selector is computed by hashing the function's signature string using Poseidon2: ``` impl FunctionSelector { pub fn from_signature<let N: u32>(signature: str<N>) -> Self { let bytes = signature.as_bytes(); let hash = poseidon2_hash_bytes(bytes); // hash is truncated to fit within 32 bits (4 bytes) FunctionSelector::from_field(hash) } } ``` The signature string follows the format `function_name(param_types)`. For example, `transfer(Field,Field)`. This approach is inspired by Solidity's function selector mechanism, but uses Poseidon2 instead of Keccak-256 for compatibility with Aztec's circuit-friendly hash functions. ## Contract artifacts[​](#contract-artifacts "Direct link to Contract artifacts") Contract artifacts are automatically generated structures that describe the contract's interface. They preserve the original function signatures (parameters and return types) before macro transformations are applied. For each function in the contract, an ABI export is generated with: 1. A parameters struct containing all function parameters 2. An ABI struct marked with `#[abi(functions)]` containing the parameters and return type For example, given a function: ``` fn increment(owner: AztecAddress) -> Field { ... } ``` The following structs are generated: ``` pub struct increment_parameters { pub owner: AztecAddress } #[abi(functions)] pub struct increment_abi { parameters: increment_parameters, return_type: Field } ``` The `#[abi(functions)]` attribute marks the struct for inclusion in the contract ABI's `outputs.functions` array. This is important because macro processing changes the actual return type of private functions to `PrivateCircuitPublicInputs`, but the toolchain needs access to the original signatures. Contract artifacts enable: * Machine-readable contract interface descriptions * TypeScript binding generation (see [how to compile contracts](/developers/testnet/docs/aztec-nr/compiling_contracts.md)) * Function return value decoding in the simulator ## Further reading[​](#further-reading "Direct link to Further reading") * [Function attributes and macros](/developers/testnet/docs/aztec-nr/framework-description/functions/attributes.md) * [Aztec.nr macro source code](https://github.com/aztec-labs-eng/aztec-node/tree/v6.0.0-rc.1/noir-projects/aztec-nr/aztec/src/macros) - for those who want to see the actual transformation implementation --- # How to Define Functions ## Overview[​](#overview "Direct link to Overview") This guide shows you how to define different types of functions in your Aztec contracts, each serving specific purposes and execution environments. ## Quick reference[​](#quick-reference "Direct link to Quick reference") | Annotation | Execution | State access | | ------------------------ | ----------------- | ------------------------------------------------------------ | | `#[external("private")]` | User device | Private state (and selected public values via storage types) | | `#[external("public")]` | Sequencer | Public state | | `#[external("utility")]` | Offchain client | Public + private (unconstrained) | | `#[internal("private")]` | N/A | Inlined private helper (non-entrypoint) | | `#[internal("public")]` | N/A | Inlined public helper (non-entrypoint) | | `#[view]` | Private or public | Read-only (no state mutation) | | `#[only_self]` | Private or public | Callable only by the same contract | | `#[initializer]` | Private or public | One-time initialization | ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") * An Aztec contract project set up with the `aztec-nr` dependency * Basic understanding of [Noir programming language](https://noir-lang.org/docs) * Familiarity with Aztec Protocol's [call types](/developers/testnet/docs/foundational-topics/call_types.md) (private vs public) ## Define private functions[​](#define-private-functions "Direct link to Define private functions") Use `#[external("private")]` to create functions that execute privately on user devices. For example: increment ``` #[external("private")] fn increment(owner: AztecAddress) { debug_log_format("Incrementing counter for owner {0}", [owner.to_field()]); self.storage.counters.at(owner).add(1).deliver(MessageDelivery::onchain_constrained()); } ``` > [Source code: docs/examples/contracts/counter\_contract/src/main.nr#L36-L42](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/counter_contract/src/main.nr#L36-L42) Private functions run in a private context, can access private state, and can read certain public values through storage types like [`DelayedPublicMutable`](/developers/testnet/docs/aztec-nr/framework-description/state_variables.md#delayedpublicmutable). ## Define public functions[​](#define-public-functions "Direct link to Define public functions") Use `#[external("public")]` to create functions that execute on the sequencer: mint\_public ``` #[external("public")] fn mint_public(employee: AztecAddress, amount: u64) { // Only Giggle can mint tokens assert_eq(self.msg_sender(), self.storage.owner.read(), "Only Giggle can mint BOB tokens"); // Add tokens to employee's public balance let current_balance = self.storage.public_balances.at(employee).read(); self.storage.public_balances.at(employee).write(current_balance + amount); } ``` > [Source code: docs/examples/contracts/bob\_token\_contract/src/main.nr#L41-L51](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/bob_token_contract/src/main.nr#L41-L51) Public functions operate on public state, similar to EVM contracts. They can write to private storage, but any data written from a public function is publicly visible. ## Define utility functions[​](#define-utility-functions "Direct link to Define utility functions") Create offchain query functions using the `#[external("utility")]` annotation with `unconstrained`. Utility functions are unconstrained functions that applications call to perform auxiliary tasks, like querying contract state or processing offchain messages. Their execution is never proven, so no guarantees are made on the correctness of their results. They can also be called from other utility functions and from private functions. See [utility calls](/developers/testnet/docs/aztec-nr/framework-description/calling_contracts.md#utility-calls). Public functions cannot call them. Example: get\_counter ``` #[external("utility")] unconstrained fn get_counter(owner: AztecAddress) -> pub u128 { self.storage.counters.at(owner).balance_of() } ``` > [Source code: docs/examples/contracts/counter\_contract/src/main.nr#L44-L49](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/counter_contract/src/main.nr#L44-L49) Use `aztec.js` `simulate` to execute utility functions and read their return values. For details, see [Call Types](/developers/testnet/docs/foundational-topics/call_types.md#simulate). ## Define view functions[​](#define-view-functions "Direct link to Define view functions") Create read-only functions using the `#[view]` annotation combined with `#[external("private")]` or `#[external("public")]`: ``` #[external("public")] #[view] fn get_config_value() -> Field { // logic } ``` View functions cannot modify contract state. They're akin to Ethereum's `view` functions. `#[view]` only applies to `#[external("private")]` and `#[external("public")]` functions. ## Define only-self functions[​](#define-only-self-functions "Direct link to Define only-self functions") Create contract-only functions using the `#[only_self]` annotation: \_assert\_is\_owner ``` #[external("public")] #[only_self] fn _assert_is_owner(address: AztecAddress) { assert_eq(address, self.storage.owner.read(), "Only Giggle can mint BOB tokens"); } ``` > [Source code: docs/examples/contracts/bob\_token\_contract/src/main.nr#L131-L137](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/bob_token_contract/src/main.nr#L131-L137) Only-self functions are only callable by the same contract, which is useful when a private function enqueues a public call that should only be callable internally. ## Define initializer functions[​](#define-initializer-functions "Direct link to Define initializer functions") Create constructor-like functions using the `#[initializer]` annotation: constructor ``` #[initializer] #[external("private")] // We can name our initializer anything we want as long as it's marked as #[initializer] fn constructor(initial_value: u128, owner: AztecAddress) { self.storage.counters.at(owner).add(initial_value).deliver( MessageDelivery::onchain_constrained(), ); } ``` > [Source code: docs/examples/contracts/counter\_contract/src/main.nr#L25-L34](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/docs/examples/contracts/counter_contract/src/main.nr#L25-L34) ### Use multiple initializers[​](#use-multiple-initializers "Direct link to Use multiple initializers") Define multiple initialization options: 1. Mark each function with `#[initializer]` 2. Choose which one to call during deployment 3. Any initializer marks the contract as initialized ## Define internal functions[​](#define-internal-functions "Direct link to Define internal functions") Create helper functions using `#[internal("private")]` or `#[internal("public")]`. Internal functions are inlined at call sites and do not create separate entrypoints: ``` #[internal("private")] fn _prepare_transfer(to: AztecAddress, amount: u128) -> Field { // helper logic for private functions } #[internal("public")] fn _update_balance(owner: AztecAddress, amount: u128) { // helper logic for public functions } ``` Call internal functions via `self.internal`: ``` let result = self.internal._prepare_transfer(recipient, amount); ``` Key constraints: * Private internal functions can only be called from private external or internal functions * Public internal function
프로젝트로 돌아가기