Skip to main content

ml_kem/
algebra.rs

1use crate::{
2    B32,
3    crypto::{PRF, PrfOutput, XOF},
4    param::CbdSamplingSize,
5};
6use array::{Array, ArraySize, typenum::U256};
7use module_lattice::{Encode, Field, MultiplyNtt, Truncate};
8use sha3::digest::XofReader;
9
10module_lattice::define_field!(BaseField, u16, u32, u64, 3329);
11
12pub(crate) type Int = <BaseField as Field>::Int;
13
14/// An element of GF(q).
15pub(crate) type Elem = module_lattice::Elem<BaseField>;
16
17/// An element of the ring `R_q`, i.e., a polynomial over `Z_q` of degree 255
18pub(crate) type Polynomial = module_lattice::Polynomial<BaseField>;
19
20/// A vector of polynomials of length `K`.
21pub(crate) type Vector<K> = module_lattice::Vector<BaseField, K>;
22
23/// An element of the ring `T_q` i.e. a tuple of 128 elements of the direct sum components of `T_q`.
24pub(crate) type NttPolynomial = module_lattice::NttPolynomial<BaseField>;
25
26/// A vector of K NTT-domain polynomials.
27pub(crate) type NttVector<K> = module_lattice::NttVector<BaseField, K>;
28
29/// A K x K matrix of NTT-domain polynomials.  Each vector represents a row of the matrix, so that
30/// multiplying on the right just requires iteration.
31pub(crate) type NttMatrix<K> = module_lattice::NttMatrix<BaseField, K, K>;
32
33/// SHAKE128 rate in bytes. It is a multiple of 3, so every block holds whole 3-byte groups.
34const SHAKE128_BLOCK_SIZE: usize = 168;
35
36/// Algorithm 7: `SampleNTT(B)`
37///
38/// The XOF output is consumed in whole SHAKE128 blocks: three blocks yield 256 accepted
39/// coefficients except with small probability, after which blocks are squeezed one at a time.
40/// The XOF input is the public seed `rho`, so the data-dependent loop does not leak secrets.
41pub(crate) fn sample_ntt(B: &mut impl XofReader) -> NttPolynomial {
42    let mut coeffs = [Elem::new(0); 256];
43
44    let mut bytes = [0u8; 3 * SHAKE128_BLOCK_SIZE];
45    B.read(&mut bytes);
46    let mut n = rej_uniform(&mut coeffs, 0, &bytes);
47
48    while n < coeffs.len() {
49        let mut block = [0u8; SHAKE128_BLOCK_SIZE];
50        B.read(&mut block);
51        n = rej_uniform(&mut coeffs, n, &block);
52    }
53
54    NttPolynomial::new(coeffs.into())
55}
56
57/// Parse `bytes` into 12-bit candidates, append those below `q` to `coeffs[n..]`, and return the
58/// new number of coefficients (Algorithm 7, steps 3-15).
59fn rej_uniform(coeffs: &mut [Elem; 256], mut n: usize, bytes: &[u8]) -> usize {
60    for b in bytes.chunks_exact(3) {
61        if n == coeffs.len() {
62            break;
63        }
64
65        let d1 = Int::from(b[0]) + ((Int::from(b[1]) & 0xf) << 8);
66        let d2 = (Int::from(b[1]) >> 4) + (Int::from(b[2]) << 4);
67
68        if d1 < BaseField::Q {
69            coeffs[n] = Elem::new(d1);
70            n += 1;
71        }
72
73        if d2 < BaseField::Q && n < coeffs.len() {
74            coeffs[n] = Elem::new(d2);
75            n += 1;
76        }
77    }
78
79    n
80}
81
82pub(crate) fn matrix_sample_ntt<K: ArraySize>(rho: &B32, transpose: bool) -> NttMatrix<K> {
83    NttMatrix::new(Array::from_fn(|i| {
84        NttVector::new(Array::from_fn(|j| {
85            let (i, j) = if transpose { (j, i) } else { (i, j) };
86            let mut xof = XOF(rho, Truncate::truncate(j), Truncate::truncate(i));
87            sample_ntt(&mut xof)
88        }))
89    }))
90}
91
92/// Algorithm 8: `SamplePolyCBD_eta(B)`
93///
94/// To avoid all the bitwise manipulation in the algorithm as written, we reuse the logic in
95/// `ByteDecode`.  We decode the PRF output into integers with `2 * eta` bits, then use
96/// `count_ones` to perform the summation described in the algorithm.
97///
98/// The PRF output is secret, so each coefficient is computed arithmetically: no memory access
99/// or branch depends on the sampled bits (in particular, there is no lookup table).
100pub(crate) fn sample_poly_cbd<Eta>(B: &PrfOutput<Eta>) -> Polynomial
101where
102    Eta: CbdSamplingSize,
103{
104    let vals: Polynomial = Encode::<Eta::SampleSize>::decode(B);
105    Polynomial::new(
106        vals.0
107            .iter()
108            .map(|val| cbd_coefficient::<Eta>(val.0))
109            .collect(),
110    )
111}
112
113/// Map `2 * eta` sampled bits to a CBD coefficient: the number of ones in the low `eta` bits
114/// minus the number of ones in the high `eta` bits, reduced mod `q`.
115fn cbd_coefficient<Eta>(bits: Int) -> Elem
116where
117    Eta: CbdSamplingSize,
118{
119    let low_mask: Int = (1 << Eta::USIZE) - 1;
120    let x = <Int as Truncate<u32>>::truncate((bits & low_mask).count_ones());
121    let y = <Int as Truncate<u32>>::truncate((bits >> Eta::USIZE).count_ones());
122
123    // x, y <= eta, so `x + Q - y` is in `[Q - eta, Q + eta]` and one conditional subtraction
124    // fully reduces it.
125    Elem::new(BaseField::small_reduce(x + BaseField::Q - y))
126}
127
128pub(crate) fn sample_poly_vec_cbd<Eta, K>(sigma: &B32, start_n: u8) -> Vector<K>
129where
130    Eta: CbdSamplingSize,
131    K: ArraySize,
132{
133    Vector::new(Array::from_fn(|i| {
134        let i: u8 = Truncate::truncate(i);
135        let N = start_n + i;
136        let prf_output = PRF::<Eta>(sigma, N);
137        sample_poly_cbd::<Eta>(&prf_output)
138    }))
139}
140
141/// The Number Theoretic Transform (NTT) is a variant of the Discrete Fourier Transform (DFT)
142/// defined over a finite field that turns costly polynomial multiplications into simple
143/// coefficient-wise multiplications modulo a fixed prime.
144pub(crate) trait Ntt {
145    type Output;
146    fn ntt(&self) -> Self::Output;
147}
148
149/// One layer of the forward NTT butterfly.
150///
151/// `LEN` is the butterfly half-length and `ITERATIONS = 128 / LEN` is the number of
152/// butterfly groups in the layer. Making both compile-time constants lets the compiler
153/// eliminate the iterator length calculation (`256 / (2 * LEN)`) that `step_by` would
154/// otherwise compute with a `UDIV` instruction.
155#[inline(always)]
156fn ntt_layer<const LEN: usize, const ITERATIONS: usize>(f: &mut Array<Elem, U256>, k: &mut usize) {
157    for i in 0..ITERATIONS {
158        let start = i * 2 * LEN;
159        let zeta = ZETA_POW_BITREV[*k];
160        *k += 1;
161
162        for j in start..(start + LEN) {
163            let t = zeta * f[j + LEN];
164            f[j + LEN] = f[j] - t;
165            f[j] = f[j] + t;
166        }
167    }
168}
169
170/// Algorithm 9: `NTT`
171impl Ntt for Polynomial {
172    type Output = NttPolynomial;
173
174    fn ntt(&self) -> NttPolynomial {
175        let mut k = 1;
176        let mut f = self.0;
177
178        ntt_layer::<128, 1>(&mut f, &mut k);
179        ntt_layer::<64, 2>(&mut f, &mut k);
180        ntt_layer::<32, 4>(&mut f, &mut k);
181        ntt_layer::<16, 8>(&mut f, &mut k);
182        ntt_layer::<8, 16>(&mut f, &mut k);
183        ntt_layer::<4, 32>(&mut f, &mut k);
184        ntt_layer::<2, 64>(&mut f, &mut k);
185
186        f.into()
187    }
188}
189
190impl<K: ArraySize> Ntt for Vector<K> {
191    type Output = NttVector<K>;
192
193    fn ntt(&self) -> NttVector<K> {
194        NttVector::new(self.0.iter().map(Ntt::ntt).collect())
195    }
196}
197
198/// The inverse NTT is the reverse of the Number Theoretic Transform, converting coefficient-wise
199/// products back into standard polynomial form while preserving correctness modulo the same prime.
200#[allow(clippy::module_name_repetitions)]
201pub(crate) trait NttInverse {
202    type Output;
203    fn ntt_inverse(&self) -> Self::Output;
204}
205
206/// One layer of the inverse NTT butterfly.
207///
208/// See [`ntt_layer`] for the rationale behind the const generics.
209#[inline(always)]
210fn ntt_inverse_layer<const LEN: usize, const ITERATIONS: usize>(
211    f: &mut Array<Elem, U256>,
212    k: &mut usize,
213) {
214    for i in 0..ITERATIONS {
215        let start = i * 2 * LEN;
216        let zeta = ZETA_POW_BITREV[*k];
217        *k -= 1;
218
219        for j in start..(start + LEN) {
220            let t = f[j];
221            f[j] = t + f[j + LEN];
222            f[j + LEN] = zeta * (f[j + LEN] - t);
223        }
224    }
225}
226
227/// Algorithm 10: `NTT^{-1}`
228impl NttInverse for NttPolynomial {
229    type Output = Polynomial;
230
231    fn ntt_inverse(&self) -> Polynomial {
232        let mut f: Array<Elem, U256> = self.0.clone();
233        let mut k = 127;
234
235        ntt_inverse_layer::<2, 64>(&mut f, &mut k);
236        ntt_inverse_layer::<4, 32>(&mut f, &mut k);
237        ntt_inverse_layer::<8, 16>(&mut f, &mut k);
238        ntt_inverse_layer::<16, 8>(&mut f, &mut k);
239        ntt_inverse_layer::<32, 4>(&mut f, &mut k);
240        ntt_inverse_layer::<64, 2>(&mut f, &mut k);
241        ntt_inverse_layer::<128, 1>(&mut f, &mut k);
242
243        Elem::new(3303) * &Polynomial::new(f)
244    }
245}
246
247impl<K: ArraySize> NttInverse for NttVector<K> {
248    type Output = Vector<K>;
249
250    fn ntt_inverse(&self) -> Vector<K> {
251        Vector::new(self.0.iter().map(NttInverse::ntt_inverse).collect())
252    }
253}
254
255/// Algorithm 11: `MultiplyNTTs`
256impl MultiplyNtt for BaseField {
257    fn multiply_ntt(lhs: &NttPolynomial, rhs: &NttPolynomial) -> NttPolynomial {
258        let mut out = NttPolynomial::new(Array::default());
259
260        for i in 0..128 {
261            let (c0, c1) = base_case_multiply(
262                lhs.0[2 * i],
263                lhs.0[2 * i + 1],
264                rhs.0[2 * i],
265                rhs.0[2 * i + 1],
266                i,
267            );
268
269            out.0[2 * i] = c0;
270            out.0[2 * i + 1] = c1;
271        }
272
273        out
274    }
275}
276
277/// Algorithm 12: `BaseCaseMultiply`
278///
279/// This is a hot loop.  We promote to u64 so that we can do the absolute minimum number of
280/// modular reductions, since these are the expensive operation.
281#[inline]
282fn base_case_multiply(a0: Elem, a1: Elem, b0: Elem, b1: Elem, i: usize) -> (Elem, Elem) {
283    let a0 = u32::from(a0.0);
284    let a1 = u32::from(a1.0);
285    let b0 = u32::from(b0.0);
286    let b1 = u32::from(b1.0);
287    let g = u32::from(GAMMA[i].0);
288
289    let b1g = u32::from(BaseField::barrett_reduce(b1 * g));
290
291    let c0 = BaseField::barrett_reduce(a0 * b0 + a1 * b1g);
292    let c1 = BaseField::barrett_reduce(a0 * b1 + a1 * b0);
293    (Elem::new(c0), Elem::new(c1))
294}
295
296/// Since the powers of zeta used in the `NTT` and `MultiplyNTTs` are fixed, we use pre-computed
297/// tables to avoid the need to compute the exponentiations at runtime.
298///
299/// * `ZETA_POW_BITREV[i] = zeta^{BitRev_7(i)}`
300/// * `GAMMA[i] = zeta^{2 BitRev_7(i) + 1}`
301///
302/// Note that the const environment here imposes some annoying conditions.  Because operator
303/// overloading can't be const, we have to do all the reductions here manually.  Because `for` loops
304/// are forbidden in `const` functions, we do them manually with `while` loops.
305///
306/// The values computed here match those provided in Appendix A of FIPS 203.
307/// `ZETA_POW_BITREV` corresponds to the first table, and `GAMMA` to the second table.
308#[allow(clippy::integer_division_remainder_used, reason = "constant")]
309const ZETA_POW_BITREV: [Elem; 128] = {
310    const ZETA: u64 = 17;
311
312    const fn bitrev7(x: usize) -> usize {
313        ((x >> 6) % 2)
314            | (((x >> 5) % 2) << 1)
315            | (((x >> 4) % 2) << 2)
316            | (((x >> 3) % 2) << 3)
317            | (((x >> 2) % 2) << 4)
318            | (((x >> 1) % 2) << 5)
319            | ((x % 2) << 6)
320    }
321
322    // Compute the powers of zeta
323    let mut pow = [Elem::new(0); 128];
324    let mut i = 0;
325    let mut curr = 1u64;
326
327    while i < 128 {
328        pow[i] = Elem::new((curr & 0xFFFF) as u16);
329        i += 1;
330        curr = (curr * ZETA) % BaseField::QLL;
331    }
332
333    // Reorder the powers according to bitrev7
334    let mut pow_bitrev = [Elem::new(0); 128];
335    let mut i = 0;
336    while i < 128 {
337        pow_bitrev[i] = pow[bitrev7(i)];
338        i += 1;
339    }
340    pow_bitrev
341};
342
343#[allow(clippy::integer_division_remainder_used, reason = "constant")]
344const GAMMA: [Elem; 128] = {
345    const ZETA: u64 = 17;
346    let mut gamma = [Elem::new(0); 128];
347    let mut i = 0;
348    while i < 128 {
349        let zpr = ZETA_POW_BITREV[i].0 as u64;
350        let g = (zpr * zpr * ZETA) % BaseField::QLL;
351        gamma[i] = Elem::new((g & 0xFFFF) as u16);
352        i += 1;
353    }
354    gamma
355};
356
357#[cfg(test)]
358mod test {
359    use super::{
360        Array, B32, BaseField, Elem, Field, Int, Ntt, NttInverse, NttMatrix, NttPolynomial,
361        NttVector, PRF, Polynomial, U256, XOF,
362    };
363    use array::{
364        ArraySize, Flatten,
365        typenum::{U2, U3, U8},
366    };
367
368    /// A polynomial with only a scalar component, to make simple test cases
369    fn const_ntt(x: Int) -> NttPolynomial {
370        let mut p = Polynomial::default();
371        p.0[0] = Elem::new(x);
372        p.ntt()
373    }
374
375    /// Multiplication in `R_q`, modulo X^256 + 1
376    fn poly_mul(lhs: &Polynomial, rhs: &Polynomial) -> Polynomial {
377        let mut out = Polynomial::default();
378        for (i, x) in lhs.0.iter().enumerate() {
379            for (j, y) in rhs.0.iter().enumerate() {
380                let (sign, index) = if i + j < 256 {
381                    (Elem::new(1), i + j)
382                } else {
383                    (Elem::new(BaseField::Q - 1), i + j - 256)
384                };
385
386                out.0[index] = out.0[index] + (sign * *x * *y);
387            }
388        }
389        out
390    }
391
392    /// Transpose `NttMatrix`
393    fn matrix_transpose<K: ArraySize>(matrix: &NttMatrix<K>) -> NttMatrix<K> {
394        NttMatrix::new(Array::from_fn(|i| {
395            NttVector::new(Array::from_fn(|j| matrix.0[j].0[i].clone()))
396        }))
397    }
398
399    #[test]
400    #[allow(clippy::cast_possible_truncation)]
401    fn polynomial_ops() {
402        let f = Polynomial::new(Array::from_fn(|i| Elem::new(i as Int)));
403        let g = Polynomial::new(Array::from_fn(|i| Elem::new(2 * i as Int)));
404        let sum = Polynomial::new(Array::from_fn(|i| Elem::new(3 * i as Int)));
405        assert_eq!((&f + &g), sum);
406        assert_eq!((&sum - &g), f);
407        assert_eq!(Elem::new(3) * &f, sum);
408    }
409
410    #[test]
411    #[allow(clippy::cast_possible_truncation, clippy::similar_names)]
412    fn ntt() {
413        let f = Polynomial::new(Array::from_fn(|i| Elem::new(i as Int)));
414        let g = Polynomial::new(Array::from_fn(|i| Elem::new(2 * i as Int)));
415        let f_hat = f.ntt();
416        let g_hat = g.ntt();
417
418        // Verify that NTT and NTT^-1 are actually inverses
419        let f_unhat = f_hat.ntt_inverse();
420        assert_eq!(f, f_unhat);
421
422        // Verify that NTT is a homomorphism with regard to addition
423        let fg = &f + &g;
424        let f_hat_g_hat = &f_hat + &g_hat;
425        let fg_unhat = f_hat_g_hat.ntt_inverse();
426        assert_eq!(fg, fg_unhat);
427
428        // Verify that NTT is a homomorphism with regard to multiplication
429        let fg = poly_mul(&f, &g);
430        let f_hat_g_hat = &f_hat * &g_hat;
431        let fg_unhat = f_hat_g_hat.ntt_inverse();
432        assert_eq!(fg, fg_unhat);
433    }
434
435    #[test]
436    fn ntt_vector() {
437        // Verify vector addition
438        let v1: NttVector<U3> = NttVector::new(Array([const_ntt(1), const_ntt(1), const_ntt(1)]));
439        let v2: NttVector<U3> = NttVector::new(Array([const_ntt(2), const_ntt(2), const_ntt(2)]));
440        let v3: NttVector<U3> = NttVector::new(Array([const_ntt(3), const_ntt(3), const_ntt(3)]));
441        assert_eq!((&v1 + &v2), v3);
442
443        // Verify dot product
444        assert_eq!((&v1 * &v2), const_ntt(6));
445        assert_eq!((&v1 * &v3), const_ntt(9));
446        assert_eq!((&v2 * &v3), const_ntt(18));
447
448        // Verify inequality (catches PartialEq mutation that returns true unconditionally)
449        assert_ne!(v1, v2);
450        assert_ne!(v1, v3);
451        assert_ne!(v2, v3);
452    }
453
454    #[test]
455    fn ntt_matrix() {
456        // Verify matrix multiplication by a vector
457        let a: NttMatrix<U3> = NttMatrix::new(Array([
458            NttVector::new(Array([const_ntt(1), const_ntt(2), const_ntt(3)])),
459            NttVector::new(Array([const_ntt(4), const_ntt(5), const_ntt(6)])),
460            NttVector::new(Array([const_ntt(7), const_ntt(8), const_ntt(9)])),
461        ]));
462        let v_in: NttVector<U3> = NttVector::new(Array([const_ntt(1), const_ntt(2), const_ntt(3)]));
463        let v_out: NttVector<U3> =
464            NttVector::new(Array([const_ntt(14), const_ntt(32), const_ntt(50)]));
465        assert_eq!(&a * &v_in, v_out);
466
467        // Verify transpose
468        let aT = NttMatrix::new(Array([
469            NttVector::new(Array([const_ntt(1), const_ntt(4), const_ntt(7)])),
470            NttVector::new(Array([const_ntt(2), const_ntt(5), const_ntt(8)])),
471            NttVector::new(Array([const_ntt(3), const_ntt(6), const_ntt(9)])),
472        ]));
473        assert_eq!(matrix_transpose(&a), aT);
474    }
475
476    // To verify the accuracy of sampling, we use a theorem related to the law of large numbers,
477    // which bounds the convergence of the Kullback-Liebler distance between the empirical
478    // distribution and the hypothesized distribution.
479    //
480    // Theorem (Cover & Thomas, 1991, Theorem 12.2.1): Let $X_1, \ldots, X_n$ be i.i.d. $~P(x)$.
481    // Then:
482    //
483    //   Pr{ D(P_{x^n} || P) > \epsilon } \leq 2^{ -n ( \epsilon - |X|^{ log(n+1) / n } ) }
484    //
485    // So if we test by computing D(P_{x^n} || P) and requiring the value to be below a threshold
486    // \epsilon, then an unbiased sampling should pass with overwhelming probability 1 - 2^{-k},
487    // for some k based on \epsilon, |X|, and n.
488    //
489    // If we take k = 256 and n = 256, then we can solve for the required threshold \epsilon:
490    //
491    //   \epsilon = 1 + |X|^{ 0.03125 }
492    //
493    // For the cases we're interested in here:
494    //
495    //   CBD(eta = 2) => |X| = 5   => epsilon ~= 2.0516
496    //   CBD(eta = 2) => |X| = 7   => epsilon ~= 2.0627
497    //   Uniform byte => |X| = 256 => epsilon ~= 2.1892
498    //
499    // Taking epsilon = 2.05 makes us conservative enough in all cases, without significantly
500    // increasing the probability of false negatives.
501    const KL_THRESHOLD: f64 = 2.05;
502
503    // The centered binomial distributions are calculated as:
504    //
505    //   bin_\eta(k) = (2\eta \choose k + \eta) 2^{-2\eta}
506    //
507    // for k in $-\eta, \ldots, \eta$.  The cases of interest here are \eta = 2, 3.
508    type Distribution = [f64; Q_SIZE];
509    const Q_SIZE: usize = BaseField::Q as usize;
510    static CBD2: Distribution = {
511        let mut dist = [0.0; Q_SIZE];
512        dist[Q_SIZE - 2] = 1.0 / 16.0;
513        dist[Q_SIZE - 1] = 4.0 / 16.0;
514        dist[0] = 6.0 / 16.0;
515        dist[1] = 4.0 / 16.0;
516        dist[2] = 1.0 / 16.0;
517        dist
518    };
519    static CBD3: Distribution = {
520        let mut dist = [0.0; Q_SIZE];
521        dist[Q_SIZE - 3] = 1.0 / 64.0;
522        dist[Q_SIZE - 2] = 6.0 / 64.0;
523        dist[Q_SIZE - 1] = 15.0 / 64.0;
524        dist[0] = 20.0 / 64.0;
525        dist[1] = 15.0 / 64.0;
526        dist[2] = 6.0 / 64.0;
527        dist[3] = 1.0 / 64.0;
528        dist
529    };
530    static UNIFORM: Distribution = [1.0 / (BaseField::Q as f64); Q_SIZE];
531
532    fn kl_divergence(p: &Distribution, q: &Distribution) -> f64 {
533        p.iter()
534            .zip(q.iter())
535            .map(|(p, q)| if *p == 0.0 { 0.0 } else { p * (p / q).log2() })
536            .sum()
537    }
538
539    #[allow(clippy::cast_precision_loss, clippy::large_stack_arrays)]
540    fn test_sample(sample: &[Elem], ref_dist: &Distribution) {
541        // Verify data and compute the empirical distribution
542        let mut sample_dist: Distribution = [0.0; Q_SIZE];
543        let bump: f64 = 1.0 / (sample.len() as f64);
544        for x in sample {
545            assert!(x.0 < BaseField::Q);
546            assert!(ref_dist[x.0 as usize] > 0.0);
547
548            sample_dist[x.0 as usize] += bump;
549        }
550
551        let d = kl_divergence(&sample_dist, ref_dist);
552        assert!(d < KL_THRESHOLD);
553    }
554
555    #[test]
556    #[allow(clippy::cast_possible_truncation)]
557    fn sample_uniform() {
558        // We require roughly Q/2 samples to verify the uniform distribution.  This is because for
559        // M < N, the uniform distribution over a subset of M elements has KL distance:
560        //
561        //   M sum(p * log(q / p)) = log(q / p) = log(N / M)
562        //
563        // Since Q ~= 2^11 and 256 == 2^8, we need 2^3 == 8 runs of 256 to get out of the bad
564        // regime and get a meaningful measurement.
565        let rho = B32::default();
566        let sample: Array<Array<Elem, U256>, U8> = Array::from_fn(|i| {
567            let mut xof = XOF(&rho, 0, i as u8);
568            super::sample_ntt(&mut xof).into()
569        });
570
571        test_sample(&sample.flatten(), &UNIFORM);
572    }
573
574    /// Algorithm 7 as written in FIPS 203: read the XOF three bytes at a time. Also returns the
575    /// number of XOF bytes consumed.
576    #[allow(
577        clippy::integer_division_remainder_used,
578        reason = "test oracle on public values"
579    )]
580    fn sample_ntt_reference(xof: &mut impl sha3::digest::XofReader) -> (NttPolynomial, usize) {
581        let mut a = Array::<Elem, U256>::default();
582        let mut j = 0;
583        let mut consumed = 0;
584        while j < 256 {
585            let mut c = [0u8; 3];
586            xof.read(&mut c);
587            consumed += 3;
588            let d1 = Int::from(c[0]) + 256 * (Int::from(c[1]) % 16);
589            let d2 = Int::from(c[1]) / 16 + 16 * Int::from(c[2]);
590            if d1 < BaseField::Q {
591                a[j] = Elem::new(d1);
592                j += 1;
593            }
594            if d2 < BaseField::Q && j < 256 {
595                a[j] = Elem::new(d2);
596                j += 1;
597            }
598        }
599        (NttPolynomial::new(a), consumed)
600    }
601
602    #[test]
603    fn sample_ntt_matches_reference() {
604        let mut needed_extra_blocks = 0;
605        for seed in 0..2000u16 {
606            let mut rho = B32::default();
607            rho[..2].copy_from_slice(&seed.to_le_bytes());
608
609            let (expected, consumed) = sample_ntt_reference(&mut XOF(&rho, 1, 2));
610            assert_eq!(super::sample_ntt(&mut XOF(&rho, 1, 2)), expected);
611
612            if consumed > 3 * super::SHAKE128_BLOCK_SIZE {
613                needed_extra_blocks += 1;
614            }
615        }
616
617        // Make sure the path that squeezes additional blocks was exercised.
618        assert!(needed_extra_blocks > 0);
619    }
620
621    #[test]
622    fn sample_poly_cbd() {
623        // Eta = 2
624        let sigma = B32::default();
625        let prf_output = PRF::<U2>(&sigma, 0);
626        let sample = super::sample_poly_cbd::<U2>(&prf_output).0;
627        test_sample(&sample, &CBD2);
628
629        // Eta = 3
630        let sigma = B32::default();
631        let prf_output = PRF::<U3>(&sigma, 0);
632        let sample = super::sample_poly_cbd::<U3>(&prf_output).0;
633        test_sample(&sample, &CBD3);
634    }
635
636    /// Check `cbd_coefficient` against Algorithm 8 (`x - y mod q`, where `x` and `y` are the sums
637    /// of the first and last `eta` bits) for every possible input.
638    #[test]
639    #[allow(
640        clippy::integer_division_remainder_used,
641        reason = "test oracle on public values"
642    )]
643    fn cbd_coefficient_matches_definition() {
644        fn check<Eta: crate::param::CbdSamplingSize>() {
645            let eta = Eta::U32;
646            for bits in 0..(1u16 << (2 * eta)) {
647                let x: u16 = (0..eta).map(|i| (bits >> i) & 1).sum();
648                let y: u16 = (eta..2 * eta).map(|i| (bits >> i) & 1).sum();
649                let expected = (x + BaseField::Q - y) % BaseField::Q;
650                assert_eq!(super::cbd_coefficient::<Eta>(bits), Elem::new(expected));
651            }
652        }
653
654        check::<U2>();
655        check::<U3>();
656    }
657}