Zama 백서

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

eForUserDecryption` directly, or `address(this)` when a contract uses the `FHE.delegateUserDecryption` helper. The two patterns are not interchangeable. * **`delegateUserDecryption`**: Grants a delegate the right to user-decrypt on behalf of the caller contract for a specific `contractAddress`, with an expiration date. * **`delegateUserDecryptionWithoutExpiration`**: Same as above, but without an expiration date. * **`revokeUserDecryptionDelegation`**: Revokes a previously granted delegation. * **`isUserDecryptable`**: Checks if a handle can be decrypted by a user in the context of a specific contract. For the EOA-side flow, the full constraints, and worked examples, see [User decryption delegation](/protocol/solidity-guides/smart-contract/acl/delegation). For the API reference, see [FHEVM API reference](/protocol/solidity-guides/smart-contract/functions#user-decryption-delegation). ## Practical uses of the ACL * **Confidential parameters**: Pass encrypted values securely between contracts, ensuring only authorized entities can access them. * **Secure state management**: Store encrypted state variables while controlling who can modify or read them. * **Privacy-preserving computations**: Enable computations on encrypted data with confidence that permissions are enforced. * **Publicly Verifiable Result Reveal**: Enable the public reveal of a confidential operation's final result. For example, enabling the public to verify the final price in a sealed-bid confidential auction. *** For a detailed explanation of the ACL's functionality, including code examples and advanced configurations, see [ACL examples](/protocol/solidity-guides/smart-contract/acl/acl_examples). # ACL examples This page provides detailed instructions and examples on how to use and implement the ACL (Access Control List) in FHEVM. For an overview of ACL concepts and their importance, refer to the [access control list (ACL) overview](/protocol/solidity-guides/smart-contract/acl). ## Controlling access: permanent and transient allowances The ACL system allows you to define two types of permissions for accessing ciphertexts: ### Permanent allowance * **Function**: `FHE.allow(ciphertext, address)` * **Purpose**: Grants persistent access to a ciphertext for a specific address. * **Storage**: Permissions are saved in a dedicated ACL contract, making them available across transactions. #### Alternative Solidity syntax You can also use method-chaining syntax for granting allowances since FHE is a Solidity library. ```solidity using FHE for *; ciphertext.allow(address1).allow(address2); ``` This is equivalent to calling `FHE.allow(ciphertext, address1)` followed by `FHE.allow(ciphertext, address2)`. ### Transient allowance * **Function**: `FHE.allowTransient(ciphertext, address)` * **Purpose**: Grants temporary access for the duration of a single transaction. * **Storage**: Permissions are stored in transient storage to save gas costs. * **Use Case**: Ideal for passing encrypted values between functions or contracts during a transaction. #### Alternative Solidity syntax Method chaining is also available for transient allowances since FHE is a Solidity library. ```solidity using FHE for *; ciphertext.allowTransient(address1).allowTransient(address2); ``` ### Syntactic sugar * **Function**: `FHE.allowThis(ciphertext)` * **Equivalent To**: `FHE.allow(ciphertext, address(this))` * **Purpose**: Simplifies granting permanent access to the current contract for managing ciphertexts. #### Alternative Solidity syntax You can also use method-chaining syntax for allowThis since FHE is a Solidity library. ```solidity using FHE for *; ciphertext.allowThis(); ``` #### Make publicly decryptable To make a ciphertext publicly decryptable, you can use the `FHE.makePubliclyDecryptable(ciphertext)` function. This grants decryption rights to anyone, which is useful for scenarios where the encrypted value should be accessible by all. ```solidity // Grant public decryption right to a ciphertext FHE.makePubliclyDecryptable(ciphertext); // Or using method syntax: ciphertext.makePubliclyDecryptable(); ``` * **Function**: `FHE.makePubliclyDecryptable(ciphertext)` * **Purpose**: Makes the ciphertext decryptable by anyone. * **Use Case**: When you want to publish encrypted results or data. > You can combine multiple allowance methods (such as `.allow()`, `.allowThis()`, `.allowTransient()`) directly on ciphertext objects to grant access to several addresses or contracts in a single, fluent statement. > > **Example** > > ```solidity > // Grant transient access to one address and permanent access to another address > ciphertext.allowTransient(address1).allow(address2); > > // Grant permanent access to the current contract and another address > ciphertext.allowThis().allow(address1); > ``` ## Best practices ### Verifying sender access When processing ciphertexts as input, it’s essential to validate that the sender is authorized to interact with the provided encrypted data. Failing to perform this verification can expose the system to inference attacks where malicious actors attempt to deduce private information. #### Example scenario: Confidential ERC20 attack Suppose a confidential ERC20 token has a `transfer(address to, euint64 encryptedAmount)` function that does **not** call `FHE.isSenderAllowed(encryptedAmount)`. The contract trusts whatever encrypted amount the caller passes in. An attacker controls two accounts they own — **Account A** (funded with 100 tokens) and **Account B** — and wants to learn the balance of a victim **Account V** without ever decrypting it. The attack: 1. The victim's encrypted balance handle is publicly readable on-chain (it lives in the contract's `balances[V]` storage). The attacker reads that handle. 2. The attacker calls `transfer(B, balances[V])` from Account A — passing the **victim's** balance handle as the `encryptedAmount`. Without `isSenderAllowed`, the contract has no way to know the attacker did not produce that handle. 3. Inside `transfer`, the contract executes `canTransfer = FHE.le(encryptedAmount, balances[A])` and conditionally moves the amount via `FHE.select`. Whether the transfer ends up actually moving tokens depends on whether `balance[V] <= 100`. 4. The attacker reads `balances[B]` after the transaction. The new handle either reflects an increase (transfer happened ⇒ `balance[V] <= 100`) or stays the same (transfer skipped ⇒ `balance[V] > 100`). Each successful or failed transfer leaks one bit about the victim's balance. By repeating the attack with progressively different sender balances, the attacker can binary-search the victim's exact balance — all without ever obtaining a decryption. The fix is one line: require `FHE.isSenderAllowed(encryptedAmount)` so the contract only accepts handles the sender is genuinely authorized to use. *** #### Example: secure verification ```solidity function transfer(address to, euint64 encryptedAmount) public { // Ensure the sender is authorized to access the encrypted amount require(FHE.isSenderAllowed(encryptedAmount), "Unauthorized access to encrypted amount."); // Proceed with further logic ... } ``` By enforcing this check, you can safeguard against inference attacks and ensure that encrypted values are only manipulated by authorized entities. ## ACL for user decryption If a ciphertext can be decrypted by a user, explicit access must be granted to them. Additionally, the user decryption mechanism requires the signature of a public key associated with the contract address. Therefore, a value that needs to be decrypted must be explicitly authorized for both the user and the contract. Due to the user decryption mechanism, a user signs a public key associated with a specific contract; therefore, the ciphertext also needs to be allowed for the contract. ### Example: Secure Transfer in ConfidentialERC20 ```solidity function transfer(address to, euint64 encryptedAmount) public { require(FHE.isSenderAllowed(encryptedAmount), "The caller is not authorized to access this encrypted amount."); euint64 amount = FHE.asEuint64(encryptedAmount); ebool canTransfer = FHE.le(amount, balances[msg.sender]); euint64 newBalanceTo = FHE.add(balances[to], FHE.select(canTransfer, amount, FHE.asEuint64(0))); balances[to] = newBalanceTo; // Allow this new balance for both the contract and the owner. FHE.allowThis(newBalanceTo); FHE.allow(newBalanceTo, to); euint64 newBalanceFrom = FHE.sub(balances[from], FHE.select(canTransfer, amount, FHE.asEuint64(0))); balances[from] = newBalanceFrom; // Allow this new balance for both the contract and the owner. FHE.allowThis(newBalanceFrom); FHE.allow(newBalanceFrom, from); } ``` By understanding how to grant and verify permissions, you can effectively manage access to encrypted data in your FHEVM smart contracts. For additional context, see the [ACL overview](/protocol/solidity-guides/smart-contract/acl). # User decryption delegation Delegation lets one account (the **delegator**) authorize another account (the **delegate**) to perform user decryption on its behalf, in the context of a specific contract. The ACL stores user decryption permissions as `(user, contractAddress)` pairs; delegation transfers the rights of `(delegator, contractAddress)` to `(delegate, contractAddress)`. ## Who is the delegator? It depends on which API you call: | Caller | API | Delegator (`msg.sender` to ACL) | | ---------------------------------- | ------------------------------------------------------------- | ------------------------------- | | **EOA** (Externally Owned Account) | `IACL.delegateForUserDecryption` directly on the ACL contract | the EOA itself | | **Smart contract** | `FHE.delegateUserDecryption` from inside a contract function | `address(this)` | `FHE.delegateUserDecryption` cannot be used by an EOA to delegate its own rights — the EOA must call the ACL directly. ## Constraints The ACL enforces three invariants when registering a delegation: * `msg.sender != contractAddress` * `msg.sender != delegate` * `delegate != contractAddress` Plus a one-delegate-or-revoke-per-block rule per `(delegator, delegate, contractAddress)` tuple. ## Pattern 1 — EOA delegates to a backend service The user calls the ACL contract directly to delegate their own rights: ```solidity import { IACL } from "@fhevm/solidity/lib/Impl.sol"; IACL(aclAddress).delegateForUserDecryption(relayer, vault, expirationDate); ``` After this, the relayer can user-decrypt any handle that has the `(EOA, vault)` ACL pair. ## Pattern 2 — Contract delegates its own rights A contract delegates user-decryption rights it has been granted. `contractAddress` must be a **different** contract whose handles this contract has been allowed to access. ```solidity import { FHE } from "@fhevm/solidity/lib/FHE.sol"; import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol"; contract Aggregator is ZamaEthereumConfig { address public immutable vault; constructor(address vault_) { vault = vault_; } function authorizeRelayer(address relayer, uint64 expirationDate) external { FHE.delegateUserDecryption(relayer, vault, expirationDate); } function revokeRelayer(address relayer) external { FHE.revokeUserDecryptionDelegation(relayer, vault); } } ``` {% hint style="warning" %} **Common mistake:** calling `FHE.delegateUserDecryption(relayer, address(this), expiration)` from inside a contract, hoping to delegate the caller user's rights. This always reverts because `msg.sender == contractAddress` violates one of the constraints listed above. Use Pattern 1 instead — the user must call the ACL directly. {% endhint %} ## API summary ```solidity // Granting (caller-contract side) FHE.delegateUserDecryption(delegate, contractAddress, expirationDate); FHE.delegateUserDecryptionWithoutExpiration(delegate, contractAddress); FHE.delegateUserDecryptions(delegate, contractAddresses, expirationDate); // batch FHE.delegateUserDecryptionsWithoutExpiration(delegate, contractAddresses); // batch // Revoking FHE.revokeUserDecryptionDelegation(delegate, contractAddress); FHE.revokeUserDecryptionDelegations(delegate, contractAddresses); // batch // Querying FHE.isDelegatedForUserDecryption(delegator, delegate, contractAddress, handle); // active for handle? FHE.getDelegatedUserDecryptionExpirationDate(delegator, delegate, contractAddress); // 0 = none, max = permanent FHE.isUserDecryptable(handle, user, contractAddress); // raw ACL check, ignores delegation ``` # Reorgs handling This page provides detailed instructions on how to handle reorg risks on Ethereum when using FHEVM. Since ACL events are propagated from the FHEVM host chain to the [Gateway](https://docs.zama.ai/protocol/protocol/overview/gateway) immediately after being included in a block, dApp developers must take special care when encrypted information is critically important. For example, if an encrypted handle conceals the private key of a Bitcoin wallet holding significant funds, we need to ensure that this information cannot inadvertently leak to the wrong person due to a reorg on the FHEVM host chain. Therefore, it's the responsibility of dApp developers to prevent such scenarios by implementing a two-step ACL authorization process with a timelock between the request and the ACL call. ## Simple example: Handling reorg risk on Ethereum On Ethereum, a reorg can be up to 95 slots deep in the worst case, so waiting for more than 95 blocks should ensure that a previously sent transaction has been finalized—unless more than 1/3 of the nodes are malicious and willing to lose their stake, which is highly improbable. ❌ **Instead of writing this contract:** ```solidity contract PrivateKeySale { euint256 privateKey; bool isBought = false; constructor(externalEuint256 _privateKey, bytes inputProof) { privateKey = FHE.fromExternal(_privateKey, inputProof); FHE.allowThis(privateKey); } function buyPrivateKey() external payable { require(msg.value == 1 ether, "Must pay 1 ETH"); require(!isBought, "Private key already bought"); isBought = true; FHE.allow(privateKey, msg.sender); } } ``` Since the \`privateKey\`\` encrypted variable contains critical information, we don't want to mistakenly leak it for free if a reorg occurs. This could happen in the previous example because we immediately grant authorization to the buyer in the same transaction that processes the sale. ✅ **We recommend writing something like this instead:** ```solidity contract PrivateKeySale { euint256 privateKey; bool isBought = false; uint256 blockWhenBought = 0; address buyer; constructor(externalEuint256 _privateKey, bytes inputProof) { privateKey = FHE.fromExternal(_privateKey, inputProof); FHE.allowThis(privateKey); } function buyPrivateKey() external payable { require(msg.value == 1 ether, "Must pay 1 ETH"); require(!isBought, "Private key already bought"); isBought = true; blockWhenBought = block.number; buyer = msg.sender; } function requestACL() external { require(isBought, "Private key has not been bought yet"); require(block.number > blockWhenBought + 95, "Too early to request ACL, risk of reorg"); FHE.allow(privateKey, buyer); } } ``` This approach ensures that at least 96 blocks have elapsed between the transaction that purchases the private key and the transaction that authorizes the buyer to decrypt it. {% hint style="info" %} This type of contract worsens the user experience by adding a timelock before users can decrypt data, so it should be used sparingly: only when leaked information could be critically important and high-value. {% endhint %} # Logics This section covers how to implement conditional logic and control flow when working with encrypted values in FHEVM. Since encrypted values cannot be directly evaluated at runtime, standard Solidity control flow (`if`, `else`, `for` with encrypted conditions) does not work with FHE ciphertexts. Instead, FHEVM provides specialized functions and patterns to handle these cases securely. ## Topics * [**Branching**](/protocol/solidity-guides/smart-contract/logics/conditions) — How to use `FHE.select` for conditional logic on encrypted values, and how to transition from encrypted conditions to non-encrypted business logic via public decryption. * [**Dealing with branches and conditions**](/protocol/solidity-guides/smart-contract/logics/loop) — Patterns for handling loops and indexed access when the condition or index is encrypted. * [**Error handling**](/protocol/solidity-guides/smart-contract/logics/error_handling) — How to handle errors in FHE computations, where standard `require` and `revert` cannot operate on encrypted values. # Branching This document explains how to implement conditional logic (if/else branching) when working with encrypted values in FHEVM. Unlike typical Solidity programming, working with Fully Homomorphic Encryption (FHE) requires specialized methods to handle conditions on encrypted data. This document covers encrypted branching and how to move from an encrypted condition to a non-encrypted business logic in your smart contract. ## What is confidential branching? In FHEVM, when you perform [comparison operations](/protocol/solidity-guides/smart-contract/operations#comparison-operations), the result is an encrypted boolean (`ebool`). Since encrypted booleans do not support standard boolean operations like `if` statements or logical operators, conditional logic must be implemented using specialized methods. To facilitate conditional assignments, FHEVM provides the `FHE.select` function, which acts as a ternary operator for encrypted values. ## **Using `FHE.select` for conditional logic** The `FHE.select` function enables branching logic by selecting one of two encrypted values based on an encrypted condition (`ebool`). It works as follows: ```solidity FHE.select(condition, valueIfTrue, valueIfFalse); ``` * **`condition`**: An encrypted boolean (`ebool`) resulting from a comparison. * **`valueIfTrue`**: The encrypted value to return if the condition is true. * **`valueIfFalse`**: The encrypted value to return if the condition is false. ## **Example: Auction Bidding Logic** Here's an example of using conditional logic to update the highest winning number in a guessing game: ```solidity function bid(externalEuint64 encryptedValue, bytes calldata inputProof) external onlyBeforeEnd { // Convert the encrypted input to an encrypted 64-bit integer euint64 bid = FHE.fromExternal(encryptedValue, inputProof); // Compare the current highest bid with the new bid ebool isAbove = FHE.lt(highestBid, bid); // Update the highest bid if the new bid is greater highestBid = FHE.select(isAbove, bid, highestBid); // Allow the contract to use the updated highest bid ciphertext FHE.allowThis(highestBid); } ``` {% hint style="info" %} This is a simplified example to demonstrate the functionality. {% endhint %} ### How Does It Work? * **Comparison**: * The `FHE.lt` function compares `highestBid` and `bid`, returning an `ebool` (`isAbove`) that indicates whether the new bid is higher. * **Selection**: * The `FHE.select` function updates `highestBid` to either the new bid or the previous highest bid, based on the encrypted condition `isAbove`. * **Permission Handling**: * After updating `highestBid`, the contract reauthorizes itself to manipulate the updated ciphertext using `FHE.allowThis`. ## Key Considerations * **Value change behavior:** Each time `FHE.select` assigns a value, a new ciphertext is created, even if the underlying plaintext value remains unchanged. This behavior is inherent to FHE and ensures data confidentiality, but developers should account for it when designing their smart contracts. * **Gas consumption:** Using `FHE.select` and other encrypted operations incurs additional gas costs compared to traditional Solidity logic. Optimize your code to minimize unnecessary operations. * *
프로젝트로 돌아가기