Debian Codegraph @

third_party/rust/prio/src/vdaf.rs

raw
1 // SPDX-License-Identifier: MPL-2.0
2
3 //! Verifiable Distributed Aggregation Functions (VDAFs) as described in
4 //! [[draft-irtf-cfrg-vdaf-08]].
5 //!
6 //! [draft-irtf-cfrg-vdaf-08]: https://datatracker.ietf.org/doc/draft-irtf-cfrg-vdaf/08/
7
8 #[cfg(feature = "experimental")]
9 use crate::dp::DifferentialPrivacyStrategy;
10 #[cfg(all(feature = "crypto-dependencies", feature = "experimental"))]
11 use crate::idpf::IdpfError;
12 #[cfg(all(feature = "crypto-dependencies", feature = "experimental"))]
13 use crate::vidpf::VidpfError;
14 use crate::{
15 codec::{CodecError, Decode, Encode, ParameterizedDecode},
16 field::{encode_fieldvec, merge_vector, FieldElement, FieldError},
17 flp::FlpError,
18 prng::PrngError,
19 vdaf::xof::Seed,
20 };
21 use serde::{Deserialize, Serialize};
22 use std::{error::Error, fmt::Debug, io::Cursor};
23 use subtle::{Choice, ConstantTimeEq};
24
25 /// A component of the domain-separation tag, used to bind the VDAF operations to the document
26 /// version. This will be revised with each draft with breaking changes.
27 pub(crate) const VERSION: u8 = 8;
28
29 /// Errors emitted by this module.
30 #[derive(Debug, thiserror::Error)]
31 #[non_exhaustive]
32 pub enum VdafError {
33 /// An error occurred.
34 #[error("vdaf error: {0}")]
35 Uncategorized(String),
36
37 /// Field error.
38 #[error("field error: {0}")]
39 Field(#[from] FieldError),
40
41 /// An error occured while parsing a message.
42 #[error("io error: {0}")]
43 IoError(#[from] std::io::Error),
44
45 /// FLP error.
46 #[error("flp error: {0}")]
47 Flp(#[from] FlpError),
48
49 /// PRNG error.
50 #[error("prng error: {0}")]
51 Prng(#[from] PrngError),
52
53 /// Failure when calling getrandom().
54 #[error("getrandom: {0}")]
55 GetRandom(#[from] getrandom::Error),
56
57 /// IDPF error.
58 #[cfg(all(feature = "crypto-dependencies", feature = "experimental"))]
59 #[error("idpf error: {0}")]
60 Idpf(#[from] IdpfError),
61
62 /// VIDPF error.
63 #[cfg(all(feature = "crypto-dependencies", feature = "experimental"))]
64 #[error("vidpf error: {0}")]
65 Vidpf(#[from] VidpfError),
66
67 /// Errors from other VDAFs.
68 #[error(transparent)]
69 Other(Box<dyn Error + 'static + Send + Sync>),
70 }
71
72 /// An additive share of a vector of field elements.
73 #[derive(Clone, Debug)]
74 pub enum Share<F, const SEED_SIZE: usize> {
75 /// An uncompressed share, typically sent to the leader.
76 Leader(Vec<F>),
77
78 /// A compressed share, typically sent to the helper.
79 Helper(Seed<SEED_SIZE>),
80 }
81
82 impl<F: ConstantTimeEq, const SEED_SIZE: usize> PartialEq for Share<F, SEED_SIZE> {
83 fn eq(&self, other: &Self) -> bool {
84 self.ct_eq(other).into()
85 }
86 }
87
88 impl<F: ConstantTimeEq, const SEED_SIZE: usize> Eq for Share<F, SEED_SIZE> {}
89
90 impl<F: ConstantTimeEq, const SEED_SIZE: usize> ConstantTimeEq for Share<F, SEED_SIZE> {
91 fn ct_eq(&self, other: &Self) -> subtle::Choice {
92 // We allow short-circuiting on the type (Leader vs Helper) of the value, but not the types'
93 // contents.
94 match (self, other) {
95 (Share::Leader(self_val), Share::Leader(other_val)) => self_val.ct_eq(other_val),
96 (Share::Helper(self_val), Share::Helper(other_val)) => self_val.ct_eq(other_val),
97 _ => Choice::from(0),
98 }
99 }
100 }
101
102 /// Parameters needed to decode a [`Share`]
103 #[derive(Clone, Debug, PartialEq, Eq)]
104 pub(crate) enum ShareDecodingParameter<const SEED_SIZE: usize> {
105 Leader(usize),
106 Helper,
107 }
108
109 impl<F: FieldElement, const SEED_SIZE: usize> ParameterizedDecode<ShareDecodingParameter<SEED_SIZE>>
110 for Share<F, SEED_SIZE>
111 {
112 fn decode_with_param(
113 decoding_parameter: &ShareDecodingParameter<SEED_SIZE>,
114 bytes: &mut Cursor<&[u8]>,
115 ) -> Result<Self, CodecError> {
116 match decoding_parameter {
117 ShareDecodingParameter::Leader(share_length) => {
118 let mut data = Vec::with_capacity(*share_length);
119 for _ in 0..*share_length {
120 data.push(F::decode(bytes)?)
121 }
122 Ok(Self::Leader(data))
123 }
124 ShareDecodingParameter::Helper => {
125 let seed = Seed::decode(bytes)?;
126 Ok(Self::Helper(seed))
127 }
128 }
129 }
130 }
131
132 impl<F: FieldElement, const SEED_SIZE: usize> Encode for Share<F, SEED_SIZE> {
133 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
134 match self {
135 Share::Leader(share_data) => {
136 for x in share_data {
137 x.encode(bytes)?;
138 }
139 Ok(())
140 }
141 Share::Helper(share_seed) => share_seed.encode(bytes),
142 }
143 }
144
145 fn encoded_len(&self) -> Option<usize> {
146 match self {
147 Share::Leader(share_data) => {
148 // Each element of the data vector has the same size.
149 Some(share_data.len() * F::ENCODED_SIZE)
150 }
151 Share::Helper(share_seed) => share_seed.encoded_len(),
152 }
153 }
154 }
155
156 /// The base trait for VDAF schemes. This trait is inherited by traits [`Client`], [`Aggregator`],
157 /// and [`Collector`], which define the roles of the various parties involved in the execution of
158 /// the VDAF.
159 pub trait Vdaf: Clone + Debug {
160 /// The type of Client measurement to be aggregated.
161 type Measurement: Clone + Debug;
162
163 /// The aggregate result of the VDAF execution.
164 type AggregateResult: Clone + Debug;
165
166 /// The aggregation parameter, used by the Aggregators to map their input shares to output
167 /// shares.
168 type AggregationParam: Clone + Debug + Decode + Encode;
169
170 /// A public share sent by a Client.
171 type PublicShare: Clone + Debug + ParameterizedDecode<Self> + Encode;
172
173 /// An input share sent by a Client.
174 type InputShare: Clone + Debug + for<'a> ParameterizedDecode<(&'a Self, usize)> + Encode;
175
176 /// An output share recovered from an input share by an Aggregator.
177 type OutputShare: Clone
178 + Debug
179 + for<'a> ParameterizedDecode<(&'a Self, &'a Self::AggregationParam)>
180 + Encode;
181
182 /// An Aggregator's share of the aggregate result.
183 type AggregateShare: Aggregatable<OutputShare = Self::OutputShare>
184 + for<'a> ParameterizedDecode<(&'a Self, &'a Self::AggregationParam)>
185 + Encode;
186
187 /// Return the VDAF's algorithm ID.
188 fn algorithm_id(&self) -> u32;
189
190 /// The number of Aggregators. The Client generates as many input shares as there are
191 /// Aggregators.
192 fn num_aggregators(&self) -> usize;
193
194 /// Generate the domain separation tag for this VDAF. The output is used for domain separation
195 /// by the XOF.
196 fn domain_separation_tag(&self, usage: u16) -> [u8; 8] {
197 let mut dst = [0_u8; 8];
198 dst[0] = VERSION;
199 dst[1] = 0; // algorithm class
200 dst[2..6].copy_from_slice(&(self.algorithm_id()).to_be_bytes());
201 dst[6..8].copy_from_slice(&usage.to_be_bytes());
202 dst
203 }
204 }
205
206 /// The Client's role in the execution of a VDAF.
207 pub trait Client<const NONCE_SIZE: usize>: Vdaf {
208 /// Shards a measurement into a public share and a sequence of input shares, one for each
209 /// Aggregator.
210 ///
211 /// Implements `Vdaf::shard` from [VDAF].
212 ///
213 /// [VDAF]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vdaf-08#section-5.1
214 fn shard(
215 &self,
216 measurement: &Self::Measurement,
217 nonce: &[u8; NONCE_SIZE],
218 ) -> Result<(Self::PublicShare, Vec<Self::InputShare>), VdafError>;
219 }
220
221 /// The Aggregator's role in the execution of a VDAF.
222 pub trait Aggregator<const VERIFY_KEY_SIZE: usize, const NONCE_SIZE: usize>: Vdaf {
223 /// State of the Aggregator during the Prepare process.
224 type PrepareState: Clone + Debug + PartialEq + Eq;
225
226 /// The type of messages sent by each aggregator at each round of the Prepare Process.
227 ///
228 /// Decoding takes a [`Self::PrepareState`] as a parameter; this [`Self::PrepareState`] may be
229 /// associated with any aggregator involved in the execution of the VDAF.
230 type PrepareShare: Clone + Debug + ParameterizedDecode<Self::PrepareState> + Encode;
231
232 /// Result of preprocessing a round of preparation shares. This is used by all aggregators as an
233 /// input to the next round of the Prepare Process.
234 ///
235 /// Decoding takes a [`Self::PrepareState`] as a parameter; this [`Self::PrepareState`] may be
236 /// associated with any aggregator involved in the execution of the VDAF.
237 type PrepareMessage: Clone
238 + Debug
239 + PartialEq
240 + Eq
241 + ParameterizedDecode<Self::PrepareState>
242 + Encode;
243
244 /// Begins the Prepare process with the other Aggregators. The [`Self::PrepareState`] returned
245 /// is passed to [`Self::prepare_next`] to get this aggregator's first-round prepare message.
246 ///
247 /// Implements `Vdaf.prep_init` from [VDAF].
248 ///
249 /// [VDAF]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vdaf-08#section-5.2
250 fn prepare_init(
251 &self,
252 verify_key: &[u8; VERIFY_KEY_SIZE],
253 agg_id: usize,
254 agg_param: &Self::AggregationParam,
255 nonce: &[u8; NONCE_SIZE],
256 public_share: &Self::PublicShare,
257 input_share: &Self::InputShare,
258 ) -> Result<(Self::PrepareState, Self::PrepareShare), VdafError>;
259
260 /// Preprocess a round of preparation shares into a single input to [`Self::prepare_next`].
261 ///
262 /// Implements `Vdaf.prep_shares_to_prep` from [VDAF].
263 ///
264 /// [VDAF]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vdaf-08#section-5.2
265 fn prepare_shares_to_prepare_message<M: IntoIterator<Item = Self::PrepareShare>>(
266 &self,
267 agg_param: &Self::AggregationParam,
268 inputs: M,
269 ) -> Result<Self::PrepareMessage, VdafError>;
270
271 /// Compute the next state transition from the current state and the previous round of input
272 /// messages. If this returns [`PrepareTransition::Continue`], then the returned
273 /// [`Self::PrepareShare`] should be combined with the other Aggregators' `PrepareShare`s from
274 /// this round and passed into another call to this method. This continues until this method
275 /// returns [`PrepareTransition::Finish`], at which point the returned output share may be
276 /// aggregated. If the method returns an error, the aggregator should consider its input share
277 /// invalid and not attempt to process it any further.
278 ///
279 /// Implements `Vdaf.prep_next` from [VDAF].
280 ///
281 /// [VDAF]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vdaf-08#section-5.2
282 fn prepare_next(
283 &self,
284 state: Self::PrepareState,
285 input: Self::PrepareMessage,
286 ) -> Result<PrepareTransition<Self, VERIFY_KEY_SIZE, NONCE_SIZE>, VdafError>;
287
288 /// Aggregates a sequence of output shares into an aggregate share.
289 fn aggregate<M: IntoIterator<Item = Self::OutputShare>>(
290 &self,
291 agg_param: &Self::AggregationParam,
292 output_shares: M,
293 ) -> Result<Self::AggregateShare, VdafError>;
294 }
295
296 /// Aggregator that implements differential privacy with Aggregator-side noise addition.
297 #[cfg(feature = "experimental")]
298 #[cfg_attr(docsrs, doc(cfg(feature = "experimental")))]
299 pub trait AggregatorWithNoise<
300 const VERIFY_KEY_SIZE: usize,
301 const NONCE_SIZE: usize,
302 DPStrategy: DifferentialPrivacyStrategy,
303 >: Aggregator<VERIFY_KEY_SIZE, NONCE_SIZE>
304 {
305 /// Adds noise to an aggregate share such that the aggregate result is differentially private
306 /// as long as one Aggregator is honest.
307 fn add_noise_to_agg_share(
308 &self,
309 dp_strategy: &DPStrategy,
310 agg_param: &Self::AggregationParam,
311 agg_share: &mut Self::AggregateShare,
312 num_measurements: usize,
313 ) -> Result<(), VdafError>;
314 }
315
316 /// The Collector's role in the execution of a VDAF.
317 pub trait Collector: Vdaf {
318 /// Combines aggregate shares into the aggregate result.
319 fn unshard<M: IntoIterator<Item = Self::AggregateShare>>(
320 &self,
321 agg_param: &Self::AggregationParam,
322 agg_shares: M,
323 num_measurements: usize,
324 ) -> Result<Self::AggregateResult, VdafError>;
325 }
326
327 /// A state transition of an Aggregator during the Prepare process.
328 #[derive(Clone, Debug)]
329 pub enum PrepareTransition<
330 V: Aggregator<VERIFY_KEY_SIZE, NONCE_SIZE>,
331 const VERIFY_KEY_SIZE: usize,
332 const NONCE_SIZE: usize,
333 > {
334 /// Continue processing.
335 Continue(V::PrepareState, V::PrepareShare),
336
337 /// Finish processing and return the output share.
338 Finish(V::OutputShare),
339 }
340
341 /// An aggregate share resulting from aggregating output shares together that
342 /// can merged with aggregate shares of the same type.
343 pub trait Aggregatable: Clone + Debug + From<Self::OutputShare> {
344 /// Type of output shares that can be accumulated into an aggregate share.
345 type OutputShare;
346
347 /// Update an aggregate share by merging it with another (`agg_share`).
348 fn merge(&mut self, agg_share: &Self) -> Result<(), VdafError>;
349
350 /// Update an aggregate share by adding `output_share`.
351 fn accumulate(&mut self, output_share: &Self::OutputShare) -> Result<(), VdafError>;
352 }
353
354 /// An output share comprised of a vector of field elements.
355 #[derive(Clone)]
356 pub struct OutputShare<F>(Vec<F>);
357
358 impl<F: ConstantTimeEq> PartialEq for OutputShare<F> {
359 fn eq(&self, other: &Self) -> bool {
360 self.ct_eq(other).into()
361 }
362 }
363
364 impl<F: ConstantTimeEq> Eq for OutputShare<F> {}
365
366 impl<F: ConstantTimeEq> ConstantTimeEq for OutputShare<F> {
367 fn ct_eq(&self, other: &Self) -> Choice {
368 self.0.ct_eq(&other.0)
369 }
370 }
371
372 impl<F> AsRef<[F]> for OutputShare<F> {
373 fn as_ref(&self) -> &[F] {
374 &self.0
375 }
376 }
377
378 impl<F> From<Vec<F>> for OutputShare<F> {
379 fn from(other: Vec<F>) -> Self {
380 Self(other)
381 }
382 }
383
384 impl<F: FieldElement> Encode for OutputShare<F> {
385 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
386 encode_fieldvec(&self.0, bytes)
387 }
388
389 fn encoded_len(&self) -> Option<usize> {
390 Some(F::ENCODED_SIZE * self.0.len())
391 }
392 }
393
394 impl<F> Debug for OutputShare<F> {
395 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396 f.debug_tuple("OutputShare").finish()
397 }
398 }
399
400 /// An aggregate share comprised of a vector of field elements.
401 ///
402 /// This is suitable for VDAFs where both output shares and aggregate shares are vectors of field
403 /// elements, and output shares need no special transformation to be merged into an aggregate share.
404 #[derive(Clone, Debug, Serialize, Deserialize)]
405
406 pub struct AggregateShare<F>(Vec<F>);
407
408 impl<F> From<Vec<F>> for AggregateShare<F> {
409 fn from(other: Vec<F>) -> Self {
410 Self(other)
411 }
412 }
413
414 impl<F: ConstantTimeEq> PartialEq for AggregateShare<F> {
415 fn eq(&self, other: &Self) -> bool {
416 self.ct_eq(other).into()
417 }
418 }
419
420 impl<F: ConstantTimeEq> Eq for AggregateShare<F> {}
421
422 impl<F: ConstantTimeEq> ConstantTimeEq for AggregateShare<F> {
423 fn ct_eq(&self, other: &Self) -> subtle::Choice {
424 self.0.ct_eq(&other.0)
425 }
426 }
427
428 impl<F: FieldElement> AsRef<[F]> for AggregateShare<F> {
429 fn as_ref(&self) -> &[F] {
430 &self.0
431 }
432 }
433
434 impl<F> From<OutputShare<F>> for AggregateShare<F> {
435 fn from(other: OutputShare<F>) -> Self {
436 Self(other.0)
437 }
438 }
439
440 impl<F: FieldElement> Aggregatable for AggregateShare<F> {
441 type OutputShare = OutputShare<F>;
442
443 fn merge(&mut self, agg_share: &Self) -> Result<(), VdafError> {
444 self.sum(agg_share.as_ref())
445 }
446
447 fn accumulate(&mut self, output_share: &Self::OutputShare) -> Result<(), VdafError> {
448 // For Poplar1, Prio2, and Prio3, no conversion is needed between output shares and
449 // aggregate shares.
450 self.sum(output_share.as_ref())
451 }
452 }
453
454 impl<F: FieldElement> AggregateShare<F> {
455 fn sum(&mut self, other: &[F]) -> Result<(), VdafError> {
456 merge_vector(&mut self.0, other).map_err(Into::into)
457 }
458 }
459
460 impl<F: FieldElement> Encode for AggregateShare<F> {
461 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
462 encode_fieldvec(&self.0, bytes)
463 }
464
465 fn encoded_len(&self) -> Option<usize> {
466 Some(F::ENCODED_SIZE * self.0.len())
467 }
468 }
469
470 /// Utilities for testing VDAFs.
471 #[cfg(feature = "test-util")]
472 #[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
473 pub mod test_utils {
474 use super::{Aggregatable, Aggregator, Client, Collector, PrepareTransition, VdafError};
475 use crate::codec::{Encode, ParameterizedDecode};
476 use rand::prelude::*;
477
478 /// Execute the VDAF end-to-end and return the aggregate result.
479 pub fn run_vdaf<V, M, const SEED_SIZE: usize>(
480 vdaf: &V,
481 agg_param: &V::AggregationParam,
482 measurements: M,
483 ) -> Result<V::AggregateResult, VdafError>
484 where
485 V: Client<16> + Aggregator<SEED_SIZE, 16> + Collector,
486 M: IntoIterator<Item = V::Measurement>,
487 {
488 let mut sharded_measurements = Vec::new();
489 for measurement in measurements.into_iter() {
490 let nonce = random();
491 let (public_share, input_shares) = vdaf.shard(&measurement, &nonce)?;
492
493 sharded_measurements.push((public_share, nonce, input_shares));
494 }
495
496 run_vdaf_sharded(vdaf, agg_param, sharded_measurements)
497 }
498
499 /// Execute the VDAF on sharded measurements and return the aggregate result.
500 pub fn run_vdaf_sharded<V, M, I, const SEED_SIZE: usize>(
501 vdaf: &V,
502 agg_param: &V::AggregationParam,
503 sharded_measurements: M,
504 ) -> Result<V::AggregateResult, VdafError>
505 where
506 V: Client<16> + Aggregator<SEED_SIZE, 16> + Collector,
507 M: IntoIterator<Item = (V::PublicShare, [u8; 16], I)>,
508 I: IntoIterator<Item = V::InputShare>,
509 {
510 let mut rng = thread_rng();
511 let mut verify_key = [0; SEED_SIZE];
512 rng.fill(&mut verify_key[..]);
513
514 let mut agg_shares: Vec<Option<V::AggregateShare>> = vec![None; vdaf.num_aggregators()];
515 let mut num_measurements: usize = 0;
516 for (public_share, nonce, input_shares) in sharded_measurements.into_iter() {
517 num_measurements += 1;
518 let out_shares = run_vdaf_prepare(
519 vdaf,
520 &verify_key,
521 agg_param,
522 &nonce,
523 public_share,
524 input_shares,
525 )?;
526 for (out_share, agg_share) in out_shares.into_iter().zip(agg_shares.iter_mut()) {
527 // Check serialization of output shares
528 let encoded_out_share = out_share.get_encoded().unwrap();
529 let round_trip_out_share =
530 V::OutputShare::get_decoded_with_param(&(vdaf, agg_param), &encoded_out_share)
531 .unwrap();
532 assert_eq!(
533 round_trip_out_share.get_encoded().unwrap(),
534 encoded_out_share
535 );
536
537 let this_agg_share = V::AggregateShare::from(out_share);
538 if let Some(ref mut inner) = agg_share {
539 inner.merge(&this_agg_share)?;
540 } else {
541 *agg_share = Some(this_agg_share);
542 }
543 }
544 }
545
546 for agg_share in agg_shares.iter() {
547 // Check serialization of aggregate shares
548 let encoded_agg_share = agg_share.as_ref().unwrap().get_encoded().unwrap();
549 let round_trip_agg_share =
550 V::AggregateShare::get_decoded_with_param(&(vdaf, agg_param), &encoded_agg_share)
551 .unwrap();
552 assert_eq!(
553 round_trip_agg_share.get_encoded().unwrap(),
554 encoded_agg_share
555 );
556 }
557
558 let res = vdaf.unshard(
559 agg_param,
560 agg_shares.into_iter().map(|option| option.unwrap()),
561 num_measurements,
562 )?;
563 Ok(res)
564 }
565
566 /// Execute VDAF preparation for a single report and return the recovered output shares.
567 pub fn run_vdaf_prepare<V, M, const SEED_SIZE: usize>(
568 vdaf: &V,
569 verify_key: &[u8; SEED_SIZE],
570 agg_param: &V::AggregationParam,
571 nonce: &[u8; 16],
572 public_share: V::PublicShare,
573 input_shares: M,
574 ) -> Result<Vec<V::OutputShare>, VdafError>
575 where
576 V: Client<16> + Aggregator<SEED_SIZE, 16> + Collector,
577 M: IntoIterator<Item = V::InputShare>,
578 {
579 let public_share =
580 V::PublicShare::get_decoded_with_param(vdaf, &public_share.get_encoded().unwrap())
581 .unwrap();
582 let input_shares = input_shares
583 .into_iter()
584 .map(|input_share| input_share.get_encoded().unwrap());
585
586 let mut states = Vec::new();
587 let mut outbound = Vec::new();
588 for (agg_id, input_share) in input_shares.enumerate() {
589 let (state, msg) = vdaf.prepare_init(
590 verify_key,
591 agg_id,
592 agg_param,
593 nonce,
594 &public_share,
595 &V::InputShare::get_decoded_with_param(&(vdaf, agg_id), &input_share)
596 .expect("failed to decode input share"),
597 )?;
598 states.push(state);
599 outbound.push(msg.get_encoded().unwrap());
600 }
601
602 let mut inbound = vdaf
603 .prepare_shares_to_prepare_message(
604 agg_param,
605 outbound.iter().map(|encoded| {
606 V::PrepareShare::get_decoded_with_param(&states[0], encoded)
607 .expect("failed to decode prep share")
608 }),
609 )?
610 .get_encoded()
611 .unwrap();
612
613 let mut out_shares = Vec::new();
614 loop {
615 let mut outbound = Vec::new();
616 for state in states.iter_mut() {
617 match vdaf.prepare_next(
618 state.clone(),
619 V::PrepareMessage::get_decoded_with_param(state, &inbound)
620 .expect("failed to decode prep message"),
621 )? {
622 PrepareTransition::Continue(new_state, msg) => {
623 outbound.push(msg.get_encoded().unwrap());
624 *state = new_state
625 }
626 PrepareTransition::Finish(out_share) => {
627 out_shares.push(out_share);
628 }
629 }
630 }
631
632 if outbound.len() == vdaf.num_aggregators() {
633 // Another round is required before output shares are computed.
634 inbound = vdaf
635 .prepare_shares_to_prepare_message(
636 agg_param,
637 outbound.iter().map(|encoded| {
638 V::PrepareShare::get_decoded_with_param(&states[0], encoded)
639 .expect("failed to decode prep share")
640 }),
641 )?
642 .get_encoded()
643 .unwrap();
644 } else if outbound.is_empty() {
645 // Each Aggregator recovered an output share.
646 break;
647 } else {
648 panic!("Aggregators did not finish the prepare phase at the same time");
649 }
650 }
651
652 Ok(out_shares)
653 }
654 }
655
656 #[cfg(test)]
657 fn fieldvec_roundtrip_test<F, V, T>(vdaf: &V, agg_param: &V::AggregationParam, length: usize)
658 where
659 F: FieldElement,
660 V: Vdaf,
661 T: Encode,
662 for<'a> T: ParameterizedDecode<(&'a V, &'a V::AggregationParam)>,
663 {
664 // Generate an arbitrary vector of field elements.
665 let vec: Vec<F> = crate::field::random_vector(length).unwrap();
666
667 // Serialize the field element vector into a vector of bytes.
668 let mut bytes = Vec::with_capacity(vec.len() * F::ENCODED_SIZE);
669 encode_fieldvec(&vec, &mut bytes).unwrap();
670
671 // Deserialize the type of interest from those bytes.
672 let value = T::get_decoded_with_param(&(vdaf, agg_param), &bytes).unwrap();
673
674 // Round-trip the value back to a vector of bytes.
675 let encoded = value.get_encoded().unwrap();
676
677 assert_eq!(encoded, bytes);
678 }
679
680 #[cfg(test)]
681 fn equality_comparison_test<T>(values: &[T])
682 where
683 T: Debug + PartialEq,
684 {
685 use std::ptr;
686
687 // This function expects that every value passed in `values` is distinct, i.e. should not
688 // compare as equal to any other element. We test both (i, j) and (j, i) to gain confidence that
689 // equality implementations are symmetric.
690 for (i, i_val) in values.iter().enumerate() {
691 for (j, j_val) in values.iter().enumerate() {
692 if i == j {
693 assert!(ptr::eq(i_val, j_val)); // sanity
694 assert_eq!(
695 i_val, j_val,
696 "Expected element at index {i} to be equal to itself, but it was not"
697 );
698 } else {
699 assert_ne!(
700 i_val, j_val,
701 "Expected elements at indices {i} & {j} to not be equal, but they were"
702 )
703 }
704 }
705 }
706 }
707
708 #[cfg(test)]
709 mod tests {
710 use crate::vdaf::{equality_comparison_test, xof::Seed, AggregateShare, OutputShare, Share};
711
712 #[test]
713 fn share_equality_test() {
714 equality_comparison_test(&[
715 Share::Leader(Vec::from([1, 2, 3])),
716 Share::Leader(Vec::from([3, 2, 1])),
717 Share::Helper(Seed([1, 2, 3])),
718 Share::Helper(Seed([3, 2, 1])),
719 ])
720 }
721
722 #[test]
723 fn output_share_equality_test() {
724 equality_comparison_test(&[
725 OutputShare(Vec::from([1, 2, 3])),
726 OutputShare(Vec::from([3, 2, 1])),
727 ])
728 }
729
730 #[test]
731 fn aggregate_share_equality_test() {
732 equality_comparison_test(&[
733 AggregateShare(Vec::from([1, 2, 3])),
734 AggregateShare(Vec::from([3, 2, 1])),
735 ])
736 }
737 }
738
739 #[cfg(feature = "test-util")]
740 #[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
741 pub mod dummy;
742 #[cfg(all(feature = "crypto-dependencies", feature = "experimental"))]
743 #[cfg_attr(
744 docsrs,
745 doc(cfg(all(feature = "crypto-dependencies", feature = "experimental")))
746 )]
747 pub mod poplar1;
748 #[cfg(all(feature = "crypto-dependencies", feature = "experimental"))]
749 #[cfg_attr(
750 docsrs,
751 doc(cfg(all(feature = "crypto-dependencies", feature = "experimental")))
752 )]
753 pub mod prio2;
754 pub mod prio3;
755 #[cfg(any(test, feature = "test-util"))]
756 #[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
757 pub mod prio3_test;
758 pub mod xof;