bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 32쪽
evm/solidity/lib/FHE.sol";
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
/**
* This trivial example demonstrates the FHE encryption mechanism.
*/
contract EncryptMultipleValues is ZamaEthereumConfig {
ebool private _encryptedEbool;
euint32 private _encryptedEuint32;
eaddress private _encryptedEaddress;
// solhint-disable-next-line no-empty-blocks
constructor() {}
function initialize(
externalEbool inputEbool,
externalEuint32 inputEuint32,
externalEaddress inputEaddress,
bytes calldata inputProof
) external {
_encryptedEbool = FHE.fromExternal(inputEbool, inputProof);
_encryptedEuint32 = FHE.fromExternal(inputEuint32, inputProof);
_encryptedEaddress = FHE.fromExternal(inputEaddress, inputProof);
// For each of the 3 values:
// Grant FHE permission to both the contract itself (`address(this)`) and the caller (`msg.sender`),
// to allow future decryption by the caller (`msg.sender`).
FHE.allowThis(_encryptedEbool);
FHE.allow(_encryptedEbool, msg.sender);
FHE.allowThis(_encryptedEuint32);
FHE.allow(_encryptedEuint32, msg.sender);
FHE.allowThis(_encryptedEaddress);
FHE.allow(_encryptedEaddress, msg.sender);
}
function encryptedBool() public view returns (ebool) {
return _encryptedEbool;
}
function encryptedUint32() public view returns (euint32) {
return _encryptedEuint32;
}
function encryptedAddress() public view returns (eaddress) {
return _encryptedEaddress;
}
}
```
{% endtab %}
{% tab title="EncryptMultipleValues.ts" %}
```ts
//TODO;
import { EncryptMultipleValues, EncryptMultipleValues__factory } from "../../../types";
import type { Signers } from "../../types";
import { FhevmType, HardhatFhevmRuntimeEnvironment } from "@fhevm/hardhat-plugin";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { expect } from "chai";
import { ethers } from "hardhat";
import * as hre from "hardhat";
async function deployFixture() {
// Contracts are deployed using the first signer/account by default
const factory = (await ethers.getContractFactory("EncryptMultipleValues")) as EncryptMultipleValues__factory;
const encryptMultipleValues = (await factory.deploy()) as EncryptMultipleValues;
const encryptMultipleValues_address = await encryptMultipleValues.getAddress();
return { encryptMultipleValues, encryptMultipleValues_address };
}
/**
* This trivial example demonstrates the FHE encryption mechanism
* and highlights a common pitfall developers may encounter.
*/
describe("EncryptMultipleValues", function () {
let contract: EncryptMultipleValues;
let contractAddress: string;
let signers: Signers;
before(async function () {
// Check whether the tests are running against an FHEVM mock environment
if (!hre.fhevm.isMock) {
throw new Error(`This hardhat test suite cannot run on Sepolia Testnet`);
}
const ethSigners: HardhatEthersSigner[] = await ethers.getSigners();
signers = { owner: ethSigners[0], alice: ethSigners[1] };
});
beforeEach(async function () {
// Deploy a new contract each time we run a new test
const deployment = await deployFixture();
contractAddress = deployment.encryptMultipleValues_address;
contract = deployment.encryptMultipleValues;
});
// ✅ Test should succeed
it("encryption should succeed", async function () {
// Use the FHEVM Hardhat plugin runtime environment
// to perform FHEVM input encryptions.
const fhevm: HardhatFhevmRuntimeEnvironment = hre.fhevm;
const input = fhevm.createEncryptedInput(contractAddress, signers.alice.address);
input.addBool(true);
input.add32(123456);
input.addAddress(signers.owner.address);
const enc = await input.encrypt();
const inputEbool = enc.handles[0];
const inputEuint32 = enc.handles[1];
const inputEaddress = enc.handles[2];
const inputProof = enc.inputProof;
// Don't forget to call `connect(signers.alice)` to make sure
// the Solidity `msg.sender` is `signers.alice.address`.
const tx = await contract.connect(signers.alice).initialize(inputEbool, inputEuint32, inputEaddress, inputProof);
await tx.wait();
const encryptedBool = await contract.encryptedBool();
const encryptedUint32 = await contract.encryptedUint32();
const encryptedAddress = await contract.encryptedAddress();
const clearBool = await fhevm.userDecryptEbool(
encryptedBool,
contractAddress, // The contract address
signers.alice, // The user wallet
);
const clearUint32 = await fhevm.userDecryptEuint(
FhevmType.euint32, // Specify the encrypted type
encryptedUint32,
contractAddress, // The contract address
signers.alice, // The user wallet
);
const clearAddress = await fhevm.userDecryptEaddress(
encryptedAddress,
contractAddress, // The contract address
signers.alice, // The user wallet
);
expect(clearBool).to.equal(true);
expect(clearUint32).to.equal(123456);
expect(clearAddress).to.equal(signers.owner.address);
});
});
```
{% endtab %}
{% endtabs %}
# fhe-encrypt-single-value
This example demonstrates the FHE encryption mechanism and highlights a common pitfall developers may encounter.
{% hint style="info" %}
To run this example correctly, make sure the files are placed in the following directories:
* `.sol` file → `<your-project-root-dir>/contracts/`
* `.ts` file → `<your-project-root-dir>/test/`
This ensures Hardhat can compile and test your contracts as expected.
{% endhint %}
{% tabs %}
{% tab title="EncryptSingleValue.sol" %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import { FHE, externalEuint32, euint32 } from "@fhevm/solidity/lib/FHE.sol";
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
/**
* This trivial example demonstrates the FHE encryption mechanism.
*/
contract EncryptSingleValue is ZamaEthereumConfig {
euint32 private _encryptedEuint32;
// solhint-disable-next-line no-empty-blocks
constructor() {}
function initialize(externalEuint32 inputEuint32, bytes calldata inputProof) external {
_encryptedEuint32 = FHE.fromExternal(inputEuint32, inputProof);
// Grant FHE permission to both the contract itself (`address(this)`) and the caller (`msg.sender`),
// to allow future decryption by the caller (`msg.sender`).
FHE.allowThis(_encryptedEuint32);
FHE.allow(_encryptedEuint32, msg.sender);
}
function encryptedUint32() public view returns (euint32) {
return _encryptedEuint32;
}
}
```
{% endtab %}
{% tab title="EncryptSingleValue.ts" %}
```ts
import { EncryptSingleValue, EncryptSingleValue__factory } from "../../../types";
import type { Signers } from "../../types";
import { FhevmType, HardhatFhevmRuntimeEnvironment } from "@fhevm/hardhat-plugin";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { expect } from "chai";
import { ethers } from "hardhat";
import * as hre from "hardhat";
async function deployFixture() {
// Contracts are deployed using the first signer/account by default
const factory = (await ethers.getContractFactory("EncryptSingleValue")) as EncryptSingleValue__factory;
const encryptSingleValue = (await factory.deploy()) as EncryptSingleValue;
const encryptSingleValue_address = await encryptSingleValue.getAddress();
return { encryptSingleValue, encryptSingleValue_address };
}
/**
* This trivial example demonstrates the FHE encryption mechanism
* and highlights a common pitfall developers may encounter.
*/
describe("EncryptSingleValue", function () {
let contract: EncryptSingleValue;
let contractAddress: string;
let signers: Signers;
before(async function () {
// Check whether the tests are running against an FHEVM mock environment
if (!hre.fhevm.isMock) {
throw new Error(`This hardhat test suite cannot run on Sepolia Testnet`);
}
const ethSigners: HardhatEthersSigner[] = await ethers.getSigners();
signers = { owner: ethSigners[0], alice: ethSigners[1] };
});
beforeEach(async function () {
// Deploy a new contract each time we run a new test
const deployment = await deployFixture();
contractAddress = deployment.encryptSingleValue_address;
contract = deployment.encryptSingleValue;
});
// ✅ Test should succeed
it("encryption should succeed", async function () {
// Use the FHEVM Hardhat plugin runtime environment
// to perform FHEVM input encryptions.
const fhevm: HardhatFhevmRuntimeEnvironment = hre.fhevm;
// 🔐 Encryption Process:
// Values are encrypted locally and bound to a specific contract/user pair.
// This grants the bound contract FHE permissions to receive and process the encrypted value,
// but only when it is sent by the bound user.
const input = fhevm.createEncryptedInput(contractAddress, signers.alice.address);
// Add a uint32 value to the list of values to encrypt locally.
input.add32(123456);
// Perform the local encryption. This operation produces two components:
// 1. `handles`: an array of FHEVM handles. In this case, a single handle associated with the
// locally encrypted uint32 value `123456`.
// 2. `inputProof`: a zero-knowledge proof that attests the `handles` are cryptographically
// bound to the pair `[contractAddress, signers.alice.address]`.
const enc = await input.encrypt();
// a 32-bytes FHEVM handle that represents a future Solidity `euint32` value.
const inputEuint32 = enc.handles[0];
const inputProof = enc.inputProof;
// Now `signers.alice.address` can send the encrypted value and its associated zero-knowledge proof
// to the smart contract deployed at `contractAddress`.
const tx = await contract.connect(signers.alice).initialize(inputEuint32, inputProof);
await tx.wait();
// Let's try to decrypt it to check that everything is ok!
const encryptedUint32 = await contract.encryptedUint32();
const clearUint32 = await fhevm.userDecryptEuint(
FhevmType.euint32, // Specify the encrypted type
encryptedUint32,
contractAddress, // The contract address
signers.alice, // The user wallet
);
expect(clearUint32).to.equal(123456);
});
// ❌ This test illustrates a very common pitfall
it("encryption should fail", async function () {
const fhevm: HardhatFhevmRuntimeEnvironment = hre.fhevm;
const enc = await fhevm.createEncryptedInput(contractAddress, signers.alice.address).add32(123456).encrypt();
const inputEuint32 = enc.handles[0];
const inputProof = enc.inputProof;
try {
// Here is a very common error !
// `contract.initialize` will sign the Ethereum transaction using user `signers.owner`
// instead of `signers.alice`.
//
// In the Solidity contract the following is checked:
// - Is the contract allowed to manipulate `inputEuint32`? Answer is: ✅ yes!
// - Is the sender allowed to manipulate `inputEuint32`? Answer is: ❌ no! Only `signers.alice` is!
const tx = await contract.initialize(inputEuint32, inputProof);
await tx.wait();
} catch {
//console.log(e);
}
});
});
```
{% endtab %}
{% endtabs %}
# fhe-user-decrypt-multiple-values
This example demonstrates the FHE user decryption mechanism with multiple values.
User decryption is a mechanism that allows specific users to decrypt encrypted values while keeping them hidden from others. Unlike public decryption where decrypted values become visible to everyone, user decryption maintains privacy by only allowing authorized users with the proper permissions to view the data. While permissions are granted onchain through smart contracts, the actual **decryption call occurs off-chain in the frontend application**.
{% hint style="info" %}
To run this example correctly, make sure the files are placed in the following directories:
* `.sol` file → `<your-project-root-dir>/contracts/`
* `.ts` file → `<your-project-root-dir>/test/`
This ensures Hardhat can compile and test your contracts as expected.
{% endhint %}
{% tabs %}
{% tab title="UserDecryptMultipleValues.sol" %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import { FHE, ebool, euint32, euint64 } from "@fhevm/solidity/lib/FHE.sol";
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
contract UserDecryptMultipleValues is ZamaEthereumConfig {
ebool private _encryptedBool; // = 0 (uninitizalized)
euint32 private _encryptedUint32; // = 0 (uninitizalized)
euint64 private _encryptedUint64; // = 0 (uninitizalized)
// solhint-disable-next-line no-empty-blocks
constructor() {}
function initialize(bool a, uint32 b, uint64 c) external {
// Compute 3 trivial FHE formulas
// _encryptedBool = a ^ false
_encryptedBool = FHE.xor(FHE.asEbool(a), FHE.asEbool(false));
// _encryptedUint32 = b + 1
_encryptedUint32 = FHE.add(FHE.asEuint32(b), FHE.asEuint32(1));
// _encryptedUint64 = c + 1
_encryptedUint64 = FHE.add(FHE.asEuint64(c), FHE.asEuint64(1));
// see `DecryptSingleValue.sol` for more detailed explanations
// about FHE permissions and asynchronous user decryption requests.
FHE.allowThis(_encryptedBool);
FHE.allowThis(_encryptedUint32);
FHE.allowThis(_encryptedUint64);
FHE.allow(_encryptedBool, msg.sender);
FHE.allow(_encryptedUint32, msg.sender);
FHE.allow(_encryptedUint64, msg.sender);
}
function encryptedBool() public view returns (ebool) {
return _encryptedBool;
}
function encryptedUint32() public view returns (euint32) {
return _encryptedUint32;
}
function encryptedUint64() public view returns (euint64) {
return _encryptedUint64;
}
}
```
{% endtab %}
{% tab title="UserDecryptMultipleValues.ts" %}
```ts
import { UserDecryptMultipleValues, UserDecryptMultipleValues__factory } from "../../../types";
import type { Signers } from "../../types";
import { HardhatFhevmRuntimeEnvironment } from "@fhevm/hardhat-plugin";
import { utils as fhevm_utils } from "@fhevm/mock-utils";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { DecryptedResults } from "@zama-fhe/relayer-sdk";
import { expect } from "chai";
import { ethers } from "hardhat";
import * as hre from "hardhat";
async function deployFixture() {
// Contracts are deployed using the first signer/account by default
const factory = (await ethers.getContractFactory("UserDecryptMultipleValues")) as UserDecryptMultipleValues__factory;
const userDecryptMultipleValues = (await factory.deploy()) as UserDecryptMultipleValues;
const userDecryptMultipleValues_address = await userDecryptMultipleValues.getAddress();
return { userDecryptMultipleValues, userDecryptMultipleValues_address };
}
/**
* This trivial example demonstrates the FHE user decryption mechanism
* and highlights a common pitfall developers may encounter.
*/
describe("UserDecryptMultipleValues", function () {
let contract: UserDecryptMultipleValues;
let contractAddress: string;
let signers: Signers;
before(async function () {
// Check whether the tests are running against an FHEVM mock environment
if (!hre.fhevm.isMock) {
throw new Error(`This hardhat test suite cannot run on Sepolia Testnet`);
}
const ethSigners: HardhatEthersSigner[] = await ethers.getSigners();
signers = { owner: ethSigners[0], alice: ethSigners[1] };
});
beforeEach(async function () {
// Deploy a new contract each time we run a new test
const deployment = await deployFixture();
contractAddress = deployment.userDecryptMultipleValues_address;
contract = deployment.userDecryptMultipleValues;
});
// ✅ Test should succeed
it("user decryption should succeed", async function () {
const tx = await contract.connect(signers.alice).initialize(true, 123456, 78901234567);
await tx.wait();
const encryptedBool = await contract.encryptedBool();
const encryptedUint32 = await contract.encryptedUint32();
const encryptedUint64 = await contract.encryptedUint64();
// The FHEVM Hardhat plugin provides a set of convenient helper functions
// that make it easy to perform FHEVM operations within your Hardhat environment.
const fhevm: HardhatFhevmRuntimeEnvironment = hre.fhevm;
const aliceKeypair = fhevm.generateKeypair();
const startTimestamp = fhevm_utils.timestampNow();
const durationDays = 365;
const aliceEip712 = fhevm.createEIP712(aliceKeypair.publicKey, [contractAddress], startTimestamp, durationDays);
const aliceSignature = await signers.alice.signTypedData(
aliceEip712.domain,
{ UserDecryptRequestVerification: aliceEip712.types.UserDecryptRequestVerification },
aliceEip712.message,
);
const decrytepResults: DecryptedResults = await fhevm.userDecrypt(
[
{ handle: encryptedBool, contractAddress: contractAddress },
{ handle: encryptedUint32, contractAddress: contractAddress },
{ handle: encryptedUint64, contractAddress: contractAddress },
],
aliceKeypair.privateKey,
aliceKeypair.publicKey,
aliceSignature,
[contractAddress],
signers.alice.address,
startTimestamp,
durationDays,
);
expect(decrytepResults[encryptedBool]).to.equal(true);
expect(decrytepResults[encryptedUint32]).to.equal(123456 + 1);
expect(decrytepResults[encryptedUint64]).to.equal(78901234567 + 1);
});
});
```
{% endtab %}
{% endtabs %}
# fhe-user-decrypt-single-value
This example demonstrates the FHE user decryption mechanism with a single value.
User decryption is a mechanism that allows specific users to decrypt encrypted values while keeping them hidden from others. Unlike public decryption where decrypted values become visible to everyone, user decryption maintains privacy by only allowing authorized users with the proper permissions to view the data. While permissions are granted onchain through smart contracts, the actual **decryption call occurs off-chain in the frontend application**.
{% hint style="info" %}
To run this example correctly, make sure the files are placed in the following directories:
* `.sol` file → `<your-project-root-dir>/contracts/`
* `.ts` file → `<your-project-root-dir>/test/`
This ensures Hardhat can compile and test your contracts as expected.
{% endhint %}
{% tabs %}
{% tab title="UserDecryptSingleValue.sol" %}
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import { FHE, euint32 } from "@fhevm/solidity/lib/FHE.sol";
import { ZamaEthereumConfig } from "@fhevm/solidity/config/ZamaConfig.sol";
/**
* This trivial example demonstrates the FHE decryption mechanism
* and highlights common pitfalls developers may encounter.
*/
contract UserDecryptSingleValue is ZamaEthereumConfig {
euint32 private _trivialEuint32;
// solhint-disable-next-line no-empty-blocks
constructor() {}
function initializeUint32(uint32 value) external {
// Compute a trivial FHE formula _trivialEuint32 = value + 1
_trivialEuint32 = FHE.add(FHE.asEuint32(value), FHE.asEuint32(1));
// Grant FHE permissions to:
// ✅ The contract caller (`msg.sender`): allows them to decrypt `_trivialEuint32`.
// ✅ The contract itself (`address(this)`): allows it to operate on `_trivialEuint32` and
// also enables the caller to perform user decryption.
//
// Note: If you forget to call `FHE.allowThis(_trivialEuint32)`, the user will NOT be able
// to user decrypt the value! Both the contract and the caller must have FHE permissions
// for user decryption to succeed.
FHE.allowThis(_trivialEuint32);
FHE.allow(_trivialEuint32, msg.sender);
}
function initializeUint32Wrong(uint32 value) external {
// Compute a trivial FHE formula _trivialEuint32 = value + 1
_trivialEuint32 = FHE.add(FHE.asEuint32(value), FHE.asEuint32(1));
// ❌ Common FHE permission mistake:
// ================================================================
// We grant FHE permissions to the contract caller (`msg.sender`),
// expecting they will be able to user decrypt the encrypted value later.
//
// However, this will fail! 💥
// The contract itself (`address(this)`) also needs FHE permissions to allow user decryption.
// Without granting the contract access using `FHE.allowThis(...)`,
// the user decryption attempt by the user will not succeed.
FHE.allow(_trivialEuint32, msg.sender);
}
function encryptedUint32() public view returns (euint32) {
return _trivialEuint32;
}
}
```
{% endtab %}
{% tab title="UserDecryptSin프로젝트로 돌아가기