bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 27쪽
ult Ciphertexts
Coprocessor-->>DB: TFHE Operation Done
end
DB-)Scheduler: Notice TFHE Operations Status<br/>(proposal)
Scheduler-)Relayer: Notice Ciphertext ready for decryption
```
# Switch-and-Squash executor
## Description
### Library crate
Upon receiving a notification, it mainly does the following steps:
* Fetches `(handle, compressed_ct)` pairs from `pbs_computations` and `ciphertexts` tables.
* Computes `large_ct` using the Switch-and-Squash algorithm.
* Updates the `large_ct` column in the `ciphertexts` table for the corresponding handle.
* Emits an event indicating the availability of the computed `large_ct`.
#### Features
**decrypt\_128** - Decrypt each `large_ct` and print it as a plaintext (for testing purposes only).
### Binary (sns-worker)
Runs sns-executor. See also `src/bin/utils/daemon_cli.rs`
## Running a SnS Worker
### The SnS key can be retrieved from the Large Objects table (pg\_largeobject). Before running a worker, the sns\_pk should be imported into tenants tables as shown below. If tenants table is not in use, then keys can be passed with CLI param --keys\_file\_path
```sql
-- Example query to import sns_pk from fhevm-keys/sns_pk
-- Import the sns_pk into the Large Object storage
sns_pk_loid := lo_import('../fhevm-keys/sns_pk');
-- Update the tenants table with the new Large Object OID
UPDATE tenants
SET sns_pk = sns_pk_loid
WHERE tenant_id = 1;
```
### Multiple workers can be launched independently to perform 128-PBS computations.
```bash
# Run a single instance of the worker
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/coprocessor \
cargo run --release -- \
--tenant-api-key "a1503fb6-d79b-4e9e-826d-44cf262f3e05" \
--pg-listen-channels "event_pbs_computations" "event_ciphertext_computed" \
--pg-notify-channel "event_pbs_computed" \
```
## Testing
* Using `Postgres` docker image
```bash
# Run Postgres as image, execute migrations and populate the DB instance with keys from fhevm-keys
cargo test --release -- --nocapture
```
* Using localhost DB
```bash
# Use COPROCESSOR_TEST_LOCALHOST_RESET to execute migrations once
COPROCESSOR_TEST_LOCALHOST_RESET=1 cargo test --release -- --nocapture
# Then, on every run
COPROCESSOR_TEST_LOCALHOST=1 cargo test --release
```
# Coprocessor stress test generator
Generator for coprocessor stress tests
## Configuration
### Environment variables
* EVGEN\_SCENARIO (default: data/evgen\_scenario.csv)
* EVGEN\_DB\_URL (default: postgresql://postgres:postgres\@127.0.0.1:5432/coprocessor)
* ACL\_CONTRACT\_ADDRESS (default: 0x05fD9B5EFE0a996095f42Ed7e77c390810CF660c)
* CHAIN\_ID (default: 12345)
* API\_KEY (default: a1503fb6-d79b-4e9e-826d-44cf262f3e05)
* TENANT\_ID (default 1)
* SYNTHETIC\_CHAIN\_LENGTH (default: 10): used in synthetic benches (MULChain, ADDChain) for the length of each transaction
* MIN\_DECRYPTION\_TYPE (default: 0): lowest type to generate (0 -> FheBool, 1 -> FheUint4, ...)
* MAX\_DECRYPTION\_TYPE (default: 6 -> FheUint128)
* OUTPUT\_HANDLES\_FOR\_PUB\_DECRYPTION (default: data/handles\_for\_pub\_decryption)
* OUTPUT\_HANDLES\_FOR\_USR\_DECRYPTION (default: data/handles\_for\_usr\_decryption)
### Scenario files
The format is semicolon separated CSV with the following order:
* Transaction type. Possible values are ERC20Transfer, DEXSwapRequest, DEXSwapClaim, MULChain, ADDChain, InputVerif, GenPubDecHandles, GenUsrDecHandles.
* ERC transfer variant (only meaningful for ERC transfer using transactions). Possible values are Whitepaper, NoCMUX, NA,
* Generator target. Either **Rate** or **Count**. Rate is in transactions generated per second. This refers to the trailing values added in the CSV line which supply pairs (rate/count, duration/count)
* Inputs. Either **ReuseInputs** or **NewInputs** - whether to generate new inputs for each transaction (so encrypt, generate proof and send for verification) or just generate some random inputs at start then reuse the same inputs to avoid the delay of round-tripping the zkproof-worker.
* Dependence. Either **Dependent** or **Independent** - whether the transactions will be chained together or ran independently (e.g. Dependent on ERC transfer means that all transfers generated in the scenario will transfer to the same destination wallet).
* Contract address
* User address
* Scenario specification: unlimited sequence of pairs (float, integer) specifying the rate/count and duration to run the generator for. E.g. **1.1; 20; 3.4; 10** if using a **Rate** target means that the generator will issue on average 1.1 transactions per second for 20 seconds then 3.4 transactions per second for 10 seconds. If the target is **Count**, then it will generate a batch of 1.1\*20=22 transactions followed by a batch of 34 transactions.
## REST API
In addition to running the stress\_generator as a CLI tool for triggering stress tests, it can also run as a standalone service on a remote machine, exposing the following APIs. The service enforces a single active job at a time, ensuring accurate performance metric collection.
* POST job - Enqueue a new job (a set of scenarios)
* GET /job/:id - Get status of a specific job by job\_id
* GET /status/running - Get job\_id of the running job
* GET /status/queued - List all queued jobs in the order they will run
### How to run
```bash
# Configure all ENV variables except EVGEN_SCENARIO
# Run as a server
cargo run --release -- --run-server --listen-address 127.0.0.1:3030
# Choose/prepare a json from 'data/json' files
# Post a job
curl -X POST http://localhost:3030/job \
-H "Content-Type: application/json" \
-d @./data/json/minitest_002_erc20.json
# Get a job result
curl -X GET http://localhost:3030/job/0
```
# Fhevm Coprocessor
## Dependencies installation
* `docker-compose`
* `rust`
* `sqlx-cli`:
```
cargo install sqlx-cli
```
## Development
Start the database
```
docker compose up -d
```
Export database url for development
```
export DATABASE_URL="postgres://postgres:postgres@localhost/coprocessor"
```
Create the database
```
sqlx db create
```
Run the migrations
```
sqlx migrate run
```
## Debugging database
Exec into postgresql shell
```
docker exec -u postgres -it fhevm-coprocessor-db-1 psql coprocessor
```
## Running tests
```
cargo test
```
## Running the first working fhevm coprocessor smoke test
Reload database and apply schemas from scratch
```
make recreate_db
```
Run the server and background fhe worker
```
cargo run -- --run-server --run-bg-worker --worker-polling-interval-ms 1000
```
# gateway-contracts
### Introduction
The **FHEVM Gateway** is a set of smart contracts that enables decrypting FHE ciphertexts from different host chains. It acts as an intermediary between the chains, the Key Management Service (KMS) and the coprocessors found within the FHEVM protocol. These contracts are responsible for:
* Verifying the legitimacy of decryption requests
* Centralizing multi-chain ciphertexts access
* Centralizing multi-chain ciphertexts commitments
* Orchestrating KMS materials
* Orchestrating protocol payments
### Main features
| Contract | Description | Features |
| ------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `CiphertextCommits` | Store ciphertext commitments from all host chains | <p>- Store regular ciphertext commitments<br>- Store Switch and Squash (SNS) ciphertext commitments</p> |
| `Decryption` | Decrypt FHE ciphertexts | <p>- Request a public decryption<br>- Request a user decryption<br>- Request a delegated user decryption</p> |
| `GatewayConfig` | Administer configuration settings | <p>- Register KMS nodes, coprocessors and host chains.<br>- Update KMS nodes, coprocessors and host chains.</p> |
| `InputVerification` | Verify an input's zero-knowledge proof of knowledge (ZKPoK) | <p>- Verify a ZKPoK<br>- Reject a ZKPoK</p> |
| `KMSGeneration` | Orchestrate KMS-related materials | <p>- Trigger generation of FHE keys<br>- Trigger generation of CRS</p> |
| `MultichainACL` | Centralize Access Control Lists (ACL) from all host chains | <p>- Grant account access to ciphertexts<br>- Authorize public decryption of ciphertexts<br>- Delegate account access to ciphertexts</p> |
| `ProtocolPayment` | Orchestrate protocol payments | <p>- Define operation prices<br>- Transfer protocol fees to FeesSenderToBurner contract fees</p> |
| `PauserSet` | Administer pauser role | - Register, remove and swap pauser addresses |
### Getting started
Documentation can be found [here](/protocol/solidity-guides/v0.10/gateway-contracts/docs/summary).
### Support
🌟 If you find this project helpful or interesting, please consider giving it a star on GitHub! Your support helps to grow the community and motivates further development.
[](https://github.com/zama-ai/fhevm/)
# Welcome to fhevm Gateway
The fhevm Gateway.
## Get started
Learn the basics of fhevm Gateway, set it up, and make it run with ease.
### References
### Supports
Ask technical questions and discuss with the community. Our team of experts usually answers within 24 hours in working days.
* [Community forum](https://community.zama.ai/c/fhevm/15)
* [Discord channel](https://discord.com/invite/zama)
* [Telegram](https://t.me/+Ojt5y-I7oR42MTkx)
### Developers
Collaborate with us to advance the FHE spaces and drive innovation together.
* [See the latest test release note](https://github.com/zama-ai/fhevm-gateway/releases)
* [Request a feature](https://github.com/zama-ai/fhevm-gateway/issues/new/choose)
* [Report a bug](https://github.com/zama-ai/fhevm-gateway/issues/new/choose)
# Table of contents
* [Welcome to fhevm Gateway](/protocol/solidity-guides/v0.10/gateway-contracts/docs)
## Getting Started
* Deployment
* [Deploy contracts locally](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/deployment/local_deploy)
* [Deploy contracts in Docker](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/deployment/docker_deploy)
* Contracts
* [GatewayConfig](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/contracts/gateway_config)
* [KMSGeneration](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/contracts/kms_generation)
* [PauserSet](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/contracts/pauser_set)
* Pausing
* [Pausing mechanism](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/pausing/pausing)
# references
# Smart Contract selectors
All smart contract selectors can be found in the [contract selectors](https://github.com/zama-ai/fhevm/blob/release/0.10.x/gateway-contracts/selectors.txt) file.
# getting-started
# contracts
# GatewayConfig contract
This section describes the `GatewayConfig` contract. It is used to configure settings for the fhevm Gateway protocol.
Several settings are stored in the contract, which can be separated in several categories:
* [Protocol metadata](#protocol-metadata)
* [Operators](#operators)
* [Governance](#governance)
* [Host chains](#host-chains)
Except for host chains, they are all set when deploying the `GatewayConfig` contract. Once set, some (but not all) of them can be updated.
## Protocol metadata
The protocol metadata is used to display information about the protocol. It includes:
* `name` : name of the protocol.
* `website` : website of the protocol.
Currently, it is set at deployment but it is not possible to update them later on.
## Operators
The operators include the Key Management Service (KMS) nodes and coprocessors. Each operator needs to be registered in the `GatewayConfig` contract in order to be able to participate in the fhevm protocol.
They serve different purposes, which are described below.
### KMS Node
A KMS node is part of a set of multiple nodes. Often called the KMS, it refers to a Multi-Party Computation (MPC) protocol that manages Fully Homomorphic Encryption (FHE) keys in a decentralized manner. It is used to :
* decrypt ciphertexts based on requests from the `Decryption` contract.
* generate [KMS public materials](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/contracts/kms_generation#public-material-generation) based on requests from the `KMSGeneration` contract.
Several metadata are stored for each KMS node:
* `txSenderAddress` : see [Sender and signer](#sender-and-signer) below. In the fhevm protocol, this account is also called the KMS connector.
* `signerAddress` : see [Sender and signer](#sender-and-signer) below.
* `ipAddress` : IP address of the KMS node.
* `storageUrl` : URL of the storage where the KMS public materials are stored. In the fhevm protocol, this URL is fetched by the coprocessors in order to download the KMS public materials needed for FHE computations.
The fhevm Gateway has a single KMS, which must be constituted of at least 1 node.
Currently, they are set at deployment and it is currently *not* possible to add or remove a KMS node to the fhevm Gateway later on.
### KMS thresholds
#### MPC threshold
Additionally, a MPC threshold needs to be attached to a set of KMS nodes. This `mpcThreshold` is a cryptographic parameter used by the KMS nodes for executing the MPC protocol and thus is accessible through the `getMpcThreshold` view function.
The MPC threshold should be strictly less than the number of registered KMS nodes.
This threshold is set at deployment and can be updated by the owner later on, as long as the above conditions are met.
#### Decryption thresholds
The decryption thresholds are used to determine the minimum number of valid responses from KMS nodes required to validate a decryption, also called "consensus", in the `Decryption` contract.
There are currently two thresholds:
* `publicDecryptionThreshold` : the minimum number of valid responses from KMS nodes required to validate a public decryption
* `userDecryptionThreshold` : the minimum number of valid responses from KMS nodes required to validate a user decryption
Both thresholds should be :
* non-null: decryption consensuses should require at least one vote
* less or equal to the number of registered KMS nodes: decryption consensuses should not require more than the number of registered KMS nodes
These thresholds are set at deployment and can be updated by the owner later on, as long as the above conditions are met.
#### KMS generation threshold
The KMS generation threshold `kmsGenThreshold` is used to determine the minimum number of valid responses from KMS nodes required to validate a KMS public material generation (FHE key, CRS).
This threshold should be :
* non-null: it should require at least one vote
* less or equal to the number of registered KMS nodes: it should not require more than the number of registered KMS nodes
This threshold is set at deployment and can be updated by the owner later on, as long as the above conditions are met.
### Coprocessor
A coprocessor is also part of a set of multiple coprocessors. They are used to :
* perform FHE computations on ciphertexts
* verify inputs' zero-knowledge proof of knowledge (ZKPoK) based on requests from the `InputVerification` contract
* handle access controls to ciphertexts for all registered [host chains](#host-chains), which are centralized in the `MultichainACL` contract
Several metadata are stored for each coprocessor:
* `txSenderAddress` : see [Sender and signer](#sender-and-signer) below.
* `signerAddress` : see [Sender and signer](#sender-and-signer) below.
* `s3BucketUrl` : URL of the S3 bucket where the ciphertexts are stored. In the fhevm protocol, this URL is fetched by the KMS connector in order to download the ciphertexts needed for decryption requests.
The fhevm Gateway has a single set of coprocessors, which must be constituted of at least 1 coprocessor.
Currently, they are set at deployment and it is currently *not* possible to add or remove a coprocessor to the fhevm Gateway later on.
### Sender and signer
Despite the above differences, each operator has both a transaction sender and a signer assigned to it:
* `txSenderAddress` : address of the account that will send transactions to the fhevm Gateway.
* `signerAddress` : address associated to the public key used to sign results sent to the fhevm Gateway.
The current list of transaction senders and signers can be retrieved using the following view functions:
* `getKmsTxSenders()`: get all the KMS nodes' transaction senders.
* `getKmsSigners()`: get all the KMS nodes' signers.
* `getCoprocessorTxSenders()`: get all the coprocessors' transaction senders.
* `getCoprocessorSigners()`: get all the coprocessors' signers.
The transaction sender and signer addresses are allowed to be the same for a given operator.
Additionally, the transaction sender address is used for identifying an operator and may be referred to its "identity". In particular, these addresses can be used as inputs to following view functions in the `GatewayConfig` contract:
* `getKmsNode(address kmsTxSenderAddress)`: get a KMS node's metadata.
* `getCoprocessor(address coprocessorTxSenderAddress)`: get a coprocessor's metadata.
## Governance
The fhevm Gateway protocol is governed by the following roles:
* `owner`: account that can perform restricted actions
* `pausers`: accounts that can pause contract functions
### Owner
The owner is first set as the account that deploys the contracts (the deployer). It is allowed to perform several restricted actions :
* upgrade the contracts
* update the pausers (see [Pausers](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/contracts/pauser_set))
* add [host chains](#host-chains)
* trigger a KMS public material generation (see [KMSGeneration](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/contracts/kms_generation#public-material-generation))
The owner is handled by OpenZeppelin's `Ownable2StepUpgradeable` contract. In particular, this means that the deployer can transfer its ownership to another account in a two-step process.
### Pausers
Details about pausers are available in the following documentation:
* [PauserSet](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/contracts/pauser_set)
* [Pausing](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/pausing/pausing)
### Host chains
Host chains are host chains registered to the protocol. Only ciphertexts generated on registered host chains are allowed to be verified by coprocessors and decrypted by the KMS.
Several metadata are stored for each host chain:
* `chainId` : unique identifier of the host chain. Unlike typical chain IDs, its value is limited to 64 bits.
* `fhevmExecutorAddress` : address of the `FHEVMExecutor` fhevm contract deployed on the host chain.
* `aclAddress` : address of the `ACL` fhevm contract deployed on the host chain.
* `name` : name associated to the host chain.
* `website` : website associated to the host chain.
Host chains are not set at deployment and are instead added through the `addHostChain` function by the owner. It is however currently not possible to remove them later on.
# KMSGeneration contract
This section describes the `KMSGeneration` contract. It is used to orchestrate public KMS-related materials for the fhevm Gateway protocol. More information about can be found in the [KMS documentation](https://docs.zama.ai/protocol/protocol/overview/kms).
The contract is used to:
* [Generate FHE keys](#generate-fhe-keys)
* [Generate CRSs](#generate-crs)
All non-view functions are restricted to either the owner of the contract or the KMS nodes' transaction senders.
## Public material generation
The `KMSGeneration` contract is used to generate different public materials needed by the fhevm protocol.
### Generate FHE ke프로젝트로 돌아가기