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