Skip to main content

ml_dsa/
sampling.rs

1use crate::{
2    algebra::{BaseField, Elem, Int, NttMatrix, NttPolynomial, NttVector, Polynomial, Vector},
3    crypto::{G, H},
4    param::{Eta, MaskSamplingSize},
5};
6use ctutils::{CtLt, CtSelect};
7use hybrid_array::Array;
8use module_lattice::{ArraySize, Field, Truncate};
9#[cfg(feature = "zeroize")]
10use zeroize::Zeroize;
11
12// Algorithm 13 BytesToBits
13fn bit_set(z: &[u8], i: usize) -> bool {
14    let bit_index = i & 0x07;
15    let byte_index = i >> 3;
16    z[byte_index] & (1 << bit_index) != 0
17}
18
19// Algorithm 14 CoeffFromThreeBytes
20fn coeff_from_three_bytes(b: [u8; 3]) -> Option<Elem> {
21    let b0: Int = b[0].into();
22    let b1: Int = b[1].into();
23    let b2: Int = b[2].into();
24
25    let b2p = if b2 > 127 { b2 - 128 } else { b2 };
26
27    let z = (b2p << 16) + (b1 << 8) + b0;
28    (z < BaseField::Q).then_some(Elem::new(z))
29}
30
31// Algorithm 15 CoeffFromHalfByte
32fn coeff_from_half_byte(b: u8, eta: Eta) -> Option<Elem> {
33    match eta {
34        Eta::Two if b < 15 => {
35            let b = Int::from(b);
36            let sub = Int::ct_select(&10, &Int::ct_select(&5, &0, b.ct_lt(&5)), b.ct_lt(&10));
37            Some(Elem::new(2) - Elem::new(b - sub))
38        }
39        Eta::Four if b < 9 => Some(Elem::new(4) - Elem::new(b.into())),
40        _ => None,
41    }
42}
43
44fn coeffs_from_byte(z: u8, eta: Eta) -> (Option<Elem>, Option<Elem>) {
45    (
46        coeff_from_half_byte(z & 0x0F, eta),
47        coeff_from_half_byte(z >> 4, eta),
48    )
49}
50
51// Algorithm 29 SampleInBall
52pub(crate) fn sample_in_ball(rho: &[u8], tau: usize) -> Polynomial {
53    const ONE: Elem = Elem::new(1);
54    const MINUS_ONE: Elem = Elem::new(BaseField::Q - 1);
55
56    let mut c = Polynomial::default();
57    let mut ctx = H::default().absorb(rho);
58
59    let mut s = [0u8; 8];
60    ctx.squeeze(&mut s);
61
62    // h = bytes_to_bits(s)
63    let mut j = [0u8];
64    for i in (256 - tau)..256 {
65        ctx.squeeze(&mut j);
66        while usize::from(j[0]) > i {
67            ctx.squeeze(&mut j);
68        }
69
70        let j = usize::from(j[0]);
71        c.0[i] = c.0[j];
72        c.0[j] = if bit_set(&s, i + tau - 256) {
73            MINUS_ONE
74        } else {
75            ONE
76        };
77    }
78
79    c
80}
81
82// Algorithm 30 RejNTTPoly
83fn rej_ntt_poly(rho: &[u8], r: u8, s: u8) -> NttPolynomial {
84    let mut j = 0;
85    let mut ctx = G::default().absorb(rho).absorb(&[s]).absorb(&[r]);
86    let mut a = NttPolynomial::default();
87
88    // Squeeze 840 bytes (5 SHAKE128 blocks) in a single call rather than 3 bytes
89    // at a time.  The rejection probability is ~0.098%, so 280 candidates are
90    // almost always sufficient while requiring the same 5 Keccak-f permutations.
91    let mut buf = [0u8; 840];
92    ctx.squeeze(&mut buf);
93
94    for chunk in buf.chunks_exact(3) {
95        if let Some(x) = coeff_from_three_bytes([chunk[0], chunk[1], chunk[2]]) {
96            a.0[j] = x;
97            j += 1;
98            if j == 256 {
99                break;
100            }
101        }
102    }
103
104    // Fallback: astronomically unlikely (~10^-44), but required for correctness.
105    let mut tmp = [0u8; 3];
106    while j < 256 {
107        ctx.squeeze(&mut tmp);
108        if let Some(x) = coeff_from_three_bytes(tmp) {
109            a.0[j] = x;
110            j += 1;
111        }
112    }
113    #[cfg(feature = "zeroize")]
114    {
115        buf.zeroize();
116        tmp.zeroize();
117    }
118    a
119}
120
121// Algorithm 31 RejBoundedPoly
122fn rej_bounded_poly(rho: &[u8], eta: Eta, r: u16) -> Polynomial {
123    let mut j = 0;
124    let mut ctx = H::default().absorb(rho).absorb(&r.to_le_bytes());
125    let mut a = Polynomial::default();
126
127    // The reference implementation uses 136 bytes (1 SHAKE256 block) for eta=2 and 272 bytes (2 blocks) for eta=4.
128    let mut buf = [0u8; 272];
129    ctx.squeeze(&mut buf);
130
131    for &byte in &buf {
132        let (z0, z1) = coeffs_from_byte(byte, eta);
133        if let Some(x) = z0 {
134            a.0[j] = x;
135            j += 1;
136            if j == 256 {
137                break;
138            }
139        }
140        if let Some(x) = z1 {
141            a.0[j] = x;
142            j += 1;
143            if j == 256 {
144                break;
145            }
146        }
147    }
148
149    // Fallback: astronomically unlikely, but required for correctness.
150    let mut tmp = [0u8; 1];
151    while j < 256 {
152        ctx.squeeze(&mut tmp);
153        let (z0, z1) = coeffs_from_byte(tmp[0], eta);
154        if let Some(x) = z0 {
155            a.0[j] = x;
156            j += 1;
157        }
158        if j < 256 {
159            if let Some(x) = z1 {
160                a.0[j] = x;
161                j += 1;
162            }
163        }
164    }
165    #[cfg(feature = "zeroize")]
166    {
167        buf.zeroize();
168        tmp.zeroize();
169    }
170    a
171}
172
173// Algorithm 32 ExpandA
174pub(crate) fn expand_a<K: ArraySize, L: ArraySize>(rho: &[u8]) -> NttMatrix<K, L> {
175    NttMatrix::from_fn(|r| {
176        NttVector::new(Array::from_fn(|s| {
177            rej_ntt_poly(rho, Truncate::truncate(r), Truncate::truncate(s))
178        }))
179    })
180}
181
182// Algorithm 33 ExpandS
183//
184// We only do half of the algorithm here, because it's inconvenient to return two vectors of
185// different sizes.  So the caller has to call twice:
186//
187//    let s1 = Vector::<K>::expand_s(rho, 0);
188//    let s2 = Vector::<L>::expand_s(rho, L::USIZE);
189pub(crate) fn expand_s<K: ArraySize>(rho: &[u8], eta: Eta, base: usize) -> Vector<K> {
190    Vector::new(Array::from_fn(|r| {
191        let r = Truncate::truncate(r + base);
192        rej_bounded_poly(rho, eta, r)
193    }))
194}
195
196// Algorithm 34 ExpandMask
197pub(crate) fn expand_mask<K, Gamma1>(rho: &[u8], mu: u16) -> Vector<K>
198where
199    K: ArraySize,
200    Gamma1: MaskSamplingSize,
201{
202    Vector::new(Array::from_fn(|r| {
203        let r: u16 = Truncate::truncate(r);
204        let v = expand_mask_xof::<Gamma1>(rho, mu + r);
205
206        Gamma1::unpack(&v)
207    }))
208}
209
210/// Expand one mask polynomial's seed before decoding it into coefficients.
211#[inline]
212pub(crate) fn expand_mask_xof<Gamma1: MaskSamplingSize>(
213    rho: &[u8],
214    nonce: u16,
215) -> Array<u8, Gamma1::SampleSize> {
216    H::default()
217        .absorb(rho)
218        .absorb(&nonce.to_le_bytes())
219        .squeeze_new::<Gamma1::SampleSize>()
220}
221
222#[cfg(test)]
223#[allow(clippy::as_conversions)]
224#[allow(clippy::cast_possible_truncation)]
225mod test {
226    use super::*;
227    use hybrid_array::typenum::{U16, U256};
228
229    fn max_abs_1(p: &Polynomial) -> bool {
230        p.0.iter()
231            .all(|x| x.0 == 0 || x.0 == 1 || x.0 == BaseField::Q - 1)
232    }
233
234    fn hamming_weight(p: &Polynomial) -> usize {
235        p.0.iter().filter(|x| x.0 != 0).count()
236    }
237
238    // Verify that SampleInBall returns a polynomial with the following properties:
239    //   a. All coefficients are from {-1, 0, 1}
240    //   b. Hamming weight is exactly tau
241    //
242    // We test 256 samples for each value of
243    #[test]
244    fn test_sample_in_ball() {
245        for tau in 1..65 {
246            for seed in 0_usize..255 {
247                let rho = ((tau as u16) << 8) + (seed as u16);
248                let p = sample_in_ball(&rho.to_be_bytes(), tau);
249                assert_eq!(hamming_weight(&p), tau);
250                assert!(max_abs_1(&p));
251            }
252        }
253    }
254
255    // Verify that RejNTTPoly produces samples that are in the proper range, and roughly uniform.
256    // For the "roughly uniform" criterion,
257    #[test]
258    fn test_rej_ntt_poly() {
259        let sample: Array<Array<Elem, U256>, U16> = Array::from_fn(|i| {
260            let i = i as u8;
261            let rho = [i; 32];
262            rej_ntt_poly(&rho, i, i + 1).0
263        });
264
265        let sample = sample.as_flattened();
266
267        let all_in_range = sample.iter().all(|x| x.0 < BaseField::Q);
268        assert!(all_in_range);
269
270        // TODO measure uniformity
271    }
272
273    #[test]
274    fn test_sample_cbd() {
275        let rho = [0; 32];
276
277        // Eta = 2
278        let sample = rej_bounded_poly(&rho, Eta::Two, 0).0;
279        let all_in_range = sample.iter().map(|x| *x + Elem::new(2)).all(|x| x.0 < 5);
280        assert!(all_in_range);
281        // TODO measure uniformity
282
283        // Eta = 4
284        let sample = rej_bounded_poly(&rho, Eta::Four, 0).0;
285        let all_in_range = sample.iter().map(|x| *x + Elem::new(4)).all(|x| x.0 < 9);
286        assert!(all_in_range);
287        // TODO measure uniformity
288    }
289}