qfall-math 0.1.1

Mathematical foundations for rapid prototyping of lattice-based cryptography
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// Copyright © 2023 Phil Milewski, Marcel Luca Schmidt
//
// This file is part of qFALL-math.
//
// qFALL-math is free software: you can redistribute it and/or modify it under
// the terms of the Mozilla Public License Version 2.0 as published by the
// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.

//! Implementation of the [`Mul`] trait for [`PolyOverZq`] values.

use super::super::PolyOverZq;
use crate::{
    error::MathError,
    integer::PolyOverZ,
    macros::arithmetics::{
        arithmetic_assign_trait_borrowed_to_owned, arithmetic_trait_borrowed_to_owned,
        arithmetic_trait_mixed_borrowed_owned, arithmetic_trait_reverse,
    },
    traits::CompareBase,
};
use core::panic;
use flint_sys::fmpz_mod_poly::fmpz_mod_poly_mul;
use std::{
    ops::{Mul, MulAssign},
    str::FromStr,
};

impl MulAssign<&PolyOverZq> for PolyOverZq {
    /// Computes the multiplication of `self` and `other` reusing
    /// the memory of `self`.
    /// [`MulAssign`] can be used on [`PolyOverZq`] in combination with
    /// [`PolyOverZq`] and [`PolyOverZ`].
    ///
    /// Parameters:
    /// - `other`: specifies the polynomial to multiply to `self`
    ///
    /// Returns the product of both polynomials modulo `q` as a [`PolyOverZq`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{integer_mod_q::PolyOverZq, integer::PolyOverZ};
    /// use std::str::FromStr;
    ///
    /// let mut a = PolyOverZq::from_str("3  1 2 3 mod 7").unwrap();
    /// let b = PolyOverZq::from_str("5  1 2 -3 0 4 mod 7").unwrap();
    /// let c = PolyOverZ::from_str("4  -1 2 5 3").unwrap();
    ///
    /// a *= &b;
    /// a *= b;
    /// a *= &c;
    /// a *= c;
    /// ```
    ///
    /// # Panics ...
    /// - if the moduli of both [`PolyOverZq`] mismatch.
    fn mul_assign(&mut self, other: &Self) {
        if !self.compare_base(other) {
            panic!("{}", self.call_compare_base_error(other).unwrap());
        }

        unsafe {
            fmpz_mod_poly_mul(
                &mut self.poly,
                &self.poly,
                &other.poly,
                self.modulus.get_fmpz_mod_ctx_struct(),
            )
        };
    }
}
impl MulAssign<&PolyOverZ> for PolyOverZq {
    /// Documentation at [`PolyOverZq::mul_assign`].
    fn mul_assign(&mut self, other: &PolyOverZ) {
        let other = PolyOverZq::from((other, self.get_mod()));

        self.mul_assign(&other);
    }
}

arithmetic_assign_trait_borrowed_to_owned!(MulAssign, mul_assign, PolyOverZq, PolyOverZq);
arithmetic_assign_trait_borrowed_to_owned!(MulAssign, mul_assign, PolyOverZq, PolyOverZ);

impl Mul for &PolyOverZq {
    type Output = PolyOverZq;
    /// Implements the [`Mul`] trait for two [`PolyOverZq`] values.
    /// [`Mul`] is implemented for any combination of [`PolyOverZq`] and borrowed [`PolyOverZq`].
    ///
    /// Parameters:
    /// - `other`: specifies the polynomial to multiply with `self`
    ///
    /// Returns the product of both polynomials as a [`PolyOverZq`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::PolyOverZq;
    /// use std::str::FromStr;
    ///
    /// let a: PolyOverZq = PolyOverZq::from_str("3  2 4 1 mod 7").unwrap();
    /// let b: PolyOverZq = PolyOverZq::from_str("3  5 1 1 mod 7").unwrap();
    ///
    /// let c: PolyOverZq = &a * &b;
    /// let d: PolyOverZq = a * b;
    /// let e: PolyOverZq = &c * d;
    /// let f: PolyOverZq = c * &e;
    /// ```
    ///
    /// # Panics ...
    /// - if the moduli of both [`PolyOverZq`] mismatch.
    fn mul(self, other: Self) -> Self::Output {
        self.mul_safe(other).unwrap()
    }
}

arithmetic_trait_borrowed_to_owned!(Mul, mul, PolyOverZq, PolyOverZq, PolyOverZq);
arithmetic_trait_mixed_borrowed_owned!(Mul, mul, PolyOverZq, PolyOverZq, PolyOverZq);

impl Mul<&PolyOverZ> for &PolyOverZq {
    type Output = PolyOverZq;
    /// Implements the [`Mul`] trait for [`PolyOverZq`] and [`PolyOverZ`].
    /// [`Mul`] is implemented for any combination of owned and borrowed values.
    ///
    /// Parameters:
    /// - `other`: specifies the polynomial to multiply to `self`
    ///
    /// Returns the product of both polynomials as a [`PolyOverZq`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::PolyOverZq;
    /// use qfall_math::integer::PolyOverZ;
    /// use std::str::FromStr;
    ///
    /// let a = PolyOverZq::from_str("4  -1 0 1 1 mod 17").unwrap();
    /// let b = PolyOverZ::from_str("4  2 0 3 1").unwrap();
    ///
    /// let c: PolyOverZq = &a * &b;
    /// ```
    fn mul(self, other: &PolyOverZ) -> Self::Output {
        let mut out = PolyOverZq::from(&self.modulus);
        unsafe {
            fmpz_mod_poly_mul(
                &mut out.poly,
                &self.poly,
                &PolyOverZq::from((other, &self.modulus)).poly,
                self.modulus.get_fmpz_mod_ctx_struct(),
            );
        }
        out
    }
}

arithmetic_trait_reverse!(Mul, mul, PolyOverZ, PolyOverZq, PolyOverZq);

arithmetic_trait_borrowed_to_owned!(Mul, mul, PolyOverZq, PolyOverZ, PolyOverZq);
arithmetic_trait_borrowed_to_owned!(Mul, mul, PolyOverZ, PolyOverZq, PolyOverZq);
arithmetic_trait_mixed_borrowed_owned!(Mul, mul, PolyOverZq, PolyOverZ, PolyOverZq);
arithmetic_trait_mixed_borrowed_owned!(Mul, mul, PolyOverZ, PolyOverZq, PolyOverZq);

impl PolyOverZq {
    /// Implements multiplication for two [`PolyOverZq`] values.
    ///
    /// Parameters:
    /// - `other`: specifies the polynomial to multiply to `self`
    ///
    /// Returns the product of both polynomials as a [`PolyOverZq`] or an error if the moduli
    /// mismatch.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::PolyOverZq;
    /// use std::str::FromStr;
    ///
    /// let a: PolyOverZq = PolyOverZq::from_str("3  2 4 1 mod 7").unwrap();
    /// let b: PolyOverZq = PolyOverZq::from_str("3  5 1 1 mod 7").unwrap();
    ///
    /// let c: PolyOverZq = a.mul_safe(&b).unwrap();
    /// ```
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`MathError::MismatchingModulus`] if the moduli of
    ///   both [`PolyOverZq`] mismatch.
    pub fn mul_safe(&self, other: &Self) -> Result<PolyOverZq, MathError> {
        if !self.compare_base(other) {
            return Err(self.call_compare_base_error(other).unwrap());
        }
        let mut out = PolyOverZq::from_str(&format!("0 mod {}", self.modulus)).unwrap();
        unsafe {
            fmpz_mod_poly_mul(
                &mut out.poly,
                &self.poly,
                &other.poly,
                self.modulus.get_fmpz_mod_ctx_struct(),
            );
        }
        Ok(out)
    }
}

#[cfg(test)]
mod test_mul_assign {
    use super::PolyOverZq;
    use crate::integer::PolyOverZ;
    use std::str::FromStr;

    /// Ensure that `mul_assign` works for small numbers.
    #[test]
    fn correct_small() {
        let mut a = PolyOverZq::from_str("3  2 4 1 mod 7").unwrap();
        let b = PolyOverZq::from_str("2  2 4 mod 7").unwrap();

        a *= b;

        assert_eq!(a, PolyOverZq::from_str("4  4 2 4 4 mod 7").unwrap());
    }

    /// Ensure that `mul_assign` works for large numbers.
    #[test]
    fn correct_large() {
        let mut a = PolyOverZq::from_str(&format!(
            "2  {} {} mod {}",
            u64::MAX,
            i64::MAX,
            u64::MAX - 58
        ))
        .unwrap();
        let b = PolyOverZq::from_str(&format!(
            "2  {} {} mod {}",
            i64::MAX,
            i64::MIN,
            u64::MAX - 58
        ))
        .unwrap();

        a *= b;

        assert_eq!(
            a,
            PolyOverZq::from_str(&format!(
                "3  {} {} {} mod {}",
                i128::from(i64::MAX) * 58,
                i128::from(i64::MIN) * 58 + i128::from(i64::MAX) * i128::from(i64::MAX),
                i128::from(i64::MAX) * i128::from(i64::MIN),
                u64::MAX - 58
            ))
            .unwrap()
        );
    }

    /// Ensure that `mul_assign` is available for all types.
    #[test]
    fn availability() {
        let mut a = PolyOverZq::from_str("3  1 2 -3 mod 5").unwrap();
        let b = PolyOverZq::from_str("3  -1 -2 3 mod 5").unwrap();
        let c = PolyOverZ::from_str("2  -2 2").unwrap();

        a *= &b;
        a *= b;
        a *= &c;
        a *= c;
    }

    /// Ensures that mismatching moduli result in a panic.
    #[test]
    #[should_panic]
    fn mismatching_moduli() {
        let mut a: PolyOverZq = PolyOverZq::from_str("3  -5 4 1 mod 7").unwrap();
        let b: PolyOverZq = PolyOverZq::from_str("3  -5 4 1 mod 8").unwrap();

        a *= b;
    }
}

#[cfg(test)]
mod test_mul {
    use super::PolyOverZq;
    use std::str::FromStr;

    /// Testing multiplication for two [`PolyOverZq`]
    #[test]
    fn mul() {
        let a: PolyOverZq = PolyOverZq::from_str("3  2 4 1 mod 7").unwrap();
        let b: PolyOverZq = PolyOverZq::from_str("2  2 4 mod 7").unwrap();
        let c: PolyOverZq = a * b;
        assert_eq!(c, PolyOverZq::from_str("4  4 2 4 4 mod 7").unwrap());
    }

    /// Testing multiplication for two borrowed [`PolyOverZq`]
    #[test]
    fn mul_borrow() {
        let a: PolyOverZq = PolyOverZq::from_str("3  2 4 1 mod 7").unwrap();
        let b: PolyOverZq = PolyOverZq::from_str("2  2 4 mod 7").unwrap();
        let c: PolyOverZq = &a * &b;
        assert_eq!(c, PolyOverZq::from_str("4  4 2 4 4 mod 7").unwrap());
    }

    /// Testing multiplication for borrowed [`PolyOverZq`] and [`PolyOverZq`]
    #[test]
    fn mul_first_borrowed() {
        let a: PolyOverZq = PolyOverZq::from_str("3  2 4 1 mod 7").unwrap();
        let b: PolyOverZq = PolyOverZq::from_str("2  2 4 mod 7").unwrap();
        let c: PolyOverZq = &a * b;
        assert_eq!(c, PolyOverZq::from_str("4  4 2 4 4 mod 7").unwrap());
    }

    /// Testing multiplication for [`PolyOverZq`] and borrowed [`PolyOverZq`]
    #[test]
    fn mul_second_borrowed() {
        let a: PolyOverZq = PolyOverZq::from_str("3  2 4 1 mod 7").unwrap();
        let b: PolyOverZq = PolyOverZq::from_str("2  2 4 mod 7").unwrap();
        let c: PolyOverZq = a * &b;
        assert_eq!(c, PolyOverZq::from_str("4  4 2 4 4 mod 7").unwrap());
    }

    /// Testing multiplication for [`PolyOverZq`] and a constant [`PolyOverZq`]
    #[test]
    fn mul_constant() {
        let a: PolyOverZq = PolyOverZq::from_str("3  2 4 1 mod 7").unwrap();
        let b: PolyOverZq = PolyOverZq::from_str("1  2 mod 7").unwrap();
        let c: PolyOverZq = &a * b;
        assert_eq!(c, PolyOverZq::from_str("3  4 1 2 mod 7").unwrap());
        assert_eq!(
            a * PolyOverZq::from_str("0 mod 7").unwrap(),
            PolyOverZq::from_str("0 mod 7").unwrap()
        );
    }

    /// Testing multiplication for large [`PolyOverZq`]
    #[test]
    fn mul_large_numbers() {
        let a: PolyOverZq = PolyOverZq::from_str(&format!(
            "2  {} {} mod {}",
            u64::MAX,
            i64::MAX,
            u64::MAX - 58
        ))
        .unwrap();
        let b: PolyOverZq = PolyOverZq::from_str(&format!(
            "2  {} {} mod {}",
            i64::MAX,
            i64::MIN,
            u64::MAX - 58
        ))
        .unwrap();
        let c: PolyOverZq = a * &b;
        assert_eq!(
            c,
            PolyOverZq::from_str(&format!(
                "3  {} {} {} mod {}",
                i128::from(i64::MAX) * 58,
                i128::from(i64::MIN) * 58 + i128::from(i64::MAX) * i128::from(i64::MAX),
                i128::from(i64::MAX) * i128::from(i64::MIN),
                u64::MAX - 58
            ))
            .unwrap()
        );
    }

    /// Testing multiplication for [`PolyOverZq`] with different moduli does not work
    #[test]
    #[should_panic]
    fn mul_mismatching_modulus() {
        let a: PolyOverZq = PolyOverZq::from_str("3  2 4 1 mod 8").unwrap();
        let b: PolyOverZq = PolyOverZq::from_str("2  -5 4 mod 7").unwrap();
        let _c: PolyOverZq = a * b;
    }

    /// Testing whether mul_safe throws an error for mismatching moduli
    #[test]
    fn mul_safe_is_err() {
        let a: PolyOverZq = PolyOverZq::from_str("3  2 4 1 mod 9").unwrap();
        let b: PolyOverZq = PolyOverZq::from_str("2  -5 4 mod 7").unwrap();
        assert!(&a.mul_safe(&b).is_err());
    }
}

#[cfg(test)]
mod test_mul_poly_over_z {
    use super::PolyOverZq;
    use crate::integer::PolyOverZ;
    use std::str::FromStr;

    /// Checks if polynomial multiplication works fine for both borrowed
    #[test]
    fn borrowed_correctness() {
        let poly_1 = PolyOverZq::from_str(&format!("1  {} mod {}", i64::MAX, u64::MAX)).unwrap();
        let poly_2 = PolyOverZ::from_str("2  1 2").unwrap();
        let poly_cmp = PolyOverZq::from_str(&format!(
            "2  {} {} mod {}",
            i64::MAX,
            i64::MAX as u64 * 2,
            u64::MAX
        ))
        .unwrap();

        let poly_1 = &poly_1 * &poly_2;

        assert_eq!(poly_cmp, poly_1);
    }

    /// Checks if multiplication works fine for different types
    #[test]
    fn availability() {
        let poly = PolyOverZq::from_str("3  1 2 3 mod 17").unwrap();
        let z = PolyOverZ::from(2);

        _ = poly.clone() * z.clone();
        _ = z.clone() * poly.clone();
        _ = &poly * &z;
        _ = &z * &poly;
        _ = &poly * z.clone();
        _ = z.clone() * &poly;
        _ = &z * poly.clone();
        _ = poly.clone() * &z;
    }
}