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.

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