tfhe 1.6.1

TFHE-rs is a fully homomorphic encryption (FHE) library that implements Zama's variant of TFHE.
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Module containing the definition of the [`CiphertextModulus`].

use tfhe_versionable::Versionize;

use crate::core_crypto::backward_compatibility::commons::ciphertext_modulus::SerializableCiphertextModulusVersions;
use crate::core_crypto::commons::traits::UnsignedInteger;
use crate::core_crypto::prelude::CastInto;
use core::num::NonZeroU128;
use std::cmp::Ordering;
use std::fmt::Display;
use std::marker::PhantomData;

use super::parameters::CiphertextModulusLog;

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
/// Private enum to avoid end user instantiating a bad CiphertextModulus
///
/// NonZeroU128 allows to always have a correct modulus and to have an enum that is no bigger than a
/// u128 with the 0 optimization as the tag then corresponds to the Native variant.
enum CiphertextModulusInner {
    Native,
    Custom(NonZeroU128),
}

#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Versionize, Hash)]
#[serde(
    try_from = "SerializableCiphertextModulus",
    into = "SerializableCiphertextModulus"
)]
#[versionize(
    SerializableCiphertextModulusVersions,
    try_from = "SerializableCiphertextModulus",
    into = "SerializableCiphertextModulus"
)]
/// Structure representing a [`CiphertextModulus`] often noted $q$.
pub struct CiphertextModulus<Scalar: UnsignedInteger> {
    inner: CiphertextModulusInner,
    _scalar: PhantomData<Scalar>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CiphertextModulusKind {
    Native,
    NonNativePowerOfTwo,
    Other,
}

#[derive(serde::Serialize, serde::Deserialize, Versionize)]
#[versionize(SerializableCiphertextModulusVersions)]
/// Actual serialized modulus to be able to carry the UnsignedInteger bitwidth information
pub struct SerializableCiphertextModulus {
    pub modulus: u128,
    pub scalar_bits: usize,
}

#[derive(Clone, Copy, Debug)]
pub enum CiphertextModulusDeserializationError {
    InvalidBitWidth { expected: usize, found: usize },
    ZeroCustomModulus,
}

impl Display for CiphertextModulusDeserializationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidBitWidth { expected, found } => write!(
                f,
                "Expected an unsigned integer with {expected} bits, \
            found {found} bits during deserialization of CiphertextModulus, \
            have you mixed types during deserialization?",
            ),
            Self::ZeroCustomModulus => write!(
                f,
                "Got zero modulus for CiphertextModulusInner::Custom variant"
            ),
        }
    }
}

impl std::error::Error for CiphertextModulusDeserializationError {}

impl<Scalar: UnsignedInteger> From<CiphertextModulus<Scalar>> for SerializableCiphertextModulus {
    fn from(value: CiphertextModulus<Scalar>) -> Self {
        let modulus = match value.inner {
            CiphertextModulusInner::Native => 0,
            CiphertextModulusInner::Custom(modulus) => modulus.get(),
        };

        Self {
            modulus,
            scalar_bits: Scalar::BITS,
        }
    }
}

impl<Scalar: UnsignedInteger> TryFrom<SerializableCiphertextModulus> for CiphertextModulus<Scalar> {
    type Error = CiphertextModulusDeserializationError;

    fn try_from(value: SerializableCiphertextModulus) -> Result<Self, Self::Error> {
        if value.scalar_bits != Scalar::BITS {
            return Err(CiphertextModulusDeserializationError::InvalidBitWidth {
                expected: Scalar::BITS,
                found: value.scalar_bits,
            });
        }

        let res = if value.modulus == 0 {
            Self {
                inner: CiphertextModulusInner::Native,
                _scalar: PhantomData,
            }
        } else {
            Self {
                inner: CiphertextModulusInner::Custom(
                    NonZeroU128::new(value.modulus)
                        .ok_or(CiphertextModulusDeserializationError::ZeroCustomModulus)?,
                ),
                _scalar: PhantomData,
            }
        };
        Ok(res.canonicalize())
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CiphertextModulusCreationError {
    ModulusTooBig,
    CustomModuli64BitsOrLessOnly,
}

impl CiphertextModulusCreationError {
    pub const fn const_err_msg(self) -> &'static str {
        match self {
            Self::ModulusTooBig => {
                "Modulus is bigger than the maximum value of the associated Scalar type"
            }
            Self::CustomModuli64BitsOrLessOnly => {
                "Non power of 2 moduli are not supported for types wider than u64"
            }
        }
    }
}

impl From<CiphertextModulusCreationError> for &str {
    fn from(value: CiphertextModulusCreationError) -> Self {
        value.const_err_msg()
    }
}

impl std::fmt::Debug for CiphertextModulusCreationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let err_str: &str = (*self).into();
        write!(f, "{err_str}")
    }
}

impl<Scalar: UnsignedInteger> CiphertextModulus<Scalar> {
    pub const fn new_native() -> Self {
        Self {
            inner: CiphertextModulusInner::Native,
            _scalar: PhantomData,
        }
    }

    #[track_caller]
    pub const fn try_new_power_of_2(
        exponent: usize,
    ) -> Result<Self, CiphertextModulusCreationError> {
        if exponent > Scalar::BITS {
            Err(CiphertextModulusCreationError::ModulusTooBig)
        } else {
            let res = if let Some(modulus) = 1u128.checked_shl(exponent as u32) {
                let Some(non_zero_modulus) = NonZeroU128::new(modulus) else {
                    panic!("Got zero modulus for CiphertextModulusInner::Custom variant")
                };

                Self {
                    inner: CiphertextModulusInner::Custom(non_zero_modulus),
                    _scalar: PhantomData,
                }
            } else {
                assert!(exponent == 128);
                assert!(Scalar::BITS == 128);
                Self {
                    inner: CiphertextModulusInner::Native,
                    _scalar: PhantomData,
                }
            };
            Ok(res.canonicalize())
        }
    }

    #[track_caller]
    pub const fn try_new(modulus: u128) -> Result<Self, CiphertextModulusCreationError> {
        if Scalar::BITS < 128 && modulus > (1 << Scalar::BITS) {
            Err(CiphertextModulusCreationError::ModulusTooBig)
        } else {
            let res = match modulus {
                0 => Self::new_native(),
                modulus => {
                    let Some(non_zero_modulus) = NonZeroU128::new(modulus) else {
                        panic!("Got zero modulus for CiphertextModulusInner::Custom variant")
                    };
                    Self {
                        inner: CiphertextModulusInner::Custom(non_zero_modulus),
                        _scalar: PhantomData,
                    }
                }
            };
            let canonicalized_result = res.canonicalize();
            if Scalar::BITS > 64 && !canonicalized_result.is_compatible_with_native_modulus() {
                return Err(CiphertextModulusCreationError::CustomModuli64BitsOrLessOnly);
            }
            Ok(canonicalized_result)
        }
    }

    pub const fn canonicalize(self) -> Self {
        match self.inner {
            CiphertextModulusInner::Native => self,
            CiphertextModulusInner::Custom(modulus) => {
                if Scalar::BITS < 128 && modulus.get() == (1 << Scalar::BITS) {
                    Self::new_native()
                } else {
                    self
                }
            }
        }
    }

    /// # Panic
    /// Panics if modulus is not able to fit in the associated Scalar type
    #[track_caller]
    pub const fn new(modulus: u128) -> Self {
        let res = match modulus {
            0 => Self::new_native(),
            _ => match Self::try_new(modulus) {
                Ok(ciphertext_modulus) => ciphertext_modulus,
                Err(err) => panic!("{}", err.const_err_msg()),
            },
        };
        res.canonicalize()
    }

    /// # Panic
    /// Panics if the stored modulus is not a power of 2.
    #[track_caller]
    pub fn get_power_of_two_scaling_to_native_torus(&self) -> Scalar {
        match self.inner {
            CiphertextModulusInner::Native => Scalar::ONE,
            CiphertextModulusInner::Custom(modulus) => {
                assert!(
                    modulus.is_power_of_two(),
                    "Cannot get scaling for non power of two modulus {modulus}"
                );
                Scalar::ONE.wrapping_shl(Scalar::BITS as u32 - modulus.ilog2())
            }
        }
    }

    /// Depending on the Scalar type used in the call, this function will determine whether the
    /// current modulus is the native modulus of the given Scalar type allowing for more efficient
    /// implementations than can rely on wrapping arithmetic operations behavior to compute the
    /// modulus.
    pub const fn is_native_modulus(&self) -> bool {
        matches!(self.inner, CiphertextModulusInner::Native)
    }

    /// Panics if the modulus is not a custom modulus
    #[track_caller]
    pub const fn get_custom_modulus(&self) -> u128 {
        match self.inner {
            CiphertextModulusInner::Native => {
                panic!("Tried getting custom modulus from native modulus")
            }
            CiphertextModulusInner::Custom(modulus) => modulus.get(),
        }
    }

    pub fn into_modulus_log(self) -> CiphertextModulusLog {
        match self.inner {
            CiphertextModulusInner::Native => CiphertextModulusLog(Scalar::BITS),
            CiphertextModulusInner::Custom(custom_mod) => {
                CiphertextModulusLog(custom_mod.get().ceil_ilog2() as usize)
            }
        }
    }

    pub fn get_custom_modulus_as_optional_scalar(&self) -> Option<Scalar> {
        match self.inner {
            CiphertextModulusInner::Native => None,
            CiphertextModulusInner::Custom(modulus) => Some(modulus.get().cast_into()),
        }
    }

    pub const fn is_compatible_with_native_modulus(&self) -> bool {
        self.is_native_modulus() || self.is_power_of_two()
    }

    pub const fn is_non_native_power_of_two(&self) -> bool {
        match self.inner {
            CiphertextModulusInner::Native => false,
            CiphertextModulusInner::Custom(modulus) => modulus.is_power_of_two(),
        }
    }

    pub const fn is_power_of_two(&self) -> bool {
        match self.inner {
            CiphertextModulusInner::Native => true,
            CiphertextModulusInner::Custom(modulus) => modulus.is_power_of_two(),
        }
    }

    pub fn try_to<ScalarTo: UnsignedInteger + CastInto<u128>>(
        &self,
    ) -> Result<CiphertextModulus<ScalarTo>, &'static str> {
        let error_msg = "failed to convert ciphertext modulus";

        let new_inner = match self.inner {
            CiphertextModulusInner::Native => match ScalarTo::BITS.cmp(&Scalar::BITS) {
                Ordering::Greater => {
                    CiphertextModulusInner::Custom(NonZeroU128::new(1u128 << Scalar::BITS).unwrap())
                }
                Ordering::Equal => CiphertextModulusInner::Native,
                Ordering::Less => {
                    return Err(error_msg);
                }
            },
            CiphertextModulusInner::Custom(v) => {
                let max = NonZeroU128::new(ScalarTo::MAX.cast_into()).unwrap();
                if v <= max {
                    CiphertextModulusInner::Custom(v)
                } else if v.is_power_of_two() && v.ilog2() as usize == ScalarTo::BITS {
                    CiphertextModulusInner::Native
                } else {
                    return Err(error_msg);
                }
            }
        };

        Ok(CiphertextModulus {
            inner: new_inner,
            _scalar: PhantomData,
        }
        .canonicalize())
    }

    pub const fn kind(&self) -> CiphertextModulusKind {
        match self.inner {
            CiphertextModulusInner::Native => CiphertextModulusKind::Native,
            CiphertextModulusInner::Custom(modulus) => {
                if modulus.is_power_of_two() {
                    CiphertextModulusKind::NonNativePowerOfTwo
                } else {
                    CiphertextModulusKind::Other
                }
            }
        }
    }

    pub fn raw_modulus_float(&self) -> f64 {
        match self.inner {
            CiphertextModulusInner::Native => 2_f64.powi(Scalar::BITS as i32),
            CiphertextModulusInner::Custom(non_zero) => non_zero.get() as f64,
        }
    }

    pub const fn associated_scalar_bits(&self) -> usize {
        Scalar::BITS
    }
}

impl<Scalar: UnsignedInteger> From<CiphertextModulus<Scalar>> for CiphertextModulusLog {
    fn from(value: CiphertextModulus<Scalar>) -> Self {
        value.into_modulus_log()
    }
}

impl<Scalar: UnsignedInteger> std::fmt::Display for CiphertextModulus<Scalar> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.inner {
            CiphertextModulusInner::Native => write!(f, "CiphertextModulus(2^{})", Scalar::BITS),
            CiphertextModulusInner::Custom(modulus) => {
                write!(f, "CiphertextModulus({})", modulus.get())
            }
        }
    }
}

impl<Scalar: UnsignedInteger> std::fmt::Debug for CiphertextModulus<Scalar> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <Self as std::fmt::Display>::fmt(self, f)
    }
}

#[cfg(test)]
mod tests {
    use super::CiphertextModulusCreationError;
    use crate::core_crypto::prelude::CiphertextModulus;

    #[test]
    fn test_modulus_struct() {
        assert!(std::mem::size_of::<CiphertextModulus<u32>>() == std::mem::size_of::<u128>());
        assert!(std::mem::size_of::<CiphertextModulus<u64>>() == std::mem::size_of::<u128>());
        assert!(std::mem::size_of::<CiphertextModulus<u128>>() == std::mem::size_of::<u128>());
        assert!(std::mem::align_of::<CiphertextModulus<u32>>() == std::mem::align_of::<u128>());
        assert!(std::mem::align_of::<CiphertextModulus<u64>>() == std::mem::align_of::<u128>());
        assert!(std::mem::align_of::<CiphertextModulus<u128>>() == std::mem::align_of::<u128>());

        {
            let mod_32 = CiphertextModulus::<u32>::try_new_power_of_2(32).unwrap();

            assert!(mod_32.is_native_modulus());

            let std_fmt = format!("{mod_32}");
            assert_eq!(&std_fmt, "CiphertextModulus(2^32)");

            let dbg_fmt = format!("{mod_32:?}");
            assert_eq!(&dbg_fmt, "CiphertextModulus(2^32)");
        }

        {
            let bad_mod_32 = CiphertextModulus::<u32>::try_new_power_of_2(64);
            assert!(bad_mod_32.is_err());
            match bad_mod_32 {
                Ok(_) => unreachable!(),
                Err(e) => assert_eq!(e, CiphertextModulusCreationError::ModulusTooBig),
            }
        }

        {
            let native_mod_128 = CiphertextModulus::<u128>::new_native();
            assert!(native_mod_128.is_native_modulus());

            let ser = bincode::serialize(&native_mod_128).unwrap();
            let deser: CiphertextModulus<u128> = bincode::deserialize(&ser).unwrap();

            assert_eq!(native_mod_128, deser);

            let deser_error: Result<CiphertextModulus<u32>, _> = bincode::deserialize(&ser);
            assert!(deser_error.is_err());
            match deser_error {
                Ok(_) => unreachable!(),
                Err(e) => match *e {
                    bincode::ErrorKind::Custom(err) => {
                        assert_eq!(
                            err.as_str(),
                            "Expected an unsigned integer with 32 bits, \
                    found 128 bits during deserialization of CiphertextModulus, \
                    have you mixed types during deserialization?",
                        );
                    }
                    _ => unreachable!(),
                },
            }
        }

        {
            let mod_128 = CiphertextModulus::<u128>::try_new_power_of_2(64).unwrap();

            assert_eq!(mod_128.get_custom_modulus(), 1 << 64);

            let ser = bincode::serialize(&mod_128).unwrap();
            let deser: CiphertextModulus<u128> = bincode::deserialize(&ser).unwrap();

            assert_eq!(mod_128, deser);

            let deser_error: Result<CiphertextModulus<u32>, _> = bincode::deserialize(&ser);
            assert!(deser_error.is_err());
            match deser_error {
                Ok(_) => unreachable!(),
                Err(e) => match *e {
                    bincode::ErrorKind::Custom(err) => {
                        assert_eq!(
                            err.as_str(),
                            "Expected an unsigned integer with 32 bits, \
                    found 128 bits during deserialization of CiphertextModulus, \
                    have you mixed types during deserialization?",
                        );
                    }
                    _ => unreachable!(),
                },
            }
        }
    }

    #[test]
    fn test_modulus_casting() {
        // Native (u64 -> u64) => Native
        let native_mod = CiphertextModulus::<u64>::try_new_power_of_2(64).unwrap();
        assert!(native_mod.is_native_modulus());
        let converted: CiphertextModulus<u64> = native_mod.try_to().unwrap();

        assert!(converted.is_native_modulus());

        // Native (u64 -> u128) => Custom
        let native_mod = CiphertextModulus::<u64>::try_new_power_of_2(64).unwrap();
        let converted: CiphertextModulus<u128> = native_mod.try_to().unwrap();

        assert!(!converted.is_native_modulus());
        assert_eq!(converted.get_custom_modulus(), 1u128 << 64);

        // Native(u64 -> u32) => Impossible
        let native_mod = CiphertextModulus::<u64>::try_new_power_of_2(64).unwrap();
        let converted: Result<CiphertextModulus<u32>, _> = native_mod.try_to();
        assert!(converted.is_err());

        // Custom(u64 -> u64) => Custom
        let custom_mod = CiphertextModulus::<u64>::try_new(64).unwrap();
        assert!(!custom_mod.is_native_modulus());
        let converted: CiphertextModulus<u64> = custom_mod.try_to().unwrap();

        assert!(!converted.is_native_modulus());
        assert_eq!(converted.get_custom_modulus(), 64);

        // Custom(u64[with value == 2**32] -> u32) => Native
        let custom_mod = CiphertextModulus::<u64>::try_new_power_of_2(32).unwrap();
        assert!(!custom_mod.is_native_modulus());
        let converted: CiphertextModulus<u32> = custom_mod.try_to().unwrap();
        assert!(converted.is_native_modulus());

        // Custom (u64[with value > 2**32] -> u32) => Impossible
        let custom_mod = CiphertextModulus::<u64>::try_new(1 << 48).unwrap();
        assert!(!custom_mod.is_native_modulus());
        let converted: Result<CiphertextModulus<u32>, _> = custom_mod.try_to();
        assert!(converted.is_err());

        // Custom (u64[with value < 2**32] -> u32) => Custom
        let custom_mod = CiphertextModulus::<u64>::try_new(1 << 21).unwrap();
        assert!(!custom_mod.is_native_modulus());
        let converted: CiphertextModulus<u32> = custom_mod.try_to().unwrap();
        assert!(!converted.is_native_modulus());
        assert_eq!(converted.get_custom_modulus(), 1 << 21);
    }
}