From e2d876f7392238780a55423074b4c10ea75409f8 Mon Sep 17 00:00:00 2001 From: jatZama Date: Thu, 26 Dec 2024 16:52:31 +0100 Subject: [PATCH] chore: remove sql db in mocked gateway chore: remove useless README docs: fixed link chore: natspec chore: natspecs chore: prettier --- .../decryptionOracle/DecryptionOracle.sol | 24 ++++-- contracts/examples/README.md | 84 ------------------- contracts/examples/TestAsyncDecrypt.sol | 1 + contracts/test/asyncDecrypt.ts | 45 ---------- docs/fundamentals/fhevm/contracts.md | 4 +- 5 files changed, 20 insertions(+), 138 deletions(-) delete mode 100644 contracts/examples/README.md diff --git a/contracts/decryptionOracle/DecryptionOracle.sol b/contracts/decryptionOracle/DecryptionOracle.sol index dded493..cdca898 100644 --- a/contracts/decryptionOracle/DecryptionOracle.sol +++ b/contracts/decryptionOracle/DecryptionOracle.sol @@ -10,9 +10,13 @@ contract DecryptionOracle is UUPSUpgradeable, Ownable2StepUpgradeable { /// @notice Name of the contract string private constant CONTRACT_NAME = "DecryptionOracle"; - /// @notice Version of the contract + /// @notice Major version of the contract. uint256 private constant MAJOR_VERSION = 0; + + /// @notice Minor version of the contract. uint256 private constant MINOR_VERSION = 1; + + /// @notice Patch version of the contract. uint256 private constant PATCH_VERSION = 0; event DecryptionRequest(uint256 indexed requestID, uint256[] cts, address contractCaller, bytes4 callbackSelector); @@ -33,6 +37,9 @@ contract DecryptionOracle is UUPSUpgradeable, Ownable2StepUpgradeable { bytes32 private constant DecryptionOracleStorageLocation = 0xd86fa2a52e99634194c279afa011b5f5166614c3198dd09bbd002d5fb5c0bc00; + /** + * @dev Returns the DecryptionOracle storage location. + */ function _getDecryptionOracleStorage() internal pure returns (DecryptionOracleStorage storage $) { assembly { $.slot := DecryptionOracleStorageLocation @@ -48,10 +55,11 @@ contract DecryptionOracle is UUPSUpgradeable, Ownable2StepUpgradeable { __Ownable_init(_decryptionOracleOwner); } - /// @notice Requests the decryption of n ciphertexts `ctsHandles` with the result returned in a callback. - /// @notice During callback, msg.sender is called with [callbackSelector,requestID,decrypt(ctsHandles[0]),decrypt(ctsHandles[1]),...,decrypt(ctsHandles[n-1]),signatures] - /// @param ctsHandles is an array of uint256s handles. - /// @param callbackSelector the callback selector to be called on msg.sender later during fulfilment + /** @notice Requests the decryption of n ciphertexts `ctsHandles` with the result returned in a callback. + * @notice During callback, msg.sender is called with [callbackSelector,requestID,decrypt(ctsHandles[0]),decrypt(ctsHandles[1]),...,decrypt(ctsHandles[n-1]),signatures] + * @param ctsHandles is an array of uint256s handles. + * @param callbackSelector the callback selector to be called on msg.sender later during fulfilment + */ function requestDecryption( uint256[] calldata ctsHandles, bytes4 callbackSelector @@ -62,8 +70,10 @@ contract DecryptionOracle is UUPSUpgradeable, Ownable2StepUpgradeable { $.counter++; } - /// @notice Getter for the name and version of the contract - /// @return string representing the name and the version of the contract + /** + * @notice Getter for the name and version of the contract. + * @return string Name and the version of the contract. + */ function getVersion() external pure virtual returns (string memory) { return string( diff --git a/contracts/examples/README.md b/contracts/examples/README.md deleted file mode 100644 index bc05b58..0000000 --- a/contracts/examples/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# FhEVM smart contract examples - -This directory contains example contracts that demonstrate the usage of the fhEVM (Fully Homomorphic Encryption Virtual Machine) smart contract library. These contracts showcase various features and functionalities of encrypted computations on the blockchain, enabling privacy-preserving operations and opening up new possibilities for confidential blockchain applications. - -## Quick overview - -| Contract Name | Description | -| -------------------- | ---------------------------------------- | -| EncryptedERC20.sol | ERC20-like token with encrypted balances | -| TestAsyncDecrypt.sol | Asynchronous decryption testing | -| BlindAuction.sol | Blind auction using encrypted bids | - -## Usage - -These contracts serve as examples and can be used as references when building your own fhEVM-compatible smart contracts. Make sure to have the necessary fhEVM library and dependencies set up in your development environment. - -For more information, refer to the [fhEVM documentation](https://docs.zama.ai/fhevm). - -## Contract summaries - -### 1. **EncryptedERC20.sol** - -An implementation of an ERC20-like token with encrypted balances and transfers. This contract demonstrates: - -- Encrypted token balances -- Private transfer operations -- Allowance management with encryption - -It showcases how traditional token systems can be made confidential using FHE techniques, allowing for private balance management on a public blockchain. - -```mermaid -graph TD - subgraph User Inputs - X1(Encrypted Amount) - X2(Encrypted Allowance) - end - subgraph Contract Logic - Y1[Check Allowance & Balance] - Y2[Update Encrypted Allowance] - Y3[Transfer Encrypted Amount] - end - X1 --> Y1 - X2 --> Y1 - Y1 --> Y2 - Y1 --> Y3 -``` - -### 2. **TestAsyncDecrypt.sol** - -Tests asynchronous decryption of various encrypted data types using the DecryptionOracle. This contract is essential for understanding how to safely decrypt data when needed, without compromising the overall security of the encrypted system. - -### 3. **BlindAuction.sol** - -Implements a blind auction system using encrypted bids. Key features include: - -- Encrypted bid submission -- Timed auction periods -- Winner determination without revealing losing bids -- Claim and withdrawal mechanisms - -This contract showcases how FHE can be used to create fair and private auction systems on the blockchain, ensuring bid confidentiality until the auction ends. - -```mermaid -graph TD - subgraph Bidding Phase - A[User Submits Encrypted Bid] - B[Contract Stores Encrypted Bid] - C[Update Highest Bid & Winning Ticket] - end - subgraph Auction End - D[Decrypt Winning Ticket] - E[Winner Claims Prize] - F[Non-Winners Withdraw Bids] - G[Transfer Highest Bid to Beneficiary] - end - A --> B - B --> C - C --> |Auction Ends| D - D --> E - D --> F - D --> G -``` - -This diagram illustrates the main processes in the BlindAuction contract, from bid submission to the final distribution of funds and prizes. diff --git a/contracts/examples/TestAsyncDecrypt.sol b/contracts/examples/TestAsyncDecrypt.sol index b7da706..ab63a40 100644 --- a/contracts/examples/TestAsyncDecrypt.sol +++ b/contracts/examples/TestAsyncDecrypt.sol @@ -117,6 +117,7 @@ contract TestAsyncDecrypt is DecryptionOracleCaller { bytes[] memory signatures ) public checkSignatures(requestID, signatures) returns (bool) { yBool = decryptedInput; + revert(); return yBool; } diff --git a/contracts/test/asyncDecrypt.ts b/contracts/test/asyncDecrypt.ts index ce44b8c..1c4b2fb 100644 --- a/contracts/test/asyncDecrypt.ts +++ b/contracts/test/asyncDecrypt.ts @@ -2,53 +2,10 @@ import dotenv from 'dotenv'; import { Wallet } from 'ethers'; import fs from 'fs'; import { ethers, network } from 'hardhat'; -import { Database } from 'sqlite3'; import { DecryptionOracle } from '../types'; import { awaitCoprocessor, getClearText } from './coprocessorUtils'; -//const oracleDB = new Database('./oracle.db'); // on-disk db for debugging -const oracleDB = new Database(':memory:'); - -oracleDB.serialize(() => - oracleDB.run( - 'CREATE TABLE decryptionRequests (requestID TEXT PRIMARY KEY,cts TEXT[] NOT NULL,contractCaller BINARY(20) NOT NULL, callbackSelector BINARY(4) NOT NULL, isFulfilled BOOLEAN NOT NULL DEFAULT FALSE);', - ), -); - -export function insertSQL( - requestID: BigInt, - cts: BigInt[], - contractCaller: string, - callbackSelector: string, - isFulfilled: boolean, -) { - try { - const requestIDString = requestID.toString(); - const ctsStrings = cts.map((num) => num.toString()); - oracleDB.run( - 'INSERT OR REPLACE INTO decryptionRequests (requestID, cts, contractCaller, callbackSelector, isFulfilled) VALUES (?, ?, ?, ?, ?)', - [requestIDString, JSON.stringify(ctsStrings), contractCaller, callbackSelector, isFulfilled], - ); - } catch (error) { - if (error.code === 'SQLITE_CONSTRAINT') { - console.log(`Record with requestID ${requestID} already exists in database`); - } - throw error; - } -} - -export function markAsFulfilled(requestID: BigInt): boolean { - try { - const requestIDString = requestID.toString(); - oracleDB.run('UPDATE decryptionRequests SET isFulfilled = TRUE WHERE requestID = ?', [requestIDString]); - return true; - } catch (error) { - console.warn(`Failed to mark request ${requestID} as fulfilled. Error: ${error.message}`); - return false; - } -} - const networkName = network.name; const parsedEnvACL = dotenv.parse(fs.readFileSync('addresses/.env.acl')); @@ -137,7 +94,6 @@ const fulfillAllPastRequestsIds = async (mocked: boolean) => { const handles = event.args[1]; const contractCaller = event.args[2]; const callbackSelector = event.args[3]; - insertSQL(requestID, handles, contractCaller, callbackSelector, false); const typesList = handles.map((handle) => parseInt(handle.toString(16).slice(-4, -2), 16)); // if request is not already fulfilled if (mocked) { @@ -189,7 +145,6 @@ const fulfillAllPastRequestsIds = async (mocked: boolean) => { }; const tx = await relayer.sendTransaction(txData); await tx.wait(); - markAsFulfilled(requestID); } } }; diff --git a/docs/fundamentals/fhevm/contracts.md b/docs/fundamentals/fhevm/contracts.md index afd222b..d008bac 100644 --- a/docs/fundamentals/fhevm/contracts.md +++ b/docs/fundamentals/fhevm/contracts.md @@ -54,8 +54,8 @@ This contract is needed for security, especially for coprocessor where we could This contract tracks the FHEGas consumed in each block, and reverts the transactions inside a block if the FHEGas block limit is exceeded. -## Gateway Contract +## DecryptionOracle Contract -The [GatewayContract](../../../contracts/gateway/GatewayContract.sol) is an onchain contract designed to interact with an offchain Gateway component that handles decryption requests. When a dApp calls the `requestDecryption` function, the Gateway contract emits an event that is caught by the Gateway service. +The [DecryptionOracle](../../../contracts/decryptionOracle/DecryptionOracle.sol) is an onchain contract designed to interact with an offchain Gateway component that handles decryption requests. When a dApp calls the `requestDecryption` function, the `DecryptionOracle` contract emits an event that is caught by the Gateway service. _Note_: It is possible to have multiple Gateways, so multiple Gateway contracts can also be deployed. This is the only contract from this documentation page that is not strictly part of "core fhEVM" contracts, and as such, it should not be considered as a "trusted" contract. We only trust the KMS and the core fhEVM contracts. The Gateway is only bridging trust from host chain to KMS chain via storage proofs, and from KMS chain to the host chain via the signatures from KMS signers.