bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 8쪽
ut
During the input window
Server
Compute provider
POST /run_compute
After the input window closes
Compute provider
Server
Webhook callback (
callback_url
)
When the proof is ready
Server
Interfold contract
publishCiphertextOutput
Before the compute deadline
Interfold contract
Program contract
verifyDataAvailability
Inside
publishCiphertextOutput
, first
Interfold contract
OpenVmBfvCiphertextVerifier
verify
Inside
publishCiphertextOutput
, second
Interfold contract
Program contract
verify
Inside
publishCiphertextOutput
, third
Two values connect the secure process to the program contract. The first is the input root: the
compute provider and the program contract must build the same input tree from the same inputs. The
second is the image ID: the program contract and the protocol verifier accept only proofs from the
guest program that the image ID names.
Read the pages in order
1. Secure process
The FHE function, the BFV parameters it receives, and the input policy.
Rust
2. Program contract
Each
IE3Program
function, when the Interfold contract calls it, and what it must check.
Solidity
3. Compute provider
How the program server runs the secure process and returns an OpenVM proof.
Off-chain
4. Verify the compute provider
How the proof is checked on-chain, and how to check the image ID of a deployment.
Audit
5. Complete example
One E3 in the template, from request to decrypted result, with the file for each step.
Walkthrough
Next steps
Project template
The folder layout and scripts of a project that
interfold init
makes.
The Interfold contract
The stages, deadlines, and functions of
Interfold.sol
.
CRISP
A complete E3 program for private voting, with ZK input proofs.
Project Template
Secure Process
## /build/e3-program/secure-process
Build
E3 Program Anatomy
Secure Process
Secure Process
The secure process is the FHE computation of an E3 program. It receives the encrypted inputs and
returns one encrypted output. It never sees a plaintext value. This page shows the function that you
write, the data it receives, and the rules that the
e3-compute-provider
crate applies around it.
At the end, you can change the computation in
program/src/lib.rs
and test it.
What you write
An E3 program crate exports two functions from
program/src/lib.rs
:
Function
Type
Purpose
fhe_processor
fn(FHEProcessorInput<'_>) -> Vec<u8>
The computation. It returns the serialized output ciphertext.
policy
fn() -> InputPolicy
How each input becomes a tree leaf, and which inputs to compute over.
The crate is named
e3-user-program
in the template (
program/Cargo.toml
). It depends on
fhe
and
fhe-traits
(fhe.rs, tag
v0.4.2
),
e3-compute-provider
, and
e3-fhe-params
. The dev runner, the
OpenVM service, and the OpenVM guest in
guest/
link a crate with this name and call these two
functions. See
The guest must match your E3 program
.
This is the policy and the processor of the default template
(
templates/default/program/src/lib.rs
) without the comments and the test. The processor adds all
inputs:
program/src/lib.rs
use
e3_compute_provider
::
{
FHEProcessorInput
,
InputPolicy
};
use
fhe
::
bfv
::
Ciphertext
;
use
fhe_traits
::
{
DeserializeParametrized
,
Serialize
};
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
()
}
CRISP uses the same processor (
examples/CRISP/program/src/lib.rs
). The two programs differ only in
their input policy. See
Input policy
.
Processor inputs
The crate defines the processor type and its input in
crates/compute-provider/src/compute_input.rs
:
crates/compute-provider/src/compute_input.rs
pub
type
FHEProcessor
=
for
<'
a
>
fn
(
FHEProcessorInput
<'
a
>)
->
Vec
<
u8
>;
pub
struct
FHEProcessorInput
<'
a
> {
pub
ciphertexts
:
&
'
a
mut
dyn
Iterator
<
Item
=
(
Vec
<
u8
>,
u64
)>,
pub
params
:
&
'
a
Arc
<
BfvParameters
>,
}
Field
Content
ciphertexts
The serialized fhe.rs BFV ciphertexts that the policy selected, one at a time, in index order. Each has its on-chain input index.
params
The BFV parameters of the E3, decoded one time and shared with the processor.
The processor receives only the inputs that the policy selected, and it must read every one. The
crate builds the input tree from all inputs first. Inside the OpenVM guest, each ciphertext is read
from the input stream and checked against the hash of its first read only when the processor asks
for it, so keep the state that the processor carries between inputs small. See
Rules the crate enforces
.
BFV parameters
The Interfold contract stores one ABI-encoded parameter set for each
paramSet
index
(
paramSetRegistry
, set with
setParamSet
). The request names the index. The server reads the
bytes for the E3 and sends them to the compute provider as
params
. The crate decodes them with
decode_bfv_params_arc
(
crates/fhe-params/src/encoding.rs
). The encoding is the tuple
(degree, plaintext_modulus, moduli[], error1_variance)
.
The same bytes reach
IE3Program.validate
as
e3ProgramParams
. The program contract stores their
Keccak-256 hash. The proof must carry the same parameter hash. See
Program Contract
.
paramSet
Preset
Degree
Plaintext modulus
Ciphertext moduli
0
InsecureThreshold512
512
100
2
2
SecureThreshold8192
8192
17000000
3
Sources:
BfvPreset::from_on_chain_param_set
in
crates/fhe-params/src/presets.rs
and the preset
constants in
crates/fhe-params/src/constants.rs
.
⚠️
Parameter set
0
is insecure. It exists for local development and tests. The template client
requests it (
paramSet: 0
in
client/src/pages/steps/RequestComputation.tsx
). Use parameter set
2
for real data.
Processor output
The processor returns the serialized output ciphertext (
Ciphertext::to_bytes
). The crate then
computes four values from the run (
SecureProcess
, which
ComputeInput::run
also uses):
Value
How the crate computes it
ciphertext_hash
Keccak-256 of the output bytes
ciphertext_commitment
The SAFE commitment of the output ciphertext
params_hash
Keccak-256 of the encoded BFV parameters
merkle_root
The Poseidon root of the input tree, one leaf for each input
The compute provider writes these values into the proof journal. The program contract and the
protocol verifier check them. See
Verify the Compute Provider
.
Input policy
An
InputPolicy
holds two function pointers (
crates/compute-provider/src/policy.rs
):
crates/compute-provider/src/policy.rs
pub
type
LeafFn
=
fn
(
&
PublishedInput
)
->
Result
<
String
,
ComputeError
>;
pub
type
SelectFn
=
fn
(
&
[
InputRecord
])
->
Vec
<
usize
>;
pub
struct
InputPolicy
{
pub
leaf
:
LeafFn
,
pub
select
:
SelectFn
,
}
leaf
builds the tree leaf for one input. It must return the same value that the program contract
inserts on-chain for that input. Otherwise the input roots do not match and the output cannot be
published.
select
returns the indices of the inputs to compute over. It must be a function of data that the
input root binds. Then every prover that uses the same inputs selects the same set.
PublishedInput
gives the leaf function the input
index
, the
ciphertext
bytes and their
Keccak-256
ciphertext_hash
, the
commitment
that the contract stored (if any), opaque
metadata
,
and
recomputed
. The
recomputed
field is the commitment that the crate computes from the bytes.
It is
None
when the bytes do not deserialize.
select
receives an
InputRecord
for each input: the same fields without the ciphertext bytes. The
secure process reads each ciphertext once for its leaf and does not keep it, so selection works on
what remains. Both types have
matches_commitment()
.
Default policy
InputPolicy::default()
uses
commitment_leaf
and
all_inputs
. The leaf is the SAFE commitment of
the ciphertext, and every input is computed over. This matches
MyProgram.publishInput
, which
inserts the commitment in the tree. Under this policy, an input that does not deserialize stops the
run with
ComputeError::LeafCommitment
.
CRISP policy
CRISP binds four values in each leaf and computes over one input for each voter slot. Its leaf
function matches
CRISPProgram.inputLeaf
:
examples/CRISP/program/src/lib.rs
pub
fn
leaf
(input
:
&
PublishedInput
)
->
Result
<
String
,
ComputeError
> {
let
commitment
=
input
.
commitment
.
ok_or_else
(
||
ComputeError
::
LeafCommitment
{
index
:
input
.
index,
reason
:
"CRISP publishes a commitment with every input"
.
to_string
(),
})
?
;
metadata_of
(input
.
index, input
.
metadata)
?
;
let
mut
outer
=
Sha256
::
new
();
outer
.
update
(input
.
ciphertext_hash
.
as_slice
());
outer
.
update
(commitment);
outer
.
update
(input
.
metadata);
Ok
(
leaf_from_digest
(
&
outer
.
finalize
()))
}
pub
fn
crisp
()
->
InputPolicy
{
InputPolicy
{
leaf,
select
:
chain_head_per_slot,
}
}
The metadata is the 20-byte slot address and a 5-byte parent index.
chain_head_per_slot
skips an
input when its bytes do not match its commitment. It also skips an input that does not extend the
current head of its slot. A skipped input keeps its leaf, so the root does not change.
leaf_from_digest
reduces a digest into the BN254 scalar field and returns it as hex. Use it when
your leaf is a hash.
Rules the crate enforces
The crate applies these rules for every E3 program. A policy cannot change them.
The crate derives every leaf from the ciphertexts that the secure process consumes.
ComputeInput
has no field for a root or for leaves.
Every published input gets a leaf, also when
select
does not choose it.
A selected index outside the input list stops the run with
ComputeError::MerkleTree
.
A selected ciphertext that differs from its first read stops the run with
ComputeError::InputChanged
, and a processor that returns before it reads every selected input
stops it with
ComputeError::Unread
.
When the program publishes per-input data, the list must have one entry for each ciphertext.
Otherwise the run stops with
ComputeError::MerkleTree
.
These rules are necessary because anyone can call
publishCiphertextOutput
. The only check on the
input root is the comparison that the program contract makes against its own tree.
The crate does not sort the inputs. A leaf position is its position in the input list, so the caller
must send the inputs in on-chain index order. A caller that reads inputs from events must sort them
by index.
Limits on the computation
The processor has no secret key. It cannot read the value of a ciphertext, so it cannot branch on
encrypted data. Control flow can use only public data, for example the number of inputs, their
indices, and the parameters.
Operation (fhe.rs
v0.4.2
)
Result
Ciphertext plus or minus ciphertext, negation
Two components. The output can be published.
Ciphertext plus, minus, or times plaintext
Two components. The output can be published.
Ciphertext times ciphertext
Three components. The output commitment rejects it.
The output commitment accepts only a ciphertext with exactly two components
(
bfv_ciphertext_to_greco
in
crates/zk-helpers
). A ciphertext product in fhe.rs has three
components. The Interfold does not publish a relinearization key, so the run then stops with
ComputeError::OutputCommitment
.
Other limits:
BFV arithmetic is modulo the plaintext modulus. With parameter set
0
the modulus is 100, so 60 +
50 decrypts to 10.
Each preset has an addition budget,
z
(
SEARCH_Z
in
crates/fhe-params/src/constants.rs
). The
ciphernodes make the smudging noise of their decryption shares large enough for an output of at
most
z
fresh ciphertexts added together.
z
is 100,000 for parameter set
2
and 1,024 for
parameter set
0
. With a larger sum, the smudging noise protects the secret key shares with less
statistical security than the preset specifies. A product with a plaintext also increases the
noise, and
z
does not count it.
The processor returns
Vec<u8>
, not a
Result
. An
unwrap
that fails panics. Inside the zkVM a
panic stops the guest, and the E3 gets no output.
When
select
returns no inputs,
Ciphertext::zero
has no components. The output commitment then
rejects the output.
The zkVM guest is single threaded. Each input adds cycles to the proof, so large rounds take
longer to prove. The guest holds one ciphertext at a time, so its memory does not limit the number
of inputs.
Test the processor
The template includes a unit test in
program/src/lib.rs
. It encrypts 3 and 2 with the
InsecureThreshold512
preset, runs
fhe_processor
, decrypts the result, and checks that it is 5.
Open a terminal in the project root.
Run
cargo test -p e3-user-program
.
The test passes when the processor returns a valid sum. Add a test for each change that you make to
the computation.
Next steps
Program contract
Insert the same leaf on-chain that your policy builds off-chain.
Compute provider
Run the secure process in dev mode or in the OpenVM zkVM.
Complete example
Follow one E3 through the template from request to result.
Overview
Program Contract
## /build/e3-program/program-contract
Build
E3 Program Anatomy
Program Contract
Program Contract
The program contract is the on-chain part of an E3 program. It configures each E3, accepts the
encrypted inputs, keeps the input tree, and checks the compute proof. This page describes each
function that the Interfold contract requires, when it is called, and what it must check. The worked
example is
contracts/MyProgram.sol
from the default template. At the end, you can change
MyProgram.sol
safely or write a new program contract.
Required interfaces
The Interfold contract calls three interfaces on a program contract. The owner cannot register a
program that does not advertise all of them.
Interface
Source file
Functions
IE3Program
interfaces/IE3Program.sol
validate
,
verify
,
publishInput
IE3ProgramDataAvailability
interfaces/IDataAvailabilityVerifier.sol
verifyDataAvailability
IERC165
@openzeppelin/contracts/utils/introspection/IERC165.sol
supportsInterface
The first two paths are relative to
packages/interfold-contracts/contracts/
. The template contract
declares all three:
contracts/MyProgram.sol
contract
MyProgram
is
IE3Program
,
IE3ProgramDataAvailability
,
IERC165
,
Ownable
{
When each function is called
Function
Caller
Called from
Effect of a revert or
false
supportsInterface
Interfold contract
registerE3Program
Registration reverts
validate
Interfold contract
request
The request reverts, and no fee is taken
publishInput
Data provider (not the Interfold contract)
Direct call on the program contract
The input is refused
verifyDataAvailability
Interfold contract
publishCiphertextOutput
The output is refused
verify
Interfold contract
publishCiphertextOutput
The output is refused (
InvalidOutput
on
false
)
Registration
Only the owner of the Interfold contract can call
registerE3Program
(
Interfold.sol
). The
function reverts in these cases:
The address has no code:
E3ProgramNotAllowed
.
The program is already registered:
ModuleAlreadyEnabled
.
The program does not return
true
from
supportsInterface
for
IE3Program
and for
IE3ProgramDataAvailability
:
E3ProgramInterfaceMissing
. Each probe has a 30000 gas limit
(
InterfoldLifecycle.validateE3ProgramInterfaces
).
unregisterE3Program
blocks new requests for a program. E3s that already exist keep their program.
A request for a program that is not registered reverts with
E3ProgramNotAllowed
.
contracts/MyProgram.sol
function
supportsInterface
(
bytes4
interfaceId)
external
pure
override
returns
(
bool
) {
return
interfaceId
==
type(IE3Program).interfaceId
||
interfaceId
==
type(IE3ProgramDataAvailability).interfaceId
||
interfaceId
==
type(IERC165).interfaceId;
}
validate
interfaces/IE3Program.sol
function
validate
(
uint256
e3Id
,
uint256
seed
,
bytes
calldata
e3ProgramParams
,
bytes
calldata
computeProviderParams
,
bytes
calldata
customParams
)
external
returns
(
bytes32
encryptionSchemeId);
The Interfold contract calls
validate
inside
request
. Before the call, it stores a provisional
E3 record. The program can read that record with
getE3(e3Id)
. The stage and the requester stay
unset until
validate
returns.
Argument
Value that the Interfold contract passes
e3Id
The new E3 ID
seed
uint256(keccak256(abi.encode(block.prevrandao, e3Id)))
e3ProgramParams
paramSetRegistry[paramSet]
: the ABI-encoded BFV parameters of the requested set
computeProviderParams
The bytes from the request, unchanged. The Interfold contract does not read them.
customParams
The bytes from the request, unchanged. The program decodes them.
validate
must do these checks and actions:
Refuse callers other than the Interfold contract. The template also accepts its own owner.
Refuse an E3 ID that is already initialized.
Store
keccak256(e3ProgramParams)
.
verify
compares the proof parameter hash with this value.
Start an empty input tree for the E3.
Decode and check
customParams
, if the program uses them.
Return
keccak256("fhe.rs:BFV")
.
After
validate
returns, the Interfold contract checks the scheme ID. Any other value reverts with
UnsupportedCryptoConfig
. The request also reverts with
InvalidEncryptionScheme
when the scheme
has no decryption verifier, public key verifier, or ciphertext verifier. The Interfold contract
takes the fee only after these checks.
contracts/MyProgram.sol
function
validate
(
uint256
e3Id
,
uint256
,
bytes
calldata
e3ProgramParams
,
bytes
calldata
,
bytes
calldata
)
external
returns
(
bytes32
) {
require
(authorizedContracts[msg.sender]
||
msg.sender
==
owner
()
,
CallerNotAuthorized
());
require
(paramsHashes[e3Id]
==
bytes32
(
0
)
,
E3AlreadyInitialized
());
paramsHashes[e3Id]
=
keccak256
(e3ProgramParams);
inputs[e3Id].
_init
(TREE_DEPTH);
return
ENCRYPTION_SCHEME_ID;
}
ENCRYPTION_SCHEME_ID
is
keccak256("fhe.rs:BFV")
and
TREE_DEPTH
is
20
. The input tree is a
LazyIMTData
from
@zk-kit/lazy-imt.sol
.
CRISPProgram.validate
adds two checks. It refuses an E3 that the Interfold contract assigned to a
different program (
E3NotAssignedToProgram
). It also checks the input window against the request
timeouts (
_validateInputTiming
).
publishInput
interfaces/IE3Program.sol
function
publishInput
(
uint256
e3Id
,
bytes
memory
data)
external
;
Data providers call
publishInput
directly on the program contract. The Interfold contract never
calls it. The program contract defines the format of
data
.
publishInput
must do these checks and actions:
Refuse inputs after the input window closes (
inputWindow[1]
).
Decode
data
and refuse empty inputs.
Check that the ciphertext is valid for this E3. For example, verify a ZK proof of correct
encryption to the committee key.
Insert one leaf in the input tree. The leaf must equal the value that the secure process policy
builds for the same input.
Emit an event that lets the server get the ciphertext and its index.
The template takes
abi.encode(bytes ciphertext, bytes32 ciphertextCommitment)
and inserts the
commitment. This matches the default input policy.
contracts/MyProgram.sol
function
publishInput
(
uint256
e3Id
,
bytes
memory
data)
external
override
{
E3
memory
e3
=
interfold.
getE3
(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
(
프로젝트로 돌아가기