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.

141 lines
4.6 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, 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. z_i: Vec<FpVar<F>>,
  54. ) -> Result<Vec<FpVar<F>>, SynthesisError> {
  55. let unit_var = UnitVar::default();
  56. let out_bytes = Sha256Gadget::evaluate(&unit_var, &z_i[0].to_bytes()?)?;
  57. let out = out_bytes.0.to_constraint_field()?;
  58. Ok(vec![out[0].clone()])
  59. }
  60. }
  61. /// cargo test --example sha256
  62. #[cfg(test)]
  63. pub mod tests {
  64. use super::*;
  65. use ark_r1cs_std::alloc::AllocVar;
  66. use ark_relations::r1cs::ConstraintSystem;
  67. // test to check that the Sha256FCircuit computes the same values inside and outside the circuit
  68. #[test]
  69. fn test_sha256_f_circuit() {
  70. let cs = ConstraintSystem::<Fr>::new_ref();
  71. let circuit = Sha256FCircuit::<Fr>::new(());
  72. let z_i = vec![Fr::from(1_u32)];
  73. let z_i1 = circuit.step_native(z_i.clone()).unwrap();
  74. let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
  75. let computed_z_i1Var = circuit
  76. .generate_step_constraints(cs.clone(), z_iVar.clone())
  77. .unwrap();
  78. assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
  79. }
  80. }
  81. /// cargo run --release --example sha256
  82. fn main() {
  83. let num_steps = 10;
  84. let initial_state = vec![Fr::from(1_u32)];
  85. let F_circuit = Sha256FCircuit::<Fr>::new(());
  86. println!("Prepare Nova ProverParams & VerifierParams");
  87. let (prover_params, verifier_params) = test_nova_setup::<Sha256FCircuit<Fr>>(F_circuit);
  88. /// The idea here is that eventually we could replace the next line chunk that defines the
  89. /// `type NOVA = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
  90. /// trait, and the rest of our code would be working without needing to be updated.
  91. type NOVA = Nova<
  92. Projective,
  93. GVar,
  94. Projective2,
  95. GVar2,
  96. Sha256FCircuit<Fr>,
  97. Pedersen<Projective>,
  98. Pedersen<Projective2>,
  99. >;
  100. println!("Initialize FoldingScheme");
  101. let mut folding_scheme = NOVA::init(&prover_params, F_circuit, initial_state.clone()).unwrap();
  102. // compute a step of the IVC
  103. for i in 0..num_steps {
  104. let start = Instant::now();
  105. folding_scheme.prove_step().unwrap();
  106. println!("Nova::prove_step {}: {:?}", i, start.elapsed());
  107. }
  108. let (running_instance, incoming_instance, cyclefold_instance) = folding_scheme.instances();
  109. println!("Run the Nova's IVC verifier");
  110. NOVA::verify(
  111. verifier_params,
  112. initial_state,
  113. folding_scheme.state(), // latest state
  114. Fr::from(num_steps as u32),
  115. running_instance,
  116. incoming_instance,
  117. cyclefold_instance,
  118. )
  119. .unwrap();
  120. }