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.

217 lines
7.8 KiB

Add IVCProof to the existing folding schemes (Nova,HyperNova,ProtoGalaxy) (#167) * Add IVCProof to the existing folding schemes (Nova,HyperNova,ProtoGalaxy) * Implement `from_ivc_proof` for the FoldingSchemes trait (and Nova, HyperNova, ProtoGalaxy), so that the FoldingScheme IVC's instance can be constructed from the given parameters and the last IVCProof, which allows to sent the IVCProof between different parties, so that they can continue iterating the IVC from the received IVCProof. Also the serializers allow for the IVCProof to be sent to a verifier that can deserialize it and verify it. This allows to remove the logic from the file [folding/nova/serialize.rs](https://github.com/privacy-scaling-explorations/sonobe/blob/f1d82418ba047cf90805f2d0505370246df24d68/folding-schemes/src/folding/nova/serialize.rs) and [folding/hypernova/serialize.rs](https://github.com/privacy-scaling-explorations/sonobe/blob/f1d82418ba047cf90805f2d0505370246df24d68/folding-schemes/src/folding/hypernova/serialize.rs) (removing the whole files), which is now covered by the `IVCProof` generated serializers (generated by macro instead of handwritten), and the test that the file contained is now abstracted and applied to all the 3 existing folding schemes (Nova, HyperNova, ProtoGalaxy) at the folding/mod.rs file. * update Nova VerifierParams serializers to avoid serializing the R1CS to save big part of the old serialized size * rm .instances() since it's not needed * add nova params serialization to nova's ivc test to ensure that IVC verification works with deserialized data * Add unified FS::ProverParam & VerifierParam serialization & deserialization (for all Nova, HyperNova and ProtoGalaxy), without serializing the R1CS/CCS and thus saving substantial serialized bytes space. * rm CanonicalDeserialize warnings msgs for VerifierParams
1 month ago
Add IVCProof to the existing folding schemes (Nova,HyperNova,ProtoGalaxy) (#167) * Add IVCProof to the existing folding schemes (Nova,HyperNova,ProtoGalaxy) * Implement `from_ivc_proof` for the FoldingSchemes trait (and Nova, HyperNova, ProtoGalaxy), so that the FoldingScheme IVC's instance can be constructed from the given parameters and the last IVCProof, which allows to sent the IVCProof between different parties, so that they can continue iterating the IVC from the received IVCProof. Also the serializers allow for the IVCProof to be sent to a verifier that can deserialize it and verify it. This allows to remove the logic from the file [folding/nova/serialize.rs](https://github.com/privacy-scaling-explorations/sonobe/blob/f1d82418ba047cf90805f2d0505370246df24d68/folding-schemes/src/folding/nova/serialize.rs) and [folding/hypernova/serialize.rs](https://github.com/privacy-scaling-explorations/sonobe/blob/f1d82418ba047cf90805f2d0505370246df24d68/folding-schemes/src/folding/hypernova/serialize.rs) (removing the whole files), which is now covered by the `IVCProof` generated serializers (generated by macro instead of handwritten), and the test that the file contained is now abstracted and applied to all the 3 existing folding schemes (Nova, HyperNova, ProtoGalaxy) at the folding/mod.rs file. * update Nova VerifierParams serializers to avoid serializing the R1CS to save big part of the old serialized size * rm .instances() since it's not needed * add nova params serialization to nova's ivc test to ensure that IVC verification works with deserialized data * Add unified FS::ProverParam & VerifierParam serialization & deserialization (for all Nova, HyperNova and ProtoGalaxy), without serializing the R1CS/CCS and thus saving substantial serialized bytes space. * rm CanonicalDeserialize warnings msgs for VerifierParams
1 month ago
  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. false,
  168. >;
  169. let mut rng = rand::rngs::OsRng;
  170. println!("Prepare Nova's ProverParams & VerifierParams");
  171. let nova_preprocess_params = PreprocessorParam::new(poseidon_config, F_circuit.clone());
  172. let nova_params = N::preprocess(&mut rng, &nova_preprocess_params).unwrap();
  173. println!("Initialize FoldingScheme");
  174. let mut folding_scheme = N::init(&nova_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(rng, external_inputs_at_step.clone(), None)
  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. println!("Run the Nova's IVC verifier");
  189. let ivc_proof = folding_scheme.ivc_proof();
  190. N::verify(
  191. nova_params.1, // Nova's verifier params
  192. ivc_proof,
  193. )
  194. .unwrap();
  195. }