sonobe/folding-schemes/examples/sha256.rs
folding-schemes/examples/sha256.rsRaw
1#![allow(non_snake_case)]
2#![allow(non_upper_case_globals)]
3#![allow(non_camel_case_types)]
4#![allow(clippy::upper_case_acronyms)]
5
6use ark_crypto_primitives::crh::{
7 sha256::{
8 constraints::{Sha256Gadget, UnitVar},
9 Sha256,
10 },
11 CRHScheme, CRHSchemeGadget,
12};
13use ark_ff::{BigInteger, PrimeField, ToConstraintField};
14use ark_r1cs_std::{fields::fp::FpVar, ToBytesGadget, ToConstraintFieldGadget};
15use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
16use core::marker::PhantomData;
17use std::time::Instant;
18
19use ark_pallas::{constraints::GVar, Fr, Projective};
20use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
21
22use folding_schemes::commitment::pedersen::Pedersen;
23use folding_schemes::folding::nova::Nova;
24use folding_schemes::frontend::FCircuit;
25use folding_schemes::{Error, FoldingScheme};
26mod utils;
27use utils::test_nova_setup;
28
29/// This is the circuit that we want to fold, it implements the FCircuit trait.
30/// The parameter z_i denotes the current state, and z_{i+1} denotes the next state which we get by
31/// applying the step.
32/// In this example we set z_i and z_{i+1} to be a single value, but the trait is made to support
33/// arrays, so our state could be an array with different values.
34#[derive(Clone, Copy, Debug)]
35pub struct Sha256FCircuit<F: PrimeField> {
36 _f: PhantomData<F>,
37}
38impl<F: PrimeField> FCircuit<F> for Sha256FCircuit<F> {
39 type Params = ();
40
41 fn new(_params: Self::Params) -> Self {
42 Self { _f: PhantomData }
43 }
44 fn state_len(self) -> usize {
45 1
46 }
47
48 /// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
49 /// z_{i+1}
50 fn step_native(self, z_i: Vec<F>) -> Result<Vec<F>, Error> {
51 let out_bytes = Sha256::evaluate(&(), z_i[0].into_bigint().to_bytes_le()).unwrap();
52 let out: Vec<F> = out_bytes.to_field_elements().unwrap();
53
54 Ok(vec![out[0]])
55 }
56
57 /// generates the constraints for the step of F for the given z_i
58 fn generate_step_constraints(
59 self,
60 _cs: ConstraintSystemRef<F>,
61 z_i: Vec<FpVar<F>>,
62 ) -> Result<Vec<FpVar<F>>, SynthesisError> {
63 let unit_var = UnitVar::default();
64 let out_bytes = Sha256Gadget::evaluate(&unit_var, &z_i[0].to_bytes()?)?;
65 let out = out_bytes.0.to_constraint_field()?;
66 Ok(vec![out[0].clone()])
67 }
68}
69
70/// cargo test --example sha256
71#[cfg(test)]
72pub mod tests {
73 use super::*;
74 use ark_r1cs_std::alloc::AllocVar;
75 use ark_relations::r1cs::ConstraintSystem;
76
77 // test to check that the Sha256FCircuit computes the same values inside and outside the circuit
78 #[test]
79 fn test_sha256_f_circuit() {
80 let cs = ConstraintSystem::<Fr>::new_ref();
81
82 let circuit = Sha256FCircuit::<Fr>::new(());
83 let z_i = vec![Fr::from(1_u32)];
84
85 let z_i1 = circuit.step_native(z_i.clone()).unwrap();
86
87 let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
88 let computed_z_i1Var = circuit
89 .generate_step_constraints(cs.clone(), z_iVar.clone())
90 .unwrap();
91 assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
92 }
93}
94
95/// cargo run --release --example sha256
96fn main() {
97 let num_steps = 10;
98 let initial_state = vec![Fr::from(1_u32)];
99
100 let F_circuit = Sha256FCircuit::<Fr>::new(());
101
102 println!("Prepare Nova ProverParams & VerifierParams");
103 let (prover_params, verifier_params) = test_nova_setup::<Sha256FCircuit<Fr>>(F_circuit);
104
105 /// The idea here is that eventually we could replace the next line chunk that defines the
106 /// `type NOVA = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
107 /// trait, and the rest of our code would be working without needing to be updated.
108 type NOVA = Nova<
109 Projective,
110 GVar,
111 Projective2,
112 GVar2,
113 Sha256FCircuit<Fr>,
114 Pedersen<Projective>,
115 Pedersen<Projective2>,
116 >;
117
118 println!("Initialize FoldingScheme");
119 let mut folding_scheme = NOVA::init(&prover_params, F_circuit, initial_state.clone()).unwrap();
120
121 // compute a step of the IVC
122 for i in 0..num_steps {
123 let start = Instant::now();
124 folding_scheme.prove_step().unwrap();
125 println!("Nova::prove_step {}: {:?}", i, start.elapsed());
126 }
127
128 let (running_instance, incomming_instance, cyclefold_instance) = folding_scheme.instances();
129
130 println!("Run the Nova's IVC verifier");
131 NOVA::verify(
132 verifier_params,
133 initial_state,
134 folding_scheme.state(), // latest state
135 Fr::from(num_steps as u32),
136 running_instance,
137 incomming_instance,
138 cyclefold_instance,
139 )
140 .unwrap();
141}