forked from arkworks-rs/poly-commit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
2320 lines (1995 loc) · 85 KB
/
mod.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
use crate::{BTreeMap, String, ToString, Vec};
use crate::{Error, Evaluations, QuerySet};
use crate::{LabeledCommitment, LabeledPolynomial, LabeledRandomness};
use crate::{PCRandomness, PCUniversalParams, Polynomial, PolynomialCommitment};
use algebra::msm::VariableBaseMSM;
use algebra::{
to_bytes, AffineCurve, Field, Group, PrimeField, ProjectiveCurve, SemanticallyValid, ToBytes,
UniformRand,
};
use rand_core::RngCore;
use std::marker::PhantomData;
use std::{format, vec};
mod data_structures;
pub use data_structures::*;
use rayon::prelude::*;
use crate::rng::{FiatShamirChaChaRng, FiatShamirRng};
use digest::Digest;
/// The dlog commitment scheme from Bootle et al. based on the hardness of the discrete
/// logarithm problem in prime-order groups.
/// This implementation is according to the variant given in [[BCMS20]][pcdas], extended
/// to support polynomials of arbitrary degree via segmentation.
///
/// Degree bound enforcement requires that (at least one of) the points at
/// which a committed polynomial is evaluated are from a distribution that is
/// random conditioned on the polynomial. This is because degree bound
/// enforcement relies on checking a polynomial identity at this point.
/// More formally, the points must be sampled from an admissible query sampler,
/// as detailed in [[CHMMVW20]][marlin].
///
/// [pcdas]: https://eprint.iacr.org/2020/499
/// [marlin]: https://eprint.iacr.org/2019/1047
#[derive(Derivative)]
#[derivative(Clone(bound = ""))]
pub struct InnerProductArgPC<G: AffineCurve, D: Digest> {
_projective: PhantomData<G>,
_digest: PhantomData<D>,
}
impl<G: AffineCurve, D: Digest> InnerProductArgPC<G, D> {
/// `PROTOCOL_NAME` is used as a seed for the setup function.
const PROTOCOL_NAME: &'static [u8] = b"PC-DL-2021";
/// The low-level single segment single poly commit function.
/// Create a dlog commitment to `scalars` using the commitment key `comm_key`.
/// Optionally, randomize the commitment using `hiding_generator` and `randomizer`.
pub fn cm_commit(
comm_key: &[G],
scalars: &[G::ScalarField],
hiding_generator: Option<G>,
randomizer: Option<G::ScalarField>,
) -> Result<G::Projective, Error> {
let scalars_bigint = scalars
.par_iter()
.map(|s| s.into_repr())
.collect::<Vec<_>>();
let mut comm = VariableBaseMSM::multi_scalar_mul(&comm_key, &scalars_bigint)
.map_err(|e| Error::IncorrectInputLength(e.to_string()))?;
if randomizer.is_some() {
if hiding_generator.is_none() {
return Err(Error::Other("Hiding generator is missing".to_owned()))
}
comm += &hiding_generator.unwrap().mul(randomizer.unwrap());
}
Ok(comm)
}
#[inline]
fn inner_product(l: &[G::ScalarField], r: &[G::ScalarField]) -> G::ScalarField {
l.par_iter().zip(r).map(|(li, ri)| *li * ri).sum()
}
/// Complete semantic checks on `ck`.
#[inline]
pub fn check_key(ck: &CommitterKey<G>, max_degree: usize) -> bool {
let pp = <Self as PolynomialCommitment<G::ScalarField>>::setup(max_degree).unwrap();
ck.is_valid() && &pp.hash == &ck.hash
}
/// Computes an opening proof of multiple check polynomials with a corresponding
/// commitment GFin opened at point.
/// No segmentation here: Bullet Polys are at most as big as the committer key.
pub fn open_check_polys<'a>(
ck: &CommitterKey<G>,
xi_s: impl IntoIterator<Item = &'a SuccinctCheckPolynomial<G::ScalarField>>,
point: G::ScalarField,
// Assumption: the evaluation point and the (xi_s, g_fins) are already bound to the
// fs_rng state.
fs_rng: &mut FiatShamirChaChaRng<D>,
) -> Result<Proof<G>, Error> {
let mut key_len = ck.comm_key.len();
if ck.comm_key.len().next_power_of_two() != key_len {
return Err(Error::Other(
"Commiter key length is not power of 2".to_owned(),
))
}
let batch_time = start_timer!(|| "Compute and batch Bullet Polys and GFin commitments");
let xi_s_vec = xi_s.into_iter().collect::<Vec<_>>();
// Compute the evaluations of the Bullet polynomials at point starting from the xi_s
let values = xi_s_vec
.par_iter()
.map(|xi_s| xi_s.evaluate(point))
.collect::<Vec<_>>();
// Absorb evaluations
fs_rng.absorb(
&values
.iter()
.flat_map(|val| to_bytes!(val).unwrap())
.collect::<Vec<_>>(),
);
// Sample new batching challenge
let random_scalar: G::ScalarField = fs_rng.squeeze_128_bits_challenge();
// Collect the powers of the batching challenge in a vector
let mut batching_chal = G::ScalarField::one();
let mut batching_chals = vec![G::ScalarField::zero(); xi_s_vec.len()];
for i in 0..batching_chals.len() {
batching_chals[i] = batching_chal;
batching_chal *= &random_scalar;
}
// Compute combined check_poly
let mut combined_check_poly = batching_chals
.into_par_iter()
.zip(xi_s_vec)
.map(|(chal, xi_s)| Polynomial::from_coefficients_vec(xi_s.compute_scaled_coeffs(chal)))
.reduce(Polynomial::zero, |acc, poly| &acc + &poly);
// It's not necessary to use the full length of the ck if all the Bullet Polys are smaller:
// trim the ck if that's the case
key_len = combined_check_poly.coeffs.len();
if key_len.next_power_of_two() != key_len {
return Err(Error::Other(
"Combined check poly length is not a power of 2".to_owned(),
))
}
let mut comm_key = &ck.comm_key[..key_len];
end_timer!(batch_time);
let proof_time = start_timer!(|| format!(
"Generating proof for degree {} combined polynomial",
key_len
));
// ith challenge
let mut round_challenge: G::ScalarField = fs_rng.squeeze_128_bits_challenge();
let h_prime = ck.h.mul(round_challenge).into_affine();
let mut coeffs = combined_check_poly.coeffs.as_mut_slice();
// Powers of z
let mut z: Vec<G::ScalarField> = Vec::with_capacity(key_len);
let mut cur_z: G::ScalarField = G::ScalarField::one();
for _ in 0..key_len {
z.push(cur_z);
cur_z *= &point;
}
let mut z = z.as_mut_slice();
// This will be used for transforming the key in each step
let mut key_proj: Vec<G::Projective> =
comm_key.iter().map(|x| (*x).into_projective()).collect();
let mut key_proj = key_proj.as_mut_slice();
let mut temp;
let log_key_len = algebra::log2(key_len) as usize;
let mut l_vec = Vec::with_capacity(log_key_len);
let mut r_vec = Vec::with_capacity(log_key_len);
let mut n = key_len;
while n > 1 {
let (coeffs_l, coeffs_r) = coeffs.split_at_mut(n / 2);
let (z_l, z_r) = z.split_at_mut(n / 2);
let (key_l, key_r) = comm_key.split_at(n / 2);
let (key_proj_l, _) = key_proj.split_at_mut(n / 2);
let l = Self::cm_commit(key_l, coeffs_r, None, None)?
+ &h_prime.mul(Self::inner_product(coeffs_r, z_l));
let r = Self::cm_commit(key_r, coeffs_l, None, None)?
+ &h_prime.mul(Self::inner_product(coeffs_l, z_r));
let lr = G::Projective::batch_normalization_into_affine(vec![l, r]);
l_vec.push(lr[0]);
r_vec.push(lr[1]);
fs_rng.absorb(&to_bytes![lr[0], lr[1]].unwrap());
round_challenge = fs_rng.squeeze_128_bits_challenge();
// round_challenge is guaranteed to be non-zero by squeeze function
let round_challenge_inv = round_challenge.inverse().unwrap();
Self::polycommit_round_reduce(
round_challenge,
round_challenge_inv,
coeffs_l,
coeffs_r,
z_l,
z_r,
key_proj_l,
key_r,
);
coeffs = coeffs_l;
z = z_l;
key_proj = key_proj_l;
temp = G::Projective::batch_normalization_into_affine(key_proj.to_vec());
comm_key = &temp;
n /= 2;
}
end_timer!(proof_time);
Ok(Proof {
l_vec,
r_vec,
final_comm_key: comm_key[0],
c: coeffs[0],
hiding_comm: None,
rand: None,
})
}
/// The succinct portion of verifying a multi-poly single-point opening proof.
/// If successful, returns the (recomputed) reduction challenge.
pub fn succinct_check<'a>(
vk: &VerifierKey<G>,
commitments: impl IntoIterator<Item = &'a LabeledCommitment<Commitment<G>>>,
point: G::ScalarField,
values: impl IntoIterator<Item = G::ScalarField>,
proof: &Proof<G>,
// This implementation assumes that the commitments, point and evaluations are
// already bound to the internal state of the Fiat Shamir rng
fs_rng: &mut FiatShamirChaChaRng<D>,
) -> Result<Option<SuccinctCheckPolynomial<G::ScalarField>>, Error> {
let check_time = start_timer!(|| "Succinct checking");
// We do not assume that the vk length is equal to the segment size.
// Instead, we read the segment size from the proof L and Rs vectors (i.e. the number
// of steps of the dlog reduction). Doing so allows us to easily verify
// the dlog opening proofs produced by different size-restricted by means
// of a single vk.
let log_key_len = proof.l_vec.len();
let key_len = 1 << log_key_len;
if proof.l_vec.len() != proof.r_vec.len() {
return Err(Error::IncorrectInputLength(
format!(
"expected l_vec size and r_vec size to be equal; instead l_vec size is {:} and r_vec size is {:}",
proof.l_vec.len(),
proof.r_vec.len()
)
));
}
let mut combined_commitment_proj = <G::Projective as ProjectiveCurve>::zero();
let mut combined_v = G::ScalarField::zero();
let lambda: G::ScalarField = fs_rng.squeeze_128_bits_challenge();
let mut cur_challenge = G::ScalarField::one();
let labeled_commitments = commitments.into_iter();
let values = values.into_iter();
for (labeled_commitment, value) in labeled_commitments.zip(values) {
let label = labeled_commitment.label();
let commitment = labeled_commitment.commitment();
combined_v += &(cur_challenge * &value);
let segments_count = commitment.comm.len();
let mut comm_lc = <G::Projective as ProjectiveCurve>::zero();
for (i, comm_single) in commitment.comm.iter().enumerate() {
if i == 0 {
comm_lc = comm_single.into_projective();
} else {
let is = i * key_len;
comm_lc += &comm_single.mul(point.pow(&[is as u64]));
}
}
if cur_challenge == G::ScalarField::one() {
combined_commitment_proj = comm_lc;
} else {
combined_commitment_proj += &comm_lc.mul(&cur_challenge);
}
cur_challenge *= λ
let degree_bound = labeled_commitment.degree_bound();
// If the degree_bound is a multiple of the key_len then there is no need to prove the degree bound polynomial identity.
let degree_bound_len = degree_bound.and_then(|degree_bound_len| {
if (degree_bound_len + 1) % key_len != 0 {
Some(degree_bound_len + 1)
} else {
None
}
});
if degree_bound_len.is_some() != commitment.shifted_comm.is_some() {
return Err(Error::Other("Degree bound and shifted commitment must be both either present or not present".to_owned()))
}
if let Some(degree_bound_len) = degree_bound_len {
if Self::check_segments_and_bounds(
degree_bound.unwrap(),
segments_count,
key_len,
label.clone(),
)
.is_err()
{
return Ok(None);
}
let shifted_degree_bound = degree_bound_len % key_len - 1;
let shift = -point.pow(&[(key_len - shifted_degree_bound - 1) as u64]);
combined_commitment_proj += &commitment.shifted_comm.unwrap().mul(cur_challenge);
combined_commitment_proj +=
&commitment.comm[segments_count - 1].mul(cur_challenge * &shift);
cur_challenge *= λ
}
}
if proof.hiding_comm.is_some() != proof.rand.is_some() {
return Err(Error::Other(
"Hiding commitment and proof randomness must be both either present or not present"
.to_owned(),
))
}
if proof.hiding_comm.is_some() {
let hiding_comm = proof.hiding_comm.unwrap();
let rand = proof.rand.unwrap();
fs_rng.absorb(&to_bytes![hiding_comm].unwrap());
let hiding_challenge: G::ScalarField = fs_rng.squeeze_128_bits_challenge();
fs_rng.absorb(&(to_bytes![rand].unwrap()));
combined_commitment_proj += &(hiding_comm.mul(hiding_challenge) - &vk.s.mul(rand));
}
// Challenge for each round
let mut round_challenges = Vec::with_capacity(log_key_len);
let mut round_challenge: G::ScalarField = fs_rng.squeeze_128_bits_challenge();
let h_prime = vk.h.mul(round_challenge);
let mut round_commitment_proj = combined_commitment_proj + &h_prime.mul(&combined_v);
let l_iter = proof.l_vec.iter();
let r_iter = proof.r_vec.iter();
for (l, r) in l_iter.zip(r_iter) {
fs_rng.absorb(&to_bytes![l, r].unwrap());
round_challenge = fs_rng.squeeze_128_bits_challenge();
round_challenges.push(round_challenge);
// round_challenge is guaranteed to be non-zero by squeeze function
round_commitment_proj +=
&(l.mul(round_challenge.inverse().unwrap()) + &r.mul(round_challenge));
}
let check_poly = SuccinctCheckPolynomial::<G::ScalarField>(round_challenges);
let v_prime = check_poly.evaluate(point) * &proof.c;
let h_prime = h_prime.into_affine();
let check_commitment_elem: G::Projective = Self::cm_commit(
&[proof.final_comm_key, h_prime],
&[proof.c, v_prime],
None,
None,
)?;
if !ProjectiveCurve::is_zero(&(round_commitment_proj - &check_commitment_elem)) {
end_timer!(check_time);
return Ok(None);
}
end_timer!(check_time);
Ok(Some(check_poly))
}
/// Succinct check of a multi-point multi-poly opening proof from [[BDFG2020]](https://eprint.iacr.org/2020/081)
/// If successful, returns the (recomputed) succinct check polynomial (the xi_s)
/// and the GFinal.
pub fn succinct_batch_check_individual_opening_challenges<'a>(
vk: &VerifierKey<G>,
commitments: impl IntoIterator<Item = &'a LabeledCommitment<Commitment<G>>>,
query_set: &QuerySet<G::ScalarField>,
values: &Evaluations<G::ScalarField>,
batch_proof: &BatchProof<G>,
// This implementation assumes that the commitments, query set and evaluations are already absorbed by the Fiat Shamir rng
fs_rng: &mut FiatShamirChaChaRng<D>,
) -> Result<(SuccinctCheckPolynomial<G::ScalarField>, G), Error> {
let commitment_map: BTreeMap<_, _> = commitments
.into_iter()
.map(|commitment| (commitment.label(), commitment))
.collect();
let batch_check_time = start_timer!(|| "Multi poly multi point batch check: succinct part");
let evals_time = start_timer!(|| "Compute batched poly value");
// lambda
let lambda: G::ScalarField = fs_rng.squeeze_128_bits_challenge();
let mut cur_challenge = G::ScalarField::one();
// Fresh random challenge x
fs_rng.absorb(&to_bytes![batch_proof.h_comm].unwrap());
let x_point: G::ScalarField = fs_rng.squeeze_128_bits_challenge();
// LC(C): reconstructed commitment to LC(p_1(X),p_2(X),...,p_m(X),h(X))
let mut lc_comm = vec![];
// Expected value wich LC(p_1(X),p_2(X),...,p_m(X),h(X)) opens to
let mut lc_value = G::ScalarField::zero();
for (label, (_point_label, point)) in query_set.iter() {
// Assert x_point != x_1, ..., x_m
if point == &x_point {
end_timer!(evals_time);
end_timer!(batch_check_time);
return Err(Error::Other(
"Squeezed a challenge equal to one of the evaluation points".to_owned(),
));
}
let labeled_commitment =
*commitment_map.get(label).ok_or(Error::MissingCommitment {
label: label.to_string(),
})?;
// y_i
let y_i = *values
.get(&(label.clone(), *point))
.ok_or(Error::MissingEvaluation {
label: label.to_string(),
})?;
// (X - x_i)
let x_polynomial =
Polynomial::from_coefficients_slice(&[-(*point), G::ScalarField::one()]);
// z_i(x)/z(x) = 1 / (x - x_i).
// unwrap cannot fail as x-x_i is guaranteed to be non-zero.
let z_i_over_z_value = x_polynomial.evaluate(x_point).inverse().unwrap();
// LC(C) = SUM ( lambda^i * z_i(x)/z(x) * C_i )
for (index, &comm_dash_segment) in
labeled_commitment.commitment().comm.iter().enumerate()
{
if index == lc_comm.len() {
lc_comm.push(<G::Projective as ProjectiveCurve>::zero());
}
lc_comm[index] += &comm_dash_segment.mul(z_i_over_z_value * &cur_challenge);
}
lc_value += y_i * cur_challenge * z_i_over_z_value;
// lambda^i
cur_challenge *= λ
}
// LC(C) = SUM ( lambda^i * z_i(x)/z(x) * C_i ) - C
let lc_comm_affine = lc_comm
.into_iter()
.enumerate()
.map(|(index, mut lc_comm_segment)| {
let h_comm_segment = if batch_proof.h_comm.len() > index {
batch_proof.h_comm[index]
} else {
G::zero()
};
lc_comm_segment.add_assign_mixed(&-h_comm_segment);
lc_comm_segment.into_affine()
})
.collect::<Vec<_>>();
// Expected open value added to the check
let batch_values = vec![lc_value];
// The reconstructed commitment to the LC polynomial put to the check
let labeled_batch_commitment = LabeledCommitment::new(
"LC".to_string(),
Commitment {
comm: lc_comm_affine,
shifted_comm: None,
},
None,
);
let batch_commitments = vec![&labeled_batch_commitment]; // commitments;
let proof = &batch_proof.proof;
end_timer!(evals_time);
let check_time = start_timer!(|| "Succinct check batched polynomial");
let check_poly =
Self::succinct_check(vk, batch_commitments, x_point, batch_values, proof, fs_rng)?;
if check_poly.is_none() {
end_timer!(check_time);
end_timer!(batch_check_time);
return Err(Error::FailedSuccinctCheck);
}
end_timer!(check_time);
end_timer!(batch_check_time);
Ok((check_poly.unwrap(), proof.final_comm_key))
}
/// Succinct verify (a batch of) multi-point mulit-poly opening proofs and, if valid,
/// return their SuccinctCheckPolynomials (the reduction challenges `xi`) and the
/// final committer keys `GFinal`.
pub fn succinct_batch_check<'a>(
vk: &VerifierKey<G>,
commitments: impl IntoIterator<Item = &'a [LabeledCommitment<Commitment<G>>]>,
query_sets: impl IntoIterator<Item = &'a QuerySet<'a, G::ScalarField>>,
values: impl IntoIterator<Item = &'a Evaluations<'a, G::ScalarField>>,
proofs: impl IntoIterator<Item = &'a BatchProof<G>>,
states: impl IntoIterator<Item = &'a <FiatShamirChaChaRng<D> as FiatShamirRng>::State>,
) -> Result<(Vec<SuccinctCheckPolynomial<G::ScalarField>>, Vec<G>), Error>
where
D::OutputSize: 'a,
{
let comms = commitments.into_iter().collect::<Vec<_>>();
let query_sets = query_sets.into_iter().collect::<Vec<_>>();
let values = values.into_iter().collect::<Vec<_>>();
let proofs = proofs.into_iter().collect::<Vec<_>>();
let states = states.into_iter().collect::<Vec<_>>();
// Perform succinct verification of all the proofs and collect
// the xi_s and the GFinal_s into DLogAccumulators
let succinct_time = start_timer!(|| "Succinct verification of proofs");
let (accumulators, failed_checks): (Vec<Result<_, Error>>, Vec<Result<_, Error>>) = comms
.into_par_iter()
.zip(query_sets)
.zip(values)
.zip(proofs)
.zip(states)
.map(|((((commitments, query_set), values), proof), state)| {
let mut fs_rng = FiatShamirChaChaRng::<D>::default();
fs_rng.set_state(state.clone());
// Perform succinct check of i-th proof
let (challenges, final_comm_key) =
Self::succinct_batch_check_individual_opening_challenges(
vk,
commitments,
query_set,
values,
proof,
&mut fs_rng,
)?;
Ok((final_comm_key, challenges))
})
.partition(Result::is_ok);
end_timer!(succinct_time);
if !failed_checks.is_empty() {
return Err(Error::FailedSuccinctCheck)
}
let accumulators = accumulators
.into_iter()
.map(Result::unwrap)
.collect::<Vec<_>>();
let g_finals = accumulators
.iter()
.map(|(g_final, _)| *g_final)
.collect::<Vec<_>>();
let challenges = accumulators
.into_iter()
.map(|(_, xi_s)| xi_s)
.collect::<Vec<_>>();
Ok((challenges, g_finals))
}
/// Checks whether degree bounds are `situated' in the last segment of a polynomial
/// TODO: Rename to check_bounds, or alternatively write a function that receives the
/// supposed degree, and which checks in addition whether the segment count is plausible.
fn check_degrees_and_bounds(
supported_degree: usize,
p: &LabeledPolynomial<G::ScalarField>,
) -> Result<(), Error> {
// We use segmentation, therefore we allow arbitrary degree polynomials: hence, the only
// check that makes sense, is the bound being bigger than the degree of the polynomial.
if let Some(bound) = p.degree_bound() {
let p_len = p.polynomial().coeffs.len();
let segment_len = supported_degree + 1;
let segments_count = std::cmp::max(
1,
p_len / segment_len + if p_len % segment_len != 0 { 1 } else { 0 },
);
if bound < p.degree() {
return Err(Error::IncorrectDegreeBound {
poly_degree: p.degree(),
degree_bound: bound,
supported_degree,
label: p.label().to_string(),
});
}
return Self::check_segments_and_bounds(
bound,
segments_count,
segment_len,
p.label().to_string(),
);
}
Ok(())
}
/// Checks if the degree bound is situated in the last segment.
fn check_segments_and_bounds(
bound: usize,
segments_count: usize,
segment_len: usize,
label: String,
) -> Result<(), Error> {
if (bound + 1) <= (segments_count - 1) * segment_len
|| (bound + 1) > segments_count * segment_len
{
return Err(Error::IncorrectSegmentedDegreeBound {
degree_bound: bound,
segments_count,
segment_len,
label,
});
}
Ok(())
}
/// Computes the 'shifted' polynomial as needed for degree bound proofs.
fn shift_polynomial(
ck: &CommitterKey<G>,
p: &Polynomial<G::ScalarField>,
degree_bound: usize,
) -> Polynomial<G::ScalarField> {
if p.is_zero() {
Polynomial::zero()
} else {
let mut shifted_polynomial_coeffs =
vec![G::ScalarField::zero(); ck.comm_key.len() - 1 - degree_bound];
shifted_polynomial_coeffs.extend_from_slice(&p.coeffs);
Polynomial::from_coefficients_vec(shifted_polynomial_coeffs)
}
}
/// Computing the base point vector of the commmitment scheme in a
/// deterministic manner, given the PROTOCOL_NAME.
fn sample_generators(num_generators: usize, seed: &[u8]) -> Vec<G> {
let generators: Vec<_> = (0..num_generators)
.into_par_iter()
.map(|i| {
let i = i as u64;
let mut hash = D::digest(&to_bytes![seed, i].unwrap());
let mut g = G::from_random_bytes(&hash);
let mut j = 0u64;
while g.is_none() {
hash = D::digest(&to_bytes![seed, i, j].unwrap());
g = G::from_random_bytes(&hash);
j += 1;
}
let generator = g.unwrap();
generator.mul_by_cofactor().into_projective()
})
.collect();
G::Projective::batch_normalization_into_affine(generators)
}
/// Perform a dlog reduction step as described in BCMS20
fn polycommit_round_reduce(
round_challenge: G::ScalarField,
round_challenge_inv: G::ScalarField,
c_l: &mut [G::ScalarField],
c_r: &[G::ScalarField],
z_l: &mut [G::ScalarField],
z_r: &[G::ScalarField],
k_l: &mut [G::Projective],
k_r: &[G],
) {
c_l.par_iter_mut()
.zip(c_r)
.for_each(|(c_l, c_r)| *c_l += &(round_challenge_inv * c_r));
z_l.par_iter_mut()
.zip(z_r)
.for_each(|(z_l, z_r)| *z_l += &(round_challenge * z_r));
k_l.par_iter_mut()
.zip(k_r)
.for_each(|(k_l, k_r)| *k_l += &(k_r.mul(round_challenge)));
}
}
/// Implementation of the PolynomialCommitment trait for the segmentized dlog commitment scheme
impl<G: AffineCurve, D: Digest> PolynomialCommitment<G::ScalarField> for InnerProductArgPC<G, D> {
type UniversalParams = UniversalParams<G>;
type CommitterKey = CommitterKey<G>;
type VerifierKey = VerifierKey<G>;
type PreparedVerifierKey = PreparedVerifierKey<G>;
type Commitment = Commitment<G>;
type PreparedCommitment = PreparedCommitment<G>;
type Randomness = Randomness<G>;
type Proof = Proof<G>;
type BatchProof = BatchProof<G>;
type Error = Error;
type RandomOracle = FiatShamirChaChaRng<D>;
/// Setup of the base point vector (deterministically derived from the
/// PROTOCOL_NAME as seed).
fn setup(max_degree: usize) -> Result<Self::UniversalParams, Self::Error> {
Self::setup_from_seed(max_degree, &Self::PROTOCOL_NAME)
}
/// Setup of the base point vector (deterministically derived from the
/// given byte array as seed).
fn setup_from_seed(
max_degree: usize,
seed: &[u8],
) -> Result<Self::UniversalParams, Self::Error> {
// Ensure that max_degree + 1 is a power of 2
let max_degree = (max_degree + 1).next_power_of_two() - 1;
let setup_time = start_timer!(|| format!("Sampling {} generators", max_degree + 3));
let generators = Self::sample_generators(max_degree + 3, seed);
end_timer!(setup_time);
let hash = D::digest(&to_bytes![&generators, max_degree as u32].unwrap()).to_vec();
let h = generators[0];
let s = generators[1];
let comm_key = generators[2..].to_vec();
let pp = UniversalParams {
comm_key,
h,
s,
hash,
};
Ok(pp)
}
/// Trims the base point vector of the setup function to a custom segment size
fn trim(
pp: &Self::UniversalParams,
// the segment size (TODO: let's rename it!)
supported_degree: usize,
) -> Result<(Self::CommitterKey, Self::VerifierKey), Self::Error> {
// Ensure that supported_degree + 1 is a power of two
let supported_degree = (supported_degree + 1).next_power_of_two() - 1;
if supported_degree > pp.max_degree() {
return Err(Error::TrimmingDegreeTooLarge);
}
let trim_time =
start_timer!(|| format!("Trimming to supported degree of {}", supported_degree));
let ck = CommitterKey {
comm_key: pp.comm_key[0..(supported_degree + 1)].to_vec(),
h: pp.h,
s: pp.s,
max_degree: pp.max_degree(),
hash: pp.hash.clone(),
};
let vk = VerifierKey {
comm_key: pp.comm_key[0..(supported_degree + 1)].to_vec(),
h: pp.h,
s: pp.s,
max_degree: pp.max_degree(),
hash: pp.hash.clone(),
};
end_timer!(trim_time);
Ok((ck, vk))
}
/// Domain extended commit function, outputs a `segmented commitment'
/// to a polynomial, regardless of its degree.
fn commit<'a>(
ck: &Self::CommitterKey,
polynomials: impl IntoIterator<Item = &'a LabeledPolynomial<G::ScalarField>>,
rng: Option<&mut dyn RngCore>,
) -> Result<
(
Vec<LabeledCommitment<Self::Commitment>>,
Vec<LabeledRandomness<Self::Randomness>>,
),
Self::Error,
> {
let rng = &mut crate::optional_rng::OptionalRng(rng);
let mut comms = Vec::new();
let mut rands = Vec::new();
let commit_time = start_timer!(|| "Committing to polynomials");
for labeled_polynomial in polynomials {
Self::check_degrees_and_bounds(ck.comm_key.len() - 1, labeled_polynomial)?;
let polynomial = labeled_polynomial.polynomial();
let label = labeled_polynomial.label();
let hiding_bound = labeled_polynomial.hiding_bound();
let degree_bound = labeled_polynomial.degree_bound();
let single_commit_time = start_timer!(|| format!(
"Polynomial {} of degree {}, degree bound {:?}, and hiding bound {:?}",
label,
polynomial.degree(),
degree_bound,
hiding_bound,
));
let key_len = ck.comm_key.len();
let p_len = polynomial.coeffs.len();
let segments_count = std::cmp::max(
1,
p_len / key_len + if p_len % key_len != 0 { 1 } else { 0 },
);
let randomness = if hiding_bound.is_some() {
Randomness::rand(segments_count, degree_bound.is_some(), rng)
} else {
Randomness::empty(segments_count)
};
let comm: Vec<G>;
// split poly in segments and commit all of them without shifting
comm = (0..segments_count)
.into_iter()
.map(|i| {
Ok(Self::cm_commit(
&ck.comm_key,
&polynomial.coeffs[i * key_len..core::cmp::min((i + 1) * key_len, p_len)],
Some(ck.s),
Some(randomness.rand[i]),
)?
.into_affine())
})
.collect::<Result<Vec<_>, _>>()?;
// committing only last segment shifted to the right edge
let shifted_comm = if degree_bound.is_some() {
let degree_bound = degree_bound.unwrap();
let degree_bound_len = degree_bound + 1; // Convert to the maximum number of coefficients
if degree_bound_len % key_len != 0 {
let comm = Self::cm_commit(
&ck.comm_key[key_len - (degree_bound_len % key_len)..],
&polynomial.coeffs[(segments_count - 1) * key_len..p_len],
Some(ck.s),
randomness.shifted_rand,
)?
.into_affine();
Some(comm)
} else {
None
}
} else {
None
};
let commitment = Commitment { comm, shifted_comm };
let labeled_comm = LabeledCommitment::new(label.to_string(), commitment, degree_bound);
let labeled_rand = LabeledRandomness::new(label.to_string(), randomness);
comms.push(labeled_comm);
rands.push(labeled_rand);
end_timer!(single_commit_time);
}
end_timer!(commit_time);
Ok((comms, rands))
}
/// Single point multi poly open, allowing the random oracle to be passed from
/// 'outside' to the function.
/// CAUTION: This is a low-level function which assumes that the statement of the
/// opening proof (i.e. commitments, query point, and evaluations) is already bound
/// to the internal state of the Fiat-Shamir rng.
fn open_individual_opening_challenges<'a>(
ck: &Self::CommitterKey,
labeled_polynomials: impl IntoIterator<Item = &'a LabeledPolynomial<G::ScalarField>>,
commitments: impl IntoIterator<Item = &'a LabeledCommitment<Self::Commitment>>,
point: G::ScalarField,
// This implementation assumes that commitments, query point and evaluations are already absorbed by the Fiat Shamir rng
fs_rng: &mut Self::RandomOracle,
rands: impl IntoIterator<Item = &'a LabeledRandomness<Self::Randomness>>,
rng: Option<&mut dyn RngCore>,
) -> Result<Self::Proof, Self::Error>
where
Self::Commitment: 'a,
Self::Randomness: 'a,
{
let key_len = ck.comm_key.len();
let log_key_len = algebra::log2(key_len) as usize;
if key_len.next_power_of_two() != key_len {
return Err(Error::Other(
"Commiter key length is not power of 2".to_owned(),
))
}
let mut combined_polynomial = Polynomial::zero();
let mut combined_rand = G::ScalarField::zero();
let mut combined_commitment_proj = <G::Projective as ProjectiveCurve>::zero();
let mut has_hiding = false;
let polys_iter = labeled_polynomials.into_iter();
let rands_iter = rands.into_iter();
let comms_iter = commitments.into_iter();
let combine_time = start_timer!(|| "Combining polynomials, randomness, and commitments.");
// as the statement of the opening proof is already bound to the interal state of the fr_rng,
// we simply squeeze the challenge scalar for the random linear combination
let lambda: G::ScalarField = fs_rng.squeeze_128_bits_challenge();
let mut cur_challenge = G::ScalarField::one();
// compute the random linear combination using the powers of lambda
for (labeled_polynomial, (labeled_commitment, labeled_randomness)) in
polys_iter.zip(comms_iter.zip(rands_iter))
{
let label = labeled_polynomial.label();
if labeled_polynomial.label() != labeled_commitment.label() {
return Err(Error::Other(
format!(
"Labels are not equal: poly '{}'. commitment '{}'",
labeled_polynomial.label(),
labeled_commitment.label()
)
.to_owned(),
))
}
Self::check_degrees_and_bounds(ck.comm_key.len() - 1, labeled_polynomial)?;
let polynomial = labeled_polynomial.polynomial();
let degree_bound = labeled_polynomial.degree_bound();
let hiding_bound = labeled_polynomial.hiding_bound();
let commitment = labeled_commitment.commitment();
let randomness = labeled_randomness.randomness();
let p_len = polynomial.coeffs.len();
let segments_count = std::cmp::max(
1,
p_len / key_len + if p_len % key_len != 0 { 1 } else { 0 },
);
// If the degree_bound is a multiple of the key_len then there is no need to prove the degree bound polynomial identity.
let degree_bound_len = degree_bound.and_then(|degree_bound| {
if (degree_bound + 1) % key_len != 0 {
Some(degree_bound + 1)
} else {
None
}
});
if degree_bound_len.is_some() != commitment.shifted_comm.is_some() {
return Err(Error::Other(
format!("shifted_comm mismatch for {}", label).to_owned(),
))
}
if degree_bound != labeled_commitment.degree_bound() {
return Err(Error::Other(
format!("labeled_comm degree bound mismatch for {}", label).to_owned(),
))
}
if hiding_bound.is_some() {
has_hiding = true;