mirror of
https://github.com/arnaucube/sonobe.git
synced 2026-01-08 15:01:30 +01:00
Full flow example (#90)
* expose params & structs for external usage * add full_flow example, move examples into 'examples' dir
This commit is contained in:
213
examples/external_inputs.rs
Normal file
213
examples/external_inputs.rs
Normal file
@@ -0,0 +1,213 @@
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_upper_case_globals)]
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(clippy::upper_case_acronyms)]
|
||||
|
||||
use ark_crypto_primitives::{
|
||||
crh::{
|
||||
poseidon::constraints::{CRHGadget, CRHParametersVar},
|
||||
poseidon::CRH,
|
||||
CRHScheme, CRHSchemeGadget,
|
||||
},
|
||||
sponge::{poseidon::PoseidonConfig, Absorb},
|
||||
};
|
||||
use ark_ff::PrimeField;
|
||||
use ark_pallas::{constraints::GVar, Fr, Projective};
|
||||
use ark_r1cs_std::fields::fp::FpVar;
|
||||
use ark_r1cs_std::{alloc::AllocVar, fields::FieldVar};
|
||||
use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
|
||||
use ark_std::Zero;
|
||||
use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
|
||||
use core::marker::PhantomData;
|
||||
use std::time::Instant;
|
||||
|
||||
use folding_schemes::commitment::pedersen::Pedersen;
|
||||
use folding_schemes::folding::nova::Nova;
|
||||
use folding_schemes::frontend::FCircuit;
|
||||
use folding_schemes::{Error, FoldingScheme};
|
||||
mod utils;
|
||||
use folding_schemes::transcript::poseidon::poseidon_test_config;
|
||||
use utils::test_nova_setup;
|
||||
|
||||
/// This is the circuit that we want to fold, it implements the FCircuit trait. The parameter z_i
|
||||
/// denotes the current state which contains 2 elements, and z_{i+1} denotes the next state which
|
||||
/// we get by applying the step.
|
||||
///
|
||||
/// In this example we set the state to be the previous state together with an external input, and
|
||||
/// the new state is an array which contains the new state and a zero which will be ignored.
|
||||
///
|
||||
/// This is useful for example if we want to fold multiple verifications of signatures, where the
|
||||
/// circuit F checks the signature and is folded for each of the signatures and public keys. To
|
||||
/// keep things simpler, the following example does not verify signatures but does a similar
|
||||
/// approach with a chain of hashes, where each iteration hashes the previous step output (z_i)
|
||||
/// together with an external input (w_i).
|
||||
///
|
||||
/// w_1 w_2 w_3 w_4
|
||||
/// │ │ │ │
|
||||
/// ▼ ▼ ▼ ▼
|
||||
/// ┌─┐ ┌─┐ ┌─┐ ┌─┐
|
||||
/// ─────►│F├────►│F├────►│F├────►│F├────►
|
||||
/// z_1 └─┘ z_2 └─┘ z_3 └─┘ z_4 └─┘ z_5
|
||||
///
|
||||
///
|
||||
/// where each F is:
|
||||
/// w_i
|
||||
/// │ ┌────────────────────┐
|
||||
/// │ │FCircuit │
|
||||
/// │ │ │
|
||||
/// └────►│ h =Hash(z_i[0],w_i)│
|
||||
/// │ │ =Hash(v, w_i) │
|
||||
/// ────────►│ │ ├───────►
|
||||
/// z_i=[v,0] │ └──►z_{i+1}=[h, 0] │ z_{i+1}=[h,0]
|
||||
/// │ │
|
||||
/// └────────────────────┘
|
||||
///
|
||||
/// where each w_i value is set at the external_inputs array.
|
||||
///
|
||||
/// The last state z_i is used together with the external input w_i as inputs to compute the new
|
||||
/// state z_{i+1}.
|
||||
/// The function F will output the new state in an array of two elements, where the second element
|
||||
/// is a 0. In other words, z_{i+1} = [F([z_i, w_i]), 0], and the 0 will be replaced by w_{i+1} in
|
||||
/// the next iteration, so z_{i+2} = [F([z_{i+1}, w_{i+1}]), 0].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ExternalInputsCircuits<F: PrimeField>
|
||||
where
|
||||
F: Absorb,
|
||||
{
|
||||
_f: PhantomData<F>,
|
||||
poseidon_config: PoseidonConfig<F>,
|
||||
external_inputs: Vec<F>,
|
||||
}
|
||||
impl<F: PrimeField> FCircuit<F> for ExternalInputsCircuits<F>
|
||||
where
|
||||
F: Absorb,
|
||||
{
|
||||
type Params = (PoseidonConfig<F>, Vec<F>); // where Vec<F> contains the external inputs
|
||||
|
||||
fn new(params: Self::Params) -> Self {
|
||||
Self {
|
||||
_f: PhantomData,
|
||||
poseidon_config: params.0,
|
||||
external_inputs: params.1,
|
||||
}
|
||||
}
|
||||
fn state_len(&self) -> usize {
|
||||
2
|
||||
}
|
||||
|
||||
/// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
|
||||
/// z_{i+1}
|
||||
fn step_native(&self, i: usize, z_i: Vec<F>) -> Result<Vec<F>, Error> {
|
||||
let input: [F; 2] = [z_i[0], self.external_inputs[i]];
|
||||
let h = CRH::<F>::evaluate(&self.poseidon_config, input).unwrap();
|
||||
Ok(vec![h, F::zero()])
|
||||
}
|
||||
|
||||
/// generates the constraints for the step of F for the given z_i
|
||||
fn generate_step_constraints(
|
||||
&self,
|
||||
cs: ConstraintSystemRef<F>,
|
||||
i: usize,
|
||||
z_i: Vec<FpVar<F>>,
|
||||
) -> Result<Vec<FpVar<F>>, SynthesisError> {
|
||||
let crh_params =
|
||||
CRHParametersVar::<F>::new_constant(cs.clone(), self.poseidon_config.clone())?;
|
||||
let external_inputVar =
|
||||
FpVar::<F>::new_witness(cs.clone(), || Ok(self.external_inputs[i])).unwrap();
|
||||
let input: [FpVar<F>; 2] = [z_i[0].clone(), external_inputVar.clone()];
|
||||
let h = CRHGadget::<F>::evaluate(&crh_params, &input)?;
|
||||
Ok(vec![h, FpVar::<F>::zero()])
|
||||
}
|
||||
}
|
||||
|
||||
/// cargo test --example external_inputs
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
use ark_r1cs_std::R1CSVar;
|
||||
use ark_relations::r1cs::ConstraintSystem;
|
||||
|
||||
// test to check that the ExternalInputsCircuits computes the same values inside and outside the circuit
|
||||
#[test]
|
||||
fn test_f_circuit() {
|
||||
let poseidon_config = poseidon_test_config::<Fr>();
|
||||
|
||||
let cs = ConstraintSystem::<Fr>::new_ref();
|
||||
|
||||
let circuit = ExternalInputsCircuits::<Fr>::new((poseidon_config, vec![Fr::from(3_u32)]));
|
||||
let z_i = vec![Fr::from(1_u32), Fr::zero()];
|
||||
|
||||
let z_i1 = circuit.step_native(0, z_i.clone()).unwrap();
|
||||
|
||||
let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
|
||||
let computed_z_i1Var = circuit
|
||||
.generate_step_constraints(cs.clone(), 0, z_iVar.clone())
|
||||
.unwrap();
|
||||
assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
|
||||
}
|
||||
}
|
||||
|
||||
/// cargo run --release --example external_inputs
|
||||
fn main() {
|
||||
let num_steps = 5;
|
||||
let initial_state = vec![Fr::from(1_u32), Fr::zero()];
|
||||
|
||||
// set the external inputs to be used at each folding step
|
||||
let external_inputs = vec![
|
||||
Fr::from(3_u32),
|
||||
Fr::from(33_u32),
|
||||
Fr::from(73_u32),
|
||||
Fr::from(103_u32),
|
||||
Fr::from(125_u32),
|
||||
];
|
||||
assert_eq!(external_inputs.len(), num_steps);
|
||||
|
||||
let poseidon_config = poseidon_test_config::<Fr>();
|
||||
let F_circuit = ExternalInputsCircuits::<Fr>::new((poseidon_config, external_inputs));
|
||||
|
||||
println!("Prepare Nova ProverParams & VerifierParams");
|
||||
let (prover_params, verifier_params) =
|
||||
test_nova_setup::<ExternalInputsCircuits<Fr>>(F_circuit.clone());
|
||||
|
||||
/// The idea here is that eventually we could replace the next line chunk that defines the
|
||||
/// `type NOVA = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
|
||||
/// trait, and the rest of our code would be working without needing to be updated.
|
||||
type NOVA = Nova<
|
||||
Projective,
|
||||
GVar,
|
||||
Projective2,
|
||||
GVar2,
|
||||
ExternalInputsCircuits<Fr>,
|
||||
Pedersen<Projective>,
|
||||
Pedersen<Projective2>,
|
||||
>;
|
||||
|
||||
println!("Initialize FoldingScheme");
|
||||
let mut folding_scheme = NOVA::init(&prover_params, F_circuit, initial_state.clone()).unwrap();
|
||||
|
||||
// compute a step of the IVC
|
||||
for i in 0..num_steps {
|
||||
let start = Instant::now();
|
||||
folding_scheme.prove_step().unwrap();
|
||||
println!("Nova::prove_step {}: {:?}", i, start.elapsed());
|
||||
}
|
||||
println!(
|
||||
"state at last step (after {} iterations): {:?}",
|
||||
num_steps,
|
||||
folding_scheme.state()
|
||||
);
|
||||
|
||||
let (running_instance, incoming_instance, cyclefold_instance) = folding_scheme.instances();
|
||||
|
||||
println!("Run the Nova's IVC verifier");
|
||||
NOVA::verify(
|
||||
verifier_params,
|
||||
initial_state.clone(),
|
||||
folding_scheme.state(), // latest state
|
||||
Fr::from(num_steps as u32),
|
||||
running_instance,
|
||||
incoming_instance,
|
||||
cyclefold_instance,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
222
examples/full_flow.rs
Normal file
222
examples/full_flow.rs
Normal file
@@ -0,0 +1,222 @@
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(clippy::upper_case_acronyms)]
|
||||
///
|
||||
/// This example performs the full flow:
|
||||
/// - define the circuit to be folded
|
||||
/// - fold the circuit with Nova+CycleFold's IVC
|
||||
/// - generate a DeciderEthCircuit final proof
|
||||
/// - generate the Solidity contract that verifies the proof
|
||||
/// - verify the proof in the EVM
|
||||
///
|
||||
use ark_bn254::{constraints::GVar, Bn254, Fr, G1Projective as G1};
|
||||
use ark_crypto_primitives::snark::SNARK;
|
||||
use ark_ff::PrimeField;
|
||||
use ark_groth16::VerifyingKey as G16VerifierKey;
|
||||
use ark_groth16::{Groth16, ProvingKey};
|
||||
use ark_grumpkin::{constraints::GVar as GVar2, Projective as G2};
|
||||
use ark_poly_commit::kzg10::VerifierKey as KZGVerifierKey;
|
||||
use ark_r1cs_std::alloc::AllocVar;
|
||||
use ark_r1cs_std::fields::fp::FpVar;
|
||||
use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
|
||||
use ark_std::Zero;
|
||||
use std::marker::PhantomData;
|
||||
use std::time::Instant;
|
||||
|
||||
use folding_schemes::{
|
||||
commitment::{
|
||||
kzg::{ProverKey as KZGProverKey, KZG},
|
||||
pedersen::Pedersen,
|
||||
CommitmentScheme,
|
||||
},
|
||||
folding::nova::{
|
||||
decider_eth::{prepare_calldata, Decider as DeciderEth},
|
||||
decider_eth_circuit::DeciderEthCircuit,
|
||||
get_cs_params_len, Nova, ProverParams,
|
||||
},
|
||||
frontend::FCircuit,
|
||||
transcript::poseidon::poseidon_test_config,
|
||||
Decider, Error, FoldingScheme,
|
||||
};
|
||||
use solidity_verifiers::{
|
||||
evm::{compile_solidity, Evm},
|
||||
utils::get_function_selector_for_nova_cyclefold_verifier,
|
||||
verifiers::nova_cyclefold::get_decider_template_for_cyclefold_decider,
|
||||
NovaCycleFoldVerifierKey,
|
||||
};
|
||||
|
||||
/// Test circuit to be folded
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CubicFCircuit<F: PrimeField> {
|
||||
_f: PhantomData<F>,
|
||||
}
|
||||
impl<F: PrimeField> FCircuit<F> for CubicFCircuit<F> {
|
||||
type Params = ();
|
||||
fn new(_params: Self::Params) -> Self {
|
||||
Self { _f: PhantomData }
|
||||
}
|
||||
fn state_len(&self) -> usize {
|
||||
1
|
||||
}
|
||||
fn step_native(&self, _i: usize, z_i: Vec<F>) -> Result<Vec<F>, Error> {
|
||||
Ok(vec![z_i[0] * z_i[0] * z_i[0] + z_i[0] + F::from(5_u32)])
|
||||
}
|
||||
fn generate_step_constraints(
|
||||
&self,
|
||||
cs: ConstraintSystemRef<F>,
|
||||
_i: usize,
|
||||
z_i: Vec<FpVar<F>>,
|
||||
) -> Result<Vec<FpVar<F>>, SynthesisError> {
|
||||
let five = FpVar::<F>::new_constant(cs.clone(), F::from(5u32))?;
|
||||
let z_i = z_i[0].clone();
|
||||
|
||||
Ok(vec![&z_i * &z_i * &z_i + &z_i + &five])
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn init_test_prover_params<FC: FCircuit<Fr, Params = ()>>() -> (
|
||||
ProverParams<G1, G2, KZG<'static, Bn254>, Pedersen<G2>>,
|
||||
KZGVerifierKey<Bn254>,
|
||||
) {
|
||||
let mut rng = ark_std::test_rng();
|
||||
let poseidon_config = poseidon_test_config::<Fr>();
|
||||
let f_circuit = FC::new(());
|
||||
let (cs_len, cf_cs_len) =
|
||||
get_cs_params_len::<G1, GVar, G2, GVar2, FC>(&poseidon_config, f_circuit).unwrap();
|
||||
let (kzg_pk, kzg_vk): (KZGProverKey<G1>, KZGVerifierKey<Bn254>) =
|
||||
KZG::<Bn254>::setup(&mut rng, cs_len).unwrap();
|
||||
let (cf_pedersen_params, _) = Pedersen::<G2>::setup(&mut rng, cf_cs_len).unwrap();
|
||||
let fs_prover_params = ProverParams::<G1, G2, KZG<Bn254>, Pedersen<G2>> {
|
||||
poseidon_config: poseidon_config.clone(),
|
||||
cs_params: kzg_pk.clone(),
|
||||
cf_cs_params: cf_pedersen_params,
|
||||
};
|
||||
(fs_prover_params, kzg_vk)
|
||||
}
|
||||
/// Initializes Nova parameters and DeciderEth parameters. Only for test purposes.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn init_params<FC: FCircuit<Fr, Params = ()>>() -> (
|
||||
ProverParams<G1, G2, KZG<'static, Bn254>, Pedersen<G2>>,
|
||||
KZGVerifierKey<Bn254>,
|
||||
ProvingKey<Bn254>,
|
||||
G16VerifierKey<Bn254>,
|
||||
) {
|
||||
let mut rng = rand::rngs::OsRng;
|
||||
let start = Instant::now();
|
||||
let (fs_prover_params, kzg_vk) = init_test_prover_params::<FC>();
|
||||
println!("generated Nova folding params: {:?}", start.elapsed());
|
||||
let f_circuit = FC::new(());
|
||||
|
||||
pub type NOVA<FC> = Nova<G1, GVar, G2, GVar2, FC, KZG<'static, Bn254>, Pedersen<G2>>;
|
||||
let z_0 = vec![Fr::zero(); f_circuit.state_len()];
|
||||
let nova = NOVA::init(&fs_prover_params, f_circuit, z_0.clone()).unwrap();
|
||||
|
||||
let decider_circuit =
|
||||
DeciderEthCircuit::<G1, GVar, G2, GVar2, KZG<Bn254>, Pedersen<G2>>::from_nova::<FC>(
|
||||
nova.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
let start = Instant::now();
|
||||
let (g16_pk, g16_vk) =
|
||||
Groth16::<Bn254>::circuit_specific_setup(decider_circuit.clone(), &mut rng).unwrap();
|
||||
println!(
|
||||
"generated G16 (Decider circuit) params: {:?}",
|
||||
start.elapsed()
|
||||
);
|
||||
(fs_prover_params, kzg_vk, g16_pk, g16_vk)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let n_steps = 10;
|
||||
// set the initial state
|
||||
let z_0 = vec![Fr::from(3_u32)];
|
||||
|
||||
let (fs_prover_params, kzg_vk, g16_pk, g16_vk) = init_params::<CubicFCircuit<Fr>>();
|
||||
|
||||
pub type NOVA = Nova<G1, GVar, G2, GVar2, CubicFCircuit<Fr>, KZG<'static, Bn254>, Pedersen<G2>>;
|
||||
pub type DECIDERETH_FCircuit = DeciderEth<
|
||||
G1,
|
||||
GVar,
|
||||
G2,
|
||||
GVar2,
|
||||
CubicFCircuit<Fr>,
|
||||
KZG<'static, Bn254>,
|
||||
Pedersen<G2>,
|
||||
Groth16<Bn254>,
|
||||
NOVA,
|
||||
>;
|
||||
let f_circuit = CubicFCircuit::<Fr>::new(());
|
||||
|
||||
// initialize the folding scheme engine, in our case we use Nova
|
||||
let mut nova = NOVA::init(&fs_prover_params, f_circuit, z_0).unwrap();
|
||||
// run n steps of the folding iteration
|
||||
for i in 0..n_steps {
|
||||
let start = Instant::now();
|
||||
nova.prove_step().unwrap();
|
||||
println!("Nova::prove_step {}: {:?}", i, start.elapsed());
|
||||
}
|
||||
|
||||
let rng = rand::rngs::OsRng;
|
||||
let start = Instant::now();
|
||||
let proof = DECIDERETH_FCircuit::prove(
|
||||
(g16_pk, fs_prover_params.cs_params.clone()),
|
||||
rng,
|
||||
nova.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
println!("generated Decider proof: {:?}", start.elapsed());
|
||||
|
||||
let verified = DECIDERETH_FCircuit::verify(
|
||||
(g16_vk.clone(), kzg_vk.clone()),
|
||||
nova.i,
|
||||
nova.z_0.clone(),
|
||||
nova.z_i.clone(),
|
||||
&nova.U_i,
|
||||
&nova.u_i,
|
||||
&proof,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(verified);
|
||||
println!("Decider proof verification: {}", verified);
|
||||
|
||||
// Now, let's generate the Solidity code that verifies this Decider final proof
|
||||
let function_selector =
|
||||
get_function_selector_for_nova_cyclefold_verifier(nova.z_0.len() * 2 + 1);
|
||||
|
||||
let calldata: Vec<u8> = prepare_calldata(
|
||||
function_selector,
|
||||
nova.i,
|
||||
nova.z_0,
|
||||
nova.z_i,
|
||||
&nova.U_i,
|
||||
&nova.u_i,
|
||||
proof,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// prepare the setup params for the solidity verifier
|
||||
let nova_cyclefold_vk = NovaCycleFoldVerifierKey::from((g16_vk, kzg_vk, f_circuit.state_len()));
|
||||
|
||||
// generate the solidity code
|
||||
let decider_solidity_code = get_decider_template_for_cyclefold_decider(nova_cyclefold_vk);
|
||||
|
||||
// verify the proof against the solidity code in the EVM
|
||||
let nova_cyclefold_verifier_bytecode = compile_solidity(&decider_solidity_code, "NovaDecider");
|
||||
let mut evm = Evm::default();
|
||||
let verifier_address = evm.create(nova_cyclefold_verifier_bytecode);
|
||||
let (_, output) = evm.call(verifier_address, calldata.clone());
|
||||
assert_eq!(*output.last().unwrap(), 1);
|
||||
|
||||
// save smart contract and the calldata
|
||||
println!("storing nova-verifier.sol and the calldata into files");
|
||||
use std::fs;
|
||||
fs::write(
|
||||
"./examples/nova-verifier.sol",
|
||||
decider_solidity_code.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write("./examples/solidity-calldata.calldata", calldata.clone()).unwrap();
|
||||
let s = solidity_verifiers::utils::get_formatted_calldata(calldata.clone());
|
||||
fs::write("./examples/solidity-calldata.inputs", s.join(",\n")).expect("");
|
||||
}
|
||||
157
examples/multi_inputs.rs
Normal file
157
examples/multi_inputs.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_upper_case_globals)]
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(clippy::upper_case_acronyms)]
|
||||
|
||||
use ark_ff::PrimeField;
|
||||
use ark_r1cs_std::alloc::AllocVar;
|
||||
use ark_r1cs_std::fields::fp::FpVar;
|
||||
use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
|
||||
use core::marker::PhantomData;
|
||||
use std::time::Instant;
|
||||
|
||||
use ark_pallas::{constraints::GVar, Fr, Projective};
|
||||
use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
|
||||
|
||||
use folding_schemes::commitment::pedersen::Pedersen;
|
||||
use folding_schemes::folding::nova::Nova;
|
||||
use folding_schemes::frontend::FCircuit;
|
||||
use folding_schemes::{Error, FoldingScheme};
|
||||
mod utils;
|
||||
use utils::test_nova_setup;
|
||||
|
||||
/// This is the circuit that we want to fold, it implements the FCircuit trait. The parameter z_i
|
||||
/// denotes the current state which contains 5 elements, and z_{i+1} denotes the next state which
|
||||
/// we get by applying the step.
|
||||
/// In this example we set z_i and z_{i+1} to have five elements, and at each step we do different
|
||||
/// operations on each of them.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct MultiInputsFCircuit<F: PrimeField> {
|
||||
_f: PhantomData<F>,
|
||||
}
|
||||
impl<F: PrimeField> FCircuit<F> for MultiInputsFCircuit<F> {
|
||||
type Params = ();
|
||||
|
||||
fn new(_params: Self::Params) -> Self {
|
||||
Self { _f: PhantomData }
|
||||
}
|
||||
fn state_len(&self) -> usize {
|
||||
5
|
||||
}
|
||||
|
||||
/// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
|
||||
/// z_{i+1}
|
||||
fn step_native(&self, _i: usize, z_i: Vec<F>) -> Result<Vec<F>, Error> {
|
||||
let a = z_i[0] + F::from(4_u32);
|
||||
let b = z_i[1] + F::from(40_u32);
|
||||
let c = z_i[2] * F::from(4_u32);
|
||||
let d = z_i[3] * F::from(40_u32);
|
||||
let e = z_i[4] + F::from(100_u32);
|
||||
|
||||
Ok(vec![a, b, c, d, e])
|
||||
}
|
||||
|
||||
/// generates the constraints for the step of F for the given z_i
|
||||
fn generate_step_constraints(
|
||||
&self,
|
||||
cs: ConstraintSystemRef<F>,
|
||||
_i: usize,
|
||||
z_i: Vec<FpVar<F>>,
|
||||
) -> Result<Vec<FpVar<F>>, SynthesisError> {
|
||||
let four = FpVar::<F>::new_constant(cs.clone(), F::from(4u32))?;
|
||||
let forty = FpVar::<F>::new_constant(cs.clone(), F::from(40u32))?;
|
||||
let onehundred = FpVar::<F>::new_constant(cs.clone(), F::from(100u32))?;
|
||||
let a = z_i[0].clone() + four.clone();
|
||||
let b = z_i[1].clone() + forty.clone();
|
||||
let c = z_i[2].clone() * four;
|
||||
let d = z_i[3].clone() * forty;
|
||||
let e = z_i[4].clone() + onehundred;
|
||||
|
||||
Ok(vec![a, b, c, d, e])
|
||||
}
|
||||
}
|
||||
|
||||
/// cargo test --example multi_inputs
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
|
||||
use ark_relations::r1cs::ConstraintSystem;
|
||||
|
||||
// test to check that the MultiInputsFCircuit computes the same values inside and outside the circuit
|
||||
#[test]
|
||||
fn test_f_circuit() {
|
||||
let cs = ConstraintSystem::<Fr>::new_ref();
|
||||
|
||||
let circuit = MultiInputsFCircuit::<Fr>::new(());
|
||||
let z_i = vec![
|
||||
Fr::from(1_u32),
|
||||
Fr::from(1_u32),
|
||||
Fr::from(1_u32),
|
||||
Fr::from(1_u32),
|
||||
Fr::from(1_u32),
|
||||
];
|
||||
|
||||
let z_i1 = circuit.step_native(0, z_i.clone()).unwrap();
|
||||
|
||||
let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
|
||||
let computed_z_i1Var = circuit
|
||||
.generate_step_constraints(cs.clone(), 0, z_iVar.clone())
|
||||
.unwrap();
|
||||
assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
|
||||
}
|
||||
}
|
||||
|
||||
/// cargo run --release --example multi_inputs
|
||||
fn main() {
|
||||
let num_steps = 10;
|
||||
let initial_state = vec![
|
||||
Fr::from(1_u32),
|
||||
Fr::from(1_u32),
|
||||
Fr::from(1_u32),
|
||||
Fr::from(1_u32),
|
||||
Fr::from(1_u32),
|
||||
];
|
||||
|
||||
let F_circuit = MultiInputsFCircuit::<Fr>::new(());
|
||||
|
||||
println!("Prepare Nova ProverParams & VerifierParams");
|
||||
let (prover_params, verifier_params) = test_nova_setup::<MultiInputsFCircuit<Fr>>(F_circuit);
|
||||
|
||||
/// The idea here is that eventually we could replace the next line chunk that defines the
|
||||
/// `type NOVA = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
|
||||
/// trait, and the rest of our code would be working without needing to be updated.
|
||||
type NOVA = Nova<
|
||||
Projective,
|
||||
GVar,
|
||||
Projective2,
|
||||
GVar2,
|
||||
MultiInputsFCircuit<Fr>,
|
||||
Pedersen<Projective>,
|
||||
Pedersen<Projective2>,
|
||||
>;
|
||||
|
||||
println!("Initialize FoldingScheme");
|
||||
let mut folding_scheme = NOVA::init(&prover_params, F_circuit, initial_state.clone()).unwrap();
|
||||
|
||||
// compute a step of the IVC
|
||||
for i in 0..num_steps {
|
||||
let start = Instant::now();
|
||||
folding_scheme.prove_step().unwrap();
|
||||
println!("Nova::prove_step {}: {:?}", i, start.elapsed());
|
||||
}
|
||||
|
||||
let (running_instance, incoming_instance, cyclefold_instance) = folding_scheme.instances();
|
||||
|
||||
println!("Run the Nova's IVC verifier");
|
||||
NOVA::verify(
|
||||
verifier_params,
|
||||
initial_state.clone(),
|
||||
folding_scheme.state(), // latest state
|
||||
Fr::from(num_steps as u32),
|
||||
running_instance,
|
||||
incoming_instance,
|
||||
cyclefold_instance,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
142
examples/sha256.rs
Normal file
142
examples/sha256.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_upper_case_globals)]
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(clippy::upper_case_acronyms)]
|
||||
|
||||
use ark_crypto_primitives::crh::{
|
||||
sha256::{
|
||||
constraints::{Sha256Gadget, UnitVar},
|
||||
Sha256,
|
||||
},
|
||||
CRHScheme, CRHSchemeGadget,
|
||||
};
|
||||
use ark_ff::{BigInteger, PrimeField, ToConstraintField};
|
||||
use ark_r1cs_std::{fields::fp::FpVar, ToBytesGadget, ToConstraintFieldGadget};
|
||||
use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
|
||||
use core::marker::PhantomData;
|
||||
use std::time::Instant;
|
||||
|
||||
use ark_pallas::{constraints::GVar, Fr, Projective};
|
||||
use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
|
||||
|
||||
use folding_schemes::commitment::pedersen::Pedersen;
|
||||
use folding_schemes::folding::nova::Nova;
|
||||
use folding_schemes::frontend::FCircuit;
|
||||
use folding_schemes::{Error, FoldingScheme};
|
||||
mod utils;
|
||||
use utils::test_nova_setup;
|
||||
|
||||
/// This is the circuit that we want to fold, it implements the FCircuit trait.
|
||||
/// The parameter z_i denotes the current state, and z_{i+1} denotes the next state which we get by
|
||||
/// applying the step.
|
||||
/// In this example we set z_i and z_{i+1} to be a single value, but the trait is made to support
|
||||
/// arrays, so our state could be an array with different values.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Sha256FCircuit<F: PrimeField> {
|
||||
_f: PhantomData<F>,
|
||||
}
|
||||
impl<F: PrimeField> FCircuit<F> for Sha256FCircuit<F> {
|
||||
type Params = ();
|
||||
|
||||
fn new(_params: Self::Params) -> Self {
|
||||
Self { _f: PhantomData }
|
||||
}
|
||||
fn state_len(&self) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
/// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
|
||||
/// z_{i+1}
|
||||
fn step_native(&self, _i: usize, z_i: Vec<F>) -> Result<Vec<F>, Error> {
|
||||
let out_bytes = Sha256::evaluate(&(), z_i[0].into_bigint().to_bytes_le()).unwrap();
|
||||
let out: Vec<F> = out_bytes.to_field_elements().unwrap();
|
||||
|
||||
Ok(vec![out[0]])
|
||||
}
|
||||
|
||||
/// generates the constraints for the step of F for the given z_i
|
||||
fn generate_step_constraints(
|
||||
&self,
|
||||
_cs: ConstraintSystemRef<F>,
|
||||
_i: usize,
|
||||
z_i: Vec<FpVar<F>>,
|
||||
) -> Result<Vec<FpVar<F>>, SynthesisError> {
|
||||
let unit_var = UnitVar::default();
|
||||
let out_bytes = Sha256Gadget::evaluate(&unit_var, &z_i[0].to_bytes()?)?;
|
||||
let out = out_bytes.0.to_constraint_field()?;
|
||||
Ok(vec![out[0].clone()])
|
||||
}
|
||||
}
|
||||
|
||||
/// cargo test --example sha256
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
|
||||
use ark_relations::r1cs::ConstraintSystem;
|
||||
|
||||
// test to check that the Sha256FCircuit computes the same values inside and outside the circuit
|
||||
#[test]
|
||||
fn test_f_circuit() {
|
||||
let cs = ConstraintSystem::<Fr>::new_ref();
|
||||
|
||||
let circuit = Sha256FCircuit::<Fr>::new(());
|
||||
let z_i = vec![Fr::from(1_u32)];
|
||||
|
||||
let z_i1 = circuit.step_native(0, z_i.clone()).unwrap();
|
||||
|
||||
let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
|
||||
let computed_z_i1Var = circuit
|
||||
.generate_step_constraints(cs.clone(), 0, z_iVar.clone())
|
||||
.unwrap();
|
||||
assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
|
||||
}
|
||||
}
|
||||
|
||||
/// cargo run --release --example sha256
|
||||
fn main() {
|
||||
let num_steps = 10;
|
||||
let initial_state = vec![Fr::from(1_u32)];
|
||||
|
||||
let F_circuit = Sha256FCircuit::<Fr>::new(());
|
||||
|
||||
println!("Prepare Nova ProverParams & VerifierParams");
|
||||
let (prover_params, verifier_params) = test_nova_setup::<Sha256FCircuit<Fr>>(F_circuit);
|
||||
|
||||
/// The idea here is that eventually we could replace the next line chunk that defines the
|
||||
/// `type NOVA = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
|
||||
/// trait, and the rest of our code would be working without needing to be updated.
|
||||
type NOVA = Nova<
|
||||
Projective,
|
||||
GVar,
|
||||
Projective2,
|
||||
GVar2,
|
||||
Sha256FCircuit<Fr>,
|
||||
Pedersen<Projective>,
|
||||
Pedersen<Projective2>,
|
||||
>;
|
||||
|
||||
println!("Initialize FoldingScheme");
|
||||
let mut folding_scheme = NOVA::init(&prover_params, F_circuit, initial_state.clone()).unwrap();
|
||||
|
||||
// compute a step of the IVC
|
||||
for i in 0..num_steps {
|
||||
let start = Instant::now();
|
||||
folding_scheme.prove_step().unwrap();
|
||||
println!("Nova::prove_step {}: {:?}", i, start.elapsed());
|
||||
}
|
||||
|
||||
let (running_instance, incoming_instance, cyclefold_instance) = folding_scheme.instances();
|
||||
|
||||
println!("Run the Nova's IVC verifier");
|
||||
NOVA::verify(
|
||||
verifier_params,
|
||||
initial_state,
|
||||
folding_scheme.state(), // latest state
|
||||
Fr::from(num_steps as u32),
|
||||
running_instance,
|
||||
incoming_instance,
|
||||
cyclefold_instance,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
49
examples/utils.rs
Normal file
49
examples/utils.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_upper_case_globals)]
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(clippy::upper_case_acronyms)]
|
||||
#![allow(dead_code)]
|
||||
use ark_pallas::{constraints::GVar, Fr, Projective};
|
||||
use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
|
||||
|
||||
use folding_schemes::commitment::{pedersen::Pedersen, CommitmentScheme};
|
||||
use folding_schemes::folding::nova::{get_r1cs, ProverParams, VerifierParams};
|
||||
use folding_schemes::frontend::FCircuit;
|
||||
use folding_schemes::transcript::poseidon::poseidon_test_config;
|
||||
|
||||
// This method computes the Nova's Prover & Verifier parameters for the example.
|
||||
// Warning: this method is only for testing purposes. For a real world use case those parameters
|
||||
// should be generated carefully (both the PoseidonConfig and the PedersenParams).
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(crate) fn test_nova_setup<FC: FCircuit<Fr>>(
|
||||
F_circuit: FC,
|
||||
) -> (
|
||||
ProverParams<Projective, Projective2, Pedersen<Projective>, Pedersen<Projective2>>,
|
||||
VerifierParams<Projective, Projective2>,
|
||||
) {
|
||||
let mut rng = ark_std::test_rng();
|
||||
let poseidon_config = poseidon_test_config::<Fr>();
|
||||
|
||||
// get the CM & CF_CM len
|
||||
let (r1cs, cf_r1cs) =
|
||||
get_r1cs::<Projective, GVar, Projective2, GVar2, FC>(&poseidon_config, F_circuit).unwrap();
|
||||
let cf_len = r1cs.A.n_rows;
|
||||
let cf_cf_len = cf_r1cs.A.n_rows;
|
||||
|
||||
let (pedersen_params, _) = Pedersen::<Projective>::setup(&mut rng, cf_len).unwrap();
|
||||
let (cf_pedersen_params, _) = Pedersen::<Projective2>::setup(&mut rng, cf_cf_len).unwrap();
|
||||
|
||||
let prover_params =
|
||||
ProverParams::<Projective, Projective2, Pedersen<Projective>, Pedersen<Projective2>> {
|
||||
poseidon_config: poseidon_config.clone(),
|
||||
cs_params: pedersen_params,
|
||||
cf_cs_params: cf_pedersen_params,
|
||||
};
|
||||
let verifier_params = VerifierParams::<Projective, Projective2> {
|
||||
poseidon_config: poseidon_config.clone(),
|
||||
r1cs,
|
||||
cf_r1cs,
|
||||
};
|
||||
(prover_params, verifier_params)
|
||||
}
|
||||
fn main() {}
|
||||
Reference in New Issue
Block a user