ark-r1cs-std/crypto-primitives/src/nizk/mod.rs
crypto-primitives/src/nizk/mod.rsRaw
1use algebra::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::{curves::bls12_381::Bls12_381, fields::bls12_381::Fr, One};
63 use r1cs_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError};
64
65 #[derive(Copy, Clone)]
66 struct R1CSCircuit {
67 x: Option<Fr>,
68 sum: Option<Fr>,
69 w: Option<Fr>,
70 }
71
72 impl R1CSCircuit {
73 pub(super) fn new(x: Fr, sum: Fr, w: Fr) -> Self {
74 Self {
75 x: Some(x),
76 sum: Some(sum),
77 w: Some(w),
78 }
79 }
80 }
81
82 impl ConstraintSynthesizer<Fr> for R1CSCircuit {
83 fn generate_constraints<CS: ConstraintSystem<Fr>>(
84 self,
85 cs: &mut CS,
86 ) -> Result<(), SynthesisError> {
87 let input = cs.alloc_input(|| "x", || Ok(self.x.unwrap()))?;
88 let sum = cs.alloc_input(|| "sum", || Ok(self.sum.unwrap()))?;
89 let witness = cs.alloc(|| "w", || Ok(self.w.unwrap()))?;
90
91 cs.enforce(
92 || "check_one",
93 |lc| lc + sum,
94 |lc| lc + CS::one(),
95 |lc| lc + input + witness,
96 );
97 Ok(())
98 }
99 }
100
101 let mut sum = Fr::one();
102 sum.add_assign(&Fr::one());
103 let circuit = R1CSCircuit::new(Fr::one(), sum, Fr::one());
104
105 let rng = &mut test_rng();
106
107 let parameters = Gm17::<Bls12_381, R1CSCircuit, [Fr]>::setup(circuit, rng).unwrap();
108
109 let proof =
110 Gm17::<Bls12_381, R1CSCircuit, [Fr]>::prove(¶meters.0, circuit, rng).unwrap();
111
112 let result =
113 Gm17::<Bls12_381, R1CSCircuit, [Fr]>::verify(¶meters.1, &[Fr::one(), sum], &proof)
114 .unwrap();
115 assert!(result);
116 }
117}