-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathprover.rs
1786 lines (1597 loc) · 72.2 KB
/
prover.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module implements prover's zk-proof primitive.
use crate::{
circuits::{
argument::{Argument, ArgumentType},
berkeley_columns::{BerkeleyChallenges, Environment, LookupEnvironment},
constraints::zk_rows_strict_lower_bound,
expr::{self, l0_1, Constants},
gate::GateType,
lookup::{self, runtime_tables::RuntimeTable, tables::combine_table_entry},
polynomials::{
complete_add::CompleteAdd,
endomul_scalar::EndomulScalar,
endosclmul::EndosclMul,
foreign_field_add::circuitgates::ForeignFieldAdd,
foreign_field_mul::{self, circuitgates::ForeignFieldMul},
generic, permutation,
poseidon::Poseidon,
range_check::circuitgates::{RangeCheck0, RangeCheck1},
rot::Rot64,
varbasemul::VarbaseMul,
xor::Xor16,
},
wires::{COLUMNS, PERMUTS},
},
curve::KimchiCurve,
error::ProverError,
lagrange_basis_evaluations::LagrangeBasisEvaluations,
plonk_sponge::FrSponge,
proof::{
LookupCommitments, PointEvaluations, ProofEvaluations, ProverCommitments, ProverProof,
RecursionChallenge,
},
prover_index::ProverIndex,
verifier_index::VerifierIndex,
};
use ark_ff::{FftField, Field, One, PrimeField, UniformRand, Zero};
use ark_poly::{
univariate::DensePolynomial, DenseUVPolynomial, EvaluationDomain, Evaluations, Polynomial,
Radix2EvaluationDomain as D,
};
use itertools::Itertools;
use mina_poseidon::{sponge::ScalarChallenge, FqSponge};
use o1_utils::ExtendedDensePolynomial as _;
use poly_commitment::{
commitment::{
absorb_commitment, b_poly_coefficients, BlindedCommitment, CommitmentCurve, PolyComm,
},
ipa::DensePolynomialOrEvaluations,
OpenProof, SRS as _,
};
use rayon::prelude::*;
use std::{array, collections::HashMap};
/// The result of a proof creation or verification.
type Result<T> = std::result::Result<T, ProverError>;
/// Helper to quickly test if a witness satisfies a constraint
macro_rules! check_constraint {
($index:expr, $evaluation:expr) => {{
check_constraint!($index, stringify!($evaluation), $evaluation);
}};
($index:expr, $label:expr, $evaluation:expr) => {{
if cfg!(debug_assertions) {
let (_, res) = $evaluation
.interpolate_by_ref()
.divide_by_vanishing_poly($index.cs.domain.d1)
.unwrap();
if !res.is_zero() {
panic!("couldn't divide by vanishing polynomial: {}", $label);
}
}
}};
}
/// Contains variables needed for lookup in the prover algorithm.
#[derive(Default)]
struct LookupContext<G, F>
where
G: CommitmentCurve,
F: FftField,
{
/// The joint combiner used to join the columns of lookup tables
joint_combiner: Option<F>,
/// The power of the joint_combiner that can be used to add a table_id column
/// to the concatenated lookup tables.
table_id_combiner: Option<F>,
/// The combined lookup entry that can be used as dummy value
dummy_lookup_value: Option<F>,
/// The combined lookup table
joint_lookup_table: Option<DensePolynomial<F>>,
joint_lookup_table_d8: Option<Evaluations<F, D<F>>>,
/// The sorted polynomials `s` in different forms
sorted: Option<Vec<Evaluations<F, D<F>>>>,
sorted_coeffs: Option<Vec<DensePolynomial<F>>>,
sorted_comms: Option<Vec<BlindedCommitment<G>>>,
sorted8: Option<Vec<Evaluations<F, D<F>>>>,
/// The aggregation polynomial in different forms
aggreg_coeffs: Option<DensePolynomial<F>>,
aggreg_comm: Option<BlindedCommitment<G>>,
aggreg8: Option<Evaluations<F, D<F>>>,
// lookup-related evaluations
/// evaluation of lookup aggregation polynomial
pub lookup_aggregation_eval: Option<PointEvaluations<Vec<F>>>,
/// evaluation of lookup table polynomial
pub lookup_table_eval: Option<PointEvaluations<Vec<F>>>,
/// evaluation of lookup sorted polynomials
pub lookup_sorted_eval: [Option<PointEvaluations<Vec<F>>>; 5],
/// evaluation of runtime lookup table polynomial
pub runtime_lookup_table_eval: Option<PointEvaluations<Vec<F>>>,
/// Runtime table
runtime_table: Option<DensePolynomial<F>>,
runtime_table_d8: Option<Evaluations<F, D<F>>>,
runtime_table_comm: Option<BlindedCommitment<G>>,
runtime_second_col_d8: Option<Evaluations<F, D<F>>>,
}
impl<G: KimchiCurve, OpeningProof: OpenProof<G>> ProverProof<G, OpeningProof>
where
G::BaseField: PrimeField,
{
/// This function constructs prover's zk-proof from the witness & the `ProverIndex` against SRS instance
///
/// # Errors
///
/// Will give error if `create_recursive` process fails.
pub fn create<
EFqSponge: Clone + FqSponge<G::BaseField, G, G::ScalarField>,
EFrSponge: FrSponge<G::ScalarField>,
>(
groupmap: &G::Map,
witness: [Vec<G::ScalarField>; COLUMNS],
runtime_tables: &[RuntimeTable<G::ScalarField>],
index: &ProverIndex<G, OpeningProof>,
) -> Result<Self>
where
VerifierIndex<G, OpeningProof>: Clone,
{
Self::create_recursive::<EFqSponge, EFrSponge>(
groupmap,
witness,
runtime_tables,
index,
Vec::new(),
None,
)
}
/// This function constructs prover's recursive zk-proof from the witness &
/// the `ProverIndex` against SRS instance
///
/// # Errors
///
/// Will give error if inputs(like `lookup_context.joint_lookup_table_d8`)
/// are None.
///
/// # Panics
///
/// Will panic if `lookup_context.joint_lookup_table_d8` is None.
pub fn create_recursive<
EFqSponge: Clone + FqSponge<G::BaseField, G, G::ScalarField>,
EFrSponge: FrSponge<G::ScalarField>,
>(
group_map: &G::Map,
mut witness: [Vec<G::ScalarField>; COLUMNS],
runtime_tables: &[RuntimeTable<G::ScalarField>],
index: &ProverIndex<G, OpeningProof>,
prev_challenges: Vec<RecursionChallenge<G>>,
blinders: Option<[Option<PolyComm<G::ScalarField>>; COLUMNS]>,
) -> Result<Self>
where
VerifierIndex<G, OpeningProof>: Clone,
{
internal_tracing::checkpoint!(internal_traces; create_recursive);
let d1_size = index.cs.domain.d1.size();
let (_, endo_r) = G::endos();
let num_chunks = if d1_size < index.max_poly_size {
1
} else {
d1_size / index.max_poly_size
};
// TODO: rng should be passed as arg
let rng = &mut rand::rngs::OsRng;
// Verify the circuit satisfiability by the computed witness (baring plookup constraints)
// Catch mistakes before proof generation.
if cfg!(debug_assertions) && !index.cs.disable_gates_checks {
let public = witness[0][0..index.cs.public].to_vec();
index.verify(&witness, &public).expect("incorrect witness");
}
//~ 1. Ensure we have room in the witness for the zero-knowledge rows.
//~ We currently expect the witness not to be of the same length as the domain,
//~ but instead be of the length of the (smaller) circuit.
//~ If we cannot add `zk_rows` rows to the columns of the witness before reaching
//~ the size of the domain, abort.
let length_witness = witness[0].len();
let length_padding = d1_size
.checked_sub(length_witness)
.ok_or(ProverError::NoRoomForZkInWitness)?;
let zero_knowledge_limit = zk_rows_strict_lower_bound(num_chunks);
// Because the lower bound is strict, the result of the function above
// is not a sufficient number of zero knowledge rows, so the error must
// be raised anytime the number of zero knowledge rows is not greater
// than the strict lower bound.
// Example:
// for 1 chunk, `zero_knowledge_limit` is 2, and we need at least 3,
// thus the error should be raised and the message should say that the
// expected number of zero knowledge rows is 3 (hence the + 1).
if (index.cs.zk_rows as usize) <= zero_knowledge_limit {
return Err(ProverError::NotZeroKnowledge(
zero_knowledge_limit + 1,
index.cs.zk_rows as usize,
));
}
if length_padding < index.cs.zk_rows as usize {
return Err(ProverError::NoRoomForZkInWitness);
}
//~ 1. Pad the witness columns with Zero gates to make them the same length as the domain.
//~ Then, randomize the last `zk_rows` of each columns.
internal_tracing::checkpoint!(internal_traces; pad_witness);
for w in &mut witness {
if w.len() != length_witness {
return Err(ProverError::WitnessCsInconsistent);
}
// padding
w.extend(std::iter::repeat(G::ScalarField::zero()).take(length_padding));
// zk-rows
for row in w.iter_mut().rev().take(index.cs.zk_rows as usize) {
*row = <G::ScalarField as UniformRand>::rand(rng);
}
}
//~ 1. Setup the Fq-Sponge.
internal_tracing::checkpoint!(internal_traces; set_up_fq_sponge);
let mut fq_sponge = EFqSponge::new(G::other_curve_sponge_params());
//~ 1. Absorb the digest of the VerifierIndex.
let verifier_index_digest = index.verifier_index_digest::<EFqSponge>();
fq_sponge.absorb_fq(&[verifier_index_digest]);
//~ 1. Absorb the commitments of the previous challenges with the Fq-sponge.
for RecursionChallenge { comm, .. } in &prev_challenges {
absorb_commitment(&mut fq_sponge, comm)
}
//~ 1. Compute the negated public input polynomial as
//~ the polynomial that evaluates to $-p_i$ for the first `public_input_size` values of the domain,
//~ and $0$ for the rest.
let public = witness[0][0..index.cs.public].to_vec();
let public_poly = -Evaluations::<G::ScalarField, D<G::ScalarField>>::from_vec_and_domain(
public,
index.cs.domain.d1,
)
.interpolate();
//~ 1. Commit (non-hiding) to the negated public input polynomial.
let public_comm = index.srs.commit_non_hiding(&public_poly, num_chunks);
let public_comm = {
index
.srs
.mask_custom(
public_comm.clone(),
&public_comm.map(|_| G::ScalarField::one()),
)
.unwrap()
.commitment
};
//~ 1. Absorb the commitment to the public polynomial with the Fq-Sponge.
//~
//~ Note: unlike the original PLONK protocol,
//~ the prover also provides evaluations of the public polynomial to help the verifier circuit.
//~ This is why we need to absorb the commitment to the public polynomial at this point.
absorb_commitment(&mut fq_sponge, &public_comm);
//~ 1. Commit to the witness columns by creating `COLUMNS` hidding commitments.
//~
//~ Note: since the witness is in evaluation form,
//~ we can use the `commit_evaluation` optimization.
internal_tracing::checkpoint!(internal_traces; commit_to_witness_columns);
let mut w_comm = vec![];
for col in 0..COLUMNS {
// witness coeff -> witness eval
let witness_eval =
Evaluations::<G::ScalarField, D<G::ScalarField>>::from_vec_and_domain(
witness[col].clone(),
index.cs.domain.d1,
);
let com = match blinders.as_ref().and_then(|b| b[col].as_ref()) {
// no blinders: blind the witness
None => index
.srs
.commit_evaluations(index.cs.domain.d1, &witness_eval, rng),
// blinders: blind the witness with them
Some(blinder) => {
// TODO: make this a function rather no? mask_with_custom()
let witness_com = index
.srs
.commit_evaluations_non_hiding(index.cs.domain.d1, &witness_eval);
index
.srs
.mask_custom(witness_com, blinder)
.map_err(ProverError::WrongBlinders)?
}
};
w_comm.push(com);
}
let w_comm: [BlindedCommitment<G>; COLUMNS] = w_comm
.try_into()
.expect("previous loop is of the correct length");
//~ 1. Absorb the witness commitments with the Fq-Sponge.
w_comm
.iter()
.for_each(|c| absorb_commitment(&mut fq_sponge, &c.commitment));
//~ 1. Compute the witness polynomials by interpolating each `COLUMNS` of the witness.
//~ As mentioned above, we commit using the evaluations form rather than the coefficients
//~ form so we can take advantage of the sparsity of the evaluations (i.e., there are many
//~ 0 entries and entries that have less-than-full-size field elemnts.)
let witness_poly: [DensePolynomial<G::ScalarField>; COLUMNS] = array::from_fn(|i| {
Evaluations::<G::ScalarField, D<G::ScalarField>>::from_vec_and_domain(
witness[i].clone(),
index.cs.domain.d1,
)
.interpolate()
});
let mut lookup_context = LookupContext::default();
//~ 1. If using lookup:
if let Some(lcs) = &index.cs.lookup_constraint_system {
internal_tracing::checkpoint!(internal_traces; use_lookup, {
"uses_lookup": true,
"uses_runtime_tables": lcs.runtime_tables.is_some(),
});
//~~ * if using runtime table:
if let Some(cfg_runtime_tables) = &lcs.runtime_tables {
//~~~ * check that all the provided runtime tables have length and IDs that match the runtime table configuration of the index
//~~~ we expect the given runtime tables to be sorted as configured, this makes it easier afterwards
let expected_runtime: Vec<_> = cfg_runtime_tables
.iter()
.map(|rt| (rt.id, rt.len))
.collect();
let runtime: Vec<_> = runtime_tables
.iter()
.map(|rt| (rt.id, rt.data.len()))
.collect();
if expected_runtime != runtime {
return Err(ProverError::RuntimeTablesInconsistent);
}
//~~~ * calculate the contribution to the second column of the lookup table
//~~~ (the runtime vector)
let (runtime_table_contribution, runtime_table_contribution_d8) = {
let mut offset = lcs
.runtime_table_offset
.expect("runtime configuration missing offset");
let mut evals = vec![G::ScalarField::zero(); d1_size];
for rt in runtime_tables {
let range = offset..(offset + rt.data.len());
evals[range].copy_from_slice(&rt.data);
offset += rt.data.len();
}
// zero-knowledge
for e in evals.iter_mut().rev().take(index.cs.zk_rows as usize) {
*e = <G::ScalarField as UniformRand>::rand(rng);
}
// get coeff and evaluation form
let runtime_table_contribution =
Evaluations::from_vec_and_domain(evals, index.cs.domain.d1).interpolate();
let runtime_table_contribution_d8 =
runtime_table_contribution.evaluate_over_domain_by_ref(index.cs.domain.d8);
(runtime_table_contribution, runtime_table_contribution_d8)
};
// commit the runtime polynomial
// (and save it to the proof)
let runtime_table_comm =
index
.srs
.commit(&runtime_table_contribution, num_chunks, rng);
// absorb the commitment
absorb_commitment(&mut fq_sponge, &runtime_table_comm.commitment);
// pre-compute the updated second column of the lookup table
let mut second_column_d8 = runtime_table_contribution_d8.clone();
second_column_d8
.evals
.par_iter_mut()
.enumerate()
.for_each(|(row, e)| {
*e += lcs.lookup_table8[1][row];
});
lookup_context.runtime_table = Some(runtime_table_contribution);
lookup_context.runtime_table_d8 = Some(runtime_table_contribution_d8);
lookup_context.runtime_table_comm = Some(runtime_table_comm);
lookup_context.runtime_second_col_d8 = Some(second_column_d8);
}
//~~ * If queries involve a lookup table with multiple columns
//~~ then squeeze the Fq-Sponge to obtain the joint combiner challenge $j'$,
//~~ otherwise set the joint combiner challenge $j'$ to $0$.
let joint_combiner = if lcs.configuration.lookup_info.features.joint_lookup_used {
fq_sponge.challenge()
} else {
G::ScalarField::zero()
};
//~~ * Derive the scalar joint combiner $j$ from $j'$ using the endomorphism (TODO: specify)
let joint_combiner: G::ScalarField = ScalarChallenge(joint_combiner).to_field(endo_r);
//~~ * If multiple lookup tables are involved,
//~~ set the `table_id_combiner` as the $j^i$ with $i$ the maximum width of any used table.
//~~ Essentially, this is to add a last column of table ids to the concatenated lookup tables.
let table_id_combiner: G::ScalarField = if lcs.table_ids8.as_ref().is_some() {
joint_combiner.pow([lcs.configuration.lookup_info.max_joint_size as u64])
} else {
// TODO: just set this to None in case multiple tables are not used
G::ScalarField::zero()
};
lookup_context.table_id_combiner = Some(table_id_combiner);
//~~ * Compute the dummy lookup value as the combination of the last entry of the XOR table (so `(0, 0, 0)`).
//~~ Warning: This assumes that we always use the XOR table when using lookups.
let dummy_lookup_value = lcs
.configuration
.dummy_lookup
.evaluate(&joint_combiner, &table_id_combiner);
lookup_context.dummy_lookup_value = Some(dummy_lookup_value);
//~~ * Compute the lookup table values as the combination of the lookup table entries.
let joint_lookup_table_d8 = {
let mut evals = Vec::with_capacity(d1_size);
for idx in 0..(d1_size * 8) {
let table_id = match lcs.table_ids8.as_ref() {
Some(table_ids8) => table_ids8.evals[idx],
None =>
// If there is no `table_ids8` in the constraint system,
// every table ID is identically 0.
{
G::ScalarField::zero()
}
};
let combined_entry =
if !lcs.configuration.lookup_info.features.uses_runtime_tables {
let table_row = lcs.lookup_table8.iter().map(|e| &e.evals[idx]);
combine_table_entry(
&joint_combiner,
&table_id_combiner,
table_row,
&table_id,
)
} else {
// if runtime table are used, the second row is modified
let second_col = lookup_context.runtime_second_col_d8.as_ref().unwrap();
let table_row = lcs.lookup_table8.iter().enumerate().map(|(col, e)| {
if col == 1 {
&second_col.evals[idx]
} else {
&e.evals[idx]
}
});
combine_table_entry(
&joint_combiner,
&table_id_combiner,
table_row,
&table_id,
)
};
evals.push(combined_entry);
}
Evaluations::from_vec_and_domain(evals, index.cs.domain.d8)
};
// TODO: This interpolation is avoidable.
let joint_lookup_table = joint_lookup_table_d8.interpolate_by_ref();
//~~ * Compute the sorted evaluations.
// TODO: Once we switch to committing using lagrange commitments,
// `witness` will be consumed when we interpolate, so interpolation will
// have to moved below this.
let sorted: Vec<_> = lookup::constraints::sorted(
dummy_lookup_value,
&joint_lookup_table_d8,
index.cs.domain.d1,
&index.cs.gates,
&witness,
joint_combiner,
table_id_combiner,
&lcs.configuration.lookup_info,
index.cs.zk_rows as usize,
)?;
//~~ * Randomize the last `EVALS` rows in each of the sorted polynomials
//~~ in order to add zero-knowledge to the protocol.
let sorted: Vec<_> = sorted
.into_iter()
.map(|chunk| {
lookup::constraints::zk_patch(
chunk,
index.cs.domain.d1,
index.cs.zk_rows as usize,
rng,
)
})
.collect();
//~~ * Commit each of the sorted polynomials.
let sorted_comms: Vec<_> = sorted
.iter()
.map(|v| index.srs.commit_evaluations(index.cs.domain.d1, v, rng))
.collect();
//~~ * Absorb each commitments to the sorted polynomials.
sorted_comms
.iter()
.for_each(|c| absorb_commitment(&mut fq_sponge, &c.commitment));
// precompute different forms of the sorted polynomials for later
// TODO: We can avoid storing these coefficients.
let sorted_coeffs: Vec<_> = sorted.iter().map(|e| e.clone().interpolate()).collect();
let sorted8: Vec<_> = sorted_coeffs
.iter()
.map(|v| v.evaluate_over_domain_by_ref(index.cs.domain.d8))
.collect();
lookup_context.joint_combiner = Some(joint_combiner);
lookup_context.sorted = Some(sorted);
lookup_context.sorted_coeffs = Some(sorted_coeffs);
lookup_context.sorted_comms = Some(sorted_comms);
lookup_context.sorted8 = Some(sorted8);
lookup_context.joint_lookup_table_d8 = Some(joint_lookup_table_d8);
lookup_context.joint_lookup_table = Some(joint_lookup_table);
}
//~ 1. Sample $\beta$ with the Fq-Sponge.
let beta = fq_sponge.challenge();
//~ 1. Sample $\gamma$ with the Fq-Sponge.
let gamma = fq_sponge.challenge();
//~ 1. If using lookup:
if let Some(lcs) = &index.cs.lookup_constraint_system {
//~~ * Compute the lookup aggregation polynomial.
let joint_lookup_table_d8 = lookup_context.joint_lookup_table_d8.as_ref().unwrap();
let aggreg = lookup::constraints::aggregation::<_, G::ScalarField>(
lookup_context.dummy_lookup_value.unwrap(),
joint_lookup_table_d8,
index.cs.domain.d1,
&index.cs.gates,
&witness,
&lookup_context.joint_combiner.unwrap(),
&lookup_context.table_id_combiner.unwrap(),
beta,
gamma,
lookup_context.sorted.as_ref().unwrap(),
rng,
&lcs.configuration.lookup_info,
index.cs.zk_rows as usize,
)?;
//~~ * Commit to the aggregation polynomial.
let aggreg_comm = index
.srs
.commit_evaluations(index.cs.domain.d1, &aggreg, rng);
//~~ * Absorb the commitment to the aggregation polynomial with the Fq-Sponge.
absorb_commitment(&mut fq_sponge, &aggreg_comm.commitment);
// precompute different forms of the aggregation polynomial for later
let aggreg_coeffs = aggreg.interpolate();
// TODO: There's probably a clever way to expand the domain without
// interpolating
let aggreg8 = aggreg_coeffs.evaluate_over_domain_by_ref(index.cs.domain.d8);
lookup_context.aggreg_comm = Some(aggreg_comm);
lookup_context.aggreg_coeffs = Some(aggreg_coeffs);
lookup_context.aggreg8 = Some(aggreg8);
}
//~ 1. Compute the permutation aggregation polynomial $z$.
internal_tracing::checkpoint!(internal_traces; z_permutation_aggregation_polynomial);
let z_poly = index.perm_aggreg(&witness, &beta, &gamma, rng)?;
//~ 1. Commit (hidding) to the permutation aggregation polynomial $z$.
let z_comm = index.srs.commit(&z_poly, num_chunks, rng);
//~ 1. Absorb the permutation aggregation polynomial $z$ with the Fq-Sponge.
absorb_commitment(&mut fq_sponge, &z_comm.commitment);
//~ 1. Sample $\alpha'$ with the Fq-Sponge.
let alpha_chal = ScalarChallenge(fq_sponge.challenge());
//~ 1. Derive $\alpha$ from $\alpha'$ using the endomorphism (TODO: details)
let alpha: G::ScalarField = alpha_chal.to_field(endo_r);
//~ 1. TODO: instantiate alpha?
let mut all_alphas = index.powers_of_alpha.clone();
all_alphas.instantiate(alpha);
//~ 1. Compute the quotient polynomial (the $t$ in $f = Z_H \cdot t$).
//~ The quotient polynomial is computed by adding all these polynomials together:
//~~ * the combined constraints for all the gates
//~~ * the combined constraints for the permutation
//~~ * TODO: lookup
//~~ * the negated public polynomial
//~ and by then dividing the resulting polynomial with the vanishing polynomial $Z_H$.
//~ TODO: specify the split of the permutation polynomial into perm and bnd?
let lookup_env = if let Some(lcs) = &index.cs.lookup_constraint_system {
let joint_lookup_table_d8 = lookup_context.joint_lookup_table_d8.as_ref().unwrap();
Some(LookupEnvironment {
aggreg: lookup_context.aggreg8.as_ref().unwrap(),
sorted: lookup_context.sorted8.as_ref().unwrap(),
selectors: &lcs.lookup_selectors,
table: joint_lookup_table_d8,
runtime_selector: lcs.runtime_selector.as_ref(),
runtime_table: lookup_context.runtime_table_d8.as_ref(),
})
} else {
None
};
internal_tracing::checkpoint!(internal_traces; eval_witness_polynomials_over_domains);
let lagrange = index.cs.evaluate(&witness_poly, &z_poly);
internal_tracing::checkpoint!(internal_traces; compute_index_evals);
let env = {
let mut index_evals = HashMap::new();
use GateType::*;
index_evals.insert(Generic, &index.column_evaluations.generic_selector4);
index_evals.insert(Poseidon, &index.column_evaluations.poseidon_selector8);
index_evals.insert(
CompleteAdd,
&index.column_evaluations.complete_add_selector4,
);
index_evals.insert(VarBaseMul, &index.column_evaluations.mul_selector8);
index_evals.insert(EndoMul, &index.column_evaluations.emul_selector8);
index_evals.insert(
EndoMulScalar,
&index.column_evaluations.endomul_scalar_selector8,
);
if let Some(selector) = &index.column_evaluations.range_check0_selector8.as_ref() {
index_evals.insert(GateType::RangeCheck0, selector);
}
if let Some(selector) = &index.column_evaluations.range_check1_selector8.as_ref() {
index_evals.insert(GateType::RangeCheck1, selector);
}
if let Some(selector) = index
.column_evaluations
.foreign_field_add_selector8
.as_ref()
{
index_evals.insert(GateType::ForeignFieldAdd, selector);
}
if let Some(selector) = index
.column_evaluations
.foreign_field_mul_selector8
.as_ref()
{
index_evals.extend(
foreign_field_mul::gadget::circuit_gates()
.iter()
.enumerate()
.map(|(_, gate_type)| (*gate_type, selector)),
);
}
if let Some(selector) = index.column_evaluations.xor_selector8.as_ref() {
index_evals.insert(GateType::Xor16, selector);
}
if let Some(selector) = index.column_evaluations.rot_selector8.as_ref() {
index_evals.insert(GateType::Rot64, selector);
}
let mds = &G::sponge_params().mds;
Environment {
constants: Constants {
endo_coefficient: index.cs.endo,
mds,
zk_rows: index.cs.zk_rows,
},
challenges: BerkeleyChallenges {
alpha,
beta,
gamma,
joint_combiner: lookup_context
.joint_combiner
.unwrap_or(G::ScalarField::zero()),
},
witness: &lagrange.d8.this.w,
coefficient: &index.column_evaluations.coefficients8,
vanishes_on_zero_knowledge_and_previous_rows: &index
.cs
.precomputations()
.vanishes_on_zero_knowledge_and_previous_rows,
z: &lagrange.d8.this.z,
l0_1: l0_1(index.cs.domain.d1),
domain: index.cs.domain,
index: index_evals,
lookup: lookup_env,
}
};
let mut cache = expr::Cache::default();
internal_tracing::checkpoint!(internal_traces; compute_quotient_poly);
let quotient_poly = {
// generic
let mut t4 = {
let generic_constraint =
generic::Generic::combined_constraints(&all_alphas, &mut cache);
let generic4 = generic_constraint.evaluations(&env);
if cfg!(debug_assertions) {
let p4 = public_poly.evaluate_over_domain_by_ref(index.cs.domain.d4);
let gen_minus_pub = &generic4 + &p4;
check_constraint!(index, gen_minus_pub);
}
generic4
};
// permutation
let (mut t8, bnd) = {
let alphas =
all_alphas.get_alphas(ArgumentType::Permutation, permutation::CONSTRAINTS);
let (perm, bnd) = index.perm_quot(&lagrange, beta, gamma, &z_poly, alphas)?;
check_constraint!(index, perm);
(perm, bnd)
};
{
use crate::circuits::argument::DynArgument;
let range_check0_enabled =
index.column_evaluations.range_check0_selector8.is_some();
let range_check1_enabled =
index.column_evaluations.range_check1_selector8.is_some();
let foreign_field_addition_enabled = index
.column_evaluations
.foreign_field_add_selector8
.is_some();
let foreign_field_multiplication_enabled = index
.column_evaluations
.foreign_field_mul_selector8
.is_some();
let xor_enabled = index.column_evaluations.xor_selector8.is_some();
let rot_enabled = index.column_evaluations.rot_selector8.is_some();
for gate in [
(
(&CompleteAdd::default() as &dyn DynArgument<G::ScalarField>),
true,
),
(&VarbaseMul::default(), true),
(&EndosclMul::default(), true),
(&EndomulScalar::default(), true),
(&Poseidon::default(), true),
// Range check gates
(&RangeCheck0::default(), range_check0_enabled),
(&RangeCheck1::default(), range_check1_enabled),
// Foreign field addition gate
(&ForeignFieldAdd::default(), foreign_field_addition_enabled),
// Foreign field multiplication gate
(
&ForeignFieldMul::default(),
foreign_field_multiplication_enabled,
),
// Xor gate
(&Xor16::default(), xor_enabled),
// Rot gate
(&Rot64::default(), rot_enabled),
]
.into_iter()
.filter_map(|(gate, is_enabled)| if is_enabled { Some(gate) } else { None })
{
let constraint = gate.combined_constraints(&all_alphas, &mut cache);
let eval = constraint.evaluations(&env);
if eval.domain().size == t4.domain().size {
t4 += &eval;
} else if eval.domain().size == t8.domain().size {
t8 += &eval;
} else {
panic!("Bad evaluation")
}
check_constraint!(index, format!("{:?}", gate.argument_type()), eval);
}
};
// lookup
{
if let Some(lcs) = index.cs.lookup_constraint_system.as_ref() {
let constraints = lookup::constraints::constraints(&lcs.configuration, false);
let constraints_len = u32::try_from(constraints.len())
.expect("not expecting a large amount of constraints");
let lookup_alphas =
all_alphas.get_alphas(ArgumentType::Lookup, constraints_len);
// as lookup constraints are computed with the expression framework,
// each of them can result in Evaluations of different domains
for (ii, (constraint, alpha_pow)) in
constraints.into_iter().zip_eq(lookup_alphas).enumerate()
{
let mut eval = constraint.evaluations(&env);
eval.evals.par_iter_mut().for_each(|x| *x *= alpha_pow);
if eval.domain().size == t4.domain().size {
t4 += &eval;
} else if eval.domain().size == t8.domain().size {
t8 += &eval;
} else if eval.evals.iter().all(|x| x.is_zero()) {
// Skip any 0-valued evaluations
} else {
panic!("Bad evaluation")
}
check_constraint!(index, format!("lookup constraint #{ii}"), eval);
}
}
}
// public polynomial
let mut f = t4.interpolate() + t8.interpolate();
f += &public_poly;
// divide contributions with vanishing polynomial
let (mut quotient, res) = f
.divide_by_vanishing_poly(index.cs.domain.d1)
.ok_or(ProverError::Prover("division by vanishing polynomial"))?;
if !res.is_zero() {
return Err(ProverError::Prover(
"rest of division by vanishing polynomial",
));
}
quotient += &bnd; // already divided by Z_H
quotient
};
//~ 1. commit (hiding) to the quotient polynomial $t$
let t_comm = { index.srs.commit("ient_poly, 7 * num_chunks, rng) };
//~ 1. Absorb the commitment of the quotient polynomial with the Fq-Sponge.
absorb_commitment(&mut fq_sponge, &t_comm.commitment);
//~ 1. Sample $\zeta'$ with the Fq-Sponge.
let zeta_chal = ScalarChallenge(fq_sponge.challenge());
//~ 1. Derive $\zeta$ from $\zeta'$ using the endomorphism (TODO: specify)
let zeta = zeta_chal.to_field(endo_r);
let omega = index.cs.domain.d1.group_gen;
let zeta_omega = zeta * omega;
//~ 1. If lookup is used, evaluate the following polynomials at $\zeta$ and $\zeta \omega$:
if index.cs.lookup_constraint_system.is_some() {
//~~ * the aggregation polynomial
let aggreg = lookup_context
.aggreg_coeffs
.as_ref()
.unwrap()
.to_chunked_polynomial(num_chunks, index.max_poly_size);
//~~ * the sorted polynomials
let sorted = lookup_context
.sorted_coeffs
.as_ref()
.unwrap()
.iter()
.map(|c| c.to_chunked_polynomial(num_chunks, index.max_poly_size))
.collect::<Vec<_>>();
//~~ * the table polynonial
let joint_table = lookup_context.joint_lookup_table.as_ref().unwrap();
let joint_table = joint_table.to_chunked_polynomial(num_chunks, index.max_poly_size);
lookup_context.lookup_aggregation_eval = Some(PointEvaluations {
zeta: aggreg.evaluate_chunks(zeta),
zeta_omega: aggreg.evaluate_chunks(zeta_omega),
});
lookup_context.lookup_table_eval = Some(PointEvaluations {
zeta: joint_table.evaluate_chunks(zeta),
zeta_omega: joint_table.evaluate_chunks(zeta_omega),
});
lookup_context.lookup_sorted_eval = array::from_fn(|i| {
if i < sorted.len() {
let sorted = &sorted[i];
Some(PointEvaluations {
zeta: sorted.evaluate_chunks(zeta),
zeta_omega: sorted.evaluate_chunks(zeta_omega),
})
} else {
None
}
});
lookup_context.runtime_lookup_table_eval =
lookup_context.runtime_table.as_ref().map(|runtime_table| {
let runtime_table =
runtime_table.to_chunked_polynomial(num_chunks, index.max_poly_size);
PointEvaluations {
zeta: runtime_table.evaluate_chunks(zeta),
zeta_omega: runtime_table.evaluate_chunks(zeta_omega),
}
});
}
//~ 1. Chunk evaluate the following polynomials at both $\zeta$ and $\zeta \omega$:
//~~ * $s_i$
//~~ * $w_i$
//~~ * $z$
//~~ * lookup (TODO, see [this issue](https://github.com/MinaProtocol/mina/issues/13886))
//~~ * generic selector
//~~ * poseidon selector
//~
//~ By "chunk evaluate" we mean that the evaluation of each polynomial can potentially be a vector of values.
//~ This is because the index's `max_poly_size` parameter dictates the maximum size of a polynomial in the protocol.
//~ If a polynomial $f$ exceeds this size, it must be split into several polynomials like so:
//~ $$f(x) = f_0(x) + x^n f_1(x) + x^{2n} f_2(x) + \cdots$$
//~
//~ And the evaluation of such a polynomial is the following list for $x \in {\zeta, \zeta\omega}$:
//~
//~ $$(f_0(x), f_1(x), f_2(x), \ldots)$$
//~
//~ TODO: do we want to specify more on that? It seems unnecessary except for the t polynomial (or if for some reason someone sets that to a low value)
internal_tracing::checkpoint!(internal_traces; lagrange_basis_eval_zeta_poly);
let zeta_evals =
LagrangeBasisEvaluations::new(index.max_poly_size, index.cs.domain.d1, zeta);
internal_tracing::checkpoint!(internal_traces; lagrange_basis_eval_zeta_omega_poly);
let zeta_omega_evals =
LagrangeBasisEvaluations::new(index.max_poly_size, index.cs.domain.d1, zeta_omega);
let chunked_evals_for_selector =
|p: &Evaluations<G::ScalarField, D<G::ScalarField>>| PointEvaluations {
zeta: zeta_evals.evaluate_boolean(p),
zeta_omega: zeta_omega_evals.evaluate_boolean(p),
};
let chunked_evals_for_evaluations =
|p: &Evaluations<G::ScalarField, D<G::ScalarField>>| PointEvaluations {
zeta: zeta_evals.evaluate(p),
zeta_omega: zeta_omega_evals.evaluate(p),
};
internal_tracing::checkpoint!(internal_traces; chunk_eval_zeta_omega_poly);
let chunked_evals = ProofEvaluations::<PointEvaluations<Vec<G::ScalarField>>> {
public: {
let chunked = public_poly.to_chunked_polynomial(num_chunks, index.max_poly_size);
Some(PointEvaluations {
zeta: chunked.evaluate_chunks(zeta),
zeta_omega: chunked.evaluate_chunks(zeta_omega),
})
},
s: array::from_fn(|i| {
chunked_evals_for_evaluations(
&index.column_evaluations.permutation_coefficients8[i],
)
}),