tfhe 1.8.0

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
use super::super::CheckError;
pub use crate::core_crypto::commons::parameters::PBSOrder;
use crate::shortint::backward_compatibility::ciphertext::*;
use crate::shortint::parameters::{CarryModulus, MessageModulus};
use serde::{Deserialize, Serialize};
use std::cmp;
use std::fmt::Debug;
use tfhe_versionable::Versionize;

/// Error for when a non trivial ciphertext was used when a trivial was expected
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct NotTrivialCiphertextError;

impl std::fmt::Display for NotTrivialCiphertextError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "The ciphertext is a not a trivial ciphertext")
    }
}

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

/// This tracks the maximal amount of noise of a [super::Ciphertext]
/// that guarantees the target p-error when doing a PBS on it
#[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize, Versionize)]
#[versionize(MaxNoiseLevelVersions)]
pub struct MaxNoiseLevel(u64);

impl MaxNoiseLevel {
    pub(crate) const UNKNOWN: Self = Self(u64::MAX);

    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    pub const fn get(&self) -> u64 {
        self.0
    }

    /// # Panics
    ///
    /// Panics if `msg_modulus` is smaller than 2, as a message space holding less than 2 values is
    /// degenerate and the norm2 limit is not defined for it, or if `carry_modulus` is 0.
    // This function is valid for current parameters as they guarantee the p-error for a norm2 noise
    // limit equal to the norm2 limit which guarantees a clean padding bit
    //
    // TODO: remove this functions once noise norm2 constraint is decorrelated and stored in
    // parameter sets
    pub const fn from_msg_carry_modulus(
        msg_modulus: MessageModulus,
        carry_modulus: CarryModulus,
    ) -> Self {
        assert!(
            msg_modulus.0 >= 2,
            "MessageModulus must be at least 2 to derive a MaxNoiseLevel"
        );
        assert!(
            carry_modulus.0 != 0,
            "CarryModulus must be non zero to derive a MaxNoiseLevel"
        );
        let level = (carry_modulus.0 * msg_modulus.0 - 1) / (msg_modulus.0 - 1);
        Self(level)
    }

    pub const fn validate(&self, noise_level: NoiseLevel) -> Result<(), CheckError> {
        if noise_level.0 > self.0 {
            return Err(CheckError::NoiseTooBig {
                noise_level,
                max_noise_level: *self,
            });
        }
        Ok(())
    }
}

/// This tracks the amount of noise in a ciphertext.
#[derive(
    Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Serialize, Deserialize, Versionize,
)]
#[versionize(NoiseLevelVersions)]
pub struct NoiseLevel(pub(crate) u64);

impl NoiseLevel {
    pub const NOMINAL: Self = Self(1);
    pub const ZERO: Self = Self(0);
    // As a safety measure the unknown noise level is set to the max value
    pub const UNKNOWN: Self = Self(u64::MAX);
}

impl NoiseLevel {
    pub fn get(&self) -> u64 {
        self.0
    }
}

impl std::ops::AddAssign for NoiseLevel {
    fn add_assign(&mut self, rhs: Self) {
        self.0 = self.0.saturating_add(rhs.0);
    }
}

impl std::ops::Add for NoiseLevel {
    type Output = Self;

    fn add(mut self, rhs: Self) -> Self {
        self += rhs;
        self
    }
}

impl std::ops::MulAssign<u64> for NoiseLevel {
    fn mul_assign(&mut self, rhs: u64) {
        self.0 = self.0.saturating_mul(rhs);
    }
}

impl std::ops::Mul<u64> for NoiseLevel {
    type Output = Self;

    fn mul(mut self, rhs: u64) -> Self::Output {
        self *= rhs;

        self
    }
}

/// Maximum value that the degree can reach.
#[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize, Versionize)]
#[versionize(MaxDegreeVersions)]
pub struct MaxDegree(pub(crate) u64);

impl MaxDegree {
    pub fn new(value: u64) -> Self {
        Self(value)
    }

    pub fn get(&self) -> u64 {
        self.0
    }

    /// # Panics
    ///
    /// Panics if either modulus is 0, as the resulting plaintext space would be empty.
    pub fn from_msg_carry_modulus(
        msg_modulus: MessageModulus,
        carry_modulus: CarryModulus,
    ) -> Self {
        assert!(
            msg_modulus.0 != 0 && carry_modulus.0 != 0,
            "MessageModulus and CarryModulus must both be non zero to derive a MaxDegree"
        );
        Self(carry_modulus.0 * msg_modulus.0 - 1)
    }

    pub fn validate(&self, degree: Degree) -> Result<(), CheckError> {
        if degree.get() > self.0 {
            return Err(CheckError::CarryFull {
                degree,
                max_degree: *self,
            });
        }
        Ok(())
    }
}

/// The maximum value a given ciphertext can have. This helps with optimizations.
#[derive(
    Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Serialize, Deserialize, Versionize,
)]
#[versionize(DegreeVersions)]
pub struct Degree(pub(crate) u64);

impl Degree {
    pub fn new(degree: u64) -> Self {
        Self(degree)
    }

    pub fn get(self) -> u64 {
        self.0
    }
}

#[cfg(test)]
impl AsMut<u64> for Degree {
    fn as_mut(&mut self) -> &mut u64 {
        &mut self.0
    }
}

impl Degree {
    pub(crate) fn after_bitxor(self, other: Self) -> Self {
        let max = cmp::max(self.0, other.0);
        let min = cmp::min(self.0, other.0);
        let mut result = max;

        //Try every possibility to find the worst case
        for i in 0..min + 1 {
            if max ^ i > result {
                result = max ^ i;
            }
        }

        Self(result)
    }

    pub(crate) fn after_bitor(self, other: Self) -> Self {
        let max = cmp::max(self.0, other.0);
        let min = cmp::min(self.0, other.0);
        let mut result = max;

        for i in 0..min + 1 {
            if max | i > result {
                result = max | i;
            }
        }

        Self(result)
    }

    pub(crate) fn after_bitand(self, other: Self) -> Self {
        Self(cmp::min(self.0, other.0))
    }

    pub(crate) fn after_left_shift(self, shift: u8, modulus: u64) -> Self {
        let mut result = 0;

        for i in 0..self.0 + 1 {
            let tmp = (i << shift) % modulus;
            if tmp > result {
                result = tmp;
            }
        }

        Self(result)
    }
}

impl std::ops::AddAssign for Degree {
    fn add_assign(&mut self, rhs: Self) {
        self.0 = self.0.saturating_add(rhs.0);
    }
}

impl std::ops::Add for Degree {
    type Output = Self;

    fn add(mut self, rhs: Self) -> Self {
        self += rhs;
        self
    }
}

impl std::ops::MulAssign<u64> for Degree {
    fn mul_assign(&mut self, rhs: u64) {
        self.0 = self.0.saturating_mul(rhs);
    }
}

impl std::ops::Mul<u64> for Degree {
    type Output = Self;

    fn mul(mut self, rhs: u64) -> Self::Output {
        self *= rhs;

        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_noise_level_ci_run_filter() {
        use rand::{thread_rng, Rng};

        let mut rng = thread_rng();

        assert_eq!(NoiseLevel::UNKNOWN.0, u64::MAX);

        let max_noise_level = NoiseLevel::UNKNOWN;
        let random_addend = rng.gen::<u64>();
        let add = max_noise_level + NoiseLevel(random_addend);
        assert_eq!(add, NoiseLevel::UNKNOWN);

        let random_positive_multiplier = rng.gen_range(1u64..=u64::MAX);
        let mul = max_noise_level * random_positive_multiplier;
        assert_eq!(mul, NoiseLevel::UNKNOWN);

        let random_noise = NoiseLevel(rng.gen_range(2..=u64::MAX));

        assert!(NoiseLevel::NOMINAL >= NoiseLevel::ZERO);
        assert!(random_noise > NoiseLevel::NOMINAL);
        assert!(random_noise <= NoiseLevel::UNKNOWN);
    }

    #[test]
    fn test_max_noise_level_from_msg_carry_modulus_ci_run_filter() {
        let max_noise_level =
            MaxNoiseLevel::from_msg_carry_modulus(MessageModulus(4), CarryModulus(4));

        assert_eq!(max_noise_level.0, 5);
    }

    #[test]
    #[should_panic(expected = "MessageModulus must be at least 2")]
    fn test_max_noise_level_from_degenerate_msg_modulus_ci_run_filter() {
        let _ = MaxNoiseLevel::from_msg_carry_modulus(MessageModulus(1), CarryModulus(2));
    }

    #[test]
    #[should_panic(expected = "CarryModulus must be non zero")]
    fn test_max_noise_level_from_zero_carry_modulus_ci_run_filter() {
        let _ = MaxNoiseLevel::from_msg_carry_modulus(MessageModulus(2), CarryModulus(0));
    }

    #[test]
    #[should_panic(expected = "must both be non zero")]
    fn test_max_degree_from_zero_msg_modulus_ci_run_filter() {
        let _ = MaxDegree::from_msg_carry_modulus(MessageModulus(0), CarryModulus(2));
    }

    #[test]
    #[should_panic(expected = "must both be non zero")]
    fn test_max_degree_from_zero_carry_modulus_ci_run_filter() {
        let _ = MaxDegree::from_msg_carry_modulus(MessageModulus(2), CarryModulus(0));
    }

    #[test]
    fn degree_after_bitxor_ci_run_filter() {
        let data = [
            (Degree(3), Degree(3), Degree(3)),
            (Degree(3), Degree(1), Degree(3)),
            (Degree(1), Degree(3), Degree(3)),
            (Degree(3), Degree(2), Degree(3)),
            (Degree(2), Degree(3), Degree(3)),
            (Degree(2), Degree(2), Degree(3)),
            (Degree(2), Degree(1), Degree(3)),
            (Degree(1), Degree(2), Degree(3)),
            (Degree(1), Degree(1), Degree(1)),
            (Degree(0), Degree(1), Degree(1)),
            (Degree(0), Degree(1), Degree(1)),
        ];

        for (lhs, rhs, expected) in data {
            let result = lhs.after_bitxor(rhs);
            assert_eq!(
                result, expected,
                "For a bitxor between variables of degree {lhs:?} and {rhs:?},\
             expected resulting degree: {expected:?}, got {result:?}"
            );
        }
    }
    #[test]
    fn degree_after_bitor_ci_run_filter() {
        let data = [
            (Degree(3), Degree(3), Degree(3)),
            (Degree(3), Degree(1), Degree(3)),
            (Degree(1), Degree(3), Degree(3)),
            (Degree(3), Degree(2), Degree(3)),
            (Degree(2), Degree(3), Degree(3)),
            (Degree(2), Degree(2), Degree(3)),
            (Degree(2), Degree(1), Degree(3)),
            (Degree(1), Degree(2), Degree(3)),
            (Degree(1), Degree(1), Degree(1)),
            (Degree(0), Degree(1), Degree(1)),
            (Degree(0), Degree(1), Degree(1)),
        ];

        for (lhs, rhs, expected) in data {
            let result = lhs.after_bitor(rhs);
            assert_eq!(
                result, expected,
                "For a bitor between variables of degree {lhs:?} and {rhs:?},\
             expected resulting degree: {expected:?}, got {result:?}"
            );
        }
    }

    #[test]
    fn degree_after_bitand_ci_run_filter() {
        let data = [
            (Degree(3), Degree(3), Degree(3)),
            (Degree(3), Degree(1), Degree(1)),
            (Degree(1), Degree(3), Degree(1)),
            (Degree(3), Degree(2), Degree(2)),
            (Degree(2), Degree(3), Degree(2)),
            (Degree(2), Degree(2), Degree(2)),
            (Degree(2), Degree(1), Degree(1)),
            (Degree(1), Degree(2), Degree(1)),
            (Degree(1), Degree(1), Degree(1)),
            (Degree(0), Degree(1), Degree(0)),
            (Degree(0), Degree(1), Degree(0)),
        ];

        for (lhs, rhs, expected) in data {
            let result = lhs.after_bitand(rhs);
            assert_eq!(
                result, expected,
                "For a bitand between variables of degree {lhs:?} and {rhs:?},\
             expected resulting degree: {expected:?}, got {result:?}"
            );
        }
    }
}