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.

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