The Interfold 백서

The Interfold

원문

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

client shows the EnvironmentError screen instead of the wizard. Variable Default VITE_INTERFOLD_ADDRESS None VITE_REGISTRY_ADDRESS None VITE_BONDING_REGISTRY_ADDRESS None VITE_E3_PROGRAM_ADDRESS None VITE_FEE_TOKEN_ADDRESS None VITE_RPC_URL http://localhost:8545 VITE_THRESHOLD_BFV_PARAMS_PRESET_NAME INSECURE_THRESHOLD_512 client/src/main.tsx also reads VITE_WALLETCONNECT_PROJECT_ID for ConnectKit. Server variables server/utils.ts requires the first group. server/index.ts reads the others. Variable Required Default Use RPC_URL Yes None The RPC URL for the SDK. INTERFOLD_ADDRESS Yes None The Interfold contract. REGISTRY_ADDRESS Yes None The CiphernodeRegistry . E3_PROGRAM_ADDRESS Yes None MyProgram , for the input events. FEE_TOKEN_ADDRESS Yes None The fee token. PRIVATE_KEY Yes None The key that signs publishCiphertextOutput . CHAIN_ID Yes None The chain ID. PROGRAM_RUNNER_URL No http://127.0.0.1:13151 The program runner. CALLBACK_URL No http://127.0.0.1:8080 The URL that the runner calls with the result. PORT No 8080 The server port. DATA_AVAILABILITY_DIRECTORY No .interfold/data-availability Where the server stores ciphertext objects. TEST_MODE No Not set Enables GET /test . Data availability The local chain entry in interfold.config.yaml sets data_availability to mode: mock_http with rpc_url: http://127.0.0.1:8080/availability . The ciphernodes read ciphertext objects from the server at that URL. A production chain uses mode: avail instead. How the client works The client is a five-step wizard. WizardContext.tsx creates the SDK with useInterfoldSDK and a memoized configuration from sdk-config.ts . The wizard advances by itself when the wallet connects and when the SDK is ready. Step Component What it does 1 ConnectWallet.tsx Asks for a wallet connection. The ConnectKit button is in the navigation bar. 2 RequestComputation.tsx Quotes the fee, approves it, and calls requestE3 . Then it waits for the committee public key. 3 EnterInputs.tsx Encrypts two numbers, computes their commitments, and sends each one to MyProgram.publishInput . 4 EncryptSubmit.tsx Shows progress and waits for the plaintext output. 5 Results.tsx Shows the sum, the E3 ID, the transaction hash, and the raw output. Events that the client listens to Event type File Action InterfoldEventType.E3_REQUESTED RequestComputation.tsx Saves e3Id and inputWindow[1] . RegistryEventType.COMMITTEE_PUBLIC_KEY_CHUNK_PUBLISHED RequestComputation.tsx Adds the chunk to a CommitteePublicKeyAssembler . It keeps the key only when validatePublicKeyCommitment returns true . InterfoldEventType.CIPHERTEXT_OUTPUT_PUBLISHED EncryptSubmit.tsx Marks the computation step as done. InterfoldEventType.PLAINTEXT_OUTPUT_PUBLISHED EncryptSubmit.tsx Decodes the result with decodePlaintextOutput and goes to the results step. The current Interfold contract emits CiphertextOutputReferencePublished for a new ciphertext output. It does not emit CiphertextOutputPublished , so the computation step in the template progress list stays open until the plaintext arrives. The SDK key for the emitted event is InterfoldEventType.CIPHERTEXT_OUTPUT_REFERENCE_PUBLISHED . Input submission client/src/utils/input.ts encodes the ciphertext and its commitment as (bytes, bytes32) and calls publishInput on the E3 program: const data = encodeAbiParameters ( parseAbiParameters ( 'bytes, bytes32' ) , [ input , ciphertextCommitment , ]) return walletClient .writeContract ({ address : programAddress , abi : myProgramAbi , functionName : 'publishInput' , args : [e3Id , data] , chain : walletClient .chain , account : sender , }) EnterInputs.tsx blocks submission after inputWindow[1] , because MyProgram.publishInput then reverts with InputDeadlineReached . For the full flow, see Encrypt and submit . How the server works The server in server/index.ts coordinates the compute step. It keeps only two in-memory sets for idempotency: scheduled and inFlight . It reads the parameters and the inputs from the chain when it runs a job. Server steps Create the SDK. createPrivateSDK calls InterfoldSDK.create with RPC_URL , PRIVATE_KEY , the hardhat chain, and the INSECURE_THRESHOLD_512 preset. It creates the SDK one time. Listen for the key. setupEventListeners watches RegistryEventType.COMMITTEE_PUBLIC_KEY_CHUNK_PUBLISHED . When a key is complete and matches its commitment, the server calls scheduleE3(e3Id) . Wait for the input window. scheduleE3 reads inputWindow[1] from getE3 . It polls the latest block time every 500 ms until the window closes. If the window is already closed, it runs at once. Collect the inputs. runProgram reads the encoded parameters from Interfold.paramSetRegistry(e3.paramSet) . It reads every InputPublished event of MyProgram for the E3, from block 0. It skips the E3 when there is one input or none. Start the compute. callFheRunner in server/runner.ts posts to PROGRAM_RUNNER_URL/run_compute . The body has the E3 ID, the chain and contract domain, the parameters, the ciphertext inputs, and callback_url . The domain is the chain ID, the Interfold address, the encryption scheme ID, and the committee public key hash. Publish the output. The runner calls POST / with e3_id , ciphertext , ciphertext_commitment , and proof . The server stores the ciphertext under its Keccak-256 hash. Then it calls sdk.publishCiphertextOutput . The webhook publishes the output with this reference: const ciphertextBytes = Buffer .from ( ciphertext .slice ( 2 ) , 'hex' ) const contentHash = keccak256 (ciphertext) await storeAvailabilityObject (contentHash , ciphertextBytes) await sdk .publishCiphertextOutput ( BigInt (e3_id) , { contentHash , ciphertextCommitment : ciphertext_commitment , computeProof : proof , // The local program verifies raw bytes as a deterministic mock receipt. availabilityProof : ciphertext , }) Server endpoints Endpoint Content POST / The program runner callback. It publishes the ciphertext output. GET /availability/objects/:contentHash Returns a stored object as application/octet-stream . The ciphernodes read here. GET /test Only with TEST_MODE . Sends server/payload.json to the program runner. Error handling The template handles errors in these places: Webhook input. POST / returns HTTP 400 when a field is missing or a value is not a hex string. It returns HTTP 500 when the publication fails. Runner failure. runProgram removes the E3 from inFlight when callFheRunner throws. A later call can then try again. callFheRunner throws when the runner returns a status that is not OK. Key chunks. The server and the client log a chunk that they cannot use, then continue. They reject a key whose commitment does not match. Client state. WizardRoutes.tsx shows EnvironmentError for missing variables and SDKErrorDisplay when the SDK hook reports an error. error-formatting.ts maps common wallet and revert messages to short text. Input window. EnterInputs.tsx compares the local time with inputWindow[1] and blocks a late submission. EncryptSubmit.tsx shows a warning when the window closed before the inputs were sent. For SDK error codes, see SDK . Before you leave local development The template server is for a local chain. Change these points before you use it on another network: server/index.ts sets the hardhat chain and the INSECURE_THRESHOLD_512 preset. Set the target chain and the preset that matches your paramSet . MyProgram.verifyDataAvailability accepts the raw bytes as the receipt. Replace it with a real data availability verifier, and publish the ciphertext to that layer. runProgram reads input events from block 0. Start from the program deployment block. The scheduled and inFlight sets are in memory. A restart loses them. Store the job state if the server must recover after a restart. The server must publish the output before the compute deadline. A missed deadline fails the E3 with ComputeTimeout , and the requester pays for completed work. Next steps Encrypt and submit Encrypt an input and send it to the E3 program step by step. Tutorial SDK Every SDK export, event type, and error code. Build Compute provider How the program runner and the compute proof work. Build Deploy to Sepolia Move the template from the local chain to a testnet. Tutorial SDK Noir Circuits ## /build/noir-circuits Build Noir Circuits Noir Circuits This page is for developers who build, change, or reuse the Noir circuits in the circuits/ directory of the Interfold repository. It shows where each package lives and which tool versions to install. It also lists the scripts that build the circuits and the Solidity verifiers, and it shows how the Rust prover finds the artifacts. At the end, you can build the circuits for a preset and a committee size. You can also use the circuit library in your own Noir project. For what the circuits prove (the PV-TBFV phases and the circuit IDs C0 to C7), read Cryptography first. The Noir sources and their tests are the source of truth for constraints and public inputs. Workspace layout All binary packages depend on one shared library. The Nargo package name of the library is lib ( circuits/lib/Nargo.toml ). circuits lib Nargo.toml src lib.nr math core configs bin config dkg threshold recursive_aggregation benchmarks Directory Contents lib/src/math Polynomials, the SAFE sponge (Poseidon2 and Keccak256), modular arithmetic, and the commitment functions with their domain separators. lib/src/core The circuit logic that the binary packages call. core/dkg holds C0 and C2 to C4. core/threshold holds C1, C5, the two user-encryption legs, C6, and C7. lib/src/configs The BFV presets ( insecure , secure ) and the committee sizes. default/mod.nr and committee/active.nr select the active pair. The build script writes both files. bin/dkg Nargo workspace: pk (C0), sk_share_computation (C2a), e_sm_share_computation (C2b), share_encryption (C3), share_decryption (C4). bin/threshold Nargo workspace: pk_generation (C1), pk_aggregation (C5), user_data_encryption_ct0 and user_data_encryption_ct1 with their wrapper user_data_encryption (P3), share_decryption (C6), decrypted_shares_aggregation (C7). bin/recursive_aggregation Twelve packages that fold proofs together. The two final circuits are dkg_aggregator and decryption_aggregator . bin/config Package validate_secure_configs . It checks the secure preset constants (CRT moduli, bounds, and parity matrices). benchmarks Timing scripts and reports. The package directory names match the CircuitName enum in crates/events/src/interfold_event/proof.rs . For example, CircuitName::PkBfv is pk , and CircuitName::DkgAggregator is dkg_aggregator . The full package index is in circuits/README.md (opens in a new tab) . How the proofs combine Each ciphernode proves its DKG steps with the inner circuits. The recursive aggregation packages fold these proofs, first for each ciphernode and then across the committee. Only the two aggregator proofs go on-chain. Inner proofs C0 to C4 for each ciphernode. Step folds c2ab_fold, c3_fold, c3ab_fold, c4ab_fold. node_fold One fold for each ciphernode. nodes_fold Folds the node_fold proofs of the committee. dkg_aggregator Adds C5. Verified on-chain. The decryption path is shorter. The C6 proofs of the committee go through c6_fold , and decryption_aggregator adds C7. The *_kernel packages make the first proof of each sequential fold ( c3_fold , c6_fold , nodes_fold ). The Solidity verifiers for the two aggregators are committed to the repository as DkgAggregatorVerifier.sol and DecryptionAggregatorVerifier.sol . BfvPkVerifier and BfvDecryptionVerifier hold the address of one of these verifiers and call it through ICircuitVerifier . Toolchain A circuit build needs two tools: nargo compiles Noir, and bb (Barretenberg) writes verification keys, proofs, and Solidity verifiers. Use the pinned versions. Artifacts from other versions do not match the prover or the committed verifiers. This table describes repository source builds. Released binaries keep the versions pinned at their release. Component Version Pinned in nargo 1.0.0-beta.26 NOIR_TOOLCHAIN in .github/workflows/ci.yml . The Noir crates in crates/zk-prover/Cargo.toml use the same tag. bb 5.2.0 required_bb_version in crates/zk-prover/versions.json , and BB_VERSION in ci.yml Circuit artifacts for source builds Build from this checkout pnpm build:circuits bb_proof_verification (Noir) v5.2.0 The Nargo.toml of each package that verifies a proof @aztec/bb.js , @noir-lang/noir_js 5.2.0 , 1.0.0-beta.26 packages/interfold-sdk/package.json For a source build, compile the circuits from the same checkout. interfold noir setup installs the CLI's release archive; it does not compile the checkout. Do not reuse an archive built with a different toolchain. A release needs a matching archive before nodes can use it. Install nargo Install noirup , then use it to install the pinned compiler: curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash export PATH = "$PATH:$HOME/.nargo/bin" noirup -v v1.0.0-beta.26 The installer adds ~/.nargo/bin to your shell profile. The export line makes it available in the current shell. Install bb For this checkout, install the binary for your platform from the Barretenberg 5.2.0 release (opens in a new tab) . For a released node, run interfold noir setup . It downloads the CLI's pinned bb , checks it against the checksum in versions.json , and installs that release's circuit archive: interfold noir setup Without an Interfold config file, the CLI installs into ~/.interfold/noir : bin/bb , circuits/ , and version.json . With a config file, it uses .interfold/noir next to that file. Put bb on your PATH The repository scripts call bb from your PATH . For a source build, add the directory with the 5.2.0 binary. To use the copy installed by a matching released CLI, add its directory: export PATH = "$HOME/.interfold/noir/bin:$PATH" Check the versions nargo --version bb --version For source builds, nargo reports 1.0.0-beta.26 and bb reports 5.2.0 . interfold noir commands interfold noir manages the bb binary and the circuit artifacts that a ciphernode uses ( crates/cli/src/noir.rs ). Command What it does interfold noir status Prints the path and version of bb and of the circuits, then the status: Ready , Barretenberg needs update , Circuits need update , or Setup required . interfold noir setup Installs what is missing or out of date. If everything matches versions.json , it prints the versions and stops. interfold noir setup --force Downloads bb and the circuit archive again. interfold noir setup --circuits-archive <PATH> Installs the circuits from a local release archive instead of the download. The circuit archive comes from the GitHub release pinned in required_circuits_version . The node selects the artifact directory from the BFV parameter set and the committee size of each E3. Build the circuits in the repository Run the build from the repository root. It needs nargo and bb on your PATH , the Rust toolchain (the script runs two Rust generators), and the JavaScript dependencies ( pnpm install ). pnpm build:circuits # insecure-512, minimum pnpm build:circuits --preset secure-8192 --committee small A build selects one BFV preset and one committee size: Option Values Default --preset insecure-512 , secure-8192 , all insecure-512 --committee minimum , micro , small , all minimum Committee N T H minimum 3 1 2 micro 9 4 5 small 19 9 14 N is the committee size, T is the threshold, and H is the number of honest parties that the DKG expects. Decryption needs T + 1 shares. The mainnet contracts accept only the secure parameter set. Sepolia and local chains accept both sets ( ActiveCryptoConfig.sol ). For each pair, the build does these steps ( scripts/build-circuits.ts ): It writes configs/default/mod.nr and configs/committee/active.nr for the pair. It regenerates the parity matrices and the C1 and C2 bounds with the Rust generators. It updates packages/interfold-contracts/scripts/utils.ts and packages/interfold-contracts/contracts/lib/ActiveCryptoConfig.sol . It compiles every package in bin/dkg , bin/threshold , and bin/recursive_aggregation with nargo compile . It writes verification keys with bb write_vk . Each base circuit gets evm , noir-recursive-no-zk , and noir-recursive keys. Each fold circuit gets a noir-recursive-no-zk key, and the two aggregators also get an evm key. It copies the artifacts to dist/circuits/<preset>/<committee>/ , with one directory for each variant ( default , recursive , evm ). Then it writes SHA256SUMS and checksums.json . The build records the active pair in circuits/bin/.active-preset.json . Downloaded release archives must match the SHA-256 compiled into the binary for their version. The binary includes pins from crates/zk-prover/versions.json ( circuits_checksums ) and the release build input. The installer checks it before extraction, then requires a nonempty internal manifest that covers every artifact file. Root manifests, SOURCE_HASH , and build stamps are metadata. noir setup --circuits-archive requires the same pin for a local archive. Add --allow-unpinned-archive to install another archive, such as a local build. The installer requires every pair in crates/zk-prover/supported-configurations.json by default, including for noir setup --circuits-archive . The release validator uses the same matrix. For a local archive, repeat --circuits-configuration <PRESET/COMMITTEE> to select a subset explicitly. For example, --circuits-configuration insecure-512/minimum selects the development configuration. Local and CI callers can request a nonempty subset through download_circuits_for_configurations or install_circuits_archive_for_configurations . The required set never depends on archive contents. Each required or included pair must contain every artifact in crates/zk-prover/required-artifacts.json . The release validator and installer share this inventory. The manifest must cover each artifact. If circuit replacement or the version update fails, the installer attempts rollback and returns the original installation error. Each rollback failure logs the source and target paths. If the previous circuits cannot be restored, the installer keeps the staging directory and logs its path for recovery. The release workflow packages the archive first and passes its SHA-256 as E3_CIRCUITS_ARCHIVE_SHA256 to binary builds and the ciphernode Docker build. The build binds this pin to the crate version. Each binary and image build checks the pin reported by interfold noir status before publication. Builds without this input still work. A download for an unpinned version fails with the missing archive name. The workflow publishes the exact archive that it hashed. Repacking changes the digest even when artifact bytes stay the same. SOURCE_HASH identifies source inputs and is not an archive digest. ⚠️ The preset and the committee size stay selected after the build, and they change tracked files. Always switch them with pnpm build:circuits --preset <name> --committee <name> . Do not edit active.nr , utils.ts , or a parity_*.nr file by hand. The pre-push hook runs pnpm check:committee , which rejects files that disagree. Circuit artifacts and verifiers are specific to the pair, so a changed H needs new circuits and new verifiers. Other circuit commands: Command What it does pnpm build:circuits --dry-run Lists the circuits that a build compiles, and stops. pnpm build:circuits --group dkg --skip-vk Compiles one group and skips the verification keys. pnpm build:circuits hash
프로젝트로 돌아가기