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.

172 lines
6.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_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_pallas::{constraints::GVar, Fr, Projective};
  18. use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
  19. use folding_schemes::commitment::pedersen::Pedersen;
  20. use folding_schemes::folding::nova::{get_r1cs, Nova, ProverParams, VerifierParams};
  21. use folding_schemes::frontend::FCircuit;
  22. use folding_schemes::transcript::poseidon::poseidon_test_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) -> Self {
  36. Self { _f: PhantomData }
  37. }
  38. /// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
  39. /// z_{i+1}
  40. fn step_native(self, z_i: Vec<F>) -> Result<Vec<F>, Error> {
  41. let out_bytes = Sha256::evaluate(&(), z_i[0].into_bigint().to_bytes_le()).unwrap();
  42. let out: Vec<F> = out_bytes.to_field_elements().unwrap();
  43. Ok(vec![out[0]])
  44. }
  45. /// generates the constraints for the step of F for the given z_i
  46. fn generate_step_constraints(
  47. self,
  48. _cs: ConstraintSystemRef<F>,
  49. z_i: Vec<FpVar<F>>,
  50. ) -> Result<Vec<FpVar<F>>, SynthesisError> {
  51. let unit_var = UnitVar::default();
  52. let out_bytes = Sha256Gadget::evaluate(&unit_var, &z_i[0].to_bytes()?)?;
  53. let out = out_bytes.0.to_constraint_field()?;
  54. Ok(vec![out[0].clone()])
  55. }
  56. }
  57. /// cargo test --example simple
  58. #[cfg(test)]
  59. pub mod tests {
  60. use super::*;
  61. use ark_r1cs_std::alloc::AllocVar;
  62. use ark_relations::r1cs::ConstraintSystem;
  63. // test to check that the Sha256FCircuit computes the same values inside and outside the circuit
  64. #[test]
  65. fn test_sha256_f_circuit() {
  66. let cs = ConstraintSystem::<Fr>::new_ref();
  67. let circuit = Sha256FCircuit::<Fr>::new(());
  68. let z_i = vec![Fr::from(1_u32)];
  69. let z_i1 = circuit.step_native(z_i.clone()).unwrap();
  70. let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
  71. let computed_z_i1Var = circuit
  72. .generate_step_constraints(cs.clone(), z_iVar.clone())
  73. .unwrap();
  74. assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
  75. }
  76. }
  77. // This method computes the Prover & Verifier parameters for the example. For a real world use case
  78. // those parameters should be generated carefuly (both the PoseidonConfig and the PedersenParams)
  79. #[allow(clippy::type_complexity)]
  80. fn nova_setup<FC: FCircuit<Fr>>(
  81. F_circuit: FC,
  82. ) -> (
  83. ProverParams<Projective, Projective2, Pedersen<Projective>, Pedersen<Projective2>>,
  84. VerifierParams<Projective, Projective2>,
  85. ) {
  86. let mut rng = ark_std::test_rng();
  87. let poseidon_config = poseidon_test_config::<Fr>();
  88. // get the CM & CF_CM len
  89. let (r1cs, cf_r1cs) =
  90. get_r1cs::<Projective, GVar, Projective2, GVar2, FC>(&poseidon_config, F_circuit).unwrap();
  91. let cm_len = r1cs.A.n_rows;
  92. let cf_cm_len = cf_r1cs.A.n_rows;
  93. let pedersen_params = Pedersen::<Projective>::new_params(&mut rng, cm_len);
  94. let cf_pedersen_params = Pedersen::<Projective2>::new_params(&mut rng, cf_cm_len);
  95. let prover_params =
  96. ProverParams::<Projective, Projective2, Pedersen<Projective>, Pedersen<Projective2>> {
  97. poseidon_config: poseidon_config.clone(),
  98. cm_params: pedersen_params,
  99. cf_cm_params: cf_pedersen_params,
  100. };
  101. let verifier_params = VerifierParams::<Projective, Projective2> {
  102. poseidon_config: poseidon_config.clone(),
  103. r1cs,
  104. cf_r1cs,
  105. };
  106. (prover_params, verifier_params)
  107. }
  108. /// cargo run --release --example fold_sha256
  109. fn main() {
  110. let num_steps = 10;
  111. let initial_state = vec![Fr::from(1_u32)];
  112. let F_circuit = Sha256FCircuit::<Fr>::new(());
  113. println!("Prepare Nova ProverParams & VerifierParams");
  114. let (prover_params, verifier_params) = nova_setup::<Sha256FCircuit<Fr>>(F_circuit);
  115. /// The idea here is that eventually we could replace the next line chunk that defines the
  116. /// `type NOVA = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
  117. /// trait, and the rest of our code would be working without needing to be updated.
  118. type NOVA = Nova<
  119. Projective,
  120. GVar,
  121. Projective2,
  122. GVar2,
  123. Sha256FCircuit<Fr>,
  124. Pedersen<Projective>,
  125. Pedersen<Projective2>,
  126. >;
  127. println!("Initialize FoldingScheme");
  128. let mut folding_scheme = NOVA::init(&prover_params, F_circuit, initial_state.clone()).unwrap();
  129. // compute a step of the IVC
  130. for i in 0..num_steps {
  131. let start = Instant::now();
  132. folding_scheme.prove_step().unwrap();
  133. println!("Nova::prove_step {}: {:?}", i, start.elapsed());
  134. }
  135. let (running_instance, incomming_instance, cyclefold_instance) = folding_scheme.instances();
  136. println!("Run the Nova's IVC verifier");
  137. NOVA::verify(
  138. verifier_params,
  139. initial_state,
  140. folding_scheme.state(), // latest state
  141. Fr::from(num_steps as u32),
  142. running_instance,
  143. incomming_instance,
  144. cyclefold_instance,
  145. )
  146. .unwrap();
  147. }