Aztec 백서

Aztec

원문

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

et/docs/aztec-nr/installation.md) for setup.) Under the hood, the macro: * Creates a `PrivateContext` from kernel-provided inputs (chain ID, block data, etc.) * Initializes the `self` object with context and storage * Hashes function inputs for the kernel (enabling variable argument counts) * Returns execution results via `PrivateCircuitPublicInputs` (nullifiers, messages, return values) ## Utility functions #\[external("utility")][​](#utility-functions-externalutility "Direct link to Utility functions #\[external(\"utility\")]") Utility functions perform state queries from an offchain client and are never included in transactions. They can access both private and public state, and can modify local PXE state (e.g., processing logs). Since execution is unconstrained and relies on [oracle calls](https://noir-lang.org/docs/guides/oracles), no guarantees are made on result correctness. A reasonable mental model is a Solidity `view` function that can only be invoked via `eth_call`, never in a transaction. Unlike Solidity `view` functions, utility functions can also modify local offchain PXE state. balance\_of\_private ``` #[external("utility")] unconstrained fn balance_of_private(owner: AztecAddress) -> u128 { self.storage.balances.at(owner).balance_of() } ``` > [Source code: noir-projects/noir-contracts/contracts/app/token\_contract/src/main.nr#L503-L508](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#L503-L508) info Utility functions can access both private and historical public data since they're not part of transactions—there's no risk of using stale or unverified state. ## Public functions #\[external("public")][​](#public-functions-externalpublic "Direct link to Public functions #\[external(\"public\")]") A public function is executed by the sequencer and has access to a state model that is very similar to that of the EVM and Ethereum. Even though they work in an EVM-like model for public transactions, they are able to write data into private storage that can be consumed later by a private function. note All data inserted into private storage from a public function will be publicly viewable (not private). To create a public function you can annotate it with the `#[external("public")]` attribute. This will make the public context available within the function's execution scope. set\_minter ``` #[external("public")] fn set_minter(minter: AztecAddress, approve: bool) { assert(self.storage.admin.read().eq(self.msg_sender()), "caller is not admin"); self.storage.minters.at(minter).write(approve); } ``` > [Source code: noir-projects/noir-contracts/contracts/app/token\_contract/src/main.nr#L153-L159](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#L153-L159) Under the hood, the macro: * Creates a `PublicContext` object that provides access to public state and transaction information * Initializes the storage struct if one is defined * Wraps the function body in a scope that handles context setup and return values * Marks the function as `pub` and `unconstrained`, meaning it doesn't generate proofs and is executed directly by the sequencer To see the exact generated code, run `aztec-nargo expand` on your contract. ## Constrained `view` Functions #\[view][​](#constrained-view-functions-view "Direct link to constrained-view-functions-view") The `#[view]` attribute can be applied to a `#[external("private")]` or a `#[external("public")]` function and it guarantees that the function cannot modify any contract state (just like `view` functions in Solidity). ## `Initializer` Functions #\[initializer][​](#initializer-functions-initializer "Direct link to initializer-functions-initializer") This is used to designate functions as initializers (or constructors) for an Aztec contract. These functions are responsible for setting up the initial state of the contract when it is first deployed. The macro does two important things: * `assert_initialization_matches_address_preimage(context)`: This checks that the arguments and sender to the initializer match the commitments from the address preimage * `mark_as_initialized(&mut context)`: This is called at the end of the function to emit the initialization nullifier, marking the contract as fully initialized and ensuring this function cannot be called again Key things to keep in mind: * A contract can have multiple initializer functions defined, but only one initializer function should be called for the lifetime of a contract instance * Other functions in the contract will have an initialization check inserted, ie they cannot be called until the contract is initialized, unless they are marked with [`#[noinitcheck]`](#noinitcheck) ## #\[noinitcheck][​](#noinitcheck "Direct link to #\[noinitcheck]") In normal circumstances, all functions in an Aztec contract (except initializers) have an initialization check inserted at the beginning of the function body. This check ensures that the contract has been initialized before any other function can be called. However, there may be scenarios where you want a function to be callable regardless of the contract's initialization state. This is when you would use `#[noinitcheck]`. When a function is annotated with `#[noinitcheck]`: * The Aztec macro processor skips the [insertion of the initialization check](#initializer-functions-initializer) for this specific function * The function can be called at any time, even if the contract hasn't been initialized yet ## #\[only\_self][​](#only_self "Direct link to #\[only_self]") External functions marked with #\[only\_self] attribute can only be called by the contract itself - if other contracts try to make the call it will fail. This attribute is commonly used when an action starts in private but needs to be completed in public. The public function must be marked with #\[only\_self] to restrict access to only the contract itself. A typical example is a private token mint operation that needs to enqueue a call to a public function to update the publicly tracked total token supply. It is also useful in private functions when dealing with tasks of an unknown size but with a large upper bound (e.g. when needing to process an unknown amount of notes or nullifiers) as they allow splitting the work in multiple circuits, possibly resulting in performance improvements for low-load scenarios. This macro inserts a check at the beginning of the function to ensure that the caller is the contract itself. This is done by adding the following assertion: ``` assert(self.msg_sender() == self.address, "Function can only be called internally"); ``` ## #\[allow\_phase\_change][​](#allow_phase_change "Direct link to #\[allow_phase_change]") Private functions normally include a check to validate the current transaction phase. The `#[allow_phase_change]` attribute skips this validation, allowing the function to handle phase transitions internally. This is primarily used in account contract entrypoints that need to handle fee payment methods spanning multiple phases: ``` #[external("private")] #[allow_phase_change] fn entrypoint(app_payload: AppPayload, fee_payment_method: u8, cancellable: bool) { // Handle different fee payment methods that may span phases } ``` ## #\[authorize\_once][​](#authorize_once "Direct link to #\[authorize_once]") The `#[authorize_once]` attribute enables authorization checks via the [authwit mechanism](/developers/testnet/docs/foundational-topics/advanced/authwit.md) with replay protection. Use this when a function performs actions on behalf of someone who is not the caller. ``` #[authorize_once("from", "authwit_nonce")] #[external("public")] fn transfer_in_public(from: AztecAddress, to: AztecAddress, amount: u128, authwit_nonce: Field) { // Transfer tokens from 'from' to 'to' } ``` The macro: * Verifies the caller is authorized to act on behalf of the `from` address * Emits the authorization request as an offchain effect for wallet verification * Consumes a nullifier with the provided nonce, preventing replay attacks ## Internal functions #\[internal("...")][​](#internal-functions-internal "Direct link to Internal functions #\[internal(\"...\")]") Internal functions are callable only from within the same contract and are inlined at call sites (like Solidity's internal functions). Unlike `#[only_self]`, they don't create a separate call—the code is directly inserted where called. ``` #[internal("private")] fn _prepare_private_balance_increase(to: AztecAddress) -> PartialNote { // Helper logic for private balance operations } #[internal("public")] fn _finalize_transfer(from: AztecAddress, amount: u128) { // Helper logic for public finalization } ``` Call internal functions via `self.internal`: ``` let partial = self.internal._prepare_private_balance_increase(recipient); ``` Key differences from `#[only_self]`: * **Inlined**: Code is inserted at call site, not a separate circuit/call * **Private internal**: Can only be called from private external or internal functions * **Public internal**: Can only be called from public external or internal functions ## Implementing notes[​](#implementing-notes "Direct link to Implementing notes") The `#[note]` attribute is used to define notes in Aztec contracts. When a struct is annotated with `#[note]`, the Aztec macro applies a series of transformations and generates implementations to turn it into a note that can be used in contracts to store private data. 1. **NoteType trait**: Provides a unique identifier for the note type via `get_id()` 2. **NoteHash trait**: Implements note hash and nullifier computation: * `compute_note_hash(self, owner, storage_slot, randomness)` - computes the note's hash * `compute_nullifier(self, context, owner, note_hash_for_nullification)` - computes the nullifier using the owner's nullifying key * `compute_nullifier_unconstrained(self, owner, note_hash_for_nullification)` - unconstrained version for use outside circuits 3. **NoteProperties struct**: A separate struct is generated to describe the note's fields, which is used for efficient retrieval of note data ### Example[​](#example "Direct link to Example") ``` #[note] pub struct CustomNote { value: Field, } ``` The `owner` is passed as a runtime parameter to the `compute_note_hash` and `compute_nullifier` functions, not stored as a field on the note. To see the exact generated code, run `aztec-nargo expand` on your contract. Key things to keep in mind: * The note struct must implement or derive the `Packable` trait * Developers can use `#[custom_note]` instead of `#[note]` to provide their own `NoteHash` implementation * The note's fields are automatically serialized and deserialized in the order they are defined in the struct ## Storage struct #\[storage][​](#storage-struct-storage "Direct link to Storage struct #\[storage]") The `#[storage]` attribute is used to define the storage structure for an Aztec contract. When a struct is annotated with `#[storage]`, the macro: 1. **Context Injection**: Injects a `Context` generic parameter into the storage struct and all its fields, allowing storage to interact with the Aztec context 2. **Storage Implementation Generation**: Generates an `impl` block with an `init` function that initializes each storage variable with its assigned slot 3. **Storage Slot Assignment**: Automatically assigns storage slots to each field based on their serialized length 4. **Storage Layout Generation**: Creates a `StorageLayout` struct exported via `#[abi(storage)]` for use in the contract artifact ### Example[​](#example-1 "Direct link to Example") ``` #[storage] struct Storage { balance: PublicMutable<Field>, owner: PublicMutable<AztecAddress>, token_map: Map<AztecAddress, Field>, } ``` To see the exact generated code, run `aztec-nargo expand` on your contract. Alternatively, use `#[storage_no_init]` if you need manual control over storage slot allocation. Key things to keep in mind: * Only one storage struct can be defined per contract, and it must be named `Storage` * `Map` types and private `Note` types always occupy a single storage slot ## #\[storage\_no\_init][​](#storage_no_init "Direct link to #\[storage_no_init]") The `#[storage_no_init]` attribute is an alternative to `#[storage]` that gives you manual control over storage slot allocation. Use this when you need custom slot assignments or want to maintain compatibility with existing storage layouts. With `#[storage_no_init]`, you must provide your own `init` function: ``` #[storage_no_init] struct Storage<Context> { balance: PublicMutable<Field, Context>, owner: PublicMutable<AztecAddress, Context>, } impl<Context> Storage<Context> { fn init(context: Context) -> Self { Storage { balance: PublicMutable::new(context, 1), // Explicit slot assignment owner: PublicMutable::new(context, 5), // Non-sequential slot } } } ``` Unlike `#[storage]`, this macro does not generate: * The `init` function (you must implement it) * The `StorageLayout` struct for the contract artifact ## Further reading[​](#further-reading "Direct link to Further reading") * [Macros reference](/developers/testnet/docs/aztec-nr/framework-description/macros.md) --- # Understanding Function Context ## What is the context[​](#what-is-the-context "Direct link to What is the context") The context is an object that is made available within every function in `Aztec.nr`. As mentioned in the [kernel circuit documentation](/developers/testnet/docs/foundational-topics/advanced/circuits/private_kernel.md). At the beginning of a function's execution, the context contains all of the kernel information that application needs to execute. During the lifecycle of a transaction, the function will update the context with each of its side effects (created notes, nullifiers etc.). At the end of a function's execution the mutated context is returned to the kernel to be checked for validity. Behind the scenes, Aztec.nr will pass data the kernel needs to and from a circuit, this is abstracted away from the developer. In a developer's eyes, the context is a useful structure that allows you to access and mutate the state of the Aztec blockchain. On this page, you'll learn * The details and functionalities of the private context in Aztec.nr * Difference between the private and public contexts and their unified APIs * Components of the private context, such as inputs and block header. * Elements like return values, read requests, new note hashes, and nullifiers in transaction processing * Differences between the private and public contexts, especially the unique features and variables in the public context ## Two contexts, one API[​](#two-contexts-one-api "Direct link to Two contexts, one API") The `Aztec` blockchain contains two environments - public and private. * Private, for private transactions taking place on user's devices. * Public, for public transactions taking place on the network's sequencers. As there are two distinct execution environments, they both require slightly differing execution contexts. Despite their differences, the APIs for interacting with each are unified. Leading to minimal context switch when working between the two environments. The following section will cover both contexts. ## The Private Context[​](#the-private-context "Direct link to The Private Context") The code snippet below shows what is contained within the private context. private-context ``` inputs: PrivateContextInputs, side_effect_counter: u32, min_revertible_side_effect_counter: u32, is_fee_payer: bool, args_hash: Field, return_hash: Field, pub(crate) expiration_timestamp: u64, pub(crate) note_hash_read_requests: BoundedVec<Scoped<Counted<Field>>, MAX_NOTE_HASH_READ_REQUESTS_PER_CALL>, pub(crate) nullifier_read_requests: BoundedVec<Scoped<Counted<Field>>, MAX_NULLIFIER_READ_REQUESTS_PER_CALL>, key_validation_requests_and_separators: BoundedVec<KeyValidationRequestAndSeparator, MAX_KEY_VALIDATION_REQUESTS_PER_CALL>, pub(crate) note_hashes: BoundedVec<Counted<NoteHash>, MAX_NOTE_HASHES_PER_CALL>, pub(crate) nullifiers: BoundedVec<Counted<Nullifier>, MAX_NULLIFIERS_PER_CALL>, pub(crate) private_call_requests: BoundedVec<PrivateCallRequest, MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL>, public_call_requests: BoundedVec<Counted<PublicCallRequest>, MAX_ENQUEUED_CALLS_PER_CALL>, public_teardown_call_request: PublicCallRequest, l2_to_l1_msgs: BoundedVec<Counted<L2ToL1Message>, MAX_L2_TO_L1_MSGS_PER_CALL>, ``` > [Source code: noir-projects/aztec-nr/aztec/src/context/private\_context.nr#L140-L163](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/aztec-nr/aztec/src/context/private_context.nr#L140-L163) ### Private Context Broken Down[​](#private-context-broken-down "Direct link to Private Context Broken Down") #### Inputs[​](#inputs "Direct link to Inputs") The context inputs includes all of the information that is passed from the kernel circuit into the application circuit. It contains the following values. private-context-inputs ``` #[derive(Eq)] pub struct PrivateContextInputs { pub call_context: CallContext, pub anchor_block_header: BlockHeader, pub tx_context: TxContext, pub start_side_effect_counter: u32, // The transaction's siloed protocol nullifier: kernel-checked, identical on every private call of the // transaction, and exactly the value inserted at index 0 of the transaction's nullifiers. Set by the PXE. pub protocol_nullifier: Field, } ``` > [Source code: noir-projects/aztec-nr/aztec/src/context/inputs/private\_context\_inputs.nr#L7-L18](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/aztec-nr/aztec/src/context/inputs/private_context_inputs.nr#L7-L18) As shown in the snippet, the application context is made up of 3 main structures. The call context, the block header, and the private global variables. First of all, the [`CallContext`](/aztec-nr-api/testnet/noir_aztec/protocol/abis/call_context/struct.CallContext.html), which contains information about the current call being made: 1. Msg Sender <!-- --> * The message sender is the account (Aztec Contract) that sent the message to the current context. In the first call of the kernel circuit (often the account contract call), this value will be empty. For all subsequent calls the value will be the previous call. > The graphic below illustrates how the message sender changes throughout the kernel circuit iterations. ![](/assets/ideal-img/sender_context_change.7a4633f.640.png) 2. Contract address * This value is the address of the current context's contract address. This value will be the value of the current contract that is being executed. 3. Flags * Furthermore there are a series of flags that are stored within the application context: <!-- --> * is\_static\_call: This will be set if and only if the current call is a static call. In a static call, state changing altering operations are not allowed. ### Block Header[​](#block-header "Direct link to Block Header") Another structure that is contained within the context is the [`BlockHeader`](/aztec-nr-api/testnet/noir_aztec/protocol/abis/block_header/struct.BlockHeader.html) object, which is the header of the block used to generate proofs against. ### Transaction Context[​](#transaction-context "Direct link to Transaction Context") The private context provides access to the [`TxContext`](/aztec-nr-api/testnet/noir_aztec/protocol/abis/transaction/tx_context/struct.TxContext.html) as well, which holds user-defined values for the transaction in general that stay constant throughout its execution. ### Args Hash[​](#args-hash "Direct link to Args Hash") To allow for flexibility in the number of arguments supported by Aztec functions, all functio
프로젝트로 돌아가기