The Interfold 백서

The Interfold

원문

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

4 + 4(N - 1) P = 14 + 4 ( N − 1 ) The base cost B B B is the sum of these terms. Each coefficient is a PricingConfig field in raw fee-token units. Term Formula PricingConfig field Key generation, fixed part k f ⋅ N k_f \cdot N k f ​ ⋅ N keyGenFixedPerNode Key generation, proofs k p ⋅ N ⋅ P k_p \cdot N \cdot P k p ​ ⋅ N ⋅ P keyGenPerEncryptionProof Key generation coordination c ⋅ N ( N − 1 ) / 2 c \cdot N(N-1)/2 c ⋅ N ( N − 1 ) /2 coordinationPerPair Proof verification v ⋅ N ⋅ P v \cdot N \cdot P v ⋅ N ⋅ P verificationPerProof Availability a ⋅ N ⋅ D a \cdot N \cdot D a ⋅ N ⋅ D availabilityPerNodePerSec Decryption d ⋅ H d \cdot H d ⋅ H decryptionPerNode Decryption coordination c ⋅ H ( H − 1 ) / 2 c \cdot H(H-1)/2 c ⋅ H ( H − 1 ) /2 coordinationPerPair Publication p p p publicationBase D D D is the billable duration in seconds. The contract takes the larger of two pre-compute estimates, then adds weighted compute and decryption time. It rounds D D D down to whole seconds. D = max ⁡ ( W s + L + W k u k , E − t ) + W c u c + W d u d D = \max\left(W_s + L + W_k u_k,\ E - t\right) + W_c u_c + W_d u_d D = max ( W s ​ + L + W k ​ u k ​ , E − t ) + W c ​ u c ​ + W d ​ u d ​ In this formula: W s W_s W s ​ is the sortition submission window, and L L L is the input window length. W k W_k W k ​ , W c W_c W c ​ , and W d W_d W d ​ are the DKG, compute, and decryption windows. u k u_k u k ​ , u c u_c u c ​ , and u d u_d u d ​ are dkgUtilizationBps , computeUtilizationBps , and decryptUtilizationBps , as fractions of 10,000. E E E is the input window end, and t t t is the block time. The service fee is S = B ⋅ ( 10000 + m ) / 10000 S = B \cdot (10000 + m) / 10000 S = B ⋅ ( 10000 + m ) /10000 , where m m m is marginBps . The total fee is S S S plus randomnessFlatFee . The contract uses integer division. These rules follow from the formula: A larger committee costs more. The key generation and coordination terms grow with N 2 N^2 N 2 . A later input window costs more for the same length. The E − t E - t E − t term reserves node availability from the request to the end of the input window. For the same parameters and pricing, a later block gives the same quote or a lower quote. request computes the quote again, so a fee approved from an earlier quote is enough. getE3Quote reverts when the request is not valid. The errors are InvalidInputDeadlineStart , InvalidInputDeadlineEnd , InvalidDuration , UnsupportedCryptoConfig , CommitteeSizeNotConfigured , CommitteeSizeTooSmall , ThresholdTooSmall , and PaymentRequired . An unregistered parameter set reverts with the message BFV param set not registered . Fee token and pricing per network The deployment configuration sets the fee token and the pricing. Governance can change these values with setFeeAssetConfig and setRandomnessFlatFee . Read the live values with feeToken() , feeTokenDecimals() , and getPricingConfig() . Setting Ethereum mainnet Sepolia Local chains Fee token USDS, 18 decimals MockUSDC , 6 decimals MockUSDC , 6 decimals randomnessFlatFee 5 USDS 1 USDC 1.00 MockUSDC marginBps 1000 (10%) 1000 (10%) 1000 (10%) protocolShareBps 182 (1.82% of service fees) 182 182 minCommitteeSize 19 3 0 (no minimum) minThreshold 2 2 0 (no minimum) The mainnet values come from deploy/protocol/mainnet-protocol.config.json . The Sepolia values come from deploy/protocol/sepolia-protocol.config.json . The local values come from scripts/deployInterfold.ts . On Sepolia, MockUSDC is a test token that anyone can mint. To get Sepolia USDC, run interfold faucet --chain sepolia . You can also call faucet() on the Faucet contract, or call mint on MockUSDC . For the contract addresses, see Contracts & Addresses . Each request freezes its fee token. Refunds and rewards for that E3 use the frozen token, also after governance changes the fee token. The lifecycle from the requester side E3 lifecycle for a requester 1 Requested 2 Committee​Finalized 3 Key​Published 4 Ciphertext​Ready 5 Complete 6 Failed 01 Requester E3Requested Requested The fee transfer succeeds. The registry requests VRF randomness and opens ticket submission. Each stage has a deadline. The contract sets each deadline when the E3 enters the stage. Stage Deadline Failure reason after the deadline Requested The registry committee deadline. The contract adds the DKG window when enough tickets arrive. CommitteeFormationTimeout CommitteeFinalized dkgDeadline : the committee deadline plus the DKG window. DKGTimeout KeyPublished computeDeadline : the later of key publication and the input window end, plus the compute window. ComputeTimeout CiphertextReady decryptionDeadline : the ciphertext publication time plus the decryption window. DecryptionTimeout The committee must publish its key before the DKG deadline and before the input window ends. A key publication after the DKG deadline reverts with DKGDeadlinePassed . A key publication after the input window end reverts with InputWindowClosedBeforeKeyPublication . Read the deadlines of an E3 with getDeadlines(e3Id) . The mainnet deployment configuration sets these windows: Window Mainnet value Randomness request timeout 3600 s (1 hour) Sortition submission window 600 s (10 minutes) DKG window 21600 s (6 hours) Compute window 604800 s (7 days) Decryption window 21600 s (6 hours) maxDuration 2592000 s (30 days) markFailedGracePeriod 3600 s (1 hour) When an E3 fails An E3 moves to Failed in one of these ways: Timeout. After a stage deadline, markE3Failed(e3Id) records the timeout reason for that stage. During markFailedGracePeriod , only the requester, the owner, or an active committee member can call it. After the grace period, anyone can call it. Committee formation. finalizeCommittee on the registry records CommitteeFormationTimeout when no usable randomness arrived. It records InsufficientCommitteeMembers when fewer than N tickets arrived. Slashing. An expulsion that leaves fewer than H active members records InsufficientCommitteeMembers . Cancellation. The requester calls cancelE3 . See Cancel a request . Ciphernodes watch the deadlines and submit markE3Failed and processE3Failure for you. Any account can also submit them. Who pays for a failure lib/FailurePayerLib.sol assigns each failure reason to a payer. The payer decides the refund. Payer Failure reasons Requester refund of the service escrow Ciphernodes CommitteeFormationTimeout , InsufficientCommitteeMembers , DKGTimeout , DKGInvalidShares , DecryptionTimeout , DecryptionInvalidShares , VerificationFailed 100% Requester NoInputsReceived , ComputeTimeout , ComputeProviderExpired , ComputeProviderFailed , RequesterCancelled The share for work that was not done For a requester-paid failure, the refund manager uses the work allocation that was frozen at request time. The default allocation is committeeFormationBps 1000, dkgBps 4000, decryptionBps 4500, and protocolBps 500. The four requester-paid reasons that new E3s can record map to the KeyPublished stage, so the split is: Recipient Share of the service escrow Honest committee members 50% Requester 45% Treasury 5% If no honest member remains, the members' share goes to the requester. RequesterCancelled is kept only for old E3s. New cancellations use CommitteeFormationTimeout . ⚠️ An E3 that gets no ciphertext output before the compute deadline fails with ComputeTimeout . The requester pays for that failure. Make sure that your compute provider and your server can publish the output inside the compute window. These rules apply in every case: The flat randomness fee is not refunded. Slashed ciphernode collateral goes to the honest committee members, or to the treasury when no honest member remains. It does not go to the requester. Cancel a request cancelE3(e3Id) is a recovery path for a randomness request that did not produce a usable result. The call succeeds only when all of these conditions are true: The caller is the requester ( NotRequester ). The E3 is in Requested . The registry has no sortition seed for the E3. The randomness deadline has passed. Otherwise the call reverts with E3NotCancellable . A valid VRF result disables cancellation. A requester therefore cannot see a committee and then cancel it to get a new draw. A cancellation fails the E3 with CommitteeFormationTimeout and releases the committee. The requester gets 100% of the service escrow after settlement. The registry marks the randomness provider as degraded and emits RandomnessCircuitBreakerTripped . This flag is advisory. It does not stop new requests, and a new provider clears it. Claim a refund Refunds are pull payments. Any account can do the first three steps. Do the last step from the requester address. Confirm that the E3 failed Read getE3Stage(e3Id) on the Interfold contract. The value must be Failed (6). The E3Failed event also gives the reason. Wait for settlement to open For an E3 with a finalized committee, settlement opens one day after getE3LifecycleDeadline(e3Id) . It also waits until no open proposal can expel a committee member. An E3 without a finalized committee settles at once. Before settlement opens, processE3Failure reverts with SettlementBlocked . Process the failure Call processE3Failure(e3Id) on the Interfold contract, if no other account has called it. The call moves the service escrow to the refund manager, and the refund manager emits RefundDistributionCalculated . NoPaymentToRefund means that another account already processed the E3. Claim the refund Call claimRequesterRefund(e3Id) on the E3RefundManager from the requester address. The contract pays the refund in the fee token that was frozen for the E3. It emits RefundClaimed . Use the refund manager that was current when you made the request. e3RefundManager() on the Interfold contract returns the current one. getRefundDistribution(e3Id) returns the calculated split, and hasRequesterClaimed(e3Id, account) shows whether you already claimed. The refund manager has no claim deadline. The claim reverts with RefundNotCalculated , NotRequester , AlreadyClaimed , or NoRefundAvailable when it cannot pay. Choose a committee size and parameter set The committee size is an enum. Each size fixes N, H, and T in lib/ActiveCryptoConfig.sol . You cannot choose other values. Size Enum value N (members) H (honest count) T (threshold) Shares to decrypt (T + 1) Minimum 0 3 2 1 2 Micro 1 9 5 4 5 Small 2 19 14 9 10 The committee stays viable while at least H members stay active. Decryption needs T + 1 shares. The parameter set selects the BFV parameters. The SDK preset must match it. paramSet SDK preset name Ring degree Use 0 INSECURE_THRESHOLD_512 512 Tests only. It has no production security. 2 SECURE_THRESHOLD_8192 8192 Production. Each network accepts different pairs: Network Parameter sets Committee sizes Ethereum mainnet 2 only Small only. The launch pricing sets minCommitteeSize to 19. Sepolia, local chains (31337 and 1337) 0 and 2 All three sizes, when the deployment configures their thresholds. A parameter set must also be registered on the chain. paramSetRegistry(paramSet) returns empty bytes for an unregistered set. The local deploy script registers the set of the active circuit build (set 0 in the checked-in configuration). With mock verifiers, it configures thresholds for all three sizes. With ENABLE_ZK_VERIFICATION=true , it configures thresholds only for the committee of the active circuit build, because its verifiers check only that committee. Mainnet retains index 1 for older E3s; version-7 requests use index 2. Use these rules to choose: Choose paramSet 2 for any value that must stay private. Choose a larger committee for more fault tolerance. It costs more. Make sure that the network has enough eligible ciphernodes and bond owners. The request reverts when fewer than N are available. Call getE3Quote to test a pair before you request. It reverts for a pair that the chain does not accept. Checklist Before each request: Confirm that requestsPaused() returns false . Confirm that e3Programs(program) returns true . Confirm that the chain accepts your committee size and parameter set. Set the SDK preset to match paramSet . Set the input window start a few seconds after the current block time. Set the input window end after the worst-case key publication time. Get the fee with getE3Quote . Approve exactly that amount for the Interfold contract. Set maxFee to the quoted amount. The worst-case key publication time is the request time plus the randomness timeout, the sortition submission window, and the DKG window. On mainnet, that sum is 25,800 seconds. After the request: Watch E3StageChanged and E3Failed for your E3 ID. Publish the ciphertext output before the compute deadline. If the E3 fails, process the failure and claim the refund from the requester address. Next steps The Interfold Contract Function signatures, events, and custom errors. Build SDK Quote, approve, and request an E3 from TypeScript. Build Best practices Design and operations practices for E3 programs. Build E3 lifecycle The stages, the events, and the timeouts in detail. Concepts The Interfold Contract SDK ## /build/sdk Build SDK SDK This page is the reference for the TypeScript SDK ( @interfold/sdk ) and the React hook package ( @interfold/react ). It is for developers who write an E3 client or a coordination server. It covers installation, the client class, requests, the committee public key, encryption, events, enums, utilities, and errors. The samples come from the default template ( templates/default ) and the SDK README. Every export on this page exists in version 0.18.0. Packages Both packages are in this repository. Package Source Import paths @interfold/sdk packages/interfold-sdk/src @interfold/sdk , @interfold/sdk/crypto , @interfold/sdk/contracts , @interfold/sdk/events @interfold/react packages/interfold-react/src @interfold/react Your application Browser or Node.js React client Coordination server @interfold/react Optional useInterfoldSDK @interfold/sdk Core InterfoldSDK ContractClient EventListener Encryption functions Dependencies Installed with the SDK @interfold/wasm @interfold/contracts viem @aztec/bb.js @noir-lang/noir_js Install Add the SDK. Add the React package only if you use React. pnpm add @interfold/sdk pnpm add @interfold/react @interfold/react has two peer dependencies: react ( ^18.2.0 ) and wagmi ( ^2.14.16 ). The encryption functions use WebAssembly. In a Vite project, add vite-plugin-wasm and vite-plugin-top-level-await , and exclude @interfold/wasm from dependency optimization. This configuration comes from the SDK README: vite.config.ts import { defineConfig } from 'vite' import wasm from 'vite-plugin-wasm' import topLevelAwait from 'vite-plugin-top-level-await' export default defineConfig ({ optimizeDeps : { exclude : [ '@interfold/wasm' ] , } , plugins : [ wasm () , topLevelAwait ()] , }) The template client uses the same two plugins in client/vite.config.ts . Create a client With viem clients new InterfoldSDK(config) creates the client. No separate initialize call is necessary. SDKConfig field Type Required Content publicClient PublicClient Yes A viem public client for reads and events. walletClient WalletClient No A viem wallet client with an account. Write calls need it. contracts ContractAddresses Yes interfold , ciphernodeRegistry , and feeToken addresses. chain Chain No The viem chain. thresholdBfvParamsPresetName ThresholdBfvParamsPresetName No The BFV preset. The default is INSECURE_THRESHOLD_512 . The constructor throws an SDKError with the code MISSING_PUBLIC_CLIENT , INVALID_ADDRESS , or INVALID_THRESHOLD_BFV_PARAMS_PRESET_NAME when the configuration is not valid. import { InterfoldSDK } from '@interfold/sdk' import { createPublicClient , createWalletClient , custom , http } from 'viem' import { sepolia } from 'viem/chains' const publicClient = createPublicClient ({ chain : sepolia , transport : http ( RPC_URL ) }) // The SDK signs with walletClient.account, so create the wallet client with an account. const [ account ] = await createWalletClient ({ chain : sepolia , transport : custom ( window .ethereum ! ) , }) .requestAddresses () const walletClient = createWalletClient ({ account , chain : sepolia , transport : custom ( window .ethereum ! ) , }) const sdk = new InterfoldSDK ({ publicClient , walletClient , contracts : { interfold : INTERFOLD_ADDRESS , ciphernodeRegistry : REGISTRY_ADDRESS , feeToken : FEE_TOKEN_ADDRESS , } , chain : sepolia , thresholdBfvParamsPresetName : 'SECURE_THRESHOLD_8192' , }) With the factory InterfoldSDK.create(options) creates the viem clients for you. It is useful on a server. Option Required Content rpcUrl Yes An http:// , https:// , ws:// , or wss:// URL. contracts Yes interfold , ciphernodeRegistry , and feeToken addresses. chain Yes The viem chain. privateKey No A private key for a local signing account. Omit it for a read-only client. thresholdBfvParamsPresetName No The BFV preset. A ws:// or wss:// URL gives a WebSocket transport with a 30-second keep-alive and five reconnect attempts at 2-second intervals. Other URLs give an HTTP transport. This sample comes from templates/default/server/index.ts : import { InterfoldSDK } from '@interfold/sdk' import { hardhat } from 'viem/chains' const sdk = InterfoldSDK .create ({ rpcUrl : RPC_URL , privateKey : PRIVATE_KEY as `0x ${ string } ` , contracts : { interfold : INTERFOLD_CONTRACT as `0x ${ string } ` , ciphernodeRegistry : CIPHERNODE_REGISTRY_CONTRACT as `0x ${ string } ` , feeToken : FEE_TOKEN_CONTRACT as `0x ${ string } ` , } , chain : hardhat , thresholdBfvParamsPresetName : 'INSECURE_THRESHOLD_512' , }) BFV presets The preset selects the BFV parameters that the client uses to encrypt. It must match the paramSet of the E3. Preset name paramSet Ring degree CRT moduli (L) Use INSECURE_THRESHOLD_512 0 512 2 Local development and tests SECURE_THRESHOLD_8192 2 8192 3 Production and secure test runs The insecure preset has no production security. Use it only for tests. ThresholdBfvParamsPresetNames lists both names, and DEFAULT_THRESHOLD_BFV_PARAMS_PRESET_NAME is INSECURE_THRESHOLD_512 . ⚠️ The SDK does not compare the preset with the paramSet of the E3. A mismatch encrypts inputs under the wrong parameters, and the committee cannot decrypt the result. Request an E3 The request takes three calls: quote the fee, approve the fee token, and send the request. This sample is trimmed from templates/default/client/src/pages/steps/RequestComputation.tsx . It adds maxFee . import { DEFAULT_COMPUTE_PROVIDER_PARAMS , DEFAULT_E3_CONFIG , calculateInputWindow , encodeComputeProviderParams , } from '@interfold/sdk' const publicClient = sdk .getPublicClient () const inputWindow = await calculateInputWindow (publicClient , 100 ) // 100 seconds const requestParams = { committeeSize : DEFAULT_E3_CONFIG .committeeSize , // CommitteeSize.Minimum inputWindow , e3Program : E3_PROGRAM_ADDRESS , paramSet : 0 , // insecure-512, for local development computeProviderParams : encodeComputeProviderParams ( DEFAULT_COMPUTE_PROVIDER_PARAMS ) , } const fee = await sdk .getE3Quote (requestParams) const approveTx = await sdk .approveFeeToken (fee) await publicClient .waitForTransactionReceipt ({ hash : approveTx }) const hash = await sdk .requestE3 ({ ... requestParams , maxFee : fee }) E3RequestParams in the SDK has these fields: Field Type Default committeeSize number ( CommitteeSize ) Required inputWindow readonly [bigint, bigint
프로젝트로 돌아가기