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#[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
38pub(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
71pub(crate) trait ConstantTimeDiv: Unsigned {
77 const CT_DIV_SHIFT: usize;
79 const CT_DIV_MULTIPLIER: u64;
81
82 #[allow(clippy::inline_always)] #[inline(always)]
86 fn ct_div(x: u32) -> u32 {
87 let x64 = u64::from(x);
90 let quotient = (x64 * Self::CT_DIV_MULTIPLIER) >> Self::CT_DIV_SHIFT;
91 #[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 const CT_DIV_SHIFT: usize = 48;
107
108 #[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 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 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)] pub(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 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 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 fn high_bits<TwoGamma2: Unsigned>(&self) -> Self {
190 self.decompose::<TwoGamma2>().0
191 }
192
193 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 let x = Elem::new(x);
299 let x0 = x.mod_plus_minus::<Mod>();
300
301 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 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 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 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}