bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 16쪽
ify
Interfold contract, at output publication
Checks the parameter hash and the input root in the proof, rebuilds the journal, calls the receipt verifier.
verifyDataAvailability
Interfold contract, at output publication
Local only. It accepts the output bytes as their own receipt.
The template
publishInput
checks only the end of the input window. Add the stage check and the
start-of-window check that
CRISPProgram
makes. Add two errors next to the other errors:
contracts/MyProgram.sol
error
KeyNotPublished
(
uint256
e3Id);
error
InputWindowNotOpen
(
uint256
e3Id);
Then replace the first check in
publishInput
:
contracts/MyProgram.sol
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)
=
abi.
decode
(data
,
(
bytes
,
bytes32
));
if
(ciphertext.length
==
0
)
revert
EmptyInputData
();
uint256
index
=
inputs[e3Id].numberOfLeaves;
inputs[e3Id].
_insert
(
uint256
(ciphertextCommitment));
emit
InputPublished
(e3Id
,
ciphertext
,
index);
}
Compile the contracts. The command also regenerates the TypeChain types in
types/
, which the
server and the deploy script import:
pnpm
compile
⚠️
The template does not check that the ciphertext bytes match the commitment, as the comment in
publishInput
says. An input with a wrong commitment can stop the E3 from completing. A
production program must check that binding, for example with a proof. See
Custom Noir
Circuits
.
Keep the
verify
function as it is. It compares
computeProof.inputRoot
with
inputs[e3Id]._root()
. The protocol ciphertext verifier does not check the input root, so this
comparison is the only check that the output covers your inputs.
Read the deploy script
deploy/default.ts
exports
deployTemplate
.
scripts/deploy-local.ts
calls it after
deployInterfold(true, false)
, which deploys the protocol with mocks.
deployTemplate
does these
steps:
With
TEMPLATE_UNPROVED_TEST=1
(the local default), it deploys
MockOpenVmReceiptVerifier
,
which accepts every proof on the local chain only. Otherwise it deploys an
OpenVmReceiptVerifier
for the guest that
interfold program compile
built.
It deploys
OpenVmBfvCiphertextVerifier
for that receipt identity and calls
setCiphertextVerifier
on the Interfold contract.
It deploys
MyProgram
with the Interfold address, the receipt verifier, and its identity. It
links
PoseidonT3
for the input tree.
It calls
registerE3Program
and checks
e3Programs(program)
.
It records the addresses in
deployed_contracts.json
and
interfold.config.yaml
.
setCiphertextVerifier
and
registerE3Program
are
onlyOwner
functions. They work locally because
the deployer owns the local Interfold contract. If you add a constructor argument to
MyProgram
,
add it to the
e3ProgramFactory.deploy(...)
call.
Read the coordination server
server/index.ts
runs the computation when the input window closes. It needs a private key to
publish the output, so it runs on a server and not in the browser.
It listens for
CommitteePublicKeyChunkPublished
. When a key is complete, it checks the key
against its commitment with
validatePublicKeyCommitment
.
It waits until the chain time passes
inputWindow[1]
.
It reads the parameter bytes from
paramSetRegistry
and every
InputPublished
event of the E3.
It skips an E3 with one input or fewer.
It sends the job to the program server at
PROGRAM_RUNNER_URL
(
POST /run_compute
).
The program server calls back at
CALLBACK_URL
. The server stores the output bytes and calls
publishCiphertextOutput
.
Variable
Source
INTERFOLD_ADDRESS
,
REGISTRY_ADDRESS
,
E3_PROGRAM_ADDRESS
,
FEE_TOKEN_ADDRESS
interfold print-env --chain localhost
RPC_URL
,
PRIVATE_KEY
,
CHAIN_ID
scripts/dev_server.sh
sets them for the local chain
PROGRAM_RUNNER_URL
Default
http://127.0.0.1:13151
CALLBACK_URL
Default
http://127.0.0.1:8080
PORT
Default
8080
The server reads the
data
field of
InputPublished
as the ciphertext. If you change the event,
change
runProgram
in
server/index.ts
too.
⚠️
The program server that
pnpm dev:all
starts is a development service. It accepts any callback
URL and does not authenticate callers. Keep it isolated from production and untrusted networks.
Read the client
The client uses
useInterfoldSDK
from
@interfold/react
. The SDK configuration is in
client/src/utils/sdk-config.ts
, and the addresses come from the
VITE_*
variables that
interfold print-env --vite
prints.
The request step (
RequestComputation.tsx
) gets a quote, approves the fee token, and requests the
E3:
client/src/pages/steps/RequestComputation.tsx
const
inputWindow
=
await
calculateInputWindow
(publicClient
,
100
)
// 100 Seconds
const
computeProviderParams
=
encodeComputeProviderParams
(
DEFAULT_COMPUTE_PROVIDER_PARAMS
)
const
requestParams
=
{
committeeSize
:
DEFAULT_E3_CONFIG
.committeeSize
,
inputWindow
,
e3Program
:
contracts
.e3Program
,
paramSet
:
0
,
// ParamSet.Insecure512
computeProviderParams
,
}
const
fee
=
await
sdk
.
sdk
.getE3Quote
(requestParams)
const
approveTx
=
await
sdk
.
sdk
.approveFeeToken
(fee)
await
publicClient
.waitForTransactionReceipt
({ hash
:
approveTx })
const
hash
=
await
requestE3
(requestParams)
The same step assembles the committee public key from
COMMITTEE_PUBLIC_KEY_CHUNK_PUBLISHED
events
with
CommitteePublicKeyAssembler
. It accepts the key only if
validatePublicKeyCommitment
returns
true
.
The input step (
EnterInputs.tsx
) encrypts each number to that key, computes its commitment, and
calls
publishInput
on the program contract:
client/src/pages/steps/EnterInputs.tsx
const
encryptedInput1
=
await
sdk
.
sdk
?.encryptNumber
(num1
,
publicKeyBytes)
const
commitment1
=
await
sdk
.
sdk
.computeCiphertextCommitment
(encryptedInput1)
await
publishInput
(
walletClient
,
e3State
.id
,
toHex
(encryptedInput1)
,
toHex
(commitment1)
,
address
,
contracts
.e3Program
,
)
publishInput
in
client/src/utils/input.ts
encodes
(bytes, bytes32)
, the format that
MyProgram.publishInput
decodes. The submit step (
EncryptSubmit.tsx
) waits for
PLAINTEXT_OUTPUT_PUBLISHED
, decodes the value with
decodePlaintextOutput
, and opens the results
step.
To follow the output publication, listen for
InterfoldEventType.CIPHERTEXT_OUTPUT_REFERENCE_PUBLISHED
. The Interfold contract emits
CiphertextOutputReferencePublished
when it accepts the ciphertext output. It does not emit
CiphertextOutputPublished
.
Run the changed program
Start the stack again:
pnpm
dev:all
The deploy step compiles and deploys the changed
MyProgram
. Run one E3 in the client. The result
is the sum of the two inputs, as before. The new checks reject an input that arrives before the
committee key is published or before
inputWindow[0]
.
What must stay the same across the parts
A change in one part often needs a change in another part. Check this table after each change.
Value
Where it is set
Where it must match
Input encoding
abi.decode(data, (bytes, bytes32))
in
publishInput
encodeAbiParameters
in
client/src/utils/input.ts
and
server/input.ts
Input tree leaf
inputs[e3Id]._insert(uint256(ciphertextCommitment))
policy()
in
program/src/lib.rs
Input event
InputPublished(e3Id, data, index)
getContractEvents
in
server/index.ts
BFV parameter set
paramSet: 0
in the request
thresholdBfvParamsPresetName: 'INSECURE_THRESHOLD_512'
in the SDK config
Receipt identity
guest/
and
program/
, built by
interfold program compile
The
imageId
in the
MyProgram
constructor and in
OpenVmBfvCiphertextVerifier
The E3 flow
The client calls
publishInput
on the program contract. The Interfold contract does not forward
inputs. See
E3 Lifecycle
for the stages and deadlines.
Next steps
Custom Noir circuits
Add a proof that each input is valid, and check it in
publishInput
.
Tutorial
Encrypt and submit
Encrypt inputs and submit them with the SDK.
Tutorial
Deploy to Sepolia
Deploy the program to the testnet and request an E3 there.
Tutorial
E3 program contract
The full
IE3Program
interface and what each function must check.
Build
Best Practices
Custom Noir Circuits
## /build/tutorials/custom-zk-circuits
Build
Tutorials
Custom Noir Circuits
Custom Noir Circuits for Input Validation
An E3 program contract cannot read the plaintext of an input. If the program must reject bad inputs,
the submitter must attach a zero-knowledge proof. This tutorial adds that proof to the default
template: each input must encrypt 0 or 1, so the sum is a count of "yes" answers. The steps follow
what CRISP does in
examples/CRISP/circuits
and
packages/crisp-contracts
.
At the end, you have two Noir circuits, a generated Solidity verifier, and a
publishInput
that
rejects an input without a valid proof.
This tutorial targets Interfold
v0.18.0
and its toolchain. For source builds from another
checkout, use that checkout's matching SDK, circuits, and
toolchain pins
.
Prerequisites:
A project from the default template. See
Build a Complete E3 Program
.
nargo
1.0.0-beta.26
and
bb
5.1.0
on your
PATH
. See
Noir Circuits
.
A checkout of the Interfold repository at the tag
v0.18.0
, with Rust installed. You compile the
user-data-encryption circuits and run one Rust tool from it.
What the proof shows
The final proof combines three proofs. The Interfold repository supplies the first two circuits. You
write the last two.
Circuit
Source
Proves
user_data_encryption_ct0
,
user_data_encryption_ct1
circuits/bin/threshold
Each part of the BFV ciphertext is a correct encryption under the committee key.
user_data_encryption
circuits/bin/threshold
Both part proofs are valid and use the same randomness.
binary_input
Your project
The plaintext is 0 or 1.
binary_input_fold
Your project
Both proofs describe the same ciphertext and plaintext, and each circuit is the expected one.
The circuits connect through commitments.
user_data_encryption
outputs five public values:
ct0_key_hash
,
ct1_key_hash
,
pk_commitment
,
ct_commitment
, and
k1_commitment
. Your input
circuit computes
ct_commitment
and
k1_commitment
from the same ciphertext and plaintext. The
fold circuit checks that the values are equal.
Encrypt
The SDK encrypts the value and returns the circuit inputs.
Encryption proof
ct0, ct1, and user_data_encryption.
Rule proof
binary_input checks the plaintext.
Fold
binary_input_fold makes one EVM proof.
publishInput
The program calls the Solidity verifier.
In CRISP, the
crisp
circuit has the role of
binary_input
, and
fold
has the role of
binary_input_fold
. The CRISP rules are larger (eligibility, signatures, and ciphertext addition),
but the structure is the same.
Project layout
Add a
circuits
directory to the project. The verifier goes in
contracts/verifiers
.
my-e3
circuits
binary_input
Nargo.toml
src
main.nr
binary_input_fold
Nargo.toml
src
main.nr
contracts
MyProgram.sol
verifiers
BinaryInputVerifier.sol
Write the input circuit
Create
circuits/binary_input/Nargo.toml
. The library at
v0.18.0
uses the
insecure-512
preset,
which the template requests (
paramSet: 0
).
circuits/binary_input/Nargo.toml
[package]
name
=
"binary_input"
type
=
"bin"
[dependencies]
interfold_lib
=
{ git
=
"https://github.com/theinterfold/interfold"
,
tag
=
"v0.18.0"
,
directory
=
"circuits/lib"
}
Create
circuits/binary_input/src/main.nr
:
circuits/binary_input/src/main.nr
use interfold_lib::configs::default::threshold::{
L, N, Q_MOD_T_CENTERED, USER_DATA_ENCRYPTION_BIT_CT, USER_DATA_ENCRYPTION_BIT_K,
};
use interfold_lib::math::{
commitments::{
compute_ciphertext_commitment, compute_single_polynomial_commitment,
DS_USER_DATA_ENCRYPTION_COMMITMENT,
},
polynomial::Polynomial,
};
/// Proves that a ciphertext encrypts 0 or 1.
///
/// Returns the ciphertext commitment and the plaintext commitment. The fold circuit compares both
/// values with the outputs of the user_data_encryption proof.
fn main(
ct0is: [Polynomial<N>; L],
ct1is: [Polynomial<N>; L],
k1: Polynomial<N>,
) -> pub (Field, Field) {
let ct_commitment =
compute_ciphertext_commitment::<N, L, USER_DATA_ENCRYPTION_BIT_CT>(ct0is, ct1is);
let k1_commitment = compute_single_polynomial_commitment::<N, USER_DATA_ENCRYPTION_BIT_K>(
k1,
DS_USER_DATA_ENCRYPTION_COMMITMENT,
);
// `k1` holds the message coefficients in descending order. `encryptNumber` writes the value
// into message coefficient 0, which is `k1.coefficients[N - 1]`. All other coefficients are 0.
for i in 0..N - 1 {
assert(k1.coefficients[i] == 0);
}
// A message bit of 1 appears in `k1` as `Q_MOD_T_CENTERED`. A bit of 0 appears as 0.
let value = k1.coefficients[N - 1];
assert(value * (Q_MOD_T_CENTERED - value) == 0);
(ct_commitment, k1_commitment)
}
The input
k1
is the plaintext polynomial scaled to
[q * m]_t
(
k1 = [q*m]_t
in
crates/zk-helpers/src/circuits/threshold/user_data_encryption/computation.rs
). For each option,
CRISP's
check_coefficient_values_with_balance
proves that the coefficient in
k1
is a weight in
[0, t)
scaled the same way. The two commitment functions are the ones that
user_data_encryption
uses, so equal inputs give equal outputs.
Check the circuit:
cd
circuits/binary_input
&&
nargo
check
The command exits without an error.
Write the fold circuit
Create
circuits/binary_input_fold/Nargo.toml
. The fold verifies proofs, so it also needs
bb_proof_verification
at the
bb
version:
circuits/binary_input_fold/Nargo.toml
[package]
name
=
"binary_input_fold"
type
=
"bin"
[dependencies]
interfold_lib
=
{ git
=
"https://github.com/theinterfold/interfold"
,
tag
=
"v0.18.0"
,
directory
=
"circuits/lib"
}
bb_proof_verification
=
{ git
=
"https://github.com/AztecProtocol/aztec-packages/"
,
tag
=
"v5.1.0"
,
directory
=
"barretenberg/noir/bb_proof_verification"
}
Create
circuits/binary_input_fold/src/main.nr
. It follows
examples/CRISP/circuits/bin/fold
:
circuits/binary_input_fold/src/main.nr
use bb_proof_verification::{UltraHonkProof, UltraHonkVerificationKey, verify_honk_proof_non_zk};
use interfold_lib::math::commitments::compute_vk_hash;
/// The hash of the four inner verification keys. Set it from the zk-artifacts vk-hash output.
pub global EXPECTED_KEY_HASH: Field = 0;
fn main(
// The user_data_encryption proof. Its public inputs are
// [ct0_key_hash, ct1_key_hash, pk_commitment, ct_commitment, k1_commitment].
user_data_encryption_verification_key: UltraHonkVerificationKey,
user_data_encryption_proof: UltraHonkProof,
user_data_encryption_public_inputs: [Field; 5],
user_data_encryption_key_hash: Field,
// The binary_input proof. Its public inputs are [ct_commitment, k1_commitment].
binary_input_verification_key: UltraHonkVerificationKey,
binary_input_proof: UltraHonkProof,
binary_input_key_hash: Field,
ct_commitment: pub Field,
k1_commitment: Field,
) -> pub Field {
verify_honk_proof_non_zk(
user_data_encryption_verification_key,
user_data_encryption_proof,
user_data_encryption_public_inputs,
user_data_encryption_key_hash,
);
verify_honk_proof_non_zk(
binary_input_verification_key,
binary_input_proof,
[ct_commitment, k1_commitment],
binary_input_key_hash,
);
// Both proofs must describe the same ciphertext and the same plaintext.
assert(ct_commitment == user_data_encryption_public_inputs[3]);
assert(k1_commitment == user_data_encryption_public_inputs[4]);
// Pin the four inner circuits. Without this check, a prover can supply any circuit.
let vk_hashes = [
user_data_encryption_key_hash,
binary_input_key_hash,
user_data_encryption_public_inputs[0],
user_data_encryption_public_inputs[1],
]
.as_vector();
assert(compute_vk_hash(vk_hashes) == EXPECTED_KEY_HASH);
// The committee public key commitment. The E3 program compares it with e3.committeePublicKey.
user_data_encryption_public_inputs[2]
}
The public inputs of the fold proof are
ct_commitment
and then the return value,
pk_commitment
.
The contract must pass them in this order.
⚠️
Do not remove the key-hash check.
verify_honk_proof_non_zk
accepts any verification key that the
prover supplies. The check against
EXPECTED_KEY_HASH
is what makes the fold accept only your
circuits.
Compile the inner circuits and write their keys
In the Interfold checkout, compile the three user-data-encryption circuits. They share the workspace
target
circuits/bin/threshold/target
:
cd
<
interfol
d
>
/circuits/bin/threshold
(
cd
user_data_encryption_ct0
&&
nargo
compile
)
(
cd
user_data_encryption_ct1
&&
nargo
compile
)
(
cd
user_data_encryption
&&
nargo
compile
)
Write a
noir-recursive-no-zk
key for each one.
bb
writes
vk
and
vk_hash
, so rename them
before the next call, as
compile_circuits.sh
does:
T
=<
interfol
d
>
/circuits/bin/threshold/target
for
name
in
user_data_encryption_ct0 user_data_encryption_ct1 user_data_encryption;
do
bb
write_vk
-b
"$T/$name.json"
-o
"$T"
-t
noir-recursive-no-zk
mv
"$T/vk"
"$T/$name.vk_recursive"
mv
"$T/vk_hash"
"$T/$name.vk_recursive_hash"
done
In your project, compile
binary_input
and write its key the same way:
cd
circuits/binary_input
nargo
compile
bb
write_vk
-b
target/binary_input.json
-o
target
-t
noir-recursive-no-zk
mv
target/vk
target/binary_input.vk_recursive
mv
target/vk_hash
target/binary_input.vk_recursive_hash
The checkout must select
insecure-512
with
minimum
, as the tag does. If you ran
pnpm build:circuits
for another pair, the user-data-encryption circuits no longer match the library
that your circuits use.
Pin the key hash
From the root of the Interfold checkout, hash the four key hashes. The order must match the order in
the fold circuit:
pnpm
zk
vk-hash
\
circuits/bin/threshold/target/user_data_encryption.vk_recursive_hash
\
<
my-e
3>
/circuits/binary_input/target/binary_input.vk_recursive_hash
\
circuits/bin/threshold/target/user_data_encryption_ct0.vk_recursive_hash
\
circuits/bin/threshold/target/user_data_encryption_ct1.vk_recursive_hash
The tool prints one field value as 32-byte hexadecimal. Set
EXPECTED_KEY_HASH
in
circuits/binary_input_fold/src/main.nr
to this value. Then compile the fold:
cd
circuits/binary_input_fold
&&
nargo
compile
Each change to
binary_input
changes its key. Repeat this step after each change.
Generate the Solidity verifier
Write the fold key for the EVM, then generate the verifier. These are the commands in
examples/CRISP/scripts/compile_circuits.sh
:
cd
circuits/binary_input_fold
bb
write_vk
-b
target/binary_input_fold.json
-o
target
--oracle_hash
keccak
mkdir
-p
../../contracts/verifiers
bb
write_solidity_verifier
-k
target/vk
-o
../../contracts/verifiers/BinaryInputVerifier.sol
The generated file declares a contract named
HonkVerifier
and the libraries
ZKTranscriptLib
and
RelationsLib
. The deployment must link the two libraries.
CRISP also changes each generated verifier with
patch_verifier
in
compile_circuits.sh
. The patch
corrects the
ModExpFailed()
error selector that
bb
emits, and it makes the constructor check the
key sizes. Copy that function if you want the same changes.
Call the verifier from publishInput
Change
contracts/MyProgram.sol
. The contract stores the verifier, and
publishInput
decodes a
third field, the proof. This version also adds the stage and window checks that
CRISPProgram
makes.
contracts/MyProgram.sol
import
{
ICircuitVerifier
}
from
'@interfold/contracts/contracts/interfaces/ICircuitVerifier.sol'
;
contract
프로젝트로 돌아가기