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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Copyright © 2023 Sven Moog, Marcel Luca Schmidt, Niklas Siemer
//
// 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/>.

//! Implementations to create a [`Zq`] value from other types.
//!
//! The explicit functions contain the documentation.

use super::Zq;
use crate::{
    error::{MathError, StringConversionError},
    integer::Z,
    integer_mod_q::Modulus,
};
use std::str::FromStr;

impl<Mod: Into<Modulus>> From<Mod> for Zq {
    /// Creates a zero integer with a given [`Modulus`].
    ///
    /// Parameters:
    /// - `modulus`: of the new [`Zq`]
    ///
    /// Returns a new constant [`Zq`] with the specified [`Modulus`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::Zq;
    /// use std::str::FromStr;
    ///
    /// let zq = Zq::from(100);
    ///
    /// let zq_cmp = Zq::from_str("0 mod 100").unwrap();
    /// assert_eq!(zq, zq_cmp);
    /// ```
    ///
    /// # Panics ...
    /// - if `modulus` is smaller than `2`.
    fn from(modulus: Mod) -> Self {
        let value = Z::default();
        let modulus = modulus.into();

        let mut out = Zq { value, modulus };
        out.reduce();
        out
    }
}

impl<IntegerValue: Into<Z>, IntegerModulus: Into<Modulus>> From<(IntegerValue, IntegerModulus)>
    for Zq
{
    /// Creates a [`Zq`] from a tuple with the integer and the modulus.
    ///
    /// Parameters:
    /// - `value`: Defines the value of the residue class.
    /// - `modulus`: Defines the modulus by which `value` is reduced.
    ///
    /// Note that the strings for integer and modulus are trimmed,
    /// i.e. all whitespaces around all values are ignored.
    ///
    /// Returns the `value` mod `modulus` as a [`Zq`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::Zq;
    /// use qfall_math::integer::Z;
    ///
    /// let answer_1 = Zq::from((1337 + 42, 1337));
    /// let answer_2 = Zq::from((Z::from(42), 1337));
    ///
    /// assert_eq!(answer_1, answer_2);
    /// ```
    ///
    /// # Panics ...
    /// - if `modulus` is smaller than `2`.
    fn from((value, modulus): (IntegerValue, IntegerModulus)) -> Self {
        let value = value.into();
        let modulus = modulus.into();

        let mut out = Zq { value, modulus };
        out.reduce();
        out
    }
}

impl FromStr for Zq {
    type Err = MathError;

    /// Creates a [`Zq`] integer from a [`String`].
    ///
    /// Parameters:
    /// - `s`: the integer and modulus value of form: `"12 mod 25"` for the number 12
    ///   under the modulus 25.
    ///
    /// Returns a [`Zq`] or an error if the provided string was not formatted
    /// correctly.
    ///
    /// # Examples
    /// ```
    /// use std::str::FromStr;
    /// use qfall_math::integer_mod_q::Zq;
    ///  
    /// let a: Zq = "100 mod 3".parse().unwrap();
    /// let b: Zq = Zq::from_str("100 mod 3").unwrap();
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type
    ///   [`StringConversionError`](MathError::StringConversionError)
    ///     - if the provided string contains a `Null` byte,
    ///     - if the provided string was not formatted correctly,
    ///     - if the provided modulus was not formatted correctly to create a [`Z`], or
    ///     - if the delimiter `mod` could not be found.
    /// - Returns a [`MathError`] of type
    ///   [`InvalidModulus`](MathError::InvalidModulus)
    ///   if the provided value is smaller than `2`.
    /// - Returns a [`MathError`] of type
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let input_split: Vec<&str> = s.split("mod").collect();
        if input_split.len() != 2 {
            return Err(StringConversionError::InvalidStringToZqInput(s.to_owned()))?;
        }

        // instantiate both parts of Zq element
        let modulus = Modulus::from_str(input_split[1].trim())?;
        let value = Z::from_str(input_split[0].trim())?;

        let mut out = Self { value, modulus };
        out.reduce();

        Ok(out)
    }
}

impl From<&Zq> for Zq {
    /// An alias for [`Zq::clone`].
    /// It makes the use of generic `Into<Zq>` types easier.
    fn from(value: &Zq) -> Self {
        value.clone()
    }
}

impl Zq {
    /// Create a [`Zq`] integer from a [`String`], i.e. its UTF8-Encoding.
    /// The inverse of this function is [`Zq::to_utf8`].
    ///
    /// Parameters:
    /// - `message`: specifies the message that is transformed via its UTF8-Encoding
    ///   to a new [`Zq`] instance.
    /// - `modulus`: Defines the modulus by which `value` is reduced.
    ///
    /// Returns value defined by `message` mod `modulus` as [`Zq`] or a [`MathError`]
    /// if the provided modulus is smaller than the UTF8-Encoding of the message.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::Zq;
    /// let message = "hello!";
    ///  
    /// let value = Zq::from_utf8(&message, i64::MAX).unwrap();
    /// assert_eq!(Zq::from((36762444129640u64, i64::MAX)), value);
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`ConversionError`](MathError::ConversionError) if the provided modulus
    ///   is smaller than the UTF8-Encoding of the message.
    ///
    /// # Panics ...
    /// - if `modulus` is smaller than `2`.
    pub fn from_utf8(message: &str, modulus: impl Into<Modulus>) -> Result<Zq, MathError> {
        let modulus: Modulus = modulus.into();
        let modulus_as_z: Z = (&modulus).into();
        let value = Z::from_utf8(message);

        if modulus_as_z > value {
            return Ok(Zq::from((value, &modulus)));
        }
        Err(MathError::ConversionError(
            "The provided modulus is smaller than the UTF8-Encoding of your message.".to_owned(),
        ))
    }
}

#[cfg(test)]
mod test_from_mod {
    use crate::integer_mod_q::Zq;
    use std::str::FromStr;

    /// Ensure that the resulting value is zero and the modulus is correctly instantiated.
    #[test]
    fn modulus_zero() {
        let zq = Zq::from(100);

        assert_eq!(zq, Zq::from_str("0 mod 100").unwrap());
    }

    /// Ensure that initializing large moduli works.
    #[test]
    fn modulus_large() {
        let zq = Zq::from(u64::MAX);

        assert_eq!(zq, Zq::from_str(&format!("0 mod {}", u64::MAX)).unwrap());
    }

    /// Ensure that mod 0 results in a panic.
    #[test]
    #[should_panic]
    fn modulus_0() {
        let _ = Zq::from(0);
    }

    /// Ensure that mod 1 results in a panic.
    #[test]
    #[should_panic]
    fn modulus_1() {
        let _ = Zq::from(1);
    }

    /// Ensure that a negative modulus results in a panic.
    #[test]
    #[should_panic]
    fn modulus_negative() {
        let _ = Zq::from(-1);
    }
}

#[cfg(test)]
mod test_from_trait {
    use crate::{
        integer::Z,
        integer_mod_q::{Modulus, Zq},
    };

    /// Test that the different combinations of rust integers, [`Z`], and [`Modulus`]
    /// in their owned and borrowed form can be used to create a [`Zq`].
    #[test]
    fn different_types() {
        let int_8: i8 = 10;
        let int_16: i16 = 10;
        let int_32: i32 = 10;
        let int_64: i64 = 10;
        let uint_8: u8 = 10;
        let uint_16: u16 = 10;
        let uint_32: u32 = 10;
        let uint_64: u64 = 10;
        let z = Z::from(10);
        let modulus = Modulus::from(10);

        // owned, owned the same type in numerator and denominator
        let _ = Zq::from((int_8, int_8));
        let _ = Zq::from((int_16, int_16));
        let _ = Zq::from((int_32, int_32));
        let _ = Zq::from((int_64, int_64));
        let _ = Zq::from((uint_8, uint_8));
        let _ = Zq::from((uint_16, uint_16));
        let _ = Zq::from((uint_32, uint_32));
        let _ = Zq::from((uint_64, uint_64));
        let _ = Zq::from((z.clone(), z.clone()));
        let _ = Zq::from((modulus.clone(), modulus.clone()));

        // borrowed, borrowed the same type in numerator and denominator
        let _ = Zq::from((&int_8, &int_8));
        let _ = Zq::from((&int_16, &int_16));
        let _ = Zq::from((&int_32, &int_32));
        let _ = Zq::from((&int_64, &int_64));
        let _ = Zq::from((&uint_8, &uint_8));
        let _ = Zq::from((&uint_16, &uint_16));
        let _ = Zq::from((&uint_32, &uint_32));
        let _ = Zq::from((&uint_64, &uint_64));
        let _ = Zq::from((&z, &z));
        let _ = Zq::from((&modulus, &modulus));

        // From now on assume that i/u8, i/u16, i/u32 and i/u64 behave the same.
        // This assumption is reasonable, since their implementation is the same.

        // owned, owned mixed types
        let _ = Zq::from((int_8, z.clone()));
        let _ = Zq::from((z.clone(), int_8));
        let _ = Zq::from((int_8, modulus.clone()));
        let _ = Zq::from((z.clone(), modulus.clone()));
        let _ = Zq::from((modulus.clone(), int_8));
        let _ = Zq::from((modulus.clone(), z.clone()));

        // owned, borrowed mixed types
        let _ = Zq::from((int_8, &z));
        let _ = Zq::from((modulus.clone(), &z));
        let _ = Zq::from((z.clone(), &int_8));
        let _ = Zq::from((z.clone(), &modulus));
        let _ = Zq::from((int_8, &modulus));
        let _ = Zq::from((modulus.clone(), &int_8));

        // borrowed, owned mixed types
        let _ = Zq::from((&int_8, z.clone()));
        let _ = Zq::from((&modulus, z.clone()));
        let _ = Zq::from((&z, int_8));
        let _ = Zq::from((&z, modulus.clone()));
        let _ = Zq::from((&int_8, modulus.clone()));
        let _ = Zq::from((&modulus, int_8));

        // borrowed, borrowed mixed types
        let _ = Zq::from((&int_8, &z));
        let _ = Zq::from((&modulus, &z));
        let _ = Zq::from((&z, &int_8));
        let _ = Zq::from((&z, &modulus));
        let _ = Zq::from((&int_8, &modulus));
        let _ = Zq::from((&modulus, &int_8));
    }

    /// Ensure that the modulus calculation is performed at initialization.
    #[test]
    fn modulus_at_initialization() {
        let a = Zq::from((0, 10));
        let b = Zq::from((10, 10));

        assert_eq!(a, b);
    }

    /// Test with small valid value and modulus.
    #[test]
    fn working_small() {
        let zq_1 = Zq::from((10, 15));
        let zq_2 = Zq::from((Z::from(10), Modulus::from(15)));

        assert_eq!(zq_1, zq_2);
    }

    /// Test with large value and modulus (FLINT uses pointer representation).
    #[test]
    fn working_large() {
        let zq_1 = Zq::from((u64::MAX - 1, u64::MAX));
        let zq_2 = Zq::from((&Z::from(u64::MAX - 1), Modulus::from(u64::MAX)));

        assert_eq!(zq_1, zq_2);
    }

    /// Test with `0` modulus (not valid)
    #[test]
    #[should_panic]
    fn modulus_zero() {
        let _ = Zq::from((10, 0));
    }

    /// Test with negative modulus (not valid)
    #[test]
    #[should_panic]
    fn modulus_negative() {
        let _ = Zq::from((10, -1));
    }
}

#[cfg(test)]
mod tests_from_str {
    use crate::integer_mod_q::Zq;
    use std::str::FromStr;

    /// Ensure that initialization with large numbers works.
    #[test]
    fn max_int_positive() {
        assert!(Zq::from_str(&format!("{} mod {}", i64::MAX, u64::MAX)).is_ok());
    }

    /// Ensure that initialization with large numbers (larger than [`i64`]) works.
    #[test]
    fn large_positive() {
        assert!(Zq::from_str(&format!("{} mod {}", u64::MAX, u128::MAX)).is_ok());
    }

    /// Ensure that initialization with large negative numbers works.
    #[test]
    fn max_int_negative() {
        assert!(Zq::from_str(&format!("-{} mod {}", i64::MAX, u64::MAX)).is_ok());
    }

    /// Ensure that initialization with large negative numbers (larger than [`i64`]) works.
    #[test]
    fn large_negative() {
        assert!(Zq::from_str(&format!("-{} mod {}", u64::MAX, u128::MAX)).is_ok());
    }

    /// Ensure that initialization with standard values works.
    #[test]
    fn normal_value() {
        assert!(Zq::from_str("42 mod 5").is_ok());
    }

    /// Ensure that initialization works with leading and trailing whitespaces.
    #[test]
    fn whitespaces_work() {
        assert!(Zq::from_str("    42 mod 5").is_ok());
        assert!(Zq::from_str("42 mod 5    ").is_ok());
        assert!(Zq::from_str("42    mod 5").is_ok());
        assert!(Zq::from_str("42 mod     5").is_ok());
    }

    /// Ensure that initialization yields an error with whitespaces in between.
    #[test]
    fn whitespaces_error() {
        assert!(Zq::from_str("4 2 mod 5").is_err());
        assert!(Zq::from_str("42 mo d 5").is_err());
        assert!(Zq::from_str("42 mod 5 0").is_err());
    }

    /// Ensure that wrong initialization yields an Error.
    #[test]
    fn error_wrong_letters() {
        assert!(Zq::from_str("hbrkt35itu3gg").is_err());
        assert!(Zq::from_str("3-2 mod 3").is_err());
        assert!(Zq::from_str("3 5").is_err());
        assert!(Zq::from_str("3%5").is_err());
        assert!(Zq::from_str("3/5 mod 3").is_err());
    }
}

#[cfg(test)]
/// Test the implementation of [`Zq::from_utf8`] briefly.
/// This module omits tests that were already provided for [`crate::integer::Z::from_utf8`].
mod test_from_utf8 {
    use super::Zq;

    /// Ensures that values that are larger than the modulus result in an error.
    #[test]
    fn not_enough_memory() {
        let message = "some_long message with too many bytes";
        let modulus = u32::MAX;

        let value = Zq::from_utf8(message, modulus);

        assert!(value.is_err());
    }

    /// Ensures that using a modulus smaller than `2` results in a panic.
    #[test]
    #[should_panic]
    fn modulus_too_small() {
        let message = "something";
        let modulus = 1;

        let _ = Zq::from_utf8(message, modulus);
    }
}