You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

153 lines
5.1 KiB

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