-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathprio3.rs
1702 lines (1518 loc) · 61.2 KB
/
prio3.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
// SPDX-License-Identifier: MPL-2.0
//! Implementation of the Prio3 VDAF [[draft-irtf-cfrg-vdaf-05]].
//!
//! **WARNING:** This code has not undergone significant security analysis. Use at your own risk.
//!
//! Prio3 is based on the Prio system desigend by Dan Boneh and Henry Corrigan-Gibbs and presented
//! at NSDI 2017 [[CGB17]]. However, it incorporates a few techniques from Boneh et al., CRYPTO
//! 2019 [[BBCG+19]], that lead to substantial improvements in terms of run time and communication
//! cost. The security of the construction was analyzed in [[DPRS23]].
//!
//! Prio3 is a transformation of a Fully Linear Proof (FLP) system [[draft-irtf-cfrg-vdaf-05]] into
//! a VDAF. The base type, [`Prio3`], supports a wide variety of aggregation functions, some of
//! which are instantiated here:
//!
//! - [`Prio3Count`] for aggregating a counter (*)
//! - [`Prio3Sum`] for copmputing the sum of integers (*)
//! - [`Prio3SumVec`] for aggregating a vector of integers
//! - [`Prio3Histogram`] for estimating a distribution via a histogram (*)
//!
//! Additional types can be constructed from [`Prio3`] as needed.
//!
//! (*) denotes that the type is specified in [[draft-irtf-cfrg-vdaf-05]].
//!
//! [BBCG+19]: https://ia.cr/2019/188
//! [CGB17]: https://crypto.stanford.edu/prio/
//! [DPRS23]: https://ia.cr/2023/130
//! [draft-irtf-cfrg-vdaf-05]: https://datatracker.ietf.org/doc/draft-irtf-cfrg-vdaf/05/
use super::prg::PrgSha3;
use crate::codec::{CodecError, Decode, Encode, ParameterizedDecode};
use crate::field::{decode_fieldvec, FftFriendlyFieldElement, FieldElement};
use crate::field::{Field128, Field64};
#[cfg(feature = "multithreaded")]
use crate::flp::gadgets::ParallelSumMultithreaded;
#[cfg(feature = "experimental")]
use crate::flp::gadgets::PolyEval;
use crate::flp::gadgets::{BlindPolyEval, ParallelSum};
#[cfg(feature = "experimental")]
use crate::flp::types::fixedpoint_l2::{
compatible_float::CompatibleFloat, FixedPointBoundedL2VecSum,
};
use crate::flp::types::{Average, Count, Histogram, Sum, SumVec};
use crate::flp::Type;
use crate::prng::Prng;
use crate::vdaf::prg::{Prg, Seed};
use crate::vdaf::{
Aggregatable, AggregateShare, Aggregator, Client, Collector, OutputShare, PrepareTransition,
Share, ShareDecodingParameter, Vdaf, VdafError,
};
#[cfg(feature = "experimental")]
use fixed::traits::Fixed;
use std::convert::TryFrom;
use std::fmt::Debug;
use std::io::Cursor;
use std::iter::{self, IntoIterator};
use std::marker::PhantomData;
const DST_MEASUREMENT_SHARE: u16 = 1;
const DST_PROOF_SHARE: u16 = 2;
const DST_JOINT_RANDOMNESS: u16 = 3;
const DST_PROVE_RANDOMNESS: u16 = 4;
const DST_QUERY_RANDOMNESS: u16 = 5;
const DST_JOINT_RAND_SEED: u16 = 6;
const DST_JOINT_RAND_PART: u16 = 7;
/// The count type. Each measurement is an integer in `[0,2)` and the aggregate result is the sum.
pub type Prio3Count = Prio3<Count<Field64>, PrgSha3, 16>;
impl Prio3Count {
/// Construct an instance of Prio3Count with the given number of aggregators.
pub fn new_count(num_aggregators: u8) -> Result<Self, VdafError> {
Prio3::new(num_aggregators, Count::new())
}
}
/// The count-vector type. Each measurement is a vector of integers in `[0,2^bits)` and the
/// aggregate is the element-wise sum.
pub type Prio3SumVec =
Prio3<SumVec<Field128, ParallelSum<Field128, BlindPolyEval<Field128>>>, PrgSha3, 16>;
impl Prio3SumVec {
/// Construct an instance of Prio3SumVec with the given number of aggregators. `bits` defines
/// the bit width of each summand of the measurement; `len` defines the length of the
/// measurement vector.
pub fn new_sum_vec(num_aggregators: u8, bits: usize, len: usize) -> Result<Self, VdafError> {
Prio3::new(num_aggregators, SumVec::new(bits, len)?)
}
}
/// Like [`Prio3SumVec`] except this type uses multithreading to improve sharding and preparation
/// time. Note that the improvement is only noticeable for very large input lengths, e.g., 201 and
/// up. (Your system's mileage may vary.)
#[cfg(feature = "multithreaded")]
#[cfg_attr(docsrs, doc(cfg(feature = "multithreaded")))]
pub type Prio3SumVecMultithreaded = Prio3<
SumVec<Field128, ParallelSumMultithreaded<Field128, BlindPolyEval<Field128>>>,
PrgSha3,
16,
>;
#[cfg(feature = "multithreaded")]
impl Prio3SumVecMultithreaded {
/// Construct an instance of Prio3SumVecMultithreaded with the given number of
/// aggregators. `bits` defines the bit width of each summand of the measurement; `len` defines
/// the length of the measurement vector.
pub fn new_sum_vec_multithreaded(
num_aggregators: u8,
bits: usize,
len: usize,
) -> Result<Self, VdafError> {
Prio3::new(num_aggregators, SumVec::new(bits, len)?)
}
}
/// The sum type. Each measurement is an integer in `[0,2^bits)` for some `0 < bits < 64` and the
/// aggregate is the sum.
pub type Prio3Sum = Prio3<Sum<Field128>, PrgSha3, 16>;
impl Prio3Sum {
/// Construct an instance of Prio3Sum with the given number of aggregators and required bit
/// length. The bit length must not exceed 64.
pub fn new_sum(num_aggregators: u8, bits: usize) -> Result<Self, VdafError> {
if bits > 64 {
return Err(VdafError::Uncategorized(format!(
"bit length ({bits}) exceeds limit for aggregate type (64)"
)));
}
Prio3::new(num_aggregators, Sum::new(bits)?)
}
}
/// The fixed point vector sum type. Each measurement is a vector of fixed point numbers
/// and the aggregate is the sum represented as 64-bit floats. The preparation phase
/// ensures the L2 norm of the input vector is < 1.
///
/// This is useful for aggregating gradients in a federated version of
/// [gradient descent](https://en.wikipedia.org/wiki/Gradient_descent) with
/// [differential privacy](https://en.wikipedia.org/wiki/Differential_privacy),
/// useful, e.g., for [differentially private deep learning](https://arxiv.org/pdf/1607.00133.pdf).
/// The bound on input norms is required for differential privacy. The fixed point representation
/// allows an easy conversion to the integer type used in internal computation, while leaving
/// conversion to the client. The model itself will have floating point parameters, so the output
/// sum has that type as well.
#[cfg(feature = "experimental")]
#[cfg_attr(docsrs, doc(cfg(feature = "experimental")))]
pub type Prio3FixedPointBoundedL2VecSum<Fx> = Prio3<
FixedPointBoundedL2VecSum<
Fx,
Field128,
ParallelSum<Field128, PolyEval<Field128>>,
ParallelSum<Field128, BlindPolyEval<Field128>>,
>,
PrgSha3,
16,
>;
#[cfg(feature = "experimental")]
impl<Fx: Fixed + CompatibleFloat<Field128>> Prio3FixedPointBoundedL2VecSum<Fx> {
/// Construct an instance of this VDAF with the given number of aggregators and number of
/// vector entries.
pub fn new_fixedpoint_boundedl2_vec_sum(
num_aggregators: u8,
entries: usize,
) -> Result<Self, VdafError> {
check_num_aggregators(num_aggregators)?;
Prio3::new(num_aggregators, FixedPointBoundedL2VecSum::new(entries)?)
}
}
/// The fixed point vector sum type. Each measurement is a vector of fixed point numbers
/// and the aggregate is the sum represented as 64-bit floats. The verification function
/// ensures the L2 norm of the input vector is < 1.
#[cfg(all(feature = "experimental", feature = "multithreaded"))]
#[cfg_attr(
docsrs,
doc(cfg(all(feature = "experimental", feature = "multithreaded")))
)]
pub type Prio3FixedPointBoundedL2VecSumMultithreaded<Fx> = Prio3<
FixedPointBoundedL2VecSum<
Fx,
Field128,
ParallelSumMultithreaded<Field128, PolyEval<Field128>>,
ParallelSumMultithreaded<Field128, BlindPolyEval<Field128>>,
>,
PrgSha3,
16,
>;
#[cfg(all(feature = "experimental", feature = "multithreaded"))]
impl<Fx: Fixed + CompatibleFloat<Field128>> Prio3FixedPointBoundedL2VecSumMultithreaded<Fx> {
/// Construct an instance of this VDAF with the given number of aggregators and number of
/// vector entries.
pub fn new_fixedpoint_boundedl2_vec_sum_multithreaded(
num_aggregators: u8,
entries: usize,
) -> Result<Self, VdafError> {
check_num_aggregators(num_aggregators)?;
Prio3::new(num_aggregators, FixedPointBoundedL2VecSum::new(entries)?)
}
}
/// The histogram type. Each measurement is an unsigned integer and the result is a histogram
/// representation of the distribution. The bucket boundaries are fixed in advance.
pub type Prio3Histogram = Prio3<Histogram<Field128>, PrgSha3, 16>;
impl Prio3Histogram {
/// Constructs an instance of Prio3Histogram with the given number of aggregators and
/// desired histogram bucket boundaries.
pub fn new_histogram(num_aggregators: u8, buckets: &[u64]) -> Result<Self, VdafError> {
let buckets = buckets.iter().map(|bucket| *bucket as u128).collect();
Prio3::new(num_aggregators, Histogram::new(buckets)?)
}
}
/// The average type. Each measurement is an integer in `[0,2^bits)` for some `0 < bits < 64` and
/// the aggregate is the arithmetic average.
pub type Prio3Average = Prio3<Average<Field128>, PrgSha3, 16>;
impl Prio3Average {
/// Construct an instance of Prio3Average with the given number of aggregators and required bit
/// length. The bit length must not exceed 64.
pub fn new_average(num_aggregators: u8, bits: usize) -> Result<Self, VdafError> {
check_num_aggregators(num_aggregators)?;
if bits > 64 {
return Err(VdafError::Uncategorized(format!(
"bit length ({bits}) exceeds limit for aggregate type (64)"
)));
}
Ok(Prio3 {
num_aggregators,
typ: Average::new(bits)?,
phantom: PhantomData,
})
}
}
/// The base type for Prio3.
///
/// An instance of Prio3 is determined by:
///
/// - a [`Type`] that defines the set of valid input measurements; and
/// - a [`Prg`] for deriving vectors of field elements from seeds.
///
/// New instances can be defined by aliasing the base type. For example, [`Prio3Count`] is an alias
/// for `Prio3<Count<Field64>, PrgSha3, 16>`.
///
/// ```
/// use prio::vdaf::{
/// Aggregator, Client, Collector, PrepareTransition,
/// prio3::Prio3,
/// };
/// use rand::prelude::*;
///
/// let num_shares = 2;
/// let vdaf = Prio3::new_count(num_shares).unwrap();
///
/// let mut out_shares = vec![vec![]; num_shares.into()];
/// let mut rng = thread_rng();
/// let verify_key = rng.gen();
/// let measurements = [0, 1, 1, 1, 0];
/// for measurement in measurements {
/// // Shard
/// let nonce = rng.gen::<[u8; 16]>();
/// let (public_share, input_shares) = vdaf.shard(&measurement, &nonce).unwrap();
///
/// // Prepare
/// let mut prep_states = vec![];
/// let mut prep_shares = vec![];
/// for (agg_id, input_share) in input_shares.iter().enumerate() {
/// let (state, share) = vdaf.prepare_init(
/// &verify_key,
/// agg_id,
/// &(),
/// &nonce,
/// &public_share,
/// input_share
/// ).unwrap();
/// prep_states.push(state);
/// prep_shares.push(share);
/// }
/// let prep_msg = vdaf.prepare_preprocess(prep_shares).unwrap();
///
/// for (agg_id, state) in prep_states.into_iter().enumerate() {
/// let out_share = match vdaf.prepare_step(state, prep_msg.clone()).unwrap() {
/// PrepareTransition::Finish(out_share) => out_share,
/// _ => panic!("unexpected transition"),
/// };
/// out_shares[agg_id].push(out_share);
/// }
/// }
///
/// // Aggregate
/// let agg_shares = out_shares.into_iter()
/// .map(|o| vdaf.aggregate(&(), o).unwrap());
///
/// // Unshard
/// let agg_res = vdaf.unshard(&(), agg_shares, measurements.len()).unwrap();
/// assert_eq!(agg_res, 3);
/// ```
#[derive(Clone, Debug)]
pub struct Prio3<T, P, const SEED_SIZE: usize>
where
T: Type,
P: Prg<SEED_SIZE>,
{
num_aggregators: u8,
typ: T,
phantom: PhantomData<P>,
}
impl<T, P, const SEED_SIZE: usize> Prio3<T, P, SEED_SIZE>
where
T: Type,
P: Prg<SEED_SIZE>,
{
/// Construct an instance of this Prio3 VDAF with the given number of aggregators and the
/// underlying type.
pub fn new(num_aggregators: u8, typ: T) -> Result<Self, VdafError> {
check_num_aggregators(num_aggregators)?;
Ok(Self {
num_aggregators,
typ,
phantom: PhantomData,
})
}
/// The output length of the underlying FLP.
pub fn output_len(&self) -> usize {
self.typ.output_len()
}
/// The verifier length of the underlying FLP.
pub fn verifier_len(&self) -> usize {
self.typ.verifier_len()
}
fn derive_joint_rand_seed<'a>(
parts: impl Iterator<Item = &'a Seed<SEED_SIZE>>,
) -> Seed<SEED_SIZE> {
let mut prg = P::init(&[0; SEED_SIZE], &Self::custom(DST_JOINT_RAND_SEED));
for part in parts {
prg.update(part.as_ref());
}
prg.into_seed()
}
fn random_size(&self) -> usize {
if self.typ.joint_rand_len() == 0 {
// Two seeds per helper for measurement and proof shares, plus one seed for proving
// randomness.
(usize::from(self.num_aggregators - 1) * 2 + 1) * SEED_SIZE
} else {
(
// Two seeds per helper for measurement and proof shares
usize::from(self.num_aggregators - 1) * 2
// One seed for proving randomness
+ 1
// One seed per aggregator for joint randomness blinds
+ usize::from(self.num_aggregators)
) * SEED_SIZE
}
}
#[allow(clippy::type_complexity)]
fn shard_with_random<const N: usize>(
&self,
measurement: &T::Measurement,
nonce: &[u8; N],
random: &[u8],
) -> Result<
(
Prio3PublicShare<SEED_SIZE>,
Vec<Prio3InputShare<T::Field, SEED_SIZE>>,
),
VdafError,
> {
if random.len() != self.random_size() {
return Err(VdafError::Uncategorized(
"incorrect random input length".to_string(),
));
}
let mut random_seeds = random.chunks_exact(SEED_SIZE);
let num_aggregators = self.num_aggregators;
let encoded_measurement = self.typ.encode_measurement(measurement)?;
// Generate the measurement shares and compute the joint randomness.
let mut helper_shares = Vec::with_capacity(num_aggregators as usize - 1);
let mut helper_joint_rand_parts = if self.typ.joint_rand_len() > 0 {
Some(Vec::with_capacity(num_aggregators as usize - 1))
} else {
None
};
let mut leader_measurement_share = encoded_measurement.clone();
for agg_id in 1..num_aggregators {
// The Option from the ChunksExact iterator is okay to unwrap because we checked that
// the randomness slice is long enough for this VDAF. The slice-to-array conversion
// Result is okay to unwrap because the ChunksExact iterator always returns slices of
// the correct length.
let measurement_share_seed = random_seeds.next().unwrap().try_into().unwrap();
let proof_share_seed = random_seeds.next().unwrap().try_into().unwrap();
let measurement_share_prng: Prng<T::Field, _> = Prng::from_seed_stream(P::seed_stream(
&Seed(measurement_share_seed),
&Self::custom(DST_MEASUREMENT_SHARE),
&[agg_id],
));
let joint_rand_blind =
if let Some(helper_joint_rand_parts) = helper_joint_rand_parts.as_mut() {
let joint_rand_blind = random_seeds.next().unwrap().try_into().unwrap();
let mut joint_rand_part_prg =
P::init(&joint_rand_blind, &Self::custom(DST_JOINT_RAND_PART));
joint_rand_part_prg.update(&[agg_id]); // Aggregator ID
joint_rand_part_prg.update(nonce);
for (x, y) in leader_measurement_share
.iter_mut()
.zip(measurement_share_prng)
{
*x -= y;
joint_rand_part_prg.update(&y.into());
}
helper_joint_rand_parts.push(joint_rand_part_prg.into_seed());
Some(joint_rand_blind)
} else {
for (x, y) in leader_measurement_share
.iter_mut()
.zip(measurement_share_prng)
{
*x -= y;
}
None
};
let helper =
HelperShare::from_seeds(measurement_share_seed, proof_share_seed, joint_rand_blind);
helper_shares.push(helper);
}
let mut leader_blind_opt = None;
let public_share = Prio3PublicShare {
joint_rand_parts: helper_joint_rand_parts
.as_ref()
.map(|helper_joint_rand_parts| {
let leader_blind_bytes = random_seeds.next().unwrap().try_into().unwrap();
let leader_blind = Seed::from_bytes(leader_blind_bytes);
let mut joint_rand_part_prg =
P::init(leader_blind.as_ref(), &Self::custom(DST_JOINT_RAND_PART));
joint_rand_part_prg.update(&[0]); // Aggregator ID
joint_rand_part_prg.update(nonce);
for x in leader_measurement_share.iter() {
joint_rand_part_prg.update(&(*x).into());
}
leader_blind_opt = Some(leader_blind);
let leader_joint_rand_seed_part = joint_rand_part_prg.into_seed();
let mut vec = Vec::with_capacity(self.num_aggregators());
vec.push(leader_joint_rand_seed_part);
vec.extend(helper_joint_rand_parts.iter().cloned());
vec
}),
};
// Compute the joint randomness.
let joint_rand: Vec<T::Field> = public_share
.joint_rand_parts
.as_ref()
.map(|joint_rand_parts| {
let joint_rand_seed = Self::derive_joint_rand_seed(joint_rand_parts.iter());
let prng: Prng<T::Field, _> = Prng::from_seed_stream(P::seed_stream(
&joint_rand_seed,
&Self::custom(DST_JOINT_RANDOMNESS),
&[],
));
prng.take(self.typ.joint_rand_len()).collect()
})
.unwrap_or_default();
// Run the proof-generation algorithm.
let prove_rand_seed = random_seeds.next().unwrap().try_into().unwrap();
let prove_rand_prng: Prng<T::Field, _> = Prng::from_seed_stream(P::seed_stream(
&Seed::from_bytes(prove_rand_seed),
&Self::custom(DST_PROVE_RANDOMNESS),
&[],
));
let prove_rand: Vec<T::Field> = prove_rand_prng.take(self.typ.prove_rand_len()).collect();
let mut leader_proof_share =
self.typ
.prove(&encoded_measurement, &prove_rand, &joint_rand)?;
// Generate the proof shares and distribute the joint randomness seed hints.
for (j, helper) in helper_shares.iter_mut().enumerate() {
let proof_share_prng: Prng<T::Field, _> = Prng::from_seed_stream(P::seed_stream(
&helper.proof_share,
&Self::custom(DST_PROOF_SHARE),
&[j as u8 + 1],
));
for (x, y) in leader_proof_share
.iter_mut()
.zip(proof_share_prng)
.take(self.typ.proof_len())
{
*x -= y;
}
}
// Prep the output messages.
let mut out = Vec::with_capacity(num_aggregators as usize);
out.push(Prio3InputShare {
measurement_share: Share::Leader(leader_measurement_share),
proof_share: Share::Leader(leader_proof_share),
joint_rand_blind: leader_blind_opt,
});
for helper in helper_shares.into_iter() {
out.push(Prio3InputShare {
measurement_share: Share::Helper(helper.measurement_share),
proof_share: Share::Helper(helper.proof_share),
joint_rand_blind: helper.joint_rand_blind,
});
}
Ok((public_share, out))
}
/// Shard measurement with constant randomness of repeated bytes.
/// This method is not secure. It is used for running test vectors for Prio3.
#[cfg(feature = "test-util")]
#[doc(hidden)]
#[allow(clippy::type_complexity)]
pub fn test_vec_shard<const N: usize>(
&self,
measurement: &T::Measurement,
nonce: &[u8; N],
) -> Result<
(
Prio3PublicShare<SEED_SIZE>,
Vec<Prio3InputShare<T::Field, SEED_SIZE>>,
),
VdafError,
> {
let size = self.random_size();
let random = iter::repeat(0..=255)
.flatten()
.take(size)
.collect::<Vec<u8>>();
self.shard_with_random(measurement, nonce, &random)
}
fn role_try_from(&self, agg_id: usize) -> Result<u8, VdafError> {
if agg_id >= self.num_aggregators as usize {
return Err(VdafError::Uncategorized("unexpected aggregator id".into()));
}
Ok(u8::try_from(agg_id).unwrap())
}
}
impl<T, P, const SEED_SIZE: usize> Vdaf for Prio3<T, P, SEED_SIZE>
where
T: Type,
P: Prg<SEED_SIZE>,
{
const ID: u32 = T::ID;
type Measurement = T::Measurement;
type AggregateResult = T::AggregateResult;
type AggregationParam = ();
type PublicShare = Prio3PublicShare<SEED_SIZE>;
type InputShare = Prio3InputShare<T::Field, SEED_SIZE>;
type OutputShare = OutputShare<T::Field>;
type AggregateShare = AggregateShare<T::Field>;
fn num_aggregators(&self) -> usize {
self.num_aggregators as usize
}
}
/// Message broadcast by the [`Client`] to every [`Aggregator`] during the Sharding phase.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Prio3PublicShare<const SEED_SIZE: usize> {
/// Contributions to the joint randomness from every aggregator's share.
joint_rand_parts: Option<Vec<Seed<SEED_SIZE>>>,
}
impl<const SEED_SIZE: usize> Encode for Prio3PublicShare<SEED_SIZE> {
fn encode(&self, bytes: &mut Vec<u8>) {
if let Some(joint_rand_parts) = self.joint_rand_parts.as_ref() {
for part in joint_rand_parts.iter() {
part.encode(bytes);
}
}
}
fn encoded_len(&self) -> Option<usize> {
if let Some(joint_rand_parts) = self.joint_rand_parts.as_ref() {
// Each seed has the same size.
Some(SEED_SIZE * joint_rand_parts.len())
} else {
Some(0)
}
}
}
impl<T, P, const SEED_SIZE: usize> ParameterizedDecode<Prio3<T, P, SEED_SIZE>>
for Prio3PublicShare<SEED_SIZE>
where
T: Type,
P: Prg<SEED_SIZE>,
{
fn decode_with_param(
decoding_parameter: &Prio3<T, P, SEED_SIZE>,
bytes: &mut Cursor<&[u8]>,
) -> Result<Self, CodecError> {
if decoding_parameter.typ.joint_rand_len() > 0 {
let joint_rand_parts = iter::repeat_with(|| Seed::<SEED_SIZE>::decode(bytes))
.take(decoding_parameter.num_aggregators.into())
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
joint_rand_parts: Some(joint_rand_parts),
})
} else {
Ok(Self {
joint_rand_parts: None,
})
}
}
}
/// Message sent by the [`Client`] to each [`Aggregator`] during the Sharding phase.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Prio3InputShare<F, const SEED_SIZE: usize> {
/// The measurement share.
measurement_share: Share<F, SEED_SIZE>,
/// The proof share.
proof_share: Share<F, SEED_SIZE>,
/// Blinding seed used by the Aggregator to compute the joint randomness. This field is optional
/// because not every [`Type`] requires joint randomness.
joint_rand_blind: Option<Seed<SEED_SIZE>>,
}
impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize> Encode for Prio3InputShare<F, SEED_SIZE> {
fn encode(&self, bytes: &mut Vec<u8>) {
if matches!(
(&self.measurement_share, &self.proof_share),
(Share::Leader(_), Share::Helper(_)) | (Share::Helper(_), Share::Leader(_))
) {
panic!("tried to encode input share with ambiguous encoding")
}
self.measurement_share.encode(bytes);
self.proof_share.encode(bytes);
if let Some(ref blind) = self.joint_rand_blind {
blind.encode(bytes);
}
}
fn encoded_len(&self) -> Option<usize> {
let mut len = self.measurement_share.encoded_len()? + self.proof_share.encoded_len()?;
if let Some(ref blind) = self.joint_rand_blind {
len += blind.encoded_len()?;
}
Some(len)
}
}
impl<'a, T, P, const SEED_SIZE: usize> ParameterizedDecode<(&'a Prio3<T, P, SEED_SIZE>, usize)>
for Prio3InputShare<T::Field, SEED_SIZE>
where
T: Type,
P: Prg<SEED_SIZE>,
{
fn decode_with_param(
(prio3, agg_id): &(&'a Prio3<T, P, SEED_SIZE>, usize),
bytes: &mut Cursor<&[u8]>,
) -> Result<Self, CodecError> {
let agg_id = prio3
.role_try_from(*agg_id)
.map_err(|e| CodecError::Other(Box::new(e)))?;
let (input_decoder, proof_decoder) = if agg_id == 0 {
(
ShareDecodingParameter::Leader(prio3.typ.input_len()),
ShareDecodingParameter::Leader(prio3.typ.proof_len()),
)
} else {
(
ShareDecodingParameter::Helper,
ShareDecodingParameter::Helper,
)
};
let measurement_share = Share::decode_with_param(&input_decoder, bytes)?;
let proof_share = Share::decode_with_param(&proof_decoder, bytes)?;
let joint_rand_blind = if prio3.typ.joint_rand_len() > 0 {
let blind = Seed::decode(bytes)?;
Some(blind)
} else {
None
};
Ok(Prio3InputShare {
measurement_share,
proof_share,
joint_rand_blind,
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
/// Message broadcast by each [`Aggregator`] in each round of the Preparation phase.
pub struct Prio3PrepareShare<F, const SEED_SIZE: usize> {
/// A share of the FLP verifier message. (See [`Type`](crate::flp::Type).)
verifier: Vec<F>,
/// A part of the joint randomness seed.
joint_rand_part: Option<Seed<SEED_SIZE>>,
}
impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize> Encode
for Prio3PrepareShare<F, SEED_SIZE>
{
fn encode(&self, bytes: &mut Vec<u8>) {
for x in &self.verifier {
x.encode(bytes);
}
if let Some(ref seed) = self.joint_rand_part {
seed.encode(bytes);
}
}
fn encoded_len(&self) -> Option<usize> {
// Each element of the verifier has the same size.
let mut len = F::ENCODED_SIZE * self.verifier.len();
if let Some(ref seed) = self.joint_rand_part {
len += seed.encoded_len()?;
}
Some(len)
}
}
impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize>
ParameterizedDecode<Prio3PrepareState<F, SEED_SIZE>> for Prio3PrepareShare<F, SEED_SIZE>
{
fn decode_with_param(
decoding_parameter: &Prio3PrepareState<F, SEED_SIZE>,
bytes: &mut Cursor<&[u8]>,
) -> Result<Self, CodecError> {
let mut verifier = Vec::with_capacity(decoding_parameter.verifier_len);
for _ in 0..decoding_parameter.verifier_len {
verifier.push(F::decode(bytes)?);
}
let joint_rand_part = if decoding_parameter.joint_rand_seed.is_some() {
Some(Seed::decode(bytes)?)
} else {
None
};
Ok(Prio3PrepareShare {
verifier,
joint_rand_part,
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
/// Result of combining a round of [`Prio3PrepareShare`] messages.
pub struct Prio3PrepareMessage<const SEED_SIZE: usize> {
/// The joint randomness seed computed by the Aggregators.
joint_rand_seed: Option<Seed<SEED_SIZE>>,
}
impl<const SEED_SIZE: usize> Encode for Prio3PrepareMessage<SEED_SIZE> {
fn encode(&self, bytes: &mut Vec<u8>) {
if let Some(ref seed) = self.joint_rand_seed {
seed.encode(bytes);
}
}
fn encoded_len(&self) -> Option<usize> {
if let Some(ref seed) = self.joint_rand_seed {
seed.encoded_len()
} else {
Some(0)
}
}
}
impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize>
ParameterizedDecode<Prio3PrepareState<F, SEED_SIZE>> for Prio3PrepareMessage<SEED_SIZE>
{
fn decode_with_param(
decoding_parameter: &Prio3PrepareState<F, SEED_SIZE>,
bytes: &mut Cursor<&[u8]>,
) -> Result<Self, CodecError> {
let joint_rand_seed = if decoding_parameter.joint_rand_seed.is_some() {
Some(Seed::decode(bytes)?)
} else {
None
};
Ok(Prio3PrepareMessage { joint_rand_seed })
}
}
impl<T, P, const SEED_SIZE: usize> Client<16> for Prio3<T, P, SEED_SIZE>
where
T: Type,
P: Prg<SEED_SIZE>,
{
#[allow(clippy::type_complexity)]
fn shard(
&self,
measurement: &T::Measurement,
nonce: &[u8; 16],
) -> Result<(Self::PublicShare, Vec<Prio3InputShare<T::Field, SEED_SIZE>>), VdafError> {
let mut random = vec![0u8; self.random_size()];
getrandom::getrandom(&mut random)?;
self.shard_with_random(measurement, nonce, &random)
}
}
/// State of each [`Aggregator`] during the Preparation phase.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Prio3PrepareState<F, const SEED_SIZE: usize> {
measurement_share: Share<F, SEED_SIZE>,
joint_rand_seed: Option<Seed<SEED_SIZE>>,
agg_id: u8,
verifier_len: usize,
}
impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize> Encode
for Prio3PrepareState<F, SEED_SIZE>
{
/// Append the encoded form of this object to the end of `bytes`, growing the vector as needed.
fn encode(&self, bytes: &mut Vec<u8>) {
self.measurement_share.encode(bytes);
if let Some(ref seed) = self.joint_rand_seed {
seed.encode(bytes);
}
}
fn encoded_len(&self) -> Option<usize> {
let mut len = self.measurement_share.encoded_len()?;
if let Some(ref seed) = self.joint_rand_seed {
len += seed.encoded_len()?;
}
Some(len)
}
}
impl<'a, T, P, const SEED_SIZE: usize> ParameterizedDecode<(&'a Prio3<T, P, SEED_SIZE>, usize)>
for Prio3PrepareState<T::Field, SEED_SIZE>
where
T: Type,
P: Prg<SEED_SIZE>,
{
fn decode_with_param(
(prio3, agg_id): &(&'a Prio3<T, P, SEED_SIZE>, usize),
bytes: &mut Cursor<&[u8]>,
) -> Result<Self, CodecError> {
let agg_id = prio3
.role_try_from(*agg_id)
.map_err(|e| CodecError::Other(Box::new(e)))?;
let share_decoder = if agg_id == 0 {
ShareDecodingParameter::Leader(prio3.typ.input_len())
} else {
ShareDecodingParameter::Helper
};
let measurement_share = Share::decode_with_param(&share_decoder, bytes)?;
let joint_rand_seed = if prio3.typ.joint_rand_len() > 0 {
Some(Seed::decode(bytes)?)
} else {
None
};
Ok(Self {
measurement_share,
joint_rand_seed,
agg_id,
verifier_len: prio3.typ.verifier_len(),
})
}
}
impl<T, P, const SEED_SIZE: usize> Aggregator<SEED_SIZE, 16> for Prio3<T, P, SEED_SIZE>
where
T: Type,
P: Prg<SEED_SIZE>,
{
type PrepareState = Prio3PrepareState<T::Field, SEED_SIZE>;
type PrepareShare = Prio3PrepareShare<T::Field, SEED_SIZE>;
type PrepareMessage = Prio3PrepareMessage<SEED_SIZE>;
/// Begins the Prep process with the other aggregators. The result of this process is
/// the aggregator's output share.
#[allow(clippy::type_complexity)]
fn prepare_init(
&self,
verify_key: &[u8; SEED_SIZE],
agg_id: usize,
_agg_param: &Self::AggregationParam,
nonce: &[u8; 16],
public_share: &Self::PublicShare,
msg: &Prio3InputShare<T::Field, SEED_SIZE>,
) -> Result<
(
Prio3PrepareState<T::Field, SEED_SIZE>,
Prio3PrepareShare<T::Field, SEED_SIZE>,
),
VdafError,
> {
let agg_id = self.role_try_from(agg_id)?;
let mut query_rand_prg = P::init(verify_key, &Self::custom(DST_QUERY_RANDOMNESS));
query_rand_prg.update(nonce);
let query_rand_prng = Prng::from_seed_stream(query_rand_prg.into_seed_stream());
// Create a reference to the (expanded) measurement share.
let expanded_measurement_share: Option<Vec<T::Field>> = match msg.measurement_share {
Share::Leader(_) => None,
Share::Helper(ref seed) => {
let measurement_share_prng = Prng::from_seed_stream(P::seed_stream(
seed,
&Self::custom(DST_MEASUREMENT_SHARE),
&[agg_id],
));
Some(measurement_share_prng.take(self.typ.input_len()).collect())
}
};
let measurement_share = match msg.measurement_share {
Share::Leader(ref data) => data,
Share::Helper(_) => expanded_measurement_share.as_ref().unwrap(),
};
// Create a reference to the (expanded) proof share.
let expanded_proof_share: Option<Vec<T::Field>> = match msg.proof_share {
Share::Leader(_) => None,
Share::Helper(ref seed) => {
let prng = Prng::from_seed_stream(P::seed_stream(
seed,
&Self::custom(DST_PROOF_SHARE),
&[agg_id],
));
Some(prng.take(self.typ.proof_len()).collect())
}
};
let proof_share = match msg.proof_share {
Share::Leader(ref data) => data,
Share::Helper(_) => expanded_proof_share.as_ref().unwrap(),
};
// Compute the joint randomness.
let (joint_rand_seed, joint_rand_part, joint_rand) = if self.typ.joint_rand_len() > 0 {
let mut joint_rand_part_prg = P::init(
msg.joint_rand_blind.as_ref().unwrap().as_ref(),
&Self::custom(DST_JOINT_RAND_PART),
);
joint_rand_part_prg.update(&[agg_id]);
joint_rand_part_prg.update(nonce);
for x in measurement_share {
joint_rand_part_prg.update(&(*x).into());
}
let own_joint_rand_part = joint_rand_part_prg.into_seed();
// Make an iterator over the joint randomness parts, but use this aggregator's
// contribution, computed from the input share, in lieu of the the corresponding part
// from the public share.
//
// The locally computed part should match the part from the public share for honestly
// generated reports. If they do not match, the joint randomness seed check during the
// next round of preparation should fail.
let corrected_joint_rand_parts = public_share
.joint_rand_parts
.iter()
.flatten()
.take(agg_id as usize)
.chain(iter::once(&own_joint_rand_part))
.chain(
public_share
.joint_rand_parts
.iter()
.flatten()
.skip(agg_id as usize + 1),
);
let joint_rand_seed = Self::derive_joint_rand_seed(corrected_joint_rand_parts);
let joint_rand_prng: Prng<T::Field, _> = Prng::from_seed_stream(P::seed_stream(
&joint_rand_seed,
&Self::custom(DST_JOINT_RANDOMNESS),
&[],