Zama 백서

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

Crucial Ordering Constraint // ============================== // The decryption proof is cryptographically bound to the specific ORDER of handles. // A proof computed for `[efoo, ebar]` will be different // from a proof computed for `[ebar, efoo]`. // // Here we expect a proof computed for `[efoo, ebar]` // bytes32[] memory ciphertextEfooEbar = new bytes32[](2); ciphertextEfooEbar[0] = FHE.toBytes32(_encryptedFoo); ciphertextEfooEbar[1] = FHE.toBytes32(_encryptedBar); // ⚠️ Once again, the order is critical to compute the ABI encoded array of clear values // The order must match the order in ciphertextEfooEbar: (efoo, ebar) bytes memory abiClearFooClearBar = abi.encode(clearFoo, clearBar); FHE.checkSignatures(ciphertextEfooEbar, abiClearFooClearBar, publicDecryptionProof); _isFinalized = true; _runFooBarClearBusinessLogicFinalization(); } function _runFooBarClearBusinessLogicFinalization() private { // Business logic starts here. // Transfer ERC20, releave price or winner etc. } } ``` {% stepper %} {% step %} ### Run On-Chain Confidential Logic We first execute the on-chain confidential logic using a TypeScript client. This simulates the initial phase of the confidential computation. ```typescript const tx = await contract.runFooBarConfidentialLogic(); await tx.wait(); ``` {% endstep %} {% step %} ### Run On-Chain Request Clear Values With the confidential logic complete, the next step is to execute the on-chain function that requests and enables public decryption of the computed encrypted values `_encryptedFoo` and `_encryptedBar`. In a production scenario, we might use a Solidity event to notify the off-chain client that the necessary encrypted values are ready for off-chain public decryption. ```typescript const tx = await contract.requestClearFooBar(); const txReceipt = await tx.wait(); const { efoo, ebar } = parseClearFooBarRequestedEvent(contract, txReceipt); ``` {% endstep %} {% step %} ### Run Off-Chain Public Decryption Now that the ciphertexts are marked as publicly decryptable, we call the off-chain function `publicDecrypt` using the `relayer-sdk`. This fetches the clear values along with the Zama KMS decryption proof required for the final on-chain verification. {% hint style="warning" %} **Crucial Ordering Constraint:** The decryption proof is cryptographically bound to the specific order of handles passed in the input array. The proof computed for `[efoo, ebar]` is different from the proof computed for `[ebar, efoo]`. {% endhint %} ```typescript const instance: FhevmInstance = await createInstance(); const results: PublicDecryptResults = await instance.publicDecrypt([efoo, ebar]); const clearFoo = results.values[efoo]; const clearBar = results.values[ebar]; // Warning! The decryption proof is computed for [efoo, ebar], NOT [ebar, efoo]! const decryptionProof: `0x${string}` = results.decryptionProof; ``` {% endstep %} {% step %} ### Run On-Chain On the client side, we have computed all the clear values and, crucially, obtained the associated decryption proof. We can now securely move on to the final step: sending this data on-chain to trigger verification and final business logic simulated in the `_runFooBarClearBusinessLogicFinalization` contract function. If verification succeeds, the contract securely executes the `_runFooBarClearBusinessLogicFinalization` (e.g., transfers funds, publishes the vote result, etc.), completing the full confidential workflow. ```typescript const tx = await contract.finalizeClearFooBar(clearFoo, clearBar, results.decryptionProof); const txReceipt = await tx.wait(); ``` {% endstep %} {% endstepper %} ## Public Decryption On-Chain & Off-Chain API #### On-chain `FHE.makePubliclyDecryptable` function The contract sets the ciphertext handle's status as publicly decryptable, globally and permanently authorizing any entity to request its off-chain cleartext value. Note the calling contract must have ACL permission to access the handle in the first place. ```solidity function makePubliclyDecryptable(ebool value) internal; function makePubliclyDecryptable(euint8 value) internal; function makePubliclyDecryptable(euint16 value) internal; ... function makePubliclyDecryptable(euint256 value) internal; ``` **Function arguments** **Function return** This function has no return value #### Off-chain relayer-sdk `publicDecrypt` function The relayer-sdk `publicDecrypt` function is defined as follow: ```typescript export type PublicDecryptResults = { clearValues: Record<`0x${string}`, bigint | boolean | `0x${string}`>; abiEncodedClearValues: `0x${string}`; decryptionProof: `0x${string}`; }; export type FhevmInstance = { //... publicDecrypt: (handles: (string | Uint8Array)[]) => Promise<PublicDecryptResults>; //... }; ``` **Function arguments** | Argument | Description | Constraints | | --------- | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `handles` | The list of ciphertext handles (represented as bytes32 values) to decrypt. | These handles must correspond to ciphertexts that have been marked as publicly decryptable on-chain. | **Function return type `PublicDecryptResults`** The function returns an object containing the three essential components required for the final on-chain verification in Step 3 of the public decryption workflow: | Property | Type | Description | On-Chain usage | | ----------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | `clearValues` | `Record<`0x${string}`, bigint \| boolean \|` 0x${string}`>` | An object mapping each input ciphertext handle to its raw decrypted cleartext value. | N/A | | `abiEncodedClearValues` | `0x${string}` | The ABI-encoded byte string of all decrypted cleartext values, preserving the exact order of the input handles list. | `abiEncodedCleartexts` argument when calling the on-chain `FHE.checkSignatures` | | `decryptionProof` | `0x${string}` | A byte array containing the KMS cryptographic signatures and necessary metadata that proves the decryption was legitimately performed. | `decryptionProof` argument when calling the on-chain `FHE.checkSignatures` | #### On-chain `FHE.checkSignatures` function ```solidity function checkSignatures(bytes32[] memory handlesList, bytes memory abiEncodedCleartexts, bytes memory decryptionProof) internal ``` **Function arguments** | Argument | Description | Constraint | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `handlesList` | The list of ciphertext handles (represented as bytes32 values) whose decryption is being verified. | Must contain the exact same number of elements as the cleartext values in abiEncodedCleartexts. | | `abiEncodedCleartexts` | The ABI encoding of the decrypted cleartext values associated with the handles. (Use abi.encode to prepare this argument.) | Order is critical: The i-th value in this encoding must be the cleartext that corresponds to the i-th handle in handlesList. Types must match. | | `decryptionProof` | A byte array containing the KMS cryptographic signatures and necessary metadata that prove the off-chain decryption was performed by the authorized Zama Key Management System. | This proof is generated by the Zama KMS and is obtained via the `relayer-sdk.publicDecrypt` function. | **Function return** This function has no return value and simply reverts if the proof verification failed. {% hint style="warning" %} Notice that the callback should always verify the signatures and implement a replay protection mechanism (see below). {% endhint %} # getting-started # Key features This document provides an overview of key features of the FHEVM smart contract library. ### Configuration and initialization Smart contracts using FHEVM require proper configuration and initialization: * **Environment setup**: Import and inherit from environment-specific configuration contracts * **Relayer configuration**: Configure secure relayer access for cryptographic operations * **Initialization checks**: Validate encrypted variables are properly initialized before use For more information see [Configuration](/protocol/solidity-guides/v0.10/docs/solidity-guides/configure). ### Encrypted data types FHEVM introduces encrypted data types compatible with Solidity: * **Booleans**: `ebool` * **Unsigned Integers**: `euint8`, `euint16`, `euint32`, `euint64`, `euint128`, `euint256` * **Addresses**: `eaddress` * **Input**: `externalEbool`, `externalEaddress`, `externalEuintXX` for handling encrypted input data Encrypted data is represented as ciphertext handles, ensuring secure computation and interaction. For more information see [use of encrypted types](/protocol/solidity-guides/v0.10/docs/solidity-guides/types). ### Casting types fhevm provides functions to cast between encrypted types: * **Casting between encrypted types**: `FHE.asEbool` converts encrypted integers to encrypted booleans * **Casting to encrypted types**: `FHE.asEuintX` converts plaintext values to encrypted types * **Casting to encrypted addresses**: `FHE.asEaddress` converts plaintext addresses to encrypted addresses For more information see [use of encrypted types](/protocol/solidity-guides/v0.10/docs/solidity-guides/types). ### Confidential computation fhevm enables symbolic execution of encrypted operations, supporting: * **Arithmetic:** `FHE.add`, `FHE.sub`, `FHE.mul`, `FHE.min`, `FHE.max`, `FHE.neg`, `FHE.div`, `FHE.rem` * Note: `div` and `rem` operations are supported only with plaintext divisors * **Bitwise:** `FHE.and`, `FHE.or`, `FHE.xor`, `FHE.not`, `FHE.shl`, `FHE.shr`, `FHE.rotl`, `FHE.rotr` * **Comparison:** `FHE.eq`, `FHE.ne`, `FHE.lt`, `FHE.le`, `FHE.gt`, `FHE.ge` * **Advanced:** `FHE.select` for branching on encrypted conditions, `FHE.randEuintX` for on-chain randomness. For more information on operations, see [Operations on encrypted types](/protocol/solidity-guides/v0.10/docs/solidity-guides/operations). For more information on conditional branching, see [Conditional logic in FHE](/protocol/solidity-guides/v0.10/docs/solidity-guides/logics/conditions). For more information on random number generation, see [Generate Random Encrypted Numbers](/protocol/solidity-guides/v0.10/docs/solidity-guides/operations/random). ### Access control mechanism fhevm enforces access control with a blockchain-based Access Control List (ACL): * **Persistent access**: `FHE.allow`, `FHE.allowThis` grants permanent permissions for ciphertexts. * **Transient access**: `FHE.allowTransient` provides temporary access for specific transactions. * **Validation**: `FHE.isSenderAllowed` ensures that only authorized entities can interact with ciphertexts. * **Persistent public decryption**: `FHE.makePubliclyDecryptable`, `FHE.isPubliclyDecryptable` makes a given ciphertext permanently publicly decryptable. For more information see [ACL](/protocol/solidity-guides/v0.10/docs/solidity-guides/acl). # Quick Start Tutorial This tutorial guides you to start quickly with Zama’s **Fully Homomorphic Encryption (FHE)** technology for building confidential smart contracts. ## What You’ll Learn In **about 30 minutes**, you'll go from a basic Solidity contract to a fully confidential one using **FHEVM**. Here's what you'll do: 1. Set up your development environment 2. Write a simple Solidity smart contract 3. Convert it into an FHEVM-compatible confidential contract 4. Test your FHEVM-compatible confidential contract ## Prerequisite * A basic understanding of **Solidity** library and **Ethereum**. * Some familiarity with **Hardhat.** {% hint style="info" %} **About Hardhat** [**Hardhat**](https://hardhat.org/) is a development environment for compiling, deploying, testing, and debugging Ethereum smart contracts. It’s widely used in the Ethereum ecosystem. In this tutorial, we'll introduce the FHEVM hardhat template that provides an easy way to use FHEVM. {% endhint %} # Set up Hardhat In this section, you’ll learn how to set up a FHEVM Hardhat development environment using the **FHEVM Hardhat template** as a starting point for building and testing fully homomorphic encrypted smart contracts. ## Create a local Hardhat Project {% stepper %} {% step %} #### Install a Node.js TLS version Ensure that Node.js is installed on your machine. * Download and install the recommended LTS (Long-Term Support) version from the [official website](https://nodejs.org/en). * Use an **even-numbered** version (e.g., `v18.x`, `v20.x`) {% hint style="warning" %} **Hardhat** does not support odd-numbered Node.js versions. If you’re using one (e.g., v21.x, v23.x), Hardhat will display a persistent warning message and may behave unexpectedly. {% endhint %} To verify your installation: ```sh node -v npm -v ``` {% endstep %} {% step %} #### Create a new GitHub repository from the FHEVM Hardhat template. 1. On GitHub, navigate to the main page of the [FHEVM Hardhat template](https://github.com/zama-ai/fhevm-hardhat-template) repository. 2. Above the file list, click the green **Use this template** button. 3. Follow the instructions to create a new repository from the FHEVM Hardhat template. {% hint style="info" %} See Github doc: [Creating a repository from a template](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template#creating-a-repository-from-a-template) {% endhint %} {% endstep %} {% step %} #### Clone your newly created GitHub repository locally Now that your GitHub repository has been created, you can clone it to your local machine: ```sh cd <your-preferred-location> git clone <url-to-your-new-repo> # Navigate to the root of your new FHEVM Hardhat project cd <your-new-repo-name> ``` Next, let’s install your local Hardhat development environment. {% endstep %} {% step %} #### Install your FHEVM Hardhat project dependencies From the project root directory, run: ```sh npm install ``` This will install all required dependencies defined in your `package.json`, setting up your local FHEVM Hardhat development environment. {% endstep %} {% step %} #### Set up the Hardhat configuration variables (optional) If you do plan to deploy to the Sepolia Ethereum Testnet, you'll need to set up the following [Hardhat Configuration variables](https://hardhat.org/hardhat-runner/docs/guides/configuration-variables). `MNEMONIC` A mnemonic is a 12-word seed phrase used to generate your Ethereum wallet keys. 1. Get one by creating a wallet with [MetaMask](https://metamask.io/), or using any trusted mnemonic generator. 2. Set it up in your Hardhat project: ```sh npx hardhat vars set MNEMONIC ``` `INFURA_API_KEY` The INFURA project key allows you to connect to Ethereum testnets like Sepolia. 1. Obtain one by following the[ Infura + MetaMask](https://docs.metamask.io/services/get-started/infura/) setup guide. 2. Configure it in your project: ```sh npx hardhat vars set INFURA_API_KEY ``` **Default Values** If you skip this step, Hardhat will fall back to these defaults: * `MNEMONIC` = "test test test test test test test test test test test junk" * `INFURA_API_KEY` = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" {% hint style="warning" %} These defaults are not suitable for real deployments. {% endhint %} {% hint style="warning" %} #### Missing variable error: If any of the requested Hardhat Configuration Variables is missing, you'll get an error message like this one:`Error HH1201: Cannot find a value for the configuration variable 'MNEMONIC'. Use 'npx hardhat vars set MNEMONIC' to set it or 'npx hardhat var setup' to list all the configuration variables used by this project.` {% endhint %} {% endstep %} {% endstepper %} Congratulations! You're all set to start building your confidential dApp. ## Optional settings ### Install VSCode extensions If you're using Visual Studio Code, there are some extensions available to improve you your development experience: * [Prettier - Code formatter by prettier.io](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) — ID:`esbenp.prettier-vscode`, * [ESLint by Microsoft](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) — ID:`dbaeumer.vscode-eslint` Solidity support (pick one only): * [Solidity by Juan Blanco](https://marketplace.visualstudio.com/items?itemName=JuanBlanco.solidity) — ID:`juanblanco.solidity` * [Solidity by Nomic Foundation](https://marketplace.visualstudio.com/items?itemName=NomicFoundation.hardhat-solidity) — ID:`nomicfoundation.hardhat-solidity` ### Reset the Hardhat project If you'd like to start from a clean slate, you can reset your FHEVM Hardhat project by removing all example code and generated files. ```sh # Navigate to the root of your new FHEVM Hardhat project cd <your-new-repo-name> ``` Then run: ```sh rm -rf test/* src/* tasks/* deploy ./fhevmTemp ./artifacts ./cache ./coverage ./types ./coverage.json ./dist ``` # Test the FHEVM contract In this tutorial, you’ll learn how to migrate a standard Hardhat test suite - from `Counter.ts` to its FHEVM-compatible version `FHECounter.ts` — and progressively enhance it to support Fully Homomorphic Encryption using Zama’s FHEVM library. ## Set up the FHEVM testing environment {% stepper %} {% step %} ### Create a test script `test/FHECounter.ts` Go to your project's `test` directory ```sh cd <your-project-root-directory>/test ``` From there, create a new file named `FHECounter.ts` and copy/paste the following Typescript skeleton code in it. ```ts import { FHECounter, FHECounter__factory } from "../types"; import { FhevmType } from "@fhevm/hardhat-plugin"; import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers"; import { expect } from "chai"; import { ethers, fhevm } from "hardhat"; type Signers = { deployer: HardhatEthersSigner; alice: HardhatEthersSigner; bob: HardhatEthersSigner; }; async function deployFixture() { const factory = (await ethers.getContractFactory("FHECounter")) as FHECounter__factory; const fheCounterContract = (await factory.deploy()) as FHECounter; const fheCounterContractAddress = await fheCounterContract.getAddress(); return { fheCounterContract, fheCounterContractAddress }; } describe("FHECounter", function () { let signers: Signers; let fheCounterContract: FHECounter; let fheCounterContractAddress: string; before(async function () { const ethSigners: HardhatEthersSigner[] = await ethers.getSigners(); signers = { deployer: ethSigners[0], alice: ethSigners[1], bob: ethSigners[2] }; }); beforeEach(async () => { ({ fheCounterContract, fheCounterContractAddress } = await deployFixture()); }); it("should be deployed", async function () { console.log(`FHECounter has been deployed at address ${fheCounterContractAddress}`); // Test the deployed address is valid expect(ethers.isAddress(fheCounterContractAddress)).to.eq(true); }); // it("count should be zero after deployment", async function () { // const count = await counterContract.getCount(); // console.log(`Counter.getCount() === ${count}`); // // Expect initial count to be 0 after deployment // expect(count).to.eq(0); // }); // it("increment the counter by 1", async function () { // const countBeforeInc = await counterContract.getCount(); // const tx = await counterContract.connect(signers.alice).increment(1); // await tx.wait(); //
프로젝트로 돌아가기