ark-r1cs-std/crypto-primitives/src/nizk/mod.rs
crypto-primitives/src/nizk/mod.rsRaw
1use algebra_core::bytes::ToBytes;
2use rand::Rng;
3
4#[cfg(feature = "gm17")]
5pub mod gm17;
6#[cfg(feature = "gm17")]
7pub use self::gm17::Gm17;
8
9#[cfg(feature = "groth16")]
10pub mod groth16;
11#[cfg(feature = "groth16")]
12pub use self::groth16::Groth16;
13
14#[cfg(feature = "r1cs")]
15pub mod constraints;
16#[cfg(feature = "r1cs")]
17pub use constraints::*;
18
19use crate::Error;
20
21pub trait NIZK {
22 type Circuit;
23 type AssignedCircuit;
24 type VerifierInput: ?Sized;
25 type ProvingParameters: Clone;
26 type VerificationParameters: Clone + Default + From<Self::PreparedVerificationParameters>;
27 type PreparedVerificationParameters: Clone + Default + From<Self::VerificationParameters>;
28 type Proof: ToBytes + Clone + Default;
29
30 fn setup<R: Rng>(
31 circuit: Self::Circuit,
32 rng: &mut R,
33 ) -> Result<
34 (
35 Self::ProvingParameters,
36 Self::PreparedVerificationParameters,
37 ),
38 Error,
39 >;
40
41 fn prove<R: Rng>(
42 parameter: &Self::ProvingParameters,
43 input_and_witness: Self::AssignedCircuit,
44 rng: &mut R,
45 ) -> Result<Self::Proof, Error>;
46
47 fn verify(
48 verifier_key: &Self::PreparedVerificationParameters,
49 input: &Self::VerifierInput,
50 proof: &Self::Proof,
51 ) -> Result<bool, Error>;
52}
53
54#[cfg(all(feature = "gm17", test))]
55mod test {
56 use algebra::test_rng;
57 use core::ops::AddAssign;
58
59 #[test]
60 fn test_gm17() {
61 use crate::nizk::{gm17::Gm17, NIZK};
62 use algebra::{
63 bls12_377::{Bls12_377, Fr},
64 One,
65 };
66 use r1cs_core::{lc, ConstraintSynthesizer, ConstraintSystemRef, SynthesisError, Variable};
67
68 #[derive(Copy, Clone)]
69 struct R1CSCircuit {
70 x: Option<Fr>,
71 sum: Option<Fr>,
72 w: Option<Fr>,
73 }
74
75 impl R1CSCircuit {
76 pub(super) fn new(x: Fr, sum: Fr, w: Fr) -> Self {
77 Self {
78 x: Some(x),
79 sum: Some(sum),
80 w: Some(w),
81 }
82 }
83 }
84
85 impl ConstraintSynthesizer<Fr> for R1CSCircuit {
86 fn generate_constraints(
87 self,
88 cs: ConstraintSystemRef<Fr>,
89 ) -> Result<(), SynthesisError> {
90 let input = cs.new_input_variable(|| Ok(self.x.unwrap()))?;
91 let sum = cs.new_input_variable(|| Ok(self.sum.unwrap()))?;
92 let witness = cs.new_witness_variable(|| Ok(self.w.unwrap()))?;
93
94 cs.enforce_constraint(lc!() + sum, lc!() + Variable::One, lc!() + input + witness)?;
95 Ok(())
96 }
97 }
98
99 let mut sum = Fr::one();
100 sum.add_assign(&Fr::one());
101 let circuit = R1CSCircuit::new(Fr::one(), sum, Fr::one());
102
103 let rng = &mut test_rng();
104
105 let parameters = Gm17::<Bls12_377, R1CSCircuit, [Fr]>::setup(circuit, rng).unwrap();
106
107 let proof =
108 Gm17::<Bls12_377, R1CSCircuit, [Fr]>::prove(¶meters.0, circuit, rng).unwrap();
109
110 let result =
111 Gm17::<Bls12_377, R1CSCircuit, [Fr]>::verify(¶meters.1, &[Fr::one(), sum], &proof)
112 .unwrap();
113 assert!(result);
114 }
115}