bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 23쪽
einput` type that refers to a particular ciphertext in the list. The list itself is serialized and passed as a byte array. For example, `inputA` and `inputB` refer to ciphertexts in the list and the serialized list is `inputProof`:
```solidity
// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.24;
import "fhevm/lib/FHE.sol";
contract Adder {
euint32 result;
function add(externalEuint32 inputA, externalEuint32 inputB, bytes calldata inputProof) public {
euint32 a = FHE.fromExternal(inputA, inputProof);
euint32 b = FHE.fromExternal(inputB, inputProof);
result = FHE.add(a, b);
FHE.allow(result, address(this));
}
}
```
Note that `inputProof` also contains the ZKPoK.
## Overview of the input mechanism
Handling inputs requires a few steps. The first one is for the user to retrieve public key material from the Gateway. The second is to encrypt plaintext inputs and compute the associated ZKPoK. Last step is to use inputs as "usual" inputs in a smart contract.
### Public key material and CRS retrieval
The first step to generate an encrypted input is to retrieve the blockchain related FHE public key material. The Gateway is the component the user queries to get that material.
The Gateway is exposing a `/keys` endpoint that returns the FHE public key and CRS alongside a signature. Users are able to verify them using KMSVerifier smart contract.
### Encryption phase
In this phase, the user encrypts the plaintext input with the FHE public key to get ciphertext `C` and compute the proof `ZkPoK`. `C` is bounded to be used with a `contractAddress` and by a `callerAddress`. The goal is for `C` to be signed the KMS to enable the usage of the input within smart contracts later.
C == ciphertext - Encrypted with the blockchain FHE public key
ZKPoK == Zero-Knowledge Proof of Knowledvge - Computed on the user side
eInput == type + index
S == Signature
```
struct CVerificationStructForKMS {
address contractAddress;
bytes32 hashOfCiphertext;
address callerAddress;
}
```
```mermaid
sequenceDiagram
participant User
participant Gateway
participant KMS Blockchain
participant KMS Core
User->>Gateway: 1. (C, contractAddr, callerAddr, ZKPoK)
Gateway->>KMS Blockchain: 2. VerifyInput(C, contractAddr, callerAddr, ZKPoK)
KMS Blockchain->>KMS Core: 3. VerifyInput(C, contractAddr, callerAddr, ZKPoK)
Note over KMS Core: 4. Verify ZkPoK
Note over KMS Core: 5. KMS_S = Sign(CVerificationStructForKMS)
KMS Core->>KMS Blockchain: 6. KMS_S
KMS Blockchain->>Gateway: 7. KMS_S
Gateway->>User: 8. KMS_S
```
### Usage
When the user receives the KMS signature, it means that the ZKPoK has been verified by the KMS and the input could be used within FHEVM. This is quite useful because on the FHEVM only the KMS signature will be verified and that is faster than verifying a ZkPoK.
```mermaid
sequenceDiagram
participant User
participant FHEVM
User->>FHEVM: (eInput, C, KMS_S)
Note over FHEVM: Reconstruct CVerificationStructFromKMS
Note over FHEVM: Verify KMS_S
```
# Symbolic Execution
Symbolic execution is a method of constructing a computational graph of FHE operations without actually doing the FHE computation. It works by utilizing what we call a ciphertext **handle**. The handle could be thought of as an unique "pointer" to a given FHE ciphertext.and is implemented as a 32-byte value that is a result of applying a hash function to either an FHE ciphertext or other handles. Symbolic execution also checks constraints on input handles (e.g. the access control list, whether types match, etc.).
Symbolic execution onchain is implemented via the [FHEVMExecutor](https://github.com/zama-ai/fhevm/blob/release/0.10.x/coprocessor/contracts/contracts/FHEVMExecutor.sol) contract. One of its main responsibilites is to deterministically generate ciphertext handles. For this, we hash the FHE operation requested and the inputs to produce the result handle H:
```
H = keccak256(fheOperation, input1, input2, ..., inputN)
```
Inputs can either be other handles or plaintext values.
## FHE Computation Data Dependencies
Note that FHEVM-native and FHEVM-coprocessor send both input handles and result handles for FHE computation. It is able to do that, because result handles are computed symbolically in the FHEVMExecutor contract. That allows for parallel FHE computation by analysing which computations are independent.
The Executor or Coprocessor can detect a conflict if an output of computation A (or the output of another computation depending on the output of A) is also used as an input in a subsequent computation B. We call these computations `dependent` and we need to execute them in order.
On the other hand, if two computations have inputs that are not related to their outputs, we call them `independent` and can schedule them to run in parallel.
# coprocessor
# Architecture
The following diagram shows an FHEVM-coprocessor that is integrated alongside an existing host blockchain.
```mermaid
graph LR;
dApp[dApp]
fhevmjs[fhevmjs]
Host(((Host Blockchain)))
Coprocessor(Coprocessor)
Gateway(Gateway)
DA[(DA)]
TKMS[TKMS]
dApp-- uses ---fhevmjs
fhevmjs-- Host Blockchain API ---Host
Host-- P2P ---Coprocessor
Host <--> |Host Blockchain API| Gateway
fhevmjs-- Reencrypt API---Gateway
fhevmjs-- Inputs API ---Gateway
Gateway-- TKMS txns, events ---TKMS
Gateway-- Inputs API ---Coprocessor
Coprocessor-- DA API ---DA
```
An important note to point out is that the Coprocessor is an offchain component. It contains the following sub-components:
* host blockchain **full node** that executes all blocks on the host blockchain
* an **executor** that does FHE computation
* a local **database** for storing FHE ciphertexts
Essentially, as the Coprocessor executes blocks and when an FHE operation is detected, the executor sub-component would actually execute the FHE computation and load/store FHE ciphertexts from the local database (and the DA). For more on execution, please look at [Symbolic Execution](/protocol/solidity-guides/v0.10/coprocessor/docs/fundamentals/fhevm/symbolic_execution) and [FHE Computation](/protocol/solidity-guides/v0.10/coprocessor/docs/fundamentals/fhevm/coprocessor/fhe_computation).
The Data Availability (DA) is a publicly-verifiable database that is a mirror of the local Coprocessor database. The reason for having is to allow anyone to verify the behaviour of the Coprocessor by examining the results it posts to it.
The Gateway is responsible for handling input verification, decryption and reencryption and host blockchain validator set updates, all via/in the KMS.
# FHE Computation
Block execution in FHEVM-coprocessor is split into two parts:
* Symbolic Execution (onchain)
* FHE Computation (offchain)
Symbolic execution happens onchain, inside the [FHEVMExecutor](https://github.com/zama-ai/fhevm/blob/release/0.10.x/coprocessor/contracts/contracts/FHEVMExecutor.sol) contract (inside the EVM). Essentially, the EVM accumulates all requested FHE operations in a block with their input handles and the corresponding result handles. Then, at the end of block execution, it sends an `AsyncCompute` request to the coprocessor such that FHE computation can be done **eventually**. Note that FHE computation can be done at a future point in time, after the block has been committed on the host blockchain. We can do that, symbolic execution only needs handles and doesn't actual FHE ciphertexts. Actual FHE ciphertexts are needed only on **decryption** and **reencryption**, i.e. when a user wants to see the plaintext value.
```mermaid
sequenceDiagram
participant Full Node
participant Coprocessor
participant DB
loop Block Execution - Symbolic
Note over Full Node: Symbolic Execution on handles in Solidity
Note over Full Node: Inside EVM: computations.add(op, [inputs], [result_handles])
end
Note over Full Node: End of Block Execution
Full Node->>+Coprocessor: AsyncCompute (AsyncComputeRequest(computations))
Coprocessor->>+DB: Insert Computations
DB->>-Coprocessor: Ack
Coprocessor->>-Full Node: AsyncComputeResponse
loop FHE Computation
Coprocessor --> DB: Read Input Ciphertexts
Note over Coprocessor: FHE Computation
Coprocessor --> DB: Write Result Ciphertexts
end
```
For more on symbolic execution, please see [Symbolic Execution](/protocol/solidity-guides/v0.10/coprocessor/docs/fundamentals/fhevm/symbolic_execution).
Note that, for now, we omit the Data Availability (DA) layer. It is still work in progress and the Coprocessor only inserts FHE ciphertexts into its local DB. Eventually, we would like that FHE ciphertexts are also inserted into the DA.
## Parallel Execution
Since the Coprocessor can extract data dependencies from the `AsyncCompute` request, it can use them to execute FHE computations in parallel.
At the time of writing, the Coprocessor uses a simple policy to schedule FHE computation on multiple threads. More optimal policies will be introduced in the future and made configurable.
# native
# Architecture
The following diagram shows an FHEVM-native blockchain with 4 validators.
```mermaid
graph LR;
Validator1{{Validator1 Node}}
Validator1-- execution API ---Executor1
Executor1(Executor1)
Validator2{{Validator2 Node}}
Validator2-- execution API ---Executor2
Executor2(Executor2)
Validator3{{Validator3 Node}}
Validator3-- execution API ---Executor3
Executor3(Executor3)
Validator4{{Validator4 Node}}
Validator4-- execution API ---Executor4
Executor4(Executor4)
FullNode{{Full Node}}
FullNode-- execution API ---ExecutorFull
ExecutorFull(Executor F)
dApp[dApp]
fhevmjs[fhevmjs]
dApp-- uses ---fhevmjs
fhevmjs-- HTTP ---Gateway
fhevmjs-- RPC ---FullNode
Gateway(((Gateway)))
Gateway-- TKMS txns, events ---TKMS
Gateway-- RPC/WebSocket ---FullNode
TKMS[[TKMS]]
```
*Note:* For brevity, we don't show P2P connections between validators and the full node in the diagram.
Each validator has two components:
* the validator node software that executes blocks and connects to other validators over the blockchain's P2P network
* the Executor that is responsible for the actual FHE computation
The Executor exposes an API that the validator node uses to send FHE computation requests.
A full node is similar to validators in the sense that it executes all blocks. The difference is that the full node doesn't have stake in the network and, therefore, cannot propose blocks. The full node has all the blockchain data locally. It can be used by the Gateway over RPC or WebSocket endpoints, allowing the Gateway to fetch storage proofs, fetch ciphertexts, listen for events on the FHEVM blockchain, etc.
The Gateway is a client from the TKMS' perspective and sends decryption/reencryption transactions, listens for "decryption ready" events, etc.
A dApp uses the **fhevmjs** library to interact with the FHEVM. Some examples are:
* connect over HTTP to the Gateway for reencryptions
* encrypt and decrypt data from the blockchain
* send transactions via a full node
* get the FHE public key from a full node
The TKMS is used to manage secret FHE key material and securely execute decryptions, reencryptions, key generation, etc. The TKMS is itself a blockchain. See [TKMS](/protocol/solidity-guides/v0.10/coprocessor/docs/fundamentals/tkms/architecture).
# FHE Computation
Block execution in FHEVM-native is split into two parts:
* Symbolic Execution
* FHE Computation
Symbolic execution happens onchain, inside the [FHEVMExecutor](https://github.com/zama-ai/fhevm/blob/release/0.10.x/coprocessor/contracts/contracts/FHEVMExecutor.sol) contract (inside the EVM). Essentially, the EVM accumulates all requested FHE operations in a block with their input handles and the corresponding result handles. It also remembers which result handles are stored via the SSTORE opcode. No FHE computations are done inside the EVM itself.
For more on symbolic execution, please see [Symbolic Execution](/protocol/solidity-guides/v0.10/coprocessor/docs/fundamentals/fhevm/symbolic_execution).
At the end of the block, the EVM sends a networking call to the Executor with the accumulated FHE computations. The Executor is free to do the FHE computations via any method, e.g. in parallel, on a cluster of compute nodes, via CPUs, GPUs, FPGAs or ASICs. The EVM waits until FHE computation for the block is done.
Finally, when results are returned to the EVM, it persists onchain the ciphertexts whose handles have been SSTOREd during symbolic execution. That way the EVM can avoid persisting ciphertexts that are intermediate results and are never actually stored by the smart contract developer.
```mermaid
sequenceDiagram
participant Node
participant Executor
loop Block Execution - Symbolic
Note over Node: Symbolic Execution on handles in Solidity
Note over Node: Inside EVM: computations.add(op, [inputs], [result_handles], [input_ciphertexts])
Note over Node: Inside EVM: if SSTORE(location, result) then sstored.add(result)
end
Note over Node: End of Block Execution
Node->>+Executor: SyncCompute (SyncComputeRequest(computations))
loop FHE Computation
Note over Executor: Read Inputs from SyncComputeRequest
Note over Executor: FHE Computation
end
Executor->>-Node: SyncComputeResponse (results)
Note over Node: Persist `sstored` Ciphertexts from `results` onchain
Note over Node: Commit Block
```
## Interaction with the FHEVMExecutor Contract
The [FHEVMExecutor](https://github.com/zama-ai/fhevm/blob/release/0.10.x/coprocessor/contracts/contracts/FHEVMExecutor.sol) contract is deployed when the chain is created and is at a well-known address that is also known by blockchain nodes. When a node (validator or full node) detects a call to this address (a CALL or STATICCALL opcode), the EVM running in the node looks at the function signature and determines which FHE computation is being requested. The result handle is the result of this particular call to the FHEVMExecutor contract and the EVM can accumulate it in the computations list for the block.
## Scheduling Policies
Since the Executor can extract data dependencies from the `SyncCompute` request, it can use them to execute FHE computations in parallel.
Different scheduling policies can be set for FHE computation via the `FHEVM_DF_SCHEDULE` environment variable with possible choices: **LOOP**, **FINE\_GRAIN**, **MAX\_PARALLELISM**, **MAX\_LOCALITY**.
# Genesis
## Contracts
For an FHEVM-native blockchain to operate and execute FHE computations, certain contracts need to be available when creating the chain - see [Contracts](/protocol/solidity-guides/v0.10/coprocessor/docs/fundamentals/fhevm/contracts). Strictly speaking, these contracts don't have to be available in the genesis block and can be deployed in the second block of the chain, at runtime.
## Keys
FHE-related keys need to available for the chain to operate properly. For example, a public FHE execution key is needed at the Executor to be able to compute on encrypted data.
As a convenience, the FHE public key can also be stored on validators/full nodes.
# Storage
Ciphertexts in FHEVM-native are stored onchain in the storage of a predefined contract that has no code and is used just for ciphertexts. At the time of writing, its address is **0x5e**.
Contract storage in the EVM is a key-value store. For ciphertexts, we use the handle as a key and the value is the actual ciphertext.
Furthermore, stored ciphertexts are immutable, making ciphertext storage append-only.
Ciphertexts can be read by anyone. We expose the `GetCiphertext` function on the `FheLib` precompiled contract. Nodes/validators must support it.
## GetCiphertext Function (selector: ff627e77)
The `GetCiphertext` function returns a serialized TFHE ciphertext given:
* the ebool/e(u)int value (also called a handle) for which the ciphertext is requested
GetCiphertext only works via the `eth_call` RPC.
To call GetCiphertext via `eth_call`, the following Python can serve as an example:
```python
import http.client
import json
# This is the address of the FheLib precompile. This value is hardcoded per blockchain.
fhe_lib_precompile_address = "0x000000000000000000000000000000000000005d"
# The ebool/e(u)int value for which the ciphertext is requested.
handle = "f038cdc8bf630e239f143abeb039b91ec82ec17a8460582e7a409fa551030c06"
# The function selector of GetCiphertext.
get_ciphertext_selector = "ff627e77"
# Call the FheLib precompile with `data` being the handle to the ciphertext.
payload = {
"jsonrpc": "2.0",
"method": "eth_call",
"params": [
{
"to": fhe_lib_precompile_address,
"data": "0x" + handle
},
"latest"
],
"id": 1,
}
con = http.client.HTTPConnection("localhost", 8545)
con.request("POST", "/", body=json.dumps(payload),
headers={"Content-Type": "application/json"})
resp = json.loads(con.getresponse().read())
# Remove leading "0x" and decode hex to get a byte buffer with the ciphertext.
ciphertext = bytes.fromhex(resp["result"][2:])
```
# gateway
# Decryption and reencryption request on TKMS
# Decryption
Everything in FHEVM is encrypted, at some point one could need to decrypt somes values. Let's give as illustration a blind auction application. After reaching the end of the auction, one need to discover (only) the winner, here is where a asynchronous decrypt could appear.
> :warning: **Decryption is public**: It means everyone will be able to see the value. If this is a personal information see [Reencryption](/protocol/solidity-guides/v0.10/coprocessor/docs/fundamentals/gateway/reencryption)
## How it's working
The Gateway acts as an oracle service: it will listen to decryption request events and return the decrypted value through a callback function. The responsabilities of the Gateway are:
* Listening decryption request from FHEVM that contains a handle `h` that corresponds to a ciphertext `C`
* Computing a storage proof `P` to attest h (i.e. C) is decryptable
* Retrieve C from FHEVM using `h` as key
* Send a decyption request to TKMS which in turn is running an internal blockchain aka `KMS BC`
* Wait and listen for `decyptionResponse` (containing the plaitext and a few signatures from KMS to attest the integrity of the palintext) event from `KMS BC`
* Return `decyptionResponse` through the callback function
## High level overview of the decryption flow
We allow explicit decryption requests for any encrypted type. The values are decrypted with the network private key.

# Inclusion Proof
The execution layer in FHEVM can perform computations on ciphertexts. At some point, it becomes necessary to reveal the actual values of these ciphertexts. However, the private key is managed by the KMS (Key Management System). The question arises: how can we perform asynchronous decryption requests (which make the values public) and re-encryptions (for personal information) when the execution layer and the KMS are decoupled? This is where inclusion proofs come into play.
## How to Compute an Inclusion Proof
## Verification of the Proof in KMS BC ISC
## Notes on Root Hash Verification
This section will be elaborated upon in the future to explain the validation of root hash integrity.
# Reencryption
Reencryption is performed on the client side by calling the gateway service using the [fhevmjs](https://github.com/zama-ai/fhevmjs/) library. To do this, you need to provide a view function that returns the ciphertext to be reencrypted.
1. The dApp retrieves the ciphertext from the view function (e.g., balanceOf).
2. The dApp generates a keypair for the user and requests the user to sign the public key.
3. The dApp calls the gateway, providing the ciphertext, public key, user address, contract address, and the user's signature.
4. The dApp decrypts the received value with the private key.
# tkms
# Architectu프로젝트로 돌아가기