Debian Codegraph @

third_party/rust/prio/src/vdaf/prio3.rs

raw
1 // SPDX-License-Identifier: MPL-2.0
2
3 //! Implementation of the Prio3 VDAF [[draft-irtf-cfrg-vdaf-08]].
4 //!
5 //! **WARNING:** This code has not undergone significant security analysis. Use at your own risk.
6 //!
7 //! Prio3 is based on the Prio system desigend by Dan Boneh and Henry Corrigan-Gibbs and presented
8 //! at NSDI 2017 [[CGB17]]. However, it incorporates a few techniques from Boneh et al., CRYPTO
9 //! 2019 [[BBCG+19]], that lead to substantial improvements in terms of run time and communication
10 //! cost. The security of the construction was analyzed in [[DPRS23]].
11 //!
12 //! Prio3 is a transformation of a Fully Linear Proof (FLP) system [[draft-irtf-cfrg-vdaf-08]] into
13 //! a VDAF. The base type, [`Prio3`], supports a wide variety of aggregation functions, some of
14 //! which are instantiated here:
15 //!
16 //! - [`Prio3Count`] for aggregating a counter (*)
17 //! - [`Prio3Sum`] for copmputing the sum of integers (*)
18 //! - [`Prio3SumVec`] for aggregating a vector of integers
19 //! - [`Prio3Histogram`] for estimating a distribution via a histogram (*)
20 //!
21 //! Additional types can be constructed from [`Prio3`] as needed.
22 //!
23 //! (*) denotes that the type is specified in [[draft-irtf-cfrg-vdaf-08]].
24 //!
25 //! [BBCG+19]: https://ia.cr/2019/188
26 //! [CGB17]: https://crypto.stanford.edu/prio/
27 //! [DPRS23]: https://ia.cr/2023/130
28 //! [draft-irtf-cfrg-vdaf-08]: https://datatracker.ietf.org/doc/draft-irtf-cfrg-vdaf/08/
29
30 use super::xof::XofTurboShake128;
31 #[cfg(feature = "experimental")]
32 use super::AggregatorWithNoise;
33 use crate::codec::{CodecError, Decode, Encode, ParameterizedDecode};
34 #[cfg(feature = "experimental")]
35 use crate::dp::DifferentialPrivacyStrategy;
36 use crate::field::{decode_fieldvec, FftFriendlyFieldElement, FieldElement};
37 use crate::field::{Field128, Field64};
38 #[cfg(feature = "multithreaded")]
39 use crate::flp::gadgets::ParallelSumMultithreaded;
40 #[cfg(feature = "experimental")]
41 use crate::flp::gadgets::PolyEval;
42 use crate::flp::gadgets::{Mul, ParallelSum};
43 #[cfg(feature = "experimental")]
44 use crate::flp::types::fixedpoint_l2::{
45 compatible_float::CompatibleFloat, FixedPointBoundedL2VecSum,
46 };
47 use crate::flp::types::{Average, Count, Histogram, Sum, SumVec};
48 use crate::flp::Type;
49 #[cfg(feature = "experimental")]
50 use crate::flp::TypeWithNoise;
51 use crate::prng::Prng;
52 use crate::vdaf::xof::{IntoFieldVec, Seed, Xof};
53 use crate::vdaf::{
54 Aggregatable, AggregateShare, Aggregator, Client, Collector, OutputShare, PrepareTransition,
55 Share, ShareDecodingParameter, Vdaf, VdafError,
56 };
57 #[cfg(feature = "experimental")]
58 use fixed::traits::Fixed;
59 use std::convert::TryFrom;
60 use std::fmt::Debug;
61 use std::io::Cursor;
62 use std::iter::{self, IntoIterator};
63 use std::marker::PhantomData;
64 use subtle::{Choice, ConstantTimeEq};
65
66 const DST_MEASUREMENT_SHARE: u16 = 1;
67 const DST_PROOF_SHARE: u16 = 2;
68 const DST_JOINT_RANDOMNESS: u16 = 3;
69 const DST_PROVE_RANDOMNESS: u16 = 4;
70 const DST_QUERY_RANDOMNESS: u16 = 5;
71 const DST_JOINT_RAND_SEED: u16 = 6;
72 const DST_JOINT_RAND_PART: u16 = 7;
73
74 /// The count type. Each measurement is an integer in `[0,2)` and the aggregate result is the sum.
75 pub type Prio3Count = Prio3<Count<Field64>, XofTurboShake128, 16>;
76
77 impl Prio3Count {
78 /// Construct an instance of Prio3Count with the given number of aggregators.
79 pub fn new_count(num_aggregators: u8) -> Result<Self, VdafError> {
80 Prio3::new(num_aggregators, 1, 0x00000000, Count::new())
81 }
82 }
83
84 /// The count-vector type. Each measurement is a vector of integers in `[0,2^bits)` and the
85 /// aggregate is the element-wise sum.
86 pub type Prio3SumVec =
87 Prio3<SumVec<Field128, ParallelSum<Field128, Mul<Field128>>>, XofTurboShake128, 16>;
88
89 impl Prio3SumVec {
90 /// Construct an instance of Prio3SumVec with the given number of aggregators. `bits` defines
91 /// the bit width of each summand of the measurement; `len` defines the length of the
92 /// measurement vector.
93 pub fn new_sum_vec(
94 num_aggregators: u8,
95 bits: usize,
96 len: usize,
97 chunk_length: usize,
98 ) -> Result<Self, VdafError> {
99 Prio3::new(
100 num_aggregators,
101 1,
102 0x00000002,
103 SumVec::new(bits, len, chunk_length)?,
104 )
105 }
106 }
107
108 /// Like [`Prio3SumVec`] except this type uses multithreading to improve sharding and preparation
109 /// time. Note that the improvement is only noticeable for very large input lengths.
110 #[cfg(feature = "multithreaded")]
111 #[cfg_attr(docsrs, doc(cfg(feature = "multithreaded")))]
112 pub type Prio3SumVecMultithreaded = Prio3<
113 SumVec<Field128, ParallelSumMultithreaded<Field128, Mul<Field128>>>,
114 XofTurboShake128,
115 16,
116 >;
117
118 #[cfg(feature = "multithreaded")]
119 impl Prio3SumVecMultithreaded {
120 /// Construct an instance of Prio3SumVecMultithreaded with the given number of
121 /// aggregators. `bits` defines the bit width of each summand of the measurement; `len` defines
122 /// the length of the measurement vector.
123 pub fn new_sum_vec_multithreaded(
124 num_aggregators: u8,
125 bits: usize,
126 len: usize,
127 chunk_length: usize,
128 ) -> Result<Self, VdafError> {
129 Prio3::new(
130 num_aggregators,
131 1,
132 0x00000002,
133 SumVec::new(bits, len, chunk_length)?,
134 )
135 }
136 }
137
138 /// The sum type. Each measurement is an integer in `[0,2^bits)` for some `0 < bits < 64` and the
139 /// aggregate is the sum.
140 pub type Prio3Sum = Prio3<Sum<Field128>, XofTurboShake128, 16>;
141
142 impl Prio3Sum {
143 /// Construct an instance of Prio3Sum with the given number of aggregators and required bit
144 /// length. The bit length must not exceed 64.
145 pub fn new_sum(num_aggregators: u8, bits: usize) -> Result<Self, VdafError> {
146 if bits > 64 {
147 return Err(VdafError::Uncategorized(format!(
148 "bit length ({bits}) exceeds limit for aggregate type (64)"
149 )));
150 }
151
152 Prio3::new(num_aggregators, 1, 0x00000001, Sum::new(bits)?)
153 }
154 }
155
156 /// The fixed point vector sum type. Each measurement is a vector of fixed point numbers
157 /// and the aggregate is the sum represented as 64-bit floats. The preparation phase
158 /// ensures the L2 norm of the input vector is < 1.
159 ///
160 /// This is useful for aggregating gradients in a federated version of
161 /// [gradient descent](https://en.wikipedia.org/wiki/Gradient_descent) with
162 /// [differential privacy](https://en.wikipedia.org/wiki/Differential_privacy),
163 /// useful, e.g., for [differentially private deep learning](https://arxiv.org/pdf/1607.00133.pdf).
164 /// The bound on input norms is required for differential privacy. The fixed point representation
165 /// allows an easy conversion to the integer type used in internal computation, while leaving
166 /// conversion to the client. The model itself will have floating point parameters, so the output
167 /// sum has that type as well.
168 #[cfg(feature = "experimental")]
169 #[cfg_attr(docsrs, doc(cfg(feature = "experimental")))]
170 pub type Prio3FixedPointBoundedL2VecSum<Fx> = Prio3<
171 FixedPointBoundedL2VecSum<
172 Fx,
173 ParallelSum<Field128, PolyEval<Field128>>,
174 ParallelSum<Field128, Mul<Field128>>,
175 >,
176 XofTurboShake128,
177 16,
178 >;
179
180 #[cfg(feature = "experimental")]
181 impl<Fx: Fixed + CompatibleFloat> Prio3FixedPointBoundedL2VecSum<Fx> {
182 /// Construct an instance of this VDAF with the given number of aggregators and number of
183 /// vector entries.
184 pub fn new_fixedpoint_boundedl2_vec_sum(
185 num_aggregators: u8,
186 entries: usize,
187 ) -> Result<Self, VdafError> {
188 check_num_aggregators(num_aggregators)?;
189 Prio3::new(
190 num_aggregators,
191 1,
192 0xFFFF0000,
193 FixedPointBoundedL2VecSum::new(entries)?,
194 )
195 }
196 }
197
198 /// The fixed point vector sum type. Each measurement is a vector of fixed point numbers
199 /// and the aggregate is the sum represented as 64-bit floats. The verification function
200 /// ensures the L2 norm of the input vector is < 1.
201 #[cfg(all(feature = "experimental", feature = "multithreaded"))]
202 #[cfg_attr(
203 docsrs,
204 doc(cfg(all(feature = "experimental", feature = "multithreaded")))
205 )]
206 pub type Prio3FixedPointBoundedL2VecSumMultithreaded<Fx> = Prio3<
207 FixedPointBoundedL2VecSum<
208 Fx,
209 ParallelSumMultithreaded<Field128, PolyEval<Field128>>,
210 ParallelSumMultithreaded<Field128, Mul<Field128>>,
211 >,
212 XofTurboShake128,
213 16,
214 >;
215
216 #[cfg(all(feature = "experimental", feature = "multithreaded"))]
217 impl<Fx: Fixed + CompatibleFloat> Prio3FixedPointBoundedL2VecSumMultithreaded<Fx> {
218 /// Construct an instance of this VDAF with the given number of aggregators and number of
219 /// vector entries.
220 pub fn new_fixedpoint_boundedl2_vec_sum_multithreaded(
221 num_aggregators: u8,
222 entries: usize,
223 ) -> Result<Self, VdafError> {
224 check_num_aggregators(num_aggregators)?;
225 Prio3::new(
226 num_aggregators,
227 1,
228 0xFFFF0000,
229 FixedPointBoundedL2VecSum::new(entries)?,
230 )
231 }
232 }
233
234 /// The histogram type. Each measurement is an integer in `[0, length)` and the result is a
235 /// histogram counting the number of occurrences of each measurement.
236 pub type Prio3Histogram =
237 Prio3<Histogram<Field128, ParallelSum<Field128, Mul<Field128>>>, XofTurboShake128, 16>;
238
239 impl Prio3Histogram {
240 /// Constructs an instance of Prio3Histogram with the given number of aggregators,
241 /// number of buckets, and parallel sum gadget chunk length.
242 pub fn new_histogram(
243 num_aggregators: u8,
244 length: usize,
245 chunk_length: usize,
246 ) -> Result<Self, VdafError> {
247 Prio3::new(
248 num_aggregators,
249 1,
250 0x00000003,
251 Histogram::new(length, chunk_length)?,
252 )
253 }
254 }
255
256 /// Like [`Prio3Histogram`] except this type uses multithreading to improve sharding and preparation
257 /// time. Note that this improvement is only noticeable for very large input lengths.
258 #[cfg(feature = "multithreaded")]
259 #[cfg_attr(docsrs, doc(cfg(feature = "multithreaded")))]
260 pub type Prio3HistogramMultithreaded = Prio3<
261 Histogram<Field128, ParallelSumMultithreaded<Field128, Mul<Field128>>>,
262 XofTurboShake128,
263 16,
264 >;
265
266 #[cfg(feature = "multithreaded")]
267 impl Prio3HistogramMultithreaded {
268 /// Construct an instance of Prio3HistogramMultithreaded with the given number of aggregators,
269 /// number of buckets, and parallel sum gadget chunk length.
270 pub fn new_histogram_multithreaded(
271 num_aggregators: u8,
272 length: usize,
273 chunk_length: usize,
274 ) -> Result<Self, VdafError> {
275 Prio3::new(
276 num_aggregators,
277 1,
278 0x00000003,
279 Histogram::new(length, chunk_length)?,
280 )
281 }
282 }
283
284 /// The average type. Each measurement is an integer in `[0,2^bits)` for some `0 < bits < 64` and
285 /// the aggregate is the arithmetic average.
286 pub type Prio3Average = Prio3<Average<Field128>, XofTurboShake128, 16>;
287
288 impl Prio3Average {
289 /// Construct an instance of Prio3Average with the given number of aggregators and required bit
290 /// length. The bit length must not exceed 64.
291 pub fn new_average(num_aggregators: u8, bits: usize) -> Result<Self, VdafError> {
292 check_num_aggregators(num_aggregators)?;
293
294 if bits > 64 {
295 return Err(VdafError::Uncategorized(format!(
296 "bit length ({bits}) exceeds limit for aggregate type (64)"
297 )));
298 }
299
300 Ok(Prio3 {
301 num_aggregators,
302 num_proofs: 1,
303 algorithm_id: 0xFFFF0000,
304 typ: Average::new(bits)?,
305 phantom: PhantomData,
306 })
307 }
308 }
309
310 /// The base type for Prio3.
311 ///
312 /// An instance of Prio3 is determined by:
313 ///
314 /// - a [`Type`] that defines the set of valid input measurements; and
315 /// - a [`Xof`] for deriving vectors of field elements from seeds.
316 ///
317 /// New instances can be defined by aliasing the base type. For example, [`Prio3Count`] is an alias
318 /// for `Prio3<Count<Field64>, XofTurboShake128, 16>`.
319 ///
320 /// ```
321 /// use prio::vdaf::{
322 /// Aggregator, Client, Collector, PrepareTransition,
323 /// prio3::Prio3,
324 /// };
325 /// use rand::prelude::*;
326 ///
327 /// let num_shares = 2;
328 /// let vdaf = Prio3::new_count(num_shares).unwrap();
329 ///
330 /// let mut out_shares = vec![vec![]; num_shares.into()];
331 /// let mut rng = thread_rng();
332 /// let verify_key = rng.gen();
333 /// let measurements = [false, true, true, true, false];
334 /// for measurement in measurements {
335 /// // Shard
336 /// let nonce = rng.gen::<[u8; 16]>();
337 /// let (public_share, input_shares) = vdaf.shard(&measurement, &nonce).unwrap();
338 ///
339 /// // Prepare
340 /// let mut prep_states = vec![];
341 /// let mut prep_shares = vec![];
342 /// for (agg_id, input_share) in input_shares.iter().enumerate() {
343 /// let (state, share) = vdaf.prepare_init(
344 /// &verify_key,
345 /// agg_id,
346 /// &(),
347 /// &nonce,
348 /// &public_share,
349 /// input_share
350 /// ).unwrap();
351 /// prep_states.push(state);
352 /// prep_shares.push(share);
353 /// }
354 /// let prep_msg = vdaf.prepare_shares_to_prepare_message(&(), prep_shares).unwrap();
355 ///
356 /// for (agg_id, state) in prep_states.into_iter().enumerate() {
357 /// let out_share = match vdaf.prepare_next(state, prep_msg.clone()).unwrap() {
358 /// PrepareTransition::Finish(out_share) => out_share,
359 /// _ => panic!("unexpected transition"),
360 /// };
361 /// out_shares[agg_id].push(out_share);
362 /// }
363 /// }
364 ///
365 /// // Aggregate
366 /// let agg_shares = out_shares.into_iter()
367 /// .map(|o| vdaf.aggregate(&(), o).unwrap());
368 ///
369 /// // Unshard
370 /// let agg_res = vdaf.unshard(&(), agg_shares, measurements.len()).unwrap();
371 /// assert_eq!(agg_res, 3);
372 /// ```
373 #[derive(Clone, Debug)]
374 pub struct Prio3<T, P, const SEED_SIZE: usize>
375 where
376 T: Type,
377 P: Xof<SEED_SIZE>,
378 {
379 num_aggregators: u8,
380 num_proofs: u8,
381 algorithm_id: u32,
382 typ: T,
383 phantom: PhantomData<P>,
384 }
385
386 impl<T, P, const SEED_SIZE: usize> Prio3<T, P, SEED_SIZE>
387 where
388 T: Type,
389 P: Xof<SEED_SIZE>,
390 {
391 /// Construct an instance of this Prio3 VDAF with the given number of aggregators, number of
392 /// proofs to generate and verify, the algorithm ID, and the underlying type.
393 pub fn new(
394 num_aggregators: u8,
395 num_proofs: u8,
396 algorithm_id: u32,
397 typ: T,
398 ) -> Result<Self, VdafError> {
399 check_num_aggregators(num_aggregators)?;
400 if num_proofs == 0 {
401 return Err(VdafError::Uncategorized(
402 "num_proofs must be at least 1".to_string(),
403 ));
404 }
405
406 Ok(Self {
407 num_aggregators,
408 num_proofs,
409 algorithm_id,
410 typ,
411 phantom: PhantomData,
412 })
413 }
414
415 /// The output length of the underlying FLP.
416 pub fn output_len(&self) -> usize {
417 self.typ.output_len()
418 }
419
420 /// The verifier length of the underlying FLP.
421 pub fn verifier_len(&self) -> usize {
422 self.typ.verifier_len()
423 }
424
425 #[inline]
426 fn num_proofs(&self) -> usize {
427 self.num_proofs.into()
428 }
429
430 fn derive_prove_rands(&self, prove_rand_seed: &Seed<SEED_SIZE>) -> Vec<T::Field> {
431 P::seed_stream(
432 prove_rand_seed,
433 &self.domain_separation_tag(DST_PROVE_RANDOMNESS),
434 &[self.num_proofs],
435 )
436 .into_field_vec(self.typ.prove_rand_len() * self.num_proofs())
437 }
438
439 fn derive_joint_rand_seed<'a>(
440 &self,
441 joint_rand_parts: impl Iterator<Item = &'a Seed<SEED_SIZE>>,
442 ) -> Seed<SEED_SIZE> {
443 let mut xof = P::init(
444 &[0; SEED_SIZE],
445 &self.domain_separation_tag(DST_JOINT_RAND_SEED),
446 );
447 for part in joint_rand_parts {
448 xof.update(part.as_ref());
449 }
450 xof.into_seed()
451 }
452
453 fn derive_joint_rands<'a>(
454 &self,
455 joint_rand_parts: impl Iterator<Item = &'a Seed<SEED_SIZE>>,
456 ) -> (Seed<SEED_SIZE>, Vec<T::Field>) {
457 let joint_rand_seed = self.derive_joint_rand_seed(joint_rand_parts);
458 let joint_rands = P::seed_stream(
459 &joint_rand_seed,
460 &self.domain_separation_tag(DST_JOINT_RANDOMNESS),
461 &[self.num_proofs],
462 )
463 .into_field_vec(self.typ.joint_rand_len() * self.num_proofs());
464
465 (joint_rand_seed, joint_rands)
466 }
467
468 fn derive_helper_proofs_share(
469 &self,
470 proofs_share_seed: &Seed<SEED_SIZE>,
471 agg_id: u8,
472 ) -> Prng<T::Field, P::SeedStream> {
473 Prng::from_seed_stream(P::seed_stream(
474 proofs_share_seed,
475 &self.domain_separation_tag(DST_PROOF_SHARE),
476 &[self.num_proofs, agg_id],
477 ))
478 }
479
480 fn derive_query_rands(&self, verify_key: &[u8; SEED_SIZE], nonce: &[u8; 16]) -> Vec<T::Field> {
481 let mut xof = P::init(
482 verify_key,
483 &self.domain_separation_tag(DST_QUERY_RANDOMNESS),
484 );
485 xof.update(&[self.num_proofs]);
486 xof.update(nonce);
487 xof.into_seed_stream()
488 .into_field_vec(self.typ.query_rand_len() * self.num_proofs())
489 }
490
491 fn random_size(&self) -> usize {
492 if self.typ.joint_rand_len() == 0 {
493 // Two seeds per helper for measurement and proof shares, plus one seed for proving
494 // randomness.
495 (usize::from(self.num_aggregators - 1) * 2 + 1) * SEED_SIZE
496 } else {
497 (
498 // Two seeds per helper for measurement and proof shares
499 usize::from(self.num_aggregators - 1) * 2
500 // One seed for proving randomness
501 + 1
502 // One seed per aggregator for joint randomness blinds
503 + usize::from(self.num_aggregators)
504 ) * SEED_SIZE
505 }
506 }
507
508 #[allow(clippy::type_complexity)]
509 pub(crate) fn shard_with_random<const N: usize>(
510 &self,
511 measurement: &T::Measurement,
512 nonce: &[u8; N],
513 random: &[u8],
514 ) -> Result<
515 (
516 Prio3PublicShare<SEED_SIZE>,
517 Vec<Prio3InputShare<T::Field, SEED_SIZE>>,
518 ),
519 VdafError,
520 > {
521 if random.len() != self.random_size() {
522 return Err(VdafError::Uncategorized(
523 "incorrect random input length".to_string(),
524 ));
525 }
526 let mut random_seeds = random.chunks_exact(SEED_SIZE);
527 let num_aggregators = self.num_aggregators;
528 let encoded_measurement = self.typ.encode_measurement(measurement)?;
529
530 // Generate the measurement shares and compute the joint randomness.
531 let mut helper_shares = Vec::with_capacity(num_aggregators as usize - 1);
532 let mut helper_joint_rand_parts = if self.typ.joint_rand_len() > 0 {
533 Some(Vec::with_capacity(num_aggregators as usize - 1))
534 } else {
535 None
536 };
537 let mut leader_measurement_share = encoded_measurement.clone();
538 for agg_id in 1..num_aggregators {
539 // The Option from the ChunksExact iterator is okay to unwrap because we checked that
540 // the randomness slice is long enough for this VDAF. The slice-to-array conversion
541 // Result is okay to unwrap because the ChunksExact iterator always returns slices of
542 // the correct length.
543 let measurement_share_seed = random_seeds.next().unwrap().try_into().unwrap();
544 let proof_share_seed = random_seeds.next().unwrap().try_into().unwrap();
545 let measurement_share_prng: Prng<T::Field, _> = Prng::from_seed_stream(P::seed_stream(
546 &Seed(measurement_share_seed),
547 &self.domain_separation_tag(DST_MEASUREMENT_SHARE),
548 &[agg_id],
549 ));
550 let joint_rand_blind = if let Some(helper_joint_rand_parts) =
551 helper_joint_rand_parts.as_mut()
552 {
553 let joint_rand_blind = random_seeds.next().unwrap().try_into().unwrap();
554 let mut joint_rand_part_xof = P::init(
555 &joint_rand_blind,
556 &self.domain_separation_tag(DST_JOINT_RAND_PART),
557 );
558 joint_rand_part_xof.update(&[agg_id]); // Aggregator ID
559 joint_rand_part_xof.update(nonce);
560
561 let mut encoding_buffer = Vec::with_capacity(T::Field::ENCODED_SIZE);
562 for (x, y) in leader_measurement_share
563 .iter_mut()
564 .zip(measurement_share_prng)
565 {
566 *x -= y;
567 y.encode(&mut encoding_buffer).map_err(|_| {
568 VdafError::Uncategorized("failed to encode measurement share".to_string())
569 })?;
570 joint_rand_part_xof.update(&encoding_buffer);
571 encoding_buffer.clear();
572 }
573
574 helper_joint_rand_parts.push(joint_rand_part_xof.into_seed());
575
576 Some(joint_rand_blind)
577 } else {
578 for (x, y) in leader_measurement_share
579 .iter_mut()
580 .zip(measurement_share_prng)
581 {
582 *x -= y;
583 }
584 None
585 };
586 let helper =
587 HelperShare::from_seeds(measurement_share_seed, proof_share_seed, joint_rand_blind);
588 helper_shares.push(helper);
589 }
590
591 let mut leader_blind_opt = None;
592 let public_share = Prio3PublicShare {
593 joint_rand_parts: helper_joint_rand_parts
594 .as_ref()
595 .map(
596 |helper_joint_rand_parts| -> Result<Vec<Seed<SEED_SIZE>>, VdafError> {
597 let leader_blind_bytes = random_seeds.next().unwrap().try_into().unwrap();
598 let leader_blind = Seed::from_bytes(leader_blind_bytes);
599
600 let mut joint_rand_part_xof = P::init(
601 leader_blind.as_ref(),
602 &self.domain_separation_tag(DST_JOINT_RAND_PART),
603 );
604 joint_rand_part_xof.update(&[0]); // Aggregator ID
605 joint_rand_part_xof.update(nonce);
606 let mut encoding_buffer = Vec::with_capacity(T::Field::ENCODED_SIZE);
607 for x in leader_measurement_share.iter() {
608 x.encode(&mut encoding_buffer).map_err(|_| {
609 VdafError::Uncategorized(
610 "failed to encode measurement share".to_string(),
611 )
612 })?;
613 joint_rand_part_xof.update(&encoding_buffer);
614 encoding_buffer.clear();
615 }
616 leader_blind_opt = Some(leader_blind);
617
618 let leader_joint_rand_seed_part = joint_rand_part_xof.into_seed();
619
620 let mut vec = Vec::with_capacity(self.num_aggregators());
621 vec.push(leader_joint_rand_seed_part);
622 vec.extend(helper_joint_rand_parts.iter().cloned());
623 Ok(vec)
624 },
625 )
626 .transpose()?,
627 };
628
629 // Compute the joint randomness.
630 let joint_rands = public_share
631 .joint_rand_parts
632 .as_ref()
633 .map(|joint_rand_parts| self.derive_joint_rands(joint_rand_parts.iter()).1)
634 .unwrap_or_default();
635
636 // Generate the proofs.
637 let prove_rands = self.derive_prove_rands(&Seed::from_bytes(
638 random_seeds.next().unwrap().try_into().unwrap(),
639 ));
640 let mut leader_proofs_share = Vec::with_capacity(self.typ.proof_len() * self.num_proofs());
641 for p in 0..self.num_proofs() {
642 let prove_rand =
643 &prove_rands[p * self.typ.prove_rand_len()..(p + 1) * self.typ.prove_rand_len()];
644 let joint_rand =
645 &joint_rands[p * self.typ.joint_rand_len()..(p + 1) * self.typ.joint_rand_len()];
646
647 leader_proofs_share.append(&mut self.typ.prove(
648 &encoded_measurement,
649 prove_rand,
650 joint_rand,
651 )?);
652 }
653
654 // Generate the proof shares and distribute the joint randomness seed hints.
655 for (j, helper) in helper_shares.iter_mut().enumerate() {
656 for (x, y) in
657 leader_proofs_share
658 .iter_mut()
659 .zip(self.derive_helper_proofs_share(
660 &helper.proofs_share,
661 u8::try_from(j).unwrap() + 1,
662 ))
663 .take(self.typ.proof_len() * self.num_proofs())
664 {
665 *x -= y;
666 }
667 }
668
669 // Prep the output messages.
670 let mut out = Vec::with_capacity(num_aggregators as usize);
671 out.push(Prio3InputShare {
672 measurement_share: Share::Leader(leader_measurement_share),
673 proofs_share: Share::Leader(leader_proofs_share),
674 joint_rand_blind: leader_blind_opt,
675 });
676
677 for helper in helper_shares.into_iter() {
678 out.push(Prio3InputShare {
679 measurement_share: Share::Helper(helper.measurement_share),
680 proofs_share: Share::Helper(helper.proofs_share),
681 joint_rand_blind: helper.joint_rand_blind,
682 });
683 }
684
685 Ok((public_share, out))
686 }
687
688 fn role_try_from(&self, agg_id: usize) -> Result<u8, VdafError> {
689 if agg_id >= self.num_aggregators as usize {
690 return Err(VdafError::Uncategorized("unexpected aggregator id".into()));
691 }
692 Ok(u8::try_from(agg_id).unwrap())
693 }
694 }
695
696 impl<T, P, const SEED_SIZE: usize> Vdaf for Prio3<T, P, SEED_SIZE>
697 where
698 T: Type,
699 P: Xof<SEED_SIZE>,
700 {
701 type Measurement = T::Measurement;
702 type AggregateResult = T::AggregateResult;
703 type AggregationParam = ();
704 type PublicShare = Prio3PublicShare<SEED_SIZE>;
705 type InputShare = Prio3InputShare<T::Field, SEED_SIZE>;
706 type OutputShare = OutputShare<T::Field>;
707 type AggregateShare = AggregateShare<T::Field>;
708
709 fn algorithm_id(&self) -> u32 {
710 self.algorithm_id
711 }
712
713 fn num_aggregators(&self) -> usize {
714 self.num_aggregators as usize
715 }
716 }
717
718 /// Message broadcast by the [`Client`] to every [`Aggregator`] during the Sharding phase.
719 #[derive(Clone, Debug)]
720 pub struct Prio3PublicShare<const SEED_SIZE: usize> {
721 /// Contributions to the joint randomness from every aggregator's share.
722 joint_rand_parts: Option<Vec<Seed<SEED_SIZE>>>,
723 }
724
725 impl<const SEED_SIZE: usize> Encode for Prio3PublicShare<SEED_SIZE> {
726 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
727 if let Some(joint_rand_parts) = self.joint_rand_parts.as_ref() {
728 for part in joint_rand_parts.iter() {
729 part.encode(bytes)?;
730 }
731 }
732 Ok(())
733 }
734
735 fn encoded_len(&self) -> Option<usize> {
736 if let Some(joint_rand_parts) = self.joint_rand_parts.as_ref() {
737 // Each seed has the same size.
738 Some(SEED_SIZE * joint_rand_parts.len())
739 } else {
740 Some(0)
741 }
742 }
743 }
744
745 impl<const SEED_SIZE: usize> PartialEq for Prio3PublicShare<SEED_SIZE> {
746 fn eq(&self, other: &Self) -> bool {
747 self.ct_eq(other).into()
748 }
749 }
750
751 impl<const SEED_SIZE: usize> Eq for Prio3PublicShare<SEED_SIZE> {}
752
753 impl<const SEED_SIZE: usize> ConstantTimeEq for Prio3PublicShare<SEED_SIZE> {
754 fn ct_eq(&self, other: &Self) -> Choice {
755 // We allow short-circuiting on the presence or absence of the joint_rand_parts.
756 option_ct_eq(
757 self.joint_rand_parts.as_deref(),
758 other.joint_rand_parts.as_deref(),
759 )
760 }
761 }
762
763 impl<T, P, const SEED_SIZE: usize> ParameterizedDecode<Prio3<T, P, SEED_SIZE>>
764 for Prio3PublicShare<SEED_SIZE>
765 where
766 T: Type,
767 P: Xof<SEED_SIZE>,
768 {
769 fn decode_with_param(
770 decoding_parameter: &Prio3<T, P, SEED_SIZE>,
771 bytes: &mut Cursor<&[u8]>,
772 ) -> Result<Self, CodecError> {
773 if decoding_parameter.typ.joint_rand_len() > 0 {
774 let joint_rand_parts = iter::repeat_with(|| Seed::<SEED_SIZE>::decode(bytes))
775 .take(decoding_parameter.num_aggregators.into())
776 .collect::<Result<Vec<_>, _>>()?;
777 Ok(Self {
778 joint_rand_parts: Some(joint_rand_parts),
779 })
780 } else {
781 Ok(Self {
782 joint_rand_parts: None,
783 })
784 }
785 }
786 }
787
788 /// Message sent by the [`Client`] to each [`Aggregator`] during the Sharding phase.
789 #[derive(Clone, Debug)]
790 pub struct Prio3InputShare<F, const SEED_SIZE: usize> {
791 /// The measurement share.
792 measurement_share: Share<F, SEED_SIZE>,
793
794 /// The proof share.
795 proofs_share: Share<F, SEED_SIZE>,
796
797 /// Blinding seed used by the Aggregator to compute the joint randomness. This field is optional
798 /// because not every [`Type`] requires joint randomness.
799 joint_rand_blind: Option<Seed<SEED_SIZE>>,
800 }
801
802 impl<F: ConstantTimeEq, const SEED_SIZE: usize> PartialEq for Prio3InputShare<F, SEED_SIZE> {
803 fn eq(&self, other: &Self) -> bool {
804 self.ct_eq(other).into()
805 }
806 }
807
808 impl<F: ConstantTimeEq, const SEED_SIZE: usize> Eq for Prio3InputShare<F, SEED_SIZE> {}
809
810 impl<F: ConstantTimeEq, const SEED_SIZE: usize> ConstantTimeEq for Prio3InputShare<F, SEED_SIZE> {
811 fn ct_eq(&self, other: &Self) -> Choice {
812 // We allow short-circuiting on the presence or absence of the joint_rand_blind.
813 option_ct_eq(
814 self.joint_rand_blind.as_ref(),
815 other.joint_rand_blind.as_ref(),
816 ) & self.measurement_share.ct_eq(&other.measurement_share)
817 & self.proofs_share.ct_eq(&other.proofs_share)
818 }
819 }
820
821 impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize> Encode for Prio3InputShare<F, SEED_SIZE> {
822 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
823 if matches!(
824 (&self.measurement_share, &self.proofs_share),
825 (Share::Leader(_), Share::Helper(_)) | (Share::Helper(_), Share::Leader(_))
826 ) {
827 panic!("tried to encode input share with ambiguous encoding")
828 }
829
830 self.measurement_share.encode(bytes)?;
831 self.proofs_share.encode(bytes)?;
832 if let Some(ref blind) = self.joint_rand_blind {
833 blind.encode(bytes)?;
834 }
835 Ok(())
836 }
837
838 fn encoded_len(&self) -> Option<usize> {
839 let mut len = self.measurement_share.encoded_len()? + self.proofs_share.encoded_len()?;
840 if let Some(ref blind) = self.joint_rand_blind {
841 len += blind.encoded_len()?;
842 }
843 Some(len)
844 }
845 }
846
847 impl<'a, T, P, const SEED_SIZE: usize> ParameterizedDecode<(&'a Prio3<T, P, SEED_SIZE>, usize)>
848 for Prio3InputShare<T::Field, SEED_SIZE>
849 where
850 T: Type,
851 P: Xof<SEED_SIZE>,
852 {
853 fn decode_with_param(
854 (prio3, agg_id): &(&'a Prio3<T, P, SEED_SIZE>, usize),
855 bytes: &mut Cursor<&[u8]>,
856 ) -> Result<Self, CodecError> {
857 let agg_id = prio3
858 .role_try_from(*agg_id)
859 .map_err(|e| CodecError::Other(Box::new(e)))?;
860 let (input_decoder, proof_decoder) = if agg_id == 0 {
861 (
862 ShareDecodingParameter::Leader(prio3.typ.input_len()),
863 ShareDecodingParameter::Leader(prio3.typ.proof_len() * prio3.num_proofs()),
864 )
865 } else {
866 (
867 ShareDecodingParameter::Helper,
868 ShareDecodingParameter::Helper,
869 )
870 };
871
872 let measurement_share = Share::decode_with_param(&input_decoder, bytes)?;
873 let proofs_share = Share::decode_with_param(&proof_decoder, bytes)?;
874 let joint_rand_blind = if prio3.typ.joint_rand_len() > 0 {
875 let blind = Seed::decode(bytes)?;
876 Some(blind)
877 } else {
878 None
879 };
880
881 Ok(Prio3InputShare {
882 measurement_share,
883 proofs_share,
884 joint_rand_blind,
885 })
886 }
887 }
888
889 #[derive(Clone, Debug)]
890 /// Message broadcast by each [`Aggregator`] in each round of the Preparation phase.
891 pub struct Prio3PrepareShare<F, const SEED_SIZE: usize> {
892 /// A share of the FLP verifier message. (See [`Type`].)
893 verifiers: Vec<F>,
894
895 /// A part of the joint randomness seed.
896 joint_rand_part: Option<Seed<SEED_SIZE>>,
897 }
898
899 impl<F: ConstantTimeEq, const SEED_SIZE: usize> PartialEq for Prio3PrepareShare<F, SEED_SIZE> {
900 fn eq(&self, other: &Self) -> bool {
901 self.ct_eq(other).into()
902 }
903 }
904
905 impl<F: ConstantTimeEq, const SEED_SIZE: usize> Eq for Prio3PrepareShare<F, SEED_SIZE> {}
906
907 impl<F: ConstantTimeEq, const SEED_SIZE: usize> ConstantTimeEq for Prio3PrepareShare<F, SEED_SIZE> {
908 fn ct_eq(&self, other: &Self) -> Choice {
909 // We allow short-circuiting on the presence or absence of the joint_rand_part.
910 option_ct_eq(
911 self.joint_rand_part.as_ref(),
912 other.joint_rand_part.as_ref(),
913 ) & self.verifiers.ct_eq(&other.verifiers)
914 }
915 }
916
917 impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize> Encode
918 for Prio3PrepareShare<F, SEED_SIZE>
919 {
920 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
921 for x in &self.verifiers {
922 x.encode(bytes)?;
923 }
924 if let Some(ref seed) = self.joint_rand_part {
925 seed.encode(bytes)?;
926 }
927 Ok(())
928 }
929
930 fn encoded_len(&self) -> Option<usize> {
931 // Each element of the verifier has the same size.
932 let mut len = F::ENCODED_SIZE * self.verifiers.len();
933 if let Some(ref seed) = self.joint_rand_part {
934 len += seed.encoded_len()?;
935 }
936 Some(len)
937 }
938 }
939
940 impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize>
941 ParameterizedDecode<Prio3PrepareState<F, SEED_SIZE>> for Prio3PrepareShare<F, SEED_SIZE>
942 {
943 fn decode_with_param(
944 decoding_parameter: &Prio3PrepareState<F, SEED_SIZE>,
945 bytes: &mut Cursor<&[u8]>,
946 ) -> Result<Self, CodecError> {
947 let mut verifiers = Vec::with_capacity(decoding_parameter.verifiers_len);
948 for _ in 0..decoding_parameter.verifiers_len {
949 verifiers.push(F::decode(bytes)?);
950 }
951
952 let joint_rand_part = if decoding_parameter.joint_rand_seed.is_some() {
953 Some(Seed::decode(bytes)?)
954 } else {
955 None
956 };
957
958 Ok(Prio3PrepareShare {
959 verifiers,
960 joint_rand_part,
961 })
962 }
963 }
964
965 #[derive(Clone, Debug)]
966 /// Result of combining a round of [`Prio3PrepareShare`] messages.
967 pub struct Prio3PrepareMessage<const SEED_SIZE: usize> {
968 /// The joint randomness seed computed by the Aggregators.
969 joint_rand_seed: Option<Seed<SEED_SIZE>>,
970 }
971
972 impl<const SEED_SIZE: usize> PartialEq for Prio3PrepareMessage<SEED_SIZE> {
973 fn eq(&self, other: &Self) -> bool {
974 self.ct_eq(other).into()
975 }
976 }
977
978 impl<const SEED_SIZE: usize> Eq for Prio3PrepareMessage<SEED_SIZE> {}
979
980 impl<const SEED_SIZE: usize> ConstantTimeEq for Prio3PrepareMessage<SEED_SIZE> {
981 fn ct_eq(&self, other: &Self) -> Choice {
982 // We allow short-circuiting on the presnce or absence of the joint_rand_seed.
983 option_ct_eq(
984 self.joint_rand_seed.as_ref(),
985 other.joint_rand_seed.as_ref(),
986 )
987 }
988 }
989
990 impl<const SEED_SIZE: usize> Encode for Prio3PrepareMessage<SEED_SIZE> {
991 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
992 if let Some(ref seed) = self.joint_rand_seed {
993 seed.encode(bytes)?;
994 }
995 Ok(())
996 }
997
998 fn encoded_len(&self) -> Option<usize> {
999 if let Some(ref seed) = self.joint_rand_seed {
1000 seed.encoded_len()
1001 } else {
1002 Some(0)
1003 }
1004 }
1005 }
1006
1007 impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize>
1008 ParameterizedDecode<Prio3PrepareState<F, SEED_SIZE>> for Prio3PrepareMessage<SEED_SIZE>
1009 {
1010 fn decode_with_param(
1011 decoding_parameter: &Prio3PrepareState<F, SEED_SIZE>,
1012 bytes: &mut Cursor<&[u8]>,
1013 ) -> Result<Self, CodecError> {
1014 let joint_rand_seed = if decoding_parameter.joint_rand_seed.is_some() {
1015 Some(Seed::decode(bytes)?)
1016 } else {
1017 None
1018 };
1019
1020 Ok(Prio3PrepareMessage { joint_rand_seed })
1021 }
1022 }
1023
1024 impl<T, P, const SEED_SIZE: usize> Client<16> for Prio3<T, P, SEED_SIZE>
1025 where
1026 T: Type,
1027 P: Xof<SEED_SIZE>,
1028 {
1029 #[allow(clippy::type_complexity)]
1030 fn shard(
1031 &self,
1032 measurement: &T::Measurement,
1033 nonce: &[u8; 16],
1034 ) -> Result<(Self::PublicShare, Vec<Prio3InputShare<T::Field, SEED_SIZE>>), VdafError> {
1035 let mut random = vec![0u8; self.random_size()];
1036 getrandom::getrandom(&mut random)?;
1037 self.shard_with_random(measurement, nonce, &random)
1038 }
1039 }
1040
1041 /// State of each [`Aggregator`] during the Preparation phase.
1042 #[derive(Clone)]
1043 pub struct Prio3PrepareState<F, const SEED_SIZE: usize> {
1044 measurement_share: Share<F, SEED_SIZE>,
1045 joint_rand_seed: Option<Seed<SEED_SIZE>>,
1046 agg_id: u8,
1047 verifiers_len: usize,
1048 }
1049
1050 impl<F: ConstantTimeEq, const SEED_SIZE: usize> PartialEq for Prio3PrepareState<F, SEED_SIZE> {
1051 fn eq(&self, other: &Self) -> bool {
1052 self.ct_eq(other).into()
1053 }
1054 }
1055
1056 impl<F: ConstantTimeEq, const SEED_SIZE: usize> Eq for Prio3PrepareState<F, SEED_SIZE> {}
1057
1058 impl<F: ConstantTimeEq, const SEED_SIZE: usize> ConstantTimeEq for Prio3PrepareState<F, SEED_SIZE> {
1059 fn ct_eq(&self, other: &Self) -> Choice {
1060 // We allow short-circuiting on the presence or absence of the joint_rand_seed, as well as
1061 // the aggregator ID & verifier length parameters.
1062 if self.agg_id != other.agg_id || self.verifiers_len != other.verifiers_len {
1063 return Choice::from(0);
1064 }
1065
1066 option_ct_eq(
1067 self.joint_rand_seed.as_ref(),
1068 other.joint_rand_seed.as_ref(),
1069 ) & self.measurement_share.ct_eq(&other.measurement_share)
1070 }
1071 }
1072
1073 impl<F, const SEED_SIZE: usize> Debug for Prio3PrepareState<F, SEED_SIZE> {
1074 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1075 f.debug_struct("Prio3PrepareState")
1076 .field("measurement_share", &"[redacted]")
1077 .field(
1078 "joint_rand_seed",
1079 match self.joint_rand_seed {
1080 Some(_) => &"Some([redacted])",
1081 None => &"None",
1082 },
1083 )
1084 .field("agg_id", &self.agg_id)
1085 .field("verifiers_len", &self.verifiers_len)
1086 .finish()
1087 }
1088 }
1089
1090 impl<F: FftFriendlyFieldElement, const SEED_SIZE: usize> Encode
1091 for Prio3PrepareState<F, SEED_SIZE>
1092 {
1093 /// Append the encoded form of this object to the end of `bytes`, growing the vector as needed.
1094 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
1095 self.measurement_share.encode(bytes)?;
1096 if let Some(ref seed) = self.joint_rand_seed {
1097 seed.encode(bytes)?;
1098 }
1099 Ok(())
1100 }
1101
1102 fn encoded_len(&self) -> Option<usize> {
1103 let mut len = self.measurement_share.encoded_len()?;
1104 if let Some(ref seed) = self.joint_rand_seed {
1105 len += seed.encoded_len()?;
1106 }
1107 Some(len)
1108 }
1109 }
1110
1111 impl<'a, T, P, const SEED_SIZE: usize> ParameterizedDecode<(&'a Prio3<T, P, SEED_SIZE>, usize)>
1112 for Prio3PrepareState<T::Field, SEED_SIZE>
1113 where
1114 T: Type,
1115 P: Xof<SEED_SIZE>,
1116 {
1117 fn decode_with_param(
1118 (prio3, agg_id): &(&'a Prio3<T, P, SEED_SIZE>, usize),
1119 bytes: &mut Cursor<&[u8]>,
1120 ) -> Result<Self, CodecError> {
1121 let agg_id = prio3
1122 .role_try_from(*agg_id)
1123 .map_err(|e| CodecError::Other(Box::new(e)))?;
1124
1125 let share_decoder = if agg_id == 0 {
1126 ShareDecodingParameter::Leader(prio3.typ.input_len())
1127 } else {
1128 ShareDecodingParameter::Helper
1129 };
1130 let measurement_share = Share::decode_with_param(&share_decoder, bytes)?;
1131
1132 let joint_rand_seed = if prio3.typ.joint_rand_len() > 0 {
1133 Some(Seed::decode(bytes)?)
1134 } else {
1135 None
1136 };
1137
1138 Ok(Self {
1139 measurement_share,
1140 joint_rand_seed,
1141 agg_id,
1142 verifiers_len: prio3.typ.verifier_len() * prio3.num_proofs(),
1143 })
1144 }
1145 }
1146
1147 impl<T, P, const SEED_SIZE: usize> Aggregator<SEED_SIZE, 16> for Prio3<T, P, SEED_SIZE>
1148 where
1149 T: Type,
1150 P: Xof<SEED_SIZE>,
1151 {
1152 type PrepareState = Prio3PrepareState<T::Field, SEED_SIZE>;
1153 type PrepareShare = Prio3PrepareShare<T::Field, SEED_SIZE>;
1154 type PrepareMessage = Prio3PrepareMessage<SEED_SIZE>;
1155
1156 /// Begins the Prep process with the other aggregators. The result of this process is
1157 /// the aggregator's output share.
1158 #[allow(clippy::type_complexity)]
1159 fn prepare_init(
1160 &self,
1161 verify_key: &[u8; SEED_SIZE],
1162 agg_id: usize,
1163 _agg_param: &Self::AggregationParam,
1164 nonce: &[u8; 16],
1165 public_share: &Self::PublicShare,
1166 msg: &Prio3InputShare<T::Field, SEED_SIZE>,
1167 ) -> Result<
1168 (
1169 Prio3PrepareState<T::Field, SEED_SIZE>,
1170 Prio3PrepareShare<T::Field, SEED_SIZE>,
1171 ),
1172 VdafError,
1173 > {
1174 let agg_id = self.role_try_from(agg_id)?;
1175
1176 // Create a reference to the (expanded) measurement share.
1177 let expanded_measurement_share: Option<Vec<T::Field>> = match msg.measurement_share {
1178 Share::Leader(_) => None,
1179 Share::Helper(ref seed) => Some(
1180 P::seed_stream(
1181 seed,
1182 &self.domain_separation_tag(DST_MEASUREMENT_SHARE),
1183 &[agg_id],
1184 )
1185 .into_field_vec(self.typ.input_len()),
1186 ),
1187 };
1188 let measurement_share = match msg.measurement_share {
1189 Share::Leader(ref data) => data,
1190 Share::Helper(_) => expanded_measurement_share.as_ref().unwrap(),
1191 };
1192
1193 // Create a reference to the (expanded) proof share.
1194 let expanded_proofs_share: Option<Vec<T::Field>> = match msg.proofs_share {
1195 Share::Leader(_) => None,
1196 Share::Helper(ref proof_shares_seed) => Some(
1197 self.derive_helper_proofs_share(proof_shares_seed, agg_id)
1198 .take(self.typ.proof_len() * self.num_proofs())
1199 .collect(),
1200 ),
1201 };
1202 let proofs_share = match msg.proofs_share {
1203 Share::Leader(ref data) => data,
1204 Share::Helper(_) => expanded_proofs_share.as_ref().unwrap(),
1205 };
1206
1207 // Compute the joint randomness.
1208 let (joint_rand_seed, joint_rand_part, joint_rands) = if self.typ.joint_rand_len() > 0 {
1209 let mut joint_rand_part_xof = P::init(
1210 msg.joint_rand_blind.as_ref().unwrap().as_ref(),
1211 &self.domain_separation_tag(DST_JOINT_RAND_PART),
1212 );
1213 joint_rand_part_xof.update(&[agg_id]);
1214 joint_rand_part_xof.update(nonce);
1215 let mut encoding_buffer = Vec::with_capacity(T::Field::ENCODED_SIZE);
1216 for x in measurement_share {
1217 x.encode(&mut encoding_buffer).map_err(|_| {
1218 VdafError::Uncategorized("failed to encode measurement share".to_string())
1219 })?;
1220 joint_rand_part_xof.update(&encoding_buffer);
1221 encoding_buffer.clear();
1222 }
1223 let own_joint_rand_part = joint_rand_part_xof.into_seed();
1224
1225 // Make an iterator over the joint randomness parts, but use this aggregator's
1226 // contribution, computed from the input share, in lieu of the the corresponding part
1227 // from the public share.
1228 //
1229 // The locally computed part should match the part from the public share for honestly
1230 // generated reports. If they do not match, the joint randomness seed check during the
1231 // next round of preparation should fail.
1232 let corrected_joint_rand_parts = public_share
1233 .joint_rand_parts
1234 .iter()
1235 .flatten()
1236 .take(agg_id as usize)
1237 .chain(iter::once(&own_joint_rand_part))
1238 .chain(
1239 public_share
1240 .joint_rand_parts
1241 .iter()
1242 .flatten()
1243 .skip(agg_id as usize + 1),
1244 );
1245
1246 let (joint_rand_seed, joint_rands) =
1247 self.derive_joint_rands(corrected_joint_rand_parts);
1248
1249 (
1250 Some(joint_rand_seed),
1251 Some(own_joint_rand_part),
1252 joint_rands,
1253 )
1254 } else {
1255 (None, None, Vec::new())
1256 };
1257
1258 // Run the query-generation algorithm.
1259 let query_rands = self.derive_query_rands(verify_key, nonce);
1260 let mut verifiers_share = Vec::with_capacity(self.typ.verifier_len() * self.num_proofs());
1261 for p in 0..self.num_proofs() {
1262 let query_rand =
1263 &query_rands[p * self.typ.query_rand_len()..(p + 1) * self.typ.query_rand_len()];
1264 let joint_rand =
1265 &joint_rands[p * self.typ.joint_rand_len()..(p + 1) * self.typ.joint_rand_len()];
1266 let proof_share =
1267 &proofs_share[p * self.typ.proof_len()..(p + 1) * self.typ.proof_len()];
1268
1269 verifiers_share.append(&mut self.typ.query(
1270 measurement_share,
1271 proof_share,
1272 query_rand,
1273 joint_rand,
1274 self.num_aggregators as usize,
1275 )?);
1276 }
1277
1278 Ok((
1279 Prio3PrepareState {
1280 measurement_share: msg.measurement_share.clone(),
1281 joint_rand_seed,
1282 agg_id,
1283 verifiers_len: verifiers_share.len(),
1284 },
1285 Prio3PrepareShare {
1286 verifiers: verifiers_share,
1287 joint_rand_part,
1288 },
1289 ))
1290 }
1291
1292 fn prepare_shares_to_prepare_message<
1293 M: IntoIterator<Item = Prio3PrepareShare<T::Field, SEED_SIZE>>,
1294 >(
1295 &self,
1296 _: &Self::AggregationParam,
1297 inputs: M,
1298 ) -> Result<Prio3PrepareMessage<SEED_SIZE>, VdafError> {
1299 let mut verifiers = vec![T::Field::zero(); self.typ.verifier_len() * self.num_proofs()];
1300 let mut joint_rand_parts = Vec::with_capacity(self.num_aggregators());
1301 let mut count = 0;
1302 for share in inputs.into_iter() {
1303 count += 1;
1304
1305 if share.verifiers.len() != verifiers.len() {
1306 return Err(VdafError::Uncategorized(format!(
1307 "unexpected verifier share length: got {}; want {}",
1308 share.verifiers.len(),
1309 verifiers.len(),
1310 )));
1311 }
1312
1313 if self.typ.joint_rand_len() > 0 {
1314 let joint_rand_seed_part = share.joint_rand_part.unwrap();
1315 joint_rand_parts.push(joint_rand_seed_part);
1316 }
1317
1318 for (x, y) in verifiers.iter_mut().zip(share.verifiers) {
1319 *x += y;
1320 }
1321 }
1322
1323 if count != self.num_aggregators {
1324 return Err(VdafError::Uncategorized(format!(
1325 "unexpected message count: got {}; want {}",
1326 count, self.num_aggregators,
1327 )));
1328 }
1329
1330 // Check the proof verifiers.
1331 for verifier in verifiers.chunks(self.typ.verifier_len()) {
1332 if !self.typ.decide(verifier)? {
1333 return Err(VdafError::Uncategorized(
1334 "proof verifier check failed".into(),
1335 ));
1336 }
1337 }
1338
1339 let joint_rand_seed = if self.typ.joint_rand_len() > 0 {
1340 Some(self.derive_joint_rand_seed(joint_rand_parts.iter()))
1341 } else {
1342 None
1343 };
1344
1345 Ok(Prio3PrepareMessage { joint_rand_seed })
1346 }
1347
1348 fn prepare_next(
1349 &self,
1350 step: Prio3PrepareState<T::Field, SEED_SIZE>,
1351 msg: Prio3PrepareMessage<SEED_SIZE>,
1352 ) -> Result<PrepareTransition<Self, SEED_SIZE, 16>, VdafError> {
1353 if self.typ.joint_rand_len() > 0 {
1354 // Check that the joint randomness was correct.
1355 if step
1356 .joint_rand_seed
1357 .as_ref()
1358 .unwrap()
1359 .ct_ne(msg.joint_rand_seed.as_ref().unwrap())
1360 .into()
1361 {
1362 return Err(VdafError::Uncategorized(
1363 "joint randomness mismatch".to_string(),
1364 ));
1365 }
1366 }
1367
1368 // Compute the output share.
1369 let measurement_share = match step.measurement_share {
1370 Share::Leader(data) => data,
1371 Share::Helper(seed) => {
1372 let dst = self.domain_separation_tag(DST_MEASUREMENT_SHARE);
1373 P::seed_stream(&seed, &dst, &[step.agg_id]).into_field_vec(self.typ.input_len())
1374 }
1375 };
1376
1377 let output_share = match self.typ.truncate(measurement_share) {
1378 Ok(data) => OutputShare(data),
1379 Err(err) => {
1380 return Err(VdafError::from(err));
1381 }
1382 };
1383
1384 Ok(PrepareTransition::Finish(output_share))
1385 }
1386
1387 /// Aggregates a sequence of output shares into an aggregate share.
1388 fn aggregate<It: IntoIterator<Item = OutputShare<T::Field>>>(
1389 &self,
1390 _agg_param: &(),
1391 output_shares: It,
1392 ) -> Result<AggregateShare<T::Field>, VdafError> {
1393 let mut agg_share = AggregateShare(vec![T::Field::zero(); self.typ.output_len()]);
1394 for output_share in output_shares.into_iter() {
1395 agg_share.accumulate(&output_share)?;
1396 }
1397
1398 Ok(agg_share)
1399 }
1400 }
1401
1402 #[cfg(feature = "experimental")]
1403 impl<T, P, S, const SEED_SIZE: usize> AggregatorWithNoise<SEED_SIZE, 16, S>
1404 for Prio3<T, P, SEED_SIZE>
1405 where
1406 T: TypeWithNoise<S>,
1407 P: Xof<SEED_SIZE>,
1408 S: DifferentialPrivacyStrategy,
1409 {
1410 fn add_noise_to_agg_share(
1411 &self,
1412 dp_strategy: &S,
1413 _agg_param: &Self::AggregationParam,
1414 agg_share: &mut Self::AggregateShare,
1415 num_measurements: usize,
1416 ) -> Result<(), VdafError> {
1417 self.typ
1418 .add_noise_to_result(dp_strategy, &mut agg_share.0, num_measurements)?;
1419 Ok(())
1420 }
1421 }
1422
1423 impl<T, P, const SEED_SIZE: usize> Collector for Prio3<T, P, SEED_SIZE>
1424 where
1425 T: Type,
1426 P: Xof<SEED_SIZE>,
1427 {
1428 /// Combines aggregate shares into the aggregate result.
1429 fn unshard<It: IntoIterator<Item = AggregateShare<T::Field>>>(
1430 &self,
1431 _agg_param: &Self::AggregationParam,
1432 agg_shares: It,
1433 num_measurements: usize,
1434 ) -> Result<T::AggregateResult, VdafError> {
1435 let mut agg = AggregateShare(vec![T::Field::zero(); self.typ.output_len()]);
1436 for agg_share in agg_shares.into_iter() {
1437 agg.merge(&agg_share)?;
1438 }
1439
1440 Ok(self.typ.decode_result(&agg.0, num_measurements)?)
1441 }
1442 }
1443
1444 #[derive(Clone)]
1445 struct HelperShare<const SEED_SIZE: usize> {
1446 measurement_share: Seed<SEED_SIZE>,
1447 proofs_share: Seed<SEED_SIZE>,
1448 joint_rand_blind: Option<Seed<SEED_SIZE>>,
1449 }
1450
1451 impl<const SEED_SIZE: usize> HelperShare<SEED_SIZE> {
1452 fn from_seeds(
1453 measurement_share: [u8; SEED_SIZE],
1454 proof_share: [u8; SEED_SIZE],
1455 joint_rand_blind: Option<[u8; SEED_SIZE]>,
1456 ) -> Self {
1457 HelperShare {
1458 measurement_share: Seed::from_bytes(measurement_share),
1459 proofs_share: Seed::from_bytes(proof_share),
1460 joint_rand_blind: joint_rand_blind.map(Seed::from_bytes),
1461 }
1462 }
1463 }
1464
1465 fn check_num_aggregators(num_aggregators: u8) -> Result<(), VdafError> {
1466 if num_aggregators == 0 {
1467 return Err(VdafError::Uncategorized(format!(
1468 "at least one aggregator is required; got {num_aggregators}"
1469 )));
1470 } else if num_aggregators > 254 {
1471 return Err(VdafError::Uncategorized(format!(
1472 "number of aggregators must not exceed 254; got {num_aggregators}"
1473 )));
1474 }
1475
1476 Ok(())
1477 }
1478
1479 impl<'a, F, T, P, const SEED_SIZE: usize> ParameterizedDecode<(&'a Prio3<T, P, SEED_SIZE>, &'a ())>
1480 for OutputShare<F>
1481 where
1482 F: FieldElement,
1483 T: Type,
1484 P: Xof<SEED_SIZE>,
1485 {
1486 fn decode_with_param(
1487 (vdaf, _): &(&'a Prio3<T, P, SEED_SIZE>, &'a ()),
1488 bytes: &mut Cursor<&[u8]>,
1489 ) -> Result<Self, CodecError> {
1490 decode_fieldvec(vdaf.output_len(), bytes).map(Self)
1491 }
1492 }
1493
1494 impl<'a, F, T, P, const SEED_SIZE: usize> ParameterizedDecode<(&'a Prio3<T, P, SEED_SIZE>, &'a ())>
1495 for AggregateShare<F>
1496 where
1497 F: FieldElement,
1498 T: Type,
1499 P: Xof<SEED_SIZE>,
1500 {
1501 fn decode_with_param(
1502 (vdaf, _): &(&'a Prio3<T, P, SEED_SIZE>, &'a ()),
1503 bytes: &mut Cursor<&[u8]>,
1504 ) -> Result<Self, CodecError> {
1505 decode_fieldvec(vdaf.output_len(), bytes).map(Self)
1506 }
1507 }
1508
1509 // This function determines equality between two optional, constant-time comparable values. It
1510 // short-circuits on the existence (but not contents) of the values -- a timing side-channel may
1511 // reveal whether the values match on Some or None.
1512 #[inline]
1513 fn option_ct_eq<T>(left: Option<&T>, right: Option<&T>) -> Choice
1514 where
1515 T: ConstantTimeEq + ?Sized,
1516 {
1517 match (left, right) {
1518 (Some(left), Some(right)) => left.ct_eq(right),
1519 (None, None) => Choice::from(1),
1520 _ => Choice::from(0),
1521 }
1522 }
1523
1524 /// This is a polyfill for `usize::ilog2()`, which is only available in Rust 1.67 and later. It is
1525 /// based on the implementation in the standard library. It can be removed when the MSRV has been
1526 /// advanced past 1.67.
1527 ///
1528 /// # Panics
1529 ///
1530 /// This function will panic if `input` is zero.
1531 fn ilog2(input: usize) -> u32 {
1532 if input == 0 {
1533 panic!("Tried to take the logarithm of zero");
1534 }
1535 (usize::BITS - 1) - input.leading_zeros()
1536 }
1537
1538 /// Finds the optimal choice of chunk length for [`Prio3Histogram`] or [`Prio3SumVec`], given its
1539 /// encoded measurement length. For [`Prio3Histogram`], the measurement length is equal to the
1540 /// length parameter. For [`Prio3SumVec`], the measurement length is equal to the product of the
1541 /// length and bits parameters.
1542 pub fn optimal_chunk_length(measurement_length: usize) -> usize {
1543 if measurement_length <= 1 {
1544 return 1;
1545 }
1546
1547 /// Candidate set of parameter choices for the parallel sum optimization.
1548 struct Candidate {
1549 gadget_calls: usize,
1550 chunk_length: usize,
1551 }
1552
1553 let max_log2 = ilog2(measurement_length + 1);
1554 let best_opt = (1..=max_log2)
1555 .rev()
1556 .map(|log2| {
1557 let gadget_calls = (1 << log2) - 1;
1558 let chunk_length = (measurement_length + gadget_calls - 1) / gadget_calls;
1559 Candidate {
1560 gadget_calls,
1561 chunk_length,
1562 }
1563 })
1564 .min_by_key(|candidate| {
1565 // Compute the proof length, in field elements, for either Prio3Histogram or Prio3SumVec
1566 (candidate.chunk_length * 2)
1567 + 2 * ((1 + candidate.gadget_calls).next_power_of_two() - 1)
1568 });
1569 // Unwrap safety: max_log2 must be at least 1, because smaller measurement_length inputs are
1570 // dealt with separately. Thus, the range iterator that the search is over will be nonempty,
1571 // and min_by_key() will always return Some.
1572 best_opt.unwrap().chunk_length
1573 }
1574
1575 #[cfg(test)]
1576 mod tests {
1577 use super::*;
1578 #[cfg(feature = "experimental")]
1579 use crate::flp::gadgets::ParallelSumGadget;
1580 use crate::vdaf::{
1581 equality_comparison_test, fieldvec_roundtrip_test,
1582 test_utils::{run_vdaf, run_vdaf_prepare},
1583 };
1584 use assert_matches::assert_matches;
1585 #[cfg(feature = "experimental")]
1586 use fixed::{
1587 types::extra::{U15, U31, U63},
1588 FixedI16, FixedI32, FixedI64,
1589 };
1590 #[cfg(feature = "experimental")]
1591 use fixed_macro::fixed;
1592 use rand::prelude::*;
1593
1594 #[test]
1595 fn test_prio3_count() {
1596 let prio3 = Prio3::new_count(2).unwrap();
1597
1598 assert_eq!(
1599 run_vdaf(&prio3, &(), [true, false, false, true, true]).unwrap(),
1600 3
1601 );
1602
1603 let mut nonce = [0; 16];
1604 let mut verify_key = [0; 16];
1605 thread_rng().fill(&mut verify_key[..]);
1606 thread_rng().fill(&mut nonce[..]);
1607
1608 let (public_share, input_shares) = prio3.shard(&false, &nonce).unwrap();
1609 run_vdaf_prepare(&prio3, &verify_key, &(), &nonce, public_share, input_shares).unwrap();
1610
1611 let (public_share, input_shares) = prio3.shard(&true, &nonce).unwrap();
1612 run_vdaf_prepare(&prio3, &verify_key, &(), &nonce, public_share, input_shares).unwrap();
1613
1614 test_serialization(&prio3, &true, &nonce).unwrap();
1615
1616 let prio3_extra_helper = Prio3::new_count(3).unwrap();
1617 assert_eq!(
1618 run_vdaf(&prio3_extra_helper, &(), [true, false, false, true, true]).unwrap(),
1619 3,
1620 );
1621 }
1622
1623 #[test]
1624 fn test_prio3_sum() {
1625 let prio3 = Prio3::new_sum(3, 16).unwrap();
1626
1627 assert_eq!(
1628 run_vdaf(&prio3, &(), [0, (1 << 16) - 1, 0, 1, 1]).unwrap(),
1629 (1 << 16) + 1
1630 );
1631
1632 let mut verify_key = [0; 16];
1633 thread_rng().fill(&mut verify_key[..]);
1634 let nonce = [0; 16];
1635
1636 let (public_share, mut input_shares) = prio3.shard(&1, &nonce).unwrap();
1637 input_shares[0].joint_rand_blind.as_mut().unwrap().0[0] ^= 255;
1638 let result = run_vdaf_prepare(&prio3, &verify_key, &(), &nonce, public_share, input_shares);
1639 assert_matches!(result, Err(VdafError::Uncategorized(_)));
1640
1641 let (public_share, mut input_shares) = prio3.shard(&1, &nonce).unwrap();
1642 assert_matches!(input_shares[0].measurement_share, Share::Leader(ref mut data) => {
1643 data[0] += Field128::one();
1644 });
1645 let result = run_vdaf_prepare(&prio3, &verify_key, &(), &nonce, public_share, input_shares);
1646 assert_matches!(result, Err(VdafError::Uncategorized(_)));
1647
1648 let (public_share, mut input_shares) = prio3.shard(&1, &nonce).unwrap();
1649 assert_matches!(input_shares[0].proofs_share, Share::Leader(ref mut data) => {
1650 data[0] += Field128::one();
1651 });
1652 let result = run_vdaf_prepare(&prio3, &verify_key, &(), &nonce, public_share, input_shares);
1653 assert_matches!(result, Err(VdafError::Uncategorized(_)));
1654
1655 test_serialization(&prio3, &1, &nonce).unwrap();
1656 }
1657
1658 #[test]
1659 fn test_prio3_sum_vec() {
1660 let prio3 = Prio3::new_sum_vec(2, 2, 20, 4).unwrap();
1661 assert_eq!(
1662 run_vdaf(
1663 &prio3,
1664 &(),
1665 [
1666 vec![0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1],
1667 vec![0, 2, 0, 0, 1, 0, 0, 0, 1, 1, 1, 3, 0, 3, 0, 0, 0, 1, 0, 0],
1668 vec![1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1],
1669 ]
1670 )
1671 .unwrap(),
1672 vec![1, 3, 1, 0, 3, 1, 0, 1, 2, 2, 3, 3, 1, 5, 1, 2, 1, 3, 0, 2],
1673 );
1674 }
1675
1676 #[test]
1677 fn test_prio3_sum_vec_multiproof() {
1678 let prio3 = Prio3::<
1679 SumVec<Field128, ParallelSum<Field128, Mul<Field128>>>,
1680 XofTurboShake128,
1681 16,
1682 >::new(2, 2, 0xFFFF0000, SumVec::new(2, 20, 4).unwrap())
1683 .unwrap();
1684
1685 assert_eq!(
1686 run_vdaf(
1687 &prio3,
1688 &(),
1689 [
1690 vec![0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1],
1691 vec![0, 2, 0, 0, 1, 0, 0, 0, 1, 1, 1, 3, 0, 3, 0, 0, 0, 1, 0, 0],
1692 vec![1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1],
1693 ]
1694 )
1695 .unwrap(),
1696 vec![1, 3, 1, 0, 3, 1, 0, 1, 2, 2, 3, 3, 1, 5, 1, 2, 1, 3, 0, 2],
1697 );
1698 }
1699
1700 #[test]
1701 #[cfg(feature = "multithreaded")]
1702 fn test_prio3_sum_vec_multithreaded() {
1703 let prio3 = Prio3::new_sum_vec_multithreaded(2, 2, 20, 4).unwrap();
1704 assert_eq!(
1705 run_vdaf(
1706 &prio3,
1707 &(),
1708 [
1709 vec![0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1],
1710 vec![0, 2, 0, 0, 1, 0, 0, 0, 1, 1, 1, 3, 0, 3, 0, 0, 0, 1, 0, 0],
1711 vec![1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1],
1712 ]
1713 )
1714 .unwrap(),
1715 vec![1, 3, 1, 0, 3, 1, 0, 1, 2, 2, 3, 3, 1, 5, 1, 2, 1, 3, 0, 2],
1716 );
1717 }
1718
1719 #[test]
1720 #[cfg(feature = "experimental")]
1721 fn test_prio3_bounded_fpvec_sum_unaligned() {
1722 type P<Fx> = Prio3FixedPointBoundedL2VecSum<Fx>;
1723 #[cfg(feature = "multithreaded")]
1724 type PM<Fx> = Prio3FixedPointBoundedL2VecSumMultithreaded<Fx>;
1725 let ctor_32 = P::<FixedI32<U31>>::new_fixedpoint_boundedl2_vec_sum;
1726 #[cfg(feature = "multithreaded")]
1727 let ctor_mt_32 = PM::<FixedI32<U31>>::new_fixedpoint_boundedl2_vec_sum_multithreaded;
1728
1729 {
1730 const SIZE: usize = 5;
1731 let fp32_0 = fixed!(0: I1F31);
1732
1733 // 32 bit fixedpoint, non-power-of-2 vector, single-threaded
1734 {
1735 let prio3_32 = ctor_32(2, SIZE).unwrap();
1736 test_fixed_vec::<_, _, _, SIZE>(fp32_0, prio3_32);
1737 }
1738
1739 // 32 bit fixedpoint, non-power-of-2 vector, multi-threaded
1740 #[cfg(feature = "multithreaded")]
1741 {
1742 let prio3_mt_32 = ctor_mt_32(2, SIZE).unwrap();
1743 test_fixed_vec::<_, _, _, SIZE>(fp32_0, prio3_mt_32);
1744 }
1745 }
1746
1747 fn test_fixed_vec<Fx, PE, M, const SIZE: usize>(
1748 fp_0: Fx,
1749 prio3: Prio3<FixedPointBoundedL2VecSum<Fx, PE, M>, XofTurboShake128, 16>,
1750 ) where
1751 Fx: Fixed + CompatibleFloat + std::ops::Neg<Output = Fx>,
1752 PE: Eq + ParallelSumGadget<Field128, PolyEval<Field128>> + Clone + 'static,
1753 M: Eq + ParallelSumGadget<Field128, Mul<Field128>> + Clone + 'static,
1754 {
1755 let fp_vec = vec![fp_0; SIZE];
1756
1757 let measurements = [fp_vec.clone(), fp_vec];
1758 assert_eq!(
1759 run_vdaf(&prio3, &(), measurements).unwrap(),
1760 vec![0.0; SIZE]
1761 );
1762 }
1763 }
1764
1765 #[test]
1766 #[cfg(feature = "experimental")]
1767 fn test_prio3_bounded_fpvec_sum() {
1768 type P<Fx> = Prio3FixedPointBoundedL2VecSum<Fx>;
1769 let ctor_16 = P::<FixedI16<U15>>::new_fixedpoint_boundedl2_vec_sum;
1770 let ctor_32 = P::<FixedI32<U31>>::new_fixedpoint_boundedl2_vec_sum;
1771 let ctor_64 = P::<FixedI64<U63>>::new_fixedpoint_boundedl2_vec_sum;
1772
1773 #[cfg(feature = "multithreaded")]
1774 type PM<Fx> = Prio3FixedPointBoundedL2VecSumMultithreaded<Fx>;
1775 #[cfg(feature = "multithreaded")]
1776 let ctor_mt_16 = PM::<FixedI16<U15>>::new_fixedpoint_boundedl2_vec_sum_multithreaded;
1777 #[cfg(feature = "multithreaded")]
1778 let ctor_mt_32 = PM::<FixedI32<U31>>::new_fixedpoint_boundedl2_vec_sum_multithreaded;
1779 #[cfg(feature = "multithreaded")]
1780 let ctor_mt_64 = PM::<FixedI64<U63>>::new_fixedpoint_boundedl2_vec_sum_multithreaded;
1781
1782 {
1783 // 16 bit fixedpoint
1784 let fp16_4_inv = fixed!(0.25: I1F15);
1785 let fp16_8_inv = fixed!(0.125: I1F15);
1786 let fp16_16_inv = fixed!(0.0625: I1F15);
1787
1788 // two aggregators, three entries per vector.
1789 {
1790 let prio3_16 = ctor_16(2, 3).unwrap();
1791 test_fixed(fp16_4_inv, fp16_8_inv, fp16_16_inv, prio3_16);
1792 }
1793
1794 #[cfg(feature = "multithreaded")]
1795 {
1796 let prio3_16_mt = ctor_mt_16(2, 3).unwrap();
1797 test_fixed(fp16_4_inv, fp16_8_inv, fp16_16_inv, prio3_16_mt);
1798 }
1799 }
1800
1801 {
1802 // 32 bit fixedpoint
1803 let fp32_4_inv = fixed!(0.25: I1F31);
1804 let fp32_8_inv = fixed!(0.125: I1F31);
1805 let fp32_16_inv = fixed!(0.0625: I1F31);
1806
1807 {
1808 let prio3_32 = ctor_32(2, 3).unwrap();
1809 test_fixed(fp32_4_inv, fp32_8_inv, fp32_16_inv, prio3_32);
1810 }
1811
1812 #[cfg(feature = "multithreaded")]
1813 {
1814 let prio3_32_mt = ctor_mt_32(2, 3).unwrap();
1815 test_fixed(fp32_4_inv, fp32_8_inv, fp32_16_inv, prio3_32_mt);
1816 }
1817 }
1818
1819 {
1820 // 64 bit fixedpoint
1821 let fp64_4_inv = fixed!(0.25: I1F63);
1822 let fp64_8_inv = fixed!(0.125: I1F63);
1823 let fp64_16_inv = fixed!(0.0625: I1F63);
1824
1825 {
1826 let prio3_64 = ctor_64(2, 3).unwrap();
1827 test_fixed(fp64_4_inv, fp64_8_inv, fp64_16_inv, prio3_64);
1828 }
1829
1830 #[cfg(feature = "multithreaded")]
1831 {
1832 let prio3_64_mt = ctor_mt_64(2, 3).unwrap();
1833 test_fixed(fp64_4_inv, fp64_8_inv, fp64_16_inv, prio3_64_mt);
1834 }
1835 }
1836
1837 fn test_fixed<Fx, PE, M>(
1838 fp_4_inv: Fx,
1839 fp_8_inv: Fx,
1840 fp_16_inv: Fx,
1841 prio3: Prio3<FixedPointBoundedL2VecSum<Fx, PE, M>, XofTurboShake128, 16>,
1842 ) where
1843 Fx: Fixed + CompatibleFloat + std::ops::Neg<Output = Fx>,
1844 PE: Eq + ParallelSumGadget<Field128, PolyEval<Field128>> + Clone + 'static,
1845 M: Eq + ParallelSumGadget<Field128, Mul<Field128>> + Clone + 'static,
1846 {
1847 let fp_vec1 = vec![fp_4_inv, fp_8_inv, fp_16_inv];
1848 let fp_vec2 = vec![fp_4_inv, fp_8_inv, fp_16_inv];
1849
1850 let fp_vec3 = vec![-fp_4_inv, -fp_8_inv, -fp_16_inv];
1851 let fp_vec4 = vec![-fp_4_inv, -fp_8_inv, -fp_16_inv];
1852
1853 let fp_vec5 = vec![fp_4_inv, -fp_8_inv, -fp_16_inv];
1854 let fp_vec6 = vec![fp_4_inv, fp_8_inv, fp_16_inv];
1855
1856 // positive entries
1857 let fp_list = [fp_vec1, fp_vec2];
1858 assert_eq!(
1859 run_vdaf(&prio3, &(), fp_list).unwrap(),
1860 vec!(0.5, 0.25, 0.125),
1861 );
1862
1863 // negative entries
1864 let fp_list2 = [fp_vec3, fp_vec4];
1865 assert_eq!(
1866 run_vdaf(&prio3, &(), fp_list2).unwrap(),
1867 vec!(-0.5, -0.25, -0.125),
1868 );
1869
1870 // both
1871 let fp_list3 = [fp_vec5, fp_vec6];
1872 assert_eq!(
1873 run_vdaf(&prio3, &(), fp_list3).unwrap(),
1874 vec!(0.5, 0.0, 0.0),
1875 );
1876
1877 let mut verify_key = [0; 16];
1878 let mut nonce = [0; 16];
1879 thread_rng().fill(&mut verify_key);
1880 thread_rng().fill(&mut nonce);
1881
1882 let (public_share, mut input_shares) = prio3
1883 .shard(&vec![fp_4_inv, fp_8_inv, fp_16_inv], &nonce)
1884 .unwrap();
1885 input_shares[0].joint_rand_blind.as_mut().unwrap().0[0] ^= 255;
1886 let result =
1887 run_vdaf_prepare(&prio3, &verify_key, &(), &nonce, public_share, input_shares);
1888 assert_matches!(result, Err(VdafError::Uncategorized(_)));
1889
1890 let (public_share, mut input_shares) = prio3
1891 .shard(&vec![fp_4_inv, fp_8_inv, fp_16_inv], &nonce)
1892 .unwrap();
1893 assert_matches!(input_shares[0].measurement_share, Share::Leader(ref mut data) => {
1894 data[0] += Field128::one();
1895 });
1896 let result =
1897 run_vdaf_prepare(&prio3, &verify_key, &(), &nonce, public_share, input_shares);
1898 assert_matches!(result, Err(VdafError::Uncategorized(_)));
1899
1900 let (public_share, mut input_shares) = prio3
1901 .shard(&vec![fp_4_inv, fp_8_inv, fp_16_inv], &nonce)
1902 .unwrap();
1903 assert_matches!(input_shares[0].proofs_share, Share::Leader(ref mut data) => {
1904 data[0] += Field128::one();
1905 });
1906 let result =
1907 run_vdaf_prepare(&prio3, &verify_key, &(), &nonce, public_share, input_shares);
1908 assert_matches!(result, Err(VdafError::Uncategorized(_)));
1909
1910 test_serialization(&prio3, &vec![fp_4_inv, fp_8_inv, fp_16_inv], &nonce).unwrap();
1911 }
1912 }
1913
1914 #[test]
1915 fn test_prio3_histogram() {
1916 let prio3 = Prio3::new_histogram(2, 4, 2).unwrap();
1917
1918 assert_eq!(
1919 run_vdaf(&prio3, &(), [0, 1, 2, 3]).unwrap(),
1920 vec![1, 1, 1, 1]
1921 );
1922 assert_eq!(run_vdaf(&prio3, &(), [0]).unwrap(), vec![1, 0, 0, 0]);
1923 assert_eq!(run_vdaf(&prio3, &(), [1]).unwrap(), vec![0, 1, 0, 0]);
1924 assert_eq!(run_vdaf(&prio3, &(), [2]).unwrap(), vec![0, 0, 1, 0]);
1925 assert_eq!(run_vdaf(&prio3, &(), [3]).unwrap(), vec![0, 0, 0, 1]);
1926 test_serialization(&prio3, &3, &[0; 16]).unwrap();
1927 }
1928
1929 #[test]
1930 #[cfg(feature = "multithreaded")]
1931 fn test_prio3_histogram_multithreaded() {
1932 let prio3 = Prio3::new_histogram_multithreaded(2, 4, 2).unwrap();
1933
1934 assert_eq!(
1935 run_vdaf(&prio3, &(), [0, 1, 2, 3]).unwrap(),
1936 vec![1, 1, 1, 1]
1937 );
1938 assert_eq!(run_vdaf(&prio3, &(), [0]).unwrap(), vec![1, 0, 0, 0]);
1939 assert_eq!(run_vdaf(&prio3, &(), [1]).unwrap(), vec![0, 1, 0, 0]);
1940 assert_eq!(run_vdaf(&prio3, &(), [2]).unwrap(), vec![0, 0, 1, 0]);
1941 assert_eq!(run_vdaf(&prio3, &(), [3]).unwrap(), vec![0, 0, 0, 1]);
1942 test_serialization(&prio3, &3, &[0; 16]).unwrap();
1943 }
1944
1945 #[test]
1946 fn test_prio3_average() {
1947 let prio3 = Prio3::new_average(2, 64).unwrap();
1948
1949 assert_eq!(run_vdaf(&prio3, &(), [17, 8]).unwrap(), 12.5f64);
1950 assert_eq!(run_vdaf(&prio3, &(), [1, 1, 1, 1]).unwrap(), 1f64);
1951 assert_eq!(run_vdaf(&prio3, &(), [0, 0, 0, 1]).unwrap(), 0.25f64);
1952 assert_eq!(
1953 run_vdaf(&prio3, &(), [1, 11, 111, 1111, 3, 8]).unwrap(),
1954 207.5f64
1955 );
1956 }
1957
1958 #[test]
1959 fn test_prio3_input_share() {
1960 let prio3 = Prio3::new_sum(5, 16).unwrap();
1961 let (_public_share, input_shares) = prio3.shard(&1, &[0; 16]).unwrap();
1962
1963 // Check that seed shares are distinct.
1964 for (i, x) in input_shares.iter().enumerate() {
1965 for (j, y) in input_shares.iter().enumerate() {
1966 if i != j {
1967 if let (Share::Helper(left), Share::Helper(right)) =
1968 (&x.measurement_share, &y.measurement_share)
1969 {
1970 assert_ne!(left, right);
1971 }
1972
1973 if let (Share::Helper(left), Share::Helper(right)) =
1974 (&x.proofs_share, &y.proofs_share)
1975 {
1976 assert_ne!(left, right);
1977 }
1978
1979 assert_ne!(x.joint_rand_blind, y.joint_rand_blind);
1980 }
1981 }
1982 }
1983 }
1984
1985 fn test_serialization<T, P, const SEED_SIZE: usize>(
1986 prio3: &Prio3<T, P, SEED_SIZE>,
1987 measurement: &T::Measurement,
1988 nonce: &[u8; 16],
1989 ) -> Result<(), VdafError>
1990 where
1991 T: Type,
1992 P: Xof<SEED_SIZE>,
1993 {
1994 let mut verify_key = [0; SEED_SIZE];
1995 thread_rng().fill(&mut verify_key[..]);
1996 let (public_share, input_shares) = prio3.shard(measurement, nonce)?;
1997
1998 let encoded_public_share = public_share.get_encoded().unwrap();
1999 let decoded_public_share =
2000 Prio3PublicShare::get_decoded_with_param(prio3, &encoded_public_share)
2001 .expect("failed to decode public share");
2002 assert_eq!(decoded_public_share, public_share);
2003 assert_eq!(
2004 public_share.encoded_len().unwrap(),
2005 encoded_public_share.len()
2006 );
2007
2008 for (agg_id, input_share) in input_shares.iter().enumerate() {
2009 let encoded_input_share = input_share.get_encoded().unwrap();
2010 let decoded_input_share =
2011 Prio3InputShare::get_decoded_with_param(&(prio3, agg_id), &encoded_input_share)
2012 .expect("failed to decode input share");
2013 assert_eq!(&decoded_input_share, input_share);
2014 assert_eq!(
2015 input_share.encoded_len().unwrap(),
2016 encoded_input_share.len()
2017 );
2018 }
2019
2020 let mut prepare_shares = Vec::new();
2021 let mut last_prepare_state = None;
2022 for (agg_id, input_share) in input_shares.iter().enumerate() {
2023 let (prepare_state, prepare_share) =
2024 prio3.prepare_init(&verify_key, agg_id, &(), nonce, &public_share, input_share)?;
2025
2026 let encoded_prepare_state = prepare_state.get_encoded().unwrap();
2027 let decoded_prepare_state =
2028 Prio3PrepareState::get_decoded_with_param(&(prio3, agg_id), &encoded_prepare_state)
2029 .expect("failed to decode prepare state");
2030 assert_eq!(decoded_prepare_state, prepare_state);
2031 assert_eq!(
2032 prepare_state.encoded_len().unwrap(),
2033 encoded_prepare_state.len()
2034 );
2035
2036 let encoded_prepare_share = prepare_share.get_encoded().unwrap();
2037 let decoded_prepare_share =
2038 Prio3PrepareShare::get_decoded_with_param(&prepare_state, &encoded_prepare_share)
2039 .expect("failed to decode prepare share");
2040 assert_eq!(decoded_prepare_share, prepare_share);
2041 assert_eq!(
2042 prepare_share.encoded_len().unwrap(),
2043 encoded_prepare_share.len()
2044 );
2045
2046 prepare_shares.push(prepare_share);
2047 last_prepare_state = Some(prepare_state);
2048 }
2049
2050 let prepare_message = prio3
2051 .prepare_shares_to_prepare_message(&(), prepare_shares)
2052 .unwrap();
2053
2054 let encoded_prepare_message = prepare_message.get_encoded().unwrap();
2055 let decoded_prepare_message = Prio3PrepareMessage::get_decoded_with_param(
2056 &last_prepare_state.unwrap(),
2057 &encoded_prepare_message,
2058 )
2059 .expect("failed to decode prepare message");
2060 assert_eq!(decoded_prepare_message, prepare_message);
2061 assert_eq!(
2062 prepare_message.encoded_len().unwrap(),
2063 encoded_prepare_message.len()
2064 );
2065
2066 Ok(())
2067 }
2068
2069 #[test]
2070 fn roundtrip_output_share() {
2071 let vdaf = Prio3::new_count(2).unwrap();
2072 fieldvec_roundtrip_test::<Field64, Prio3Count, OutputShare<Field64>>(&vdaf, &(), 1);
2073
2074 let vdaf = Prio3::new_sum(2, 17).unwrap();
2075 fieldvec_roundtrip_test::<Field128, Prio3Sum, OutputShare<Field128>>(&vdaf, &(), 1);
2076
2077 let vdaf = Prio3::new_histogram(2, 12, 3).unwrap();
2078 fieldvec_roundtrip_test::<Field128, Prio3Histogram, OutputShare<Field128>>(&vdaf, &(), 12);
2079 }
2080
2081 #[test]
2082 fn roundtrip_aggregate_share() {
2083 let vdaf = Prio3::new_count(2).unwrap();
2084 fieldvec_roundtrip_test::<Field64, Prio3Count, AggregateShare<Field64>>(&vdaf, &(), 1);
2085
2086 let vdaf = Prio3::new_sum(2, 17).unwrap();
2087 fieldvec_roundtrip_test::<Field128, Prio3Sum, AggregateShare<Field128>>(&vdaf, &(), 1);
2088
2089 let vdaf = Prio3::new_histogram(2, 12, 3).unwrap();
2090 fieldvec_roundtrip_test::<Field128, Prio3Histogram, AggregateShare<Field128>>(
2091 &vdaf,
2092 &(),
2093 12,
2094 );
2095 }
2096
2097 #[test]
2098 fn public_share_equality_test() {
2099 equality_comparison_test(&[
2100 Prio3PublicShare {
2101 joint_rand_parts: Some(Vec::from([Seed([0])])),
2102 },
2103 Prio3PublicShare {
2104 joint_rand_parts: Some(Vec::from([Seed([1])])),
2105 },
2106 Prio3PublicShare {
2107 joint_rand_parts: None,
2108 },
2109 ])
2110 }
2111
2112 #[test]
2113 fn input_share_equality_test() {
2114 equality_comparison_test(&[
2115 // Default.
2116 Prio3InputShare {
2117 measurement_share: Share::Leader(Vec::from([0])),
2118 proofs_share: Share::Leader(Vec::from([1])),
2119 joint_rand_blind: Some(Seed([2])),
2120 },
2121 // Modified measurement share.
2122 Prio3InputShare {
2123 measurement_share: Share::Leader(Vec::from([100])),
2124 proofs_share: Share::Leader(Vec::from([1])),
2125 joint_rand_blind: Some(Seed([2])),
2126 },
2127 // Modified proof share.
2128 Prio3InputShare {
2129 measurement_share: Share::Leader(Vec::from([0])),
2130 proofs_share: Share::Leader(Vec::from([101])),
2131 joint_rand_blind: Some(Seed([2])),
2132 },
2133 // Modified joint_rand_blind.
2134 Prio3InputShare {
2135 measurement_share: Share::Leader(Vec::from([0])),
2136 proofs_share: Share::Leader(Vec::from([1])),
2137 joint_rand_blind: Some(Seed([102])),
2138 },
2139 // Missing joint_rand_blind.
2140 Prio3InputShare {
2141 measurement_share: Share::Leader(Vec::from([0])),
2142 proofs_share: Share::Leader(Vec::from([1])),
2143 joint_rand_blind: None,
2144 },
2145 ])
2146 }
2147
2148 #[test]
2149 fn prepare_share_equality_test() {
2150 equality_comparison_test(&[
2151 // Default.
2152 Prio3PrepareShare {
2153 verifiers: Vec::from([0]),
2154 joint_rand_part: Some(Seed([1])),
2155 },
2156 // Modified verifier.
2157 Prio3PrepareShare {
2158 verifiers: Vec::from([100]),
2159 joint_rand_part: Some(Seed([1])),
2160 },
2161 // Modified joint_rand_part.
2162 Prio3PrepareShare {
2163 verifiers: Vec::from([0]),
2164 joint_rand_part: Some(Seed([101])),
2165 },
2166 // Missing joint_rand_part.
2167 Prio3PrepareShare {
2168 verifiers: Vec::from([0]),
2169 joint_rand_part: None,
2170 },
2171 ])
2172 }
2173
2174 #[test]
2175 fn prepare_message_equality_test() {
2176 equality_comparison_test(&[
2177 // Default.
2178 Prio3PrepareMessage {
2179 joint_rand_seed: Some(Seed([0])),
2180 },
2181 // Modified joint_rand_seed.
2182 Prio3PrepareMessage {
2183 joint_rand_seed: Some(Seed([100])),
2184 },
2185 // Missing joint_rand_seed.
2186 Prio3PrepareMessage {
2187 joint_rand_seed: None,
2188 },
2189 ])
2190 }
2191
2192 #[test]
2193 fn prepare_state_equality_test() {
2194 equality_comparison_test(&[
2195 // Default.
2196 Prio3PrepareState {
2197 measurement_share: Share::Leader(Vec::from([0])),
2198 joint_rand_seed: Some(Seed([1])),
2199 agg_id: 2,
2200 verifiers_len: 3,
2201 },
2202 // Modified measurement share.
2203 Prio3PrepareState {
2204 measurement_share: Share::Leader(Vec::from([100])),
2205 joint_rand_seed: Some(Seed([1])),
2206 agg_id: 2,
2207 verifiers_len: 3,
2208 },
2209 // Modified joint_rand_seed.
2210 Prio3PrepareState {
2211 measurement_share: Share::Leader(Vec::from([0])),
2212 joint_rand_seed: Some(Seed([101])),
2213 agg_id: 2,
2214 verifiers_len: 3,
2215 },
2216 // Missing joint_rand_seed.
2217 Prio3PrepareState {
2218 measurement_share: Share::Leader(Vec::from([0])),
2219 joint_rand_seed: None,
2220 agg_id: 2,
2221 verifiers_len: 3,
2222 },
2223 // Modified agg_id.
2224 Prio3PrepareState {
2225 measurement_share: Share::Leader(Vec::from([0])),
2226 joint_rand_seed: Some(Seed([1])),
2227 agg_id: 102,
2228 verifiers_len: 3,
2229 },
2230 // Modified verifier_len.
2231 Prio3PrepareState {
2232 measurement_share: Share::Leader(Vec::from([0])),
2233 joint_rand_seed: Some(Seed([1])),
2234 agg_id: 2,
2235 verifiers_len: 103,
2236 },
2237 ])
2238 }
2239
2240 #[test]
2241 fn test_optimal_chunk_length() {
2242 // nonsense argument, but make sure it doesn't panic.
2243 optimal_chunk_length(0);
2244
2245 // edge cases on either side of power-of-two jumps
2246 assert_eq!(optimal_chunk_length(1), 1);
2247 assert_eq!(optimal_chunk_length(2), 2);
2248 assert_eq!(optimal_chunk_length(3), 1);
2249 assert_eq!(optimal_chunk_length(18), 6);
2250 assert_eq!(optimal_chunk_length(19), 3);
2251
2252 // additional arbitrary test cases
2253 assert_eq!(optimal_chunk_length(40), 6);
2254 assert_eq!(optimal_chunk_length(10_000), 79);
2255 assert_eq!(optimal_chunk_length(100_000), 393);
2256
2257 // confirm that the chunk lengths are truly optimal
2258 for measurement_length in [2, 3, 4, 5, 18, 19, 40] {
2259 let optimal_chunk_length = optimal_chunk_length(measurement_length);
2260 let optimal_proof_length = Histogram::<Field128, ParallelSum<_, _>>::new(
2261 measurement_length,
2262 optimal_chunk_length,
2263 )
2264 .unwrap()
2265 .proof_len();
2266 for chunk_length in 1..=measurement_length {
2267 let proof_length =
2268 Histogram::<Field128, ParallelSum<_, _>>::new(measurement_length, chunk_length)
2269 .unwrap()
2270 .proof_len();
2271 assert!(proof_length >= optimal_proof_length);
2272 }
2273 }
2274 }
2275 }