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::{ConstraintSynthesizer, ConstraintSystem, SynthesisError};
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<CS: ConstraintSystem<Fr>>(
87 self,
88 cs: &mut CS,
89 ) -> Result<(), SynthesisError> {
90 let input = cs.alloc_input(|| "x", || Ok(self.x.unwrap()))?;
91 let sum = cs.alloc_input(|| "sum", || Ok(self.sum.unwrap()))?;
92 let witness = cs.alloc(|| "w", || Ok(self.w.unwrap()))?;
93
94 cs.enforce(
95 || "check_one",
96 |lc| lc + sum,
97 |lc| lc + CS::one(),
98 |lc| lc + input + witness,
99 );
100 Ok(())
101 }
102 }
103
104 let mut sum = Fr::one();
105 sum.add_assign(&Fr::one());
106 let circuit = R1CSCircuit::new(Fr::one(), sum, Fr::one());
107
108 let rng = &mut test_rng();
109
110 let parameters = Gm17::<Bls12_377, R1CSCircuit, [Fr]>::setup(circuit, rng).unwrap();
111
112 let proof =
113 Gm17::<Bls12_377, R1CSCircuit, [Fr]>::prove(¶meters.0, circuit, rng).unwrap();
114
115 let result =
116 Gm17::<Bls12_377, R1CSCircuit, [Fr]>::verify(¶meters.1, &[Fr::one(), sum], &proof)
117 .unwrap();
118 assert!(result);
119 }
120}