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.

167 lines
5.4 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_ff::PrimeField;
  6. use ark_r1cs_std::alloc::AllocVar;
  7. use ark_r1cs_std::fields::fp::FpVar;
  8. use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
  9. use core::marker::PhantomData;
  10. use std::time::Instant;
  11. use ark_bn254::{constraints::GVar, Bn254, Fr, G1Projective as Projective};
  12. use ark_grumpkin::{constraints::GVar as GVar2, Projective as Projective2};
  13. use folding_schemes::commitment::{kzg::KZG, pedersen::Pedersen};
  14. use folding_schemes::folding::nova::Nova;
  15. use folding_schemes::frontend::FCircuit;
  16. use folding_schemes::{Error, FoldingScheme};
  17. mod utils;
  18. use utils::init_nova_ivc_params;
  19. /// This is the circuit that we want to fold, it implements the FCircuit trait. The parameter z_i
  20. /// denotes the current state which contains 5 elements, and z_{i+1} denotes the next state which
  21. /// we get by applying the step.
  22. /// In this example we set z_i and z_{i+1} to have five elements, and at each step we do different
  23. /// operations on each of them.
  24. #[derive(Clone, Copy, Debug)]
  25. pub struct MultiInputsFCircuit<F: PrimeField> {
  26. _f: PhantomData<F>,
  27. }
  28. impl<F: PrimeField> FCircuit<F> for MultiInputsFCircuit<F> {
  29. type Params = ();
  30. fn new(_params: Self::Params) -> Result<Self, Error> {
  31. Ok(Self { _f: PhantomData })
  32. }
  33. fn state_len(&self) -> usize {
  34. 5
  35. }
  36. fn external_inputs_len(&self) -> usize {
  37. 0
  38. }
  39. /// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
  40. /// z_{i+1}
  41. fn step_native(
  42. &self,
  43. _i: usize,
  44. z_i: Vec<F>,
  45. _external_inputs: Vec<F>,
  46. ) -> Result<Vec<F>, Error> {
  47. let a = z_i[0] + F::from(4_u32);
  48. let b = z_i[1] + F::from(40_u32);
  49. let c = z_i[2] * F::from(4_u32);
  50. let d = z_i[3] * F::from(40_u32);
  51. let e = z_i[4] + F::from(100_u32);
  52. Ok(vec![a, b, c, d, e])
  53. }
  54. /// generates the constraints for the step of F for the given z_i
  55. fn generate_step_constraints(
  56. &self,
  57. cs: ConstraintSystemRef<F>,
  58. _i: usize,
  59. z_i: Vec<FpVar<F>>,
  60. _external_inputs: Vec<FpVar<F>>,
  61. ) -> Result<Vec<FpVar<F>>, SynthesisError> {
  62. let four = FpVar::<F>::new_constant(cs.clone(), F::from(4u32))?;
  63. let forty = FpVar::<F>::new_constant(cs.clone(), F::from(40u32))?;
  64. let onehundred = FpVar::<F>::new_constant(cs.clone(), F::from(100u32))?;
  65. let a = z_i[0].clone() + four.clone();
  66. let b = z_i[1].clone() + forty.clone();
  67. let c = z_i[2].clone() * four;
  68. let d = z_i[3].clone() * forty;
  69. let e = z_i[4].clone() + onehundred;
  70. Ok(vec![a, b, c, d, e])
  71. }
  72. }
  73. /// cargo test --example multi_inputs
  74. #[cfg(test)]
  75. pub mod tests {
  76. use super::*;
  77. use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
  78. use ark_relations::r1cs::ConstraintSystem;
  79. // test to check that the MultiInputsFCircuit computes the same values inside and outside the circuit
  80. #[test]
  81. fn test_f_circuit() {
  82. let cs = ConstraintSystem::<Fr>::new_ref();
  83. let circuit = MultiInputsFCircuit::<Fr>::new(()).unwrap();
  84. let z_i = vec![
  85. Fr::from(1_u32),
  86. Fr::from(1_u32),
  87. Fr::from(1_u32),
  88. Fr::from(1_u32),
  89. Fr::from(1_u32),
  90. ];
  91. let z_i1 = circuit.step_native(0, z_i.clone(), vec![]).unwrap();
  92. let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
  93. let computed_z_i1Var = circuit
  94. .generate_step_constraints(cs.clone(), 0, z_iVar.clone(), vec![])
  95. .unwrap();
  96. assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
  97. }
  98. }
  99. /// cargo run --release --example multi_inputs
  100. fn main() {
  101. let num_steps = 10;
  102. let initial_state = vec![
  103. Fr::from(1_u32),
  104. Fr::from(1_u32),
  105. Fr::from(1_u32),
  106. Fr::from(1_u32),
  107. Fr::from(1_u32),
  108. ];
  109. let F_circuit = MultiInputsFCircuit::<Fr>::new(()).unwrap();
  110. println!("Prepare Nova ProverParams & VerifierParams");
  111. let (prover_params, verifier_params, _) =
  112. init_nova_ivc_params::<MultiInputsFCircuit<Fr>>(F_circuit);
  113. /// The idea here is that eventually we could replace the next line chunk that defines the
  114. /// `type NOVA = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
  115. /// trait, and the rest of our code would be working without needing to be updated.
  116. type NOVA = Nova<
  117. Projective,
  118. GVar,
  119. Projective2,
  120. GVar2,
  121. MultiInputsFCircuit<Fr>,
  122. KZG<'static, Bn254>,
  123. Pedersen<Projective2>,
  124. >;
  125. println!("Initialize FoldingScheme");
  126. let mut folding_scheme = NOVA::init(&prover_params, F_circuit, initial_state.clone()).unwrap();
  127. // compute a step of the IVC
  128. for i in 0..num_steps {
  129. let start = Instant::now();
  130. folding_scheme.prove_step(vec![]).unwrap();
  131. println!("Nova::prove_step {}: {:?}", i, start.elapsed());
  132. }
  133. let (running_instance, incoming_instance, cyclefold_instance) = folding_scheme.instances();
  134. println!("Run the Nova's IVC verifier");
  135. NOVA::verify(
  136. verifier_params,
  137. initial_state.clone(),
  138. folding_scheme.state(), // latest state
  139. Fr::from(num_steps as u32),
  140. running_instance,
  141. incoming_instance,
  142. cyclefold_instance,
  143. )
  144. .unwrap();
  145. }