Debian Codegraph @

third_party/rust/prio/tests/discrete_gauss.rs

raw
1 // SPDX-License-Identifier: MPL-2.0
2
3 use num_bigint::{BigInt, BigUint};
4 use num_rational::Ratio;
5 use num_traits::FromPrimitive;
6 use prio::dp::distributions::DiscreteGaussian;
7 use prio::vdaf::xof::SeedStreamTurboShake128;
8 use rand::distributions::Distribution;
9 use rand::SeedableRng;
10 use serde::Deserialize;
11
12 /// A test vector of discrete Gaussian samples, produced by the python reference
13 /// implementation for [[CKS20]]. The script used to generate the test vector can
14 /// be found in this gist:
15 /// https://gist.github.com/divergentdave/94cab188e84a4764db6cdd1288e6ead3
16 /// The python reference implementation is here:
17 /// https://github.com/IBM/discrete-gaussian-differential-privacy
18 ///
19 /// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf
20 #[derive(Debug, Eq, PartialEq, Deserialize)]
21 pub struct DiscreteGaussTestVector {
22 #[serde(with = "hex")]
23 seed: [u8; 16],
24 std_num: u128,
25 std_denom: u128,
26 samples: Vec<i128>,
27 }
28
29 #[test]
30 fn discrete_gauss_reference() {
31 let test_vectors: Vec<DiscreteGaussTestVector> = vec![
32 serde_json::from_str(include_str!("test_vectors/discrete_gauss_3.json")).unwrap(),
33 serde_json::from_str(include_str!("test_vectors/discrete_gauss_9.json")).unwrap(),
34 serde_json::from_str(include_str!("test_vectors/discrete_gauss_100.json")).unwrap(),
35 serde_json::from_str(include_str!("test_vectors/discrete_gauss_41293847.json")).unwrap(),
36 serde_json::from_str(include_str!(
37 "test_vectors/discrete_gauss_9999999999999999999999.json"
38 ))
39 .unwrap(),
40 serde_json::from_str(include_str!("test_vectors/discrete_gauss_2.342.json")).unwrap(),
41 ];
42
43 for test_vector in test_vectors {
44 let sampler = DiscreteGaussian::new(Ratio::<BigUint>::new(
45 test_vector.std_num.into(),
46 test_vector.std_denom.into(),
47 ))
48 .unwrap();
49
50 // check samples are consistent
51 let mut rng = SeedStreamTurboShake128::from_seed(test_vector.seed);
52 let samples: Vec<BigInt> = (0..test_vector.samples.len())
53 .map(|_| sampler.sample(&mut rng))
54 .collect();
55
56 assert_eq!(
57 samples,
58 test_vector
59 .samples
60 .iter()
61 .map(|&s| BigInt::from_i128(s).unwrap())
62 .collect::<Vec::<BigInt>>()
63 );
64 }
65 }