Zama 백서

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

FHEVM v0.9 versions**. 2. **Update Solidity Config:** Replace the removed `SepoliaConfig` with the unified **`ZamaEthereumConfig`**. 3. **Update Solidity Code:** Remove all calls to the discontinued Oracle-based FHE library functions. 4. **Re-compile & Re-deploy:** Due to new FHEVM addresses, all affected contracts must be re-compiled and re-deployed on Sepolia. 5. **Rewrite Public Decryption Logic:** Eliminate reliance on the discontinued Zama Oracle and implement the **self-relaying** workflow using the `@zama-fhe/relayer-sdk` and `FHE.verifySignatures()`. Follow these steps for a smooth transition to FHEVM v0.9: ### Step 1: Update Core Dependencies Ensure your project uses the latest versions of the FHEVM development tools. | Dependency | Minimum Required Version | Notes | | ----------------------- | ------------------------ | --------------------------------------------------------------------- | | `@fhevm/solidity` | `v0.9.1` | Contains the updated FHE library contracts. | | `@zama-fhe/relayer-sdk` | `v0.3.0-5` | **Crucial for v0.9:** Enables the new self-relaying decryption model. | | `@fhevm/hardhat-plugin` | `v0.3.0-1` | Latest tooling support for development and deployment. | ### Step 2: Update Network Configuration in Solidity The Solidity contracts now use a unified configuration contract defined in `@fhevm/solidity/config/ZamaConfig.sol`. * **⚠️ Removal:** The `SepoliaConfig` contract is now **removed**. * **✅ New Standard:** Update your imports and usages to use the new standard **`ZamaEthereumConfig`** contract. This change simplifies future cross-chain compatibility. The new `ZamaEthereumConfig` abstract contract now dynamically resolves the FHEVM host addresses according to the `block.chainid`. Replace: ```solidity import { SepoliaConfig } from "@fhevm/solidity/config/ZamaConfig.sol"; ``` With: ```solidity import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol"; ``` You can read more about [Configuration on the dedicated page](/protocol/solidity-guides/v0.10/docs/solidity-guides/configure). ### Step 3: Update Solidity Code The Zama public decryption Oracle is discontinued. The following functions are no more available in the FHE Solidity library: * `FHE.loadRequestedHandles` * `FHE.requestDecryptionWithoutSavingHandles` * `FHE.requestDecryption` ### Step 4: Re-compile and Re-deploy Smart Contracts Due to fundamental changes in the FHEVM implementation and underlying infrastructure: * **New FHEVM Addresses:** The contract addresses for core FHE components have changed. * **Action:** You **must** re-compile your entire Solidity codebase and re-deploy all affected contracts to the **Sepolia** network. ### Step 5: Adjust Public Decryption Logic (Crucial Architectural Change) The most significant change is the discontinuation of the Zama Oracle. This requires substantial adjustments to how your dApp handles decryption on-chain. | Aspect | FHEVM v0.8 (Old Logic) | FHEVM v0.9 (New Logic) | | ---------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | **Decryption Handler** | **Zama Oracle** actively listens for requests and submits the result. | **dApp Client/User** performs the off-chain decryption (self-relaying). | | **Solidity Function** | Used `FHE.requestDecryption()`. | You will now create custom functions that accept the decrypted value and the proof. | | **Client-Side Tool** | N/A | **Use `@zama-fhe/relayer-sdk`** to perform the `publicDecrypt` and obtain the proof. | > **Action:** Thoroughly review your Solidity code, dApp logic, and backend services. Any code relying on the external Oracle must be rewritten to implement the self-relaying workflow using the `@zama-fhe/relayer-sdk`. ## FHEVM v0.9 Code Examples: Public Decryption Logic The following code examples illustrate the **new public decryption logic** introduced in v0.9. This new workflow uses the combination of: * **On-chain public decyption permission** via `FHE.makePubliclyDecryptable` * **Off-chain decryption** via `publicDecrypt` using the `@zama-fhe/relayer-sdk` or the FHEVM Hardhat Plugin * **On-chain signature verification** via `FHE.checkSignatures` #### Code Examples * [HeadsOrTails](/protocol/solidity-guides/v0.10/docs/examples/heads-or-tails): Demonstrates the complete public decryption workflow where a cipher text is first marked as decryptable on-chain via `FHE.makePubliclyDecryptable`, and its cleartext value is subsequently verified on-chain using `FHE.checkSignatures` after being fetched off-chain via `publicDecrypt`. * [HighestDieRoll](/protocol/solidity-guides/v0.10/docs/examples/highest-die-roll): Extends the public decryption workflow to a multi-input scenario, demonstrating how the on-chain `FHE.checkSignatures` function ensures the authenticity of multiple cleartext values derived from multiple encrypted on-chain cypher texts. # Mocked mode This document provides an overview of mocked mode in the FHEVM framework, explaining how it enables faster development and testing of smart contracts that use Fully Homomorphic Encryption (FHE). ## Overview **Mocked mode** is a development and testing feature provided in the FHEVM framework that allows developers to simulate the behavior of Fully Homomorphic Encryption (FHE) without requiring the full encryption and decryption processes to be performed. This makes development and testing cycles faster and more efficient by replacing actual cryptographic operations with mocked values, which behave similarly to encrypted data but without the computational overhead of true encryption. ## How to use mocked mode ### 1. **Hardhat template** Mocked mode is currently supported in the [Zama Hardhat template](https://github.com/zama-ai/fhevm-hardhat-template). Developers can enable mocked mode to simulate encrypted operations while building and testing smart contracts locally. The Hardhat template includes pre-configured scripts and libraries to simplify the setup process for mocked mode. Refer to the [\[Quick start - Hardhat\]](https://github.com/zama-ai/fhevm/blob/release/0.10.x/docs/getting-started/overview-1/hardhat/README.md) guide for instructions on using the Hardhat template. ### 2. **Foundry (coming soon)** Mocked mode support is planned for [Foundry](https://github.com/zama-ai/fhevm/blob/release/0.10.x/docs/solidity-guides/write_contract/foundry.md) in future releases. ## How mocked mode works For faster testing iterations, instead of launching all the tests on the local FHEVM node, which could last several minutes, you can use a mocked version of the FHEVM by running `pnpm test`. The same tests should (almost always) pass as is, without any modification; neither the JavaScript files nor the Solidity files need to be changed between the mocked and the real version. The mocked mode does **not** actually perform real encryption for encrypted types and instead runs the tests on a local Hardhat node, which is implementing the original EVM (i.e., non-FHEVM). Additionally, the mocked mode will let you use all the Hardhat-related special testing and debugging methods, such as `evm_mine`, `evm_snapshot`, `evm_revert`, etc., which are very helpful for testing. ## Development workflow with mocked mode When developing confidential contracts, we recommend to use first the mocked version of FHEVM for faster testing with `pnpm test` and coverage computation via `pnpm coverage`, this will lead to a better developer experience. It's essential to run tests of the final contract version using the real FHEVM. You can do this by running `pnpm test` before deployment. To run the mocked tests use either: ```sh pnpm test ``` Or equivalently: ```sh npx hardhat test --network hardhat ``` In mocked mode, all tests should pass in few seconds instead of few minutes, allowing a better developer experience. Furthermore, getting the coverage of tests is only possible in mocked mode. Just use the following command: ``` pnpm coverage ``` Or equivalently: ``` npx hardhat coverage ``` Then open the file `coverage/index.html` to see the coverage results. This will increase security by pointing out missing branches not covered yet by the current test suite. {% hint style="info" %} Due to limitations in the `solidity-coverage` package, test coverage computation does not work with tests that use the `evm_snapshot` Hardhat testing method. {% endhint %} If you are using Hardhat snapshots in your tests, we recommend adding the `[skip-on-coverage]` tag at the end of your test description. Here's an example: ```js import { expect } from 'chai'; import { ethers, network } from 'hardhat'; import { createInstances, decrypt8, decrypt16, decrypt32, decrypt64 } from '../instance'; import { getSigners, initSigners } from '../signers'; import { deployRandFixture } from './Rand.fixture'; describe('Rand', function () { before(async function () { await initSigners(); this.signers = await getSigners(); }); beforeEach(async function () { const contract = await deployRandFixture(); this.contractAddress = await contract.getAddress(); this.rand = contract; this.instances = await createInstances(this.signers); }); it('64 bits generate with upper bound and decrypt', async function () { const values: bigint[] = []; for (let i = 0; i < 5; i++) { const txn = await this.rand.generate64UpperBound(262144); await txn.wait(); const valueHandle = await this.rand.value64(); const value = await decrypt64(valueHandle); expect(value).to.be.lessThanOrEqual(262141); values.push(value); } // Expect at least two different generated values. const unique = new Set(values); expect(unique.size).to.be.greaterThanOrEqual(2); }); it('8 and 16 bits generate and decrypt with hardhat snapshots [skip-on-coverage]', async function () { if (network.name === 'hardhat') { // snapshots are only possible in hardhat node, i.e in mocked mode this.snapshotId = await ethers.provider.send('evm_snapshot'); const values: number[] = []; for (let i = 0; i < 5; i++) { const txn = await this.rand.generate8(); await txn.wait(); const valueHandle = await this.rand.value8(); const value = await decrypt8(valueHandle); expect(value).to.be.lessThanOrEqual(0xff); values.push(value); } // Expect at least two different generated values. const unique = new Set(values); expect(unique.size).to.be.greaterThanOrEqual(2); await ethers.provider.send('evm_revert', [this.snapshotId]); const values2: number[] = []; for (let i = 0; i < 5; i++) { const txn = await this.rand.generate8(); await txn.wait(); const valueHandle = await this.rand.value8(); const value = await decrypt8(valueHandle); expect(value).to.be.lessThanOrEqual(0xff); values2.push(value); } // Expect at least two different generated values. const unique2 = new Set(values2); expect(unique2.size).to.be.greaterThanOrEqual(2); } }); }); ``` * **The first test** always runs in both mocked mode (`pnpm test`) and coverage mode (`pnpm coverage`). * **The second test** runs only while testing mocked mode (`pnpm test`) since it uses snapshots which are only available there. The test is skipped in coverage mode due to the `[skip-on-coverage]` suffix in its description. It also checks that the network is 'hardhat' to avoid failures in non-mocked environments. --- [Next Page](https://docs.zama.org/protocol/llms-full.txt/2) # How to Transform Your Smart Contract into a FHEVM Smart Contract? This short guide will walk you through converting a standard Solidity contract into one that leverages Fully Homomorphic Encryption (FHE) using FHEVM. This approach lets you develop your contract logic as usual, then adapt it to support encrypted computation for privacy. For this guide, we will focus on a voting contract example. *** ## 1. Start with a Standard Solidity Contract Begin by writing your voting contract in Solidity as you normally would. Focus on implementing the core logic and functionality. ```solidity // Standard Solidity voting contract example pragma solidity ^0.8.0; contract SimpleVoting { mapping(address => bool) public hasVoted; uint64 public yesVotes; uint64 public noVotes; uint256 public voteDeadline; function vote(bool support) public { require(block.timestamp <= voteDeadline, "Too late to vote"); require(!hasVoted[msg.sender], "Already voted"); hasVoted[msg.sender] = true; if (support) { yesVotes += 1; } else { noVotes += 1; } } function getResults() public view returns (uint64, uint64) { return (yesVotes, noVotes); } } ``` *** ## 2. Identify Sensitive Data and Operations Review your contract and determine which variables, functions, or computations require privacy. In this example, the vote counts (`yesVotes`, `noVotes`) and individual votes should be encrypted. *** ## 3. Integrate FHEVM and update your business logic accordingly. Replace standard data types and operations with their FHEVM equivalents for the identified sensitive parts. Use encrypted types and FHEVM library functions to perform computations on encrypted data. ```solidity pragma solidity ^0.8.0; import "@fhevm/solidity/lib/FHE.sol"; import {ZamaEthereumConfig} from "@fhevm/solidity/config/ZamaConfig.sol"; contract EncryptedSimpleVoting is ZamaEthereumConfig { enum VotingStatus { Open, DecryptionInProgress, ResultsDecrypted } mapping(address => bool) public hasVoted; VotingStatus public status; uint64 public decryptedYesVotes; uint64 public decryptedNoVotes; uint256 public voteDeadline; euint64 private encryptedYesVotes; euint64 private encryptedNoVotes; constructor() { encryptedYesVotes = FHE.asEuint64(0); encryptedNoVotes = FHE.asEuint64(0); FHE.allowThis(encryptedYesVotes); FHE.allowThis(encryptedNoVotes); } function vote(externalEbool support, bytes memory inputProof) public { require(block.timestamp <= voteDeadline, "Too late to vote"); require(!hasVoted[msg.sender], "Already voted"); hasVoted[msg.sender] = true; ebool isSupport = FHE.fromExternal(support, inputProof); encryptedYesVotes = FHE.select(isSupport, FHE.add(encryptedYesVotes, 1), encryptedYesVotes); encryptedNoVotes = FHE.select(isSupport, encryptedNoVotes, FHE.add(encryptedNoVotes, 1)); FHE.allowThis(encryptedYesVotes); FHE.allowThis(encryptedNoVotes); } function requestVoteDecryption() public { require(block.timestamp > voteDeadline, "Voting is not finished"); bytes32[] memory cts = new bytes32[](2); cts[0] = FHE.toBytes32(encryptedYesVotes); cts[1] = FHE.toBytes32(encryptedNoVotes); uint256 requestId = FHE.requestDecryption(cts, this.callbackDecryptVotes.selector); status = VotingStatus.DecryptionInProgress; } function callbackDecryptVotes(uint256 requestId, bytes memory cleartexts, bytes memory decryptionProof) public { FHE.checkSignatures(requestId, cleartexts, decryptionProof); (uint64 yesVotes, uint64 noVotes) = abi.decode(cleartexts, (uint64, uint64)); decryptedYesVotes = yesVotes; decryptedNoVotes = noVotes; status = VotingStatus.ResultsDecrypted; } function getResults() public view returns (uint64, uint64) { require(status == VotingStatus.ResultsDecrypted, "Results were not decrypted"); return ( decryptedYesVotes, decryptedNoVotes ); } } ``` Adjust your contract’s code to accept and return encrypted data where necessary. This may involve changing function parameters and return types to work with ciphertexts instead of plaintext values, as shown above. * The `vote` function now has two parameters: `support` and `inputProof`. * The `getResults` can only be called after the decryption occurred. Otherwise, the decrypted results are not visible to anyone. However, it is far from being the main change. As this example illustrates, working with FHEVM often requires re-architecting the original logic to support privacy. In the updated code, the logic becomes async; results are hidden until a request (to the oracle) explicitely has to be made to decrypt publically the vote results. ## Conclusion As this short guide showed, integrating with FHEVM not only requires integration with the FHEVM stack, it also requires refactoring your business logic to support mechanism to swift between encrypted and non-encrypted components of the logic. # Supported types This document introduces the encrypted integer types provided by the `FHE` library in FHEVM and explains their usage, including casting, state variable declarations, and type-specific considerations. ## Introduction The `FHE` library offers a robust type system with encrypted integer types, enabling secure computations on confidential data in smart contracts. These encrypted types are validated both at compile time and runtime to ensure correctness and security. ### Key features of encrypted types * Encrypted integers function similarly to Solidity’s native integer types, but they operate on **Fully Homomorphic Encryption (FHE)** ciphertexts. * Arithmetic operations on `e(u)int` types are **unchecked**, meaning they wrap around on overflow. This design choice ensures confidentiality by avoiding the leakage of information through error detection. * Future versions of the `FHE` library will support encrypted integers with overflow checking, but with the trade-off of exposing limited information about the operands. {% hint style="info" %} Encrypted integers with overflow checking will soon be available in the `FHE` library. These will allow reversible arithmetic operations but may reveal some information about the input values. {% endhint %} Encrypted integers in FHEVM are represented as FHE ciphertexts, abstracted using ciphertext handles. These types, prefixed with `e` (for example, `euint64`) act as secure wrappers over the ciphertext handles. ## List of encrypted types The `FHE` library currently supports the following encrypted types: | Type | Bit Length | Supported Operators | Aliases (with supported operators) | | -------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | | Ebool | 2 | and, or, xor, eq, ne, not, select, rand | | | Euint8 | 8 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | | | Euint16 | 16 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | | | Euint32 | 32 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | | | Euint64 | 64 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | | | Euint128 | 128 | add, sub, mul, div, rem, and, or, xor, shl, shr, rotl, rotr, eq, ne, ge, gt, le, lt, min, max, neg, not, select, rand, randBounded | | | Euint160 | 160 | | Eaddress (eq, ne, select) | | Euint256 | 256 | and, or, xor, shl, shr, rotl, rotr, eq, ne, neg, not, select, rand, randBounded | | {% hint style="info" %} Division (\`div\`) and remainder (\`rem\`) operations are only supported when the right-hand side (\`rhs\`) operand is a plaintext (non-encrypted) value. Attempting to use an encrypted value as \`rhs\` will result in a panic. This restriction ensures correct and secure computation within the current framework. {% endhint %} {% hint style="info" %} Higher-precision integer types are available in the `TFHE-rs` library and can be added to `fhevm` as needed. {% endhint %} # 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 hig
프로젝트로 돌아가기