Zama 백서

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

t through the `addHostChainsToGatewayConfig` task found in [addHostChains.ts](https://github.com/zama-ai/fhevm/blob/release/0.10.x/gateway-contracts/tasks/addHostChains.ts) ## Run tests Run all tests on the local network: ```bash make test-local ``` A `--skip-setup` flag is used to avoid re-deploying the contracts before running the tests. # pausing # Environment variables This section describes the environment variables used for pausing the FHEVM gateway. In the following, the values are given as examples. Most of them are from the `.env.example` file and are used for local testing. The accounts found in it are already-funded hardhat accounts generated with the following command: ```bash make get-accounts ``` ## Summary Here's the complete list of environment variables used for pausing the FHEVM gateway. More detailed information can be found in [this section](#in-details) below. Solidity types are defined in [Solidity's documentation](https://docs.soliditylang.org/en/latest/types.html). | Environment Variable | Description | Solidity Type | Default | Comment | | ---------------------- | --------------------------------- | ------------- | ------- | ------- | | `PAUSER_PRIVATE_KEY` | Private key of one of the pausers | bytes32 | - | - | | `DEPLOYER_PRIVATE_KEY` | Private key of the deployer | bytes32 | - | - | ## In details * Pauser private key: ```bash PAUSER_PRIVATE_KEY="0x3588ffb4f4d9bea785a012b895543fe68f2d580a9d449decc91a25878064079a" # (bytes32) ``` The pauser private key is the private key of one of the pausers registered in the `PauserSet` contract. It is used to pause the contracts using the pausing hardhat tasks, including the `pauseAllGatewayContracts`. Each operator are expected to set this environment variable to the private key associated to their hot wallet used as pauser. * Deployer private key ```bash DEPLOYER_PRIVATE_KEY="0x7136d8dc72f873124f4eded25f3525a20f6cee4296564c76b44f1d582c57640f" # (bytes32) ``` This is the private key of the deployer account, used to deploy the contracts (see [Deployment](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/deployment/env_variables)). If the ownership of the `GatewayConfig` contract is handled by the deployer, it can be used to unpause the contracts (see [Pausing](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/pausing/pausing)). # Pausing mechanism This section describes the pausing mechanism for the fhevm Gateway protocol. It is meant to be used in case of emergency, to pause the protocol in order to prevent any new requests (input proof, decryptions) to be processed. The Gateway can only be paused and unpaused manually. It is handled through the following contracts: * `PauserSet`: manages the pauser addresses (see [PauserSet](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/contracts/pauser_set)) * `Pausable` (abstract): provides the pausing and unpausing functionalities ## Pausing contracts A pauser is an account that can pause the following Gateway contracts: * `Decryption` * `InputVerification` A paused contract means that any transaction sent to trigger its *request* functions will be reverted. This means responses for already-sent requests will still be accepted and on-going consensus can be reached. Additionally, other view functions will still be callable. ### Decryption contract When paused, the following functions will be reverted: * `publicDecryptionRequest` * `userDecryptionRequest` * `delegatedUserDecryptionRequest` ### InputVerification contract When paused, the following functions will be reverted: * `verifyProofRequest` ## Hardhat tasks It is possible to pause and unpause the contracts through hardhat tasks defined in [pauseContracts.ts](https://github.com/zama-ai/fhevm/blob/release/0.10.x/gateway-contracts/tasks/pauseContracts.ts). ### Pausing tasks Pausing tasks are: * `pauseAllGatewayContracts`: pause all the Gateway contracts * `pauseInputVerification`: pause the `InputVerification` contract only * `pauseDecryption`: pause the `Decryption` contract only These tasks require the `PAUSER_PRIVATE_KEY` environment variable to be set locally. See [Environment variables](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/pausing/env_variables) for more details. ### Unpausing tasks Unpausing tasks are: * `unpauseAllGatewayContracts`: unpause all the Gateway contracts * `unpauseInputVerification`: unpause the `InputVerification` contract only * `unpauseDecryption`: unpause the `Decryption` contract only **Important**: These tasks are only possible if the ownership of the `GatewayConfig` contract is handled by the deployer, which requires the `DEPLOYER_PRIVATE_KEY` environment variable to be set locally (see [Environment variables](/protocol/solidity-guides/v0.10/gateway-contracts/docs/getting-started/pausing/env_variables)). Once the `GatewayConfig` contract is owned by a multi-sig owner, these tasks will not be able to unpause the contracts. Instead, `GatewayConfig` contract will need to be unpaused by calling its `unpause` function through this multi-sig contract. # host-contracts ### Introduction This node package contains the core Solidity host contracts needed to deploy an FHEVM instance on a host EVM blockchain. ### Getting started run ``` npm install ``` To run forge tests: ``` npm run forge:soldeer npm run test:forge ``` # kms-connector ### Introduction **KMS Connector** connects the KMS Core with the FHEVM Gateway smart contracts. ### Main features * Forward requests coming from the Gateway to the KMS Core * Forward responses coming from the KMS Core to the Gateway via transaction * The KMS Connector is composed of three Rust micro-services: * `GatewayListener`: listens and stores the Gateway events into a database * `KmsWorker`: forwards requests from a database to the KMS Core, and stores responses into the database * `TransactionSender`: sends the responses from the database to the Gateway via transactions ### Table of Contents * [Introduction](#introduction) * [Main features](#main-features) * [Getting Started](#getting-started) * [Configuration](#configuration) * [Configuration Precedence](#configuration-precedence) * [S3 Configuration](#s3-configuration) * [Wallet Configuration](#wallet-configuration) * [Security Considerations](#security-considerations) * [Architecture](#architecture) * [Support](#support) ### Getting Started All services consist of a single binary. The service can be started via its `start` subcommand, with or without a config file (but environment variables would then need to be used instead): ```bash ./gw-listener start --config config/gw-listener.toml KMS_CONNECTOR_DATABASE_URL="postgres://postgres:postgres@localhost" ./gw-listener start ``` ### Configuration The KMS Connector supports flexible configuration through both TOML files and environment variables. You can use either method or combine them, with environment variables taking precedence over file-based configuration. See the [configuration examples](https://github.com/zama-ai/fhevm/blob/release/0.10.x/kms-connector/config/README.md) for each service, which document all the fields of the configuration with the associated environment variable, as well as its default value. #### Configuration Precedence The configuration values are loaded in the following order, with later sources overriding earlier ones: 1. Default values (lowest priority) 2. TOML config file (if provided) 3. Environment variables (highest priority) #### S3 Configuration The KMS Connector retrieves ciphertexts from S3-compatible storage. The connector relies on the S3 URLs provided by the Gateway's events being properly formatted. If no URLs are provided, it will fall back to the optional S3 configured values. #### Wallet Configuration The KMS Connector supports two methods for configuring the wallet used for signing decryption responses: * Private key directly as a hex string * AWS KMS Wallet The connector will attempt to initialize the wallet in the following order: 1. Private key string (if provided) 2. AWS KMS configuration (if provided) At least one of these two options must be provided. **Security Considerations** * Private keys provided as strings are supported for development purposes, but should not be used in production. These keys should be handled with extreme caution to avoid exposure ### Architecture See the [architecture documentation](/protocol/solidity-guides/v0.10/kms-connector/docs/architecture) for more detail. ### 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. [![GitHub stars](https://img.shields.io/github/stars/zama-ai/fhevm?style=social)](https://github.com/zama-ai/fhevm/) # docs # KMS Connector Architecture ## Introduction The role of the KMS Connector is to forward the Gateway's events to the KMS Core and the responses of the KMS Core to the Gateway. The ambition of `fhevm` is to be able to handle thousands of decryptions per second. If the KMS Connector does not play its role, it would break the whole `fhevm` flow, so we must ensure that: * it never misses any Gateway events * it never misses any KMS Core responses * it is able to catch up events/responses in case it has been down for some time ## Architecture overview In order to achieve this, the KMS Connector has been divided into 3 components: * **GatewayListener** * Multiple listeners, so we do not miss Gateway events if one is down * Each listener listens to an RPC node of the Gateway * Each listener can have backup RPC nodes URL in case the connection with the first one is lost * Each listener tries to write the events it catches in a Postgres DB (only 1 will succeed, the others will ignore the duplicate key error) * The number of listeners should be able to scale up to avoid missing events but also to scale down to not waste resources when it is not required * **KmsWorker** * One or multiple workers * In the first place, we will probably start with only one worker * But we should be able to scale the number of workers to handle more events if required * Gets notified by the Postgres DB when new events are stored * Forwards the events' requests to the KMS Core, and stores its responses to DB * Removes the events from the DB once handled * **TransactionSender** * Only one tx sender * Gets notified by the Postgres DB when new KMS Core responses are stored * Forwards the KMS Core responses to the Gateway by submitting transactions * Removes the responses from the DB once forwarded Here is an overview of the architecture: ```mermaid block-beta columns 5 block:gateway:5 columns 3 space title1("Gateway L3") space r1["RPC node 1"] r2["RPC node 2"] r3["RPC node 3"] end space:5 block:connector:5 columns 5 space:2 title2("KMS Connector") space:2 l1["GatewayListener"] l2["GatewayListener"] l3["GatewayListener"] w["KmsWorker"] txs["TransactionSender"] end space:5 l1 -- "Listen events" --> r1 l2 -- "Listen events" --> r2 l3 -- "Listen events" --> r3 db[("DB")]:4 kms["KMS Core"] l1 -- "Put \n events" --> db l2 -- "Put \n events" --> db l3 -- "Put \n events" --> db w -- "Pick events \n & \n Put tx" --> db w -- "GRPC" --> kms kms -- "GRPC" --> w txs -- "\n Pick \n tx" --> db txs -- "Send tx" --> r3 class title1 BT1 classDef BT1 stroke:transparent,fill:transparent class title2 BT2 classDef BT2 stroke:transparent,fill:transparent ``` ## KMS Connector flow Here is an overview of the KMS Connector flow from the Gateway request event emitted to the transaction response: ```mermaid flowchart LR Gw[Gateway L3] -->|emit event| L[GatewayListener] L -->|insert event| DB[(Postgres)] DB -->|trigger notification| W[KmsWorker] W -->|GRPC request| C[KmsCore] C -->|GRPC response| W W -->|insert response| DB DB -->|trigger notification| T[TransactionSender] T -->|tx response| Gw ``` ## Database design Each event emitted by the Gateway or response received from the KMS Core has its table representation in the DB, with a notification triggered when data is inserted within this table. The `KmsWorker` and `TransactionSender` listen to these notifications and perform their jobs when a notification is received. Example with `PublicDecryptionResponse` received from the KMS Core: ```sql CREATE TABLE IF NOT EXISTS public_decryption_requests ( decryption_id BYTEA NOT NULL, sns_ct_materials sns_ciphertext_material[] NOT NULL, under_process BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMP NOT NULL DEFAULT NOW(), PRIMARY KEY (decryption_id) ); CREATE OR REPLACE FUNCTION notify_public_decryption_request() RETURNS trigger AS $$ BEGIN NOTIFY public_decryption_request_available; RETURN NULL; END; $$ LANGUAGE plpgsql; CREATE OR REPLACE FUNCTION notify_user_decryption_request() RETURNS trigger AS $$ BEGIN NOTIFY user_decryption_request_available; RETURN NULL; END; $$ LANGUAGE plpgsql; ``` Queries to insert events/responses in the DB use `ON CONFLICT DO NOTHING` to ignore concurrency errors: ```rust sqlx::query!( "INSERT INTO public_decryption_requests VALUES ($1, $2) ON CONFLICT DO NOTHING", id, sns_ciphertexts ) .execute(&db_pool) .await?; ``` When a `KmsWorker` picks events in the DB to process them, it sets the `under_process` field of the associated requests to `TRUE`, to lock these events from other workers. Then it can remove them when processed without concurrency issue: ```rust let event = sqlx::query!( " UPDATE public_decryption_requests SET under_process = TRUE FROM ( SELECT decryption_id FROM public_decryption_requests WHERE under_process = FALSE ) AS req WHERE public_decryption_requests.decryption_id = req.decryption_id RETURNING req.decryption_id, sns_ct_materials ", id ) .fetch_one(&mut db_pool) .await?; ``` Events are automatically deleted from the database when the associated response is inserted in the database. If an error happens while processing an event, the `KmsWorker` restores the `under_process` field of the associated request to `FALSE` to unlock the event. Responses are deleted from the database once the transaction to the Gateway has been successfully sent. ## Reliability ### Never miss Gateway events As we will run multiple `GatewayListener` instances, we assume that they will not crash all simultaneously, thus that all events emitted by the Gateway would be written in the DB. There is also a `from_block_number` option in its configuration, to be able to recover all events from a given block number. So even if we run only one `KmsWorker` that crashes, it will have access to unhandled events when restarted. ### Never miss KMS Core responses Until the `KmsWorker` has received a response from the KMS Core, the associated event request will stay in the DB. So if the `KmsWorker` or KMS Core crashes before the KMS Core responds, the `KmsWorker` will be able to re-pick the event from the DB and re-send the request when the connection with the KMS Core is re-established. Thus, no KMS Core responses should be missed. ### Catch up events/responses after downtime The DB notifications are used to handle events/responses while the KMS Connector's components are running. But what about events/responses that happened while the `KmsWorker` or the `TransactionSender` was down? Both the `KmsWorker` and the `TransactionSender` have a polling mechanism, in case no notification are received from the DB during a certain period of time. If that timeout is reached, they will fetch the DB for events/responses even if no notification are received. Thus, after downtime, both these services would be able to catch up missed events/responses, even if no new events/responses are produced. # library-solidity ### Introduction **FHEVM Solidity** is a Solidity library that allows developers to write confidential smart contracts with the standard Solidity development workflow. ### Main features The FHEVM Solidity library offers the following core features: * **Encrypted types**: Use encrypted integers like `euint8`, `euint16`, ..., `euint256` directly in Solidity contracts. * **Encrypted operations**: Perform operations on encrypted data using FHE-compatible functions like `add`, `sub`, `eq`, `lt`, `ternary`, etc. * **Access control**: Restrict which accounts can decrypt or update values with programmable access logic. * **Symbolic execution**: All encrypted operations are executed symbolically on the chain, with actual computation performed off-chain by the [coprocessor](/protocol/solidity-guides/v0.10/coprocessor). *See full details in the* [*Key concepts*](https://docs.zama.ai/fhevm/smart-contract/key_concepts) *section of the documentation.* ### Get started To start writing confidential smart contracts using FHEVM Solidity, follow the Hardhat setup guide here: [Getting Started with Hardhat](https://docs.zama.ai/fhevm/getting-started/overview-1/hardhat). run ``` npm install ``` To run forge tests: ``` npm run forge:soldeer npm run test:forge ``` ### Resources * [Documentation](https://docs.zama.ai/fhevm/) * [Contract examples](https://github.com/zama-ai/fhevm/blob/release/0.10.x/library-solidity/examples/README.md) ### 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. [![GitHub stars](https://img.shields.io/github/stars/zama-ai/fhevm?style=social)](https://github.com/zama-ai/fhevm/) # Security ## Reporting a Vulnerability If you find a security related bug in HTTPZ, we kindly ask you for responsible disclosure and for giving us appropriate time to react, analyze and develop a fix to mitigate the found security vulnerability. To report the vulnerability please open a draft [GitHub security advisory](https://github.com/zama-ai/fhevm-solidity/security/advisories/new) # codegen ## How to Run `codegen` in the required FHEVM packages #### To Generate FHEVM library & Tests, ```sh # @fhevm/solidity package cd library-solidity npm run codegen ``` ```sh # @fhevm/host-contracts package cd host-contracts npm run codegen ``` ```sh # End-to-End tests package cd tests-suite/e2e npm run codegen ``` #### To Regenerate Random Overloads (optional) ```sh cd library-solidity npm run codegen:overloads ``` ```sh cd host-contracts npm run codegen:overloads ``` ```sh cd tests-suite/e2e npm run codegen:overloads ``` ## Install ```sh npm install ``` ## Codegen Config File `codgen` requires a `codegen.config.json` file as argument. Here is an example of codegen config file used to generate e2e tests: ```json { "__comment": "All relative paths are resolved against directories.baseDir", "baseDir": ".", "noLib": true, "noHostContracts": true, "tests": { "numberOfTestSplits": 96, "overloads": "../../library-solidity/codegen/overloads/e2e.json", "publicDecrypt": true, "shuffle": true, "shuffleWithPseuseRand": true, "solidity": { "__comment": "All imports paths are relative to outDir", "outDir": "./contracts/operations", "imports": ["@fhevm/solidity/lib/FHE.sol", ["E2ECoprocessorConfig", "../E2ECoprocessorConfigLocal.sol"]], "parentContractName": "E2ECoprocessorConfig" }, "typescript": { "__comment": "All imports paths are relative to outDir", "outDir": "./test/fhevmOperations", "imports": [ ["instance", "../instance"], ["signers", "../signers"], ["typechain", "../../types"] ] } } } ``` ## Codegen Config File Documentation * `baseDir` (string, optional): The path the target directory used as the base directory. If the path is relative, the absolute path is resolved relatively to the config file. (default: config file directory) * `noLib` (boolean, optional): `true` to disable FHEVM library contracts generation (`FHE.sol`, `Impl.sol`, `FheType.sol`). (default: `false`) *
프로젝트로 돌아가기