bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 65쪽
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.
## 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.12/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/v0.12/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
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.12/smart-contract/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, byte프로젝트로 돌아가기