Zama 백서

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

tr></tbody></table> For more details, refer to the [Random Encrypted Numbers](/protocol/solidity-guides/smart-contract/operations/random) document. ## Best Practices Here are some best practices to follow when using encrypted operations in your smart contracts: ### Use the appropriate encrypted type size Choose the smallest encrypted type that can accommodate your data to optimize gas costs. For example, use `euint8` for small numbers (0-255) rather than `euint256`. ❌ Avoid using oversized types: ```solidity // Bad: Using euint256 for small numbers wastes gas euint64 age = FHE.asEuint128(25); // age will never exceed 255 euint64 percentage = FHE.asEuint128(75); // percentage is 0-100 ``` ✅ Instead, use the smallest appropriate type: ```solidity // Good: Using appropriate sized types euint8 age = FHE.asEuint8(25); // age fits in 8 bits euint8 percentage = FHE.asEuint8(75); // percentage fits in 8 bits ``` ### Use scalar operands when possible to save gas Some FHE operators exist in two versions: one where all operands are ciphertexts handles, and another where one of the operands is an unencrypted scalar. Whenever possible, use the scalar operand version, as this will save a lot of gas. ❌ For example, this snippet cost way more in gas: ```solidity euint32 x; ... x = FHE.add(x,FHE.asEuint(42)); ``` ✅ Than this one: ```solidity euint32 x; // ... x = FHE.add(x,42); ``` Despite both leading to the same encrypted result! ### Beware of overflows of FHE arithmetic operators FHE arithmetic operators can overflow. Do not forget to take into account such a possibility when implementing FHEVM smart contracts. ❌ For example, if you wanted to create a mint function for an encrypted ERC20 token with an encrypted `totalSupply` state variable, this code is vulnerable to overflows: ```solidity function mint(externalEuint32 encryptedAmount, bytes calldata inputProof) public { euint32 mintedAmount = FHE.fromExternal(encryptedAmount, inputProof); totalSupply = FHE.add(totalSupply, mintedAmount); balances[msg.sender] = FHE.add(balances[msg.sender], mintedAmount); FHE.allowThis(balances[msg.sender]); FHE.allow(balances[msg.sender], msg.sender); } ``` ✅ But you can fix this issue by using `FHE.select` to cancel the mint in case of an overflow: ```solidity function mint(externalEuint32 encryptedAmount, bytes calldata inputProof) public { euint32 mintedAmount = FHE.fromExternal(encryptedAmount, inputProof); euint32 tempTotalSupply = FHE.add(totalSupply, mintedAmount); ebool isOverflow = FHE.lt(tempTotalSupply, totalSupply); totalSupply = FHE.select(isOverflow, totalSupply, tempTotalSupply); euint32 tempBalanceOf = FHE.add(balances[msg.sender], mintedAmount); balances[msg.sender] = FHE.select(isOverflow, balances[msg.sender], tempBalanceOf); FHE.allowThis(balances[msg.sender]); FHE.allow(balances[msg.sender], msg.sender); } ``` Notice that we did not check separately the overflow on `balances[msg.sender]` but only on `totalSupply` variable, because `totalSupply` is the sum of the balances of all the users, so `balances[msg.sender]` could never overflow if `totalSupply` did not. # Casting and trivial encryption This documentation covers the `asEbool`, `asEuintXX`, and `asEaddress` operations provided by the FHE library for working with encrypted data in the FHEVM. These operations are essential for converting between plaintext and encrypted types, as well as handling encrypted inputs. The operations can be categorized into two main use cases: 1. **Trivial encryption**: Converting plaintext values to encrypted types 2. **Type casting**: Converting between different encrypted types ## 1. Trivial encryption Trivial encryption simply put is a plain text in a format of a ciphertext. ### Overview Trivial encryption is the process of converting plaintext values into encrypted types (ciphertexts) compatible with FHE operators. Although the data is in ciphertext format, it remains publicly visible on-chain, making it useful for operations between public and private values. This type of casting involves converting plaintext (unencrypted) values into their encrypted equivalents, such as: * `bool` → `ebool` * `uint` → `euintXX` * `address` → `eaddress` {% hint style="info" %} When doing trivial encryption, the data is made compatible with FHE operations but remains publicly visible on-chain unless explicitly encrypted. {% endhint %} #### **Example** ```solidity euint64 value64 = FHE.asEuint64(7262); // Trivial encrypt a uint64 ebool valueBool = FHE.asEbool(true); // Trivial encrypt a boolean ``` ## 2. Casting between encrypted types This type of casting is used to reinterpret or convert one encrypted type into another. For example: * `euint32` → `euint64` Casting between encrypted types is often required when working with operations that demand specific sizes or precisions. > **Important**: When casting between encrypted types: > > * Casting from smaller types to larger types (e.g. `euint32` → `euint64`) preserves all information > * Casting from larger types to smaller types (e.g. `euint64` → `euint32`) will truncate and lose information The table below summarizes the available casting functions: | From type | To type | Function | | --------- | -------- | --------------- | | `euintX` | `euintX` | `FHE.asEuintXX` | | `ebool` | `euintX` | `FHE.asEuintXX` | | `euintX` | `ebool` | `FHE.asEbool` | {% hint style="info" %} Casting between encrypted types is efficient and often necessary when handling data with differing precision requirements. {% endhint %} ### **Workflow for encrypted types** ```solidity // Casting between encrypted types euint32 value32 = FHE.asEuint32(value64); // Cast to euint32 ebool valueBool = FHE.asEbool(value32); // Cast to ebool ``` ## Overall operation summary | Casting Type | Function | Input Type | Output Type | | ------------------------ | ------------------- | ----------------- | ----------- | | Trivial encryption | `FHE.asEuintXX(x)` | `uintX` | `euintX` | | | `FHE.asEbool(x)` | `bool` | `ebool` | | | `FHE.asEaddress(x)` | `address` | `eaddress` | | Conversion between types | `FHE.asEuintXX(x)` | `euintXX`/`ebool` | `euintYY` | | | `FHE.asEbool(x)` | `euintXX` | `ebool` | # Generate random numbers This document explains how to generate cryptographically secure random encrypted numbers fully on-chain using the `FHE` library in fhevm. These numbers are encrypted and remain confidential, enabling privacy-preserving smart contract logic. ## **Key notes on random number generation** * **On-chain execution**: Random number generation must be executed during a transaction, as it requires the pseudo-random number generator (PRNG) state to be updated on-chain. This operation cannot be performed using the `eth_call` RPC method. * **Cryptographic security**: The generated random numbers are cryptographically secure and encrypted, ensuring privacy and unpredictability. {% hint style="info" %} Random number generation must be performed during transactions, as it requires the pseudo-random number generator (PRNG) state to be mutated on-chain. Therefore, it cannot be executed using the `eth_call` RPC method. {% endhint %} ## **Basic usage** The `FHE` library allows you to generate random encrypted numbers of various bit sizes. Below is a list of supported types and their usage: ```solidity // Generate random encrypted numbers ebool rb = FHE.randEbool(); // Random encrypted boolean euint8 r8 = FHE.randEuint8(); // Random 8-bit number euint16 r16 = FHE.randEuint16(); // Random 16-bit number euint32 r32 = FHE.randEuint32(); // Random 32-bit number euint64 r64 = FHE.randEuint64(); // Random 64-bit number euint128 r128 = FHE.randEuint128(); // Random 128-bit number euint256 r256 = FHE.randEuint256(); // Random 256-bit number ``` ### **Example: Random Boolean** ```solidity function randomBoolean() public returns (ebool) { return FHE.randEbool(); } ``` ## **Bounded random numbers** To generate random numbers within a specific range, you can specify an **upper bound**. The specified upper bound must be a power of 2. The random number will be in the range `[0, upperBound - 1]`. ```solidity // Generate random numbers with upper bounds euint8 r8 = FHE.randEuint8(32); // Random number between 0-31 euint16 r16 = FHE.randEuint16(512); // Random number between 0-511 euint32 r32 = FHE.randEuint32(65536); // Random number between 0-65535 ``` ### **Example: Random number with upper bound** ```solidity function randomBoundedNumber(uint16 upperBound) public returns (euint16) { return FHE.randEuint16(upperBound); } ``` ## **Security Considerations** * **Cryptographic security**:\ The random numbers are generated using a cryptographically secure pseudo-random number generator (CSPRNG) and remain encrypted until explicitly decrypted. * **Gas consumption**:\ Each call to a random number generation function consumes gas. Developers should optimize the use of these functions, especially in gas-sensitive contracts. * **Privacy guarantee**:\ Random values are fully encrypted, ensuring they cannot be accessed or predicted by unauthorized parties. # Encrypted inputs This document introduces the concept of encrypted inputs in the FHEVM, explaining their role, structure, validation process, and how developers can integrate them into smart contracts and applications. Encrypted inputs are a core feature of FHEVM, enabling users to push encrypted data onto the blockchain while ensuring data confidentiality and integrity. ## What are encrypted inputs? Encrypted inputs are data values submitted by users in ciphertext form. These inputs allow sensitive information to remain confidential while still being processed by smart contracts. They are accompanied by **Zero-Knowledge Proofs of Knowledge (ZKPoKs)** to ensure the validity of the encrypted data without revealing the plaintext. ### Key characteristics of encrypted inputs: 1. **Confidentiality**: Data is encrypted using the public FHE key, ensuring that only authorized parties can decrypt or process the values. 2. **Validation via ZKPoKs**: Each encrypted input is accompanied by a proof verifying that the user knows the plaintext value of the ciphertext, preventing replay attacks or misuse. 3. **Efficient packing**: All inputs for a transaction are packed into a single ciphertext in a user-defined order, optimizing the size and generation of the zero-knowledge proof. ## Parameters in encrypted functions When a function in a smart contract is called, it may accept two types of parameters for encrypted inputs: 1. **`externalEbool`, `externalEaddress`,`externalEuintXX`**: Refers to the index of the encrypted parameter within the proof, representing a specific encrypted input handle. 2. **`bytes`**: Contains the ciphertext and the associated zero-knowledge proof used for validation. Here’s an example of a Solidity function accepting multiple encrypted parameters: ```solidity function exampleFunction( externalEbool param1, externalEuint64 param2, externalEuint8 param3, bytes calldata inputProof ) public { // Function logic here } ``` In this example, `param1`, `param2`, and `param3` are encrypted inputs for `ebool`, `euint64`, and `euint8` while `inputProof` contains the corresponding ZKPoK to validate their authenticity. ### Input Generation using Hardhat In the below example, we use Alice's address to create the encrypted inputs and submits the transaction. ```typescript import { fhevm } from "hardhat"; const input = fhevm.createEncryptedInput(contract.address, signers.alice.address); input.addBool(canTransfer); // at index 0 input.add64(transferAmount); // at index 1 input.add8(transferType); // at index 2 const encryptedInput = await input.encrypt(); const externalEboolParam1 = encryptedInput.handles[0]; const externalEuint64Param2 = encryptedInput.handles[1]; const externalEuint8Param3 = encryptedInput.handles[2]; const inputProof = encryptedInput.inputProof; tx = await myContract .connect(signers.alice) [ "exampleFunction(bytes32,bytes32,bytes32,bytes)" ](signers.bob.address, externalEboolParam1, externalEuint64Param2, externalEuint8Param3, inputProof); await tx.wait(); ``` ### Input Order Developers are free to design the function parameters in any order. There is no required correspondence between the order in which encrypted inputs are constructed in TypeScript and the order of arguments in the Solidity function. ## Validating encrypted inputs Smart contracts process encrypted inputs by verifying them against the associated zero-knowledge proof. This is done using the `FHE.asEuintXX`, `FHE.asEbool`, or `FHE.asEaddress` functions, which validate the input and convert it into the appropriate encrypted type. ### Example validation This example demonstrates a function that performs multiple encrypted operations, such as updating a user's encrypted balance and toggling an encrypted boolean flag: ```solidity function myExample(externalEuint64 encryptedAmount, externalEbool encryptedToggle, bytes calldata inputProof) public { // Validate and convert the encrypted inputs euint64 amount = FHE.fromExternal(encryptedAmount, inputProof); ebool toggleFlag = FHE.fromExternal(encryptedToggle, inputProof); // Update the user's encrypted balance balances[msg.sender] = FHE.add(balances[msg.sender], amount); // Toggle the user's encrypted flag userFlags[msg.sender] = FHE.not(toggleFlag); // FHE permissions and function logic here ... } // Function to retrieve a user's encrypted balance function getEncryptedBalance() public view returns (euint64) { return balances[msg.sender]; } // Function to retrieve a user's encrypted flag function getEncryptedFlag() public view returns (ebool) { return userFlags[msg.sender]; } ``` ### Example validation in the `ConfidentialERC20.sol` smart contract Here’s an example of a smart contract function that verifies an encrypted input before proceeding: ```solidity function transfer( address to, externalEuint64 encryptedAmount, bytes calldata inputProof ) public { // Verify the provided encrypted amount and convert it into an encrypted uint64 euint64 amount = FHE.fromExternal(encryptedAmount, inputProof); // Function logic here, such as transferring funds ... } ``` ### How validation works 1. **Input verification**:\ The `FHE.fromExternal` function ensures that the input is a valid ciphertext with a corresponding ZKPoK. 2. **Type conversion**:\ The function transforms `externalEbool`, `externalEaddress`, `externalEuintXX` into the appropriate encrypted type (`ebool`, `eaddress`, `euintXX`) for further operations within the contract. ## Best Practices * **Input packing**: Minimize the size and complexity of zero-knowledge proofs by packing all encrypted inputs into a single ciphertext. * **Frontend encryption**: Always encrypt inputs using the FHE public key on the client side to ensure data confidentiality. * **Proof management**: Ensure that the correct zero-knowledge proof is associated with each encrypted input to avoid validation errors. Encrypted inputs and their validation form the backbone of secure and private interactions in the FHEVM. By leveraging these tools, developers can create robust, privacy-preserving smart contracts without compromising functionality or scalability. # Access Control List This document describes the Access Control List (ACL) system in FHEVM, a core feature that governs access to encrypted data. The ACL ensures that only authorized accounts or contracts can interact with specific ciphertexts, preserving confidentiality while enabling composable smart contracts. This overview provides a high-level understanding of what the ACL is, why it's essential, and how it works. ## What is the ACL? The ACL is a permission management system designed to control who can access, compute on, or decrypt encrypted values in fhevm. By defining and enforcing these permissions, the ACL ensures that encrypted data remains secure while still being usable within authorized contexts. ## Why is the ACL important? Encrypted data in FHEVM is entirely confidential, meaning that without proper access control, even the contract holding the ciphertext cannot interact with it. The ACL enables: * **Granular permissions**: Define specific access rules for individual accounts or contracts. * **Secure computations**: Ensure that only authorized entities can manipulate or decrypt encrypted data. * **Gas efficiency**: Optimize permissions using transient access for temporary needs, reducing storage and gas costs. ## How does the ACL work? ### Types of access * **Permanent allowance**: * Configured using `FHE.allow(ciphertext, address)`. * Grants long-term access to the ciphertext for a specific address. * Stored in a dedicated contract for persistent storage. * **Transient allowance**: * Configured using `FHE.allowTransient(ciphertext, address)`. * Grants access to the ciphertext only for the duration of the current transaction. * Stored in transient storage, reducing gas costs. * Ideal for temporary operations like passing ciphertexts to external functions. * **Permanent public allowance**: * Configured using `FHE.makePubliclyDecryptable(ciphertext)`. * Grants long-term access to the ciphertext for any user. * Stored in a dedicated contract for persistent storage. **Syntactic sugar**: * `FHE.allowThis(ciphertext)` is shorthand for `FHE.allow(ciphertext, address(this))`. It authorizes the current contract to reuse a ciphertext handle in future transactions. ### Transient vs. permanent allowance | Allowance type | Purpose | Storage type | Use case | | -------------- | ---------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | **Transient** | Temporary access during a transaction. | [Transient storage](https://eips.ethereum.org/EIPS/eip-1153) (EIP-1153) | Calling external functions or computations with ciphertexts. Use when wanting to save on gas costs. | | **Permanent** | Long-term access across multiple transactions. | Dedicated contract storage | Persistent ciphertexts for contracts or users requiring ongoing access. | ## Granting and verifying access ### Granting access Developers can use functions like `allow`, `allowThis`, and `allowTransient` to grant permissions: * **`allow`**: Grants permanent access to an address. * **`allowThis`**: Grants the current contract access to manipulate the ciphertext. * **`allowTransient`**: Grants temporary access to an address for the current transaction. * **`makePubliclyDecryptable`**: Grants permanent, global permission for any entity to decrypt the cleartext value associated with the given ciphertext (handle) off-chain. ### Verifying access To check if an entity has permission to access a ciphertext, use functions like `isAllowed` or `isSenderAllowed`: * **`isAllowed`**: Verifies if a specific address has permission. * **`isSenderAllowed`**: Simplifies checks for the current transaction sender. * **`isPubliclyDecryptable`**: Verifies whether any entity is permitted to retrieve the ciphertext's cleartext value off-chain. * **`checkSignatures`**: Verifies the authenticity of a cleartext value by checking cryptographic signatures. This ensures that the value submitted back to the chain originated from a legitimate public decryption operation on the associated ciphertext handle. * **`isAccountDenied`**: Checks whether an account is on the deny list. Denied accounts are blocked from `allow*` calls inside the ACL contract, so they cannot grant or receive new permissions on encrypted values. ### User decryption delegation The ACL supports delegating user decryption rights from one account to another (for example, a backend service or relayer). The **delegator** is whichever account calls into the ACL — an EOA when calling `IACL.delegat
프로젝트로 돌아가기