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.

151 lines
5.0 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;
  21. use folding_schemes::frontend::FCircuit;
  22. use folding_schemes::{Error, FoldingScheme};
  23. mod utils;
  24. use utils::init_nova_ivc_params;
  25. /// This is the circuit that we want to fold, it implements the FCircuit trait.
  26. /// The parameter z_i denotes the current state, and z_{i+1} denotes the next state which we get by
  27. /// applying the step.
  28. /// In this example we set z_i and z_{i+1} to be a single value, but the trait is made to support
  29. /// arrays, so our state could be an array with different values.
  30. #[derive(Clone, Copy, Debug)]
  31. pub struct Sha256FCircuit<F: PrimeField> {
  32. _f: PhantomData<F>,
  33. }
  34. impl<F: PrimeField> FCircuit<F> for Sha256FCircuit<F> {
  35. type Params = ();
  36. fn new(_params: Self::Params) -> Result<Self, Error> {
  37. Ok(Self { _f: PhantomData })
  38. }
  39. fn state_len(&self) -> usize {
  40. 1
  41. }
  42. fn external_inputs_len(&self) -> usize {
  43. 0
  44. }
  45. /// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
  46. /// z_{i+1}
  47. fn step_native(
  48. &self,
  49. _i: usize,
  50. z_i: Vec<F>,
  51. _external_inputs: Vec<F>,
  52. ) -> Result<Vec<F>, Error> {
  53. let out_bytes = Sha256::evaluate(&(), z_i[0].into_bigint().to_bytes_le()).unwrap();
  54. let out: Vec<F> = out_bytes.to_field_elements().unwrap();
  55. Ok(vec![out[0]])
  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. _external_inputs: Vec<FpVar<F>>,
  64. ) -> Result<Vec<FpVar<F>>, SynthesisError> {
  65. let unit_var = UnitVar::default();
  66. let out_bytes = Sha256Gadget::evaluate(&unit_var, &z_i[0].to_bytes()?)?;
  67. let out = out_bytes.0.to_constraint_field()?;
  68. Ok(vec![out[0].clone()])
  69. }
  70. }
  71. /// cargo test --example sha256
  72. #[cfg(test)]
  73. pub mod tests {
  74. use super::*;
  75. use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
  76. use ark_relations::r1cs::ConstraintSystem;
  77. // test to check that the Sha256FCircuit computes the same values inside and outside the circuit
  78. #[test]
  79. fn test_f_circuit() {
  80. let cs = ConstraintSystem::<Fr>::new_ref();
  81. let circuit = Sha256FCircuit::<Fr>::new(()).unwrap();
  82. let z_i = vec![Fr::from(1_u32)];
  83. let z_i1 = circuit.step_native(0, z_i.clone(), vec![]).unwrap();
  84. let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
  85. let computed_z_i1Var = circuit
  86. .generate_step_constraints(cs.clone(), 0, z_iVar.clone(), vec![])
  87. .unwrap();
  88. assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
  89. }
  90. }
  91. /// cargo run --release --example sha256
  92. fn main() {
  93. let num_steps = 10;
  94. let initial_state = vec![Fr::from(1_u32)];
  95. let F_circuit = Sha256FCircuit::<Fr>::new(()).unwrap();
  96. println!("Prepare Nova ProverParams & VerifierParams");
  97. let (prover_params, verifier_params, _) = init_nova_ivc_params::<Sha256FCircuit<Fr>>(F_circuit);
  98. /// The idea here is that eventually we could replace the next line chunk that defines the
  99. /// `type NOVA = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
  100. /// trait, and the rest of our code would be working without needing to be updated.
  101. type NOVA = Nova<
  102. Projective,
  103. GVar,
  104. Projective2,
  105. GVar2,
  106. Sha256FCircuit<Fr>,
  107. KZG<'static, Bn254>,
  108. Pedersen<Projective2>,
  109. >;
  110. println!("Initialize FoldingScheme");
  111. let mut folding_scheme = NOVA::init(&prover_params, F_circuit, initial_state.clone()).unwrap();
  112. // compute a step of the IVC
  113. for i in 0..num_steps {
  114. let start = Instant::now();
  115. folding_scheme.prove_step(vec![]).unwrap();
  116. println!("Nova::prove_step {}: {:?}", i, start.elapsed());
  117. }
  118. let (running_instance, incoming_instance, cyclefold_instance) = folding_scheme.instances();
  119. println!("Run the Nova's IVC verifier");
  120. NOVA::verify(
  121. verifier_params,
  122. initial_state,
  123. folding_scheme.state(), // latest state
  124. Fr::from(num_steps as u32),
  125. running_instance,
  126. incoming_instance,
  127. cyclefold_instance,
  128. )
  129. .unwrap();
  130. }