1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Copyright 2023 Jan Niklas Siemer
//
// This file is part of qFALL-math.
//
// qFALL-math is free software: you can redistribute it and/or modify it under
// the terms of the Mozilla Public License Version 2.0 as published by the
// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.
//! This module contains algorithms for sampling
//! according to the binomial distribution.
use crate::{
error::MathError,
integer::{PolyOverZ, Z},
integer_mod_q::{ModulusPolynomialRingZq, PolynomialRingZq},
macros::seeded::seedable_function,
rational::Q,
};
impl PolynomialRingZq {
seedable_function!(
/// Generates a [`PolynomialRingZq`] instance of maximum degree `modulus.get_degree() - 1` and
/// coefficients chosen according to the binomial distribution
/// parameterized by `n` and `p`.
///
/// Parameters:
/// - `modulus`: specifies the [`ModulusPolynomialRingZq`] over which the
/// ring of polynomials modulo `modulus.get_q()` is defined
/// - `n`: specifies the number of trials
/// - `p`: specifies the probability of success
#[seeded]
/// - `seed`: specifies the 256-bit seed of the PRNG used for sampling
#[optionally_seeded]
/// - `seed`: specifies an optional 256-bit seed of the PRNG used for sampling.
#[optionally_seeded]
/// If `None` is provided, a fresh [`ThreadRng`](rand::rngs::ThreadRng) is used instead.
///
/// Returns a fresh [`PolynomialRingZq`] instance of length `modulus.get_degree() - 1`
/// with coefficients chosen according to the binomial distribution or a [`MathError`]
/// if `n < 0`, `p ∉ (0,1)`, `n` does not fit into an [`i64`].
///
/// # Examples
/// ```
/// use qfall_math::integer_mod_q::{PolynomialRingZq, ModulusPolynomialRingZq};
/// use std::str::FromStr;
/// let modulus = ModulusPolynomialRingZq::from_str("3 1 2 1 mod 17").unwrap();
///
#[unseeded]
/// let sample = PolynomialRingZq::sample_binomial(&modulus, 2, 0.5).unwrap();
#[seeded]
/// let sample = PolynomialRingZq::sample_binomial_seeded(&modulus, 2, 0.5, [42; 32]).unwrap();
/// ```
///
/// # Errors and Failures
/// - Returns a [`MathError`] of type [`InvalidIntegerInput`](MathError::InvalidIntegerInput)
/// if `n < 0`.
/// - Returns a [`MathError`] of type [`InvalidInterval`](MathError::InvalidInterval)
/// if `p ∉ (0,1)`.
/// - Returns a [`MathError`] of type [`ConversionError`](MathError::ConversionError)
/// if `n` does not fit into an [`i64`].
///
/// # Panics ...
/// - if the provided [`ModulusPolynomialRingZq`] has degree `0` or smaller.
pub(crate) fn sample_binomial(
modulus: &ModulusPolynomialRingZq,
n: impl Into<Z>,
p: impl Into<Q>,
seed: Option<[u8; 32]>,
) -> Result<Self, MathError> {
Self::sample_binomial_with_offset_optionally_seeded(modulus, 0, n, p, seed)
}
);
seedable_function!(
/// Generates a [`PolynomialRingZq`] instance of maximum degree `modulus.get_degree() - 1` and
/// coefficients chosen according to the binomial distribution
/// parameterized by `n` and `p` with given `offset`.
///
/// Parameters:
/// - `modulus`: specifies the [`ModulusPolynomialRingZq`] over which the
/// ring of polynomials modulo `modulus.get_q()` is defined
/// - `offset`: specifies an offset applied to each sample
/// collected from the binomial distribution
/// - `n`: specifies the number of trials
/// - `p`: specifies the probability of success
#[seeded]
/// - `seed`: specifies the 256-bit seed of the PRNG used for sampling
#[optionally_seeded]
/// - `seed`: specifies an optional 256-bit seed of the PRNG used for sampling.
#[optionally_seeded]
/// If `None` is provided, a fresh [`ThreadRng`](rand::rngs::ThreadRng) is used instead.
///
/// Returns a fresh [`PolynomialRingZq`] instance of length `modulus.get_degree() - 1`
/// with coefficients chosen according to the binomial distribution or a [`MathError`]
/// if `n < 0`, `p ∉ (0,1)`, `n` does not fit into an [`i64`].
///
/// # Examples
/// ```
/// use qfall_math::integer_mod_q::{PolynomialRingZq, ModulusPolynomialRingZq};
/// use std::str::FromStr;
/// let modulus = ModulusPolynomialRingZq::from_str("3 1 2 1 mod 17").unwrap();
///
#[unseeded]
/// let sample = PolynomialRingZq::sample_binomial_with_offset(&modulus, -1, 2, 0.5).unwrap();
#[seeded]
/// let sample = PolynomialRingZq::sample_binomial_with_offset_seeded(&modulus, -1, 2, 0.5, [42; 32]).unwrap();
/// ```
///
/// # Errors and Failures
/// - Returns a [`MathError`] of type [`InvalidIntegerInput`](MathError::InvalidIntegerInput)
/// if `n < 0`.
/// - Returns a [`MathError`] of type [`InvalidInterval`](MathError::InvalidInterval)
/// if `p ∉ (0,1)`.
/// - Returns a [`MathError`] of type [`ConversionError`](MathError::ConversionError)
/// if `n` does not fit into an [`i64`].
///
/// # Panics ...
/// - if the provided [`ModulusPolynomialRingZq`] has degree `0` or smaller.
pub(crate) fn sample_binomial_with_offset(
modulus: &ModulusPolynomialRingZq,
offset: impl Into<Z>,
n: impl Into<Z>,
p: impl Into<Q>,
seed: Option<[u8; 32]>,
) -> Result<Self, MathError> {
assert!(
modulus.get_degree() > 0,
"ModulusPolynomial of degree 0 is insufficient to sample over."
);
let poly_z = PolyOverZ::sample_binomial_with_offset_optionally_seeded(
modulus.get_degree() - 1,
offset,
n,
p,
seed,
)?;
Ok(PolynomialRingZq {
poly: poly_z,
modulus: modulus.clone(),
})
}
);
}
#[cfg(test)]
mod test_sample_binomial {
use super::{PolynomialRingZq, Z};
use crate::utils::sample::test_seed;
use crate::{
integer_mod_q::{ModulusPolynomialRingZq, PolyOverZq},
traits::{GetCoefficient, SetCoefficient},
};
use std::str::FromStr;
// As all major tests regarding an appropriate binomial distribution,
// whether the correct interval is kept, and if the errors are thrown correctly,
// are performed in the `utils` module, we omit these tests here.
/// Checks whether the boundaries of the interval are kept.
#[test]
fn boundaries_kept() {
for seeded in [false, true] {
let modulus = ModulusPolynomialRingZq::from_str("4 1 0 0 1 mod 17").unwrap();
for _ in 0..8 {
let poly = PolynomialRingZq::sample_binomial_optionally_seeded(
&modulus,
2,
0.5,
seeded.then(test_seed),
)
.unwrap();
let sample: Z = poly.get_coeff(0).unwrap();
assert!(Z::ZERO <= sample || sample <= 2);
}
}
}
/// Checks whether the number of coefficients is correct.
#[test]
fn nr_coeffs() {
for seeded in [false, true] {
let degrees = [1, 3, 7, 15, 32, 120];
for degree in degrees {
let mut modulus = PolyOverZq::from((1, u64::MAX));
modulus.set_coeff(degree, 1).unwrap();
let modulus = ModulusPolynomialRingZq::from(&modulus);
let res = PolynomialRingZq::sample_binomial_optionally_seeded(
&modulus,
256,
0.99999,
seeded.then(test_seed),
)
.unwrap();
assert_eq!(
modulus.get_degree(),
res.get_degree() + 1,
"This test can fail with probability close to 0."
);
}
}
}
/// Checks whether 0 modulus polynomial is insufficient.
#[test]
fn invalid_modulus() {
for seeded in [false, true] {
let result = std::panic::catch_unwind(|| {
let modulus = ModulusPolynomialRingZq::from_str("1 1 mod 17").unwrap();
let _ = PolynomialRingZq::sample_binomial_optionally_seeded(
&modulus,
2,
0.5,
seeded.then(test_seed),
);
});
assert!(result.is_err());
}
}
/// Checks whether the same seed results in the same sample.
#[test]
fn same_seed_same_sample() {
use crate::integer_mod_q::{ModulusPolynomialRingZq, PolynomialRingZq};
use std::str::FromStr;
let modulus = ModulusPolynomialRingZq::from_str("3 1 2 1 mod 17").unwrap();
let sample_0 =
PolynomialRingZq::sample_binomial_seeded(&modulus, 2, 0.5, [42; 32]).unwrap();
let sample_1 =
PolynomialRingZq::sample_binomial_seeded(&modulus, 2, 0.5, [42; 32]).unwrap();
assert_eq!(sample_0, sample_1);
}
/// Checks whether the seeded variant outputs the known sample for a fixed seed.
#[test]
fn known_answer() {
use crate::integer_mod_q::{ModulusPolynomialRingZq, PolynomialRingZq};
use std::str::FromStr;
let modulus = ModulusPolynomialRingZq::from_str("3 1 2 1 mod 17").unwrap();
let sample = PolynomialRingZq::sample_binomial_seeded(&modulus, 2, 0.5, [42; 32]).unwrap();
assert_eq!("2 0 2 / 3 1 2 1 mod 17", sample.to_string());
}
/// Checks whether the unseeded and the seeded function are available.
#[test]
fn availability() {
use crate::integer_mod_q::{ModulusPolynomialRingZq, PolynomialRingZq};
use std::str::FromStr;
let modulus = ModulusPolynomialRingZq::from_str("3 1 2 1 mod 17").unwrap();
// explicitly checks the existence of the unseeded and the seeded function
let _ = PolynomialRingZq::sample_binomial(&modulus, 2, 0.5);
let _ = PolynomialRingZq::sample_binomial_seeded(&modulus, 2, 0.5, test_seed());
}
}
#[cfg(test)]
mod test_sample_binomial_with_offset {
use super::{PolynomialRingZq, Z};
use crate::utils::sample::test_seed;
use crate::{
integer_mod_q::{ModulusPolynomialRingZq, PolyOverZq},
traits::{GetCoefficient, SetCoefficient},
};
use std::str::FromStr;
// As all major tests regarding an appropriate binomial distribution,
// whether the correct interval is kept, and if the errors are thrown correctly,
// are performed in the `utils` module, we omit these tests here.
/// Checks whether the boundaries of the interval are kept.
#[test]
fn boundaries_kept() {
for seeded in [false, true] {
let modulus = ModulusPolynomialRingZq::from_str("4 1 0 0 1 mod 17").unwrap();
for _ in 0..8 {
let poly = PolynomialRingZq::sample_binomial_with_offset_optionally_seeded(
&modulus,
-1,
2,
0.5,
seeded.then(test_seed),
)
.unwrap();
let sample: Z = poly.get_coeff(0).unwrap();
assert!(Z::MINUS_ONE <= sample || sample <= Z::ONE);
}
}
}
/// Checks whether the number of coefficients is correct.
#[test]
fn nr_coeffs() {
for seeded in [false, true] {
let degrees = [1, 3, 7, 15, 32, 120];
for degree in degrees {
let mut modulus = PolyOverZq::from((1, u64::MAX));
modulus.set_coeff(degree, 1).unwrap();
let modulus = ModulusPolynomialRingZq::from(&modulus);
let res = PolynomialRingZq::sample_binomial_with_offset_optionally_seeded(
&modulus,
1,
2,
0.5,
seeded.then(test_seed),
)
.unwrap();
assert_eq!(modulus.get_degree(), res.get_degree() + 1);
}
}
}
/// Checks whether 0 modulus polynomial is insufficient.
#[test]
fn invalid_modulus() {
for seeded in [false, true] {
let result = std::panic::catch_unwind(|| {
let modulus = ModulusPolynomialRingZq::from_str("1 1 mod 17").unwrap();
let _ = PolynomialRingZq::sample_binomial_with_offset_optionally_seeded(
&modulus,
-1,
2,
0.5,
seeded.then(test_seed),
);
});
assert!(result.is_err());
}
}
/// Checks whether the same seed results in the same sample.
#[test]
fn same_seed_same_sample() {
use crate::integer_mod_q::{ModulusPolynomialRingZq, PolynomialRingZq};
use std::str::FromStr;
let modulus = ModulusPolynomialRingZq::from_str("3 1 2 1 mod 17").unwrap();
let sample_0 =
PolynomialRingZq::sample_binomial_with_offset_seeded(&modulus, -1, 2, 0.5, [42; 32])
.unwrap();
let sample_1 =
PolynomialRingZq::sample_binomial_with_offset_seeded(&modulus, -1, 2, 0.5, [42; 32])
.unwrap();
assert_eq!(sample_0, sample_1);
}
/// Checks whether the seeded variant outputs the known sample for a fixed seed.
#[test]
fn known_answer() {
use crate::integer_mod_q::{ModulusPolynomialRingZq, PolynomialRingZq};
use std::str::FromStr;
let modulus = ModulusPolynomialRingZq::from_str("3 1 2 1 mod 17").unwrap();
let sample =
PolynomialRingZq::sample_binomial_with_offset_seeded(&modulus, -1, 2, 0.5, [42; 32])
.unwrap();
assert_eq!("2 -1 1 / 3 1 2 1 mod 17", sample.to_string());
}
/// Checks whether the unseeded and the seeded function are available.
#[test]
fn availability() {
use crate::integer_mod_q::{ModulusPolynomialRingZq, PolynomialRingZq};
use std::str::FromStr;
let modulus = ModulusPolynomialRingZq::from_str("3 1 2 1 mod 17").unwrap();
// explicitly checks the existence of the unseeded and the seeded function
let _ = PolynomialRingZq::sample_binomial_with_offset(&modulus, -1, 2, 0.5);
let _ =
PolynomialRingZq::sample_binomial_with_offset_seeded(&modulus, -1, 2, 0.5, test_seed());
}
}