Debian Codegraph @

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

raw
1 // SPDX-License-Identifier: MPL-2.0
2
3 //! Tools for evaluating Prio3 test vectors.
4
5 use crate::{
6 codec::{Encode, ParameterizedDecode},
7 flp::Type,
8 vdaf::{
9 prio3::{Prio3, Prio3InputShare, Prio3PrepareShare, Prio3PublicShare},
10 xof::Xof,
11 Aggregator, Collector, OutputShare, PrepareTransition, Vdaf,
12 },
13 };
14 use serde::{Deserialize, Serialize};
15 use std::{collections::HashMap, convert::TryInto, fmt::Debug};
16
17 #[derive(Debug, Deserialize, Serialize)]
18 struct TEncoded(#[serde(with = "hex")] Vec<u8>);
19
20 impl AsRef<[u8]> for TEncoded {
21 fn as_ref(&self) -> &[u8] {
22 &self.0
23 }
24 }
25
26 #[derive(Deserialize, Serialize)]
27 struct TPrio3Prep<M> {
28 measurement: M,
29 #[serde(with = "hex")]
30 nonce: Vec<u8>,
31 #[serde(with = "hex")]
32 rand: Vec<u8>,
33 public_share: TEncoded,
34 input_shares: Vec<TEncoded>,
35 prep_shares: Vec<Vec<TEncoded>>,
36 prep_messages: Vec<TEncoded>,
37 out_shares: Vec<Vec<TEncoded>>,
38 }
39
40 #[derive(Deserialize, Serialize)]
41 struct TPrio3<M> {
42 verify_key: TEncoded,
43 shares: u8,
44 prep: Vec<TPrio3Prep<M>>,
45 agg_shares: Vec<TEncoded>,
46 agg_result: serde_json::Value,
47 #[serde(flatten)]
48 other_params: HashMap<String, serde_json::Value>,
49 }
50
51 macro_rules! err {
52 (
53 $test_num:ident,
54 $error:expr,
55 $msg:expr
56 ) => {
57 panic!("test #{} failed: {} err: {}", $test_num, $msg, $error)
58 };
59 }
60
61 // TODO Generalize this method to work with any VDAF. To do so we would need to add
62 // `shard_with_random()` to traits. (There may be a less invasive alternative.)
63 fn check_prep_test_vec<MS, MP, T, P, const SEED_SIZE: usize>(
64 prio3: &Prio3<T, P, SEED_SIZE>,
65 verify_key: &[u8; SEED_SIZE],
66 test_num: usize,
67 t: &TPrio3Prep<MS>,
68 ) -> Vec<OutputShare<T::Field>>
69 where
70 MS: Clone,
71 MP: From<MS>,
72 T: Type<Measurement = MP>,
73 P: Xof<SEED_SIZE>,
74 {
75 let nonce = <[u8; 16]>::try_from(t.nonce.clone()).unwrap();
76 let (public_share, input_shares) = prio3
77 .shard_with_random(&t.measurement.clone().into(), &nonce, &t.rand)
78 .expect("failed to generate input shares");
79
80 assert_eq!(
81 public_share,
82 Prio3PublicShare::get_decoded_with_param(prio3, t.public_share.as_ref())
83 .unwrap_or_else(|e| err!(test_num, e, "decode test vector (public share)")),
84 );
85 for (agg_id, want) in t.input_shares.iter().enumerate() {
86 assert_eq!(
87 input_shares[agg_id],
88 Prio3InputShare::get_decoded_with_param(&(prio3, agg_id), want.as_ref())
89 .unwrap_or_else(|e| err!(test_num, e, "decode test vector (input share)")),
90 "#{test_num}"
91 );
92 assert_eq!(
93 input_shares[agg_id].get_encoded().unwrap(),
94 want.as_ref(),
95 "#{test_num}"
96 )
97 }
98
99 let mut states = Vec::new();
100 let mut prep_shares = Vec::new();
101 for (agg_id, input_share) in input_shares.iter().enumerate() {
102 let (state, prep_share) = prio3
103 .prepare_init(verify_key, agg_id, &(), &nonce, &public_share, input_share)
104 .unwrap_or_else(|e| err!(test_num, e, "prep state init"));
105 states.push(state);
106 prep_shares.push(prep_share);
107 }
108
109 assert_eq!(1, t.prep_shares.len(), "#{test_num}");
110 for (i, want) in t.prep_shares[0].iter().enumerate() {
111 assert_eq!(
112 prep_shares[i],
113 Prio3PrepareShare::get_decoded_with_param(&states[i], want.as_ref())
114 .unwrap_or_else(|e| err!(test_num, e, "decode test vector (prep share)")),
115 "#{test_num}"
116 );
117 assert_eq!(
118 prep_shares[i].get_encoded().unwrap(),
119 want.as_ref(),
120 "#{test_num}"
121 );
122 }
123
124 let inbound = prio3
125 .prepare_shares_to_prepare_message(&(), prep_shares)
126 .unwrap_or_else(|e| err!(test_num, e, "prep preprocess"));
127 assert_eq!(t.prep_messages.len(), 1);
128 assert_eq!(inbound.get_encoded().unwrap(), t.prep_messages[0].as_ref());
129
130 let mut out_shares = Vec::new();
131 for state in states.iter_mut() {
132 match prio3.prepare_next(state.clone(), inbound.clone()).unwrap() {
133 PrepareTransition::Finish(out_share) => {
134 out_shares.push(out_share);
135 }
136 _ => panic!("unexpected transition"),
137 }
138 }
139
140 for (got, want) in out_shares.iter().zip(t.out_shares.iter()) {
141 let got: Vec<Vec<u8>> = got
142 .as_ref()
143 .iter()
144 .map(|x| x.get_encoded().unwrap())
145 .collect();
146 assert_eq!(got.len(), want.len());
147 for (got_elem, want_elem) in got.iter().zip(want.iter()) {
148 assert_eq!(got_elem.as_slice(), want_elem.as_ref());
149 }
150 }
151
152 out_shares
153 }
154
155 #[must_use]
156 fn check_aggregate_test_vec<MS, MP, T, P, const SEED_SIZE: usize>(
157 prio3: &Prio3<T, P, SEED_SIZE>,
158 t: &TPrio3<MS>,
159 ) -> T::AggregateResult
160 where
161 MS: Clone,
162 MP: From<MS>,
163 T: Type<Measurement = MP>,
164 P: Xof<SEED_SIZE>,
165 {
166 let verify_key = t.verify_key.as_ref().try_into().unwrap();
167
168 let mut all_output_shares = vec![Vec::new(); prio3.num_aggregators()];
169 for (test_num, p) in t.prep.iter().enumerate() {
170 let output_shares = check_prep_test_vec(prio3, verify_key, test_num, p);
171 for (aggregator_output_shares, output_share) in
172 all_output_shares.iter_mut().zip(output_shares.into_iter())
173 {
174 aggregator_output_shares.push(output_share);
175 }
176 }
177
178 let aggregate_shares = all_output_shares
179 .into_iter()
180 .map(|aggregator_output_shares| prio3.aggregate(&(), aggregator_output_shares).unwrap())
181 .collect::<Vec<_>>();
182
183 for (got, want) in aggregate_shares.iter().zip(t.agg_shares.iter()) {
184 let got = got.get_encoded().unwrap();
185 assert_eq!(got.as_slice(), want.as_ref());
186 }
187
188 prio3.unshard(&(), aggregate_shares, 1).unwrap()
189 }
190
191 /// Evaluate a Prio3 test vector. The instance of Prio3 is constructed from the `new_vdaf` callback,
192 /// which takes in the VDAF parameters encoded by the test vectors and the number of shares.
193 ///
194 /// This version allows customizing the deserialization of measurements, via an additional type
195 /// parameter.
196 #[cfg(feature = "test-util")]
197 #[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
198 pub fn check_test_vec_custom_de<MS, MP, A, T, P, const SEED_SIZE: usize>(
199 test_vec_json_str: &str,
200 new_vdaf: impl Fn(&HashMap<String, serde_json::Value>, u8) -> Prio3<T, P, SEED_SIZE>,
201 ) where
202 MS: for<'de> Deserialize<'de> + Clone,
203 MP: From<MS>,
204 A: for<'de> Deserialize<'de> + Debug + Eq,
205 T: Type<Measurement = MP, AggregateResult = A>,
206 P: Xof<SEED_SIZE>,
207 {
208 let t: TPrio3<MS> = serde_json::from_str(test_vec_json_str).unwrap();
209 let vdaf = new_vdaf(&t.other_params, t.shares);
210 let agg_result = check_aggregate_test_vec(&vdaf, &t);
211 assert_eq!(agg_result, serde_json::from_value(t.agg_result).unwrap());
212 }
213
214 /// Evaluate a Prio3 test vector. The instance of Prio3 is constructed from the `new_vdaf` callback,
215 /// which takes in the VDAF parameters encoded by the test vectors and the number of shares.
216 #[cfg(feature = "test-util")]
217 #[cfg_attr(docsrs, doc(cfg(feature = "test-util")))]
218 pub fn check_test_vec<M, A, T, P, const SEED_SIZE: usize>(
219 test_vec_json_str: &str,
220 new_vdaf: impl Fn(&HashMap<String, serde_json::Value>, u8) -> Prio3<T, P, SEED_SIZE>,
221 ) where
222 M: for<'de> Deserialize<'de> + Clone,
223 A: for<'de> Deserialize<'de> + Debug + Eq,
224 T: Type<Measurement = M, AggregateResult = A>,
225 P: Xof<SEED_SIZE>,
226 {
227 check_test_vec_custom_de::<M, M, _, _, _, SEED_SIZE>(test_vec_json_str, new_vdaf)
228 }
229
230 #[derive(Debug, Clone, Deserialize)]
231 #[serde(transparent)]
232 struct Prio3CountMeasurement(u8);
233
234 impl From<Prio3CountMeasurement> for bool {
235 fn from(value: Prio3CountMeasurement) -> Self {
236 value.0 != 0
237 }
238 }
239
240 #[test]
241 fn test_vec_prio3_count() {
242 for test_vector_str in [
243 include_str!("test_vec/08/Prio3Count_0.json"),
244 include_str!("test_vec/08/Prio3Count_1.json"),
245 ] {
246 check_test_vec_custom_de::<Prio3CountMeasurement, _, _, _, _, 16>(
247 test_vector_str,
248 |_json_params, num_shares| Prio3::new_count(num_shares).unwrap(),
249 );
250 }
251 }
252
253 #[test]
254 fn test_vec_prio3_sum() {
255 for test_vector_str in [
256 include_str!("test_vec/08/Prio3Sum_0.json"),
257 include_str!("test_vec/08/Prio3Sum_1.json"),
258 ] {
259 check_test_vec(test_vector_str, |json_params, num_shares| {
260 let bits = json_params["bits"].as_u64().unwrap() as usize;
261 Prio3::new_sum(num_shares, bits).unwrap()
262 });
263 }
264 }
265
266 #[test]
267 fn test_vec_prio3_sum_vec() {
268 for test_vector_str in [
269 include_str!("test_vec/08/Prio3SumVec_0.json"),
270 include_str!("test_vec/08/Prio3SumVec_1.json"),
271 ] {
272 check_test_vec(test_vector_str, |json_params, num_shares| {
273 let bits = json_params["bits"].as_u64().unwrap() as usize;
274 let length = json_params["length"].as_u64().unwrap() as usize;
275 let chunk_length = json_params["chunk_length"].as_u64().unwrap() as usize;
276 Prio3::new_sum_vec(num_shares, bits, length, chunk_length).unwrap()
277 });
278 }
279 }
280
281 #[test]
282 fn test_vec_prio3_histogram() {
283 for test_vector_str in [
284 include_str!("test_vec/08/Prio3Histogram_0.json"),
285 include_str!("test_vec/08/Prio3Histogram_1.json"),
286 ] {
287 check_test_vec(test_vector_str, |json_params, num_shares| {
288 let length = json_params["length"].as_u64().unwrap() as usize;
289 let chunk_length = json_params["chunk_length"].as_u64().unwrap() as usize;
290 Prio3::new_histogram(num_shares, length, chunk_length).unwrap()
291 });
292 }
293 }