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