Skip to main content

module_lattice/
algebra.rs

1use super::truncate::Truncate;
2
3use array::{Array, ArraySize, typenum::U256};
4use core::fmt::Debug;
5use core::ops::{Add, Mul, Neg, Sub};
6use num_traits::PrimInt;
7
8#[cfg(feature = "ctutils")]
9use ctutils::{Choice, CtEq, CtEqSlice};
10#[cfg(feature = "zeroize")]
11use zeroize::Zeroize;
12
13/// Finite field with efficient modular reduction for lattice-based cryptography.
14pub trait Field: Copy + Default + Debug + PartialEq {
15    /// Base integer type used to represent field elements
16    type Int: PrimInt + Default + Debug + From<u8> + Into<u128> + Into<Self::Long> + Truncate<u128>;
17    /// Double-width integer type used for intermediate computations.
18    type Long: PrimInt + From<Self::Int>;
19    /// Quadruple-width integer type used for Barrett reduction.
20    type LongLong: PrimInt;
21
22    /// Field modulus.
23    const Q: Self::Int;
24    /// Field modulus as [`Self::Long`].
25    const QL: Self::Long;
26    /// Field modulus as [`Self::LongLong`].
27    const QLL: Self::LongLong;
28
29    /// Bit shift used in Barrett reduction.
30    const BARRETT_SHIFT: usize;
31    /// Precomputed multiplier for Barrett reduction.
32    const BARRETT_MULTIPLIER: Self::LongLong;
33
34    /// Reduce a value that's already close to the modulus range.
35    fn small_reduce(x: Self::Int) -> Self::Int;
36    /// Reduce a wider value to a field element using Barrett reduction.
37    fn barrett_reduce(x: Self::Long) -> Self::Int;
38}
39
40/// The `define_field` macro creates a zero-sized struct and an implementation of the [`Field`]
41/// trait for that struct.  The caller must specify:
42///
43/// * `$field`: The name of the zero-sized struct to be created
44/// * `$q`: The prime number that defines the field.
45/// * `$int`: The primitive integer type to be used to represent members of the field
46/// * `$long`: The primitive integer type to be used to represent products of two field members.
47///   This type should have roughly twice the bits of `$int`.
48/// * `$longlong`: The primitive integer type to be used to represent products of three field
49///   members. This type should have roughly four times the bits of `$int`.
50#[macro_export]
51macro_rules! define_field {
52    ($field:ident, $int:ty, $long:ty, $longlong:ty, $q:literal) => {
53        $crate::define_field!($field, $int, $long, $longlong, $q, "Finite field");
54    };
55    ($field:ident, $int:ty, $long:ty, $longlong:ty, $q:literal, $doc:expr) => {
56        #[doc = $doc]
57        #[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
58        pub struct $field;
59
60        impl $crate::Field for $field {
61            type Int = $int;
62            type Long = $long;
63            type LongLong = $longlong;
64
65            const Q: Self::Int = $q;
66            const QL: Self::Long = $q;
67            const QLL: Self::LongLong = $q;
68
69            #[allow(clippy::as_conversions)]
70            const BARRETT_SHIFT: usize = 2 * (Self::Q.ilog2() + 1) as usize;
71            #[allow(clippy::integer_division_remainder_used)]
72            const BARRETT_MULTIPLIER: Self::LongLong = (1 << Self::BARRETT_SHIFT) / Self::QLL;
73
74            fn small_reduce(x: Self::Int) -> Self::Int {
75                if x < Self::Q { x } else { x - Self::Q }
76            }
77
78            fn barrett_reduce(x: Self::Long) -> Self::Int {
79                let x: Self::LongLong = x.into();
80                let product = x * Self::BARRETT_MULTIPLIER;
81                let quotient = product >> Self::BARRETT_SHIFT;
82                let remainder = x - quotient * Self::QLL;
83                Self::small_reduce($crate::Truncate::truncate(remainder))
84            }
85        }
86    };
87}
88
89/// An [`Elem`] is a member of the specified prime-order field.
90///
91/// Elements can be added, subtracted, multiplied, and negated, and the overloaded operators will
92/// ensure both that the integer values remain in the field, and that the reductions are done
93/// efficiently.
94///
95/// For addition and subtraction, a simple conditional subtraction is used; for multiplication,
96/// Barrett reduction.
97#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
98pub struct Elem<F: Field>(pub F::Int);
99
100impl<F: Field> Elem<F> {
101    /// Create a new field element.
102    pub const fn new(x: F::Int) -> Self {
103        Self(x)
104    }
105}
106
107#[cfg(feature = "ctutils")]
108impl<F: Field> CtEq for Elem<F>
109where
110    F::Int: CtEq,
111{
112    fn ct_eq(&self, other: &Self) -> Choice {
113        self.0.ct_eq(&other.0)
114    }
115}
116
117#[cfg(feature = "ctutils")]
118impl<F: Field<Int: CtEq>> CtEqSlice for Elem<F> {}
119
120#[cfg(feature = "zeroize")]
121impl<F: Field> Zeroize for Elem<F>
122where
123    F::Int: Zeroize,
124{
125    fn zeroize(&mut self) {
126        self.0.zeroize();
127    }
128}
129
130impl<F: Field> Neg for Elem<F> {
131    type Output = Elem<F>;
132
133    fn neg(self) -> Elem<F> {
134        Elem(F::small_reduce(F::Q - self.0))
135    }
136}
137
138impl<F: Field> Add<Elem<F>> for Elem<F> {
139    type Output = Elem<F>;
140
141    fn add(self, rhs: Elem<F>) -> Elem<F> {
142        Elem(F::small_reduce(self.0 + rhs.0))
143    }
144}
145
146impl<F: Field> Sub<Elem<F>> for Elem<F> {
147    type Output = Elem<F>;
148
149    fn sub(self, rhs: Elem<F>) -> Elem<F> {
150        Elem(F::small_reduce(self.0 + F::Q - rhs.0))
151    }
152}
153
154impl<F: Field> Mul<Elem<F>> for Elem<F> {
155    type Output = Elem<F>;
156
157    fn mul(self, rhs: Elem<F>) -> Elem<F> {
158        let lhs: F::Long = self.0.into();
159        let rhs: F::Long = rhs.0.into();
160        let prod = lhs * rhs;
161        Elem(F::barrett_reduce(prod))
162    }
163}
164
165/// A `Polynomial` is a member of the ring `R_q = Z_q[X] / (X^256)` of degree-256 polynomials
166/// over the finite field with prime order `q`.
167///
168/// Polynomials can be added, subtracted, negated, and multiplied by field elements.
169#[derive(Clone, Copy, Default, Debug, PartialEq)]
170pub struct Polynomial<F: Field>(pub Array<Elem<F>, U256>);
171
172impl<F: Field> Polynomial<F> {
173    /// Create a new polynomial.
174    pub const fn new(x: Array<Elem<F>, U256>) -> Self {
175        Self(x)
176    }
177}
178
179#[cfg(feature = "zeroize")]
180impl<F: Field> Zeroize for Polynomial<F>
181where
182    F::Int: Zeroize,
183{
184    fn zeroize(&mut self) {
185        self.0.zeroize();
186    }
187}
188
189impl<F: Field> Add<&Polynomial<F>> for &Polynomial<F> {
190    type Output = Polynomial<F>;
191
192    fn add(self, rhs: &Polynomial<F>) -> Polynomial<F> {
193        Polynomial(
194            self.0
195                .iter()
196                .zip(rhs.0.iter())
197                .map(|(&x, &y)| x + y)
198                .collect(),
199        )
200    }
201}
202
203impl<F: Field> Sub<&Polynomial<F>> for &Polynomial<F> {
204    type Output = Polynomial<F>;
205
206    fn sub(self, rhs: &Polynomial<F>) -> Polynomial<F> {
207        Polynomial(
208            self.0
209                .iter()
210                .zip(rhs.0.iter())
211                .map(|(&x, &y)| x - y)
212                .collect(),
213        )
214    }
215}
216
217impl<F: Field> Mul<&Polynomial<F>> for Elem<F> {
218    type Output = Polynomial<F>;
219
220    fn mul(self, rhs: &Polynomial<F>) -> Polynomial<F> {
221        Polynomial(rhs.0.iter().map(|&x| self * x).collect())
222    }
223}
224
225impl<F: Field> Neg for &Polynomial<F> {
226    type Output = Polynomial<F>;
227
228    fn neg(self) -> Polynomial<F> {
229        Polynomial(self.0.iter().map(|&x| -x).collect())
230    }
231}
232
233/// A `Vector` is a vector of polynomials from `R_q` of length `K`.
234///
235/// Vectors can be added, subtracted, negated, and multiplied by field elements.
236#[derive(Clone, Default, Debug, PartialEq)]
237pub struct Vector<F: Field, K: ArraySize>(pub Array<Polynomial<F>, K>);
238
239impl<F: Field, K: ArraySize> Vector<F, K> {
240    /// Create a new vector.
241    pub const fn new(x: Array<Polynomial<F>, K>) -> Self {
242        Self(x)
243    }
244}
245
246#[cfg(feature = "zeroize")]
247impl<F: Field, K: ArraySize> Zeroize for Vector<F, K>
248where
249    F::Int: Zeroize,
250{
251    fn zeroize(&mut self) {
252        self.0.zeroize();
253    }
254}
255
256impl<F: Field, K: ArraySize> Add<Vector<F, K>> for Vector<F, K> {
257    type Output = Vector<F, K>;
258    fn add(self, rhs: Vector<F, K>) -> Vector<F, K> {
259        Add::add(&self, &rhs)
260    }
261}
262impl<F: Field, K: ArraySize> Add<&Vector<F, K>> for &Vector<F, K> {
263    type Output = Vector<F, K>;
264
265    fn add(self, rhs: &Vector<F, K>) -> Vector<F, K> {
266        Vector(
267            self.0
268                .iter()
269                .zip(rhs.0.iter())
270                .map(|(x, y)| x + y)
271                .collect(),
272        )
273    }
274}
275
276impl<F: Field, K: ArraySize> Sub<&Vector<F, K>> for &Vector<F, K> {
277    type Output = Vector<F, K>;
278
279    fn sub(self, rhs: &Vector<F, K>) -> Vector<F, K> {
280        Vector(
281            self.0
282                .iter()
283                .zip(rhs.0.iter())
284                .map(|(x, y)| x - y)
285                .collect(),
286        )
287    }
288}
289
290impl<F: Field, K: ArraySize> Mul<&Vector<F, K>> for Elem<F> {
291    type Output = Vector<F, K>;
292
293    fn mul(self, rhs: &Vector<F, K>) -> Vector<F, K> {
294        Vector(rhs.0.iter().map(|x| self * x).collect())
295    }
296}
297
298impl<F: Field, K: ArraySize> Neg for &Vector<F, K> {
299    type Output = Vector<F, K>;
300
301    fn neg(self) -> Vector<F, K> {
302        Vector(self.0.iter().map(|x| -x).collect())
303    }
304}
305
306/// An `NttPolynomial` is a member of the NTT algebra `T_q = Z_q[X]^256` of 256-tuples of field
307/// elements.
308///
309/// NTT polynomials can be added and subtracted, negated, and multiplied by scalars.
310/// We do not define multiplication of NTT polynomials here: that is defined by the downstream
311/// crate using the [`MultiplyNtt`] trait.
312///
313/// We also do not define the mappings between normal polynomials and NTT polynomials (i.e., between
314/// `R_q` and `T_q`).
315#[derive(Clone, Default, Debug, Eq, PartialEq)]
316pub struct NttPolynomial<F: Field>(pub Array<Elem<F>, U256>);
317
318impl<F: Field> NttPolynomial<F> {
319    /// Create a new NTT polynomial.
320    pub const fn new(x: Array<Elem<F>, U256>) -> Self {
321        Self(x)
322    }
323}
324
325impl<F: Field> Add<&NttPolynomial<F>> for &NttPolynomial<F> {
326    type Output = NttPolynomial<F>;
327
328    fn add(self, rhs: &NttPolynomial<F>) -> NttPolynomial<F> {
329        NttPolynomial(
330            self.0
331                .iter()
332                .zip(rhs.0.iter())
333                .map(|(&x, &y)| x + y)
334                .collect(),
335        )
336    }
337}
338
339impl<F: Field> Sub<&NttPolynomial<F>> for &NttPolynomial<F> {
340    type Output = NttPolynomial<F>;
341
342    fn sub(self, rhs: &NttPolynomial<F>) -> NttPolynomial<F> {
343        NttPolynomial(
344            self.0
345                .iter()
346                .zip(rhs.0.iter())
347                .map(|(&x, &y)| x - y)
348                .collect(),
349        )
350    }
351}
352
353impl<F: Field> Mul<&NttPolynomial<F>> for Elem<F> {
354    type Output = NttPolynomial<F>;
355
356    fn mul(self, rhs: &NttPolynomial<F>) -> NttPolynomial<F> {
357        NttPolynomial(rhs.0.iter().map(|&x| self * x).collect())
358    }
359}
360
361impl<F> Mul<&NttPolynomial<F>> for &NttPolynomial<F>
362where
363    F: Field + MultiplyNtt,
364{
365    type Output = NttPolynomial<F>;
366
367    fn mul(self, rhs: &NttPolynomial<F>) -> NttPolynomial<F> {
368        F::multiply_ntt(self, rhs)
369    }
370}
371
372/// Perform multiplication in the NTT domain.
373pub trait MultiplyNtt: Field {
374    /// Multiply two NTT polynomials.
375    fn multiply_ntt(lhs: &NttPolynomial<Self>, rhs: &NttPolynomial<Self>) -> NttPolynomial<Self>;
376}
377
378impl<F: Field> Neg for &NttPolynomial<F> {
379    type Output = NttPolynomial<F>;
380
381    fn neg(self) -> NttPolynomial<F> {
382        NttPolynomial(self.0.iter().map(|&x| -x).collect())
383    }
384}
385
386impl<F: Field> From<Array<Elem<F>, U256>> for NttPolynomial<F> {
387    fn from(f: Array<Elem<F>, U256>) -> NttPolynomial<F> {
388        NttPolynomial(f)
389    }
390}
391
392impl<F: Field> From<NttPolynomial<F>> for Array<Elem<F>, U256> {
393    fn from(f_hat: NttPolynomial<F>) -> Array<Elem<F>, U256> {
394        f_hat.0
395    }
396}
397
398#[cfg(feature = "ctutils")]
399impl<F: Field> CtEq for NttPolynomial<F>
400where
401    F::Int: CtEq,
402{
403    fn ct_eq(&self, other: &Self) -> Choice {
404        self.0.ct_eq(&other.0)
405    }
406}
407
408#[cfg(feature = "ctutils")]
409impl<F: Field<Int: CtEq>> CtEqSlice for NttPolynomial<F> {}
410
411#[cfg(feature = "zeroize")]
412impl<F: Field> Zeroize for NttPolynomial<F>
413where
414    F::Int: Zeroize,
415{
416    fn zeroize(&mut self) {
417        self.0.zeroize();
418    }
419}
420
421/// An [`NttVector`] is a vector of polynomials from `T_q` of length `K`.
422///
423/// NTT vectors can be added and subtracted.  If multiplication is defined for NTT polynomials, then
424/// NTT vectors can be multiplied by NTT polynomials, and "multiplied" with each other to produce a
425/// dot product.
426#[derive(Clone, Default, Debug, Eq, PartialEq)]
427pub struct NttVector<F: Field, K: ArraySize>(pub Array<NttPolynomial<F>, K>);
428
429impl<F: Field, K: ArraySize> NttVector<F, K> {
430    /// Create a new NTT vector.
431    pub const fn new(x: Array<NttPolynomial<F>, K>) -> Self {
432        Self(x)
433    }
434}
435
436#[cfg(feature = "ctutils")]
437impl<F: Field, K: ArraySize> CtEq for NttVector<F, K>
438where
439    F::Int: CtEq,
440{
441    fn ct_eq(&self, other: &Self) -> Choice {
442        self.0.ct_eq(&other.0)
443    }
444}
445
446#[cfg(feature = "ctutils")]
447impl<F: Field<Int: CtEq>, K: ArraySize> CtEqSlice for NttVector<F, K> {}
448
449#[cfg(feature = "zeroize")]
450impl<F: Field, K: ArraySize> Zeroize for NttVector<F, K>
451where
452    F::Int: Zeroize,
453{
454    fn zeroize(&mut self) {
455        self.0.zeroize();
456    }
457}
458
459impl<F: Field, K: ArraySize> Add<&NttVector<F, K>> for &NttVector<F, K> {
460    type Output = NttVector<F, K>;
461
462    fn add(self, rhs: &NttVector<F, K>) -> NttVector<F, K> {
463        NttVector(
464            self.0
465                .iter()
466                .zip(rhs.0.iter())
467                .map(|(x, y)| x + y)
468                .collect(),
469        )
470    }
471}
472
473impl<F: Field, K: ArraySize> Sub<&NttVector<F, K>> for &NttVector<F, K> {
474    type Output = NttVector<F, K>;
475
476    fn sub(self, rhs: &NttVector<F, K>) -> NttVector<F, K> {
477        NttVector(
478            self.0
479                .iter()
480                .zip(rhs.0.iter())
481                .map(|(x, y)| x - y)
482                .collect(),
483        )
484    }
485}
486
487impl<F: Field, K: ArraySize> Mul<&NttVector<F, K>> for &NttPolynomial<F>
488where
489    for<'a> &'a NttPolynomial<F>: Mul<&'a NttPolynomial<F>, Output = NttPolynomial<F>>,
490{
491    type Output = NttVector<F, K>;
492
493    fn mul(self, rhs: &NttVector<F, K>) -> NttVector<F, K> {
494        NttVector(rhs.0.iter().map(|x| self * x).collect())
495    }
496}
497
498impl<F: Field, K: ArraySize> Mul<&NttVector<F, K>> for &NttVector<F, K>
499where
500    for<'a> &'a NttPolynomial<F>: Mul<&'a NttPolynomial<F>, Output = NttPolynomial<F>>,
501{
502    type Output = NttPolynomial<F>;
503
504    fn mul(self, rhs: &NttVector<F, K>) -> NttPolynomial<F> {
505        self.0
506            .iter()
507            .zip(rhs.0.iter())
508            .map(|(x, y)| x * y)
509            .fold(NttPolynomial::default(), |x, y| &x + &y)
510    }
511}
512
513/// A `K x L` matrix of NTT-domain polynomials.
514///
515/// Each vector represents a row of the matrix, so that multiplying on the right just requires
516/// iteration.
517///
518/// Multiplication on the right by vectors is the only defined operation, and is only defined when
519/// multiplication of NTT polynomials is defined.
520#[derive(Clone, Default, Debug, PartialEq)]
521pub struct NttMatrix<F: Field, K: ArraySize, L: ArraySize>(pub Array<NttVector<F, L>, K>);
522
523impl<F: Field, K: ArraySize, L: ArraySize> NttMatrix<F, K, L> {
524    /// Create a new NTT matrix.
525    pub const fn new(x: Array<NttVector<F, L>, K>) -> Self {
526        Self(x)
527    }
528}
529
530impl<F: Field, K: ArraySize, L: ArraySize> Mul<&NttVector<F, L>> for &NttMatrix<F, K, L>
531where
532    for<'a> &'a NttPolynomial<F>: Mul<&'a NttPolynomial<F>, Output = NttPolynomial<F>>,
533{
534    type Output = NttVector<F, K>;
535
536    fn mul(self, rhs: &NttVector<F, L>) -> NttVector<F, K> {
537        NttVector(self.0.iter().map(|x| x * rhs).collect())
538    }
539}