Debian Codegraph @

third_party/rust/prio/src/idpf.rs

raw
1 //! This module implements the incremental distributed point function (IDPF) described in
2 //! [[draft-irtf-cfrg-vdaf-08]].
3 //!
4 //! [draft-irtf-cfrg-vdaf-08]: https://datatracker.ietf.org/doc/draft-irtf-cfrg-vdaf/08/
5
6 use crate::{
7 codec::{CodecError, Decode, Encode, ParameterizedDecode},
8 field::{FieldElement, FieldElementExt},
9 vdaf::{
10 xof::{Seed, XofFixedKeyAes128Key},
11 VdafError, VERSION,
12 },
13 };
14 use bitvec::{
15 bitvec,
16 boxed::BitBox,
17 prelude::{Lsb0, Msb0},
18 slice::BitSlice,
19 vec::BitVec,
20 view::BitView,
21 };
22 use rand_core::RngCore;
23 use std::{
24 collections::{HashMap, VecDeque},
25 fmt::Debug,
26 io::{Cursor, Read},
27 iter::zip,
28 ops::{Add, AddAssign, ControlFlow, Index, Sub},
29 };
30 use subtle::{Choice, ConditionallyNegatable, ConditionallySelectable, ConstantTimeEq};
31
32 /// IDPF-related errors.
33 #[derive(Debug, thiserror::Error)]
34 #[non_exhaustive]
35 pub enum IdpfError {
36 /// Error from incompatible shares at different levels.
37 #[error("tried to merge shares from incompatible levels")]
38 MismatchedLevel,
39
40 /// Invalid parameter, indicates an invalid input to either [`Idpf::gen`] or [`Idpf::eval`].
41 #[error("invalid parameter: {0}")]
42 InvalidParameter(String),
43 }
44
45 /// An index used as the input to an IDPF evaluation.
46 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
47 pub struct IdpfInput {
48 /// The index as a boxed bit slice.
49 index: BitBox,
50 }
51
52 impl IdpfInput {
53 /// Convert a slice of bytes into an IDPF input, where the bits of each byte are processed in
54 /// MSB-to-LSB order. (Subsequent bytes are processed in their natural order.)
55 pub fn from_bytes(bytes: &[u8]) -> IdpfInput {
56 let bit_slice_u8_storage = bytes.view_bits::<Msb0>();
57 let mut bit_vec_usize_storage = bitvec![0; bit_slice_u8_storage.len()];
58 bit_vec_usize_storage.clone_from_bitslice(bit_slice_u8_storage);
59 IdpfInput {
60 index: bit_vec_usize_storage.into_boxed_bitslice(),
61 }
62 }
63
64 /// Convert a slice of booleans into an IDPF input.
65 pub fn from_bools(bools: &[bool]) -> IdpfInput {
66 let bits = bools.iter().collect::<BitVec>();
67 IdpfInput {
68 index: bits.into_boxed_bitslice(),
69 }
70 }
71
72 /// Create a new IDPF input by appending to this input.
73 pub fn clone_with_suffix(&self, suffix: &[bool]) -> IdpfInput {
74 let mut vec = BitVec::with_capacity(self.index.len() + suffix.len());
75 vec.extend_from_bitslice(&self.index);
76 vec.extend(suffix);
77 IdpfInput {
78 index: vec.into_boxed_bitslice(),
79 }
80 }
81
82 /// Get the length of the input in bits.
83 pub fn len(&self) -> usize {
84 self.index.len()
85 }
86
87 /// Check if the input is empty, i.e. it does not contain any bits.
88 pub fn is_empty(&self) -> bool {
89 self.index.is_empty()
90 }
91
92 /// Get an iterator over the bits that make up this input.
93 pub fn iter(&self) -> impl DoubleEndedIterator<Item = bool> + '_ {
94 self.index.iter().by_vals()
95 }
96
97 /// Convert the IDPF into a byte slice. If the length of the underlying bit vector is not a
98 /// multiple of `8`, then the least significant bits of the last byte are `0`-padded.
99 pub fn to_bytes(&self) -> Vec<u8> {
100 let mut vec = BitVec::<u8, Msb0>::with_capacity(self.index.len());
101 vec.extend_from_bitslice(&self.index);
102 vec.set_uninitialized(false);
103 vec.into_vec()
104 }
105
106 /// Return the `level`-bit prefix of this IDPF input.
107 pub fn prefix(&self, level: usize) -> Self {
108 Self {
109 index: self.index[..=level].to_owned().into(),
110 }
111 }
112
113 /// Return the bit at the specified level if the level is in bounds.
114 pub fn get(&self, level: usize) -> Option<bool> {
115 self.index.get(level).as_deref().copied()
116 }
117 }
118
119 impl From<BitVec<usize, Lsb0>> for IdpfInput {
120 fn from(bit_vec: BitVec<usize, Lsb0>) -> Self {
121 IdpfInput {
122 index: bit_vec.into_boxed_bitslice(),
123 }
124 }
125 }
126
127 impl From<BitBox<usize, Lsb0>> for IdpfInput {
128 fn from(bit_box: BitBox<usize, Lsb0>) -> Self {
129 IdpfInput { index: bit_box }
130 }
131 }
132
133 impl<I> Index<I> for IdpfInput
134 where
135 BitSlice: Index<I>,
136 {
137 type Output = <BitSlice as Index<I>>::Output;
138
139 fn index(&self, index: I) -> &Self::Output {
140 &self.index[index]
141 }
142 }
143
144 /// Trait for values to be programmed into an IDPF.
145 ///
146 /// Values must form an Abelian group, so that they can be secret-shared, and the group operation
147 /// must be represented by [`Add`]. Values must be encodable and decodable, without need for a
148 /// decoding parameter. Values can be pseudorandomly generated, with a uniform probability
149 /// distribution, from XOF output.
150 pub trait IdpfValue:
151 Add<Output = Self>
152 + AddAssign
153 + Sub<Output = Self>
154 + ConditionallyNegatable
155 + Encode
156 + ParameterizedDecode<Self::ValueParameter>
157 + Sized
158 {
159 /// Any run-time parameters needed to produce a value.
160 type ValueParameter;
161
162 /// Generate a pseudorandom value from a seed stream.
163 fn generate<S>(seed_stream: &mut S, parameter: &Self::ValueParameter) -> Self
164 where
165 S: RngCore;
166
167 /// Returns the additive identity.
168 fn zero(parameter: &Self::ValueParameter) -> Self;
169
170 /// Conditionally select between two values. Implementations must perform this operation in
171 /// constant time.
172 ///
173 /// This is the same as in [`subtle::ConditionallySelectable`], but without the [`Copy`] bound.
174 fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self;
175 }
176
177 impl<F> IdpfValue for F
178 where
179 F: FieldElement,
180 {
181 type ValueParameter = ();
182
183 fn generate<S>(seed_stream: &mut S, _: &()) -> Self
184 where
185 S: RngCore,
186 {
187 // This is analogous to `Prng::get()`, but does not make use of a persistent buffer of
188 // output.
189 let mut buffer = [0u8; 64];
190 assert!(
191 buffer.len() >= F::ENCODED_SIZE,
192 "field is too big for buffer"
193 );
194 loop {
195 seed_stream.fill_bytes(&mut buffer[..F::ENCODED_SIZE]);
196 match F::from_random_rejection(&buffer[..F::ENCODED_SIZE]) {
197 ControlFlow::Break(x) => return x,
198 ControlFlow::Continue(()) => continue,
199 }
200 }
201 }
202
203 fn zero(_: &()) -> Self {
204 <Self as FieldElement>::zero()
205 }
206
207 fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
208 <F as ConditionallySelectable>::conditional_select(a, b, choice)
209 }
210 }
211
212 /// An output from evaluation of an IDPF at some level and index.
213 #[derive(Debug, PartialEq, Eq)]
214 pub enum IdpfOutputShare<VI, VL> {
215 /// An IDPF output share corresponding to an inner tree node.
216 Inner(VI),
217 /// An IDPF output share corresponding to a leaf tree node.
218 Leaf(VL),
219 }
220
221 impl<VI, VL> IdpfOutputShare<VI, VL>
222 where
223 VI: IdpfValue,
224 VL: IdpfValue,
225 {
226 /// Combine two output share values into one.
227 pub fn merge(self, other: Self) -> Result<IdpfOutputShare<VI, VL>, IdpfError> {
228 match (self, other) {
229 (IdpfOutputShare::Inner(mut self_value), IdpfOutputShare::Inner(other_value)) => {
230 self_value += other_value;
231 Ok(IdpfOutputShare::Inner(self_value))
232 }
233 (IdpfOutputShare::Leaf(mut self_value), IdpfOutputShare::Leaf(other_value)) => {
234 self_value += other_value;
235 Ok(IdpfOutputShare::Leaf(self_value))
236 }
237 (_, _) => Err(IdpfError::MismatchedLevel),
238 }
239 }
240 }
241
242 fn extend(seed: &[u8; 16], xof_fixed_key: &XofFixedKeyAes128Key) -> ([[u8; 16]; 2], [Choice; 2]) {
243 let mut seed_stream = xof_fixed_key.with_seed(seed);
244
245 let mut seeds = [[0u8; 16], [0u8; 16]];
246 seed_stream.fill_bytes(&mut seeds[0]);
247 seed_stream.fill_bytes(&mut seeds[1]);
248
249 // "Steal" the control bits from the seeds.
250 let control_bits_0 = seeds[0].as_ref()[0] & 1;
251 let control_bits_1 = seeds[1].as_ref()[0] & 1;
252 seeds[0].as_mut()[0] &= 0xfe;
253 seeds[1].as_mut()[0] &= 0xfe;
254
255 (seeds, [control_bits_0.into(), control_bits_1.into()])
256 }
257
258 fn convert<V>(
259 seed: &[u8; 16],
260 xof_fixed_key: &XofFixedKeyAes128Key,
261 parameter: &V::ValueParameter,
262 ) -> ([u8; 16], V)
263 where
264 V: IdpfValue,
265 {
266 let mut seed_stream = xof_fixed_key.with_seed(seed);
267
268 let mut next_seed = [0u8; 16];
269 seed_stream.fill_bytes(&mut next_seed);
270
271 (next_seed, V::generate(&mut seed_stream, parameter))
272 }
273
274 /// Helper method to update seeds, update control bits, and output the correction word for one level
275 /// of the IDPF key generation process.
276 fn generate_correction_word<V>(
277 input_bit: Choice,
278 value: V,
279 parameter: &V::ValueParameter,
280 keys: &mut [[u8; 16]; 2],
281 control_bits: &mut [Choice; 2],
282 extend_xof_fixed_key: &XofFixedKeyAes128Key,
283 convert_xof_fixed_key: &XofFixedKeyAes128Key,
284 ) -> IdpfCorrectionWord<V>
285 where
286 V: IdpfValue,
287 {
288 // Expand both keys into two seeds and two control bits each.
289 let (seed_0, control_bits_0) = extend(&keys[0], extend_xof_fixed_key);
290 let (seed_1, control_bits_1) = extend(&keys[1], extend_xof_fixed_key);
291
292 let (keep, lose) = (input_bit, !input_bit);
293
294 let cw_seed = xor_seeds(
295 &conditional_select_seed(lose, &seed_0),
296 &conditional_select_seed(lose, &seed_1),
297 );
298 let cw_control_bits = [
299 control_bits_0[0] ^ control_bits_1[0] ^ input_bit ^ Choice::from(1),
300 control_bits_0[1] ^ control_bits_1[1] ^ input_bit,
301 ];
302 let cw_control_bits_keep =
303 Choice::conditional_select(&cw_control_bits[0], &cw_control_bits[1], keep);
304
305 let previous_control_bits = *control_bits;
306 let control_bits_0_keep =
307 Choice::conditional_select(&control_bits_0[0], &control_bits_0[1], keep);
308 let control_bits_1_keep =
309 Choice::conditional_select(&control_bits_1[0], &control_bits_1[1], keep);
310 control_bits[0] = control_bits_0_keep ^ (cw_control_bits_keep & previous_control_bits[0]);
311 control_bits[1] = control_bits_1_keep ^ (cw_control_bits_keep & previous_control_bits[1]);
312
313 let seed_0_keep = conditional_select_seed(keep, &seed_0);
314 let seed_1_keep = conditional_select_seed(keep, &seed_1);
315 let seeds_corrected = [
316 conditional_xor_seeds(&seed_0_keep, &cw_seed, previous_control_bits[0]),
317 conditional_xor_seeds(&seed_1_keep, &cw_seed, previous_control_bits[1]),
318 ];
319
320 let (new_key_0, elements_0) =
321 convert::<V>(&seeds_corrected[0], convert_xof_fixed_key, parameter);
322 let (new_key_1, elements_1) =
323 convert::<V>(&seeds_corrected[1], convert_xof_fixed_key, parameter);
324
325 keys[0] = new_key_0;
326 keys[1] = new_key_1;
327
328 let mut cw_value = value - elements_0 + elements_1;
329 cw_value.conditional_negate(control_bits[1]);
330
331 IdpfCorrectionWord {
332 seed: cw_seed,
333 control_bits: cw_control_bits,
334 value: cw_value,
335 }
336 }
337
338 /// Helper function to evaluate one level of an IDPF. This updates the seed and control bit
339 /// arguments that are passed in.
340 #[allow(clippy::too_many_arguments)]
341 fn eval_next<V>(
342 is_leader: bool,
343 parameter: &V::ValueParameter,
344 key: &mut [u8; 16],
345 control_bit: &mut Choice,
346 correction_word: &IdpfCorrectionWord<V>,
347 input_bit: Choice,
348 extend_xof_fixed_key: &XofFixedKeyAes128Key,
349 convert_xof_fixed_key: &XofFixedKeyAes128Key,
350 ) -> V
351 where
352 V: IdpfValue,
353 {
354 let (mut seeds, mut control_bits) = extend(key, extend_xof_fixed_key);
355
356 seeds[0] = conditional_xor_seeds(&seeds[0], &correction_word.seed, *control_bit);
357 control_bits[0] ^= correction_word.control_bits[0] & *control_bit;
358 seeds[1] = conditional_xor_seeds(&seeds[1], &correction_word.seed, *control_bit);
359 control_bits[1] ^= correction_word.control_bits[1] & *control_bit;
360
361 let seed_corrected = conditional_select_seed(input_bit, &seeds);
362 *control_bit = Choice::conditional_select(&control_bits[0], &control_bits[1], input_bit);
363
364 let (new_key, elements) = convert::<V>(&seed_corrected, convert_xof_fixed_key, parameter);
365 *key = new_key;
366
367 let mut out =
368 elements + V::conditional_select(&V::zero(parameter), &correction_word.value, *control_bit);
369 out.conditional_negate(Choice::from((!is_leader) as u8));
370 out
371 }
372
373 /// This defines a family of IDPFs (incremental distributed point functions) with certain types of
374 /// values at inner tree nodes and at leaf tree nodes.
375 ///
376 /// IDPF keys can be generated by providing an input and programmed outputs for each tree level to
377 /// [`Idpf::gen`].
378 pub struct Idpf<VI, VL>
379 where
380 VI: IdpfValue,
381 VL: IdpfValue,
382 {
383 inner_node_value_parameter: VI::ValueParameter,
384 leaf_node_value_parameter: VL::ValueParameter,
385 }
386
387 impl<VI, VL> Idpf<VI, VL>
388 where
389 VI: IdpfValue,
390 VL: IdpfValue,
391 {
392 /// Construct an [`Idpf`] instance with the given run-time parameters needed for inner and leaf
393 /// values.
394 pub fn new(
395 inner_node_value_parameter: VI::ValueParameter,
396 leaf_node_value_parameter: VL::ValueParameter,
397 ) -> Self {
398 Self {
399 inner_node_value_parameter,
400 leaf_node_value_parameter,
401 }
402 }
403
404 pub(crate) fn gen_with_random<M: IntoIterator<Item = VI>>(
405 &self,
406 input: &IdpfInput,
407 inner_values: M,
408 leaf_value: VL,
409 binder: &[u8],
410 random: &[[u8; 16]; 2],
411 ) -> Result<(IdpfPublicShare<VI, VL>, [Seed<16>; 2]), VdafError> {
412 let bits = input.len();
413
414 let initial_keys: [Seed<16>; 2] =
415 [Seed::from_bytes(random[0]), Seed::from_bytes(random[1])];
416
417 let extend_dst = [
418 VERSION, 1, /* algorithm class */
419 0, 0, 0, 0, /* algorithm ID */
420 0, 0, /* usage */
421 ];
422 let convert_dst = [
423 VERSION, 1, /* algorithm class */
424 0, 0, 0, 0, /* algorithm ID */
425 0, 1, /* usage */
426 ];
427 let extend_xof_fixed_key = XofFixedKeyAes128Key::new(&extend_dst, binder);
428 let convert_xof_fixed_key = XofFixedKeyAes128Key::new(&convert_dst, binder);
429
430 let mut keys = [initial_keys[0].0, initial_keys[1].0];
431 let mut control_bits = [Choice::from(0u8), Choice::from(1u8)];
432 let mut inner_correction_words = Vec::with_capacity(bits - 1);
433
434 for (level, value) in inner_values.into_iter().enumerate() {
435 if level >= bits - 1 {
436 return Err(IdpfError::InvalidParameter(
437 "too many values were supplied".to_string(),
438 )
439 .into());
440 }
441 inner_correction_words.push(generate_correction_word::<VI>(
442 Choice::from(input[level] as u8),
443 value,
444 &self.inner_node_value_parameter,
445 &mut keys,
446 &mut control_bits,
447 &extend_xof_fixed_key,
448 &convert_xof_fixed_key,
449 ));
450 }
451 if inner_correction_words.len() != bits - 1 {
452 return Err(
453 IdpfError::InvalidParameter("too few values were supplied".to_string()).into(),
454 );
455 }
456 let leaf_correction_word = generate_correction_word::<VL>(
457 Choice::from(input[bits - 1] as u8),
458 leaf_value,
459 &self.leaf_node_value_parameter,
460 &mut keys,
461 &mut control_bits,
462 &extend_xof_fixed_key,
463 &convert_xof_fixed_key,
464 );
465 let public_share = IdpfPublicShare {
466 inner_correction_words,
467 leaf_correction_word,
468 };
469
470 Ok((public_share, initial_keys))
471 }
472
473 /// The IDPF key generation algorithm.
474 ///
475 /// Generate and return a sequence of IDPF shares for `input`. The parameters `inner_values`
476 /// and `leaf_value` provide the output values for each successive level of the prefix tree.
477 pub fn gen<M>(
478 &self,
479 input: &IdpfInput,
480 inner_values: M,
481 leaf_value: VL,
482 binder: &[u8],
483 ) -> Result<(IdpfPublicShare<VI, VL>, [Seed<16>; 2]), VdafError>
484 where
485 M: IntoIterator<Item = VI>,
486 {
487 if input.is_empty() {
488 return Err(
489 IdpfError::InvalidParameter("invalid number of bits: 0".to_string()).into(),
490 );
491 }
492 let mut random = [[0u8; 16]; 2];
493 for random_seed in random.iter_mut() {
494 getrandom::getrandom(random_seed)?;
495 }
496 self.gen_with_random(input, inner_values, leaf_value, binder, &random)
497 }
498
499 /// Evaluate an IDPF share on `prefix`, starting from a particular tree level with known
500 /// intermediate values.
501 #[allow(clippy::too_many_arguments)]
502 fn eval_from_node(
503 &self,
504 is_leader: bool,
505 public_share: &IdpfPublicShare<VI, VL>,
506 start_level: usize,
507 mut key: [u8; 16],
508 mut control_bit: Choice,
509 prefix: &IdpfInput,
510 binder: &[u8],
511 cache: &mut dyn IdpfCache,
512 ) -> Result<IdpfOutputShare<VI, VL>, IdpfError> {
513 let bits = public_share.inner_correction_words.len() + 1;
514
515 let extend_dst = [
516 VERSION, 1, /* algorithm class */
517 0, 0, 0, 0, /* algorithm ID */
518 0, 0, /* usage */
519 ];
520 let convert_dst = [
521 VERSION, 1, /* algorithm class */
522 0, 0, 0, 0, /* algorithm ID */
523 0, 1, /* usage */
524 ];
525 let extend_xof_fixed_key = XofFixedKeyAes128Key::new(&extend_dst, binder);
526 let convert_xof_fixed_key = XofFixedKeyAes128Key::new(&convert_dst, binder);
527
528 let mut last_inner_output = None;
529 for ((correction_word, input_bit), level) in public_share.inner_correction_words
530 [start_level..]
531 .iter()
532 .zip(prefix[start_level..].iter())
533 .zip(start_level..)
534 {
535 last_inner_output = Some(eval_next(
536 is_leader,
537 &self.inner_node_value_parameter,
538 &mut key,
539 &mut control_bit,
540 correction_word,
541 Choice::from(*input_bit as u8),
542 &extend_xof_fixed_key,
543 &convert_xof_fixed_key,
544 ));
545 let cache_key = &prefix[..=level];
546 cache.insert(cache_key, &(key, control_bit.unwrap_u8()));
547 }
548
549 if prefix.len() == bits {
550 let leaf_output = eval_next(
551 is_leader,
552 &self.leaf_node_value_parameter,
553 &mut key,
554 &mut control_bit,
555 &public_share.leaf_correction_word,
556 Choice::from(prefix[bits - 1] as u8),
557 &extend_xof_fixed_key,
558 &convert_xof_fixed_key,
559 );
560 // Note: there's no point caching this node's key, because we will always run the
561 // eval_next() call for the leaf level.
562 Ok(IdpfOutputShare::Leaf(leaf_output))
563 } else {
564 Ok(IdpfOutputShare::Inner(last_inner_output.unwrap()))
565 }
566 }
567
568 /// The IDPF key evaluation algorithm.
569 ///
570 /// Evaluate an IDPF share on `prefix`.
571 pub fn eval(
572 &self,
573 agg_id: usize,
574 public_share: &IdpfPublicShare<VI, VL>,
575 key: &Seed<16>,
576 prefix: &IdpfInput,
577 binder: &[u8],
578 cache: &mut dyn IdpfCache,
579 ) -> Result<IdpfOutputShare<VI, VL>, IdpfError> {
580 let bits = public_share.inner_correction_words.len() + 1;
581 if agg_id > 1 {
582 return Err(IdpfError::InvalidParameter(format!(
583 "invalid aggregator ID {agg_id}"
584 )));
585 }
586 let is_leader = agg_id == 0;
587 if prefix.is_empty() {
588 return Err(IdpfError::InvalidParameter("empty prefix".to_string()));
589 }
590 if prefix.len() > bits {
591 return Err(IdpfError::InvalidParameter(format!(
592 "prefix length ({}) exceeds configured number of bits ({})",
593 prefix.len(),
594 bits,
595 )));
596 }
597
598 // Check for cached keys first, starting from the end of our desired path down the tree, and
599 // walking back up. If we get a hit, stop there and evaluate the remainder of the tree path
600 // going forward.
601 if prefix.len() > 1 {
602 // Skip checking for `prefix` in the cache, because we don't store field element
603 // values along with keys and control bits. Instead, start looking one node higher
604 // up, so we can recompute everything for the last level of `prefix`.
605 let mut cache_key = &prefix[..prefix.len() - 1];
606 while !cache_key.is_empty() {
607 if let Some((key, control_bit)) = cache.get(cache_key) {
608 // Evaluate the IDPF starting from the cached data at a previously-computed
609 // node, and return the result.
610 return self.eval_from_node(
611 is_leader,
612 public_share,
613 /* start_level */ cache_key.len(),
614 key,
615 Choice::from(control_bit),
616 prefix,
617 binder,
618 cache,
619 );
620 }
621 cache_key = &cache_key[..cache_key.len() - 1];
622 }
623 }
624 // Evaluate starting from the root node.
625 self.eval_from_node(
626 is_leader,
627 public_share,
628 /* start_level */ 0,
629 key.0,
630 /* control_bit */ Choice::from((!is_leader) as u8),
631 prefix,
632 binder,
633 cache,
634 )
635 }
636 }
637
638 /// An IDPF public share. This contains the list of correction words used by all parties when
639 /// evaluating the IDPF.
640 #[derive(Debug, Clone)]
641 pub struct IdpfPublicShare<VI, VL> {
642 /// Correction words for each inner node level.
643 inner_correction_words: Vec<IdpfCorrectionWord<VI>>,
644 /// Correction word for the leaf node level.
645 leaf_correction_word: IdpfCorrectionWord<VL>,
646 }
647
648 impl<VI, VL> ConstantTimeEq for IdpfPublicShare<VI, VL>
649 where
650 VI: ConstantTimeEq,
651 VL: ConstantTimeEq,
652 {
653 fn ct_eq(&self, other: &Self) -> Choice {
654 self.inner_correction_words
655 .ct_eq(&other.inner_correction_words)
656 & self.leaf_correction_word.ct_eq(&other.leaf_correction_word)
657 }
658 }
659
660 impl<VI, VL> PartialEq for IdpfPublicShare<VI, VL>
661 where
662 VI: ConstantTimeEq,
663 VL: ConstantTimeEq,
664 {
665 fn eq(&self, other: &Self) -> bool {
666 self.ct_eq(other).into()
667 }
668 }
669
670 impl<VI, VL> Eq for IdpfPublicShare<VI, VL>
671 where
672 VI: ConstantTimeEq,
673 VL: ConstantTimeEq,
674 {
675 }
676
677 impl<VI, VL> Encode for IdpfPublicShare<VI, VL>
678 where
679 VI: Encode,
680 VL: Encode,
681 {
682 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
683 // Control bits need to be written within each byte in LSB-to-MSB order, and assigned into
684 // bytes in big-endian order. Thus, the first four levels will have their control bits
685 // encoded in the last byte, and the last levels will have their control bits encoded in the
686 // first byte.
687 let mut control_bits: BitVec<u8, Lsb0> =
688 BitVec::with_capacity(self.inner_correction_words.len() * 2 + 2);
689 for correction_words in self.inner_correction_words.iter() {
690 control_bits.extend(correction_words.control_bits.iter().map(|x| bool::from(*x)));
691 }
692 control_bits.extend(
693 self.leaf_correction_word
694 .control_bits
695 .iter()
696 .map(|x| bool::from(*x)),
697 );
698 control_bits.set_uninitialized(false);
699 let mut packed_control = control_bits.into_vec();
700 bytes.append(&mut packed_control);
701
702 for correction_words in self.inner_correction_words.iter() {
703 Seed(correction_words.seed).encode(bytes)?;
704 correction_words.value.encode(bytes)?;
705 }
706 Seed(self.leaf_correction_word.seed).encode(bytes)?;
707 self.leaf_correction_word.value.encode(bytes)
708 }
709
710 fn encoded_len(&self) -> Option<usize> {
711 let control_bits_count = (self.inner_correction_words.len() + 1) * 2;
712 let mut len = (control_bits_count + 7) / 8 + (self.inner_correction_words.len() + 1) * 16;
713 for correction_words in self.inner_correction_words.iter() {
714 len += correction_words.value.encoded_len()?;
715 }
716 len += self.leaf_correction_word.value.encoded_len()?;
717 Some(len)
718 }
719 }
720
721 impl<VI, VL> ParameterizedDecode<usize> for IdpfPublicShare<VI, VL>
722 where
723 VI: Decode,
724 VL: Decode,
725 {
726 fn decode_with_param(bits: &usize, bytes: &mut Cursor<&[u8]>) -> Result<Self, CodecError> {
727 let packed_control_len = (bits + 3) / 4;
728 let mut packed = vec![0u8; packed_control_len];
729 bytes.read_exact(&mut packed)?;
730 let unpacked_control_bits: BitVec<u8, Lsb0> = BitVec::from_vec(packed);
731
732 let mut inner_correction_words = Vec::with_capacity(bits - 1);
733 for chunk in unpacked_control_bits[0..(bits - 1) * 2].chunks(2) {
734 let control_bits = [(chunk[0] as u8).into(), (chunk[1] as u8).into()];
735 let seed = Seed::decode(bytes)?.0;
736 let value = VI::decode(bytes)?;
737 inner_correction_words.push(IdpfCorrectionWord {
738 seed,
739 control_bits,
740 value,
741 })
742 }
743
744 let control_bits = [
745 (unpacked_control_bits[(bits - 1) * 2] as u8).into(),
746 (unpacked_control_bits[bits * 2 - 1] as u8).into(),
747 ];
748 let seed = Seed::decode(bytes)?.0;
749 let value = VL::decode(bytes)?;
750 let leaf_correction_word = IdpfCorrectionWord {
751 seed,
752 control_bits,
753 value,
754 };
755
756 // Check that unused packed bits are zero.
757 if unpacked_control_bits[bits * 2..].any() {
758 return Err(CodecError::UnexpectedValue);
759 }
760
761 Ok(IdpfPublicShare {
762 inner_correction_words,
763 leaf_correction_word,
764 })
765 }
766 }
767
768 #[derive(Debug, Clone)]
769 struct IdpfCorrectionWord<V> {
770 seed: [u8; 16],
771 control_bits: [Choice; 2],
772 value: V,
773 }
774
775 impl<V> ConstantTimeEq for IdpfCorrectionWord<V>
776 where
777 V: ConstantTimeEq,
778 {
779 fn ct_eq(&self, other: &Self) -> Choice {
780 self.seed.ct_eq(&other.seed)
781 & self.control_bits.ct_eq(&other.control_bits)
782 & self.value.ct_eq(&other.value)
783 }
784 }
785
786 impl<V> PartialEq for IdpfCorrectionWord<V>
787 where
788 V: ConstantTimeEq,
789 {
790 fn eq(&self, other: &Self) -> bool {
791 self.ct_eq(other).into()
792 }
793 }
794
795 impl<V> Eq for IdpfCorrectionWord<V> where V: ConstantTimeEq {}
796
797 pub(crate) fn xor_seeds(left: &[u8; 16], right: &[u8; 16]) -> [u8; 16] {
798 let mut seed = [0u8; 16];
799 for (a, (b, c)) in left.iter().zip(right.iter().zip(seed.iter_mut())) {
800 *c = a ^ b;
801 }
802 seed
803 }
804
805 fn and_seeds(left: &[u8; 16], right: &[u8; 16]) -> [u8; 16] {
806 let mut seed = [0u8; 16];
807 for (a, (b, c)) in left.iter().zip(right.iter().zip(seed.iter_mut())) {
808 *c = a & b;
809 }
810 seed
811 }
812
813 fn or_seeds(left: &[u8; 16], right: &[u8; 16]) -> [u8; 16] {
814 let mut seed = [0u8; 16];
815 for (a, (b, c)) in left.iter().zip(right.iter().zip(seed.iter_mut())) {
816 *c = a | b;
817 }
818 seed
819 }
820
821 /// Take a control bit, and fan it out into a byte array that can be used as a mask for XOF seeds,
822 /// without branching. If the control bit input is 0, all bytes will be equal to 0, and if the
823 /// control bit input is 1, all bytes will be equal to 255.
824 fn control_bit_to_seed_mask(control: Choice) -> [u8; 16] {
825 let mask = -(control.unwrap_u8() as i8) as u8;
826 [mask; 16]
827 }
828
829 /// Take two seeds and a control bit, and return the first seed if the control bit is zero, or the
830 /// XOR of the two seeds if the control bit is one. This does not branch on the control bit.
831 pub(crate) fn conditional_xor_seeds(
832 normal_input: &[u8; 16],
833 switched_input: &[u8; 16],
834 control: Choice,
835 ) -> [u8; 16] {
836 xor_seeds(
837 normal_input,
838 &and_seeds(switched_input, &control_bit_to_seed_mask(control)),
839 )
840 }
841
842 /// Returns one of two seeds, depending on the value of a selector bit. Does not branch on the
843 /// selector input or make selector-dependent memory accesses.
844 pub(crate) fn conditional_select_seed(select: Choice, seeds: &[[u8; 16]; 2]) -> [u8; 16] {
845 or_seeds(
846 &and_seeds(&control_bit_to_seed_mask(!select), &seeds[0]),
847 &and_seeds(&control_bit_to_seed_mask(select), &seeds[1]),
848 )
849 }
850
851 /// Interchange the contents of seeds if the choice is 1, otherwise seeds remain unchanged.
852 pub(crate) fn conditional_swap_seed(lhs: &mut [u8; 16], rhs: &mut [u8; 16], choice: Choice) {
853 zip(lhs, rhs).for_each(|(a, b)| u8::conditional_swap(a, b, choice));
854 }
855
856 /// An interface that provides memoization of IDPF computations.
857 ///
858 /// Each instance of a type implementing `IdpfCache` should only be used with one IDPF key and
859 /// public share.
860 ///
861 /// In typical use, IDPFs will be evaluated repeatedly on inputs of increasing length, as part of a
862 /// protocol executed by multiple participants. Each IDPF evaluation computes keys and control
863 /// bits corresponding to tree nodes along a path determined by the input to the IDPF. Thus, the
864 /// values from nodes further up in the tree may be cached and reused in evaluations of subsequent
865 /// longer inputs. If one IDPF input is a prefix of another input, then the first input's path down
866 /// the tree is a prefix of the other input's path.
867 pub trait IdpfCache {
868 /// Fetch cached values for the node identified by the IDPF input.
869 fn get(&self, input: &BitSlice) -> Option<([u8; 16], u8)>;
870
871 /// Store values corresponding to the node identified by the IDPF input.
872 fn insert(&mut self, input: &BitSlice, values: &([u8; 16], u8));
873 }
874
875 /// A no-op [`IdpfCache`] implementation that always reports a cache miss.
876 #[derive(Default)]
877 pub struct NoCache {}
878
879 impl NoCache {
880 /// Construct a `NoCache` object.
881 pub fn new() -> NoCache {
882 NoCache::default()
883 }
884 }
885
886 impl IdpfCache for NoCache {
887 fn get(&self, _: &BitSlice) -> Option<([u8; 16], u8)> {
888 None
889 }
890
891 fn insert(&mut self, _: &BitSlice, _: &([u8; 16], u8)) {}
892 }
893
894 /// A simple [`IdpfCache`] implementation that caches intermediate results in an in-memory hash map,
895 /// with no eviction.
896 #[derive(Default)]
897 pub struct HashMapCache {
898 map: HashMap<BitBox, ([u8; 16], u8)>,
899 }
900
901 impl HashMapCache {
902 /// Create a new unpopulated `HashMapCache`.
903 pub fn new() -> HashMapCache {
904 HashMapCache::default()
905 }
906
907 /// Create a new unpopulated `HashMapCache`, with a set pre-allocated capacity.
908 pub fn with_capacity(capacity: usize) -> HashMapCache {
909 Self {
910 map: HashMap::with_capacity(capacity),
911 }
912 }
913 }
914
915 impl IdpfCache for HashMapCache {
916 fn get(&self, input: &BitSlice) -> Option<([u8; 16], u8)> {
917 self.map.get(input).cloned()
918 }
919
920 fn insert(&mut self, input: &BitSlice, values: &([u8; 16], u8)) {
921 if !self.map.contains_key(input) {
922 self.map
923 .insert(input.to_owned().into_boxed_bitslice(), *values);
924 }
925 }
926 }
927
928 /// A simple [`IdpfCache`] implementation that caches intermediate results in memory, with
929 /// first-in-first-out eviction, and lookups via linear probing.
930 pub struct RingBufferCache {
931 ring: VecDeque<(BitBox, [u8; 16], u8)>,
932 }
933
934 impl RingBufferCache {
935 /// Create a new unpopulated `RingBufferCache`.
936 pub fn new(capacity: usize) -> RingBufferCache {
937 Self {
938 ring: VecDeque::with_capacity(std::cmp::max(capacity, 1)),
939 }
940 }
941 }
942
943 impl IdpfCache for RingBufferCache {
944 fn get(&self, input: &BitSlice) -> Option<([u8; 16], u8)> {
945 // iterate back-to-front, so that we check the most recently pushed entry first.
946 for entry in self.ring.iter().rev() {
947 if input == entry.0 {
948 return Some((entry.1, entry.2));
949 }
950 }
951 None
952 }
953
954 fn insert(&mut self, input: &BitSlice, values: &([u8; 16], u8)) {
955 // evict first (to avoid growing the storage)
956 if self.ring.len() == self.ring.capacity() {
957 self.ring.pop_front();
958 }
959 self.ring
960 .push_back((input.to_owned().into_boxed_bitslice(), values.0, values.1));
961 }
962 }
963
964 /// Utilities for testing IDPFs.
965 #[cfg(feature = "test-util")]
966 #[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
967 pub mod test_utils {
968 use super::*;
969
970 use rand::prelude::*;
971 use zipf::ZipfDistribution;
972
973 /// Generate a set of IDPF inputs with the given bit length `bits`. They are sampled according
974 /// to the Zipf distribution with parameters `zipf_support` and `zipf_exponent`. Return the
975 /// measurements, along with the prefixes traversed during the heavy hitters computation for
976 /// the given threshold.
977 ///
978 /// The prefix tree consists of a sequence of candidate prefixes for each level. For a given level,
979 /// the candidate prefixes are computed from the hit counts of the prefixes at the previous level:
980 /// For any prefix `p` whose hit count is at least the desired threshold, add `p || 0` and `p || 1`
981 /// to the list.
982 pub fn generate_zipf_distributed_batch(
983 rng: &mut impl Rng,
984 bits: usize,
985 threshold: usize,
986 measurement_count: usize,
987 zipf_support: usize,
988 zipf_exponent: f64,
989 ) -> (Vec<IdpfInput>, Vec<Vec<IdpfInput>>) {
990 // Generate random inputs.
991 let mut inputs = Vec::with_capacity(zipf_support);
992 for _ in 0..zipf_support {
993 let bools: Vec<bool> = (0..bits).map(|_| rng.gen()).collect();
994 inputs.push(IdpfInput::from_bools(&bools));
995 }
996
997 // Sample a number of inputs according to the Zipf distribution.
998 let mut samples = Vec::with_capacity(measurement_count);
999 let zipf = ZipfDistribution::new(zipf_support, zipf_exponent).unwrap();
1000 for _ in 0..measurement_count {
1001 samples.push(inputs[zipf.sample(rng) - 1].clone());
1002 }
1003
1004 // Compute the prefix tree for the desired threshold.
1005 let mut prefix_tree = Vec::with_capacity(bits);
1006 prefix_tree.push(vec![
1007 IdpfInput::from_bools(&[false]),
1008 IdpfInput::from_bools(&[true]),
1009 ]);
1010
1011 for level in 0..bits - 1 {
1012 // Compute the hit count of each prefix from the previous level.
1013 let mut hit_counts = vec![0; prefix_tree[level].len()];
1014 for (hit_count, prefix) in hit_counts.iter_mut().zip(prefix_tree[level].iter()) {
1015 for sample in samples.iter() {
1016 let mut is_prefix = true;
1017 for j in 0..prefix.len() {
1018 if prefix[j] != sample[j] {
1019 is_prefix = false;
1020 break;
1021 }
1022 }
1023 if is_prefix {
1024 *hit_count += 1;
1025 }
1026 }
1027 }
1028
1029 // Compute the next set of candidate prefixes.
1030 let mut next_prefixes = Vec::with_capacity(prefix_tree.last().unwrap().len());
1031 for (hit_count, prefix) in hit_counts.iter().zip(prefix_tree[level].iter()) {
1032 if *hit_count >= threshold {
1033 next_prefixes.push(prefix.clone_with_suffix(&[false]));
1034 next_prefixes.push(prefix.clone_with_suffix(&[true]));
1035 }
1036 }
1037 prefix_tree.push(next_prefixes);
1038 }
1039
1040 (samples, prefix_tree)
1041 }
1042 }
1043
1044 #[cfg(test)]
1045 mod tests {
1046 use std::{
1047 collections::HashMap,
1048 convert::TryInto,
1049 io::Cursor,
1050 ops::{Add, AddAssign, Sub},
1051 str::FromStr,
1052 sync::Mutex,
1053 };
1054
1055 use assert_matches::assert_matches;
1056 use bitvec::{
1057 bitbox,
1058 prelude::{BitBox, Lsb0},
1059 slice::BitSlice,
1060 vec::BitVec,
1061 };
1062 use num_bigint::BigUint;
1063 use rand::random;
1064 use subtle::{Choice, ConditionallyNegatable, ConditionallySelectable};
1065
1066 use super::{
1067 HashMapCache, Idpf, IdpfCache, IdpfCorrectionWord, IdpfInput, IdpfOutputShare,
1068 IdpfPublicShare, NoCache, RingBufferCache,
1069 };
1070 use crate::{
1071 codec::{
1072 decode_u32_items, encode_u32_items, CodecError, Decode, Encode, ParameterizedDecode,
1073 },
1074 field::{Field128, Field255, Field64, FieldElement},
1075 prng::Prng,
1076 vdaf::{poplar1::Poplar1IdpfValue, xof::Seed},
1077 };
1078
1079 #[test]
1080 fn idpf_input_conversion() {
1081 let input_1 = IdpfInput::from_bools(&[
1082 false, true, false, false, false, false, false, true, false, true, false, false, false,
1083 false, true, false,
1084 ]);
1085 let input_2 = IdpfInput::from_bytes(b"AB");
1086 assert_eq!(input_1, input_2);
1087 let bits = bitbox![0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0];
1088 assert_eq!(input_1[..], bits);
1089 }
1090
1091 /// A lossy IDPF cache, for testing purposes, that randomly returns cache misses.
1092 #[derive(Default)]
1093 struct LossyCache {
1094 map: HashMap<BitBox, ([u8; 16], u8)>,
1095 }
1096
1097 impl LossyCache {
1098 /// Create a new unpopulated `LossyCache`.
1099 fn new() -> LossyCache {
1100 LossyCache::default()
1101 }
1102 }
1103
1104 impl IdpfCache for LossyCache {
1105 fn get(&self, input: &BitSlice) -> Option<([u8; 16], u8)> {
1106 if random() {
1107 self.map.get(input).cloned()
1108 } else {
1109 None
1110 }
1111 }
1112
1113 fn insert(&mut self, input: &BitSlice, values: &([u8; 16], u8)) {
1114 if !self.map.contains_key(input) {
1115 self.map
1116 .insert(input.to_owned().into_boxed_bitslice(), *values);
1117 }
1118 }
1119 }
1120
1121 /// A wrapper [`IdpfCache`] implementation that records `get()` calls, for testing purposes.
1122 struct SnoopingCache<T> {
1123 inner: T,
1124 get_calls: Mutex<Vec<BitBox>>,
1125 insert_calls: Mutex<Vec<(BitBox, [u8; 16], u8)>>,
1126 }
1127
1128 impl<T> SnoopingCache<T> {
1129 fn new(inner: T) -> SnoopingCache<T> {
1130 SnoopingCache {
1131 inner,
1132 get_calls: Mutex::new(Vec::new()),
1133 insert_calls: Mutex::new(Vec::new()),
1134 }
1135 }
1136 }
1137
1138 impl<T> IdpfCache for SnoopingCache<T>
1139 where
1140 T: IdpfCache,
1141 {
1142 fn get(&self, input: &BitSlice) -> Option<([u8; 16], u8)> {
1143 self.get_calls
1144 .lock()
1145 .unwrap()
1146 .push(input.to_owned().into_boxed_bitslice());
1147 self.inner.get(input)
1148 }
1149
1150 fn insert(&mut self, input: &BitSlice, values: &([u8; 16], u8)) {
1151 self.insert_calls.lock().unwrap().push((
1152 input.to_owned().into_boxed_bitslice(),
1153 values.0,
1154 values.1,
1155 ));
1156 self.inner.insert(input, values)
1157 }
1158 }
1159
1160 #[test]
1161 fn test_idpf_poplar() {
1162 let input = bitbox![0, 1, 1, 0, 1].into();
1163 let nonce: [u8; 16] = random();
1164 let idpf = Idpf::new((), ());
1165 let (public_share, keys) = idpf
1166 .gen(
1167 &input,
1168 Vec::from([Poplar1IdpfValue::new([Field64::one(), Field64::one()]); 4]),
1169 Poplar1IdpfValue::new([Field255::one(), Field255::one()]),
1170 &nonce,
1171 )
1172 .unwrap();
1173
1174 check_idpf_poplar_evaluation(
1175 &public_share,
1176 &keys,
1177 &bitbox![0].into(),
1178 &nonce,
1179 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::one(), Field64::one()])),
1180 &mut NoCache::new(),
1181 &mut NoCache::new(),
1182 );
1183 check_idpf_poplar_evaluation(
1184 &public_share,
1185 &keys,
1186 &bitbox![1].into(),
1187 &nonce,
1188 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::zero(), Field64::zero()])),
1189 &mut NoCache::new(),
1190 &mut NoCache::new(),
1191 );
1192 check_idpf_poplar_evaluation(
1193 &public_share,
1194 &keys,
1195 &bitbox![0, 1].into(),
1196 &nonce,
1197 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::one(), Field64::one()])),
1198 &mut NoCache::new(),
1199 &mut NoCache::new(),
1200 );
1201 check_idpf_poplar_evaluation(
1202 &public_share,
1203 &keys,
1204 &bitbox![0, 0].into(),
1205 &nonce,
1206 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::zero(), Field64::zero()])),
1207 &mut NoCache::new(),
1208 &mut NoCache::new(),
1209 );
1210 check_idpf_poplar_evaluation(
1211 &public_share,
1212 &keys,
1213 &bitbox![1, 0].into(),
1214 &nonce,
1215 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::zero(), Field64::zero()])),
1216 &mut NoCache::new(),
1217 &mut NoCache::new(),
1218 );
1219 check_idpf_poplar_evaluation(
1220 &public_share,
1221 &keys,
1222 &bitbox![1, 1].into(),
1223 &nonce,
1224 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::zero(), Field64::zero()])),
1225 &mut NoCache::new(),
1226 &mut NoCache::new(),
1227 );
1228 check_idpf_poplar_evaluation(
1229 &public_share,
1230 &keys,
1231 &bitbox![0, 1, 1].into(),
1232 &nonce,
1233 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::one(), Field64::one()])),
1234 &mut NoCache::new(),
1235 &mut NoCache::new(),
1236 );
1237 check_idpf_poplar_evaluation(
1238 &public_share,
1239 &keys,
1240 &bitbox![0, 1, 1, 0].into(),
1241 &nonce,
1242 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::one(), Field64::one()])),
1243 &mut NoCache::new(),
1244 &mut NoCache::new(),
1245 );
1246 check_idpf_poplar_evaluation(
1247 &public_share,
1248 &keys,
1249 &bitbox![0, 1, 1, 0, 1].into(),
1250 &nonce,
1251 &IdpfOutputShare::Leaf(Poplar1IdpfValue::new([Field255::one(), Field255::one()])),
1252 &mut NoCache::new(),
1253 &mut NoCache::new(),
1254 );
1255 check_idpf_poplar_evaluation(
1256 &public_share,
1257 &keys,
1258 &bitbox![0, 1, 1, 0, 0].into(),
1259 &nonce,
1260 &IdpfOutputShare::Leaf(Poplar1IdpfValue::new([Field255::zero(), Field255::zero()])),
1261 &mut NoCache::new(),
1262 &mut NoCache::new(),
1263 );
1264 check_idpf_poplar_evaluation(
1265 &public_share,
1266 &keys,
1267 &bitbox![1, 0, 1, 0, 0].into(),
1268 &nonce,
1269 &IdpfOutputShare::Leaf(Poplar1IdpfValue::new([Field255::zero(), Field255::zero()])),
1270 &mut NoCache::new(),
1271 &mut NoCache::new(),
1272 );
1273 }
1274
1275 fn check_idpf_poplar_evaluation(
1276 public_share: &IdpfPublicShare<Poplar1IdpfValue<Field64>, Poplar1IdpfValue<Field255>>,
1277 keys: &[Seed<16>; 2],
1278 prefix: &IdpfInput,
1279 binder: &[u8],
1280 expected_output: &IdpfOutputShare<Poplar1IdpfValue<Field64>, Poplar1IdpfValue<Field255>>,
1281 cache_0: &mut dyn IdpfCache,
1282 cache_1: &mut dyn IdpfCache,
1283 ) {
1284 let idpf = Idpf::new((), ());
1285 let share_0 = idpf
1286 .eval(0, public_share, &keys[0], prefix, binder, cache_0)
1287 .unwrap();
1288 let share_1 = idpf
1289 .eval(1, public_share, &keys[1], prefix, binder, cache_1)
1290 .unwrap();
1291 let output = share_0.merge(share_1).unwrap();
1292 assert_eq!(&output, expected_output);
1293 }
1294
1295 #[test]
1296 fn test_idpf_poplar_medium() {
1297 // This test on 40 byte inputs takes about a second in debug mode. (and ten milliseconds in
1298 // release mode)
1299 const INPUT_LEN: usize = 320;
1300 let mut bits = bitbox![0; INPUT_LEN];
1301 for mut bit in bits.iter_mut() {
1302 bit.set(random());
1303 }
1304 let input = bits.clone().into();
1305
1306 let mut inner_values = Vec::with_capacity(INPUT_LEN - 1);
1307 let mut prng = Prng::new().unwrap();
1308 for _ in 0..INPUT_LEN - 1 {
1309 inner_values.push(Poplar1IdpfValue::new([
1310 Field64::one(),
1311 prng.next().unwrap(),
1312 ]));
1313 }
1314 let leaf_values =
1315 Poplar1IdpfValue::new([Field255::one(), Prng::new().unwrap().next().unwrap()]);
1316
1317 let nonce: [u8; 16] = random();
1318 let idpf = Idpf::new((), ());
1319 let (public_share, keys) = idpf
1320 .gen(&input, inner_values.clone(), leaf_values, &nonce)
1321 .unwrap();
1322 let mut cache_0 = RingBufferCache::new(3);
1323 let mut cache_1 = RingBufferCache::new(3);
1324
1325 for (level, values) in inner_values.iter().enumerate() {
1326 let mut prefix = BitBox::from_bitslice(&bits[..=level]).into();
1327 check_idpf_poplar_evaluation(
1328 &public_share,
1329 &keys,
1330 &prefix,
1331 &nonce,
1332 &IdpfOutputShare::Inner(*values),
1333 &mut cache_0,
1334 &mut cache_1,
1335 );
1336 let flipped_bit = !prefix[level];
1337 prefix.index.set(level, flipped_bit);
1338 check_idpf_poplar_evaluation(
1339 &public_share,
1340 &keys,
1341 &prefix,
1342 &nonce,
1343 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::zero(), Field64::zero()])),
1344 &mut cache_0,
1345 &mut cache_1,
1346 );
1347 }
1348 check_idpf_poplar_evaluation(
1349 &public_share,
1350 &keys,
1351 &input,
1352 &nonce,
1353 &IdpfOutputShare::Leaf(leaf_values),
1354 &mut cache_0,
1355 &mut cache_1,
1356 );
1357 let mut modified_bits = bits.clone();
1358 modified_bits.set(INPUT_LEN - 1, !bits[INPUT_LEN - 1]);
1359 check_idpf_poplar_evaluation(
1360 &public_share,
1361 &keys,
1362 &modified_bits.into(),
1363 &nonce,
1364 &IdpfOutputShare::Leaf(Poplar1IdpfValue::new([Field255::zero(), Field255::zero()])),
1365 &mut cache_0,
1366 &mut cache_1,
1367 );
1368 }
1369
1370 #[test]
1371 fn idpf_poplar_cache_behavior() {
1372 let bits = bitbox![0, 1, 1, 1, 0, 1, 0, 0];
1373 let input = bits.into();
1374
1375 let mut inner_values = Vec::with_capacity(7);
1376 let mut prng = Prng::new().unwrap();
1377 for _ in 0..7 {
1378 inner_values.push(Poplar1IdpfValue::new([
1379 Field64::one(),
1380 prng.next().unwrap(),
1381 ]));
1382 }
1383 let leaf_values =
1384 Poplar1IdpfValue::new([Field255::one(), Prng::new().unwrap().next().unwrap()]);
1385
1386 let nonce: [u8; 16] = random();
1387 let idpf = Idpf::new((), ());
1388 let (public_share, keys) = idpf
1389 .gen(&input, inner_values.clone(), leaf_values, &nonce)
1390 .unwrap();
1391 let mut cache_0 = SnoopingCache::new(HashMapCache::new());
1392 let mut cache_1 = HashMapCache::new();
1393
1394 check_idpf_poplar_evaluation(
1395 &public_share,
1396 &keys,
1397 &bitbox![1, 1, 0, 0].into(),
1398 &nonce,
1399 &IdpfOutputShare::Inner(Poplar1IdpfValue::new([Field64::zero(), Field64::zero()])),
1400 &mut cache_0,
1401 &mut cache_1,
1402 );
1403 assert_eq!(
1404 cache_0
1405 .get_calls
1406 .lock()
1407 .unwrap()
1408 .drain(..)
1409 .collect::<Vec<_>>(),
1410 vec![bitbox![1, 1, 0], bitbox![1, 1], bitbox![1]],
1411 );
1412 assert_eq!(
1413 cache_0
1414 .insert_calls
1415 .lock()
1416 .unwrap()
1417 .drain(..)
1418 .map(|(input, _, _)| input)
1419 .collect::<Vec<_>>(),
1420 vec![
1421 bitbox![1],
1422 bitbox![1, 1],
1423 bitbox![1, 1, 0],
1424 bitbox![1, 1, 0, 0]
1425 ],
1426 );
1427
1428 check_idpf_poplar_evaluation(
1429 &public_share,
1430 &keys,
1431 &bitbox![0].into(),
1432 &nonce,
1433 &IdpfOutputShare::Inner(inner_values[0]),
1434 &mut cache_0,
1435 &mut cache_1,
1436 );
1437 assert_eq!(
1438 cache_0
1439 .get_calls
1440 .lock()
1441 .unwrap()
1442 .drain(..)
1443 .collect::<Vec<BitBox>>(),
1444 Vec::<BitBox>::new(),
1445 );
1446 assert_eq!(
1447 cache_0
1448 .insert_calls
1449 .lock()
1450 .unwrap()
1451 .drain(..)
1452 .map(|(input, _, _)| input)
1453 .collect::<Vec<_>>(),
1454 vec![bitbox![0]],
1455 );
1456
1457 check_idpf_poplar_evaluation(
1458 &public_share,
1459 &keys,
1460 &bitbox![0, 1].into(),
1461 &nonce,
1462 &IdpfOutputShare::Inner(inner_values[1]),
1463 &mut cache_0,
1464 &mut cache_1,
1465 );
1466 assert_eq!(
1467 cache_0
1468 .get_calls
1469 .lock()
1470 .unwrap()
1471 .drain(..)
1472 .collect::<Vec<_>>(),
1473 vec![bitbox![0]],
1474 );
1475 assert_eq!(
1476 cache_0
1477 .insert_calls
1478 .lock()
1479 .unwrap()
1480 .drain(..)
1481 .map(|(input, _, _)| input)
1482 .collect::<Vec<_>>(),
1483 vec![bitbox![0, 1]],
1484 );
1485
1486 check_idpf_poplar_evaluation(
1487 &public_share,
1488 &keys,
1489 &input,
1490 &nonce,
1491 &IdpfOutputShare::Leaf(leaf_values),
1492 &mut cache_0,
1493 &mut cache_1,
1494 );
1495 assert_eq!(
1496 cache_0
1497 .get_calls
1498 .lock()
1499 .unwrap()
1500 .drain(..)
1501 .collect::<Vec<_>>(),
1502 vec![
1503 bitbox![0, 1, 1, 1, 0, 1, 0],
1504 bitbox![0, 1, 1, 1, 0, 1],
1505 bitbox![0, 1, 1, 1, 0],
1506 bitbox![0, 1, 1, 1],
1507 bitbox![0, 1, 1],
1508 bitbox![0, 1],
1509 ],
1510 );
1511 assert_eq!(
1512 cache_0
1513 .insert_calls
1514 .lock()
1515 .unwrap()
1516 .drain(..)
1517 .map(|(input, _, _)| input)
1518 .collect::<Vec<_>>(),
1519 vec![
1520 bitbox![0, 1, 1],
1521 bitbox![0, 1, 1, 1],
1522 bitbox![0, 1, 1, 1, 0],
1523 bitbox![0, 1, 1, 1, 0, 1],
1524 bitbox![0, 1, 1, 1, 0, 1, 0],
1525 ],
1526 );
1527
1528 check_idpf_poplar_evaluation(
1529 &public_share,
1530 &keys,
1531 &input,
1532 &nonce,
1533 &IdpfOutputShare::Leaf(leaf_values),
1534 &mut cache_0,
1535 &mut cache_1,
1536 );
1537 assert_eq!(
1538 cache_0
1539 .get_calls
1540 .lock()
1541 .unwrap()
1542 .drain(..)
1543 .collect::<Vec<_>>(),
1544 vec![bitbox![0, 1, 1, 1, 0, 1, 0]],
1545 );
1546 assert!(cache_0.insert_calls.lock().unwrap().is_empty());
1547 }
1548
1549 #[test]
1550 fn idpf_poplar_lossy_cache() {
1551 let bits = bitbox![1, 0, 0, 1, 1, 0, 1, 0];
1552 let input = bits.into();
1553
1554 let mut inner_values = Vec::with_capacity(7);
1555 let mut prng = Prng::new().unwrap();
1556 for _ in 0..7 {
1557 inner_values.push(Poplar1IdpfValue::new([
1558 Field64::one(),
1559 prng.next().unwrap(),
1560 ]));
1561 }
1562 let leaf_values =
1563 Poplar1IdpfValue::new([Field255::one(), Prng::new().unwrap().next().unwrap()]);
1564
1565 let nonce: [u8; 16] = random();
1566 let idpf = Idpf::new((), ());
1567 let (public_share, keys) = idpf
1568 .gen(&input, inner_values.clone(), leaf_values, &nonce)
1569 .unwrap();
1570 let mut cache_0 = LossyCache::new();
1571 let mut cache_1 = LossyCache::new();
1572
1573 for (level, values) in inner_values.iter().enumerate() {
1574 check_idpf_poplar_evaluation(
1575 &public_share,
1576 &keys,
1577 &input[..=level].to_owned().into(),
1578 &nonce,
1579 &IdpfOutputShare::Inner(*values),
1580 &mut cache_0,
1581 &mut cache_1,
1582 );
1583 }
1584 check_idpf_poplar_evaluation(
1585 &public_share,
1586 &keys,
1587 &input,
1588 &nonce,
1589 &IdpfOutputShare::Leaf(leaf_values),
1590 &mut cache_0,
1591 &mut cache_1,
1592 );
1593 }
1594
1595 #[test]
1596 fn test_idpf_poplar_error_cases() {
1597 let nonce: [u8; 16] = random();
1598 let idpf = Idpf::new((), ());
1599 // Zero bits does not make sense.
1600 idpf.gen(
1601 &bitbox![].into(),
1602 Vec::<Poplar1IdpfValue<Field64>>::new(),
1603 Poplar1IdpfValue::new([Field255::zero(); 2]),
1604 &nonce,
1605 )
1606 .unwrap_err();
1607
1608 let (public_share, keys) = idpf
1609 .gen(
1610 &bitbox![0;10].into(),
1611 Vec::from([Poplar1IdpfValue::new([Field64::zero(); 2]); 9]),
1612 Poplar1IdpfValue::new([Field255::zero(); 2]),
1613 &nonce,
1614 )
1615 .unwrap();
1616
1617 // Wrong number of values.
1618 idpf.gen(
1619 &bitbox![0; 10].into(),
1620 Vec::from([Poplar1IdpfValue::new([Field64::zero(); 2]); 8]),
1621 Poplar1IdpfValue::new([Field255::zero(); 2]),
1622 &nonce,
1623 )
1624 .unwrap_err();
1625 idpf.gen(
1626 &bitbox![0; 10].into(),
1627 Vec::from([Poplar1IdpfValue::new([Field64::zero(); 2]); 10]),
1628 Poplar1IdpfValue::new([Field255::zero(); 2]),
1629 &nonce,
1630 )
1631 .unwrap_err();
1632
1633 // Evaluating with empty prefix.
1634 assert!(idpf
1635 .eval(
1636 0,
1637 &public_share,
1638 &keys[0],
1639 &bitbox![].into(),
1640 &nonce,
1641 &mut NoCache::new(),
1642 )
1643 .is_err());
1644 // Evaluating with too-long prefix.
1645 assert!(idpf
1646 .eval(
1647 0,
1648 &public_share,
1649 &keys[0],
1650 &bitbox![0; 11].into(),
1651 &nonce,
1652 &mut NoCache::new(),
1653 )
1654 .is_err());
1655 }
1656
1657 #[test]
1658 fn idpf_poplar_public_share_round_trip() {
1659 let public_share = IdpfPublicShare {
1660 inner_correction_words: Vec::from([
1661 IdpfCorrectionWord {
1662 seed: [0xab; 16],
1663 control_bits: [Choice::from(1), Choice::from(0)],
1664 value: Poplar1IdpfValue::new([
1665 Field64::from(83261u64),
1666 Field64::from(125159u64),
1667 ]),
1668 },
1669 IdpfCorrectionWord{
1670 seed: [0xcd;16],
1671 control_bits: [Choice::from(0), Choice::from(1)],
1672 value: Poplar1IdpfValue::new([
1673 Field64::from(17614120u64),
1674 Field64::from(20674u64),
1675 ]),
1676 },
1677 ]),
1678 leaf_correction_word: IdpfCorrectionWord {
1679 seed: [0xff; 16],
1680 control_bits: [Choice::from(1), Choice::from(1)],
1681 value: Poplar1IdpfValue::new([
1682 Field255::one(),
1683 Field255::get_decoded(
1684 b"\xf0\xde\xbc\x9a\x78\x56\x34\x12\xf0\xde\xbc\x9a\x78\x56\x34\x12\xf0\xde\xbc\x9a\x78\x56\x34\x12\xf0\xde\xbc\x9a\x78\x56\x34\x12", // field element correction word, continued
1685 ).unwrap(),
1686 ]),
1687 },
1688 };
1689 let message = hex::decode(concat!(
1690 "39", // packed control bit correction words (0b00111001)
1691 "abababababababababababababababab", // seed correction word, first level
1692 "3d45010000000000", // field element correction word
1693 "e7e8010000000000", // field element correction word, continued
1694 "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", // seed correction word, second level
1695 "28c50c0100000000", // field element correction word
1696 "c250000000000000", // field element correction word, continued
1697 "ffffffffffffffffffffffffffffffff", // seed correction word, third level
1698 "0100000000000000000000000000000000000000000000000000000000000000", // field element correction word, leaf field
1699 "f0debc9a78563412f0debc9a78563412f0debc9a78563412f0debc9a78563412", // field element correction word, continued
1700 ))
1701 .unwrap();
1702 let encoded = public_share.get_encoded().unwrap();
1703 let decoded = IdpfPublicShare::get_decoded_with_param(&3, &message).unwrap();
1704 assert_eq!(public_share, decoded);
1705 assert_eq!(message, encoded);
1706 assert_eq!(public_share.encoded_len().unwrap(), encoded.len());
1707
1708 // check serialization of packed control bits when they span multiple bytes:
1709 let public_share = IdpfPublicShare {
1710 inner_correction_words: Vec::from([
1711 IdpfCorrectionWord {
1712 seed: [0; 16],
1713 control_bits: [Choice::from(1), Choice::from(1)],
1714 value: Poplar1IdpfValue::new([Field64::zero(), Field64::zero()]),
1715 },
1716 IdpfCorrectionWord {
1717 seed: [0; 16],
1718 control_bits: [Choice::from(1), Choice::from(1)],
1719 value: Poplar1IdpfValue::new([Field64::zero(), Field64::zero()]),
1720 },
1721 IdpfCorrectionWord {
1722 seed: [0; 16],
1723 control_bits: [Choice::from(1), Choice::from(0)],
1724 value: Poplar1IdpfValue::new([Field64::zero(), Field64::zero()]),
1725 },
1726 IdpfCorrectionWord {
1727 seed: [0; 16],
1728 control_bits: [Choice::from(1), Choice::from(1)],
1729 value: Poplar1IdpfValue::new([Field64::zero(), Field64::zero()]),
1730 },
1731 IdpfCorrectionWord {
1732 seed: [0; 16],
1733 control_bits: [Choice::from(1), Choice::from(1)],
1734 value: Poplar1IdpfValue::new([Field64::zero(), Field64::zero()]),
1735 },
1736 IdpfCorrectionWord {
1737 seed: [0; 16],
1738 control_bits: [Choice::from(0), Choice::from(1)],
1739 value: Poplar1IdpfValue::new([Field64::zero(), Field64::zero()]),
1740 },
1741 IdpfCorrectionWord {
1742 seed: [0; 16],
1743 control_bits: [Choice::from(1), Choice::from(1)],
1744 value: Poplar1IdpfValue::new([Field64::zero(), Field64::zero()]),
1745 },
1746 IdpfCorrectionWord {
1747 seed: [0; 16],
1748 control_bits: [Choice::from(1), Choice::from(1)],
1749 value: Poplar1IdpfValue::new([Field64::zero(), Field64::zero()]),
1750 },
1751 ]),
1752 leaf_correction_word: IdpfCorrectionWord {
1753 seed: [0; 16],
1754 control_bits: [Choice::from(0), Choice::from(1)],
1755 value: Poplar1IdpfValue::new([Field255::zero(), Field255::zero()]),
1756 },
1757 };
1758 let message = hex::decode(concat!(
1759 "dffb02", // packed correction word control bits: 0b11011111, 0b11111011, 0b10
1760 "00000000000000000000000000000000",
1761 "0000000000000000",
1762 "0000000000000000",
1763 "00000000000000000000000000000000",
1764 "0000000000000000",
1765 "0000000000000000",
1766 "00000000000000000000000000000000",
1767 "0000000000000000",
1768 "0000000000000000",
1769 "00000000000000000000000000000000",
1770 "0000000000000000",
1771 "0000000000000000",
1772 "00000000000000000000000000000000",
1773 "0000000000000000",
1774 "0000000000000000",
1775 "00000000000000000000000000000000",
1776 "0000000000000000",
1777 "0000000000000000",
1778 "00000000000000000000000000000000",
1779 "0000000000000000",
1780 "0000000000000000",
1781 "00000000000000000000000000000000",
1782 "0000000000000000",
1783 "0000000000000000",
1784 "00000000000000000000000000000000",
1785 "0000000000000000000000000000000000000000000000000000000000000000",
1786 "0000000000000000000000000000000000000000000000000000000000000000",
1787 ))
1788 .unwrap();
1789 let encoded = public_share.get_encoded().unwrap();
1790 let decoded = IdpfPublicShare::get_decoded_with_param(&9, &message).unwrap();
1791 assert_eq!(public_share, decoded);
1792 assert_eq!(message, encoded);
1793 }
1794
1795 #[test]
1796 fn idpf_poplar_public_share_control_bit_codec() {
1797 let test_cases = [
1798 (&[false, true][..], &[0b10][..]),
1799 (
1800 &[false, false, true, false, false, true][..],
1801 &[0b10_0100u8][..],
1802 ),
1803 (
1804 &[
1805 true, true, false, true, false, false, false, false, true, true,
1806 ][..],
1807 &[0b0000_1011, 0b11][..],
1808 ),
1809 (
1810 &[
1811 true, true, false, true, false, true, true, true, false, true, false, true,
1812 false, false, true, false,
1813 ][..],
1814 &[0b1110_1011, 0b0100_1010][..],
1815 ),
1816 (
1817 &[
1818 true, true, true, true, true, false, true, true, false, true, true, true,
1819 false, true, false, true, false, false, true, false, true, true,
1820 ][..],
1821 &[0b1101_1111, 0b1010_1110, 0b11_0100][..],
1822 ),
1823 ];
1824
1825 for (control_bits, serialized_control_bits) in test_cases {
1826 let public_share = IdpfPublicShare::<
1827 Poplar1IdpfValue<Field64>,
1828 Poplar1IdpfValue<Field255>,
1829 > {
1830 inner_correction_words: control_bits[..control_bits.len() - 2]
1831 .chunks(2)
1832 .map(|chunk| IdpfCorrectionWord {
1833 seed: [0; 16],
1834 control_bits: [Choice::from(chunk[0] as u8), Choice::from(chunk[1] as u8)],
1835 value: Poplar1IdpfValue::new([Field64::zero(); 2]),
1836 })
1837 .collect(),
1838 leaf_correction_word: IdpfCorrectionWord {
1839 seed: [0; 16],
1840 control_bits: [
1841 Choice::from(control_bits[control_bits.len() - 2] as u8),
1842 Choice::from(control_bits[control_bits.len() - 1] as u8),
1843 ],
1844 value: Poplar1IdpfValue::new([Field255::zero(); 2]),
1845 },
1846 };
1847
1848 let mut serialized_public_share = serialized_control_bits.to_owned();
1849 let idpf_bits = control_bits.len() / 2;
1850 let size_seeds = 16 * idpf_bits;
1851 let size_field_vecs =
1852 Field64::ENCODED_SIZE * 2 * (idpf_bits - 1) + Field255::ENCODED_SIZE * 2;
1853 serialized_public_share.resize(
1854 serialized_control_bits.len() + size_seeds + size_field_vecs,
1855 0,
1856 );
1857
1858 assert_eq!(public_share.get_encoded().unwrap(), serialized_public_share);
1859 assert_eq!(
1860 IdpfPublicShare::get_decoded_with_param(&idpf_bits, &serialized_public_share)
1861 .unwrap(),
1862 public_share
1863 );
1864 }
1865 }
1866
1867 #[test]
1868 fn idpf_poplar_public_share_unused_bits() {
1869 let mut buf = vec![0u8; 4096];
1870
1871 buf[0] = 1 << 2;
1872 let err =
1873 IdpfPublicShare::<Field64, Field255>::decode_with_param(&1, &mut Cursor::new(&buf))
1874 .unwrap_err();
1875 assert_matches!(err, CodecError::UnexpectedValue);
1876
1877 buf[0] = 1 << 4;
1878 let err =
1879 IdpfPublicShare::<Field64, Field255>::decode_with_param(&2, &mut Cursor::new(&buf))
1880 .unwrap_err();
1881 assert_matches!(err, CodecError::UnexpectedValue);
1882
1883 buf[0] = 1 << 6;
1884 let err =
1885 IdpfPublicShare::<Field64, Field255>::decode_with_param(&3, &mut Cursor::new(&buf))
1886 .unwrap_err();
1887 assert_matches!(err, CodecError::UnexpectedValue);
1888
1889 buf[0] = 0;
1890 buf[1] = 1 << 2;
1891 let err =
1892 IdpfPublicShare::<Field64, Field255>::decode_with_param(&5, &mut Cursor::new(&buf))
1893 .unwrap_err();
1894 assert_matches!(err, CodecError::UnexpectedValue);
1895 }
1896
1897 /// Stores a test vector for the IDPF key generation algorithm.
1898 struct IdpfTestVector {
1899 /// The number of bits in IDPF inputs.
1900 bits: usize,
1901 /// The binder string used when generating and evaluating keys.
1902 binder: Vec<u8>,
1903 /// The IDPF input provided to the key generation algorithm.
1904 alpha: IdpfInput,
1905 /// The IDPF output values, at each inner level, provided to the key generation algorithm.
1906 beta_inner: Vec<Poplar1IdpfValue<Field64>>,
1907 /// The IDPF output values for the leaf level, provided to the key generation algorithm.
1908 beta_leaf: Poplar1IdpfValue<Field255>,
1909 /// The two keys returned by the key generation algorithm.
1910 keys: [[u8; 16]; 2],
1911 /// The public share returned by the key generation algorithm.
1912 public_share: Vec<u8>,
1913 }
1914
1915 /// Load a test vector for Idpf key generation.
1916 fn load_idpfpoplar_test_vector() -> IdpfTestVector {
1917 let test_vec: serde_json::Value =
1918 serde_json::from_str(include_str!("vdaf/test_vec/08/IdpfPoplar_0.json")).unwrap();
1919 let test_vec_obj = test_vec.as_object().unwrap();
1920
1921 let bits = test_vec_obj
1922 .get("bits")
1923 .unwrap()
1924 .as_u64()
1925 .unwrap()
1926 .try_into()
1927 .unwrap();
1928
1929 let alpha_str = test_vec_obj.get("alpha").unwrap().as_str().unwrap();
1930 let alpha_bignum = BigUint::from_str(alpha_str).unwrap();
1931 let zero_bignum = BigUint::from(0u8);
1932 let one_bignum = BigUint::from(1u8);
1933 let alpha_bits = (0..bits)
1934 .map(|level| (&alpha_bignum >> (bits - level - 1)) & &one_bignum != zero_bignum)
1935 .collect::<BitVec>();
1936 let alpha = alpha_bits.into();
1937
1938 let beta_inner_level_array = test_vec_obj.get("beta_inner").unwrap().as_array().unwrap();
1939 let beta_inner = beta_inner_level_array
1940 .iter()
1941 .map(|array| {
1942 Poplar1IdpfValue::new([
1943 Field64::from(array[0].as_str().unwrap().parse::<u64>().unwrap()),
1944 Field64::from(array[1].as_str().unwrap().parse::<u64>().unwrap()),
1945 ])
1946 })
1947 .collect::<Vec<_>>();
1948
1949 let beta_leaf_array = test_vec_obj.get("beta_leaf").unwrap().as_array().unwrap();
1950 let beta_leaf = Poplar1IdpfValue::new([
1951 Field255::from(
1952 beta_leaf_array[0]
1953 .as_str()
1954 .unwrap()
1955 .parse::<BigUint>()
1956 .unwrap(),
1957 ),
1958 Field255::from(
1959 beta_leaf_array[1]
1960 .as_str()
1961 .unwrap()
1962 .parse::<BigUint>()
1963 .unwrap(),
1964 ),
1965 ]);
1966
1967 let keys_array = test_vec_obj.get("keys").unwrap().as_array().unwrap();
1968 let keys = [
1969 hex::decode(keys_array[0].as_str().unwrap())
1970 .unwrap()
1971 .try_into()
1972 .unwrap(),
1973 hex::decode(keys_array[1].as_str().unwrap())
1974 .unwrap()
1975 .try_into()
1976 .unwrap(),
1977 ];
1978
1979 let public_share_hex = test_vec_obj.get("public_share").unwrap();
1980 let public_share = hex::decode(public_share_hex.as_str().unwrap()).unwrap();
1981
1982 let binder_hex = test_vec_obj.get("binder").unwrap();
1983 let binder = hex::decode(binder_hex.as_str().unwrap()).unwrap();
1984
1985 IdpfTestVector {
1986 bits,
1987 binder,
1988 alpha,
1989 beta_inner,
1990 beta_leaf,
1991 keys,
1992 public_share,
1993 }
1994 }
1995
1996 #[test]
1997 fn idpf_poplar_generate_test_vector() {
1998 let test_vector = load_idpfpoplar_test_vector();
1999 let idpf = Idpf::new((), ());
2000 let (public_share, keys) = idpf
2001 .gen_with_random(
2002 &test_vector.alpha,
2003 test_vector.beta_inner,
2004 test_vector.beta_leaf,
2005 &test_vector.binder,
2006 &test_vector.keys,
2007 )
2008 .unwrap();
2009
2010 assert_eq!(keys[0].0, test_vector.keys[0]);
2011 assert_eq!(keys[1].0, test_vector.keys[1]);
2012
2013 let expected_public_share =
2014 IdpfPublicShare::get_decoded_with_param(&test_vector.bits, &test_vector.public_share)
2015 .unwrap();
2016 for (level, (correction_words, expected_correction_words)) in public_share
2017 .inner_correction_words
2018 .iter()
2019 .zip(expected_public_share.inner_correction_words.iter())
2020 .enumerate()
2021 {
2022 assert_eq!(
2023 correction_words, expected_correction_words,
2024 "layer {level} did not match\n{correction_words:#x?}\n{expected_correction_words:#x?}"
2025 );
2026 }
2027 assert_eq!(
2028 public_share.leaf_correction_word,
2029 expected_public_share.leaf_correction_word
2030 );
2031
2032 assert_eq!(
2033 public_share, expected_public_share,
2034 "public share did not match\n{public_share:#x?}\n{expected_public_share:#x?}"
2035 );
2036 let encoded_public_share = public_share.get_encoded().unwrap();
2037 assert_eq!(encoded_public_share, test_vector.public_share);
2038 }
2039
2040 #[test]
2041 fn idpf_input_from_bytes_to_bytes() {
2042 let test_cases: &[&[u8]] = &[b"hello", b"banana", &[1], &[127], &[1, 2, 3, 4], &[]];
2043 for test_case in test_cases {
2044 assert_eq!(&IdpfInput::from_bytes(test_case).to_bytes(), test_case);
2045 }
2046 }
2047
2048 #[test]
2049 fn idpf_input_from_bools_to_bytes() {
2050 let input = IdpfInput::from_bools(&[true; 7]);
2051 assert_eq!(input.to_bytes(), &[254]);
2052 let input = IdpfInput::from_bools(&[true; 9]);
2053 assert_eq!(input.to_bytes(), &[255, 128]);
2054 }
2055
2056 /// Demonstrate use of an IDPF with values that need run-time parameters for random generation.
2057 #[test]
2058 fn idpf_with_value_parameters() {
2059 use super::IdpfValue;
2060
2061 /// A test-only type for use as an [`IdpfValue`].
2062 #[derive(Debug, Clone, Copy)]
2063 struct MyUnit;
2064
2065 impl IdpfValue for MyUnit {
2066 type ValueParameter = ();
2067
2068 fn generate<S>(_: &mut S, _: &Self::ValueParameter) -> Self
2069 where
2070 S: rand_core::RngCore,
2071 {
2072 MyUnit
2073 }
2074
2075 fn zero(_: &()) -> Self {
2076 MyUnit
2077 }
2078
2079 fn conditional_select(_: &Self, _: &Self, _: Choice) -> Self {
2080 MyUnit
2081 }
2082 }
2083
2084 impl Encode for MyUnit {
2085 fn encode(&self, _: &mut Vec<u8>) -> Result<(), CodecError> {
2086 Ok(())
2087 }
2088 }
2089
2090 impl Decode for MyUnit {
2091 fn decode(_: &mut Cursor<&[u8]>) -> Result<Self, CodecError> {
2092 Ok(MyUnit)
2093 }
2094 }
2095
2096 impl ConditionallySelectable for MyUnit {
2097 fn conditional_select(_: &Self, _: &Self, _: Choice) -> Self {
2098 MyUnit
2099 }
2100 }
2101
2102 impl ConditionallyNegatable for MyUnit {
2103 fn conditional_negate(&mut self, _: Choice) {}
2104 }
2105
2106 impl Add for MyUnit {
2107 type Output = Self;
2108
2109 fn add(self, _: Self) -> Self::Output {
2110 MyUnit
2111 }
2112 }
2113
2114 impl AddAssign for MyUnit {
2115 fn add_assign(&mut self, _: Self) {}
2116 }
2117
2118 impl Sub for MyUnit {
2119 type Output = Self;
2120
2121 fn sub(self, _: Self) -> Self::Output {
2122 MyUnit
2123 }
2124 }
2125
2126 /// A test-only type for use as an [`IdpfValue`], representing a variable-length vector of
2127 /// field elements. The length must be fixed before generating IDPF keys, but we assume it
2128 /// is not known at compile time.
2129 #[derive(Debug, Clone)]
2130 struct MyVector(Vec<Field128>);
2131
2132 impl IdpfValue for MyVector {
2133 type ValueParameter = usize;
2134
2135 fn generate<S>(seed_stream: &mut S, length: &Self::ValueParameter) -> Self
2136 where
2137 S: rand_core::RngCore,
2138 {
2139 let mut output = vec![<Field128 as FieldElement>::zero(); *length];
2140 for element in output.iter_mut() {
2141 *element = <Field128 as IdpfValue>::generate(seed_stream, &());
2142 }
2143 MyVector(output)
2144 }
2145
2146 fn zero(length: &usize) -> Self {
2147 MyVector(vec![<Field128 as FieldElement>::zero(); *length])
2148 }
2149
2150 fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
2151 debug_assert_eq!(a.0.len(), b.0.len());
2152 let mut output = vec![<Field128 as FieldElement>::zero(); a.0.len()];
2153 for ((a_elem, b_elem), output_elem) in
2154 a.0.iter().zip(b.0.iter()).zip(output.iter_mut())
2155 {
2156 *output_elem = <Field128 as ConditionallySelectable>::conditional_select(
2157 a_elem, b_elem, choice,
2158 );
2159 }
2160 MyVector(output)
2161 }
2162 }
2163
2164 impl Encode for MyVector {
2165 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
2166 encode_u32_items(bytes, &(), &self.0)
2167 }
2168 }
2169
2170 impl Decode for MyVector {
2171 fn decode(bytes: &mut Cursor<&[u8]>) -> Result<Self, CodecError> {
2172 decode_u32_items(&(), bytes).map(MyVector)
2173 }
2174 }
2175
2176 impl ConditionallyNegatable for MyVector {
2177 fn conditional_negate(&mut self, choice: Choice) {
2178 for element in self.0.iter_mut() {
2179 element.conditional_negate(choice);
2180 }
2181 }
2182 }
2183
2184 impl Add for MyVector {
2185 type Output = Self;
2186
2187 fn add(self, rhs: Self) -> Self::Output {
2188 debug_assert_eq!(self.0.len(), rhs.0.len());
2189 let mut output = vec![<Field128 as FieldElement>::zero(); self.0.len()];
2190 for ((left_elem, right_elem), output_elem) in
2191 self.0.iter().zip(rhs.0.iter()).zip(output.iter_mut())
2192 {
2193 *output_elem = left_elem + right_elem;
2194 }
2195 MyVector(output)
2196 }
2197 }
2198
2199 impl AddAssign for MyVector {
2200 fn add_assign(&mut self, rhs: Self) {
2201 debug_assert_eq!(self.0.len(), rhs.0.len());
2202 for (self_elem, right_elem) in self.0.iter_mut().zip(rhs.0.iter()) {
2203 *self_elem += *right_elem;
2204 }
2205 }
2206 }
2207
2208 impl Sub for MyVector {
2209 type Output = Self;
2210
2211 fn sub(self, rhs: Self) -> Self::Output {
2212 debug_assert_eq!(self.0.len(), rhs.0.len());
2213 let mut output = vec![<Field128 as FieldElement>::zero(); self.0.len()];
2214 for ((left_elem, right_elem), output_elem) in
2215 self.0.iter().zip(rhs.0.iter()).zip(output.iter_mut())
2216 {
2217 *output_elem = left_elem - right_elem;
2218 }
2219 MyVector(output)
2220 }
2221 }
2222
2223 // Use a unit type for inner nodes, thus emulating a DPF. Use a newtype around a `Vec` for
2224 // the leaf nodes, to test out values that require runtime parameters.
2225 let idpf = Idpf::new((), 3);
2226 let binder = b"binder";
2227 let (public_share, [key_0, key_1]) = idpf
2228 .gen(
2229 &IdpfInput::from_bytes(b"ae"),
2230 [MyUnit; 15],
2231 MyVector(Vec::from([
2232 Field128::from(1),
2233 Field128::from(2),
2234 Field128::from(3),
2235 ])),
2236 binder,
2237 )
2238 .unwrap();
2239
2240 let zero_share_0 = idpf
2241 .eval(
2242 0,
2243 &public_share,
2244 &key_0,
2245 &IdpfInput::from_bytes(b"ou"),
2246 binder,
2247 &mut NoCache::new(),
2248 )
2249 .unwrap();
2250 let zero_share_1 = idpf
2251 .eval(
2252 1,
2253 &public_share,
2254 &key_1,
2255 &IdpfInput::from_bytes(b"ou"),
2256 binder,
2257 &mut NoCache::new(),
2258 )
2259 .unwrap();
2260 let zero_output = zero_share_0.merge(zero_share_1).unwrap();
2261 assert_matches!(zero_output, IdpfOutputShare::Leaf(value) => {
2262 assert_eq!(value.0.len(), 3);
2263 assert_eq!(value.0[0], <Field128 as FieldElement>::zero());
2264 assert_eq!(value.0[1], <Field128 as FieldElement>::zero());
2265 assert_eq!(value.0[2], <Field128 as FieldElement>::zero());
2266 });
2267
2268 let programmed_share_0 = idpf
2269 .eval(
2270 0,
2271 &public_share,
2272 &key_0,
2273 &IdpfInput::from_bytes(b"ae"),
2274 binder,
2275 &mut NoCache::new(),
2276 )
2277 .unwrap();
2278 let programmed_share_1 = idpf
2279 .eval(
2280 1,
2281 &public_share,
2282 &key_1,
2283 &IdpfInput::from_bytes(b"ae"),
2284 binder,
2285 &mut NoCache::new(),
2286 )
2287 .unwrap();
2288 let programmed_output = programmed_share_0.merge(programmed_share_1).unwrap();
2289 assert_matches!(programmed_output, IdpfOutputShare::Leaf(value) => {
2290 assert_eq!(value.0.len(), 3);
2291 assert_eq!(value.0[0], Field128::from(1));
2292 assert_eq!(value.0[1], Field128::from(2));
2293 assert_eq!(value.0[2], Field128::from(3));
2294 });
2295 }
2296 }