Aztec 백서

Aztec

원문

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

ging-secret-strategy) for the variants, the trade-offs, and the defaults in each environment. For an unconstrained self-send (the recipient is one of the wallet's own accounts), the PXE always uses an [address-derived shared secret](/developers/testnet/docs/aztec-nr/framework-description/note_delivery.md#tagging-secret-strategy) regardless of what the hook returns: both sides' keys are local, so no handshake is needed. ### In Noir tests[​](#in-noir-tests-1 "Direct link to In Noir tests") When testing in Noir, leaving the strategy unset makes `TestEnvironment` fall back to the bare PXE default. Set a strategy when creating the environment to exercise a specific one; it affects message delivery in private executions that use the default wallet strategy hook. Use `with_default_tag_secret_strategy` to configure the strategy for a specific delivery mode: ``` let env = TestEnvironment::new_opts( TestEnvironmentOptions::new().with_default_tag_secret_strategy( MessageDelivery::onchain_unconstrained(), TaggingSecretStrategy::non_interactive_handshake(), ), ); ``` Use `with_default_tag_secret_strategy_all_modes` only when the same strategy should apply to both constrained and unconstrained delivery. Contract-fixed delivery derivations bypass this default strategy. ### In production[​](#in-production-1 "Direct link to In production") Pass a `resolveTaggingSecretStrategy` hook when [creating the PXE](#configuring-hooks). It receives a `TaggingSecretStrategyRequest` with the executing contract's address and the message's sender, recipient, and delivery mode (`'constrained'` or `'unconstrained'`), so a wallet can apply per-application or per-recipient policies, or surface the decision to the user, instead of returning a fixed value. When the hook is absent, the PXE applies a default: both delivery modes use a [non-interactive handshake](/developers/testnet/docs/aztec-nr/framework-description/note_delivery.md#tagging-secret-strategy) so the recipient can discover the message without prior coordination. Returning `{ type: 'interactive-handshake' }` makes the handshake registry request the recipient's signed authorization through the [`resolveCustomRequest`](#resolvecustomrequest) hook (see the [example](#example-interactive-handshakes) below), so a wallet should only choose it when that request can be served. ## `resolveCustomRequest`[​](#resolvecustomrequest "Direct link to resolvecustomrequest") A general-purpose hook for *custom*, caller-defined requests. A contract reaches for it when it needs something it cannot get on its own: not from its local notes, not from the protocol's existing oracles. The contract gives the request a `kind` and an opaque `payload`, and the wallet returns an opaque response. Because the request is caller-defined, the wallet decides per `kind` how to answer, whether by reading state it holds, contacting another party, or fetching offchain data. ### In production[​](#in-production-2 "Direct link to In production") Pass a `resolveCustomRequest` hook when [creating the PXE](#configuring-hooks). It receives a `CustomRequest` with the issuing contract's address and class ID, the request `kind`, and the opaque `payload`, and returns the response. Because any contract can issue a request, the hook should check both the `kind` and the issuing contract before answering, dispatching on `kind` to the matching resolver. When the hook is absent, the request cannot be served and simulation fails. ### Example: interactive handshakes[​](#example-interactive-handshakes "Direct link to Example: interactive handshakes") The `HandshakeRegistry`'s `interactive_handshake` uses this hook to obtain the recipient's signed authorization. The payload carries what the signer needs to decide: who the recipient is, the handshake being authorized, and the chain context, but never the sender. The response carries what the registry needs to verify the recipient's signature in-circuit. --- # Kernelless simulations This page explains what kernelless simulation is in the Private eXecution Environment (PXE), how it differs from a full simulation, and where it does and does not apply. If you are looking for the recipe to make `.simulate()` succeed without signing prompts, see [Simulate without signing prompts](/developers/testnet/docs/aztec-js/how_to_simulate_without_signing.md). ## Overview[​](#overview "Direct link to Overview") A "full" simulation in the PXE runs the user's private function bytecode, then runs every private kernel circuit (init, inner, reset, tail) over the resulting execution trace. The kernels enforce protocol rules such as side-effect counter sequencing. A **kernelless simulation** runs the same private bytecode, but skips the kernel circuits. Instead, the PXE computes the values the kernel would have produced in TypeScript via `generateSimulatedProvingResult`. The output of a kernelless simulation is the same shape as a full simulation, so callers can read return values, offchain effects, and gas estimates from it without caring which path produced them. Kernelless simulation is the **default** for `PXE.simulateTx`. The `skipKernels` option in `SimulateTxOpts` defaults to `true`, and `BaseWallet` inherits that default. In normal use, every call to `.simulate()` on a contract method already runs without the kernels. The main consequence is speed. Skipping the kernels removes the most expensive part of simulation, so a kernelless run is faster than a full run on typical transactions. ## What the PXE still does[​](#what-the-pxe-still-does "Direct link to What the PXE still does") A kernelless simulation is not a partial execution. The PXE still: * runs the real ACIR bytecode for every private function in the call chain * executes oracles, decrypts notes, builds nullifiers, and captures offchain effects * simulates public calls against an ephemeral fork of public state * runs `node.isValidTx` against the resulting transaction, unless `skipTxValidation` is set * at the raw `PXE.simulateTx` level, enforces fee payer presence unless `skipFeeEnforcement` is set. Contract `.simulate()` calls through `BaseWallet` already pass `skipFeeEnforcement: true` for estimation, so you do not need to provide a fee block for normal read simulations What it skips with `skipKernels: true`: * the private kernel init, inner, reset, and tail circuits * the proof generation associated with those kernels The kernels themselves do not check authentication witnesses. Authwit validity is checked by user-contract code (the `is_valid` call that the `#[authorize_once]` macro injects into the called function). What lets a kernelless simulation skip the signing prompt is the **stub-account override**, not the absence of the kernels: replacing the caller's account contract with a stub whose `is_valid` always returns true lets that user-contract check pass without a signature. ## Simulation overrides[​](#simulation-overrides "Direct link to Simulation overrides") A kernelless simulation accepts an optional `SimulationOverrides` payload that lets you replace pieces of the state the PXE would otherwise read from chain. The shape (in `yarn-project/stdlib/src/tx/simulated_tx.ts`) is: ``` type ContractOverrides = Record< string, { instance: ContractInstanceWithAddress } >; class SimulationOverrides { publicStorage?: PublicStorageOverride[]; contracts?: ContractOverrides; } ``` Two parts: * `publicStorage` rewrites slots in the ephemeral public-data fork before simulation. This is compatible with kernel execution; you can use it with or without `skipKernels`. * `contracts` swaps a contract instance in the simulator's contract DB by replacing its `currentContractClassId`. There is no `artifact` field; the new class id must already be registered with the PXE via `pxe.registerContractClass(...)` so the simulator can resolve the bytecode. This requires `skipKernels: true`: PXE explicitly rejects contract overrides combined with kernel execution, because the kernels would fail validations against the swapped class. The `contracts` override path is what makes "simulate without signing" possible. Replacing the caller's account contract with a stub whose `is_valid` always returns true lets the simulation reach `#[authorize_once]` call sites without prompting the user to sign anything. For the cheat that simulates a contract as if it had already been upgraded to a new class, see [`fastForwardContractUpdate`](/developers/testnet/docs/aztec-js/how_to_test.md#fast-forwarding-a-contract-update), which returns a `SimulationOverrides` covering both the registry storage rewrite and the upgraded instance entry. ## Stub account contracts[​](#stub-account-contracts "Direct link to Stub account contracts") The stub-account pattern is the standard way to drive a kernelless simulation without authwit prompts. The Noir sources live at `noir-projects/noir-contracts/contracts/account/simulated_schnorr_account_contract/` and `simulated_ecdsa_account_contract/`. Both implement `is_valid` to always return `IS_VALID_SELECTOR`, so authwit validity checks pass without a real signature. Their constructors deliberately emit the same shape of side effects as the real account contracts (one nullifier for the contract init, one nullifier for the `SinglePrivateImmutable` signing-key state, one note hash for the key note, and a private log) so that gas estimation against the stub produces the same numbers as the real account. ## Authwit requests come from the app, not the stub[​](#authwit-requests-come-from-the-app-not-the-stub "Direct link to Authwit requests come from the app, not the stub") The `CallAuthorizationRequest` offchain effects you see during a kernelless simulation are emitted by the **app or token contract's `#[authorize_once]` macro** during private execution. The stub account's only job is to let the validity check pass so the simulation can reach those call sites in the first place. The wallet then collects the requests via `collectOffchainEffects(privateExecutionResult)`, filters them by `CallAuthorizationRequest.getSelector()`, and decodes each one to build a real `AuthWitness`. ## Where kernelless does not apply[​](#where-kernelless-does-not-apply "Direct link to Where kernelless does not apply") The default applies to `simulateTx`, but not to every entry point that looks like simulation: * **`profileTx`** is not kernelless. `PXE.profileTx` always runs the private kernels after private execution; `skipProofGeneration` controls only whether a proof is produced, not whether kernel logic runs. If you call `.profile()` to measure circuit gates, expect the full kernel cost. * **Public-only fast path**. When `BaseWallet.simulateTx` detects a leading run of public static calls, it sends them straight to `node.simulatePublicCalls` through `simulateViaNode`, bypassing the PXE private path entirely. There is no kernel to skip. `SimulationOverrides` still applies on that path. * **Utility functions**. `FunctionType.UTILITY` calls go through `wallet.executeUtility`, not `pxe.simulateTx`. `ContractFunctionInteraction.simulate` rejects `overrides.publicStorage` and `overrides.contracts` for utility functions. ## Gas estimation parity[​](#gas-estimation-parity "Direct link to Gas estimation parity") If the real transaction will pay through a fee payment contract (FPC) with private side effects (the FPC emits notes during fee payment), include that FPC in the simulation's fee options. The FPC's side effects feed into gas estimation, and you can run kernelless with the FPC attached to get both the speed benefit and accurate gas numbers. The default of "omit the fee block" only produces accurate gas for transactions whose fee path has no private side effects. ## Multi-account scopes[​](#multi-account-scopes "Direct link to Multi-account scopes") A simulation can run with multiple scoped accounts via `additionalScopes`. If you build a stub-account override for the sender only, the simulation will still prompt for authwits from any other in-scope account it touches. The override map must cover every account in scope, not just `from`. The canonical implementation is `EmbeddedWallet.buildAccountOverrides` in `yarn-project/wallets/src/embedded/embedded_wallet.ts`: for each scoped address, fetch the live contract instance from the PXE, copy it, and rewrite `currentContractClassId` to point at the stub class id registered at wallet startup. When implementing overrides in your own wallet, follow this pattern and make sure the scope list you build against matches the one the simulation will run with. ## When you might still want a full simulation[​](#when-you-might-still-want-a-full-simulation "Direct link to When you might still want a full simulation") Kernelless is the right default. Reach for `skipKernels: false` only when you are validating kernel-level behavior itself. For everything else, including accurate gas estimation through a fee payment contract with private side effects, run kernelless with the appropriate fee options. ## Related[​](#related "Direct link to Related") * [Simulate without signing prompts](/developers/testnet/docs/aztec-js/how_to_simulate_without_signing.md) for the recipe-oriented version of this page. * [Reading contract data](/developers/testnet/docs/aztec-js/how_to_read_data.md) for the basic `.simulate()` API. * [Wallets](/developers/testnet/docs/foundational-topics/wallets.md) for the wallet's role in capturing private authorizations during simulation. --- # State Management Aztec has a hybrid public/private state model. Contract developers can specify which data is public and which is private, as well as the functions that operate on that data. Private and public data are stored in two separate trees: a **public data tree** and a **note hashes tree**. Both trees store state for all accounts on the network directly as leaves, unlike Ethereum where a state trie contains smaller tries for individual accounts. This means storage must be carefully allocated to prevent collisions. Storage is *siloed* to each contract, though the exact siloing mechanism differs slightly between public and private storage. ## Public State[​](#public-state "Direct link to Public State") Public state in Aztec works similarly to other blockchains. It is transparent and managed by smart contract logic. The sequencer stores and updates public state. It executes state transitions, generates proofs of correct execution (or delegates to the prover network), and publishes data to Ethereum. ## Private State[​](#private-state "Direct link to Private State") Private state is encrypted and owned by users who hold the decryption keys. It uses an append-only data structure since updating records directly would leak information about the transaction graph. To "delete" private state, you add an associated nullifier to a nullifier set. The nullifier is computed such that observers cannot link a state record to its nullifier without the owner's keys. Modifying state is accomplished by nullifying the existing record and creating a new one. This gives private state an intrinsic UTXO (unspent transaction output) structure. ## Notes[​](#notes "Direct link to Notes") Private state uses UTXOs, commonly called **notes**. Notes are encrypted pieces of data that only their owner can decrypt. ### How Notes Work[​](#how-notes-work "Direct link to How Notes Work") In Ethereum's account-based model, each account maps to a specific storage location. In Aztec's UTXO model, notes specify their owner and have no fixed relationship between accounts and data locations. Rather than storing entire notes, the protocol stores **note commitments** (hashes) in a Merkle tree called the note hash tree. Users prove they know the note preimage when updating private state. When a note is consumed, Aztec creates a nullifier from the note data and may create new notes with updated information. This decouples the actions of creating, updating, and deleting private state. ![](/assets/ideal-img/public-and-private-state-diagram.8ac73af.640.png) Notes work like cash. To spend a 5 dollar note on a $3.50 purchase, you nullify the $5 note and create two new notes: $1.50 for yourself and $3.50 for the recipient. Only you and the recipient know about the $3.50 transfer. ### Sending Notes[​](#sending-notes "Direct link to Sending Notes") When creating notes for a recipient, you need a way to deliver them: **Onchain (encrypted logs):** The standard method. Emit an encrypted log as part of your transaction. The encrypted note data is posted onchain, allowing recipients to find notes through [note discovery](/developers/testnet/docs/foundational-topics/advanced/storage/note_discovery.md). **Offchain:** If you know the recipient directly, share the note data with them. They store it in their PXE and can spend it later. **Self-created notes:** Notes you create for yourself don't need broadcasting. Store them in your PXE to prove ownership and spend them later. ### Abstracting Notes[​](#abstracting-notes "Direct link to Abstracting Notes") Users don't need to think about individual notes. The Aztec.nr library abstracts notes by letting developers define custom note types that specify how notes are created, nullified, transferred, and displayed. Aztec.nr also handles [note discovery](/developers/testnet/docs/foundational-topics/advanced/storage/note_discovery.md) for notes encrypted to a user's account. ## Technical Details[​](#technical-details "Direct link to Technical Details") ### Storage Slots[​](#storage-slots "Direct link to Storage Slots") Public storage uses literal storage slots. Private storage uses logical storage slots that associate multiple notes together. See [storage slots](/developers/testnet/docs/foundational-topics/advanced/storage/storage_slots.md) for details. ### Contract Address Siloing[​](#contract-address-siloing "Direct link to Contract Address Siloing") The contract address is included when computing note hashes to ensure different contracts don't produce identical hashes. The protocol handles this automatically. ### Note Types[​](#note-types "Direct link to Note Types") Aztec.nr provides several note types: * **`PrivateSet`** - A collection of notes, useful for balances represented as multiple value notes * **`PrivateMutable`** - A single note representing one value that can be replaced * **`PrivateImmutable`** - A single note that cannot be changed after initialization These state variables must be wrapped in an `Owned<>` type that specifies the note owner. The `Owned<>` wrapper binds a note collection to a specific owner address, ensuring notes are correctly associated with their owner for nullifier computation and access control. ``` #[storage] struct Storage<Context> { balance: Owned<PrivateSet<UintNote, Context>, Context>, } ``` Notes can also be custom types storing any values your application needs. Use the `#[note]` macro for standard notes or `#[custom_note]` for notes requiring custom hash or nullifier computation. ### Built-in Note Types[​](#built-in-note-types "Direct link to Built-in Note Types") **`UintNote`** - Stores a numeric value (`u128`). Supports partial notes for scenarios where the value is determined in public execution. uint\_note\_def ``` #[derive(Deserialize, Eq, Serialize, Packable)] #[custom_note] pub struct UintNote { /// The number stored in the note. pub value: u128, } ``` > [Source code: noir-projects/aztec-nr/uint-note/src/uint\_note.nr#L30-L37](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/aztec-nr/uint-note/src/uint_note.nr#L30-L37) **`FieldNote`** - Stores a single `Field` value. ### Creating and Destroying Notes[​](#creating-and-destroying-notes "Direct link to Creating and Destroying Notes") The [lifecycle module](https://github.com/aztec-labs-eng/aztec-node/tree/v6.0.0-rc.1/noir-projects/aztec-nr/aztec/src/note/lifecycle.nr) contai
프로젝트로 돌아가기