Debian Codegraph @

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

raw
1 // SPDX-License-Identifier: MPL-2.0
2
3 //! Implementation of Poplar1 as specified in [[draft-irtf-cfrg-vdaf-08]].
4 //!
5 //! [draft-irtf-cfrg-vdaf-08]: https://datatracker.ietf.org/doc/draft-irtf-cfrg-vdaf/08/
6
7 use crate::{
8 codec::{CodecError, Decode, Encode, ParameterizedDecode},
9 field::{decode_fieldvec, merge_vector, Field255, Field64, FieldElement},
10 idpf::{Idpf, IdpfInput, IdpfOutputShare, IdpfPublicShare, IdpfValue, RingBufferCache},
11 prng::Prng,
12 vdaf::{
13 xof::{Seed, Xof, XofTurboShake128},
14 Aggregatable, Aggregator, Client, Collector, PrepareTransition, Vdaf, VdafError,
15 },
16 };
17 use bitvec::{prelude::Lsb0, vec::BitVec};
18 use rand_core::RngCore;
19 use std::{
20 convert::TryFrom,
21 fmt::Debug,
22 io::{Cursor, Read},
23 iter,
24 marker::PhantomData,
25 num::TryFromIntError,
26 ops::{Add, AddAssign, Sub},
27 };
28 use subtle::{Choice, ConditionallyNegatable, ConditionallySelectable, ConstantTimeEq};
29
30 const DST_SHARD_RANDOMNESS: u16 = 1;
31 const DST_CORR_INNER: u16 = 2;
32 const DST_CORR_LEAF: u16 = 3;
33 const DST_VERIFY_RANDOMNESS: u16 = 4;
34
35 impl<P, const SEED_SIZE: usize> Poplar1<P, SEED_SIZE> {
36 /// Create an instance of [`Poplar1`]. The caller provides the bit length of each
37 /// measurement (`BITS` as defined in [[draft-irtf-cfrg-vdaf-08]]).
38 ///
39 /// [draft-irtf-cfrg-vdaf-08]: https://datatracker.ietf.org/doc/draft-irtf-cfrg-vdaf/08/
40 pub fn new(bits: usize) -> Self {
41 Self {
42 bits,
43 phantom: PhantomData,
44 }
45 }
46 }
47
48 impl Poplar1<XofTurboShake128, 16> {
49 /// Create an instance of [`Poplar1`] using [`XofTurboShake128`]. The caller provides the bit length of
50 /// each measurement (`BITS` as defined in [[draft-irtf-cfrg-vdaf-08]]).
51 ///
52 /// [draft-irtf-cfrg-vdaf-08]: https://datatracker.ietf.org/doc/draft-irtf-cfrg-vdaf/08/
53 pub fn new_turboshake128(bits: usize) -> Self {
54 Poplar1::new(bits)
55 }
56 }
57
58 /// The Poplar1 VDAF.
59 #[derive(Debug)]
60 pub struct Poplar1<P, const SEED_SIZE: usize> {
61 bits: usize,
62 phantom: PhantomData<P>,
63 }
64
65 impl<P: Xof<SEED_SIZE>, const SEED_SIZE: usize> Poplar1<P, SEED_SIZE> {
66 /// Construct a `Prng` with the given seed and info-string suffix.
67 fn init_prng<I, B, F>(
68 &self,
69 seed: &[u8; SEED_SIZE],
70 usage: u16,
71 binder_chunks: I,
72 ) -> Prng<F, P::SeedStream>
73 where
74 I: IntoIterator<Item = B>,
75 B: AsRef<[u8]>,
76 P: Xof<SEED_SIZE>,
77 F: FieldElement,
78 {
79 let mut xof = P::init(seed, &self.domain_separation_tag(usage));
80 for binder_chunk in binder_chunks.into_iter() {
81 xof.update(binder_chunk.as_ref());
82 }
83 Prng::from_seed_stream(xof.into_seed_stream())
84 }
85 }
86
87 impl<P, const SEED_SIZE: usize> Clone for Poplar1<P, SEED_SIZE> {
88 fn clone(&self) -> Self {
89 Self {
90 bits: self.bits,
91 phantom: PhantomData,
92 }
93 }
94 }
95
96 /// Poplar1 public share.
97 ///
98 /// This is comprised of the correction words generated for the IDPF.
99 pub type Poplar1PublicShare =
100 IdpfPublicShare<Poplar1IdpfValue<Field64>, Poplar1IdpfValue<Field255>>;
101
102 impl<P, const SEED_SIZE: usize> ParameterizedDecode<Poplar1<P, SEED_SIZE>> for Poplar1PublicShare {
103 fn decode_with_param(
104 poplar1: &Poplar1<P, SEED_SIZE>,
105 bytes: &mut Cursor<&[u8]>,
106 ) -> Result<Self, CodecError> {
107 Self::decode_with_param(&poplar1.bits, bytes)
108 }
109 }
110
111 /// Poplar1 input share.
112 ///
113 /// This is comprised of an IDPF key share and the correlated randomness used to compute the sketch
114 /// during preparation.
115 #[derive(Debug, Clone)]
116 pub struct Poplar1InputShare<const SEED_SIZE: usize> {
117 /// IDPF key share.
118 idpf_key: Seed<16>,
119
120 /// Seed used to generate the Aggregator's share of the correlated randomness used in the first
121 /// part of the sketch.
122 corr_seed: Seed<SEED_SIZE>,
123
124 /// Aggregator's share of the correlated randomness used in the second part of the sketch. Used
125 /// for inner nodes of the IDPF tree.
126 corr_inner: Vec<[Field64; 2]>,
127
128 /// Aggregator's share of the correlated randomness used in the second part of the sketch. Used
129 /// for leaf nodes of the IDPF tree.
130 corr_leaf: [Field255; 2],
131 }
132
133 impl<const SEED_SIZE: usize> PartialEq for Poplar1InputShare<SEED_SIZE> {
134 fn eq(&self, other: &Self) -> bool {
135 self.ct_eq(other).into()
136 }
137 }
138
139 impl<const SEED_SIZE: usize> Eq for Poplar1InputShare<SEED_SIZE> {}
140
141 impl<const SEED_SIZE: usize> ConstantTimeEq for Poplar1InputShare<SEED_SIZE> {
142 fn ct_eq(&self, other: &Self) -> Choice {
143 // We short-circuit on the length of corr_inner being different. Only the content is
144 // protected.
145 if self.corr_inner.len() != other.corr_inner.len() {
146 return Choice::from(0);
147 }
148
149 let mut res = self.idpf_key.ct_eq(&other.idpf_key)
150 & self.corr_seed.ct_eq(&other.corr_seed)
151 & self.corr_leaf.ct_eq(&other.corr_leaf);
152 for (x, y) in self.corr_inner.iter().zip(other.corr_inner.iter()) {
153 res &= x.ct_eq(y);
154 }
155 res
156 }
157 }
158
159 impl<const SEED_SIZE: usize> Encode for Poplar1InputShare<SEED_SIZE> {
160 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
161 self.idpf_key.encode(bytes)?;
162 self.corr_seed.encode(bytes)?;
163 for corr in self.corr_inner.iter() {
164 corr[0].encode(bytes)?;
165 corr[1].encode(bytes)?;
166 }
167 self.corr_leaf[0].encode(bytes)?;
168 self.corr_leaf[1].encode(bytes)
169 }
170
171 fn encoded_len(&self) -> Option<usize> {
172 let mut len = 0;
173 len += SEED_SIZE; // idpf_key
174 len += SEED_SIZE; // corr_seed
175 len += self.corr_inner.len() * 2 * Field64::ENCODED_SIZE; // corr_inner
176 len += 2 * Field255::ENCODED_SIZE; // corr_leaf
177 Some(len)
178 }
179 }
180
181 impl<'a, P, const SEED_SIZE: usize> ParameterizedDecode<(&'a Poplar1<P, SEED_SIZE>, usize)>
182 for Poplar1InputShare<SEED_SIZE>
183 {
184 fn decode_with_param(
185 (poplar1, _agg_id): &(&'a Poplar1<P, SEED_SIZE>, usize),
186 bytes: &mut Cursor<&[u8]>,
187 ) -> Result<Self, CodecError> {
188 let idpf_key = Seed::decode(bytes)?;
189 let corr_seed = Seed::decode(bytes)?;
190 let mut corr_inner = Vec::with_capacity(poplar1.bits - 1);
191 for _ in 0..poplar1.bits - 1 {
192 corr_inner.push([Field64::decode(bytes)?, Field64::decode(bytes)?]);
193 }
194 let corr_leaf = [Field255::decode(bytes)?, Field255::decode(bytes)?];
195 Ok(Self {
196 idpf_key,
197 corr_seed,
198 corr_inner,
199 corr_leaf,
200 })
201 }
202 }
203
204 /// Poplar1 preparation state.
205 #[derive(Clone, Debug)]
206 pub struct Poplar1PrepareState(PrepareStateVariant);
207
208 impl PartialEq for Poplar1PrepareState {
209 fn eq(&self, other: &Self) -> bool {
210 self.ct_eq(other).into()
211 }
212 }
213
214 impl Eq for Poplar1PrepareState {}
215
216 impl ConstantTimeEq for Poplar1PrepareState {
217 fn ct_eq(&self, other: &Self) -> Choice {
218 self.0.ct_eq(&other.0)
219 }
220 }
221
222 impl Encode for Poplar1PrepareState {
223 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
224 self.0.encode(bytes)
225 }
226
227 fn encoded_len(&self) -> Option<usize> {
228 self.0.encoded_len()
229 }
230 }
231
232 impl<'a, P, const SEED_SIZE: usize> ParameterizedDecode<(&'a Poplar1<P, SEED_SIZE>, usize)>
233 for Poplar1PrepareState
234 {
235 fn decode_with_param(
236 decoding_parameter: &(&'a Poplar1<P, SEED_SIZE>, usize),
237 bytes: &mut Cursor<&[u8]>,
238 ) -> Result<Self, CodecError> {
239 Ok(Self(PrepareStateVariant::decode_with_param(
240 decoding_parameter,
241 bytes,
242 )?))
243 }
244 }
245
246 #[derive(Clone, Debug)]
247 enum PrepareStateVariant {
248 Inner(PrepareState<Field64>),
249 Leaf(PrepareState<Field255>),
250 }
251
252 impl PartialEq for PrepareStateVariant {
253 fn eq(&self, other: &Self) -> bool {
254 self.ct_eq(other).into()
255 }
256 }
257
258 impl Eq for PrepareStateVariant {}
259
260 impl ConstantTimeEq for PrepareStateVariant {
261 fn ct_eq(&self, other: &Self) -> Choice {
262 // We allow short-circuiting on the type (Inner vs Leaf).
263 match (self, other) {
264 (Self::Inner(self_val), Self::Inner(other_val)) => self_val.ct_eq(other_val),
265 (Self::Leaf(self_val), Self::Leaf(other_val)) => self_val.ct_eq(other_val),
266 _ => Choice::from(0),
267 }
268 }
269 }
270
271 impl Encode for PrepareStateVariant {
272 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
273 match self {
274 PrepareStateVariant::Inner(prep_state) => {
275 0u8.encode(bytes)?;
276 prep_state.encode(bytes)
277 }
278 PrepareStateVariant::Leaf(prep_state) => {
279 1u8.encode(bytes)?;
280 prep_state.encode(bytes)
281 }
282 }
283 }
284
285 fn encoded_len(&self) -> Option<usize> {
286 Some(
287 1 + match self {
288 PrepareStateVariant::Inner(prep_state) => prep_state.encoded_len()?,
289 PrepareStateVariant::Leaf(prep_state) => prep_state.encoded_len()?,
290 },
291 )
292 }
293 }
294
295 impl<'a, P, const SEED_SIZE: usize> ParameterizedDecode<(&'a Poplar1<P, SEED_SIZE>, usize)>
296 for PrepareStateVariant
297 {
298 fn decode_with_param(
299 decoding_parameter: &(&'a Poplar1<P, SEED_SIZE>, usize),
300 bytes: &mut Cursor<&[u8]>,
301 ) -> Result<Self, CodecError> {
302 match u8::decode(bytes)? {
303 0 => {
304 let prep_state = PrepareState::decode_with_param(decoding_parameter, bytes)?;
305 Ok(Self::Inner(prep_state))
306 }
307 1 => {
308 let prep_state = PrepareState::decode_with_param(decoding_parameter, bytes)?;
309 Ok(Self::Leaf(prep_state))
310 }
311 _ => Err(CodecError::UnexpectedValue),
312 }
313 }
314 }
315
316 #[derive(Clone)]
317 struct PrepareState<F> {
318 sketch: SketchState<F>,
319 output_share: Vec<F>,
320 }
321
322 impl<F: ConstantTimeEq> PartialEq for PrepareState<F> {
323 fn eq(&self, other: &Self) -> bool {
324 self.ct_eq(other).into()
325 }
326 }
327
328 impl<F: ConstantTimeEq> Eq for PrepareState<F> {}
329
330 impl<F: ConstantTimeEq> ConstantTimeEq for PrepareState<F> {
331 fn ct_eq(&self, other: &Self) -> Choice {
332 self.sketch.ct_eq(&other.sketch) & self.output_share.ct_eq(&other.output_share)
333 }
334 }
335
336 impl<F> Debug for PrepareState<F> {
337 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
338 f.debug_struct("PrepareState")
339 .field("sketch", &"[redacted]")
340 .field("output_share", &"[redacted]")
341 .finish()
342 }
343 }
344
345 impl<F: FieldElement> Encode for PrepareState<F> {
346 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
347 self.sketch.encode(bytes)?;
348 // `expect` safety: output_share's length is the same as the number of prefixes; the number
349 // of prefixes is capped at 2^32-1.
350 u32::try_from(self.output_share.len())
351 .expect("Couldn't convert output_share length to u32")
352 .encode(bytes)?;
353 for elem in &self.output_share {
354 elem.encode(bytes)?;
355 }
356 Ok(())
357 }
358
359 fn encoded_len(&self) -> Option<usize> {
360 Some(self.sketch.encoded_len()? + 4 + self.output_share.len() * F::ENCODED_SIZE)
361 }
362 }
363
364 impl<'a, P, F: FieldElement, const SEED_SIZE: usize>
365 ParameterizedDecode<(&'a Poplar1<P, SEED_SIZE>, usize)> for PrepareState<F>
366 {
367 fn decode_with_param(
368 decoding_parameter: &(&'a Poplar1<P, SEED_SIZE>, usize),
369 bytes: &mut Cursor<&[u8]>,
370 ) -> Result<Self, CodecError> {
371 let sketch = SketchState::<F>::decode_with_param(decoding_parameter, bytes)?;
372 let output_share_len = u32::decode(bytes)?
373 .try_into()
374 .map_err(|err: TryFromIntError| CodecError::Other(err.into()))?;
375 let output_share = iter::repeat_with(|| F::decode(bytes))
376 .take(output_share_len)
377 .collect::<Result<_, _>>()?;
378 Ok(Self {
379 sketch,
380 output_share,
381 })
382 }
383 }
384
385 #[derive(Clone, Debug)]
386 enum SketchState<F> {
387 #[allow(non_snake_case)]
388 RoundOne {
389 A_share: F,
390 B_share: F,
391 is_leader: bool,
392 },
393 RoundTwo,
394 }
395
396 impl<F: ConstantTimeEq> PartialEq for SketchState<F> {
397 fn eq(&self, other: &Self) -> bool {
398 self.ct_eq(other).into()
399 }
400 }
401
402 impl<F: ConstantTimeEq> Eq for SketchState<F> {}
403
404 impl<F: ConstantTimeEq> ConstantTimeEq for SketchState<F> {
405 fn ct_eq(&self, other: &Self) -> Choice {
406 // We allow short-circuiting on the round (RoundOne vs RoundTwo), as well as is_leader for
407 // RoundOne comparisons.
408 match (self, other) {
409 (
410 SketchState::RoundOne {
411 A_share: self_a_share,
412 B_share: self_b_share,
413 is_leader: self_is_leader,
414 },
415 SketchState::RoundOne {
416 A_share: other_a_share,
417 B_share: other_b_share,
418 is_leader: other_is_leader,
419 },
420 ) => {
421 if self_is_leader != other_is_leader {
422 return Choice::from(0);
423 }
424
425 self_a_share.ct_eq(other_a_share) & self_b_share.ct_eq(other_b_share)
426 }
427
428 (SketchState::RoundTwo, SketchState::RoundTwo) => Choice::from(1),
429 _ => Choice::from(0),
430 }
431 }
432 }
433
434 impl<F: FieldElement> Encode for SketchState<F> {
435 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
436 match self {
437 SketchState::RoundOne {
438 A_share, B_share, ..
439 } => {
440 0u8.encode(bytes)?;
441 A_share.encode(bytes)?;
442 B_share.encode(bytes)
443 }
444 SketchState::RoundTwo => 1u8.encode(bytes),
445 }
446 }
447
448 fn encoded_len(&self) -> Option<usize> {
449 Some(
450 1 + match self {
451 SketchState::RoundOne { .. } => 2 * F::ENCODED_SIZE,
452 SketchState::RoundTwo => 0,
453 },
454 )
455 }
456 }
457
458 impl<'a, P, F: FieldElement, const SEED_SIZE: usize>
459 ParameterizedDecode<(&'a Poplar1<P, SEED_SIZE>, usize)> for SketchState<F>
460 {
461 #[allow(non_snake_case)]
462 fn decode_with_param(
463 (_, agg_id): &(&'a Poplar1<P, SEED_SIZE>, usize),
464 bytes: &mut Cursor<&[u8]>,
465 ) -> Result<Self, CodecError> {
466 match u8::decode(bytes)? {
467 0 => {
468 let A_share = F::decode(bytes)?;
469 let B_share = F::decode(bytes)?;
470 let is_leader = agg_id == &0;
471 Ok(Self::RoundOne {
472 A_share,
473 B_share,
474 is_leader,
475 })
476 }
477 1 => Ok(Self::RoundTwo),
478 _ => Err(CodecError::UnexpectedValue),
479 }
480 }
481 }
482
483 impl<F: FieldElement> SketchState<F> {
484 fn decode_sketch_share(&self, bytes: &mut Cursor<&[u8]>) -> Result<Vec<F>, CodecError> {
485 match self {
486 // The sketch share is three field elements.
487 Self::RoundOne { .. } => Ok(vec![
488 F::decode(bytes)?,
489 F::decode(bytes)?,
490 F::decode(bytes)?,
491 ]),
492 // The sketch verifier share is one field element.
493 Self::RoundTwo => Ok(vec![F::decode(bytes)?]),
494 }
495 }
496
497 fn decode_sketch(&self, bytes: &mut Cursor<&[u8]>) -> Result<Option<[F; 3]>, CodecError> {
498 match self {
499 // The sketch is three field elements.
500 Self::RoundOne { .. } => Ok(Some([
501 F::decode(bytes)?,
502 F::decode(bytes)?,
503 F::decode(bytes)?,
504 ])),
505 // The sketch verifier should be zero if the sketch if valid. Instead of transmitting
506 // this zero over the wire, we just expect an empty message.
507 Self::RoundTwo => Ok(None),
508 }
509 }
510 }
511
512 /// Poplar1 preparation message.
513 #[derive(Clone, Debug, PartialEq, Eq)]
514 pub struct Poplar1PrepareMessage(PrepareMessageVariant);
515
516 #[derive(Clone, Debug, PartialEq, Eq)]
517 enum PrepareMessageVariant {
518 SketchInner([Field64; 3]),
519 SketchLeaf([Field255; 3]),
520 Done,
521 }
522
523 impl Encode for Poplar1PrepareMessage {
524 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
525 match self.0 {
526 PrepareMessageVariant::SketchInner(vec) => {
527 vec[0].encode(bytes)?;
528 vec[1].encode(bytes)?;
529 vec[2].encode(bytes)
530 }
531 PrepareMessageVariant::SketchLeaf(vec) => {
532 vec[0].encode(bytes)?;
533 vec[1].encode(bytes)?;
534 vec[2].encode(bytes)
535 }
536 PrepareMessageVariant::Done => Ok(()),
537 }
538 }
539
540 fn encoded_len(&self) -> Option<usize> {
541 match self.0 {
542 PrepareMessageVariant::SketchInner(..) => Some(3 * Field64::ENCODED_SIZE),
543 PrepareMessageVariant::SketchLeaf(..) => Some(3 * Field255::ENCODED_SIZE),
544 PrepareMessageVariant::Done => Some(0),
545 }
546 }
547 }
548
549 impl ParameterizedDecode<Poplar1PrepareState> for Poplar1PrepareMessage {
550 fn decode_with_param(
551 state: &Poplar1PrepareState,
552 bytes: &mut Cursor<&[u8]>,
553 ) -> Result<Self, CodecError> {
554 match state.0 {
555 PrepareStateVariant::Inner(ref state_variant) => Ok(Self(
556 state_variant
557 .sketch
558 .decode_sketch(bytes)?
559 .map_or(PrepareMessageVariant::Done, |sketch| {
560 PrepareMessageVariant::SketchInner(sketch)
561 }),
562 )),
563 PrepareStateVariant::Leaf(ref state_variant) => Ok(Self(
564 state_variant
565 .sketch
566 .decode_sketch(bytes)?
567 .map_or(PrepareMessageVariant::Done, |sketch| {
568 PrepareMessageVariant::SketchLeaf(sketch)
569 }),
570 )),
571 }
572 }
573 }
574
575 /// A vector of field elements transmitted while evaluating Poplar1.
576 #[derive(Clone, Debug)]
577 pub enum Poplar1FieldVec {
578 /// Field type for inner nodes of the IDPF tree.
579 Inner(Vec<Field64>),
580
581 /// Field type for leaf nodes of the IDPF tree.
582 Leaf(Vec<Field255>),
583 }
584
585 impl Poplar1FieldVec {
586 fn zero(is_leaf: bool, len: usize) -> Self {
587 if is_leaf {
588 Self::Leaf(vec![<Field255 as FieldElement>::zero(); len])
589 } else {
590 Self::Inner(vec![<Field64 as FieldElement>::zero(); len])
591 }
592 }
593 }
594
595 impl PartialEq for Poplar1FieldVec {
596 fn eq(&self, other: &Self) -> bool {
597 self.ct_eq(other).into()
598 }
599 }
600
601 impl Eq for Poplar1FieldVec {}
602
603 impl ConstantTimeEq for Poplar1FieldVec {
604 fn ct_eq(&self, other: &Self) -> Choice {
605 // We allow short-circuiting on the type (Inner vs Leaf).
606 match (self, other) {
607 (Poplar1FieldVec::Inner(self_val), Poplar1FieldVec::Inner(other_val)) => {
608 self_val.ct_eq(other_val)
609 }
610 (Poplar1FieldVec::Leaf(self_val), Poplar1FieldVec::Leaf(other_val)) => {
611 self_val.ct_eq(other_val)
612 }
613 _ => Choice::from(0),
614 }
615 }
616 }
617
618 impl Encode for Poplar1FieldVec {
619 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
620 match self {
621 Self::Inner(ref data) => {
622 for elem in data {
623 elem.encode(bytes)?;
624 }
625 Ok(())
626 }
627 Self::Leaf(ref data) => {
628 for elem in data {
629 elem.encode(bytes)?;
630 }
631 Ok(())
632 }
633 }
634 }
635
636 fn encoded_len(&self) -> Option<usize> {
637 match self {
638 Self::Inner(ref data) => Some(Field64::ENCODED_SIZE * data.len()),
639 Self::Leaf(ref data) => Some(Field255::ENCODED_SIZE * data.len()),
640 }
641 }
642 }
643
644 impl<'a, P: Xof<SEED_SIZE>, const SEED_SIZE: usize>
645 ParameterizedDecode<(&'a Poplar1<P, SEED_SIZE>, &'a Poplar1AggregationParam)>
646 for Poplar1FieldVec
647 {
648 fn decode_with_param(
649 (poplar1, agg_param): &(&'a Poplar1<P, SEED_SIZE>, &'a Poplar1AggregationParam),
650 bytes: &mut Cursor<&[u8]>,
651 ) -> Result<Self, CodecError> {
652 if agg_param.level() == poplar1.bits - 1 {
653 decode_fieldvec(agg_param.prefixes().len(), bytes).map(Poplar1FieldVec::Leaf)
654 } else {
655 decode_fieldvec(agg_param.prefixes().len(), bytes).map(Poplar1FieldVec::Inner)
656 }
657 }
658 }
659
660 impl ParameterizedDecode<Poplar1PrepareState> for Poplar1FieldVec {
661 fn decode_with_param(
662 state: &Poplar1PrepareState,
663 bytes: &mut Cursor<&[u8]>,
664 ) -> Result<Self, CodecError> {
665 match state.0 {
666 PrepareStateVariant::Inner(ref state_variant) => Ok(Poplar1FieldVec::Inner(
667 state_variant.sketch.decode_sketch_share(bytes)?,
668 )),
669 PrepareStateVariant::Leaf(ref state_variant) => Ok(Poplar1FieldVec::Leaf(
670 state_variant.sketch.decode_sketch_share(bytes)?,
671 )),
672 }
673 }
674 }
675
676 impl Aggregatable for Poplar1FieldVec {
677 type OutputShare = Self;
678
679 fn merge(&mut self, agg_share: &Self) -> Result<(), VdafError> {
680 match (self, agg_share) {
681 (Self::Inner(ref mut left), Self::Inner(right)) => Ok(merge_vector(left, right)?),
682 (Self::Leaf(ref mut left), Self::Leaf(right)) => Ok(merge_vector(left, right)?),
683 _ => Err(VdafError::Uncategorized(
684 "cannot merge leaf nodes wiith inner nodes".into(),
685 )),
686 }
687 }
688
689 fn accumulate(&mut self, output_share: &Self) -> Result<(), VdafError> {
690 match (self, output_share) {
691 (Self::Inner(ref mut left), Self::Inner(right)) => Ok(merge_vector(left, right)?),
692 (Self::Leaf(ref mut left), Self::Leaf(right)) => Ok(merge_vector(left, right)?),
693 _ => Err(VdafError::Uncategorized(
694 "cannot accumulate leaf nodes with inner nodes".into(),
695 )),
696 }
697 }
698 }
699
700 /// Poplar1 aggregation parameter.
701 ///
702 /// This includes an indication of what level of the IDPF tree is being evaluated and the set of
703 /// prefixes to evaluate at that level.
704 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
705 pub struct Poplar1AggregationParam {
706 level: u16,
707 prefixes: Vec<IdpfInput>,
708 }
709
710 impl Poplar1AggregationParam {
711 /// Construct an aggregation parameter from a set of candidate prefixes.
712 ///
713 /// # Errors
714 ///
715 /// * The list of prefixes is empty.
716 /// * The prefixes have different lengths (they must all be the same).
717 /// * The prefixes have length 0, or length longer than 2^16 bits.
718 /// * There are more than 2^32 - 1 prefixes.
719 /// * The prefixes are not unique.
720 /// * The prefixes are not in lexicographic order.
721 pub fn try_from_prefixes(prefixes: Vec<IdpfInput>) -> Result<Self, VdafError> {
722 if prefixes.is_empty() {
723 return Err(VdafError::Uncategorized(
724 "at least one prefix is required".into(),
725 ));
726 }
727 if u32::try_from(prefixes.len()).is_err() {
728 return Err(VdafError::Uncategorized("too many prefixes".into()));
729 }
730
731 let len = prefixes[0].len();
732 let mut last_prefix = None;
733 for prefix in prefixes.iter() {
734 if prefix.len() != len {
735 return Err(VdafError::Uncategorized(
736 "all prefixes must have the same length".into(),
737 ));
738 }
739 if let Some(last_prefix) = last_prefix {
740 if prefix <= last_prefix {
741 if prefix == last_prefix {
742 return Err(VdafError::Uncategorized(
743 "prefixes must be nonrepeating".into(),
744 ));
745 } else {
746 return Err(VdafError::Uncategorized(
747 "prefixes must be in lexicographic order".into(),
748 ));
749 }
750 }
751 }
752 last_prefix = Some(prefix);
753 }
754
755 let level = len
756 .checked_sub(1)
757 .ok_or_else(|| VdafError::Uncategorized("prefixes are too short".into()))?;
758 let level = u16::try_from(level)
759 .map_err(|_| VdafError::Uncategorized("prefixes are too long".into()))?;
760
761 Ok(Self { level, prefixes })
762 }
763
764 /// Return the level of the IDPF tree.
765 pub fn level(&self) -> usize {
766 usize::from(self.level)
767 }
768
769 /// Return the prefixes.
770 pub fn prefixes(&self) -> &[IdpfInput] {
771 self.prefixes.as_ref()
772 }
773 }
774
775 impl Encode for Poplar1AggregationParam {
776 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
777 // Okay to unwrap because `try_from_prefixes()` checks this conversion succeeds.
778 let prefix_count = u32::try_from(self.prefixes.len()).unwrap();
779 self.level.encode(bytes)?;
780 prefix_count.encode(bytes)?;
781
782 // The encoding of the prefixes is defined by treating the IDPF indices as integers,
783 // shifting and ORing them together, and encoding the resulting arbitrary precision integer
784 // in big endian byte order. Thus, the first prefix will appear in the last encoded byte,
785 // aligned to its least significant bit. The last prefix will appear in the first encoded
786 // byte, not necessarily aligned to a byte boundary. If the highest bits in the first byte
787 // are unused, they will be set to zero.
788
789 // When an IDPF index is treated as an integer, the first bit is the integer's most
790 // significant bit, and bits are subsequently processed in order of decreasing significance.
791 // Thus, setting aside the order of bytes, bits within each byte are ordered with the
792 // [`Msb0`](bitvec::prelude::Msb0) convention, not [`Lsb0`](bitvec::prelude::Msb0). Yet,
793 // the entire integer is aligned to the least significant bit of the last byte, so we
794 // could not use `Msb0` directly without padding adjustments. Instead, we use `Lsb0`
795 // throughout and reverse the bit order of each prefix.
796
797 let mut packed = self
798 .prefixes
799 .iter()
800 .flat_map(|input| input.iter().rev())
801 .collect::<BitVec<u8, Lsb0>>();
802 packed.set_uninitialized(false);
803 let mut packed = packed.into_vec();
804 packed.reverse();
805 bytes.append(&mut packed);
806 Ok(())
807 }
808
809 fn encoded_len(&self) -> Option<usize> {
810 let packed_bit_count = (usize::from(self.level) + 1) * self.prefixes.len();
811 // 4 bytes for the number of prefixes, 2 bytes for the level, and a variable number of bytes
812 // for the packed prefixes themselves.
813 Some(6 + (packed_bit_count + 7) / 8)
814 }
815 }
816
817 impl Decode for Poplar1AggregationParam {
818 fn decode(bytes: &mut Cursor<&[u8]>) -> Result<Self, CodecError> {
819 let level = u16::decode(bytes)?;
820 let prefix_count =
821 usize::try_from(u32::decode(bytes)?).map_err(|e| CodecError::Other(e.into()))?;
822
823 let packed_bit_count = (usize::from(level) + 1) * prefix_count;
824 let mut packed = vec![0u8; (packed_bit_count + 7) / 8];
825 bytes.read_exact(&mut packed)?;
826 if packed_bit_count % 8 != 0 {
827 let unused_bits = packed[0] >> (packed_bit_count % 8);
828 if unused_bits != 0 {
829 return Err(CodecError::UnexpectedValue);
830 }
831 }
832 packed.reverse();
833 let bits = BitVec::<u8, Lsb0>::from_vec(packed);
834
835 let prefixes = bits
836 .chunks_exact(usize::from(level) + 1)
837 .take(prefix_count)
838 .map(|chunk| IdpfInput::from(chunk.iter().rev().collect::<BitVec>()))
839 .collect::<Vec<IdpfInput>>();
840
841 Poplar1AggregationParam::try_from_prefixes(prefixes)
842 .map_err(|e| CodecError::Other(e.into()))
843 }
844 }
845
846 impl<P: Xof<SEED_SIZE>, const SEED_SIZE: usize> Vdaf for Poplar1<P, SEED_SIZE> {
847 type Measurement = IdpfInput;
848 type AggregateResult = Vec<u64>;
849 type AggregationParam = Poplar1AggregationParam;
850 type PublicShare = Poplar1PublicShare;
851 type InputShare = Poplar1InputShare<SEED_SIZE>;
852 type OutputShare = Poplar1FieldVec;
853 type AggregateShare = Poplar1FieldVec;
854
855 fn algorithm_id(&self) -> u32 {
856 0x00001000
857 }
858
859 fn num_aggregators(&self) -> usize {
860 2
861 }
862 }
863
864 impl<P: Xof<SEED_SIZE>, const SEED_SIZE: usize> Poplar1<P, SEED_SIZE> {
865 fn shard_with_random(
866 &self,
867 input: &IdpfInput,
868 nonce: &[u8; 16],
869 idpf_random: &[[u8; 16]; 2],
870 poplar_random: &[[u8; SEED_SIZE]; 3],
871 ) -> Result<(Poplar1PublicShare, Vec<Poplar1InputShare<SEED_SIZE>>), VdafError> {
872 if input.len() != self.bits {
873 return Err(VdafError::Uncategorized(format!(
874 "unexpected input length ({})",
875 input.len()
876 )));
877 }
878
879 // Generate the authenticator for each inner level of the IDPF tree.
880 let mut prng =
881 self.init_prng::<_, _, Field64>(&poplar_random[2], DST_SHARD_RANDOMNESS, [nonce]);
882 let auth_inner: Vec<Field64> = (0..self.bits - 1).map(|_| prng.get()).collect();
883
884 // Generate the authenticator for the last level of the IDPF tree (i.e., the leaves).
885 //
886 // TODO(cjpatton) spec: Consider using a different XOF for the leaf and inner nodes.
887 // "Switching" the XOF between field types is awkward.
888 let mut prng = prng.into_new_field::<Field255>();
889 let auth_leaf = prng.get();
890
891 // Generate the IDPF shares.
892 let idpf = Idpf::new((), ());
893 let (public_share, [idpf_key_0, idpf_key_1]) = idpf.gen_with_random(
894 input,
895 auth_inner
896 .iter()
897 .map(|auth| Poplar1IdpfValue([Field64::one(), *auth])),
898 Poplar1IdpfValue([Field255::one(), auth_leaf]),
899 nonce,
900 idpf_random,
901 )?;
902
903 // Generate the correlated randomness for the inner nodes. This includes additive shares of
904 // the random offsets `a, b, c` and additive shares of `A := -2*a + auth` and `B := a^2 + b
905 // - a*auth + c`, where `auth` is the authenticator for the level of the tree. These values
906 // are used, respectively, to compute and verify the sketch during the preparation phase.
907 // (See Section 4.2 of [BBCG+21].)
908 let corr_seed_0 = &poplar_random[0];
909 let corr_seed_1 = &poplar_random[1];
910 let mut prng = prng.into_new_field::<Field64>();
911 let mut corr_prng_0 = self.init_prng::<_, _, Field64>(
912 corr_seed_0,
913 DST_CORR_INNER,
914 [[0].as_slice(), nonce.as_slice()],
915 );
916 let mut corr_prng_1 = self.init_prng::<_, _, Field64>(
917 corr_seed_1,
918 DST_CORR_INNER,
919 [[1].as_slice(), nonce.as_slice()],
920 );
921 let mut corr_inner_0 = Vec::with_capacity(self.bits - 1);
922 let mut corr_inner_1 = Vec::with_capacity(self.bits - 1);
923 for auth in auth_inner.into_iter() {
924 let (next_corr_inner_0, next_corr_inner_1) =
925 compute_next_corr_shares(&mut prng, &mut corr_prng_0, &mut corr_prng_1, auth);
926 corr_inner_0.push(next_corr_inner_0);
927 corr_inner_1.push(next_corr_inner_1);
928 }
929
930 // Generate the correlated randomness for the leaf nodes.
931 let mut prng = prng.into_new_field::<Field255>();
932 let mut corr_prng_0 = self.init_prng::<_, _, Field255>(
933 corr_seed_0,
934 DST_CORR_LEAF,
935 [[0].as_slice(), nonce.as_slice()],
936 );
937 let mut corr_prng_1 = self.init_prng::<_, _, Field255>(
938 corr_seed_1,
939 DST_CORR_LEAF,
940 [[1].as_slice(), nonce.as_slice()],
941 );
942 let (corr_leaf_0, corr_leaf_1) =
943 compute_next_corr_shares(&mut prng, &mut corr_prng_0, &mut corr_prng_1, auth_leaf);
944
945 Ok((
946 public_share,
947 vec![
948 Poplar1InputShare {
949 idpf_key: idpf_key_0,
950 corr_seed: Seed::from_bytes(*corr_seed_0),
951 corr_inner: corr_inner_0,
952 corr_leaf: corr_leaf_0,
953 },
954 Poplar1InputShare {
955 idpf_key: idpf_key_1,
956 corr_seed: Seed::from_bytes(*corr_seed_1),
957 corr_inner: corr_inner_1,
958 corr_leaf: corr_leaf_1,
959 },
960 ],
961 ))
962 }
963
964 /// Evaluate the IDPF at the given prefixes and compute the Aggregator's share of the sketch.
965 #[allow(clippy::too_many_arguments)]
966 fn eval_and_sketch<F>(
967 &self,
968 verify_key: &[u8; SEED_SIZE],
969 agg_id: usize,
970 nonce: &[u8; 16],
971 agg_param: &Poplar1AggregationParam,
972 public_share: &Poplar1PublicShare,
973 idpf_key: &Seed<16>,
974 corr_prng: &mut Prng<F, P::SeedStream>,
975 ) -> Result<(Vec<F>, Vec<F>), VdafError>
976 where
977 P: Xof<SEED_SIZE>,
978 F: FieldElement,
979 Poplar1IdpfValue<F>:
980 From<IdpfOutputShare<Poplar1IdpfValue<Field64>, Poplar1IdpfValue<Field255>>>,
981 {
982 let mut verify_prng = self.init_prng(
983 verify_key,
984 DST_VERIFY_RANDOMNESS,
985 [nonce.as_slice(), agg_param.level.to_be_bytes().as_slice()],
986 );
987
988 let mut out_share = Vec::with_capacity(agg_param.prefixes.len());
989 let mut sketch_share = vec![
990 corr_prng.get(), // a_share
991 corr_prng.get(), // b_share
992 corr_prng.get(), // c_share
993 ];
994
995 let mut idpf_eval_cache = RingBufferCache::new(agg_param.prefixes.len());
996 let idpf = Idpf::<Poplar1IdpfValue<Field64>, Poplar1IdpfValue<Field255>>::new((), ());
997 for prefix in agg_param.prefixes.iter() {
998 let share = Poplar1IdpfValue::<F>::from(idpf.eval(
999 agg_id,
1000 public_share,
1001 idpf_key,
1002 prefix,
1003 nonce,
1004 &mut idpf_eval_cache,
1005 )?);
1006
1007 let r = verify_prng.get();
1008 let checked_data_share = share.0[0] * r;
1009 sketch_share[0] += checked_data_share;
1010 sketch_share[1] += checked_data_share * r;
1011 sketch_share[2] += share.0[1] * r;
1012 out_share.push(share.0[0]);
1013 }
1014
1015 Ok((out_share, sketch_share))
1016 }
1017 }
1018
1019 impl<P: Xof<SEED_SIZE>, const SEED_SIZE: usize> Client<16> for Poplar1<P, SEED_SIZE> {
1020 fn shard(
1021 &self,
1022 input: &IdpfInput,
1023 nonce: &[u8; 16],
1024 ) -> Result<(Self::PublicShare, Vec<Poplar1InputShare<SEED_SIZE>>), VdafError> {
1025 let mut idpf_random = [[0u8; 16]; 2];
1026 let mut poplar_random = [[0u8; SEED_SIZE]; 3];
1027 for random_seed in idpf_random.iter_mut() {
1028 getrandom::getrandom(random_seed)?;
1029 }
1030 for random_seed in poplar_random.iter_mut() {
1031 getrandom::getrandom(random_seed)?;
1032 }
1033 self.shard_with_random(input, nonce, &idpf_random, &poplar_random)
1034 }
1035 }
1036
1037 impl<P: Xof<SEED_SIZE>, const SEED_SIZE: usize> Aggregator<SEED_SIZE, 16>
1038 for Poplar1<P, SEED_SIZE>
1039 {
1040 type PrepareState = Poplar1PrepareState;
1041 type PrepareShare = Poplar1FieldVec;
1042 type PrepareMessage = Poplar1PrepareMessage;
1043
1044 #[allow(clippy::type_complexity)]
1045 fn prepare_init(
1046 &self,
1047 verify_key: &[u8; SEED_SIZE],
1048 agg_id: usize,
1049 agg_param: &Poplar1AggregationParam,
1050 nonce: &[u8; 16],
1051 public_share: &Poplar1PublicShare,
1052 input_share: &Poplar1InputShare<SEED_SIZE>,
1053 ) -> Result<(Poplar1PrepareState, Poplar1FieldVec), VdafError> {
1054 let is_leader = match agg_id {
1055 0 => true,
1056 1 => false,
1057 _ => {
1058 return Err(VdafError::Uncategorized(format!(
1059 "invalid aggregator ID ({agg_id})"
1060 )))
1061 }
1062 };
1063
1064 if usize::from(agg_param.level) < self.bits - 1 {
1065 let mut corr_prng = self.init_prng::<_, _, Field64>(
1066 input_share.corr_seed.as_ref(),
1067 DST_CORR_INNER,
1068 [[agg_id as u8].as_slice(), nonce.as_slice()],
1069 );
1070 // Fast-forward the correlated randomness XOF to the level of the tree that we are
1071 // aggregating.
1072 for _ in 0..3 * agg_param.level {
1073 corr_prng.get();
1074 }
1075
1076 let (output_share, sketch_share) = self.eval_and_sketch::<Field64>(
1077 verify_key,
1078 agg_id,
1079 nonce,
1080 agg_param,
1081 public_share,
1082 &input_share.idpf_key,
1083 &mut corr_prng,
1084 )?;
1085
1086 Ok((
1087 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
1088 sketch: SketchState::RoundOne {
1089 A_share: input_share.corr_inner[usize::from(agg_param.level)][0],
1090 B_share: input_share.corr_inner[usize::from(agg_param.level)][1],
1091 is_leader,
1092 },
1093 output_share,
1094 })),
1095 Poplar1FieldVec::Inner(sketch_share),
1096 ))
1097 } else {
1098 let corr_prng = self.init_prng::<_, _, Field255>(
1099 input_share.corr_seed.as_ref(),
1100 DST_CORR_LEAF,
1101 [[agg_id as u8].as_slice(), nonce.as_slice()],
1102 );
1103
1104 let (output_share, sketch_share) = self.eval_and_sketch::<Field255>(
1105 verify_key,
1106 agg_id,
1107 nonce,
1108 agg_param,
1109 public_share,
1110 &input_share.idpf_key,
1111 &mut corr_prng.into_new_field(),
1112 )?;
1113
1114 Ok((
1115 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
1116 sketch: SketchState::RoundOne {
1117 A_share: input_share.corr_leaf[0],
1118 B_share: input_share.corr_leaf[1],
1119 is_leader,
1120 },
1121 output_share,
1122 })),
1123 Poplar1FieldVec::Leaf(sketch_share),
1124 ))
1125 }
1126 }
1127
1128 fn prepare_shares_to_prepare_message<M: IntoIterator<Item = Poplar1FieldVec>>(
1129 &self,
1130 _: &Poplar1AggregationParam,
1131 inputs: M,
1132 ) -> Result<Poplar1PrepareMessage, VdafError> {
1133 let mut inputs = inputs.into_iter();
1134 let prep_share_0 = inputs
1135 .next()
1136 .ok_or_else(|| VdafError::Uncategorized("insufficient number of prep shares".into()))?;
1137 let prep_share_1 = inputs
1138 .next()
1139 .ok_or_else(|| VdafError::Uncategorized("insufficient number of prep shares".into()))?;
1140 if inputs.next().is_some() {
1141 return Err(VdafError::Uncategorized(
1142 "more prep shares than expected".into(),
1143 ));
1144 }
1145
1146 match (prep_share_0, prep_share_1) {
1147 (Poplar1FieldVec::Inner(share_0), Poplar1FieldVec::Inner(share_1)) => {
1148 Ok(Poplar1PrepareMessage(
1149 next_message(share_0, share_1)?.map_or(PrepareMessageVariant::Done, |sketch| {
1150 PrepareMessageVariant::SketchInner(sketch)
1151 }),
1152 ))
1153 }
1154 (Poplar1FieldVec::Leaf(share_0), Poplar1FieldVec::Leaf(share_1)) => {
1155 Ok(Poplar1PrepareMessage(
1156 next_message(share_0, share_1)?.map_or(PrepareMessageVariant::Done, |sketch| {
1157 PrepareMessageVariant::SketchLeaf(sketch)
1158 }),
1159 ))
1160 }
1161 _ => Err(VdafError::Uncategorized(
1162 "received prep shares with mismatched field types".into(),
1163 )),
1164 }
1165 }
1166
1167 fn prepare_next(
1168 &self,
1169 state: Poplar1PrepareState,
1170 msg: Poplar1PrepareMessage,
1171 ) -> Result<PrepareTransition<Self, SEED_SIZE, 16>, VdafError> {
1172 match (state.0, msg.0) {
1173 // Round one
1174 (
1175 PrepareStateVariant::Inner(PrepareState {
1176 sketch:
1177 SketchState::RoundOne {
1178 A_share,
1179 B_share,
1180 is_leader,
1181 },
1182 output_share,
1183 }),
1184 PrepareMessageVariant::SketchInner(sketch),
1185 ) => Ok(PrepareTransition::Continue(
1186 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
1187 sketch: SketchState::RoundTwo,
1188 output_share,
1189 })),
1190 Poplar1FieldVec::Inner(finish_sketch(sketch, A_share, B_share, is_leader)),
1191 )),
1192 (
1193 PrepareStateVariant::Leaf(PrepareState {
1194 sketch:
1195 SketchState::RoundOne {
1196 A_share,
1197 B_share,
1198 is_leader,
1199 },
1200 output_share,
1201 }),
1202 PrepareMessageVariant::SketchLeaf(sketch),
1203 ) => Ok(PrepareTransition::Continue(
1204 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
1205 sketch: SketchState::RoundTwo,
1206 output_share,
1207 })),
1208 Poplar1FieldVec::Leaf(finish_sketch(sketch, A_share, B_share, is_leader)),
1209 )),
1210
1211 // Round two
1212 (
1213 PrepareStateVariant::Inner(PrepareState {
1214 sketch: SketchState::RoundTwo,
1215 output_share,
1216 }),
1217 PrepareMessageVariant::Done,
1218 ) => Ok(PrepareTransition::Finish(Poplar1FieldVec::Inner(
1219 output_share,
1220 ))),
1221 (
1222 PrepareStateVariant::Leaf(PrepareState {
1223 sketch: SketchState::RoundTwo,
1224 output_share,
1225 }),
1226 PrepareMessageVariant::Done,
1227 ) => Ok(PrepareTransition::Finish(Poplar1FieldVec::Leaf(
1228 output_share,
1229 ))),
1230
1231 _ => Err(VdafError::Uncategorized(
1232 "prep message field type does not match state".into(),
1233 )),
1234 }
1235 }
1236
1237 fn aggregate<M: IntoIterator<Item = Poplar1FieldVec>>(
1238 &self,
1239 agg_param: &Poplar1AggregationParam,
1240 output_shares: M,
1241 ) -> Result<Poplar1FieldVec, VdafError> {
1242 aggregate(
1243 usize::from(agg_param.level) == self.bits - 1,
1244 agg_param.prefixes.len(),
1245 output_shares,
1246 )
1247 }
1248 }
1249
1250 impl<P: Xof<SEED_SIZE>, const SEED_SIZE: usize> Collector for Poplar1<P, SEED_SIZE> {
1251 fn unshard<M: IntoIterator<Item = Poplar1FieldVec>>(
1252 &self,
1253 agg_param: &Poplar1AggregationParam,
1254 agg_shares: M,
1255 _num_measurements: usize,
1256 ) -> Result<Vec<u64>, VdafError> {
1257 let result = aggregate(
1258 usize::from(agg_param.level) == self.bits - 1,
1259 agg_param.prefixes.len(),
1260 agg_shares,
1261 )?;
1262
1263 match result {
1264 Poplar1FieldVec::Inner(vec) => Ok(vec.into_iter().map(u64::from).collect()),
1265 Poplar1FieldVec::Leaf(vec) => Ok(vec
1266 .into_iter()
1267 .map(u64::try_from)
1268 .collect::<Result<Vec<_>, _>>()?),
1269 }
1270 }
1271 }
1272
1273 impl From<IdpfOutputShare<Poplar1IdpfValue<Field64>, Poplar1IdpfValue<Field255>>>
1274 for Poplar1IdpfValue<Field64>
1275 {
1276 fn from(
1277 out_share: IdpfOutputShare<Poplar1IdpfValue<Field64>, Poplar1IdpfValue<Field255>>,
1278 ) -> Poplar1IdpfValue<Field64> {
1279 match out_share {
1280 IdpfOutputShare::Inner(array) => array,
1281 IdpfOutputShare::Leaf(..) => panic!("tried to convert leaf share into inner field"),
1282 }
1283 }
1284 }
1285
1286 impl From<IdpfOutputShare<Poplar1IdpfValue<Field64>, Poplar1IdpfValue<Field255>>>
1287 for Poplar1IdpfValue<Field255>
1288 {
1289 fn from(
1290 out_share: IdpfOutputShare<Poplar1IdpfValue<Field64>, Poplar1IdpfValue<Field255>>,
1291 ) -> Poplar1IdpfValue<Field255> {
1292 match out_share {
1293 IdpfOutputShare::Inner(..) => panic!("tried to convert inner share into leaf field"),
1294 IdpfOutputShare::Leaf(array) => array,
1295 }
1296 }
1297 }
1298
1299 /// Derive shares of the correlated randomness for the next level of the IDPF tree.
1300 //
1301 // TODO(cjpatton) spec: Consider deriving the shares of a, b, c for each level directly from the
1302 // seed, rather than iteratively, as we do in Doplar. This would be more efficient for the
1303 // Aggregators. As long as the Client isn't significantly slower, this should be a win.
1304 #[allow(non_snake_case)]
1305 fn compute_next_corr_shares<F: FieldElement + From<u64>, S: RngCore>(
1306 prng: &mut Prng<F, S>,
1307 corr_prng_0: &mut Prng<F, S>,
1308 corr_prng_1: &mut Prng<F, S>,
1309 auth: F,
1310 ) -> ([F; 2], [F; 2]) {
1311 let two = F::from(2);
1312 let a = corr_prng_0.get() + corr_prng_1.get();
1313 let b = corr_prng_0.get() + corr_prng_1.get();
1314 let c = corr_prng_0.get() + corr_prng_1.get();
1315 let A = -two * a + auth;
1316 let B = a * a + b - a * auth + c;
1317 let corr_1 = [prng.get(), prng.get()];
1318 let corr_0 = [A - corr_1[0], B - corr_1[1]];
1319 (corr_0, corr_1)
1320 }
1321
1322 /// Compute the Aggregator's share of the sketch verifier. The shares should sum to zero.
1323 #[allow(non_snake_case)]
1324 fn finish_sketch<F: FieldElement>(
1325 sketch: [F; 3],
1326 A_share: F,
1327 B_share: F,
1328 is_leader: bool,
1329 ) -> Vec<F> {
1330 let mut next_sketch_share = A_share * sketch[0] + B_share;
1331 if !is_leader {
1332 next_sketch_share += sketch[0] * sketch[0] - sketch[1] - sketch[2];
1333 }
1334 vec![next_sketch_share]
1335 }
1336
1337 fn next_message<F: FieldElement>(
1338 mut share_0: Vec<F>,
1339 share_1: Vec<F>,
1340 ) -> Result<Option<[F; 3]>, VdafError> {
1341 merge_vector(&mut share_0, &share_1)?;
1342
1343 if share_0.len() == 1 {
1344 if share_0[0] != F::zero() {
1345 Err(VdafError::Uncategorized(
1346 "sketch verification failed".into(),
1347 )) // Invalid sketch
1348 } else {
1349 Ok(None) // Sketch verification succeeded
1350 }
1351 } else if share_0.len() == 3 {
1352 Ok(Some([share_0[0], share_0[1], share_0[2]])) // Sketch verification continues
1353 } else {
1354 Err(VdafError::Uncategorized(format!(
1355 "unexpected sketch length ({})",
1356 share_0.len()
1357 )))
1358 }
1359 }
1360
1361 fn aggregate<M: IntoIterator<Item = Poplar1FieldVec>>(
1362 is_leaf: bool,
1363 len: usize,
1364 shares: M,
1365 ) -> Result<Poplar1FieldVec, VdafError> {
1366 let mut result = Poplar1FieldVec::zero(is_leaf, len);
1367 for share in shares.into_iter() {
1368 result.accumulate(&share)?;
1369 }
1370 Ok(result)
1371 }
1372
1373 /// A vector of two field elements.
1374 ///
1375 /// This represents the values that Poplar1 programs into IDPFs while sharding.
1376 #[derive(Debug, Clone, Copy)]
1377 pub struct Poplar1IdpfValue<F>([F; 2]);
1378
1379 impl<F> Poplar1IdpfValue<F> {
1380 /// Create a new value from a pair of field elements.
1381 pub fn new(array: [F; 2]) -> Self {
1382 Self(array)
1383 }
1384 }
1385
1386 impl<F> IdpfValue for Poplar1IdpfValue<F>
1387 where
1388 F: FieldElement,
1389 {
1390 type ValueParameter = ();
1391
1392 fn zero(_: &()) -> Self {
1393 Self([F::zero(); 2])
1394 }
1395
1396 fn generate<S: RngCore>(seed_stream: &mut S, _: &()) -> Self {
1397 Self([F::generate(seed_stream, &()), F::generate(seed_stream, &())])
1398 }
1399
1400 fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
1401 ConditionallySelectable::conditional_select(a, b, choice)
1402 }
1403 }
1404
1405 impl<F> Add for Poplar1IdpfValue<F>
1406 where
1407 F: Copy + Add<Output = F>,
1408 {
1409 type Output = Self;
1410
1411 fn add(self, rhs: Self) -> Self {
1412 Self([self.0[0] + rhs.0[0], self.0[1] + rhs.0[1]])
1413 }
1414 }
1415
1416 impl<F> AddAssign for Poplar1IdpfValue<F>
1417 where
1418 F: Copy + AddAssign,
1419 {
1420 fn add_assign(&mut self, rhs: Self) {
1421 self.0[0] += rhs.0[0];
1422 self.0[1] += rhs.0[1];
1423 }
1424 }
1425
1426 impl<F> Sub for Poplar1IdpfValue<F>
1427 where
1428 F: Copy + Sub<Output = F>,
1429 {
1430 type Output = Self;
1431
1432 fn sub(self, rhs: Self) -> Self {
1433 Self([self.0[0] - rhs.0[0], self.0[1] - rhs.0[1]])
1434 }
1435 }
1436
1437 impl<F> PartialEq for Poplar1IdpfValue<F>
1438 where
1439 F: PartialEq,
1440 {
1441 fn eq(&self, other: &Self) -> bool {
1442 self.0 == other.0
1443 }
1444 }
1445
1446 impl<F> ConstantTimeEq for Poplar1IdpfValue<F>
1447 where
1448 F: ConstantTimeEq,
1449 {
1450 fn ct_eq(&self, other: &Self) -> Choice {
1451 self.0.ct_eq(&other.0)
1452 }
1453 }
1454
1455 impl<F> Encode for Poplar1IdpfValue<F>
1456 where
1457 F: FieldElement,
1458 {
1459 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
1460 self.0[0].encode(bytes)?;
1461 self.0[1].encode(bytes)
1462 }
1463
1464 fn encoded_len(&self) -> Option<usize> {
1465 Some(F::ENCODED_SIZE * 2)
1466 }
1467 }
1468
1469 impl<F> Decode for Poplar1IdpfValue<F>
1470 where
1471 F: Decode,
1472 {
1473 fn decode(bytes: &mut Cursor<&[u8]>) -> Result<Self, CodecError> {
1474 Ok(Self([F::decode(bytes)?, F::decode(bytes)?]))
1475 }
1476 }
1477
1478 impl<F> ConditionallySelectable for Poplar1IdpfValue<F>
1479 where
1480 F: ConditionallySelectable,
1481 {
1482 fn conditional_select(a: &Self, b: &Self, choice: subtle::Choice) -> Self {
1483 Self([
1484 F::conditional_select(&a.0[0], &b.0[0], choice),
1485 F::conditional_select(&a.0[1], &b.0[1], choice),
1486 ])
1487 }
1488 }
1489
1490 impl<F> ConditionallyNegatable for Poplar1IdpfValue<F>
1491 where
1492 F: ConditionallyNegatable,
1493 {
1494 fn conditional_negate(&mut self, choice: subtle::Choice) {
1495 F::conditional_negate(&mut self.0[0], choice);
1496 F::conditional_negate(&mut self.0[1], choice);
1497 }
1498 }
1499
1500 #[cfg(test)]
1501 mod tests {
1502 use super::*;
1503 use crate::vdaf::{equality_comparison_test, test_utils::run_vdaf_prepare};
1504 use assert_matches::assert_matches;
1505 use rand::prelude::*;
1506 use serde::Deserialize;
1507 use std::collections::HashSet;
1508
1509 fn test_prepare<P: Xof<SEED_SIZE>, const SEED_SIZE: usize>(
1510 vdaf: &Poplar1<P, SEED_SIZE>,
1511 verify_key: &[u8; SEED_SIZE],
1512 nonce: &[u8; 16],
1513 public_share: &Poplar1PublicShare,
1514 input_shares: &[Poplar1InputShare<SEED_SIZE>],
1515 agg_param: &Poplar1AggregationParam,
1516 expected_result: Vec<u64>,
1517 ) {
1518 let out_shares = run_vdaf_prepare(
1519 vdaf,
1520 verify_key,
1521 agg_param,
1522 nonce,
1523 public_share.clone(),
1524 input_shares.to_vec(),
1525 )
1526 .unwrap();
1527
1528 // Convert aggregate shares and unshard.
1529 let agg_share_0 = vdaf.aggregate(agg_param, [out_shares[0].clone()]).unwrap();
1530 let agg_share_1 = vdaf.aggregate(agg_param, [out_shares[1].clone()]).unwrap();
1531 let result = vdaf
1532 .unshard(agg_param, [agg_share_0, agg_share_1], 1)
1533 .unwrap();
1534 assert_eq!(
1535 result, expected_result,
1536 "unexpected result (level={})",
1537 agg_param.level
1538 );
1539 }
1540
1541 fn run_heavy_hitters<B: AsRef<[u8]>, P: Xof<SEED_SIZE>, const SEED_SIZE: usize>(
1542 vdaf: &Poplar1<P, SEED_SIZE>,
1543 verify_key: &[u8; SEED_SIZE],
1544 threshold: usize,
1545 measurements: impl IntoIterator<Item = B>,
1546 expected_result: impl IntoIterator<Item = B>,
1547 ) {
1548 let mut rng = thread_rng();
1549
1550 // Sharding step
1551 let reports: Vec<(
1552 [u8; 16],
1553 Poplar1PublicShare,
1554 Vec<Poplar1InputShare<SEED_SIZE>>,
1555 )> = measurements
1556 .into_iter()
1557 .map(|measurement| {
1558 let nonce = rng.gen();
1559 let (public_share, input_shares) = vdaf
1560 .shard(&IdpfInput::from_bytes(measurement.as_ref()), &nonce)
1561 .unwrap();
1562 (nonce, public_share, input_shares)
1563 })
1564 .collect();
1565
1566 let mut agg_param = Poplar1AggregationParam {
1567 level: 0,
1568 prefixes: vec![
1569 IdpfInput::from_bools(&[false]),
1570 IdpfInput::from_bools(&[true]),
1571 ],
1572 };
1573
1574 let mut agg_result = Vec::new();
1575 for level in 0..vdaf.bits {
1576 let mut out_shares_0 = Vec::with_capacity(reports.len());
1577 let mut out_shares_1 = Vec::with_capacity(reports.len());
1578
1579 // Preparation step
1580 for (nonce, public_share, input_shares) in reports.iter() {
1581 let out_shares = run_vdaf_prepare(
1582 vdaf,
1583 verify_key,
1584 &agg_param,
1585 nonce,
1586 public_share.clone(),
1587 input_shares.to_vec(),
1588 )
1589 .unwrap();
1590
1591 out_shares_0.push(out_shares[0].clone());
1592 out_shares_1.push(out_shares[1].clone());
1593 }
1594
1595 // Aggregation step
1596 let agg_share_0 = vdaf.aggregate(&agg_param, out_shares_0).unwrap();
1597 let agg_share_1 = vdaf.aggregate(&agg_param, out_shares_1).unwrap();
1598
1599 // Unsharding step
1600 agg_result = vdaf
1601 .unshard(&agg_param, [agg_share_0, agg_share_1], reports.len())
1602 .unwrap();
1603
1604 agg_param.level += 1;
1605
1606 // Unless this is the last level of the tree, construct the next set of candidate
1607 // prefixes.
1608 if level < vdaf.bits - 1 {
1609 let mut next_prefixes = Vec::new();
1610 for (prefix, count) in agg_param.prefixes.into_iter().zip(agg_result.iter()) {
1611 if *count >= threshold as u64 {
1612 next_prefixes.push(prefix.clone_with_suffix(&[false]));
1613 next_prefixes.push(prefix.clone_with_suffix(&[true]));
1614 }
1615 }
1616
1617 agg_param.prefixes = next_prefixes;
1618 }
1619 }
1620
1621 let got: HashSet<IdpfInput> = agg_param
1622 .prefixes
1623 .into_iter()
1624 .zip(agg_result.iter())
1625 .filter(|(_prefix, count)| **count >= threshold as u64)
1626 .map(|(prefix, _count)| prefix)
1627 .collect();
1628
1629 let want: HashSet<IdpfInput> = expected_result
1630 .into_iter()
1631 .map(|bytes| IdpfInput::from_bytes(bytes.as_ref()))
1632 .collect();
1633
1634 assert_eq!(got, want);
1635 }
1636
1637 #[test]
1638 fn shard_prepare() {
1639 let mut rng = thread_rng();
1640 let vdaf = Poplar1::new_turboshake128(64);
1641 let verify_key = rng.gen();
1642 let input = IdpfInput::from_bytes(b"12341324");
1643 let nonce = rng.gen();
1644 let (public_share, input_shares) = vdaf.shard(&input, &nonce).unwrap();
1645
1646 test_prepare(
1647 &vdaf,
1648 &verify_key,
1649 &nonce,
1650 &public_share,
1651 &input_shares,
1652 &Poplar1AggregationParam {
1653 level: 7,
1654 prefixes: vec![
1655 IdpfInput::from_bytes(b"0"),
1656 IdpfInput::from_bytes(b"1"),
1657 IdpfInput::from_bytes(b"2"),
1658 IdpfInput::from_bytes(b"f"),
1659 ],
1660 },
1661 vec![0, 1, 0, 0],
1662 );
1663
1664 for level in 0..vdaf.bits {
1665 test_prepare(
1666 &vdaf,
1667 &verify_key,
1668 &nonce,
1669 &public_share,
1670 &input_shares,
1671 &Poplar1AggregationParam {
1672 level: level as u16,
1673 prefixes: vec![input.prefix(level)],
1674 },
1675 vec![1],
1676 );
1677 }
1678 }
1679
1680 #[test]
1681 fn heavy_hitters() {
1682 let mut rng = thread_rng();
1683 let verify_key = rng.gen();
1684 let vdaf = Poplar1::new_turboshake128(8);
1685
1686 run_heavy_hitters(
1687 &vdaf,
1688 &verify_key,
1689 2, // threshold
1690 [
1691 "a", "b", "c", "d", "e", "f", "g", "g", "h", "i", "i", "i", "j", "j", "k", "l",
1692 ], // measurements
1693 ["g", "i", "j"], // heavy hitters
1694 );
1695 }
1696
1697 #[test]
1698 fn encoded_len() {
1699 // Input share
1700 let input_share = Poplar1InputShare {
1701 idpf_key: Seed::<16>::generate().unwrap(),
1702 corr_seed: Seed::<16>::generate().unwrap(),
1703 corr_inner: vec![
1704 [Field64::one(), <Field64 as FieldElement>::zero()],
1705 [Field64::one(), <Field64 as FieldElement>::zero()],
1706 [Field64::one(), <Field64 as FieldElement>::zero()],
1707 ],
1708 corr_leaf: [Field255::one(), <Field255 as FieldElement>::zero()],
1709 };
1710 assert_eq!(
1711 input_share.get_encoded().unwrap().len(),
1712 input_share.encoded_len().unwrap()
1713 );
1714
1715 // Prepaare message variants
1716 let prep_msg = Poplar1PrepareMessage(PrepareMessageVariant::SketchInner([
1717 Field64::one(),
1718 Field64::one(),
1719 Field64::one(),
1720 ]));
1721 assert_eq!(
1722 prep_msg.get_encoded().unwrap().len(),
1723 prep_msg.encoded_len().unwrap()
1724 );
1725 let prep_msg = Poplar1PrepareMessage(PrepareMessageVariant::SketchLeaf([
1726 Field255::one(),
1727 Field255::one(),
1728 Field255::one(),
1729 ]));
1730 assert_eq!(
1731 prep_msg.get_encoded().unwrap().len(),
1732 prep_msg.encoded_len().unwrap()
1733 );
1734 let prep_msg = Poplar1PrepareMessage(PrepareMessageVariant::Done);
1735 assert_eq!(
1736 prep_msg.get_encoded().unwrap().len(),
1737 prep_msg.encoded_len().unwrap()
1738 );
1739
1740 // Field vector variants.
1741 let field_vec = Poplar1FieldVec::Inner(vec![Field64::one(); 23]);
1742 assert_eq!(
1743 field_vec.get_encoded().unwrap().len(),
1744 field_vec.encoded_len().unwrap()
1745 );
1746 let field_vec = Poplar1FieldVec::Leaf(vec![Field255::one(); 23]);
1747 assert_eq!(
1748 field_vec.get_encoded().unwrap().len(),
1749 field_vec.encoded_len().unwrap()
1750 );
1751
1752 // Aggregation parameter.
1753 let agg_param = Poplar1AggregationParam::try_from_prefixes(Vec::from([
1754 IdpfInput::from_bytes(b"ab"),
1755 IdpfInput::from_bytes(b"cd"),
1756 ]))
1757 .unwrap();
1758 assert_eq!(
1759 agg_param.get_encoded().unwrap().len(),
1760 agg_param.encoded_len().unwrap()
1761 );
1762 let agg_param = Poplar1AggregationParam::try_from_prefixes(Vec::from([
1763 IdpfInput::from_bools(&[false]),
1764 IdpfInput::from_bools(&[true]),
1765 ]))
1766 .unwrap();
1767 assert_eq!(
1768 agg_param.get_encoded().unwrap().len(),
1769 agg_param.encoded_len().unwrap()
1770 );
1771 }
1772
1773 #[test]
1774 fn round_trip_prepare_state() {
1775 let vdaf = Poplar1::new_turboshake128(1);
1776 for (agg_id, prep_state) in [
1777 (
1778 0,
1779 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
1780 sketch: SketchState::RoundOne {
1781 A_share: Field64::from(0),
1782 B_share: Field64::from(1),
1783 is_leader: true,
1784 },
1785 output_share: Vec::from([Field64::from(2), Field64::from(3), Field64::from(4)]),
1786 })),
1787 ),
1788 (
1789 1,
1790 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
1791 sketch: SketchState::RoundOne {
1792 A_share: Field64::from(5),
1793 B_share: Field64::from(6),
1794 is_leader: false,
1795 },
1796 output_share: Vec::from([Field64::from(7), Field64::from(8), Field64::from(9)]),
1797 })),
1798 ),
1799 (
1800 0,
1801 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
1802 sketch: SketchState::RoundTwo,
1803 output_share: Vec::from([
1804 Field64::from(10),
1805 Field64::from(11),
1806 Field64::from(12),
1807 ]),
1808 })),
1809 ),
1810 (
1811 1,
1812 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
1813 sketch: SketchState::RoundTwo,
1814 output_share: Vec::from([
1815 Field64::from(13),
1816 Field64::from(14),
1817 Field64::from(15),
1818 ]),
1819 })),
1820 ),
1821 (
1822 0,
1823 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
1824 sketch: SketchState::RoundOne {
1825 A_share: Field255::from(16),
1826 B_share: Field255::from(17),
1827 is_leader: true,
1828 },
1829 output_share: Vec::from([
1830 Field255::from(18),
1831 Field255::from(19),
1832 Field255::from(20),
1833 ]),
1834 })),
1835 ),
1836 (
1837 1,
1838 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
1839 sketch: SketchState::RoundOne {
1840 A_share: Field255::from(21),
1841 B_share: Field255::from(22),
1842 is_leader: false,
1843 },
1844 output_share: Vec::from([
1845 Field255::from(23),
1846 Field255::from(24),
1847 Field255::from(25),
1848 ]),
1849 })),
1850 ),
1851 (
1852 0,
1853 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
1854 sketch: SketchState::RoundTwo,
1855 output_share: Vec::from([
1856 Field255::from(26),
1857 Field255::from(27),
1858 Field255::from(28),
1859 ]),
1860 })),
1861 ),
1862 (
1863 1,
1864 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
1865 sketch: SketchState::RoundTwo,
1866 output_share: Vec::from([
1867 Field255::from(29),
1868 Field255::from(30),
1869 Field255::from(31),
1870 ]),
1871 })),
1872 ),
1873 ] {
1874 let encoded_prep_state = prep_state.get_encoded().unwrap();
1875 assert_eq!(prep_state.encoded_len(), Some(encoded_prep_state.len()));
1876 let decoded_prep_state =
1877 Poplar1PrepareState::get_decoded_with_param(&(&vdaf, agg_id), &encoded_prep_state)
1878 .unwrap();
1879 assert_eq!(prep_state, decoded_prep_state);
1880 }
1881 }
1882
1883 #[test]
1884 fn round_trip_agg_param() {
1885 // These test cases were generated using the reference Sage implementation.
1886 // (https://github.com/cfrg/draft-irtf-cfrg-vdaf/tree/main/poc) Sage statements used to
1887 // generate each test case are given in comments.
1888 for (prefixes, reference_encoding) in [
1889 // poplar.encode_agg_param(0, [0])
1890 (
1891 Vec::from([IdpfInput::from_bools(&[false])]),
1892 [0, 0, 0, 0, 0, 1, 0].as_slice(),
1893 ),
1894 // poplar.encode_agg_param(0, [1])
1895 (
1896 Vec::from([IdpfInput::from_bools(&[true])]),
1897 [0, 0, 0, 0, 0, 1, 1].as_slice(),
1898 ),
1899 // poplar.encode_agg_param(0, [0, 1])
1900 (
1901 Vec::from([
1902 IdpfInput::from_bools(&[false]),
1903 IdpfInput::from_bools(&[true]),
1904 ]),
1905 [0, 0, 0, 0, 0, 2, 2].as_slice(),
1906 ),
1907 // poplar.encode_agg_param(1, [0b00, 0b01, 0b10, 0b11])
1908 (
1909 Vec::from([
1910 IdpfInput::from_bools(&[false, false]),
1911 IdpfInput::from_bools(&[false, true]),
1912 IdpfInput::from_bools(&[true, false]),
1913 IdpfInput::from_bools(&[true, true]),
1914 ]),
1915 [0, 1, 0, 0, 0, 4, 0xe4].as_slice(),
1916 ),
1917 // poplar.encode_agg_param(1, [0b00, 0b10, 0b11])
1918 (
1919 Vec::from([
1920 IdpfInput::from_bools(&[false, false]),
1921 IdpfInput::from_bools(&[true, false]),
1922 IdpfInput::from_bools(&[true, true]),
1923 ]),
1924 [0, 1, 0, 0, 0, 3, 0x38].as_slice(),
1925 ),
1926 // poplar.encode_agg_param(2, [0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111])
1927 (
1928 Vec::from([
1929 IdpfInput::from_bools(&[false, false, false]),
1930 IdpfInput::from_bools(&[false, false, true]),
1931 IdpfInput::from_bools(&[false, true, false]),
1932 IdpfInput::from_bools(&[false, true, true]),
1933 IdpfInput::from_bools(&[true, false, false]),
1934 IdpfInput::from_bools(&[true, false, true]),
1935 IdpfInput::from_bools(&[true, true, false]),
1936 IdpfInput::from_bools(&[true, true, true]),
1937 ]),
1938 [0, 2, 0, 0, 0, 8, 0xfa, 0xc6, 0x88].as_slice(),
1939 ),
1940 // poplar.encode_agg_param(9, [0b01_1011_0010, 0b10_1101_1010])
1941 (
1942 Vec::from([
1943 IdpfInput::from_bools(&[
1944 false, true, true, false, true, true, false, false, true, false,
1945 ]),
1946 IdpfInput::from_bools(&[
1947 true, false, true, true, false, true, true, false, true, false,
1948 ]),
1949 ]),
1950 [0, 9, 0, 0, 0, 2, 0x0b, 0x69, 0xb2].as_slice(),
1951 ),
1952 // poplar.encode_agg_param(15, [0xcafe])
1953 (
1954 Vec::from([IdpfInput::from_bytes(b"\xca\xfe")]),
1955 [0, 15, 0, 0, 0, 1, 0xca, 0xfe].as_slice(),
1956 ),
1957 ] {
1958 let agg_param = Poplar1AggregationParam::try_from_prefixes(prefixes).unwrap();
1959 let encoded = agg_param.get_encoded().unwrap();
1960 assert_eq!(encoded, reference_encoding);
1961 let decoded = Poplar1AggregationParam::get_decoded(reference_encoding).unwrap();
1962 assert_eq!(decoded, agg_param);
1963 }
1964 }
1965
1966 #[test]
1967 fn agg_param_wrong_unused_bit() {
1968 let err = Poplar1AggregationParam::get_decoded(&[0, 0, 0, 0, 0, 1, 2]).unwrap_err();
1969 assert_matches!(err, CodecError::UnexpectedValue);
1970 }
1971
1972 #[test]
1973 fn agg_param_ordering() {
1974 let err = Poplar1AggregationParam::get_decoded(&[0, 0, 0, 0, 0, 2, 1]).unwrap_err();
1975 assert_matches!(err, CodecError::Other(_));
1976 let err = Poplar1AggregationParam::get_decoded(&[0, 0, 0, 0, 0, 2, 0]).unwrap_err();
1977 assert_matches!(err, CodecError::Other(_));
1978 let err = Poplar1AggregationParam::get_decoded(&[0, 0, 0, 0, 0, 2, 3]).unwrap_err();
1979 assert_matches!(err, CodecError::Other(_));
1980 }
1981
1982 #[derive(Debug, Deserialize)]
1983 struct HexEncoded(#[serde(with = "hex")] Vec<u8>);
1984
1985 impl AsRef<[u8]> for HexEncoded {
1986 fn as_ref(&self) -> &[u8] {
1987 &self.0
1988 }
1989 }
1990
1991 #[derive(Debug, Deserialize)]
1992 struct PoplarTestVector {
1993 agg_param: (usize, Vec<u64>),
1994 agg_result: Vec<u64>,
1995 agg_shares: Vec<HexEncoded>,
1996 bits: usize,
1997 prep: Vec<PreparationTestVector>,
1998 verify_key: HexEncoded,
1999 }
2000
2001 #[derive(Debug, Deserialize)]
2002 struct PreparationTestVector {
2003 input_shares: Vec<HexEncoded>,
2004 measurement: u64,
2005 nonce: HexEncoded,
2006 out_shares: Vec<Vec<HexEncoded>>,
2007 prep_messages: Vec<HexEncoded>,
2008 prep_shares: Vec<Vec<HexEncoded>>,
2009 public_share: HexEncoded,
2010 rand: HexEncoded,
2011 }
2012
2013 fn check_test_vec(input: &str) {
2014 let test_vector: PoplarTestVector = serde_json::from_str(input).unwrap();
2015 assert_eq!(test_vector.prep.len(), 1);
2016 let prep = &test_vector.prep[0];
2017 let measurement_bits = (0..test_vector.bits)
2018 .rev()
2019 .map(|i| (prep.measurement >> i) & 1 != 0)
2020 .collect::<BitVec>();
2021 let measurement = IdpfInput::from(measurement_bits);
2022 let (agg_param_level, agg_param_prefixes_int) = test_vector.agg_param;
2023 let agg_param_prefixes = agg_param_prefixes_int
2024 .iter()
2025 .map(|int| {
2026 let bits = (0..=agg_param_level)
2027 .rev()
2028 .map(|i| (*int >> i) & 1 != 0)
2029 .collect::<BitVec>();
2030 bits.into()
2031 })
2032 .collect::<Vec<IdpfInput>>();
2033 let agg_param = Poplar1AggregationParam::try_from_prefixes(agg_param_prefixes).unwrap();
2034 let verify_key = test_vector.verify_key.as_ref().try_into().unwrap();
2035 let nonce = prep.nonce.as_ref().try_into().unwrap();
2036
2037 let mut idpf_random = [[0u8; 16]; 2];
2038 let mut poplar_random = [[0u8; 16]; 3];
2039 for (input, output) in prep
2040 .rand
2041 .as_ref()
2042 .chunks_exact(16)
2043 .zip(idpf_random.iter_mut().chain(poplar_random.iter_mut()))
2044 {
2045 output.copy_from_slice(input);
2046 }
2047
2048 // Shard measurement.
2049 let poplar = Poplar1::new_turboshake128(test_vector.bits);
2050 let (public_share, input_shares) = poplar
2051 .shard_with_random(&measurement, &nonce, &idpf_random, &poplar_random)
2052 .unwrap();
2053
2054 // Run aggregation.
2055 let (init_prep_state_0, init_prep_share_0) = poplar
2056 .prepare_init(
2057 &verify_key,
2058 0,
2059 &agg_param,
2060 &nonce,
2061 &public_share,
2062 &input_shares[0],
2063 )
2064 .unwrap();
2065 let (init_prep_state_1, init_prep_share_1) = poplar
2066 .prepare_init(
2067 &verify_key,
2068 1,
2069 &agg_param,
2070 &nonce,
2071 &public_share,
2072 &input_shares[1],
2073 )
2074 .unwrap();
2075
2076 let r1_prep_msg = poplar
2077 .prepare_shares_to_prepare_message(
2078 &agg_param,
2079 [init_prep_share_0.clone(), init_prep_share_1.clone()],
2080 )
2081 .unwrap();
2082
2083 let (r1_prep_state_0, r1_prep_share_0) = assert_matches!(
2084 poplar
2085 .prepare_next(init_prep_state_0.clone(), r1_prep_msg.clone())
2086 .unwrap(),
2087 PrepareTransition::Continue(state, share) => (state, share)
2088 );
2089 let (r1_prep_state_1, r1_prep_share_1) = assert_matches!(
2090 poplar
2091 .prepare_next(init_prep_state_1.clone(), r1_prep_msg.clone())
2092 .unwrap(),
2093 PrepareTransition::Continue(state, share) => (state, share)
2094 );
2095
2096 let r2_prep_msg = poplar
2097 .prepare_shares_to_prepare_message(
2098 &agg_param,
2099 [r1_prep_share_0.clone(), r1_prep_share_1.clone()],
2100 )
2101 .unwrap();
2102
2103 let out_share_0 = assert_matches!(
2104 poplar
2105 .prepare_next(r1_prep_state_0.clone(), r2_prep_msg.clone())
2106 .unwrap(),
2107 PrepareTransition::Finish(out) => out
2108 );
2109 let out_share_1 = assert_matches!(
2110 poplar
2111 .prepare_next(r1_prep_state_1, r2_prep_msg.clone())
2112 .unwrap(),
2113 PrepareTransition::Finish(out) => out
2114 );
2115
2116 let agg_share_0 = poplar.aggregate(&agg_param, [out_share_0.clone()]).unwrap();
2117 let agg_share_1 = poplar.aggregate(&agg_param, [out_share_1.clone()]).unwrap();
2118
2119 // Collect result.
2120 let agg_result = poplar
2121 .unshard(&agg_param, [agg_share_0.clone(), agg_share_1.clone()], 1)
2122 .unwrap();
2123
2124 // Check all intermediate results against the test vector, and exercise both encoding and decoding.
2125 assert_eq!(
2126 public_share,
2127 Poplar1PublicShare::get_decoded_with_param(&poplar, prep.public_share.as_ref())
2128 .unwrap()
2129 );
2130 assert_eq!(
2131 &public_share.get_encoded().unwrap(),
2132 prep.public_share.as_ref()
2133 );
2134 assert_eq!(
2135 input_shares[0],
2136 Poplar1InputShare::get_decoded_with_param(&(&poplar, 0), prep.input_shares[0].as_ref())
2137 .unwrap()
2138 );
2139 assert_eq!(
2140 &input_shares[0].get_encoded().unwrap(),
2141 prep.input_shares[0].as_ref()
2142 );
2143 assert_eq!(
2144 input_shares[1],
2145 Poplar1InputShare::get_decoded_with_param(&(&poplar, 1), prep.input_shares[1].as_ref())
2146 .unwrap()
2147 );
2148 assert_eq!(
2149 &input_shares[1].get_encoded().unwrap(),
2150 prep.input_shares[1].as_ref()
2151 );
2152 assert_eq!(
2153 init_prep_share_0,
2154 Poplar1FieldVec::get_decoded_with_param(
2155 &init_prep_state_0,
2156 prep.prep_shares[0][0].as_ref()
2157 )
2158 .unwrap()
2159 );
2160 assert_eq!(
2161 &init_prep_share_0.get_encoded().unwrap(),
2162 prep.prep_shares[0][0].as_ref()
2163 );
2164 assert_eq!(
2165 init_prep_share_1,
2166 Poplar1FieldVec::get_decoded_with_param(
2167 &init_prep_state_1,
2168 prep.prep_shares[0][1].as_ref()
2169 )
2170 .unwrap()
2171 );
2172 assert_eq!(
2173 &init_prep_share_1.get_encoded().unwrap(),
2174 prep.prep_shares[0][1].as_ref()
2175 );
2176 assert_eq!(
2177 r1_prep_msg,
2178 Poplar1PrepareMessage::get_decoded_with_param(
2179 &init_prep_state_0,
2180 prep.prep_messages[0].as_ref()
2181 )
2182 .unwrap()
2183 );
2184 assert_eq!(
2185 &r1_prep_msg.get_encoded().unwrap(),
2186 prep.prep_messages[0].as_ref()
2187 );
2188
2189 assert_eq!(
2190 r1_prep_share_0,
2191 Poplar1FieldVec::get_decoded_with_param(
2192 &r1_prep_state_0,
2193 prep.prep_shares[1][0].as_ref()
2194 )
2195 .unwrap()
2196 );
2197 assert_eq!(
2198 &r1_prep_share_0.get_encoded().unwrap(),
2199 prep.prep_shares[1][0].as_ref()
2200 );
2201 assert_eq!(
2202 r1_prep_share_1,
2203 Poplar1FieldVec::get_decoded_with_param(
2204 &r1_prep_state_0,
2205 prep.prep_shares[1][1].as_ref()
2206 )
2207 .unwrap()
2208 );
2209 assert_eq!(
2210 &r1_prep_share_1.get_encoded().unwrap(),
2211 prep.prep_shares[1][1].as_ref()
2212 );
2213 assert_eq!(
2214 r2_prep_msg,
2215 Poplar1PrepareMessage::get_decoded_with_param(
2216 &r1_prep_state_0,
2217 prep.prep_messages[1].as_ref()
2218 )
2219 .unwrap()
2220 );
2221 assert_eq!(
2222 &r2_prep_msg.get_encoded().unwrap(),
2223 prep.prep_messages[1].as_ref()
2224 );
2225 for (out_share, expected_out_share) in [
2226 (out_share_0, &prep.out_shares[0]),
2227 (out_share_1, &prep.out_shares[1]),
2228 ] {
2229 match out_share {
2230 Poplar1FieldVec::Inner(vec) => {
2231 assert_eq!(vec.len(), expected_out_share.len());
2232 for (element, expected) in vec.iter().zip(expected_out_share.iter()) {
2233 assert_eq!(&element.get_encoded().unwrap(), expected.as_ref());
2234 }
2235 }
2236 Poplar1FieldVec::Leaf(vec) => {
2237 assert_eq!(vec.len(), expected_out_share.len());
2238 for (element, expected) in vec.iter().zip(expected_out_share.iter()) {
2239 assert_eq!(&element.get_encoded().unwrap(), expected.as_ref());
2240 }
2241 }
2242 };
2243 }
2244 assert_eq!(
2245 agg_share_0,
2246 Poplar1FieldVec::get_decoded_with_param(
2247 &(&poplar, &agg_param),
2248 test_vector.agg_shares[0].as_ref()
2249 )
2250 .unwrap()
2251 );
2252
2253 assert_eq!(
2254 &agg_share_0.get_encoded().unwrap(),
2255 test_vector.agg_shares[0].as_ref()
2256 );
2257 assert_eq!(
2258 agg_share_1,
2259 Poplar1FieldVec::get_decoded_with_param(
2260 &(&poplar, &agg_param),
2261 test_vector.agg_shares[1].as_ref()
2262 )
2263 .unwrap()
2264 );
2265 assert_eq!(
2266 &agg_share_1.get_encoded().unwrap(),
2267 test_vector.agg_shares[1].as_ref()
2268 );
2269 assert_eq!(agg_result, test_vector.agg_result);
2270 }
2271
2272 #[test]
2273 fn test_vec_poplar1_0() {
2274 check_test_vec(include_str!("test_vec/08/Poplar1_0.json"));
2275 }
2276
2277 #[test]
2278 fn test_vec_poplar1_1() {
2279 check_test_vec(include_str!("test_vec/08/Poplar1_1.json"));
2280 }
2281
2282 #[test]
2283 fn test_vec_poplar1_2() {
2284 check_test_vec(include_str!("test_vec/08/Poplar1_2.json"));
2285 }
2286
2287 #[test]
2288 fn test_vec_poplar1_3() {
2289 check_test_vec(include_str!("test_vec/08/Poplar1_3.json"));
2290 }
2291
2292 #[test]
2293 fn input_share_equality_test() {
2294 equality_comparison_test(&[
2295 // Default.
2296 Poplar1InputShare {
2297 idpf_key: Seed([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
2298 corr_seed: Seed([16, 17, 18]),
2299 corr_inner: Vec::from([
2300 [Field64::from(19), Field64::from(20)],
2301 [Field64::from(21), Field64::from(22)],
2302 [Field64::from(23), Field64::from(24)],
2303 ]),
2304 corr_leaf: [Field255::from(25), Field255::from(26)],
2305 },
2306 // Modified idpf_key.
2307 Poplar1InputShare {
2308 idpf_key: Seed([15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]),
2309 corr_seed: Seed([16, 17, 18]),
2310 corr_inner: Vec::from([
2311 [Field64::from(19), Field64::from(20)],
2312 [Field64::from(21), Field64::from(22)],
2313 [Field64::from(23), Field64::from(24)],
2314 ]),
2315 corr_leaf: [Field255::from(25), Field255::from(26)],
2316 },
2317 // Modified corr_seed.
2318 Poplar1InputShare {
2319 idpf_key: Seed([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
2320 corr_seed: Seed([18, 17, 16]),
2321 corr_inner: Vec::from([
2322 [Field64::from(19), Field64::from(20)],
2323 [Field64::from(21), Field64::from(22)],
2324 [Field64::from(23), Field64::from(24)],
2325 ]),
2326 corr_leaf: [Field255::from(25), Field255::from(26)],
2327 },
2328 // Modified corr_inner.
2329 Poplar1InputShare {
2330 idpf_key: Seed([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
2331 corr_seed: Seed([16, 17, 18]),
2332 corr_inner: Vec::from([
2333 [Field64::from(24), Field64::from(23)],
2334 [Field64::from(22), Field64::from(21)],
2335 [Field64::from(20), Field64::from(19)],
2336 ]),
2337 corr_leaf: [Field255::from(25), Field255::from(26)],
2338 },
2339 // Modified corr_leaf.
2340 Poplar1InputShare {
2341 idpf_key: Seed([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
2342 corr_seed: Seed([16, 17, 18]),
2343 corr_inner: Vec::from([
2344 [Field64::from(19), Field64::from(20)],
2345 [Field64::from(21), Field64::from(22)],
2346 [Field64::from(23), Field64::from(24)],
2347 ]),
2348 corr_leaf: [Field255::from(26), Field255::from(25)],
2349 },
2350 ])
2351 }
2352
2353 #[test]
2354 fn prepare_state_equality_test() {
2355 // This test effectively covers PrepareStateVariant, PrepareState, SketchState as well.
2356 equality_comparison_test(&[
2357 // Inner, round one. (default)
2358 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
2359 sketch: SketchState::RoundOne {
2360 A_share: Field64::from(0),
2361 B_share: Field64::from(1),
2362 is_leader: false,
2363 },
2364 output_share: Vec::from([Field64::from(2), Field64::from(3)]),
2365 })),
2366 // Inner, round one, modified A_share.
2367 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
2368 sketch: SketchState::RoundOne {
2369 A_share: Field64::from(100),
2370 B_share: Field64::from(1),
2371 is_leader: false,
2372 },
2373 output_share: Vec::from([Field64::from(2), Field64::from(3)]),
2374 })),
2375 // Inner, round one, modified B_share.
2376 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
2377 sketch: SketchState::RoundOne {
2378 A_share: Field64::from(0),
2379 B_share: Field64::from(101),
2380 is_leader: false,
2381 },
2382 output_share: Vec::from([Field64::from(2), Field64::from(3)]),
2383 })),
2384 // Inner, round one, modified is_leader.
2385 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
2386 sketch: SketchState::RoundOne {
2387 A_share: Field64::from(0),
2388 B_share: Field64::from(1),
2389 is_leader: true,
2390 },
2391 output_share: Vec::from([Field64::from(2), Field64::from(3)]),
2392 })),
2393 // Inner, round one, modified output_share.
2394 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
2395 sketch: SketchState::RoundOne {
2396 A_share: Field64::from(0),
2397 B_share: Field64::from(1),
2398 is_leader: false,
2399 },
2400 output_share: Vec::from([Field64::from(3), Field64::from(2)]),
2401 })),
2402 // Inner, round two. (default)
2403 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
2404 sketch: SketchState::RoundTwo,
2405 output_share: Vec::from([Field64::from(2), Field64::from(3)]),
2406 })),
2407 // Inner, round two, modified output_share.
2408 Poplar1PrepareState(PrepareStateVariant::Inner(PrepareState {
2409 sketch: SketchState::RoundTwo,
2410 output_share: Vec::from([Field64::from(3), Field64::from(2)]),
2411 })),
2412 // Leaf, round one. (default)
2413 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
2414 sketch: SketchState::RoundOne {
2415 A_share: Field255::from(0),
2416 B_share: Field255::from(1),
2417 is_leader: false,
2418 },
2419 output_share: Vec::from([Field255::from(2), Field255::from(3)]),
2420 })),
2421 // Leaf, round one, modified A_share.
2422 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
2423 sketch: SketchState::RoundOne {
2424 A_share: Field255::from(100),
2425 B_share: Field255::from(1),
2426 is_leader: false,
2427 },
2428 output_share: Vec::from([Field255::from(2), Field255::from(3)]),
2429 })),
2430 // Leaf, round one, modified B_share.
2431 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
2432 sketch: SketchState::RoundOne {
2433 A_share: Field255::from(0),
2434 B_share: Field255::from(101),
2435 is_leader: false,
2436 },
2437 output_share: Vec::from([Field255::from(2), Field255::from(3)]),
2438 })),
2439 // Leaf, round one, modified is_leader.
2440 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
2441 sketch: SketchState::RoundOne {
2442 A_share: Field255::from(0),
2443 B_share: Field255::from(1),
2444 is_leader: true,
2445 },
2446 output_share: Vec::from([Field255::from(2), Field255::from(3)]),
2447 })),
2448 // Leaf, round one, modified output_share.
2449 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
2450 sketch: SketchState::RoundOne {
2451 A_share: Field255::from(0),
2452 B_share: Field255::from(1),
2453 is_leader: false,
2454 },
2455 output_share: Vec::from([Field255::from(3), Field255::from(2)]),
2456 })),
2457 // Leaf, round two. (default)
2458 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
2459 sketch: SketchState::RoundTwo,
2460 output_share: Vec::from([Field255::from(2), Field255::from(3)]),
2461 })),
2462 // Leaf, round two, modified output_share.
2463 Poplar1PrepareState(PrepareStateVariant::Leaf(PrepareState {
2464 sketch: SketchState::RoundTwo,
2465 output_share: Vec::from([Field255::from(3), Field255::from(2)]),
2466 })),
2467 ])
2468 }
2469
2470 #[test]
2471 fn field_vec_equality_test() {
2472 equality_comparison_test(&[
2473 // Inner. (default)
2474 Poplar1FieldVec::Inner(Vec::from([Field64::from(0), Field64::from(1)])),
2475 // Inner, modified value.
2476 Poplar1FieldVec::Inner(Vec::from([Field64::from(1), Field64::from(0)])),
2477 // Leaf. (deafult)
2478 Poplar1FieldVec::Leaf(Vec::from([Field255::from(0), Field255::from(1)])),
2479 // Leaf, modified value.
2480 Poplar1FieldVec::Leaf(Vec::from([Field255::from(1), Field255::from(0)])),
2481 ])
2482 }
2483 }