testudo/src/r1csproof.rs
src/r1csproof.rsRaw
1#![allow(clippy::too_many_arguments)]
2use crate::group::CompressedGroup;
3use crate::sumcheck::SumcheckInstanceProof;
4
5use super::commitments::{Commitments, MultiCommitGens};
6use super::dense_mlpoly::{
7 DensePolynomial, EqPolynomial, PolyCommitment, PolyCommitmentGens, PolyEvalProof,
8};
9use super::errors::ProofVerifyError;
10use super::group::{
11 CompressGroupElement, DecompressGroupElement, GroupElement, VartimeMultiscalarMul,
12};
13use super::math::Math;
14use super::nizk::{EqualityProof, KnowledgeProof, ProductProof};
15use super::r1csinstance::R1CSInstance;
16use super::random::RandomTape;
17use super::scalar::Scalar;
18use super::sparse_mlpoly::{SparsePolyEntry, SparsePolynomial};
19use super::sumcheck::ZKSumcheckInstanceProof;
20use super::timer::Timer;
21use super::transcript::{AppendToTranscript, ProofTranscript};
22use ark_ec::ProjectiveCurve;
23use ark_ff::PrimeField;
24use ark_serialize::*;
25use ark_std::{One, Zero};
26use core::iter;
27use merlin::Transcript;
28
29#[derive(CanonicalSerialize, CanonicalDeserialize, Debug)]
30pub struct R1CSProof {
31 sc_proof_phase1: SumcheckInstanceProof,
32 claims_phase2: (Scalar, Scalar, Scalar, Scalar),
33 // pok_claims_phase2: (KnowledgeProof, ProductProof),
34 // proof_eq_sc_phase1: EqualityProof,
35 sc_proof_phase2: SumcheckInstanceProof,
36 eval_vars_at_ry: Scalar,
37 // proof_eval_vars_at_ry: PolyEvalProof,
38 // proof_eq_sc_phase2: EqualityProof,
39}
40
41pub struct R1CSSumcheckGens {
42 gens_1: MultiCommitGens,
43 gens_3: MultiCommitGens,
44 gens_4: MultiCommitGens,
45}
46
47// TODO: fix passing gens_1_ref
48impl R1CSSumcheckGens {
49 pub fn new(label: &'static [u8], gens_1_ref: &MultiCommitGens) -> Self {
50 let gens_1 = gens_1_ref.clone();
51 let gens_3 = MultiCommitGens::new(3, label);
52 let gens_4 = MultiCommitGens::new(4, label);
53
54 R1CSSumcheckGens {
55 gens_1,
56 gens_3,
57 gens_4,
58 }
59 }
60}
61
62pub struct R1CSGens {
63 gens_sc: R1CSSumcheckGens,
64 gens_pc: PolyCommitmentGens,
65}
66
67impl R1CSGens {
68 pub fn new(label: &'static [u8], _num_cons: usize, num_vars: usize) -> Self {
69 let num_poly_vars = num_vars.log_2();
70 let gens_pc = PolyCommitmentGens::new(num_poly_vars, label);
71 let gens_sc = R1CSSumcheckGens::new(label, &gens_pc.gens.gens_1);
72 R1CSGens { gens_sc, gens_pc }
73 }
74}
75
76impl R1CSProof {
77 fn prove_phase_one(
78 num_rounds: usize,
79 evals_tau: &mut DensePolynomial,
80 evals_Az: &mut DensePolynomial,
81 evals_Bz: &mut DensePolynomial,
82 evals_Cz: &mut DensePolynomial,
83 transcript: &mut Transcript,
84 ) -> (SumcheckInstanceProof, Vec<Scalar>, Vec<Scalar>) {
85 let comb_func =
86 |poly_tau_comp: &Scalar,
87 poly_A_comp: &Scalar,
88 poly_B_comp: &Scalar,
89 poly_C_comp: &Scalar|
90 -> Scalar { (*poly_tau_comp) * ((*poly_A_comp) * poly_B_comp - poly_C_comp) };
91
92 let (sc_proof_phase_one, r, claims) = SumcheckInstanceProof::prove_cubic_with_additive_term(
93 &Scalar::zero(), // claim is zero
94 num_rounds,
95 evals_tau,
96 evals_Az,
97 evals_Bz,
98 evals_Cz,
99 comb_func,
100 transcript,
101 );
102
103 (sc_proof_phase_one, r, claims)
104 }
105
106 fn prove_phase_two(
107 num_rounds: usize,
108 claim: &Scalar,
109 evals_z: &mut DensePolynomial,
110 evals_ABC: &mut DensePolynomial,
111 transcript: &mut Transcript,
112 ) -> (SumcheckInstanceProof, Vec<Scalar>, Vec<Scalar>) {
113 let comb_func =
114 |poly_A_comp: &Scalar, poly_B_comp: &Scalar| -> Scalar { (*poly_A_comp) * poly_B_comp };
115 let (sc_proof_phase_two, r, claims) = SumcheckInstanceProof::prove_quad(
116 claim, num_rounds, evals_z, evals_ABC, comb_func, transcript,
117 );
118
119 (sc_proof_phase_two, r, claims)
120 }
121
122 fn protocol_name() -> &'static [u8] {
123 b"R1CS proof"
124 }
125
126 pub fn prove(
127 inst: &R1CSInstance,
128 vars: Vec<Scalar>,
129 input: &[Scalar],
130 gens: &R1CSGens,
131 transcript: &mut Transcript,
132 random_tape: &mut RandomTape,
133 ) -> (R1CSProof, Vec<Scalar>, Vec<Scalar>) {
134 let timer_prove = Timer::new("R1CSProof::prove");
135 transcript.append_protocol_name(R1CSProof::protocol_name());
136
137 // we currently require the number of |inputs| + 1 to be at most number of vars
138 assert!(input.len() < vars.len());
139
140 input.append_to_transcript(b"input", transcript);
141
142 let poly_vars = DensePolynomial::new(vars.clone());
143
144 let timer_sc_proof_phase1 = Timer::new("prove_sc_phase_one");
145
146 // append input to variables to create a single vector z
147 let z = {
148 let num_inputs = input.len();
149 let num_vars = vars.len();
150 let mut z = vars;
151 z.extend(&vec![Scalar::one()]); // add constant term in z
152 z.extend(input);
153 z.extend(&vec![Scalar::zero(); num_vars - num_inputs - 1]); // we will pad with zeros
154 z
155 };
156
157 // derive the verifier's challenge tau
158 let (num_rounds_x, num_rounds_y) = (inst.get_num_cons().log_2(), z.len().log_2());
159 let tau = transcript.challenge_vector(b"challenge_tau", num_rounds_x);
160 // compute the initial evaluation table for R(\tau, x)
161 let mut poly_tau = DensePolynomial::new(EqPolynomial::new(tau).evals());
162 let (mut poly_Az, mut poly_Bz, mut poly_Cz) =
163 inst.multiply_vec(inst.get_num_cons(), z.len(), &z);
164
165 let (sc_proof_phase1, rx, _claims_phase1) = R1CSProof::prove_phase_one(
166 num_rounds_x,
167 &mut poly_tau,
168 &mut poly_Az,
169 &mut poly_Bz,
170 &mut poly_Cz,
171 transcript,
172 );
173 assert_eq!(poly_tau.len(), 1);
174 assert_eq!(poly_Az.len(), 1);
175 assert_eq!(poly_Bz.len(), 1);
176 assert_eq!(poly_Cz.len(), 1);
177 timer_sc_proof_phase1.stop();
178
179 let (tau_claim, Az_claim, Bz_claim, Cz_claim) =
180 (&poly_tau[0], &poly_Az[0], &poly_Bz[0], &poly_Cz[0]);
181 let prod_Az_Bz_claims = (*Az_claim) * Bz_claim;
182
183 // prove the final step of sum-check #1
184 let taus_bound_rx = tau_claim;
185 let claim_post_phase1 = ((*Az_claim) * Bz_claim - Cz_claim) * taus_bound_rx;
186
187 let timer_sc_proof_phase2 = Timer::new("prove_sc_phase_two");
188 // combine the three claims into a single claim
189 let r_A = transcript.challenge_scalar(b"challenege_Az");
190 let r_B = transcript.challenge_scalar(b"challenege_Bz");
191 let r_C = transcript.challenge_scalar(b"challenege_Cz");
192 let claim_phase2 = r_A * Az_claim + r_B * Bz_claim + r_C * Cz_claim;
193
194 let evals_ABC = {
195 // compute the initial evaluation table for R(\tau, x)
196 let evals_rx = EqPolynomial::new(rx.clone()).evals();
197 let (evals_A, evals_B, evals_C) =
198 inst.compute_eval_table_sparse(inst.get_num_cons(), z.len(), &evals_rx);
199
200 assert_eq!(evals_A.len(), evals_B.len());
201 assert_eq!(evals_A.len(), evals_C.len());
202 (0..evals_A.len())
203 .map(|i| r_A * evals_A[i] + r_B * evals_B[i] + r_C * evals_C[i])
204 .collect::<Vec<Scalar>>()
205 };
206
207 // another instance of the sum-check protocol
208 let (sc_proof_phase2, ry, claims_phase2) = R1CSProof::prove_phase_two(
209 num_rounds_y,
210 &claim_phase2,
211 &mut DensePolynomial::new(z),
212 &mut DensePolynomial::new(evals_ABC),
213 transcript,
214 );
215 timer_sc_proof_phase2.stop();
216
217 let timer_polyeval = Timer::new("polyeval");
218 let eval_vars_at_ry = poly_vars.evaluate(&ry[1..].to_vec());
219 timer_polyeval.stop();
220
221 timer_prove.stop();
222
223 (
224 R1CSProof {
225 sc_proof_phase1,
226 claims_phase2: (*Az_claim, *Bz_claim, *Cz_claim, prod_Az_Bz_claims),
227 sc_proof_phase2,
228 eval_vars_at_ry,
229 },
230 rx,
231 ry,
232 )
233 }
234
235 pub fn verify(
236 &self,
237 num_vars: usize,
238 num_cons: usize,
239 input: &[Scalar],
240 evals: &(Scalar, Scalar, Scalar),
241 transcript: &mut Transcript,
242 gens: &R1CSGens,
243 ) -> Result<(Vec<Scalar>, Vec<Scalar>), ProofVerifyError> {
244 transcript.append_protocol_name(R1CSProof::protocol_name());
245
246 input.append_to_transcript(b"input", transcript);
247
248 let n = num_vars;
249
250 let (num_rounds_x, num_rounds_y) = (num_cons.log_2(), (2 * num_vars).log_2());
251
252 // derive the verifier's challenge tau
253 let tau = transcript.challenge_vector(b"challenge_tau", num_rounds_x);
254
255 // verify the first sum-check instance
256 let claim_phase1 = Scalar::zero();
257 let (claim_post_phase1, rx) =
258 self
259 .sc_proof_phase1
260 .verify(claim_phase1, num_rounds_x, 3, transcript)?;
261
262 // perform the intermediate sum-check test with claimed Az, Bz, and Cz
263 let (Az_claim, Bz_claim, Cz_claim, prod_Az_Bz_claims) = &self.claims_phase2;
264
265 let taus_bound_rx: Scalar = (0..rx.len())
266 .map(|i| rx[i] * tau[i] + (Scalar::one() - rx[i]) * (Scalar::one() - tau[i]))
267 .product();
268
269 let expected_claim_post_phase1 = (*prod_Az_Bz_claims - *Cz_claim) * (taus_bound_rx);
270
271 assert_eq!(claim_post_phase1, expected_claim_post_phase1);
272
273 // derive three public challenges and then derive a joint claim
274 let r_A = transcript.challenge_scalar(b"challenege_Az");
275 let r_B = transcript.challenge_scalar(b"challenege_Bz");
276 let r_C = transcript.challenge_scalar(b"challenege_Cz");
277
278 let claim_phase2 = r_A * Az_claim + r_B * Bz_claim + r_C * Cz_claim;
279
280 // verify the joint claim with a sum-check protocol
281 let (claim_post_phase2, ry) =
282 self
283 .sc_proof_phase2
284 .verify(claim_phase2, num_rounds_y, 2, transcript)?;
285
286 let poly_input_eval = {
287 // constant term
288 let mut input_as_sparse_poly_entries = vec![SparsePolyEntry::new(0, Scalar::one())];
289 //remaining inputs
290 input_as_sparse_poly_entries.extend(
291 (0..input.len())
292 .map(|i| SparsePolyEntry::new(i + 1, input[i]))
293 .collect::<Vec<SparsePolyEntry>>(),
294 );
295 SparsePolynomial::new(n.log_2(), input_as_sparse_poly_entries).evaluate(&ry[1..])
296 };
297
298 let eval_Z_at_ry = (Scalar::one() - ry[0]) * self.eval_vars_at_ry + ry[0] * poly_input_eval;
299
300 // perform the final check in the second sum-check protocol
301 let (eval_A_r, eval_B_r, eval_C_r) = evals;
302 let scalar = r_A * eval_A_r + r_B * eval_B_r + r_C * eval_C_r;
303 let expected_claim_post_phase2 = eval_Z_at_ry * scalar;
304
305 assert_eq!(expected_claim_post_phase2, claim_post_phase2);
306
307 Ok((rx, ry))
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 use ark_std::UniformRand;
315 use test::Bencher;
316
317 fn produce_tiny_r1cs() -> (R1CSInstance, Vec<Scalar>, Vec<Scalar>) {
318 // three constraints over five variables Z1, Z2, Z3, Z4, and Z5
319 // rounded to the nearest power of two
320 let num_cons = 128;
321 let num_vars = 256;
322 let num_inputs = 2;
323
324 // encode the above constraints into three matrices
325 let mut A: Vec<(usize, usize, Scalar)> = Vec::new();
326 let mut B: Vec<(usize, usize, Scalar)> = Vec::new();
327 let mut C: Vec<(usize, usize, Scalar)> = Vec::new();
328
329 let one = Scalar::one();
330 // constraint 0 entries
331 // (Z1 + Z2) * I0 - Z3 = 0;
332 A.push((0, 0, one));
333 A.push((0, 1, one));
334 B.push((0, num_vars + 1, one));
335 C.push((0, 2, one));
336
337 // constraint 1 entries
338 // (Z1 + I1) * (Z3) - Z4 = 0
339 A.push((1, 0, one));
340 A.push((1, num_vars + 2, one));
341 B.push((1, 2, one));
342 C.push((1, 3, one));
343 // constraint 3 entries
344 // Z5 * 1 - 0 = 0
345 A.push((2, 4, one));
346 B.push((2, num_vars, one));
347
348 let inst = R1CSInstance::new(num_cons, num_vars, num_inputs, &A, &B, &C);
349
350 // compute a satisfying assignment
351 let mut rng = ark_std::rand::thread_rng();
352 let i0 = Scalar::rand(&mut rng);
353 let i1 = Scalar::rand(&mut rng);
354 let z1 = Scalar::rand(&mut rng);
355 let z2 = Scalar::rand(&mut rng);
356 let z3 = (z1 + z2) * i0; // constraint 1: (Z1 + Z2) * I0 - Z3 = 0;
357 let z4 = (z1 + i1) * z3; // constraint 2: (Z1 + I1) * (Z3) - Z4 = 0
358 let z5 = Scalar::zero(); //constraint 3
359
360 let mut vars = vec![Scalar::zero(); num_vars];
361 vars[0] = z1;
362 vars[1] = z2;
363 vars[2] = z3;
364 vars[3] = z4;
365 vars[4] = z5;
366
367 let mut input = vec![Scalar::zero(); num_inputs];
368 input[0] = i0;
369 input[1] = i1;
370
371 (inst, vars, input)
372 }
373
374 #[test]
375 fn test_tiny_r1cs() {
376 let (inst, vars, input) = tests::produce_tiny_r1cs();
377 let is_sat = inst.is_sat(&vars, &input);
378 assert!(is_sat);
379 }
380
381 #[test]
382 fn test_synthetic_r1cs() {
383 let (inst, vars, input) = R1CSInstance::produce_synthetic_r1cs(1024, 1024, 10);
384 let is_sat = inst.is_sat(&vars, &input);
385 assert!(is_sat);
386 }
387
388 #[test]
389 pub fn check_r1cs_proof() {
390 let num_vars = 1024;
391 let num_cons = num_vars;
392 let num_inputs = 10;
393 let (inst, vars, input) = R1CSInstance::produce_synthetic_r1cs(num_cons, num_vars, num_inputs);
394
395 let gens = R1CSGens::new(b"test-m", num_cons, num_vars);
396
397 let mut random_tape = RandomTape::new(b"proof");
398 let mut prover_transcript = Transcript::new(b"example");
399 let (proof, rx, ry) = R1CSProof::prove(
400 &inst,
401 vars,
402 &input,
403 &gens,
404 &mut prover_transcript,
405 &mut random_tape,
406 );
407
408 let inst_evals = inst.evaluate(&rx, &ry);
409
410 let mut verifier_transcript = Transcript::new(b"example");
411 assert!(proof
412 .verify(
413 inst.get_num_vars(),
414 inst.get_num_cons(),
415 &input,
416 &inst_evals,
417 &mut verifier_transcript,
418 &gens,
419 )
420 .is_ok());
421 }
422
423 #[bench]
424 fn bench_r1cs_proof(b: &mut Bencher) {
425 b.iter(|| check_r1cs_proof());
426 }
427}