Zama 백서

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

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"); // ⚠️ 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, reveal 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 %} # Hardhat plugin This section will guide you through writing and testing FHEVM smart contracts in Solidity using [Hardhat](https://hardhat.org). ### The FHEVM Hardhat Plugin To write FHEVM smart contracts using Hardhat, you need to install the [FHEVM Hardhat Plugin](https://www.npmjs.com/package/@fhevm/hardhat-plugin) in your Hardhat project. This plugin enables you to develop, test, and interact with FHEVM contracts right out of the box. It extends Hardhat’s functionality with a complete FHEVM API that allows you: * Encrypt data * Decrypt data * Run tests using various FHEVM execution modes * Write FHEVM-enabled Hardhat Tasks ### Where to go next 🟨 Go to [**Setup Hardhat**](https://docs.zama.ai/protocol/solidity-guides/getting-started/setup) to initialize your FHEVM Hardhat project. 🟨 Go to [**Write FHEVM Tests in Hardhat**](/protocol/solidity-guides/v0.12/development-guide/hardhat/write_test) for details on writing tests of FHEVM smart contracts using Hardhat. 🟨 Go to [**Run FHEVM Tests in Hardhat**](/protocol/solidity-guides/v0.12/development-guide/hardhat/run_test) to learn how to execute those tests in different FHEVM environments. 🟨 Go to [**Write FHEVM Hardhat Task**](/protocol/solidity-guides/v0.12/development-guide/hardhat/write_task) to learn how to write your own custom FHEVM Hardhat task. # Write FHEVM tests in Hardhat In this section, you'll find everything you need to set up a new [Hardhat](https://hardhat.org) project and start developing FHEVM smart contracts from scratch using the [FHEVM Hardhat Plugin](https://www.npmjs.com/package/@fhevm/hardhat-plugin) ### Enabling the FHEVM Hardhat Plugin in your Hardhat project Like any Hardhat plugin, the [FHEVM Hardhat Plugin](https://www.npmjs.com/package/@fhevm/hardhat-plugin) must be enabled by adding the following `import` statement to your `hardhat.config.ts` file: ```typescript import "@fhevm/hardhat-plugin"; ``` {% hint style="warning" %} Without this import, the Hardhat FHEVM API will **not** be available in your Hardhat runtime environment (HRE). {% endhint %} ### Accessing the Hardhat FHEVM API The plugin extends the standard [Hardhat Runtime Environment](https://hardhat.org/hardhat-runner/docs/advanced/hardhat-runtime-environment) (or `hre` in short) with the new `fhevm` Hardhat module. You can access it in either of the following ways: ```typescript import { fhevm } from "hardhat"; ``` or ```typescript import * as hre from "hardhat"; // Then access: hre.fhevm ``` ### Encrypting Values Using the Hardhat FHEVM API Suppose the FHEVM smart contract you want to test has a function called `foo` that takes an encrypted `uint32` value as input. The Solidity function `foo` should be declared as follows: ```solidity function foo(externalEunit32 value, bytes calldata memory inputProof); ``` Where: * `externalEunit32 value` : is a `bytes32` representing the encrypted `uint32` * `bytes calldata memory inputProof` : is a `bytes` array representing the zero-knowledge proof of knowledge that validates the encryption To compute these arguments in TypeScript, you need: * The **address of the target smart contract** * The **signer’s address** (i.e., the account sending the transaction) {% stepper %} {% step %} **Create a new encrypted input** ```ts // use the `fhevm` API module from the Hardhat Runtime Environment const input = fhevm.createEncryptedInput(contractAddress, signers.alice.address); ``` {% endstep %} {% step %} **Add the value you want to encrypt.** ```ts input.add32(12345); ``` {% endstep %} {% step %} **Perform local encryption.** ```ts const encryptedInputs = await input.encrypt(); ``` {% endstep %} {% step %} **Call the Solidity function** ```ts const externalUint32Value = encryptedInputs.handles[0]; const inputProof = encryptedInputs.proof; const tx = await input.foo(externalUint32Value, inputProof); await tx.wait(); ``` {% endstep %} {% endstepper %} #### Encryption examples * [Basic encryption examples](https://docs.zama.ai/protocol/examples/basic/encryption) * [FHECounter](https://docs.zama.ai/protocol/examples#an-fhe-counter) ### Decrypting values using the Hardhat FHEVM API Suppose user **Alice** wants to decrypt a `euint32` value that is stored in a smart contract exposing the following Solidity `view` function: ```solidity function getEncryptedUint32Value() public view returns (euint32) { returns _encryptedUint32Value; } ``` {% hint style="warning" %} For simplicity, we assume that both Alice’s account and the target smart contract already have the necessary FHE permissions to decrypt this value. For a detailed explanation of how FHE permissions work, see the [`initializeUint32()`](https://docs.zama.ai/protocol/examples/basic/decryption/fhe-decrypt-single-value#tab-decryptsinglevalue.sol) function in [DecryptSingleValue.sol](https://docs.zama.ai/protocol/examples/basic/decryption/fhe-decrypt-single-value#tab-decryptsinglevalue.sol). {% endhint %} {% stepper %} {% step %} **Retrieve the encrypted value (a `bytes32` handle) from the smart contract:** ```ts const encryptedUint32Value = await contract.getEncryptedUint32Value(); ``` {% endstep %} {% step %} **Perform the decryption using the FHEVM API:** ```ts const clearUint32Value = await fhevm.userDecryptEuint( FhevmType.euint32, // Encrypted type (must match the Solidity type) encryptedUint32Value, // bytes32 handle Alice wants to decrypt contractAddress, // Target contract address signers.alice, // Alice’s wallet ); ``` {% hint style="warning" %} If either the target smart contract or the user does **NOT** have FHE permissions, then the decryption call will fail! {% endhint %} {% endstep %} {% endstepper %} #### Supported Decryption Types Use the appropriate function for each encrypted data type: | Type | Function | | ---------- | -------------------------------- | | `euintXXX` | `fhevm.userDecryptEuint(...)` | | `ebool` | `fhevm.userDecryptEbool(...)` | | `eaddress` | `fhevm.userDecryptEaddress(...)` | #### Decryption examples * [Basic decryption examples](https://docs.zama.ai/protocol/examples/basic/decryption) * [FHECounter](https://docs.zama.ai/protocol/examples#an-fhe-counter) # Deploy contracts and run tests In this section, you'll find everything you need to test your FHEVM smart contracts in your [Hardhat](https://hardhat.org) project. ### FHEVM Runtime Modes The FHEVM Hardhat plugin provides three **FHEVM runtime modes** tailored for different stages of contract development and testing. Each mode offers a trade-off between speed, encryption, and persistence. 1. The **Hardhat (In-Memory)** default network: 🧪 *Uses mock encryption.* Ideal for regular tests, CI test coverage, and fast feedback during early contract development. No real encryption is used. 2. The **Hardhat Node (Local Server)** network: 🧪 *Uses mock encryption.* Ideal when you need persistent state - for example, when testing frontend interactions, simulating user flows, or validating deployments in a realistic local environment. Still uses mock encryption. 3. The **Sepolia Testnet** network: 🔐 *Uses real encryption.* Use this mode once your contract logic is stable and validated locally. This is the only mode that runs on the full FHEVM stack with **real encrypted values**. It simulates real-world production conditions but is slower and requires Sepolia ETH. {% hint style="success" %} **Zama Testnet** is not a blockchain itself. It is a protocol that enables you to run confidential smart contracts on existing blockchains (such as Ethereum, Base, and others) with the support of encrypted types. See the [FHE on blockchain](https://docs.zama.ai/protocol/protocol/overview) guide to learn more about the protocol architecture. Currently, **Zama Protocol** is available on the **Sepolia Testnet**. Support for additional chains will be added in the future. [See the roadmap↗](https://docs.zama.ai/protocol/zama-protocol-litepaper#roadmap) {% endhint %}
프로젝트로 돌아가기