Skip to main content

ml_dsa/
algebra.rs

1use core::ops::Mul;
2use ctutils::{CtEq, CtGt, CtLt, CtSelect};
3use hybrid_array::{
4    Array, ArraySize,
5    typenum::{Shleft, U1, U13, Unsigned},
6};
7use module_lattice::{Field, MaybeBox, Truncate};
8
9module_lattice::define_field!(BaseField, u32, u64, u128, 8_380_417);
10
11pub(crate) type Int = <BaseField as Field>::Int;
12
13pub(crate) type Elem = module_lattice::Elem<BaseField>;
14pub(crate) type Polynomial = module_lattice::Polynomial<BaseField>;
15pub(crate) type Vector<K> = module_lattice::Vector<BaseField, K>;
16pub(crate) type NttPolynomial = module_lattice::NttPolynomial<BaseField>;
17pub(crate) type NttVector<K> = module_lattice::NttVector<BaseField, K>;
18
19/// Private matrix storage which offloads each row before constructing the next one.
20/// Without `alloc`, `MaybeBox` keeps the rows inline.
21#[derive(Clone, Debug, PartialEq)]
22pub(crate) struct NttMatrix<K: ArraySize, L: ArraySize>(Array<MaybeBox<NttVector<L>>, K>);
23
24impl<K: ArraySize, L: ArraySize> NttMatrix<K, L> {
25    pub(crate) fn from_fn(mut f: impl FnMut(usize) -> NttVector<L>) -> Self {
26        Self(Array::from_fn(|i| MaybeBox::new(f(i))))
27    }
28}
29
30impl<K: ArraySize, L: ArraySize> Mul<&NttVector<L>> for &NttMatrix<K, L> {
31    type Output = NttVector<K>;
32
33    fn mul(self, rhs: &NttVector<L>) -> Self::Output {
34        NttVector::new(self.0.iter().map(|row| &**row * rhs).collect())
35    }
36}
37
38// We require modular reduction for three moduli: q, 2^d, and 2 * gamma2.  All three of these are
39// greater than sqrt(q), which means that a number reduced mod q will always be less than M^2,
40// which means that barrett reduction will work.
41pub(crate) trait BarrettReduce: Unsigned {
42    const SHIFT: usize;
43    const MULTIPLIER: u64;
44
45    fn reduce(x: u32) -> u32 {
46        let m = Self::U64;
47        let x: u64 = x.into();
48        let quotient = (x * Self::MULTIPLIER) >> Self::SHIFT;
49        let remainder = x - quotient * m;
50
51        let r_small: u32 = Truncate::truncate(remainder);
52        let r_large: u32 = Truncate::truncate(remainder.wrapping_sub(m));
53        u32::ct_select(&r_large, &r_small, remainder.ct_lt(&m))
54    }
55}
56
57impl<M> BarrettReduce for M
58where
59    M: Unsigned,
60{
61    #[allow(clippy::as_conversions)]
62    const SHIFT: usize = 2 * (M::U64.ilog2() + 1) as usize;
63    #[allow(clippy::integer_division_remainder_used, reason = "constant")]
64    const MULTIPLIER: u64 = (1 << Self::SHIFT) / M::U64;
65}
66
67pub(crate) trait Decompose {
68    fn decompose<TwoGamma2: Unsigned>(self) -> (Elem, Elem);
69}
70
71/// Constant-time division by a compile-time constant divisor.
72///
73/// This trait provides a constant-time alternative to the hardware division
74/// instruction, which has variable timing based on operand values.
75/// Uses Barrett reduction to compute `x / M` where M is a compile-time constant.
76pub(crate) trait ConstantTimeDiv: Unsigned {
77    /// Bit shift for Barrett reduction, chosen to provide sufficient precision
78    const CT_DIV_SHIFT: usize;
79    /// Precomputed multiplier: ceil(2^SHIFT / M)
80    const CT_DIV_MULTIPLIER: u64;
81
82    /// Perform constant-time division of x by `Self::U32`
83    /// Requires: x < Q (the field modulus, ~2^23)
84    #[allow(clippy::inline_always)] // Required for constant-time guarantees in crypto code
85    #[inline(always)]
86    fn ct_div(x: u32) -> u32 {
87        // Barrett reduction: q = (x * MULTIPLIER) >> SHIFT
88        // This gives us floor(x / M) for x < Q
89        let x64 = u64::from(x);
90        let quotient = (x64 * Self::CT_DIV_MULTIPLIER) >> Self::CT_DIV_SHIFT;
91        // Quotient is guaranteed to fit in u32 because:
92        // - x < Q (~2^23), so quotient = x / M < x < 2^23 < 2^32
93        #[allow(clippy::cast_possible_truncation, clippy::as_conversions)]
94        let result = quotient as u32;
95        result
96    }
97}
98
99impl<M> ConstantTimeDiv for M
100where
101    M: Unsigned,
102{
103    // Use a shift that provides enough precision for the ML-DSA field (Q ~ 2^23)
104    // We need SHIFT > log2(Q) + log2(M) to ensure accuracy
105    // With Q < 2^24 and M < 2^20, SHIFT = 48 is sufficient
106    const CT_DIV_SHIFT: usize = 48;
107
108    // Precompute the multiplier at compile time
109    // We add (M-1) before dividing to get ceiling division, ensuring we never underestimate
110    #[allow(clippy::integer_division_remainder_used, reason = "constant")]
111    const CT_DIV_MULTIPLIER: u64 = (1u64 << Self::CT_DIV_SHIFT).div_ceil(M::U64);
112}
113
114impl Decompose for Elem {
115    // Algorithm 36 Decompose
116    //
117    // This implementation uses constant-time division to avoid timing side-channels.
118    // The original algorithm used hardware division which has variable timing based
119    // on operand values, potentially leaking secret information during signing.
120    fn decompose<TwoGamma2: Unsigned>(self) -> (Elem, Elem) {
121        let r_plus = self.clone();
122        let r0 = r_plus.mod_plus_minus::<TwoGamma2>();
123
124        let diff = r_plus - r0;
125        let is_edge = diff.0.ct_eq(&(BaseField::Q - 1));
126
127        // Compute both branches unconditionally
128        let edge = (Elem::new(0), r0 - Elem::new(1));
129        let r1 = Elem::new(TwoGamma2::ct_div(diff.0));
130        let normal = (r1, r0);
131
132        let r1_out = Elem::new(u32::ct_select(&normal.0.0, &edge.0.0, is_edge));
133        let r0_out = Elem::new(u32::ct_select(&normal.1.0, &edge.1.0, is_edge));
134        (r1_out, r0_out)
135    }
136}
137
138#[allow(clippy::module_name_repetitions)] // I can't think of a better name
139pub(crate) trait AlgebraExt: Sized {
140    fn mod_plus_minus<M: Unsigned>(&self) -> Self;
141    fn infinity_norm(&self) -> Int;
142    fn power2round(&self) -> (Self, Self);
143    fn high_bits<TwoGamma2: Unsigned>(&self) -> Self;
144    fn low_bits<TwoGamma2: Unsigned>(&self) -> Self;
145}
146
147impl AlgebraExt for Elem {
148    fn mod_plus_minus<M: Unsigned>(&self) -> Self {
149        let raw_mod = Elem::new(M::reduce(self.0));
150        let in_lower_half = !raw_mod.0.ct_gt(&(M::U32 >> 1));
151        Elem::new(u32::ct_select(
152            &(raw_mod - Elem::new(M::U32)).0,
153            &raw_mod.0,
154            in_lower_half,
155        ))
156    }
157
158    // FIPS 204 defines the infinity norm differently for signed vs. unsigned integers:
159    //
160    // * For w in Z, |w|_\infinity = |w|, the absolute value of w
161    // * For w in Z_q, |W|_infinity = |w mod^\pm q|
162    //
163    // Note that these two definitions are equivalent if |w| < q/2.  This property holds for all of
164    // the signed integers used in this crate, so we can safely use the unsigned version.  However,
165    // since mod_plus_minus is also unsigned, we need to unwrap the "negative" values.
166    fn infinity_norm(&self) -> u32 {
167        let in_lower_half = !self.0.ct_gt(&(BaseField::Q >> 1));
168        u32::ct_select(&(BaseField::Q - self.0), &self.0, in_lower_half)
169    }
170
171    // Algorithm 35 Power2Round
172    //
173    // In the specification, this function maps to signed integers rather than modular integers.
174    // To avoid the need for a whole separate type for signed integer polynomials, we represent
175    // these values using integers mod Q.  This is safe because Q is much larger than 2^13, so
176    // there's no risk of overlap between positive numbers (x) and negative numbers (Q-x).
177    fn power2round(&self) -> (Self, Self) {
178        type D = U13;
179        type Pow2D = Shleft<U1, D>;
180
181        let r_plus = self.clone();
182        let r0 = r_plus.mod_plus_minus::<Pow2D>();
183        let r1 = Elem::new((r_plus - r0).0 >> D::USIZE);
184
185        (r1, r0)
186    }
187
188    // Algorithm 37 HighBits
189    fn high_bits<TwoGamma2: Unsigned>(&self) -> Self {
190        self.decompose::<TwoGamma2>().0
191    }
192
193    // Algorithm 38 LowBits
194    fn low_bits<TwoGamma2: Unsigned>(&self) -> Self {
195        self.decompose::<TwoGamma2>().1
196    }
197}
198
199impl AlgebraExt for Polynomial {
200    fn mod_plus_minus<M: Unsigned>(&self) -> Self {
201        Self(self.0.iter().map(AlgebraExt::mod_plus_minus::<M>).collect())
202    }
203
204    fn infinity_norm(&self) -> u32 {
205        self.0
206            .iter()
207            .map(AlgebraExt::infinity_norm)
208            .fold(0, |acc, x| u32::ct_select(&x, &acc, acc.ct_gt(&x)))
209    }
210
211    fn power2round(&self) -> (Self, Self) {
212        let mut r1 = Self::default();
213        let mut r0 = Self::default();
214
215        for (i, x) in self.0.iter().enumerate() {
216            (r1.0[i], r0.0[i]) = x.power2round();
217        }
218
219        (r1, r0)
220    }
221
222    fn high_bits<TwoGamma2: Unsigned>(&self) -> Self {
223        Self(
224            self.0
225                .iter()
226                .map(AlgebraExt::high_bits::<TwoGamma2>)
227                .collect(),
228        )
229    }
230
231    fn low_bits<TwoGamma2: Unsigned>(&self) -> Self {
232        Self(
233            self.0
234                .iter()
235                .map(AlgebraExt::low_bits::<TwoGamma2>)
236                .collect(),
237        )
238    }
239}
240
241impl<K: ArraySize> AlgebraExt for Vector<K> {
242    fn mod_plus_minus<M: Unsigned>(&self) -> Self {
243        Self(self.0.iter().map(AlgebraExt::mod_plus_minus::<M>).collect())
244    }
245
246    fn infinity_norm(&self) -> u32 {
247        self.0
248            .iter()
249            .map(AlgebraExt::infinity_norm)
250            .fold(0, |acc, x| u32::ct_select(&x, &acc, acc.ct_gt(&x)))
251    }
252
253    fn power2round(&self) -> (Self, Self) {
254        let mut r1 = Self::default();
255        let mut r0 = Self::default();
256
257        for (i, x) in self.0.iter().enumerate() {
258            (r1.0[i], r0.0[i]) = x.power2round();
259        }
260
261        (r1, r0)
262    }
263
264    fn high_bits<TwoGamma2: Unsigned>(&self) -> Self {
265        Self(
266            self.0
267                .iter()
268                .map(AlgebraExt::high_bits::<TwoGamma2>)
269                .collect(),
270        )
271    }
272
273    fn low_bits<TwoGamma2: Unsigned>(&self) -> Self {
274        Self(
275            self.0
276                .iter()
277                .map(AlgebraExt::low_bits::<TwoGamma2>)
278                .collect(),
279        )
280    }
281}
282
283#[cfg(test)]
284#[allow(clippy::integer_division_remainder_used, reason = "tests")]
285mod test {
286    use super::*;
287
288    use crate::{MlDsa65, ParameterSet};
289
290    type Mod = <MlDsa65 as ParameterSet>::TwoGamma2;
291    const MOD: u32 = Mod::U32;
292    const MOD_ELEM: Elem = Elem::new(MOD);
293
294    #[test]
295    fn mod_plus_minus() {
296        for x in 0..MOD {
297            // BaseField::Q {
298            let x = Elem::new(x);
299            let x0 = x.mod_plus_minus::<Mod>();
300
301            // Outputs from mod+- should be in the half-open interval (-gamma2, gamma2]
302            let positive_bound = x0.0 <= MOD / 2;
303            let negative_bound = x0.0 > BaseField::Q - MOD / 2;
304            assert!(positive_bound || negative_bound);
305
306            // The output should be equivalent to the input, mod 2 * gamma2.  We add 2 * gamma2
307            // before comparing so that both values are "positive", avoiding interactions between
308            // the mod-Q and mod-M operations.
309            let xn = x + MOD_ELEM;
310            let x0n = x0 + MOD_ELEM;
311            assert_eq!(xn.0 % MOD, x0n.0 % MOD);
312        }
313    }
314
315    #[test]
316    fn decompose() {
317        for x in 0..MOD {
318            let x = Elem::new(x);
319            let (x1, x0) = x.decompose::<Mod>();
320
321            // The low-order output from decompose() is a mod+- output, optionally minus one.  So
322            // they should be in the closed interval [-gamma2, gamma2].
323            let positive_bound = x0.0 <= MOD / 2;
324            let negative_bound = x0.0 >= BaseField::Q - MOD / 2;
325            assert!(positive_bound || negative_bound);
326
327            // The low-order and high-order outputs should combine to form the input.
328            let xx = (MOD * x1.0 + x0.0) % BaseField::Q;
329            assert_eq!(xx, x.0);
330        }
331    }
332
333    #[test]
334    fn barrett_reduce_boundary() {
335        let m_minus_1 = Mod::U32 - 1;
336        assert_eq!(Mod::reduce(m_minus_1), m_minus_1);
337        assert_eq!(Mod::reduce(Mod::U32), 0);
338        assert_eq!(Mod::reduce(Mod::U32 + 1), 1);
339        assert_eq!(Mod::reduce(2 * Mod::U32 - 1), m_minus_1);
340        assert_eq!(Mod::reduce(2 * Mod::U32), 0);
341    }
342
343    #[test]
344    fn constant_time_div_accuracy() {
345        for x in 0..1000 {
346            assert_eq!(Mod::ct_div(x), x / Mod::U32);
347        }
348        for x in (BaseField::Q - 1000)..BaseField::Q {
349            assert_eq!(Mod::ct_div(x), x / Mod::U32);
350        }
351    }
352
353    #[test]
354    fn decompose_edge_case() {
355        let q_minus_1 = Elem::new(BaseField::Q - 1);
356        let (r1, r0) = q_minus_1.decompose::<Mod>();
357        let reconstructed = (MOD * r1.0 + r0.0) % BaseField::Q;
358        assert_eq!(reconstructed, q_minus_1.0);
359    }
360
361    #[test]
362    fn high_low_bits_consistency() {
363        for x in [0, 1, MOD / 2, MOD - 1, MOD, MOD + 1, BaseField::Q - 1] {
364            let elem = Elem::new(x);
365            let (decomp_high, decomp_low) = elem.decompose::<Mod>();
366            assert_eq!(elem.high_bits::<Mod>(), decomp_high);
367            assert_eq!(elem.low_bits::<Mod>(), decomp_low);
368        }
369    }
370}