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.

222 lines
8.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_bn254::{constraints::GVar, Bn254, Fr, G1Projective as Projective};
  6. use ark_crypto_primitives::{
  7. crh::{
  8. poseidon::constraints::{CRHGadget, CRHParametersVar},
  9. poseidon::CRH,
  10. CRHScheme, CRHSchemeGadget,
  11. },
  12. sponge::{poseidon::PoseidonConfig, Absorb},
  13. };
  14. use ark_ff::PrimeField;
  15. use ark_grumpkin::{constraints::GVar as GVar2, Projective as Projective2};
  16. use ark_r1cs_std::alloc::AllocVar;
  17. use ark_r1cs_std::fields::fp::FpVar;
  18. use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
  19. use core::marker::PhantomData;
  20. use std::time::Instant;
  21. use folding_schemes::commitment::{kzg::KZG, pedersen::Pedersen};
  22. use folding_schemes::folding::nova::{Nova, PreprocessorParam};
  23. use folding_schemes::frontend::FCircuit;
  24. use folding_schemes::transcript::poseidon::poseidon_canonical_config;
  25. use folding_schemes::{Error, FoldingScheme};
  26. /// This is the circuit that we want to fold, it implements the FCircuit trait. The parameter z_i
  27. /// denotes the current state which contains 1 element, and z_{i+1} denotes the next state which we
  28. /// get by applying the step.
  29. ///
  30. /// In this example we set the state to be the previous state together with an external input, and
  31. /// the new state is an array which contains the new state.
  32. ///
  33. /// This is useful for example if we want to fold multiple verifications of signatures, where the
  34. /// circuit F checks the signature and is folded for each of the signatures and public keys. To
  35. /// keep things simpler, the following example does not verify signatures but does a similar
  36. /// approach with a chain of hashes, where each iteration hashes the previous step output (z_i)
  37. /// together with an external input (w_i).
  38. ///
  39. /// w_1 w_2 w_3 w_4
  40. /// │ │ │ │
  41. /// ▼ ▼ ▼ ▼
  42. /// ┌─┐ ┌─┐ ┌─┐ ┌─┐
  43. /// ─────►│F├────►│F├────►│F├────►│F├────►
  44. /// z_1 └─┘ z_2 └─┘ z_3 └─┘ z_4 └─┘ z_5
  45. ///
  46. ///
  47. /// where each F is:
  48. /// w_i
  49. /// │ ┌────────────────────┐
  50. /// │ │FCircuit │
  51. /// │ │ │
  52. /// └────►│ h =Hash(z_i[0],w_i)│
  53. /// ────────►│ │ ├───────►
  54. /// z_i │ └──►z_{i+1}=[h] │ z_{i+1}
  55. /// │ │
  56. /// └────────────────────┘
  57. ///
  58. /// where each w_i value is set at the external_inputs array.
  59. ///
  60. /// The last state z_i is used together with the external input w_i as inputs to compute the new
  61. /// state z_{i+1}.
  62. #[derive(Clone, Debug)]
  63. pub struct ExternalInputsCircuit<F: PrimeField>
  64. where
  65. F: Absorb,
  66. {
  67. _f: PhantomData<F>,
  68. poseidon_config: PoseidonConfig<F>,
  69. }
  70. impl<F: PrimeField> FCircuit<F> for ExternalInputsCircuit<F>
  71. where
  72. F: Absorb,
  73. {
  74. type Params = PoseidonConfig<F>;
  75. fn new(params: Self::Params) -> Result<Self, Error> {
  76. Ok(Self {
  77. _f: PhantomData,
  78. poseidon_config: params,
  79. })
  80. }
  81. fn state_len(&self) -> usize {
  82. 1
  83. }
  84. fn external_inputs_len(&self) -> usize {
  85. 1
  86. }
  87. /// computes the next state value for the step of F for the given z_i and external_inputs
  88. /// z_{i+1}
  89. fn step_native(
  90. &self,
  91. _i: usize,
  92. z_i: Vec<F>,
  93. external_inputs: Vec<F>,
  94. ) -> Result<Vec<F>, Error> {
  95. let hash_input: [F; 2] = [z_i[0], external_inputs[0]];
  96. let h = CRH::<F>::evaluate(&self.poseidon_config, hash_input).unwrap();
  97. Ok(vec![h])
  98. }
  99. /// generates the constraints and returns the next state value for the step of F for the given
  100. /// z_i and external_inputs
  101. fn generate_step_constraints(
  102. &self,
  103. cs: ConstraintSystemRef<F>,
  104. _i: usize,
  105. z_i: Vec<FpVar<F>>,
  106. external_inputs: Vec<FpVar<F>>,
  107. ) -> Result<Vec<FpVar<F>>, SynthesisError> {
  108. let crh_params =
  109. CRHParametersVar::<F>::new_constant(cs.clone(), self.poseidon_config.clone())?;
  110. let hash_input: [FpVar<F>; 2] = [z_i[0].clone(), external_inputs[0].clone()];
  111. let h = CRHGadget::<F>::evaluate(&crh_params, &hash_input)?;
  112. Ok(vec![h])
  113. }
  114. }
  115. /// cargo test --example external_inputs
  116. #[cfg(test)]
  117. pub mod tests {
  118. use super::*;
  119. use ark_r1cs_std::R1CSVar;
  120. use ark_relations::r1cs::ConstraintSystem;
  121. // test to check that the ExternalInputsCircuit computes the same values inside and outside the circuit
  122. #[test]
  123. fn test_f_circuit() {
  124. let poseidon_config = poseidon_canonical_config::<Fr>();
  125. let cs = ConstraintSystem::<Fr>::new_ref();
  126. let circuit = ExternalInputsCircuit::<Fr>::new(poseidon_config).unwrap();
  127. let z_i = vec![Fr::from(1_u32)];
  128. let external_inputs = vec![Fr::from(3_u32)];
  129. let z_i1 = circuit
  130. .step_native(0, z_i.clone(), external_inputs.clone())
  131. .unwrap();
  132. let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
  133. let external_inputsVar =
  134. Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(external_inputs)).unwrap();
  135. let computed_z_i1Var = circuit
  136. .generate_step_constraints(cs.clone(), 0, z_iVar, external_inputsVar)
  137. .unwrap();
  138. assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
  139. }
  140. }
  141. /// cargo run --release --example external_inputs
  142. fn main() {
  143. let num_steps = 5;
  144. let initial_state = vec![Fr::from(1_u32)];
  145. // prepare the external inputs to be used at each folding step
  146. let external_inputs = vec![
  147. vec![Fr::from(3_u32)],
  148. vec![Fr::from(33_u32)],
  149. vec![Fr::from(73_u32)],
  150. vec![Fr::from(103_u32)],
  151. vec![Fr::from(125_u32)],
  152. ];
  153. assert_eq!(external_inputs.len(), num_steps);
  154. let poseidon_config = poseidon_canonical_config::<Fr>();
  155. let F_circuit = ExternalInputsCircuit::<Fr>::new(poseidon_config.clone()).unwrap();
  156. /// The idea here is that eventually we could replace the next line chunk that defines the
  157. /// `type N = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
  158. /// trait, and the rest of our code would be working without needing to be updated.
  159. type N = Nova<
  160. Projective,
  161. GVar,
  162. Projective2,
  163. GVar2,
  164. ExternalInputsCircuit<Fr>,
  165. KZG<'static, Bn254>,
  166. Pedersen<Projective2>,
  167. >;
  168. let mut rng = rand::rngs::OsRng;
  169. println!("Prepare Nova's ProverParams & VerifierParams");
  170. let nova_preprocess_params = PreprocessorParam::new(poseidon_config, F_circuit.clone());
  171. let (nova_pp, nova_vp) = N::preprocess(&mut rng, &nova_preprocess_params).unwrap();
  172. println!("Initialize FoldingScheme");
  173. let mut folding_scheme = N::init(&nova_pp, F_circuit, initial_state.clone()).unwrap();
  174. // compute a step of the IVC
  175. for (i, external_inputs_at_step) in external_inputs.iter().enumerate() {
  176. let start = Instant::now();
  177. folding_scheme
  178. .prove_step(rng, external_inputs_at_step.clone())
  179. .unwrap();
  180. println!("Nova::prove_step {}: {:?}", i, start.elapsed());
  181. }
  182. println!(
  183. "state at last step (after {} iterations): {:?}",
  184. num_steps,
  185. folding_scheme.state()
  186. );
  187. let (running_instance, incoming_instance, cyclefold_instance) = folding_scheme.instances();
  188. println!("Run the Nova's IVC verifier");
  189. N::verify(
  190. nova_vp,
  191. initial_state.clone(),
  192. folding_scheme.state(), // latest state
  193. Fr::from(num_steps as u32),
  194. running_instance,
  195. incoming_instance,
  196. cyclefold_instance,
  197. )
  198. .unwrap();
  199. }