tfhe 1.6.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
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
use crate::conformance::ParameterSetConformant;
use crate::core_crypto::commons::numeric::UnsignedNumeric;
use crate::integer::backward_compatibility::noise_squashing::*;
use crate::integer::block_decomposition::{BlockRecomposer, RecomposableFrom, SignExtendable};
use crate::integer::ciphertext::{
    BooleanBlock, RadixCiphertext, SignedRadixCiphertext, SquashedNoiseBooleanBlock,
    SquashedNoiseRadixCiphertext, SquashedNoiseSignedRadixCiphertext,
};
use crate::integer::server_key::ServerKey;
use crate::integer::ClientKey;
use crate::named::Named;
use crate::shortint::noise_squashing::NoiseSquashingKeyConformanceParams;
use crate::shortint::parameters::NoiseSquashingParameters;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use tfhe_versionable::Versionize;

#[derive(Clone, Debug, Serialize, Deserialize, Versionize)]
#[versionize(NoiseSquashingPrivateKeyVersions)]
pub struct NoiseSquashingPrivateKey {
    pub(crate) key: crate::shortint::noise_squashing::NoiseSquashingPrivateKey,
}

pub struct NoiseSquashingPrivateKeyView<'a> {
    pub(crate) key: crate::shortint::noise_squashing::NoiseSquashingPrivateKeyView<'a>,
}

#[derive(Clone, Debug, Serialize, Deserialize, Versionize)]
#[versionize(NoiseSquashingKeyVersions)]
pub struct NoiseSquashingKey {
    pub(crate) key: crate::shortint::noise_squashing::NoiseSquashingKey,
}

#[derive(Clone, Debug, Serialize, Deserialize, Versionize)]
#[versionize(CompressedNoiseSquashingKeyVersions)]
pub struct CompressedNoiseSquashingKey {
    pub(crate) key: crate::shortint::noise_squashing::CompressedNoiseSquashingKey,
}

impl Named for NoiseSquashingKey {
    const NAME: &'static str = "integer::NoiseSquashingKey";
}

impl Named for CompressedNoiseSquashingKey {
    const NAME: &'static str = "integer::CompressedNoiseSquashingKey";
}

impl Named for NoiseSquashingPrivateKey {
    const NAME: &'static str = "integer::NoiseSquashingPrivateKey";
}

impl NoiseSquashingPrivateKey {
    pub fn noise_squashing_parameters(&self) -> NoiseSquashingParameters {
        self.key.noise_squashing_parameters()
    }
}

impl CompressedNoiseSquashingKey {
    pub fn decompress(&self) -> NoiseSquashingKey {
        NoiseSquashingKey {
            key: self.key.decompress(),
        }
    }

    pub fn into_raw_parts(self) -> crate::shortint::noise_squashing::CompressedNoiseSquashingKey {
        let Self { key } = self;
        key
    }

    pub fn from_raw_parts(
        key: crate::shortint::noise_squashing::CompressedNoiseSquashingKey,
    ) -> Self {
        Self { key }
    }
}

impl NoiseSquashingPrivateKeyView<'_> {
    pub fn decrypt_radix<T>(&self, ct: &SquashedNoiseRadixCiphertext) -> crate::Result<T>
    where
        T: RecomposableFrom<u128> + UnsignedNumeric,
    {
        let SquashedNoiseRadixCiphertext {
            packed_blocks,
            original_block_count,
        } = ct;

        if packed_blocks.is_empty() {
            return Ok(T::ZERO);
        }

        let packed_blocks_msg_mod = packed_blocks[0].message_modulus();
        let packed_blocks_carry_mod = packed_blocks[0].carry_modulus();

        if packed_blocks_carry_mod.0 < packed_blocks_msg_mod.0 {
            return Err(crate::error!(
                "Input blocks cannot hold properly packed data and cannot be decrypted. \
                CarryModulus ({packed_blocks_carry_mod:?}) should be greater or equal to \
                the MessageModulus ({packed_blocks_msg_mod:?})",
            ));
        }

        if !packed_blocks.iter().all(|block| {
            block.message_modulus() == packed_blocks_msg_mod
                && block.carry_modulus() == packed_blocks_carry_mod
        }) {
            return Err(crate::error!(
                "Inconsistent message and carry moduli in provided SquashedNoiseRadixCiphertext."
            ));
        }

        let key_msg_mod = self.key.message_modulus();
        let key_carry_mod = self.key.carry_modulus();

        if packed_blocks_msg_mod != key_msg_mod || packed_blocks_carry_mod != key_carry_mod {
            return Err(crate::error!(
                "Input SquashedNoiseRadixCiphertext has incompatible \
                message modulus {packed_blocks_msg_mod:?} or \
                carry modulus {packed_blocks_carry_mod:?} with the current \
                NoiseSquashingPrivateKey message modulus {key_msg_mod:?}, \
                carry modulus {key_carry_mod:?}."
            ));
        }

        // We pack messages together so the number of bits per block is related to the msg_mod
        // squared, we only require the carry to be big enough to hold a message
        let bits_in_packed_block = (packed_blocks_msg_mod.0 * packed_blocks_msg_mod.0).ilog2();
        // Packed block has a message modulus with 2x the number of bits vs. the original
        let bits_in_original_block = bits_in_packed_block / 2;
        let original_block_count = *original_block_count as u32;
        let original_bit_size = bits_in_original_block * original_block_count;
        let decrypted_packed_block_iter = packed_blocks
            .iter()
            .map(|block| self.key.decrypt_squashed_noise_ciphertext(block));

        Ok(BlockRecomposer::recompose_unsigned_with_size(
            decrypted_packed_block_iter,
            bits_in_packed_block,
            original_bit_size,
        ))
    }

    pub fn decrypt_signed_radix<T>(
        &self,
        ct: &SquashedNoiseSignedRadixCiphertext,
    ) -> crate::Result<T>
    where
        T: RecomposableFrom<u128> + SignExtendable,
    {
        let SquashedNoiseSignedRadixCiphertext {
            packed_blocks,
            original_block_count,
        } = ct;

        if packed_blocks.is_empty() {
            return Ok(T::ZERO);
        }

        let packed_blocks_msg_mod = packed_blocks[0].message_modulus();
        let packed_blocks_carry_mod = packed_blocks[0].carry_modulus();

        if packed_blocks_carry_mod.0 < packed_blocks_msg_mod.0 {
            return Err(crate::error!(
                "Input blocks cannot hold properly packed data and cannot be decrypted. \
                CarryModulus ({packed_blocks_carry_mod:?}) should be greater or equal to \
                the MessageModulus ({packed_blocks_msg_mod:?})",
            ));
        }

        if !packed_blocks.iter().all(|block| {
            block.message_modulus() == packed_blocks_msg_mod
                && block.carry_modulus() == packed_blocks_carry_mod
        }) {
            return Err(crate::error!(
                "Inconsistent message and carry moduli in provided \
                SquashedNoiseSignedRadixCiphertext"
            ));
        }

        let key_msg_mod = self.key.message_modulus();
        let key_carry_mod = self.key.carry_modulus();

        if packed_blocks_msg_mod != key_msg_mod || packed_blocks_carry_mod != key_carry_mod {
            return Err(crate::error!(
                "Input SquashedNoiseSignedRadixCiphertext has incompatible \
                message modulus {packed_blocks_msg_mod:?} or \
                carry modulus {packed_blocks_carry_mod:?} with the current \
                NoiseSquashingPrivateKey message modulus {key_msg_mod:?}, \
                carry modulus {key_carry_mod:?}."
            ));
        }

        // We pack messages together so the number of bits per block is related to the msg_mod
        // squared, we only require the carry to be big enough to hold a message
        let bits_in_packed_block = (packed_blocks_msg_mod.0 * packed_blocks_msg_mod.0).ilog2();
        // Packed block has a message modulus with 2x the number of bits vs. the original
        let bits_in_original_block = bits_in_packed_block / 2;
        let original_block_count = *original_block_count as u32;
        let original_bit_size = bits_in_original_block * original_block_count;
        let decrypted_packed_block_iter = packed_blocks
            .iter()
            .map(|block| self.key.decrypt_squashed_noise_ciphertext(block));

        Ok(BlockRecomposer::recompose_signed_with_size(
            decrypted_packed_block_iter,
            bits_in_packed_block,
            original_bit_size,
        ))
    }

    pub fn decrypt_bool(&self, ct: &SquashedNoiseBooleanBlock) -> crate::Result<bool> {
        let SquashedNoiseBooleanBlock { ciphertext } = ct;

        let boolean_block_msg_mod = ciphertext.message_modulus();
        let boolean_block_carry_mod = ciphertext.carry_modulus();

        let key_msg_mod = self.key.message_modulus();
        let key_carry_mod = self.key.carry_modulus();

        if boolean_block_msg_mod != key_msg_mod || boolean_block_carry_mod != key_carry_mod {
            return Err(crate::error!(
                "Input SquashedNoiseBooleanBlock has incompatible \
                message modulus {boolean_block_msg_mod:?} or \
                carry modulus {boolean_block_carry_mod:?} with the current \
                NoiseSquashingPrivateKey message modulus {key_msg_mod:?}, \
                carry modulus {key_carry_mod:?}."
            ));
        }

        let decrypted = self.key.decrypt_squashed_noise_ciphertext(ciphertext);

        Ok(decrypted != 0)
    }
}

impl NoiseSquashingPrivateKey {
    pub fn new_compressed_noise_squashing_key(
        &self,
        client_key: &ClientKey,
    ) -> CompressedNoiseSquashingKey {
        client_key.new_compressed_noise_squashing_key(self)
    }

    pub fn new(params: NoiseSquashingParameters) -> Self {
        assert!(
            params.carry_modulus().0 >= params.message_modulus().0,
            "NoiseSquashingPrivateKey requires its CarryModulus {:?} to be greater \
            or equal to its MessageModulus {:?}",
            params.carry_modulus().0,
            params.message_modulus().0,
        );

        Self {
            key: crate::shortint::noise_squashing::NoiseSquashingPrivateKey::new(params),
        }
    }

    pub(crate) fn as_view(&self) -> NoiseSquashingPrivateKeyView<'_> {
        NoiseSquashingPrivateKeyView {
            key: self.key.as_view(),
        }
    }

    pub fn decrypt_radix<T>(&self, ct: &SquashedNoiseRadixCiphertext) -> crate::Result<T>
    where
        T: RecomposableFrom<u128> + UnsignedNumeric,
    {
        self.as_view().decrypt_radix(ct)
    }

    pub fn decrypt_signed_radix<T>(
        &self,
        ct: &SquashedNoiseSignedRadixCiphertext,
    ) -> crate::Result<T>
    where
        T: RecomposableFrom<u128> + SignExtendable,
    {
        self.as_view().decrypt_signed_radix(ct)
    }

    pub fn decrypt_bool(&self, ct: &SquashedNoiseBooleanBlock) -> crate::Result<bool> {
        self.as_view().decrypt_bool(ct)
    }

    pub fn into_raw_parts(self) -> crate::shortint::noise_squashing::NoiseSquashingPrivateKey {
        let Self { key } = self;
        key
    }

    pub fn from_raw_parts(key: crate::shortint::noise_squashing::NoiseSquashingPrivateKey) -> Self {
        Self { key }
    }
}

impl NoiseSquashingKey {
    pub fn into_raw_parts(self) -> crate::shortint::noise_squashing::NoiseSquashingKey {
        let Self { key } = self;
        key
    }

    pub fn from_raw_parts(key: crate::shortint::noise_squashing::NoiseSquashingKey) -> Self {
        Self { key }
    }

    pub fn squash_radix_ciphertext_noise(
        &self,
        src_server_key: &ServerKey,
        ciphertext: &RadixCiphertext,
    ) -> crate::Result<SquashedNoiseRadixCiphertext> {
        let original_block_count = ciphertext.blocks.len();

        let packed_blocks = ciphertext
            .blocks
            .par_chunks(2)
            .map(|two_values| {
                let packed = src_server_key
                    .can_pack_block_chunk(two_values)
                    .map(|two_values| src_server_key.pack_block_chunk(two_values))?;

                self.key
                    .checked_squash_ciphertext_noise(&packed, &src_server_key.key)
            })
            .collect::<crate::Result<Vec<_>>>()?;

        Ok(SquashedNoiseRadixCiphertext {
            packed_blocks,
            original_block_count,
        })
    }

    pub fn squash_signed_radix_ciphertext_noise(
        &self,
        src_server_key: &ServerKey,
        ciphertext: &SignedRadixCiphertext,
    ) -> crate::Result<SquashedNoiseSignedRadixCiphertext> {
        let original_block_count = ciphertext.blocks.len();

        let packed_blocks = ciphertext
            .blocks
            .par_chunks(2)
            .map(|two_values| {
                let packed = src_server_key.pack_block_chunk(two_values);

                self.key
                    .checked_squash_ciphertext_noise(&packed, &src_server_key.key)
            })
            .collect::<crate::Result<Vec<_>>>()?;

        Ok(SquashedNoiseSignedRadixCiphertext {
            packed_blocks,
            original_block_count,
        })
    }

    pub fn squash_boolean_block_noise(
        &self,
        src_server_key: &ServerKey,
        boolean_block: &BooleanBlock,
    ) -> crate::Result<SquashedNoiseBooleanBlock> {
        Ok(SquashedNoiseBooleanBlock {
            ciphertext: self
                .key
                .checked_squash_ciphertext_noise(&boolean_block.0, &src_server_key.key)?,
        })
    }
}

impl ClientKey {
    pub fn new_compressed_noise_squashing_key(
        &self,
        noise_squashing_private_key: &NoiseSquashingPrivateKey,
    ) -> CompressedNoiseSquashingKey {
        CompressedNoiseSquashingKey {
            key: self
                .key
                .new_compressed_noise_squashing_key(&noise_squashing_private_key.key),
        }
    }

    pub fn new_noise_squashing_key(
        &self,
        noise_squashing_private_key: &NoiseSquashingPrivateKey,
    ) -> NoiseSquashingKey {
        NoiseSquashingKey {
            key: self
                .key
                .new_noise_squashing_key(&noise_squashing_private_key.key),
        }
    }
}

impl CompressedNoiseSquashingKey {
    pub fn new(
        client_key: &ClientKey,
        noise_squashing_private_key: &NoiseSquashingPrivateKey,
    ) -> Self {
        client_key.new_compressed_noise_squashing_key(noise_squashing_private_key)
    }
}

impl NoiseSquashingKey {
    pub fn new(
        client_key: &ClientKey,
        noise_squashing_private_key: &NoiseSquashingPrivateKey,
    ) -> Self {
        client_key.new_noise_squashing_key(noise_squashing_private_key)
    }
}

impl ParameterSetConformant for NoiseSquashingKey {
    type ParameterSet = NoiseSquashingKeyConformanceParams;

    fn is_conformant(&self, parameter_set: &Self::ParameterSet) -> bool {
        let Self { key } = self;

        // The atomic pattern we support requires packing
        if key.carry_modulus().0 < key.message_modulus().0 {
            return false;
        }

        key.is_conformant(parameter_set)
    }
}

impl ParameterSetConformant for CompressedNoiseSquashingKey {
    type ParameterSet = NoiseSquashingKeyConformanceParams;

    fn is_conformant(&self, parameter_set: &Self::ParameterSet) -> bool {
        let Self { key } = self;

        // The atomic pattern we support requires packing
        if key.carry_modulus().0 < key.message_modulus().0 {
            return false;
        }

        key.is_conformant(parameter_set)
    }
}