sonobe/examples/sha256.rs
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, _i: usize, 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 _i: usize,
62 z_i: Vec<FpVar<F>>,
63 ) -> Result<Vec<FpVar<F>>, SynthesisError> {
64 let unit_var = UnitVar::default();
65 let out_bytes = Sha256Gadget::evaluate(&unit_var, &z_i[0].to_bytes()?)?;
66 let out = out_bytes.0.to_constraint_field()?;
67 Ok(vec![out[0].clone()])
68 }
69}
70
71/// cargo test --example sha256
72#[cfg(test)]
73pub mod tests {
74 use super::*;
75 use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
76 use ark_relations::r1cs::ConstraintSystem;
77
78 // test to check that the Sha256FCircuit computes the same values inside and outside the circuit
79 #[test]
80 fn test_f_circuit() {
81 let cs = ConstraintSystem::<Fr>::new_ref();
82
83 let circuit = Sha256FCircuit::<Fr>::new(());
84 let z_i = vec![Fr::from(1_u32)];
85
86 let z_i1 = circuit.step_native(0, z_i.clone()).unwrap();
87
88 let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
89 let computed_z_i1Var = circuit
90 .generate_step_constraints(cs.clone(), 0, z_iVar.clone())
91 .unwrap();
92 assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
93 }
94}
95
96/// cargo run --release --example sha256
97fn main() {
98 let num_steps = 10;
99 let initial_state = vec![Fr::from(1_u32)];
100
101 let F_circuit = Sha256FCircuit::<Fr>::new(());
102
103 println!("Prepare Nova ProverParams & VerifierParams");
104 let (prover_params, verifier_params) = test_nova_setup::<Sha256FCircuit<Fr>>(F_circuit);
105
106 /// The idea here is that eventually we could replace the next line chunk that defines the
107 /// `type NOVA = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
108 /// trait, and the rest of our code would be working without needing to be updated.
109 type NOVA = Nova<
110 Projective,
111 GVar,
112 Projective2,
113 GVar2,
114 Sha256FCircuit<Fr>,
115 Pedersen<Projective>,
116 Pedersen<Projective2>,
117 >;
118
119 println!("Initialize FoldingScheme");
120 let mut folding_scheme = NOVA::init(&prover_params, F_circuit, initial_state.clone()).unwrap();
121
122 // compute a step of the IVC
123 for i in 0..num_steps {
124 let start = Instant::now();
125 folding_scheme.prove_step().unwrap();
126 println!("Nova::prove_step {}: {:?}", i, start.elapsed());
127 }
128
129 let (running_instance, incoming_instance, cyclefold_instance) = folding_scheme.instances();
130
131 println!("Run the Nova's IVC verifier");
132 NOVA::verify(
133 verifier_params,
134 initial_state,
135 folding_scheme.state(), // latest state
136 Fr::from(num_steps as u32),
137 running_instance,
138 incoming_instance,
139 cyclefold_instance,
140 )
141 .unwrap();
142}