Zama 백서

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

h-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. ## 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/v0.10/docs/solidity-guides/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/v0.10/docs/solidity-guides/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 Consider an **Confidential ERC20 token**. An attacker controlling two accounts, **Account A** and **Account B**, with 100 tokens in Account A, could exploit the system as follows: 1. The attacker attempts to send the target user's encrypted balance from **Account A** to **Account B**. 2. Observing the transaction outcome, the attacker gains information: * **If successful**: The target's balance is equal to or less than 100 tokens. * **If failed**: The target's balance exceeds 100 tokens. This type of attack allows the attacker to infer private balances without explicit access. To prevent this, always use the `FHE.isSenderAllowed()` function to verify that the sender has legitimate access to the encrypted amount being transferred. *** #### 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 decrypt 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/v0.10/docs/solidity-guides/acl). # 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 isAlreadyBought = 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(encryptedPrivateKey, 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 isAlreadyBought = 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 %} # decryption # Debugging # oracle ## Public Decryption This section explains how to handle public decryption in FHEVM. Public decryption allows plaintext data to be accessed when required for contract logic or user presentation, ensuring confidentiality is maintained throughout the process. Public decryption is essential in two primary cases: 1. **Smart contract logic**: A contract requires plaintext values for computations or decision-making. 2. **User interaction**: Plaintext data needs to be revealed to all users, such as revealing the decision of the vote. ### Overview Public decryption of a confidential on-chain result is designed as an asynchronous three-steps process that splits the work between the blockchain (on-chain) and off-chain execution environments. **Step 1: On-Chain Setup - Enabling Permanent Public Access** This step is executed by the smart contract using the FHE Solidity library to signal that a specific confidential result is ready to be revealed. * **FHE Solidity Library Function:** `FHE.makePubliclyDecryptable` * **Action:** The contract sets the ciphertext handle's status as publicly decryptable, **globally and permanently** authorizing any entity to request its off-chain cleartext value. * **Result:** The ciphertext is now accessible to any entity, which can request its decryption from the Zama off-chain Relayer. **Step 2: Off-chain Decryption - Decryption and Proof Generation** This step can be executed by any off-chain client using the Relayer SDK. * **Relayer SDK Function:** `FhevmInstance.publicDecrypt` * **Action:** The off-chain client submits the ciphertext handle to the Zama Relayer's Key Management System (KMS). * **Result:** The Zama Relayer returns three items: 1. The cleartext (the decrypted value). 2. The ABI-encoding of that cleartext. 3. A Decryption Proof (a byte array of signatures and metadata) that serves as a cryptographic guarantee that the cleartext is the authentic, unmodified result of the decryption performed by the KMS. **Step 3: On-Chain Verification - Submit and Guarantee Authenticity** This final step is executed on-chain by the contrat using the FHE Solidity library with the proof generated off-chain to ensure the cleartext submitted to the contract is trustworthy. * **FHE Solidity Library Function:** `FHE.checkSignatures` * **Action:** The caller submits the cleartext and decryption proof back to a contract function. The contract calls `FHE.checkSignatures`, which reverts the transaction if the proof is invalid or does not match the cleartext/ciphertext pair. * **Result:** The receiving contract gains a cryptographic guarantee that the submitted cleartext is the authentic decrypted value of the original ciphertext. The contract can then securely execute its business logic (e.g., reveal a vote, transfer funds, update state). ### Tutorial This tutorial provides a deep dive into the three-step asynchronous public decryption process required to finalize a confidential on-chain computation by publicly revealing its result. The Solidity contract provided below, `FooBarContract`, is used to model this entire workflow. The contract's main function `runFooBarConfidentialLogic` simulates the execution of a complex confidential computation (e.g., calculating a winner or a final price) that results in 2 encrypted final values (ciphertexts) `_encryptedFoo` and `_encryptedBar`. Then, in order to finalize the workflow, the `FooBarContract` needs the decrypted clear values of both `_encryptedFoo` and `_encryptedBar` to decide whether to trigger some finalization logic (e.g. reveal a vote, transfer funds). The `FooBarContract`'s function `_runFooBarClearBusinessLogicFinalization` simulates this step. Since the FHEVM prevents direct on-chain decryption, the process must shift to an off-chain decryption phase, which presents a challenge: ***How can the\*\*\*\* ****`FooBarContract`**** ****trust that the cleartext submitted back to the chain is the authentic, unmodified result of the decryption of both**** ****`_encryptedFoo`**** ****and**** ****`_encryptedBar`****?*** This is where the off-chain `publicDecrypt` function and the on-chain `checkSignatures` function come into play. #### The Solidity Contract ```solidity pragma solidity ^0.8.24; import "@fhevm/solidity/lib/FHE.sol"; import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol"; contract FooBarContract is ZamaEthereumConfig { ebool _encryptedFoo; euint8 _encryptedBar; bool _clearFoo; uint8 _clearBar; bool _isFinalized; event ClearFooBarRequested(ebool encryptedFoo, euint8 encryptedBar); constructor() {} function _isFooBarConfidentialLogicExecuted() private returns (bool) { return FHE.isInitialized(_encryptedFoo) && FHE.isInitialized(_encryptedBar); } modifier whenConfidentialLogicExecuted() { require(_isFooBarConfidentialLogicExecuted(), "foo confidential logic not yet executed!") _; } function runFooBarConfidentialLogic() external { require(!_isFooBarConfidentialLogicExecuted(), "foobar confidential logic already executed!") _encryptedFoo = FHE.randEbool(); _encryptedBar = FHE.randEuint8(); } function getEncryptedFoo() public whenConfidentialLogicExecuted returns (ebool) { return _encryptedFoo; } function getEncryptedBar() public whenConfidentialLogicExecuted returns (euint8) { return _encryptedBar; } function requestClearFooBar() external whenConfidentialLogicExecuted { FHE.makePubliclyDecryptable(_encryptedFoo); FHE.makePubliclyDecryptable(_encryptedBar); emit ClearFooBarRequested(_encryptedFoo, _encryptedBar); } function finalizeClearFooBar(bool clearFoo, uint8 clearBar, bytes memory publicDecryptionProof) external whenConfidentialLogicExecuted { require(!_isFinalized, "foo is already revealed"); // ⚠️
프로젝트로 돌아가기