The Interfold 백서

The Interfold

원문

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

Prints the source hash that identifies a build. pnpm build:circuits sync-config --preset <p> --committee <c> Updates utils.ts and ActiveCryptoConfig.sol only. It does not compile. pnpm check:committee Checks that the committee and BFV values agree across Noir, Rust, TypeScript, and Solidity. pnpm noir:lint ( scripts/lint-circuits.sh ) Runs nargo fmt --check and nargo check on the library and each package. It exits with success if nargo is missing. pnpm noir:test ( scripts/test-circuits.sh ) Runs nargo test on circuits/lib and decryption_aggregator , then nargo execute on bin/config , then the dkg_aggregator and node_fold tests for three preset and committee pairs. To make sample inputs for one circuit, use zk-artifacts generate . Its --committee value must match the active committee of the library: pnpm zk generate --circuit pk-generation --preset insecure --committee minimum --toml pnpm zk list prints the circuit names that it accepts. Generate the Solidity verifiers The Honk verifiers for dkg_aggregator and decryption_aggregator are committed under packages/interfold-contracts/contracts/verifiers/bfv/honk/ . The files at the top of that directory are for insecure-512 with minimum . Every other pair has its own directory, honk/<preset>/<committee>/ . pnpm build:circuits --preset insecure-512 --committee minimum pnpm generate:verifiers # rewrite the committed verifiers pnpm check:verifiers # compare them with the current keys, write nothing generate:verifiers compiles each circuit if necessary, runs bb write_vk -t evm and bb write_solidity_verifier , and renames the contract from HonkVerifier to a name such as DkgAggregatorVerifier . It refuses to run when the build stamp in dist/circuits or circuits/bin/.active-preset.json does not match the requested pair. For another pair, add --preset <name> --committee <name> . Each generated verifier has this function, the same as ICircuitVerifier ( contracts/interfaces/ICircuitVerifier.sol ): function verify ( bytes calldata _proof , bytes32 [] calldata _publicInputs ) external view returns ( bool ); Verifiers for your own circuits An E3 program can check its inputs with its own circuits. CRISP does this in examples/CRISP/scripts/compile_circuits.sh : It compiles user_data_encryption_ct0 , user_data_encryption_ct1 , and user_data_encryption from circuits/bin/threshold . It writes their verification keys with bb write_vk -t noir-recursive-no-zk . It compiles the application circuit and writes its key the same way. It compiles the fold circuit, which verifies both proofs, and writes its key with bb write_vk --oracle_hash keccak . It runs bb write_solidity_verifier on the fold key and copies the result to packages/crisp-contracts/contracts/verifiers/ . The script makes two verifiers: CRISPVerifier.sol from the crisp and fold circuits, and CRISPOnchainVerifier.sol from crisp_onchain and fold_onchain . The verifiers do not depend on the BFV preset. The fold circuit accepts the key hashes of both presets. The custom circuits tutorial follows these steps for a new circuit. The SDK function generateProof() proves only the three user-data-encryption circuits. It embeds artifacts built for insecure-512 with minimum . See the SDK page. Use circuits/lib in another Noir project Add the library as a dependency in your Nargo.toml . Use the release tag that matches the prover and the circuits that your deployment uses. CRISP uses the name interfold_lib : Nargo.toml [dependencies] interfold_lib = { git = "https://github.com/theinterfold/interfold" , tag = "v0.18.0" , directory = "circuits/lib" } Then import from it by that name: use interfold_lib::configs::default::threshold::{L, N}; use interfold_lib::math::commitments::compute_ciphertext_commitment; use interfold_lib::math::polynomial::Polynomial; The library at the tag v0.18.0 selects insecure-512 with minimum . The build script writes that selection into the source. For another pair, use a path dependency on a local checkout. To use another pair, run pnpm build:circuits for the pair in the checkout, then point the dependency at it: Nargo.toml [dependencies] interfold_lib = { path = "<checkout>/circuits/lib" } The library itself depends on poseidon v0.3.0 and keccak256 v0.1.2 from noir-lang , and on bignum v0.4.1 from gnosisguild/noir-bignum . Rust integration The crate e3-zk-prover ( crates/zk-prover ) runs the circuits for the ciphernode. Item Role ZkBackend Finds bb and the circuit directory. check_status , ensure_installed , download_bb , and download_circuits implement interfold noir . ZkProver Runs bb prove and bb verify as a subprocess. It reads artifacts from <circuits>/<preset>/<committee>/<variant>/ . Provable The trait for one circuit. It names the CircuitName and builds the witness inputs. CircuitVariant ( e3-events ) Default ( noir-recursive-no-zk ), Recursive ( noir-recursive ), and Evm ( evm ). These are the directory names in the archive. ProofRequestActor , ProofVerificationActor , ShareVerificationActor The actors that request proofs and check the proofs of other ciphernodes. The event types ( CircuitName , ProofType ) are in crates/events . The protocol flow that uses them is in agent/flow-trace/04_DKG_AND_COMPUTATION.md (opens in a new tab) . Add or rename a circuit Put the package in bin/dkg , bin/threshold , or bin/recursive_aggregation . The build script finds packages in these groups automatically. Add the package to the members list of the group workspace, for bin/dkg and bin/threshold . Add the directory to DIRS in scripts/lint-circuits.sh , for a package in bin/recursive_aggregation . Add a CircuitName variant in crates/events if the Rust prover must run the circuit. Rebuild each pair that you ship, and regenerate the verifiers if the circuit goes on-chain. Next steps Custom Noir circuits Write an input-validation circuit, make its verifier, and call it from an E3 program. Tutorial Cryptography The PV-TBFV phases and what each circuit proves. Concepts SDK Encryption functions and the embedded user-data-encryption prover. Reference Client and Server Best Practices ## /build/best-practices Build Best Practices Best Practices This page lists design and operations practices for E3 programs and the applications around them. It is for developers who design an E3 program, request E3s, or run a coordination server. Each practice names the mechanism in the code that makes it necessary. At the end, you have a deployment checklist. Request parameters Choose a supported committee size. The committee enum fixes N, H, and T in lib/ActiveCryptoConfig.sol . On mainnet, the launch pricing sets minCommitteeSize to 19, so only Small is accepted. getE3Quote reverts with CommitteeSizeTooSmall for a smaller size. Use the secure parameter set for private data. Version-7 mainnet accepts only paramSet 2 (secure-8192). The insecure-512 preset has no production security. Match the SDK preset to the parameter set. The SDK does not compare them. A mismatch encrypts inputs under the wrong parameters. Place the input window after the worst-case key time. The worst-case key time is the request time plus randomnessRequestTimeout , sortitionSubmissionWindow , and dkgWindow . The committee cannot publish its key after inputWindow[1] ( InputWindowClosedBeforeKeyPublication ). A window that starts earlier can lose input time while DKG runs. In Avail mode, CRISPProgram.validate refuses a voting start before the worst-case key time. Add a start buffer. inputWindow[0] must not be earlier than the block time when the request executes. calculateInputWindow adds 15 seconds by default. Keep the input window no longer than necessary. The quote charges node availability from the request to the end of the input window. The worst-case lifecycle must also stay inside maxDuration ( InvalidDuration ). Put per-E3 settings in customParams . Interfold stores the bytes on the E3 and passes them to e3Program.validate . CRISPProgram decodes its round settings from customParams . Fees Quote right before the request. For the same parameters and pricing, a later block gives the same quote or a lower quote. An approval of the latest quote is enough. Approve only the quoted amount. request pulls exactly the quoted fee with transferFrom . A larger approval stays open for later calls. Set maxFee , expectedFeeToken , and expectedCryptoConfigId . These fields make the request revert when governance changes the fee, the fee token, or the circuit configuration after your quote. requestE3 in the SDK sets the last two for you. Check requestsPaused() before you offer a request. A new deployment starts paused, and governance can pause requests again. Program contract Advertise both interfaces. registerE3Program probes IE3Program and IE3ProgramDataAvailability through ERC-165. It rejects a program that does not advertise both ( E3ProgramInterfaceMissing ). Check the request in validate . Interfold stores the E3 record before it calls validate , so the program can read the input window and the frozen timeouts. A revert in validate cancels the request before the fee transfer. Gate publishInput yourself. Interfold does not check inputs. The template program checks only inputWindow[1] . CRISPProgram also checks a ballot proof, a commitment deadline, and a signed availability attestation. Keep each E3 inside the addition budget of its preset. The ciphernodes make the smudging noise large enough for at most z fresh ciphertexts added together. z is 100,000 for secure-8192 and 1,024 for insecure-512. Interfold does not count inputs, so limit them in publishInput . CRISPProgram stops at 100,000 inputs with InputLimitReached , a limit that fits the secure-8192 budget but not the insecure-512 budget. See Limits on the computation . Bind each ciphertext to its commitment. The template program inserts the commitment into its input tree without a proof of the binding. A comment in MyProgram.sol states that production programs must verify it, because an invalid input can stop the E3 from completing. Check the input root in verify . The template verify requires the compute proof to use the stored parameter hash and the current root of the input tree ( InvalidComputeContext ). A program without this check cannot prove which inputs the computation used. Verify the arguments, not Interfold storage. Interfold calls verify before it stores the output. IE3Program states that verify must check the supplied hash, commitment, and proof. Replace the mock data availability verifier. The template verifyDataAvailability accepts any bytes that hash to the content hash. It is for the local stack only. Output and liveness Publish the ciphertext output inside its window. Interfold accepts it only after inputWindow[1] and not after the compute deadline. Read the deadline with getDeadlines(e3Id) . Treat the compute deadline as a hard limit. A missed compute deadline fails the E3 with ComputeTimeout . The requester pays for that failure: 50% of the service escrow goes to the honest members and 5% to the treasury. Make publication safe to repeat. A second publication reverts with CiphertextOutputAlreadyPublished . Check the stage before you retry after a crash. Store job state on disk. The template server keeps its job state in memory and watches only new key events. After a restart, it does not schedule an E3 whose key was published earlier. Publish the ciphertext before you publish the reference. The ciphernodes fetch the bytes from the data availability layer with the content hash. On the local stack, they read GET /availability/objects/:contentHash on the template server. Clients and events Check the committee key against its commitment. The key chunks are transport data. Use CommitteePublicKeyAssembler and validatePublicKeyCommitment , as the template client and server do. Listen to the events that the contracts emit. Use CIPHERTEXT_OUTPUT_REFERENCE_PUBLISHED , not CIPHERTEXT_OUTPUT_PUBLISHED . Use COMMITTEE_PUBLIC_KEY_CHUNK_PUBLISHED , not COMMITTEE_PUBLISHED . The current contracts do not emit CiphertextOutputPublished or CommitteePublished . Filter every event by E3 ID. The SDK watches all events of a type on the contract. The template handlers compare event.data.e3Id with the current E3. Read history with a start block. getHistoricalEvents reads in ranges of 10,000 blocks when you give fromBlock . Start at the contract deployment block, not at block 0. Wait for confirmations before an irreversible action. A reorganization can remove a log. Ciphernodes apply logs after ingestion_confirmations blocks (default 1). The CRISP availability service reads finalized blocks before it retires a job. Failures and refunds Know who can end an overdue E3. Ciphernodes submit markE3Failed and processE3Failure . During markFailedGracePeriod (1 hour in the mainnet configuration), only the requester, the owner, or an active committee member can call markE3Failed . After that, any account can. Expect a delay before a refund. For an E3 with a finalized committee, settlement opens one day after getE3LifecycleDeadline(e3Id) . Until then, processE3Failure reverts with SettlementBlocked . Request from an account that can claim. Only the requester address can call claimRequesterRefund . A smart contract wallet must be able to make this call. For the full refund rules, see Request an E3 . Testing Run a full E3 in CI. pnpm test:integration in the template runs the server tests, then an E3 from the request to the plaintext output ( tests/integration.spec.ts ). It needs an interfold binary built with the test-only-skip-proof-aggregation feature. pnpm dev:setup builds it in the monorepo. Test the runner without a request. With TEST_MODE=1 , GET /test on the server sends server/payload.json to the program runner. pnpm dev:all sets TEST_MODE=1 . Test the contracts. pnpm test in the template runs the Hardhat tests. Deployment checklist Deploy the E3 program. Ask the Interfold owner to register it with registerE3Program . Replace the mock verifyDataAvailability with a real data availability verifier. Set the chain, the RPC URL, and the preset in the server and the client. Fund the server key with gas for publishCiphertextOutput . Fund the requester with the fee token. Read the token from feeToken() . Confirm that getE3Quote accepts your committee size and parameter set on the target chain. Run pnpm test:integration against the new build. On mainnet, the Interfold owner is the governance DAO. A program registration is a governance action. Next steps Request an E3 Fees, deadlines, failures, and refunds from the requester side. Build Program contract Write validate , publishInput , and verify for your program. Build Client and server The template client and server that these practices refer to. Build Noir Circuits Build a Complete E3 Program ## /build/tutorials/write-e3-program Build Tutorials Build a Complete E3 Program Build a Complete E3 Program This tutorial builds an E3 program from the default template. You go through each part that you own: the Secure Process in Rust, the program contract in Solidity, the coordination server, and the client in TypeScript. You make a change to the contract, check that the parts still agree, and run a complete E3 on a local chain. At the end, you know which file does what, and which values must stay the same across the parts. Prerequisites: the Interfold CLI, Rust, Node.js, pnpm, and Foundry ( pnpm dev:all starts anvil ). See Installation . Read E3 Program Anatomy for the concepts. The parts of the program Client Browser Requests the E3 Encrypts inputs Shows the result Coordination server Off-chain Waits for the input window Calls the program server Publishes the output Secure Process Compute provider fhe_processor policy Program contract On-chain validate publishInput verify verifyDataAvailability Part File Role Secure Process program/src/lib.rs The FHE computation over the encrypted inputs, and the input policy. Program contract contracts/MyProgram.sol Accepts inputs, keeps the input tree, and verifies the compute proof. Deploy script deploy/default.ts Deploys the program and registers it with the Interfold contract. Coordination server server/index.ts Starts the computation after the input window and publishes the ciphertext output. Client client/src/pages/steps/*.tsx The five-step web flow: connect, request, enter inputs, submit, and results. Configuration interfold.config.yaml Chain, contract addresses, local ciphernodes, and the program mode ( program.dev ). Create the project Create a project from the default template: interfold init my-e3 cd my-e3 interfold init downloads templates/default at the tag of your CLI version (for example v0.18.0 ). It pins the @interfold/* packages and the Rust crates to that release, runs pnpm install , and makes the first Git commit. my-e3 program src lib.rs contracts MyProgram.sol Mocks deploy server client scripts hardhat.config.ts interfold.config.yaml Run the template one time Start the complete local stack: pnpm dev:all The command starts anvil , deploys the Interfold contracts and MyProgram , starts five local ciphernodes, the program server, the coordination server, and the client. Open http://localhost:3000 , connect a wallet, and run one E3 with two numbers. The result is their sum. The Quick Start has the wallet setup. Stop the stack with Ctrl+C before you change the code. Read the Secure Process program/src/lib.rs exports two functions. The program server calls both. program/src/lib.rs pub fn policy () -> InputPolicy { InputPolicy :: default () } pub fn fhe_processor (fhe_inputs : FHEProcessorInput <' _ >) -> Vec < u8 > { let mut sum = Ciphertext :: zero (fhe_inputs . params); for (bytes, _) in fhe_inputs . ciphertexts { let ciphertext = Ciphertext :: from_bytes ( & bytes, fhe_inputs . params) . unwrap (); sum += & ciphertext; } sum . to_bytes () } fhe_processor adds the ciphertexts homomorphically and returns the encrypted sum. It never sees a plaintext. The ciphertexts arrive one at a time, which is how the OpenVM guest proves rounds larger than its memory. policy returns InputPolicy::default() . The input tree leaf is the SAFE commitment of each ciphertext, and the processor uses every input. This matches MyProgram.publishInput , which inserts the commitment. Run the unit test. It encrypts 3 and 2 with a test key, runs fhe_processor , decrypts, and expects 5: cargo test -p e3-user-program When you change the computation, keep these rules: Return one BFV ciphertext with two parts. The decryption circuit (C6) takes ct0 and ct1 only. The processor receives no relinearization key, so do not multiply two ciphertexts. Select inputs only through policy . The compute proof commits to the root of the inputs that the processor used, and MyProgram.verify compares it with the on-chain tree. The Secure Process explains the input policy in detail. Harden publishInput contracts/MyProgram.sol implements IE3Program and IE3ProgramDataAvailability : Function Called by What the template does supportsInterface Interfold contract, at registration Reports IE3Program , IE3ProgramDataAvailability , and IERC165 . Registration fails without them. validate Interfold contract, at request Stores keccak256(e3ProgramParams) , starts an input tree of depth 20, returns keccak256("fhe.rs:BFV") . publishInput The data provider, directly Decodes (bytes ciphertext, bytes32 commitment) , inserts the commitment, emits InputPublished . ver
프로젝트로 돌아가기