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.

148 lines
5.0 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_crypto_primitives::crh::{
  6. sha256::{
  7. constraints::{Sha256Gadget, UnitVar},
  8. Sha256,
  9. },
  10. CRHScheme, CRHSchemeGadget,
  11. };
  12. use ark_ff::{BigInteger, PrimeField, ToConstraintField};
  13. use ark_r1cs_std::{fields::fp::FpVar, ToBytesGadget, ToConstraintFieldGadget};
  14. use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
  15. use core::marker::PhantomData;
  16. use std::time::Instant;
  17. use ark_bn254::{constraints::GVar, Bn254, Fr, G1Projective as Projective};
  18. use ark_grumpkin::{constraints::GVar as GVar2, Projective as Projective2};
  19. use folding_schemes::commitment::{kzg::KZG, pedersen::Pedersen};
  20. use folding_schemes::folding::nova::{Nova, PreprocessorParam};
  21. use folding_schemes::frontend::FCircuit;
  22. use folding_schemes::transcript::poseidon::poseidon_canonical_config;
  23. use folding_schemes::{Error, FoldingScheme};
  24. /// This is the circuit that we want to fold, it implements the FCircuit trait.
  25. /// The parameter z_i denotes the current state, and z_{i+1} denotes the next state which we get by
  26. /// applying the step.
  27. /// In this example we set z_i and z_{i+1} to be a single value, but the trait is made to support
  28. /// arrays, so our state could be an array with different values.
  29. #[derive(Clone, Copy, Debug)]
  30. pub struct Sha256FCircuit<F: PrimeField> {
  31. _f: PhantomData<F>,
  32. }
  33. impl<F: PrimeField> FCircuit<F> for Sha256FCircuit<F> {
  34. type Params = ();
  35. fn new(_params: Self::Params) -> Result<Self, Error> {
  36. Ok(Self { _f: PhantomData })
  37. }
  38. fn state_len(&self) -> usize {
  39. 1
  40. }
  41. fn external_inputs_len(&self) -> usize {
  42. 0
  43. }
  44. /// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
  45. /// z_{i+1}
  46. fn step_native(
  47. &self,
  48. _i: usize,
  49. z_i: Vec<F>,
  50. _external_inputs: Vec<F>,
  51. ) -> Result<Vec<F>, Error> {
  52. let out_bytes = Sha256::evaluate(&(), z_i[0].into_bigint().to_bytes_le()).unwrap();
  53. let out: Vec<F> = out_bytes.to_field_elements().unwrap();
  54. Ok(vec![out[0]])
  55. }
  56. /// generates the constraints for the step of F for the given z_i
  57. fn generate_step_constraints(
  58. &self,
  59. _cs: ConstraintSystemRef<F>,
  60. _i: usize,
  61. z_i: Vec<FpVar<F>>,
  62. _external_inputs: Vec<FpVar<F>>,
  63. ) -> Result<Vec<FpVar<F>>, SynthesisError> {
  64. let unit_var = UnitVar::default();
  65. let out_bytes = Sha256Gadget::evaluate(&unit_var, &z_i[0].to_bytes()?)?;
  66. let out = out_bytes.0.to_constraint_field()?;
  67. Ok(vec![out[0].clone()])
  68. }
  69. }
  70. /// cargo test --example sha256
  71. #[cfg(test)]
  72. pub mod tests {
  73. use super::*;
  74. use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
  75. use ark_relations::r1cs::ConstraintSystem;
  76. // test to check that the Sha256FCircuit computes the same values inside and outside the circuit
  77. #[test]
  78. fn test_f_circuit() {
  79. let cs = ConstraintSystem::<Fr>::new_ref();
  80. let circuit = Sha256FCircuit::<Fr>::new(()).unwrap();
  81. let z_i = vec![Fr::from(1_u32)];
  82. let z_i1 = circuit.step_native(0, z_i.clone(), vec![]).unwrap();
  83. let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
  84. let computed_z_i1Var = circuit
  85. .generate_step_constraints(cs.clone(), 0, z_iVar.clone(), vec![])
  86. .unwrap();
  87. assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
  88. }
  89. }
  90. /// cargo run --release --example sha256
  91. fn main() {
  92. let num_steps = 10;
  93. let initial_state = vec![Fr::from(1_u32)];
  94. let F_circuit = Sha256FCircuit::<Fr>::new(()).unwrap();
  95. /// The idea here is that eventually we could replace the next line chunk that defines the
  96. /// `type N = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
  97. /// trait, and the rest of our code would be working without needing to be updated.
  98. type N = Nova<
  99. Projective,
  100. GVar,
  101. Projective2,
  102. GVar2,
  103. Sha256FCircuit<Fr>,
  104. KZG<'static, Bn254>,
  105. Pedersen<Projective2>,
  106. false,
  107. >;
  108. let poseidon_config = poseidon_canonical_config::<Fr>();
  109. let mut rng = rand::rngs::OsRng;
  110. println!("Prepare Nova ProverParams & VerifierParams");
  111. let nova_preprocess_params = PreprocessorParam::new(poseidon_config, F_circuit);
  112. let nova_params = N::preprocess(&mut rng, &nova_preprocess_params).unwrap();
  113. println!("Initialize FoldingScheme");
  114. let mut folding_scheme = N::init(&nova_params, F_circuit, initial_state.clone()).unwrap();
  115. // compute a step of the IVC
  116. for i in 0..num_steps {
  117. let start = Instant::now();
  118. folding_scheme.prove_step(rng, vec![], None).unwrap();
  119. println!("Nova::prove_step {}: {:?}", i, start.elapsed());
  120. }
  121. println!("Run the Nova's IVC verifier");
  122. let ivc_proof = folding_scheme.ivc_proof();
  123. N::verify(
  124. nova_params.1, // Nova's verifier params
  125. ivc_proof,
  126. )
  127. .unwrap();
  128. }