Zama 백서

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

ert if a condition fails, making it challenging to notify users of issues like insufficient funds or invalid inputs. 2. **Limited feedback**: Encrypted computations lack direct mechanisms for exposing failure reasons while maintaining confidentiality. ## **Recommended approach: Error logging with a handler** To address these challenges, implement an **error handler** that records the most recent error for each user. This allows dApps or frontends to query error states and provide appropriate feedback to users. ### **Example implementation** The following contract snippet demonstrates how to implement and use an error handler: ```solidity struct LastError { euint8 error; // Encrypted error code uint timestamp; // Timestamp of the error } // Define error codes euint8 internal NO_ERROR; euint8 internal NOT_ENOUGH_FUNDS; constructor() { NO_ERROR = FHE.asEuint8(0); // Code 0: No error NOT_ENOUGH_FUNDS = FHE.asEuint8(1); // Code 1: Insufficient funds } // Store the last error for each address mapping(address => LastError) private _lastErrors; // Event to notify about an error state change event ErrorChanged(address indexed user); /** * @dev Set the last error for a specific address. * @param error Encrypted error code. * @param addr Address of the user. */ function setLastError(euint8 error, address addr) private { _lastErrors[addr] = LastError(error, block.timestamp); emit ErrorChanged(addr); } /** * @dev Internal transfer function with error handling. * @param from Sender's address. * @param to Recipient's address. * @param amount Encrypted transfer amount. */ function _transfer(address from, address to, euint32 amount) internal { // Check if the sender has enough balance to transfer ebool canTransfer = FHE.le(amount, balances[from]); // Log the error state: NO_ERROR or NOT_ENOUGH_FUNDS setLastError(FHE.select(canTransfer, NO_ERROR, NOT_ENOUGH_FUNDS), msg.sender); // Perform the transfer operation conditionally balances[to] = FHE.add(balances[to], FHE.select(canTransfer, amount, FHE.asEuint32(0))); FHE.allowThis(balances[to]); FHE.allow(balances[to], to); balances[from] = FHE.sub(balances[from], FHE.select(canTransfer, amount, FHE.asEuint32(0))); FHE.allowThis(balances[from]); FHE.allow(balances[from], from); } ``` ## **How It Works** 1. **Define error codes**: * `NO_ERROR`: Indicates a successful operation. * `NOT_ENOUGH_FUNDS`: Indicates insufficient balance for a transfer. 2. **Record errors**: * Use the `setLastError` function to log the latest error for a specific address along with the current timestamp. * Emit the `ErrorChanged` event to notify external systems (e.g., dApps) about the error state change. 3. **Conditional updates**: * Use the `FHE.select` function to update balances and log errors based on the transfer condition (`canTransfer`). 4. **Frontend integration**: * The dApp can query `_lastErrors` for a user’s most recent error and display appropriate feedback, such as "Insufficient funds" or "Transaction successful." ## **Example error query** The frontend or another contract can query the `_lastErrors` mapping to retrieve error details: ```solidity /** * @dev Get the last error for a specific address. * @param user Address of the user. * @return error Encrypted error code. * @return timestamp Timestamp of the error. */ function getLastError(address user) public view returns (euint8 error, uint timestamp) { LastError memory lastError = _lastErrors[user]; return (lastError.error, lastError.timestamp); } ``` ## **Benefits of this approach** 1. **User feedback**: * Provides actionable error messages without compromising the confidentiality of encrypted computations. 2. **Scalable error tracking**: * Logs errors per user, making it easy to identify and debug specific issues. 3. **Event-driven notifications**: * Enables frontends to react to errors in real time via the `ErrorChanged` event. By implementing error handlers as demonstrated, developers can ensure a seamless user experience while maintaining the privacy and integrity of encrypted data operations. # Dealing with branches and conditions This document explains how to handle branches, loops or conditions when working with Fully Homomorphic Encryption (FHE), specifically when the condition / index is encrypted. ## Breaking a loop ❌ In FHE, it is not possible to break a loop based on an encrypted condition. For example, this would not work: ```solidity euint8 maxValue = FHE.asEuint(6); // Could be a value between 0 and 10 euint8 x = FHE.asEuint(0); // some code while(FHE.lt(x, maxValue)){ x = FHE.add(x, 2); } ``` If your code logic requires looping on an encrypted boolean condition, we highly suggest to try to replace it by a finite loop with an appropriate constant maximum number of steps and use `FHE.select` inside the loop. ## Suggested approach ✅ For example, the previous code could maybe be replaced by the following snippet: ```solidity euint8 maxValue = FHE.asEuint(6); // Could be a value between 0 and 10 euint8 x; // some code for (uint32 i = 0; i < 10; i++) { euint8 toAdd = FHE.select(FHE.lt(x, maxValue), 2, 0); x = FHE.add(x, toAdd); } ``` In this snippet, we perform 10 iterations, adding 4 to `x` in each iteration as long as the iteration count is less than `maxValue`. If the iteration count exceeds `maxValue`, we add 0 instead for the remaining iterations because we can't break the loop. ## Best practices ### Obfuscate branching The previous paragraph emphasized that branch logic should rely as much as possible on `FHE.select` instead of decryptions. It hides effectively which branch has been executed. However, this is sometimes not enough. Enhancing the privacy of smart contracts often requires revisiting your application's logic. For example, if implementing a simple AMM for two encrypted ERC20 tokens based on a linear constant function, it is recommended to not only hide the amounts being swapped, but also the token which is swapped in a pair. ✅ Here is a very simplified example implementation, we suppose here that the rate between tokenA and tokenB is constant and equals to 1: ```solidity // typically either encryptedAmountAIn or encryptedAmountBIn is an encrypted null value // ideally, the user already owns some amounts of both tokens and has pre-approved the AMM on both tokens function swapTokensForTokens( externalEuint32 encryptedAmountAIn, externalEuint32 encryptedAmountBIn, bytes calldata inputProof ) external { euint32 encryptedAmountA = FHE.asEuint32(encryptedAmountAIn, inputProof); // even if amount is null, do a transfer to obfuscate trade direction euint32 encryptedAmountB = FHE.asEuint32(encryptedAmountBIn, inputProof); // even if amount is null, do a transfer to obfuscate trade direction // send tokens from user to AMM contract FHE.allowTransient(encryptedAmountA, tokenA); IConfidentialERC20(tokenA).transferFrom(msg.sender, address(this), encryptedAmountA); FHE.allowTransient(encryptedAmountB, tokenB); IConfidentialERC20(tokenB).transferFrom(msg.sender, address(this), encryptedAmountB); // send tokens from AMM contract to user // Price of tokenA in tokenB is constant and equal to 1, so we just swap the encrypted amounts here FHE.allowTransient(encryptedAmountB, tokenA); IConfidentialERC20(tokenA).transfer(msg.sender, encryptedAmountB); FHE.allowTransient(encryptedAmountA, tokenB); IConfidentialERC20(tokenB).transferFrom(msg.sender, address(this), encryptedAmountA); } ``` Notice that to preserve confidentiality, we had to make two inputs transfers on both tokens from the user to the AMM contract, and similarly two output transfers from the AMM to the user, even if technically most of the times it will make sense that one of the user inputs `encryptedAmountAIn` or `encryptedAmountBIn` is actually an encrypted zero. This is different from a classical non-confidential AMM with regular ERC20 tokens: in this case, the user would need to just do one input transfer to the AMM on the token being sold, and receive only one output transfer from the AMM on the token being bought. ### Avoid using encrypted indexes Using encrypted indexes to pick an element from an array without revealing it is not very efficient, because you would still need to loop on all the indexes to preserve confidentiality. However, there are plans to make this kind of operation much more efficient in the future, by adding specialized operators for arrays. For instance, imagine you have an encrypted array called `encArray` and you want to update an encrypted value `x` to match an item from this list, `encArray[i]`, *without* disclosing which item you're choosing. ❌ You must loop over all the indexes and check equality homomorphically, however this pattern is very expensive in gas and should be avoided whenever possible. ```solidity euint32 x; euint32[] encArray; function setXwithEncryptedIndex(externalEuint32 encryptedIndex, bytes calldata inputProof) public { euint32 index = FHE.asEuint32(encryptedIndex, inputProof); for (uint32 i = 0; i < encArray.length; i++) { ebool isEqual = FHE.eq(index, i); x = FHE.select(isEqual, encArray[i], x); } FHE.allowThis(x); } ``` # Operations on encrypted types This document outlines the operations supported on encrypted types in the `FHE` library, enabling arithmetic, bitwise, comparison, and more on Fully Homomorphic Encryption (FHE) ciphertexts. ## Arithmetic operations The following arithmetic operations are supported for encrypted integers (`euintX`): | Name | Function name | Symbol | Type | | ---------------------------- | ------------- | ------ | ------ | | Add | `FHE.add` | `+` | Binary | | Subtract | `FHE.sub` | `-` | Binary | | Multiply | `FHE.mul` | `*` | Binary | | Divide (plaintext divisor) | `FHE.div` | | Binary | | Reminder (plaintext divisor) | `FHE.rem` | | Binary | | Negation | `FHE.neg` | `-` | Unary | | Min | `FHE.min` | | Binary | | Max | `FHE.max` | | Binary | {% hint style="info" %} Division (FHE.div) and remainder (FHE.rem) operations are currently supported only with plaintext divisors. {% endhint %} ## Bitwise operations The FHE library also supports bitwise operations, including shifts and rotations: | Name | Function name | Symbol | Type | | ------------ | ------------- | ------ | ------ | | Bitwise AND | `FHE.and` | `&` | Binary | | Bitwise OR | `FHE.or` | `\|` | Binary | | Bitwise XOR | `FHE.xor` | `^` | Binary | | Bitwise NOT | `FHE.not` | `~` | Unary | | Shift Right | `FHE.shr` | | Binary | | Shift Left | `FHE.shl` | | Binary | | Rotate Right | `FHE.rotr` | | Binary | | Rotate Left | `FHE.rotl` | | Binary | The shift operators `FHE.shr` and `FHE.shl` can take any encrypted type `euintX` as a first operand and either a `uint8`or a `euint8` as a second operand, however the second operand will always be computed modulo the number of bits of the first operand. For example, `FHE.shr(euint64 x, 70)` is equivalent to `FHE.shr(euint64 x, 6)` because `70 % 64 = 6`. This differs from the classical shift operators in Solidity, where there is no intermediate modulo operation, so for instance any `uint64` shifted right via `>>` would give a null result. ## Comparison operations Encrypted integers can be compared using the following functions: | Name | Function name | Symbol | Type | | --------------------- | ------------- | ------ | ------ | | Equal | `FHE.eq` | | Binary | | Not equal | `FHE.ne` | | Binary | | Greater than or equal | `FHE.ge` | | Binary | | Greater than | `FHE.gt` | | Binary | | Less than or equal | `FHE.le` | | Binary | | Less than | `FHE.lt` | | Binary | ## Ternary operation The `FHE.select` function is a ternary operation that selects one of two encrypted values based on an encrypted condition: | Name | Function name | Symbol | Type | | ------ | ------------- | ------ | ------- | | Select | `FHE.select` | | Ternary | ## Random operations You can generate cryptographically secure random numbers fully on-chain: <table data-header-hidden><thead><tr><th></th><th width="206"></th><th></th><th></th></tr></thead><tbody><tr><td><strong>Name</strong></td><td><strong>Function Name</strong></td><td><strong>Symbol</strong></td><td><strong>Type</strong></td></tr><tr><td>Random Unsigned Integer</td><td><code>FHE.randEuintX()</code></td><td></td><td>Random</td></tr></tbody></table> For more details, refer to the [Random Encrypted Numbers](/protocol/solidity-guides/v0.10/docs/solidity-guides/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.asEuint32(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.asEuint32(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.asEboolXX` | {% 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.r
프로젝트로 돌아가기