The Interfold 백서

The Interfold

원문

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

MyProgram is IE3Program , IE3ProgramDataAvailability , IERC165 , Ownable { // ... ICircuitVerifier public immutable inputVerifier; error KeyNotPublished ( uint256 e3Id); error InputWindowNotOpen ( uint256 e3Id); error InvalidInputProof (); constructor ( IInterfold _interfold , IOpenVmReceiptVerifier _verifier , ICircuitVerifier _inputVerifier , bytes32 _imageId ) Ownable (msg.sender) { require ( address (_verifier) != address ( 0 ) , VerifierAddressZero ()); require ( address (_inputVerifier) != address ( 0 ) , VerifierAddressZero ()); inputVerifier = _inputVerifier; // ... the rest of the template constructor } function publishInput ( uint256 e3Id , bytes memory data) external override { E3 memory e3 = interfold. getE3 (e3Id); if (interfold. getE3Stage (e3Id) != IInterfold.E3Stage.KeyPublished) revert KeyNotPublished (e3Id); if (block.timestamp < e3.inputWindow[ 0 ]) revert InputWindowNotOpen (e3Id); if (block.timestamp > e3.inputWindow[ 1 ]) revert InputDeadlineReached (); ( bytes memory ciphertext , bytes32 ciphertextCommitment , bytes memory proof) = abi. decode ( data , ( bytes , bytes32 , bytes ) ); if (ciphertext.length == 0 ) revert EmptyInputData (); // The order must match the public inputs of the fold circuit. bytes32 [] memory publicInputs = new bytes32 []( 2 ); publicInputs[ 0 ] = ciphertextCommitment; publicInputs[ 1 ] = e3.committeePublicKey; if ( ! inputVerifier. verify (proof , publicInputs)) revert InvalidInputProof (); uint256 index = inputs[e3Id].numberOfLeaves; inputs[e3Id]. _insert ( uint256 (ciphertextCommitment)); emit InputPublished (e3Id , ciphertext , index); } // ... } e3.committeePublicKey holds the commitment that CiphernodeRegistryOwnable.publishCommittee sent to the Interfold contract. The fold proof returns the same commitment, so a proof for another committee key fails. The value in publicInputs[0] is the commitment that the program inserts into its input tree. ⚠️ The proof binds the commitment, not the ciphertext bytes. A submitter can send a valid proof with other bytes. The default input policy of the template ( InputPolicy::default() ) cannot detect this, because its leaf is the commitment alone. The CRISP Secure Process drops an input whose bytes do not reproduce its commitment ( matches_commitment in examples/CRISP/program/src/lib.rs ). See The Secure Process . Deploy the verifier with the program In deploy/default.ts , deploy the two libraries and the verifier before MyProgram . Use fully qualified names, as examples/CRISP/packages/crisp-contracts/scripts/verifiers.ts does. Every generated verifier declares the same contract names. deploy/default.ts const source = 'contracts/verifiers/BinaryInputVerifier.sol' const zkTranscriptLib = await ethers .deployContract ( ` ${ source } :ZKTranscriptLib` ) await zkTranscriptLib .waitForDeployment () const relationsLib = await ethers .deployContract ( ` ${ source } :RelationsLib` ) await relationsLib .waitForDeployment () const inputVerifierFactory = await ethers .getContractFactory ( ` ${ source } :HonkVerifier` , { libraries : { [ `project/ ${ source } :ZKTranscriptLib` ] : await zkTranscriptLib .getAddress () , [ `project/ ${ source } :RelationsLib` ] : await relationsLib .getAddress () , } , }) const inputVerifier = await inputVerifierFactory .deploy () await inputVerifier .waitForDeployment () // Pass the verifier as the new third constructor argument. const e3Program = await e3ProgramFactory .deploy ( await interfold .getAddress () , await verifier .getAddress () , await inputVerifier .getAddress () , programId , ) Run pnpm compile to regenerate the TypeChain types before you deploy. Prove each input in the client The client makes five proofs: three for the encryption, one for the rule, and the fold. Then it encodes the input for publishInput . This function is adapted from generateProof in examples/CRISP/packages/crisp-sdk/src/vote.ts . Before you use it, do these two things: Copy the five compiled JSON files ( user_data_encryption_ct0 , user_data_encryption_ct1 , user_data_encryption , binary_input , and binary_input_fold ) into client/src/circuits . Add @aztec/bb.js 5.1.0 and @noir-lang/noir_js 1.0.0-beta.26 to client/package.json . These are the versions that @interfold/sdk uses in release 0.18.0 . client/src/utils/prove-input.ts import { Barretenberg , UltraHonkBackend } from '@aztec/bb.js' import { Noir , type CompiledCircuit } from '@noir-lang/noir_js' import type { InterfoldSDK } from '@interfold/sdk' import { bytesToHex , encodeAbiParameters , parseAbiParameters } from 'viem' import ct0Circuit from '@/circuits/user_data_encryption_ct0.json' import ct1Circuit from '@/circuits/user_data_encryption_ct1.json' import udeCircuit from '@/circuits/user_data_encryption.json' import binaryInputCircuit from '@/circuits/binary_input.json' import foldCircuit from '@/circuits/binary_input_fold.json' const proofToFields = (proof : Uint8Array ) : string [] => { const fields : string [] = [] for ( let i = 0 ; i < proof . length ; i += 32 ) fields .push ( bytesToHex ( proof .slice (i , i + 32 ))) return fields } export async function proveBinaryInput (sdk : InterfoldSDK , value : bigint , publicKey : Uint8Array ) { const { encryptedData , circuitInputs: c } = await sdk .encryptNumberAndGenInputs (value , publicKey) // The fold circuit needs 2^21 points. In the browser, a later `initSRSChonk` call does not // enlarge the SRS that `new` loads, so pass the size here. const api = await Barretenberg .new ({ srsSize : 2 ** 21 }) const inner = { verifierTarget : 'noir-recursive-no-zk' } as const const prove = async (circuit : CompiledCircuit , inputs : Record < string , unknown >) => { const { witness , returnValue } = await new Noir (circuit) .execute (inputs as any ) const backend = new UltraHonkBackend ( circuit .bytecode , api) const proof = await backend .generateProof (witness , inner) const artifacts = await backend .generateRecursiveProofArtifacts ( proof .proof , proof . publicInputs . length , inner , ) return { proof , artifacts , returnValue } } try { const ct0 = await prove (ct0Circuit as CompiledCircuit , { pk0is : c .pk0is , ct0is : c .ct0is , u : c .u , e0 : c .e0 , k1 : c .k1 , r : c .r , }) const ct1 = await prove (ct1Circuit as CompiledCircuit , { pk1is : c .pk1is , ct1is : c .ct1is , u : c .u , e1 : c .e1 , r_ct1 : c .r_ct1 , }) const ude = await prove (udeCircuit as CompiledCircuit , { ct0_verification_key : ct0 . artifacts .vkAsFields , ct0_proof : proofToFields ( ct0 . proof .proof) , ct0_public_inputs : ct0 . proof .publicInputs , ct0_key_hash : ct0 . artifacts .vkHash , ct1_verification_key : ct1 . artifacts .vkAsFields , ct1_proof : proofToFields ( ct1 . proof .proof) , ct1_public_inputs : ct1 . proof .publicInputs , ct1_key_hash : ct1 . artifacts .vkHash , }) const rule = await prove (binaryInputCircuit as CompiledCircuit , { ct0is : c .ct0is , ct1is : c .ct1is , k1 : c .k1 , }) const [ ctCommitment , k1Commitment ] = rule .returnValue as string [] const { witness } = await new Noir (foldCircuit as CompiledCircuit ) .execute ({ user_data_encryption_verification_key : ude . artifacts .vkAsFields , user_data_encryption_proof : proofToFields ( ude . proof .proof) , user_data_encryption_public_inputs : ude . proof .publicInputs , user_data_encryption_key_hash : ude . artifacts .vkHash , binary_input_verification_key : rule . artifacts .vkAsFields , binary_input_proof : proofToFields ( rule . proof .proof) , binary_input_key_hash : rule . artifacts .vkHash , ct_commitment : String (ctCommitment) , k1_commitment : String (k1Commitment) , }) const fold = await new UltraHonkBackend ( (foldCircuit as CompiledCircuit ).bytecode , api , ) .generateProof (witness , { verifierTarget : 'evm' , }) // publicInputs[0] is ct_commitment, the value that publishInput inserts into its tree. return encodeAbiParameters ( parseAbiParameters ( 'bytes, bytes32, bytes' ) , [ bytesToHex (encryptedData) , fold .publicInputs[ 0 ] as `0x ${ string } ` , bytesToHex ( fold .proof) , ]) } finally { await api .destroy () } } Send the result as data in publishInput(e3Id, data) . The template encodes inputs in client/src/utils/input.ts and server/input.ts as (bytes, bytes32) . Change both files to the new format. Test the circuit Put Noir tests ( #[test] functions) next to the circuit code and run them with nargo test in the package. CRISP does this in examples/CRISP/circuits/lib/src/merkle_tree.nr and runs the tests with pnpm test:circuits . Compare with CRISP Part This tutorial CRISP Rule circuit binary_input : the value is 0 or 1 crisp : census membership, signature, vote rules, and the ciphertext addition Fold circuit 2 public inputs 9 public inputs, from prev_ct_commitment to the committee public key Key-hash check One constant Two constants, one for each BFV preset, so one verifier serves both presets Verifiers BinaryInputVerifier.sol CRISPVerifier.sol (census Merkle tree) and CRISPOnchainVerifier.sol (on-chain voting power) Input flow One publishInput transaction publishInput , then finalizeInput after the ciphertext is available on Avail For small checks, you do not always need a circuit. A contract can check public data itself, for example an allow list of submitters. Next steps Noir Circuits The circuits workspace, the toolchain, and the verifier scripts. Reference E3 program contract The full IE3Program interface and what each function must check. Build CRISP A complete E3 application that uses these patterns for private voting. Example Deploy to Sepolia Deploy the program and its verifier to the testnet. Tutorial Build a Complete E3 Program Encrypt and Submit an Input ## /build/tutorials/encrypt-and-submit Build Tutorials Encrypt and Submit an Input Encrypt and Submit an Input This tutorial shows the client side of one E3 on the local template stack. You request an E3, get the committee public key, encrypt two numbers, and submit them to the E3 program. Then you read the decrypted sum. It is for developers who have the template running and want to write their own client code. Every call on this page is a real SDK or viem call, and the input format is the format that the template program MyProgram accepts. Get the key Join the key chunks and check the commitment. Encrypt Encrypt the value to the committee key. Commit Compute the SAFE commitment of the ciphertext. Submit Call publishInput on the E3 program. Read Decode the plaintext output. Before you start You need these items: A running template stack. Run pnpm dev:all in the project. See Quick Start . @interfold/sdk and viem in your project. For a browser, also add the Vite plugins from SDK . The addresses from interfold print-env --chain localhost : INTERFOLD_ADDRESS , REGISTRY_ADDRESS , FEE_TOKEN_ADDRESS , and E3_PROGRAM_ADDRESS . A funded local account. The first Anvil account deploys the contracts and holds the mock fee token. The samples run in Node.js. They use RPC_URL , PRIVATE_KEY , and the four addresses as variables. Procedure Create the SDK client Create one SDK instance and one viem wallet client. The SDK sends Interfold calls. The wallet client sends the E3 program call. import { InterfoldSDK } from '@interfold/sdk' import { createWalletClient , http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { hardhat } from 'viem/chains' const sdk = InterfoldSDK .create ({ rpcUrl : RPC_URL , privateKey : PRIVATE_KEY , contracts : { interfold : INTERFOLD_ADDRESS , ciphernodeRegistry : REGISTRY_ADDRESS , feeToken : FEE_TOKEN_ADDRESS , } , chain : hardhat , // Must match paramSet 0, which the request in the next step uses. thresholdBfvParamsPresetName : 'INSECURE_THRESHOLD_512' , }) const walletClient = createWalletClient ({ account : privateKeyToAccount ( PRIVATE_KEY ) , chain : hardhat , transport : http ( 'http://localhost:8545' ) , }) The result is a client that can read, write, and watch events. Request an E3 Quote the fee, approve it, and send the request. Then read the E3 ID from the E3Requested log. import { DEFAULT_COMPUTE_PROVIDER_PARAMS , InterfoldEventType , calculateInputWindow , encodeComputeProviderParams , type E3RequestedData , } from '@interfold/sdk' const publicClient = sdk .getPublicClient () const requestParams = { committeeSize : 0 , // CommitteeSize.Minimum inputWindow : await calculateInputWindow (publicClient , 300 ) , // 300-second window e3Program : E3_PROGRAM_ADDRESS , paramSet : 0 , computeProviderParams : encodeComputeProviderParams ( DEFAULT_COMPUTE_PROVIDER_PARAMS ) , } const fee = await sdk .getE3Quote (requestParams) await sdk .waitForTransaction ( await sdk .approveFeeToken (fee)) const requestHash = await sdk .requestE3 ({ ... requestParams , maxFee : fee }) const receipt = await publicClient .waitForTransactionReceipt ({ hash : requestHash }) const logs = await sdk .getHistoricalEvents ( InterfoldEventType . E3_REQUESTED , receipt .blockNumber , receipt .blockNumber , ) const requestLog = logs .find ((log) => log .transactionHash === requestHash) const e3Id = (requestLog as unknown as { args : E3RequestedData }). args .e3Id The result is the E3 ID. It is a large number, because the Interfold address is in its high bits. Get the committee public key Wait for the committee to publish the key. Committee members publish the serialized key in CommitteePublicKeyChunkPublished events. Join the chunks, and keep the key only if it matches the proven commitment. This code follows templates/default/server/index.ts . import { CommitteePublicKeyAssembler , RegistryEventType } from '@interfold/sdk' import { hexToBytes } from 'viem' const assembler = new CommitteePublicKeyAssembler () const publicKey = await new Promise < Uint8Array >((resolve) => { void sdk .onInterfoldEvent ( RegistryEventType . COMMITTEE_PUBLIC_KEY_CHUNK_PUBLISHED , async (event) => { if ( event . data .e3Id !== e3Id) return try { const assembled = assembler .add ( event .data) if ( ! assembled) return const isBoundKey = await sdk .validatePublicKeyCommitment ( assembled .publicKey , hexToBytes ( assembled .pkCommitment) , ) if (isBoundKey) resolve ( assembled .publicKey) } catch (error) { console .warn ( 'Ignored an invalid key chunk:' , error) } } , ) }) The result is the committee public key as a Uint8Array . On the local stack, it arrives after the committee completes DKG. Encrypt the input Encrypt the value to the committee key. Then compute the SAFE commitment of the ciphertext. const ciphertext = await sdk .encryptNumber ( 20 n , publicKey) const commitment = await sdk .computeCiphertextCommitment (ciphertext) The result is the ciphertext bytes and a 32-byte commitment. To encrypt a list of values, use sdk.encryptVector(BigUint64Array.from([1n, 2n]), publicKey) . Submit the input Encode the ciphertext and the commitment as (bytes, bytes32) . Then call publishInput on the E3 program. import { bytesToHex , encodeAbiParameters , parseAbi , parseAbiParameters } from 'viem' const data = encodeAbiParameters ( parseAbiParameters ( 'bytes, bytes32' ) , [ bytesToHex (ciphertext) , bytesToHex (commitment) , ]) const inputHash = await walletClient .writeContract ({ address : E3_PROGRAM_ADDRESS , abi : parseAbi ([ 'function publishInput(uint256 e3Id, bytes data)' ]) , functionName : 'publishInput' , args : [e3Id , data] , }) await sdk .waitForTransaction (inputHash) The result is a mined transaction with an InputPublished(e3Id, data, index) log from MyProgram . MyProgram rejects the call after inputWindow[1] with InputDeadlineReached . Submit a second input Repeat the two previous steps with a second value, for example 22n . The template server runs the computation only when the E3 has at least two inputs. Read the result Watch for the plaintext output of your E3. Decode it with decodePlaintextOutput . import { decodePlaintextOutput } from '@interfold/sdk' await sdk .onInterfoldEvent ( InterfoldEventType . PLAINTEXT_OUTPUT_PUBLISHED , (event) => { if ( event . data .e3Id !== e3Id) return console .log ( 'Sum:' , decodePlaintextOutput ( event . data .plaintextOutput)) }) The result appears after the input window closes. The server sends the inputs to the program runner and publishes the ciphertext output. Then the committee decrypts it. The output is the sum of the two values. To check the result later, read the stage and the record: import { E3Stage , decodePlaintextOutput } from '@interfold/sdk' if (( await sdk .getE3Stage (e3Id)) === E3Stage .Complete) { const e3 = await sdk .getE3 (e3Id) console .log ( 'Sum:' , decodePlaintextOutput ( e3 .plaintextOutput)) } Read the key after it is published A client that starts after the key publication does not get the live events. Read the chunks from history instead. Give a fromBlock before the key publication. The SDK then reads in ranges of 10,000 blocks. import { CommitteePublicKeyAssembler , RegistryEventType , type CommitteePublicKeyChunkPublishedData , } from '@interfold/sdk' import { hexToBytes } from 'viem' const assembler = new CommitteePublicKeyAssembler () const chunkLogs = await sdk .getHistoricalEvents ( RegistryEventType . COMMITTEE_PUBLIC_KEY_CHUNK_PUBLISHED , fromBlock , ) for ( const log of chunkLogs) { const chunk = (log as unknown as { args : CommitteePublicKeyChunkPublishedData }).args if ( chunk .e3Id !== e3Id) continue const assembled = assembler .add (chunk) if ( assembled && ( await sdk .validatePublicKeyCommitment ( assembled .publicKey , hexToBytes ( assembled .pkCommitment))) ) { // assembled.publicKey is the committee key. break } } sdk.getE3PublicKey(e3Id) returns only the 32-byte commitment from the registry. It does not return the key. sdk.generatePublicKey() returns a new random BFV public key. It is useful to test encryption without a committee. The committee cannot decrypt data that is encrypted to this key. Add an encryption proof A program can require a proof that the ciphertext is a valid encryption. sdk.encryptNumberAndGenProof(value, publicKey) returns { encryptedData, proof } . The circuits in the SDK support only the INSECURE_THRESHOLD_512 preset and the Minimum committee. For other presets, use encryptNumberAndGenInputs and your own circuits. See SDK and Custom Noir circuits . How CRISP submits inputs CRISP stores ballot ciphertexts on Avail, not on Ethereum. Its input flow has three parts: The CRISP server checks the ballot proof, stores the exact bytes, and signs an availability attestation. CRISPProgram.publishInput checks the proof and the attestation, reserves the tree leaf, and emits InputCommitted . The server publishes the bytes to Avail. After the Avail range is bridged to Ethereum, any account calls finalizeInput with the receipt. The program emits InputPublished . CRISPProgram.verify refuses the compute proof while an input is still pending. See CRISP . Common problems Symptom Cause Fix The key promise never resolves The watcher started after the key chunks were published. Read the chunks from history. validatePublicKeyCommitment retu
프로젝트로 돌아가기