Aztec 백서

Aztec

원문

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

t and it remains private. The note hash tree is append-only - if it wasn't, when a note was spent, external observers would notice that the tree leaf inserted in some transaction was modified in a second transaction, linking them together and leaking privacy. For example, when a user made a payment to a third party, the recipient would be able to know when they spent the received funds. Nullifiers exist to solve this issue. Note: Aztec.nr comes with some prebuilt note types, including [`UintNote`](https://github.com/aztec-labs-eng/aztec-node/tree/v6.0.0-rc.1/noir-projects/aztec-nr/uint-note) and [`AddressNote`](https://github.com/aztec-labs-eng/aztec-node/tree/v6.0.0-rc.1/noir-projects/aztec-nr/address-note), but users are also free to create their own with the `#[note]` macro. ##### Note Lifecycle[​](#note-lifecycle "Direct link to Note Lifecycle") Notes are more complicated than public state, and so it helps to see the different stages one goes through, and when and where each stage happens: * **Creation**: an account executing a private contract function creates a new note according to contract logic, e.g., transferring tokens to a recipient. Note values (e.g., a token amount) and metadata are set, the note hash is computed, and inserted as one of the effects of the transaction. * **Encryption**: the content of the note is encrypted with a key only the sender and intended recipient know - no other account can decrypt this message. * **Delivery**: the encrypted message is delivered to the recipient via some means. Options include storing it onchain as a transaction log, or sending it offchain, e.g., via email or by having the recipient scan a QR code on the sender's device. * **Insertion**: the transaction is sent to the network and gets included in a block. The note hash is inserted into the note hash tree - this is visible to the entire network, but the content of the note remains private. * **Discovery**: the recipient processes the encrypted message they were sent, decrypting it and finding the note's content (i.e., the hash preimage). They verify that the note's hash exists onchain in the note hash tree. They store the note's content in their own private database and can now spend the note. * **Reading**: while executing a private contract function, the recipient fetches the note's content and metadata from their private database (in their PXE) and shows that its hash exists in the note hash tree as part of the zero-knowledge proof. * **Nullification**: the recipient computes the note's nullifier and inserts it as one of the effects of the transaction, preventing the note from being read again. #### Nullifiers[​](#nullifiers "Direct link to Nullifiers") A nullifier is a value which indicates a resource has been spent. Nullifiers are unique and stored onchain in the nullifier tree. The protocol forbids the same nullifier from being inserted into the tree twice. Spending the same resource therefore results in a duplicate nullifier, which invalidates the transaction. The nullifier tree is **append-only** for the same reason that the note hash tree is append-only. Most often, nullifiers are used to mark a note as being spent, which prevents note double spends. This requires two properties from the function that computes a note's nullifier: * **Deterministic**: the nullifier **must** be deterministic given a note, so that the same nullifier value is computed every time the note is attempted to be spent. A non-deterministic nullifier would result in a note being spendable more than once because the nullifiers would not be duplicates. * **Secret**: the nullifier **must** not be computable by anyone except the owner, *even by someone who knows the full note content*. This is because some third parties *do* know the note content: when paying someone and creating a note for them, the payer creates the note on their device and thus has access to all of its data and metadata. There are multiple ways to compute nullifiers that fulfill this property, but typically they are computed as a **hash of the note contents concatenated with a private key of the note's owner**. These values are **immutable**, and only the owner knows their private keys, ensuring both determinism and secrecy. These nullifiers are sometimes called 'zcash-style nullifiers' because this is the format ZCash uses for their note nullifiers. ### Note Messages and Discovery[​](#note-messages-and-discovery "Direct link to Note Messages and Discovery") Because notes are private, not even the intended recipient is aware of their existence, and therefore they must be somehow notified. For example, when making a payment and creating a note for the payee with the intended amount, they must be shown the preimage of the note that was inserted in the note hash tree in a given transaction in order to acknowledge the payment. Recipients learning about notes created for them is known as 'note discovery', which is a process Aztec.nr handles efficiently and automatically. However, it does mean that when a note is created, a *message* with the content of the note is created and needs to be delivered to a recipient via one of multiple means detailed below. When working with private state variables, many operations return a `NoteMessage<Note>` type rather than the note directly. This is a type-safe wrapper that ensures you explicitly decide how to deliver the note to its recipient. #### Delivery Methods[​](#delivery-methods "Direct link to Delivery Methods") Private notes need to be communicated to their recipients so they know the note exists and can use it. The [`NoteMessage`](/aztec-nr-api/testnet/noir_aztec/note/struct.NoteMessage) wrapper forces you to make an explicit choice about how this happens: * [`MessageDelivery::onchain_constrained()`](/aztec-nr-api/testnet/noir_aztec/messages/delivery/struct.MessageDelivery): Verified in the circuit (most secure, but highest cost) - Use when the sender cannot be trusted to deliver correctly (e.g., protocol fees, multisig config updates). * [`MessageDelivery::onchain_unconstrained()`](/aztec-nr-api/testnet/noir_aztec/messages/delivery/struct.MessageDelivery): Message stored onchain but no guarantees on content - Use when the sender is incentivized to deliver correctly but may not have an offchain channel to the recipient. * [`MessageDelivery::offchain()`](/aztec-nr-api/testnet/noir_aztec/messages/delivery/struct.MessageDelivery): Lowest cost, no onchain data - Use when the sender and recipient can communicate and the sender is incentivized to deliver correctly. note\_delivery ``` #[external("private")] fn mint(amount: u128, recipient: AztecAddress) { let replacement_note_message = self.storage.admin.get_note(); let admin = replacement_note_message.get_note().address; assert(admin == self.msg_sender(), "Only admin can mint"); // We deliver the new note message to the admin using unconstrained delivery, since the admin is motivated to // deliver the message to themselves (hence no need to constrain it). replacement_note_message.deliver(MessageDelivery::onchain_unconstrained()); // We increase the total supply and once again use unconstrained delivery, since the admin is motivated to // deliver the message (he's the owner of the new note as well). self.storage.total_supply.replace(|current| UintNote { value: current.value + amount }, admin).deliver( MessageDelivery::onchain_unconstrained(), ); // At last we mint the tokens to the recipient. self.storage.balances.at(recipient).add(amount).deliver(MessageDelivery::onchain_constrained()); } ``` > [Source code: noir-projects/noir-contracts/contracts/app/private\_token\_contract/src/main.nr#L63-L82](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/private_token_contract/src/main.nr#L63-L82) Methods that return `NoteMessage` include `initialize()`, `get_note()`, and `replace()` on `PrivateMutable`, `initialize()` on `PrivateImmutable`, and `insert()` on `PrivateSet` (more on these methods and private state variable types shortly). ### How Aztec.nr Abstracts Private State Variables[​](#how-aztecnr-abstracts-private-state-variables "Direct link to How Aztec.nr Abstracts Private State Variables") Implementing a private state variable requires careful coordination of multiple primitives and concepts (creating notes, encrypting, delivering, discovering and processing messages, reading notes, and computing their nullifiers). Aztec.nr provides convenient types and functions that handle all of these low-level details to allow developers to write safe code without having to understand the nitty-gritty. By applying the `#[note]` [macro](/aztec-nr-api/testnet/noir_aztec/macros/notes/fn.note) to a [noir struct](https://noir-lang.org/docs/language/data_types/structs), users can define values that will be storable in notes. Private state variables can then hold these notes and be used to read, write, and deliver note messages to the intended recipient. note Advanced users can change this default behavior by either defining their [own custom note](/developers/testnet/docs/aztec-nr/framework-description/custom_notes.md) hash and nullifier functions, implementing their own state variables, or even accessing the note hash and nullifiers tree directly. The snippet below shows a contract with two private state variables: an admin address (stored in an `AddressNote`) and a counter of how many calls the admin has made (stored in a `UintNote`). These values will be private and therefore not known except by the accounts that own these notes (the admin). In the `perform_admin_action` private function, the contract checks that it is being called by the correct admin and updates the call count by incrementing it by one. (Note that this is not a real snippet, it's missing some small irrelevant details - but the gist of it is correct) ``` #[note] pub struct AddressNote { value: AztecAddress, } #[note] pub struct UintNote { value: u128, } #[storage] struct Storage { admin: Owned<PrivateImmutable<AddressNote, Context>, Context>, admin_call_count: Owned<PrivateMutable<UintNote, Context>, Context>, } #[external("private")] fn perform_admin_action() { // Read the contract's admin address and check against the caller let admin = self.storage.admin.get_note().value; assert(self.msg_sender() == admin); // Update the call count by replacing (updating - rename soon) the current note with a new one that equals the // current value + 1 - this requires knowing what the current value is in the first place, i.e., reading the variable. // // We then deliver the encrypted message with the note's content to the admin so that they become aware of the new // value of the counter and can update it again in the future. self.storage.admin_call_count .replace(|current| UintNote{ value: current.value + 1 }) // wouldn't it be great if we didn't have to deal with this wrapping and unwrapping? .deliver(MessageDelivery::onchain_constrained()); // ... } ``` ### Choosing a Private State Variable[​](#choosing-a-private-state-variable "Direct link to Choosing a Private State Variable") Due to the complexities of Aztec's private state model, private state variables do not map 1:1 with public state variables. Understanding these differences between the different private state variables is important when it comes to designing private smart contracts. Below is a table comparing certain key properties of the different private state variables Aztec.nr offers: | State variable | Mutable? | Cost to read? | Writable by third parties? | Example use case | | ----------------------------------------------------------------------------------------- | -------- | ------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------- | | [`PrivateMutable`](/aztec-nr-api/testnet/noir_aztec/state_vars/struct.PrivateMutable) | yes | yes | no | Mutable user state only accessible by them (e.g. user settings or keys) | | [`PrivateImmutable`](/aztec-nr-api/testnet/noir_aztec/state_vars/struct.PrivateImmutable) | no | no | no | Fixed configuration, one-way actions (e.g. initialization settings for a proposal) | | [`PrivateSet`](/aztec-nr-api/testnet/noir_aztec/state_vars/struct.PrivateSet) | yes | yes | yes | Aggregated state others can add to, e.g. token balance (set of amount notes), nft collections (set of nft ids) | ### Owned State Variables[​](#owned-state-variables "Direct link to Owned State Variables") Private state variables like `PrivateMutable`, `PrivateImmutable`, and `PrivateSet` implement the `OwnedStateVariable` trait. You must wrap them in `Owned`. Access the underlying state variable for a specific owner using `.at(owner)` ### PrivateMutable[​](#privatemutable "Direct link to PrivateMutable") `PrivateMutable` is conceptually similar to `PublicMutable` and regular Solidity state variables in that it is a variable that has exactly one value at any point in time that can be read and written. However, for `PrivateMutable`: * The value is, of course, *private*, meaning only the account the value belongs to can read it. * *Only ONE account can read and write the state variable*. It is not possible, for example, to use a `PrivateMutable` to store user settings and then have some admin account alter these settings. * Reading the current value results in the state variable being updated, increasing tx costs and requiring delivery of a note message. * There is no `write` function - the current value is instead `replace`d. #### Declaration[​](#declaration-3 "Direct link to Declaration") owned\_private\_mutable ``` subscriptions: Owned<PrivateMutable<SubscriptionNote, Context>, Context>, ``` > [Source code: noir-projects/noir-contracts/contracts/app/app\_subscription\_contract/src/main.nr#L74-L76](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/app_subscription_contract/src/main.nr#L74-L76) #### `is_initialized`[​](#is_initialized "Direct link to is_initialized") An unconstrained method to check whether the `PrivateMutable` has been initialized or not: owned\_private\_mutable\_is\_initialized ``` #[external("utility")] unconstrained fn is_initialized(subscriber: AztecAddress) -> bool { self.storage.subscriptions.at(subscriber).is_initialized() } ``` > [Source code: noir-projects/noir-contracts/contracts/app/app\_subscription\_contract/src/main.nr#L171-L176](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/app_subscription_contract/src/main.nr#L171-L176) #### `initialize` and `initialize_or_replace`[​](#initialize-and-initialize_or_replace "Direct link to initialize-and-initialize_or_replace") The `PrivateMutable` should be initialized to create the first note and value. This can be done with either `initialize` or `initialize_or_replace`: owned\_private\_mutable\_initialize ``` self .storage .subscriptions .at(subscriber) .initialize_or_replace(|_| SubscriptionNote { expiry_block_number, remaining_txs: tx_count }) .deliver(MessageDelivery::onchain_constrained()); ``` > [Source code: noir-projects/noir-contracts/contracts/app/app\_subscription\_contract/src/main.nr#L161-L168](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/app_subscription_contract/src/main.nr#L161-L168) #### `get_note`[​](#get_note "Direct link to get_note") This function allows us to get the note of a `PrivateMutable`, essentially reading the value: ``` #[external("private")] fn read_settings() { let owner = self.msg_sender(); self.storage.user_settings.at(owner).get_note().deliver(MessageDelivery::onchain_constrained()); } ``` info To ensure that a user's private execution always uses the latest value of a `PrivateMutable`, the `get_note` function will nullify the note that it is reading. This means that if two people are trying to use this function with the same note, only one will succeed. Reading a `PrivateMutable` nullifies and recreates the note. This makes reads indistinguishable from writes and ensures the sequencer cannot learn the note's value. #### `replace`[​](#replace "Direct link to replace") To update the value of a `PrivateMutable`, we can use the `replace` method: owned\_single\_private\_mutable\_replace ``` #[external("private")] fn transfer_admin(new_admin: AztecAddress) { self .storage .admin .replace( |old| { assert(old.address == self.msg_sender(), "Only admin can transfer admin privileges"); AddressNote { address: new_admin } }, new_admin, ) .deliver(MessageDelivery::onchain_constrained()); } ``` > [Source code: noir-projects/noir-contracts/contracts/app/private\_token\_contract/src/main.nr#L85-L100](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/app/private_token_contract/src/main.nr#L85-L100) ### PrivateImmutable[​](#privateimmutable "Direct link to PrivateImmutable") `PrivateImmutable` represents a unique private state variable that, as the name suggests, is immutable. Once initialized, its value cannot be altered. This is the private equivalent of `PublicImmutable`, except the value is only known to its owner. Unlike `PrivateMutable`, the `get_note` function for a `PrivateImmutable` doesn't nullify the current note and returns the `Note` directly (not wrapped in `NoteMessage`). This means that multiple accounts can concurrently call this function to read the value. #### Declaration[​](#declaration-4 "Direct link to Declaration") private\_immutable ``` note_in_private_immutable: Owned<PrivateImmutable<TestNote, Context>, Context>, ``` > [Source code: noir-projects/noir-contracts/contracts/test/test\_contract/src/main.nr#L92-L94](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/test/test_contract/src/main.nr#L92-L94) `PrivateImmutable` variables also have the `initialize` and `get_note` functions on them but no `initialize_or_replace` since they cannot be modified. ### PrivateSet[​](#privateset "Direct link to PrivateSet") `PrivateSet` is used for managing a collection of notes. Like `PrivateMutable`, this is a private state variable that can be modified. There are two key differences: * A `PrivateSet` is not a single value but a *set* (a collection) of values (represented by notes) * Any account can insert values into someone else's set. The set's current value is the collection of notes in the set that have not yet been nullified. These notes can have any type: they could be NFT IDs representing a user's NFT collection, or they might be token amounts, in which case *the sum* of all values in the set would be the user's current balance. #### Declaration[​](#declaration-5 "Direct link to Declaration") For example, to add private token balances to storage: private\_set ``` #[storage] struct Storage<Context> { balances: Owned<PrivateSet<FieldNote, Context>, Context>, } ``` > [Source code: noir-projects/noir-contracts/contracts/test/pending\_note\_hashes\_contract/src/main.nr#L27-L32](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/test/pending_note_hashes_contract/src/main.nr#L27-L32) #### `insert`[​](#insert "Direct link to insert") Allows us to modify the storage by inserting a note into the `PrivateSet`: private\_set\_insert ``` owner_balance.insert(note).deliver(MessageDelivery::onchain_unconstrained()); ``` > [Source code: noir-projects/noir-contracts/contracts/test/pending\_note\_hashes\_contract/src/main.nr#L47-L49](https://github.com/aztec-labs-eng/aztec-node/blob/v6.0.0-rc.1/noir-projects/noir-contracts/contracts/test/pending_note_hashes_contract/src/main.nr#L47-L49) Note: The `Owned` wrapper req
프로젝트로 돌아가기