Debian Codegraph @

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

raw
1 // SPDX-License-Identifier: MPL-2.0
2
3 //! Backwards-compatible port of the ENPA Prio system to a VDAF.
4
5 use crate::{
6 codec::{CodecError, Decode, Encode, ParameterizedDecode},
7 field::{
8 decode_fieldvec, FftFriendlyFieldElement, FieldElement, FieldElementWithInteger, FieldPrio2,
9 },
10 prng::Prng,
11 vdaf::{
12 prio2::{
13 client::{self as v2_client, proof_length},
14 server as v2_server,
15 },
16 xof::Seed,
17 Aggregatable, AggregateShare, Aggregator, Client, Collector, OutputShare,
18 PrepareTransition, Share, ShareDecodingParameter, Vdaf, VdafError,
19 },
20 };
21 use hmac::{Hmac, Mac};
22 use rand_core::RngCore;
23 use sha2::Sha256;
24 use std::{convert::TryFrom, io::Cursor};
25 use subtle::{Choice, ConstantTimeEq};
26
27 mod client;
28 mod server;
29 #[cfg(test)]
30 mod test_vector;
31
32 /// The Prio2 VDAF. It supports the same measurement type as
33 /// [`Prio3SumVec`](crate::vdaf::prio3::Prio3SumVec) with `bits == 1` but uses the proof system and
34 /// finite field deployed in ENPA.
35 #[derive(Clone, Debug)]
36 pub struct Prio2 {
37 input_len: usize,
38 }
39
40 impl Prio2 {
41 /// Returns an instance of the VDAF for the given input length.
42 pub fn new(input_len: usize) -> Result<Self, VdafError> {
43 let n = (input_len + 1).next_power_of_two();
44 if let Ok(size) = u32::try_from(2 * n) {
45 if size > FieldPrio2::generator_order() {
46 return Err(VdafError::Uncategorized(
47 "input size exceeds field capacity".into(),
48 ));
49 }
50 } else {
51 return Err(VdafError::Uncategorized(
52 "input size exceeds memory capacity".into(),
53 ));
54 }
55
56 Ok(Prio2 { input_len })
57 }
58
59 /// Prepare an input share for aggregation using the given field element `query_rand` to
60 /// compute the verifier share.
61 ///
62 /// In the [`Aggregator`] trait implementation for [`Prio2`], the query randomness is computed
63 /// jointly by the Aggregators. This method is designed to be used in applications, like ENPA,
64 /// in which the query randomness is instead chosen by a third-party.
65 pub fn prepare_init_with_query_rand(
66 &self,
67 query_rand: FieldPrio2,
68 input_share: &Share<FieldPrio2, 32>,
69 is_leader: bool,
70 ) -> Result<(Prio2PrepareState, Prio2PrepareShare), VdafError> {
71 let expanded_data: Option<Vec<FieldPrio2>> = match input_share {
72 Share::Leader(_) => None,
73 Share::Helper(ref seed) => {
74 let prng = Prng::from_prio2_seed(seed.as_ref());
75 Some(prng.take(proof_length(self.input_len)).collect())
76 }
77 };
78 let data = match input_share {
79 Share::Leader(ref data) => data,
80 Share::Helper(_) => expanded_data.as_ref().unwrap(),
81 };
82
83 let verifier_share = v2_server::generate_verification_message(
84 self.input_len,
85 query_rand,
86 data, // Combined input and proof shares
87 is_leader,
88 )
89 .map_err(|e| VdafError::Uncategorized(e.to_string()))?;
90
91 let truncated_share = match input_share {
92 Share::Leader(data) => Share::Leader(data[..self.input_len].to_vec()),
93 Share::Helper(seed) => Share::Helper(seed.clone()),
94 };
95
96 Ok((
97 Prio2PrepareState(truncated_share),
98 Prio2PrepareShare(verifier_share),
99 ))
100 }
101
102 /// Choose a random point for polynomial evaluation.
103 ///
104 /// The point returned is not one of the roots used for polynomial interpolation.
105 pub(crate) fn choose_eval_at<S>(&self, prng: &mut Prng<FieldPrio2, S>) -> FieldPrio2
106 where
107 S: RngCore,
108 {
109 // Make sure the query randomness isn't a root of unity. Evaluating the proof at any of
110 // these points would be a privacy violation, since these points were used by the prover to
111 // construct the wire polynomials.
112 let n = (self.input_len + 1).next_power_of_two();
113 let proof_length = 2 * n;
114 loop {
115 let eval_at: FieldPrio2 = prng.get();
116 // Unwrap safety: the constructor checks that this conversion succeeds.
117 if eval_at.pow(u32::try_from(proof_length).unwrap()) != FieldPrio2::one() {
118 return eval_at;
119 }
120 }
121 }
122 }
123
124 impl Vdaf for Prio2 {
125 type Measurement = Vec<u32>;
126 type AggregateResult = Vec<u32>;
127 type AggregationParam = ();
128 type PublicShare = ();
129 type InputShare = Share<FieldPrio2, 32>;
130 type OutputShare = OutputShare<FieldPrio2>;
131 type AggregateShare = AggregateShare<FieldPrio2>;
132
133 fn algorithm_id(&self) -> u32 {
134 0xFFFF0000
135 }
136
137 fn num_aggregators(&self) -> usize {
138 // Prio2 can easily be extended to support more than two Aggregators.
139 2
140 }
141 }
142
143 impl Client<16> for Prio2 {
144 fn shard(
145 &self,
146 measurement: &Vec<u32>,
147 _nonce: &[u8; 16],
148 ) -> Result<(Self::PublicShare, Vec<Share<FieldPrio2, 32>>), VdafError> {
149 if measurement.len() != self.input_len {
150 return Err(VdafError::Uncategorized("incorrect input length".into()));
151 }
152 let mut input: Vec<FieldPrio2> = Vec::with_capacity(measurement.len());
153 for int in measurement {
154 input.push((*int).into());
155 }
156
157 let mut mem = v2_client::ClientMemory::new(self.input_len)?;
158 let copy_data = |share_data: &mut [FieldPrio2]| {
159 share_data[..].clone_from_slice(&input);
160 };
161 let mut leader_data = mem.prove_with(self.input_len, copy_data);
162
163 let helper_seed = Seed::generate()?;
164 let helper_prng = Prng::from_prio2_seed(helper_seed.as_ref());
165 for (s1, d) in leader_data.iter_mut().zip(helper_prng.into_iter()) {
166 *s1 -= d;
167 }
168
169 Ok((
170 (),
171 vec![Share::Leader(leader_data), Share::Helper(helper_seed)],
172 ))
173 }
174 }
175
176 /// State of each [`Aggregator`] during the Preparation phase.
177 #[derive(Clone, Debug)]
178 pub struct Prio2PrepareState(Share<FieldPrio2, 32>);
179
180 impl PartialEq for Prio2PrepareState {
181 fn eq(&self, other: &Self) -> bool {
182 self.ct_eq(other).into()
183 }
184 }
185
186 impl Eq for Prio2PrepareState {}
187
188 impl ConstantTimeEq for Prio2PrepareState {
189 fn ct_eq(&self, other: &Self) -> Choice {
190 self.0.ct_eq(&other.0)
191 }
192 }
193
194 impl Encode for Prio2PrepareState {
195 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
196 self.0.encode(bytes)
197 }
198
199 fn encoded_len(&self) -> Option<usize> {
200 self.0.encoded_len()
201 }
202 }
203
204 impl<'a> ParameterizedDecode<(&'a Prio2, usize)> for Prio2PrepareState {
205 fn decode_with_param(
206 (prio2, agg_id): &(&'a Prio2, usize),
207 bytes: &mut Cursor<&[u8]>,
208 ) -> Result<Self, CodecError> {
209 let share_decoder = if *agg_id == 0 {
210 ShareDecodingParameter::Leader(prio2.input_len)
211 } else {
212 ShareDecodingParameter::Helper
213 };
214 let out_share = Share::decode_with_param(&share_decoder, bytes)?;
215 Ok(Self(out_share))
216 }
217 }
218
219 /// Message emitted by each [`Aggregator`] during the Preparation phase.
220 #[derive(Clone, Debug)]
221 pub struct Prio2PrepareShare(v2_server::VerificationMessage<FieldPrio2>);
222
223 impl Encode for Prio2PrepareShare {
224 fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
225 self.0.f_r.encode(bytes)?;
226 self.0.g_r.encode(bytes)?;
227 self.0.h_r.encode(bytes)
228 }
229
230 fn encoded_len(&self) -> Option<usize> {
231 Some(FieldPrio2::ENCODED_SIZE * 3)
232 }
233 }
234
235 impl ParameterizedDecode<Prio2PrepareState> for Prio2PrepareShare {
236 fn decode_with_param(
237 _state: &Prio2PrepareState,
238 bytes: &mut Cursor<&[u8]>,
239 ) -> Result<Self, CodecError> {
240 Ok(Self(v2_server::VerificationMessage {
241 f_r: FieldPrio2::decode(bytes)?,
242 g_r: FieldPrio2::decode(bytes)?,
243 h_r: FieldPrio2::decode(bytes)?,
244 }))
245 }
246 }
247
248 impl Aggregator<32, 16> for Prio2 {
249 type PrepareState = Prio2PrepareState;
250 type PrepareShare = Prio2PrepareShare;
251 type PrepareMessage = ();
252
253 fn prepare_init(
254 &self,
255 agg_key: &[u8; 32],
256 agg_id: usize,
257 _agg_param: &Self::AggregationParam,
258 nonce: &[u8; 16],
259 _public_share: &Self::PublicShare,
260 input_share: &Share<FieldPrio2, 32>,
261 ) -> Result<(Prio2PrepareState, Prio2PrepareShare), VdafError> {
262 let is_leader = role_try_from(agg_id)?;
263
264 // In the ENPA Prio system, the query randomness is generated by a third party and
265 // distributed to the Aggregators after they receive their input shares. In a VDAF, shared
266 // randomness is derived from a nonce selected by the client. For Prio2 we compute the
267 // query using HMAC-SHA256 evaluated over the nonce.
268 //
269 // Unwrap safety: new_from_slice() is infallible for Hmac.
270 let mut mac = Hmac::<Sha256>::new_from_slice(agg_key).unwrap();
271 mac.update(nonce);
272 let hmac_tag = mac.finalize();
273 let mut prng = Prng::from_prio2_seed(&hmac_tag.into_bytes().into());
274 let query_rand = self.choose_eval_at(&mut prng);
275
276 self.prepare_init_with_query_rand(query_rand, input_share, is_leader)
277 }
278
279 fn prepare_shares_to_prepare_message<M: IntoIterator<Item = Prio2PrepareShare>>(
280 &self,
281 _: &Self::AggregationParam,
282 inputs: M,
283 ) -> Result<(), VdafError> {
284 let verifier_shares: Vec<v2_server::VerificationMessage<FieldPrio2>> =
285 inputs.into_iter().map(|msg| msg.0).collect();
286 if verifier_shares.len() != 2 {
287 return Err(VdafError::Uncategorized(
288 "wrong number of verifier shares".into(),
289 ));
290 }
291
292 if !v2_server::is_valid_share(&verifier_shares[0], &verifier_shares[1]) {
293 return Err(VdafError::Uncategorized(
294 "proof verifier check failed".into(),
295 ));
296 }
297
298 Ok(())
299 }
300
301 fn prepare_next(
302 &self,
303 state: Prio2PrepareState,
304 _input: (),
305 ) -> Result<PrepareTransition<Self, 32, 16>, VdafError> {
306 let data = match state.0 {
307 Share::Leader(data) => data,
308 Share::Helper(seed) => {
309 let prng = Prng::from_prio2_seed(seed.as_ref());
310 prng.take(self.input_len).collect()
311 }
312 };
313 Ok(PrepareTransition::Finish(OutputShare::from(data)))
314 }
315
316 fn aggregate<M: IntoIterator<Item = OutputShare<FieldPrio2>>>(
317 &self,
318 _agg_param: &Self::AggregationParam,
319 out_shares: M,
320 ) -> Result<AggregateShare<FieldPrio2>, VdafError> {
321 let mut agg_share = AggregateShare(vec![FieldPrio2::zero(); self.input_len]);
322 for out_share in out_shares.into_iter() {
323 agg_share.accumulate(&out_share)?;
324 }
325
326 Ok(agg_share)
327 }
328 }
329
330 impl Collector for Prio2 {
331 fn unshard<M: IntoIterator<Item = AggregateShare<FieldPrio2>>>(
332 &self,
333 _agg_param: &Self::AggregationParam,
334 agg_shares: M,
335 _num_measurements: usize,
336 ) -> Result<Vec<u32>, VdafError> {
337 let mut agg = AggregateShare(vec![FieldPrio2::zero(); self.input_len]);
338 for agg_share in agg_shares.into_iter() {
339 agg.merge(&agg_share)?;
340 }
341
342 Ok(agg.0.into_iter().map(u32::from).collect())
343 }
344 }
345
346 impl<'a> ParameterizedDecode<(&'a Prio2, usize)> for Share<FieldPrio2, 32> {
347 fn decode_with_param(
348 (prio2, agg_id): &(&'a Prio2, usize),
349 bytes: &mut Cursor<&[u8]>,
350 ) -> Result<Self, CodecError> {
351 let is_leader = role_try_from(*agg_id).map_err(|e| CodecError::Other(Box::new(e)))?;
352 let decoder = if is_leader {
353 ShareDecodingParameter::Leader(proof_length(prio2.input_len))
354 } else {
355 ShareDecodingParameter::Helper
356 };
357
358 Share::decode_with_param(&decoder, bytes)
359 }
360 }
361
362 impl<'a, F> ParameterizedDecode<(&'a Prio2, &'a ())> for OutputShare<F>
363 where
364 F: FieldElement,
365 {
366 fn decode_with_param(
367 (prio2, _): &(&'a Prio2, &'a ()),
368 bytes: &mut Cursor<&[u8]>,
369 ) -> Result<Self, CodecError> {
370 decode_fieldvec(prio2.input_len, bytes).map(Self)
371 }
372 }
373
374 impl<'a, F> ParameterizedDecode<(&'a Prio2, &'a ())> for AggregateShare<F>
375 where
376 F: FieldElement,
377 {
378 fn decode_with_param(
379 (prio2, _): &(&'a Prio2, &'a ()),
380 bytes: &mut Cursor<&[u8]>,
381 ) -> Result<Self, CodecError> {
382 decode_fieldvec(prio2.input_len, bytes).map(Self)
383 }
384 }
385
386 fn role_try_from(agg_id: usize) -> Result<bool, VdafError> {
387 match agg_id {
388 0 => Ok(true),
389 1 => Ok(false),
390 _ => Err(VdafError::Uncategorized("unexpected aggregator id".into())),
391 }
392 }
393
394 #[cfg(test)]
395 mod tests {
396 use super::*;
397 use crate::vdaf::{
398 equality_comparison_test, fieldvec_roundtrip_test, prio2::test_vector::Priov2TestVector,
399 test_utils::run_vdaf,
400 };
401 use assert_matches::assert_matches;
402 use rand::prelude::*;
403
404 #[test]
405 fn run_prio2() {
406 let prio2 = Prio2::new(6).unwrap();
407
408 assert_eq!(
409 run_vdaf(
410 &prio2,
411 &(),
412 [
413 vec![0, 0, 0, 0, 1, 0],
414 vec![0, 1, 0, 0, 0, 0],
415 vec![0, 1, 1, 0, 0, 0],
416 vec![1, 1, 1, 0, 0, 0],
417 vec![0, 0, 0, 0, 1, 1],
418 ]
419 )
420 .unwrap(),
421 vec![1, 3, 2, 0, 2, 1],
422 );
423 }
424
425 #[test]
426 fn prepare_state_serialization() {
427 let mut rng = thread_rng();
428 let verify_key = rng.gen::<[u8; 32]>();
429 let nonce = rng.gen::<[u8; 16]>();
430 let data = vec![0, 0, 1, 1, 0];
431 let prio2 = Prio2::new(data.len()).unwrap();
432 let (public_share, input_shares) = prio2.shard(&data, &nonce).unwrap();
433 for (agg_id, input_share) in input_shares.iter().enumerate() {
434 let (prepare_state, prepare_share) = prio2
435 .prepare_init(
436 &verify_key,
437 agg_id,
438 &(),
439 &[0; 16],
440 &public_share,
441 input_share,
442 )
443 .unwrap();
444
445 let encoded_prepare_state = prepare_state.get_encoded().unwrap();
446 let decoded_prepare_state = Prio2PrepareState::get_decoded_with_param(
447 &(&prio2, agg_id),
448 &encoded_prepare_state,
449 )
450 .expect("failed to decode prepare state");
451 assert_eq!(decoded_prepare_state, prepare_state);
452 assert_eq!(
453 prepare_state.encoded_len().unwrap(),
454 encoded_prepare_state.len()
455 );
456
457 let encoded_prepare_share = prepare_share.get_encoded().unwrap();
458 let decoded_prepare_share =
459 Prio2PrepareShare::get_decoded_with_param(&prepare_state, &encoded_prepare_share)
460 .expect("failed to decode prepare share");
461 assert_eq!(decoded_prepare_share.0.f_r, prepare_share.0.f_r);
462 assert_eq!(decoded_prepare_share.0.g_r, prepare_share.0.g_r);
463 assert_eq!(decoded_prepare_share.0.h_r, prepare_share.0.h_r);
464 assert_eq!(
465 prepare_share.encoded_len().unwrap(),
466 encoded_prepare_share.len()
467 );
468 }
469 }
470
471 #[test]
472 fn roundtrip_output_share() {
473 let vdaf = Prio2::new(31).unwrap();
474 fieldvec_roundtrip_test::<FieldPrio2, Prio2, OutputShare<FieldPrio2>>(&vdaf, &(), 31);
475 }
476
477 #[test]
478 fn roundtrip_aggregate_share() {
479 let vdaf = Prio2::new(31).unwrap();
480 fieldvec_roundtrip_test::<FieldPrio2, Prio2, AggregateShare<FieldPrio2>>(&vdaf, &(), 31);
481 }
482
483 #[test]
484 fn priov2_backward_compatibility() {
485 let test_vector: Priov2TestVector =
486 serde_json::from_str(include_str!("test_vec/prio2/fieldpriov2.json")).unwrap();
487 let vdaf = Prio2::new(test_vector.dimension).unwrap();
488 let mut leader_output_shares = Vec::new();
489 let mut helper_output_shares = Vec::new();
490 for (server_1_share, server_2_share) in test_vector
491 .server_1_decrypted_shares
492 .iter()
493 .zip(&test_vector.server_2_decrypted_shares)
494 {
495 let input_share_1 = Share::get_decoded_with_param(&(&vdaf, 0), server_1_share).unwrap();
496 let input_share_2 = Share::get_decoded_with_param(&(&vdaf, 1), server_2_share).unwrap();
497 let (prepare_state_1, prepare_share_1) = vdaf
498 .prepare_init(&[0; 32], 0, &(), &[0; 16], &(), &input_share_1)
499 .unwrap();
500 let (prepare_state_2, prepare_share_2) = vdaf
501 .prepare_init(&[0; 32], 1, &(), &[0; 16], &(), &input_share_2)
502 .unwrap();
503 vdaf.prepare_shares_to_prepare_message(&(), [prepare_share_1, prepare_share_2])
504 .unwrap();
505 let transition_1 = vdaf.prepare_next(prepare_state_1, ()).unwrap();
506 let output_share_1 =
507 assert_matches!(transition_1, PrepareTransition::Finish(out) => out);
508 let transition_2 = vdaf.prepare_next(prepare_state_2, ()).unwrap();
509 let output_share_2 =
510 assert_matches!(transition_2, PrepareTransition::Finish(out) => out);
511 leader_output_shares.push(output_share_1);
512 helper_output_shares.push(output_share_2);
513 }
514
515 let leader_aggregate_share = vdaf.aggregate(&(), leader_output_shares).unwrap();
516 let helper_aggregate_share = vdaf.aggregate(&(), helper_output_shares).unwrap();
517 let aggregate_result = vdaf
518 .unshard(
519 &(),
520 [leader_aggregate_share, helper_aggregate_share],
521 test_vector.server_1_decrypted_shares.len(),
522 )
523 .unwrap();
524 let reconstructed = aggregate_result
525 .into_iter()
526 .map(FieldPrio2::from)
527 .collect::<Vec<_>>();
528
529 assert_eq!(reconstructed, test_vector.reference_sum);
530 }
531
532 #[test]
533 fn prepare_state_equality_test() {
534 equality_comparison_test(&[
535 Prio2PrepareState(Share::Leader(Vec::from([
536 FieldPrio2::from(0),
537 FieldPrio2::from(1),
538 ]))),
539 Prio2PrepareState(Share::Leader(Vec::from([
540 FieldPrio2::from(1),
541 FieldPrio2::from(0),
542 ]))),
543 Prio2PrepareState(Share::Helper(Seed(
544 (0..32).collect::<Vec<_>>().try_into().unwrap(),
545 ))),
546 Prio2PrepareState(Share::Helper(Seed(
547 (1..33).collect::<Vec<_>>().try_into().unwrap(),
548 ))),
549 ])
550 }
551 }