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
use super::*;
use crate::core_crypto::prelude::new_seeder;
use crate::prelude::*;
use crate::shortint::parameters::test_params::*;
use crate::xof_key_set::{CompressedXofKeySet, XofKeySet};
use crate::*;

fn run_xof_key_set_test(config: Config, tag_str: &str, device: Device, check_expansion: bool) {
    let mut seeder = new_seeder();
    let private_seed_bytes = seeder.seed().0.to_le_bytes().to_vec();
    let security_bits = 128;
    let max_norm_hwt = NormalizedHammingWeightBound::new(0.8).unwrap();
    let tag = Tag::from(tag_str);

    let (cks, compressed_key_set) = CompressedXofKeySet::generate(
        config,
        private_seed_bytes,
        security_bits,
        max_norm_hwt,
        tag.clone(),
    )
    .unwrap();

    assert_eq!(cks.tag(), compressed_key_set.compressed_public_key.tag());
    assert_eq!(cks.tag(), &tag);
    assert_eq!(compressed_key_set.tag(), &tag);
    test_xof_key_set(&compressed_key_set, config, device, &cks);
    if check_expansion {
        test_xof_expansion_is_same_as_classic(compressed_key_set);
    }
}

mod cpu {
    use super::*;

    #[test]
    fn test_xof_key_set_legacy_rerand_classic_params() {
        run_xof_key_set_test(
            TEST_LEGACY_RERAND_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_SMALL_ZKV2_TUNIFORM_2M128.into(),
            "classic_2_2",
            Device::Cpu,
            false,
        );
    }

    #[test]
    fn test_xof_key_set_legacy_rerand_ks32_params_big_pke() {
        run_xof_key_set_test(
            TEST_LEGACY_RERAND_META_PARAM_CPU_2_2_KS32_PBS_PKE_TO_BIG_ZKV2_TUNIFORM_2M128.into(),
            "ks32 big pke",
            Device::Cpu,
            false,
        );
    }

    #[test]
    fn test_xof_key_set_legacy_rerand_ks32_params_small_pke() {
        run_xof_key_set_test(
            TEST_LEGACY_RERAND_META_PARAM_CPU_2_2_KS32_PBS_PKE_TO_SMALL_ZKV2_TUNIFORM_2M128.into(),
            "ks32 small pke",
            Device::Cpu,
            false,
        );
    }

    #[test]
    fn test_xof_key_set_classic_params() {
        run_xof_key_set_test(
            TEST_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_SMALL_ZKV2_TUNIFORM_2M128.into(),
            "classic_2_2",
            Device::Cpu,
            true,
        );
    }

    #[test]
    fn test_xof_key_set_ks32_params_big_pke() {
        run_xof_key_set_test(
            TEST_META_PARAM_CPU_2_2_KS32_PBS_PKE_TO_BIG_ZKV2_TUNIFORM_2M128.into(),
            "ks32 big pke",
            Device::Cpu,
            true,
        );
    }

    #[test]
    fn test_xof_key_set_ks32_params_small_pke() {
        run_xof_key_set_test(
            TEST_META_PARAM_CPU_2_2_KS32_PBS_PKE_TO_SMALL_ZKV2_TUNIFORM_2M128.into(),
            "ks32 small pke",
            Device::Cpu,
            true,
        );
    }
}

#[cfg(feature = "gpu")]
mod gpu {
    use super::*;

    // Triggers rerand with KS (V1.5 legacy params have dedicated re_randomization_parameters)
    #[test]
    fn test_xof_key_set_legacy_rerand_multibit_group_4_small_pke() {
        run_xof_key_set_test(
            TEST_LEGACY_RERAND_META_PARAM_GPU_2_2_MULTI_BIT_GROUP_4_KS_PBS_PKE_TO_SMALL_ZKV2_TUNIFORM_2M128.into(),
            "gpu multibit group 4",
            Device::CudaGpu,
            true,
        );
    }

    // Triggers rerand with KS (V1.5 legacy params have dedicated re_randomization_parameters)
    #[test]
    fn test_xof_key_set_legacy_rerand_multibit_group_4_big_pke() {
        run_xof_key_set_test(
            TEST_LEGACY_RERAND_META_PARAM_GPU_2_2_MULTI_BIT_GROUP_4_KS_PBS_PKE_TO_BIG_ZKV2_TUNIFORM_2M128.into(),
            "gpu multibit group 4",
            Device::CudaGpu,
            true,
        );
    }

    // Triggers rerand without KS (V1.6 params have no re_randomization_parameters)
    #[test]
    fn test_xof_key_set_multibit_group_4_small_pke() {
        run_xof_key_set_test(
            TEST_META_PARAM_GPU_2_2_MULTI_BIT_GROUP_4_KS_PBS_PKE_TO_SMALL_ZKV2_TUNIFORM_2M128
                .into(),
            "gpu multibit group 4 small pke",
            Device::CudaGpu,
            true,
        );
    }

    // Triggers rerand without KS (V1.6 params have no re_randomization_parameters)
    #[test]
    fn test_xof_key_set_multibit_group_4_big_pke() {
        run_xof_key_set_test(
            TEST_META_PARAM_GPU_2_2_MULTI_BIT_GROUP_4_KS_PBS_PKE_TO_BIG_ZKV2_TUNIFORM_2M128.into(),
            "gpu multibit group 4 big pke",
            Device::CudaGpu,
            true,
        );
    }

    // Triggers rerand without KS (V1.6 CPU params have no re_randomization_parameters)
    #[test]
    fn test_xof_key_set_with_cpu_params() {
        run_xof_key_set_test(
            TEST_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_SMALL_ZKV2_TUNIFORM_2M128.into(),
            "gpu with cpu v1.6 params",
            Device::CudaGpu,
            true,
        );
    }

    // Triggers rerand with KS (V1.5 legacy params have dedicated re_randomization_parameters)
    #[test]
    fn test_xof_key_set_legacy_rerand_with_cpu_params() {
        run_xof_key_set_test(
            TEST_LEGACY_RERAND_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_SMALL_ZKV2_TUNIFORM_2M128.into(),
            "gpu with cpu params",
            Device::CudaGpu,
            true,
        );
    }
}

/// Check that expanding a CompressedXofKeySet by first splitting it into a Pk and
/// CompressedServerKey, thus not using the dedicated function for decompression/expansion
/// yields the same thing as using the dedicated expand (used by decompress) method of
/// CompressedXofKeySet
fn test_xof_expansion_is_same_as_classic(key_set: CompressedXofKeySet) {
    let (xof_pk, xof_sk) = key_set.expand();
    let (_seed, cpk, csk) = key_set.into_raw_parts();
    // into_raw_parts syncs the public key tag to match the server key tag
    assert_eq!(cpk.tag(), csk.tag());
    let pk = cpk.decompress();

    let sk = csk.integer_key.expand();

    #[allow(
        clippy::manual_assert,
        reason = "The type does not impl Debug, and if it did, the output would be unreadable"
    )]
    if sk != xof_sk {
        panic!("Expanded server keys are not equal");
    }
    assert_eq!(pk, xof_pk);
}

fn test_xof_key_set(
    compressed_key_set: &CompressedXofKeySet,
    config: Config,
    device: Device,
    cks: &ClientKey,
) {
    let compressed_size_limit = 1 << 32; // 4GB
    let mut data = vec![];
    crate::safe_serialization::safe_serialize(compressed_key_set, &mut data, compressed_size_limit)
        .unwrap();
    let compressed_key_set: CompressedXofKeySet =
        crate::safe_serialization::safe_deserialize(data.as_slice(), compressed_size_limit)
            .unwrap();

    let expected_tag = cks.tag().clone();
    // Test Tagged trait on CompressedXofKeySet
    assert_eq!(compressed_key_set.tag(), &expected_tag);
    {
        let mut compressed_clone = compressed_key_set.clone();
        compressed_clone.tag_mut().set_u64(0xDEAD);
        assert_eq!(compressed_clone.tag().as_u64(), 0xDEAD);
        // Original unchanged
        assert_eq!(compressed_key_set.tag(), &expected_tag);
        // test sync
        let (_seed, cpk, csk) = compressed_clone.into_raw_parts();
        assert_eq!(cpk.tag().as_u64(), 0xDEAD);
        assert_eq!(csk.tag().as_u64(), 0xDEAD);
    }

    assert!(compressed_key_set.is_conformant(&config));

    let cpk = match device {
        Device::Cpu => {
            let key_set = compressed_key_set.decompress().unwrap();
            let size_limit = 1 << 32; // 4GB
            let mut data = vec![];
            crate::safe_serialization::safe_serialize(&key_set, &mut data, size_limit).unwrap();
            let mut key_set: XofKeySet =
                crate::safe_serialization::safe_deserialize(data.as_slice(), size_limit).unwrap();

            assert_eq!(key_set.tag(), &expected_tag);

            key_set.tag_mut().set_u64(0xCAFE);
            assert_eq!(key_set.tag().as_u64(), 0xCAFE);

            let (pk, sk) = key_set.into_raw_parts();
            assert_eq!(pk.tag().as_u64(), 0xCAFE);
            assert_eq!(sk.tag().as_u64(), 0xCAFE);

            assert!(sk.is_conformant(&config.into()));
            set_server_key(sk);
            pk
        }
        #[cfg(feature = "gpu")]
        Device::CudaGpu => {
            let mut key_set = compressed_key_set.decompress_to_gpu().unwrap();
            assert_eq!(key_set.tag(), &expected_tag);

            key_set.tag_mut().set_u64(0xCAFE);
            assert_eq!(key_set.tag().as_u64(), 0xCAFE);

            let (pk, sk) = key_set.into_raw_parts();
            assert_eq!(pk.tag().as_u64(), 0xCAFE);
            assert_eq!(sk.tag().as_u64(), 0xCAFE);

            set_server_key(sk);
            pk
        }
        #[cfg(feature = "hpu")]
        Device::Hpu => {
            panic!("HPU not supported in this test")
        }
    };

    let cpk = &cpk;

    let clear_a = rand::random::<u32>();
    let clear_b = rand::random::<u32>();

    {
        let a = FheUint32::encrypt(clear_a, cks);
        let b = FheUint32::encrypt(clear_b, cks);

        let c = &a * &b;
        let d = &a & &b;

        let c_dec: u32 = c.decrypt(cks);
        let d_dec: u32 = d.decrypt(cks);

        assert_eq!(clear_a.wrapping_mul(clear_b), c_dec);
        assert_eq!(clear_a & clear_b, d_dec);
    }

    for build_packed in [true, false] {
        #[cfg(feature = "gpu")]
        if !build_packed && device == Device::CudaGpu {
            continue;
        }

        let mut builder = CompactCiphertextList::builder(cpk);
        builder.push(clear_a).push(clear_b);
        let list = if build_packed {
            builder.build_packed()
        } else {
            builder.build()
        };

        let expander = list.expand().unwrap();
        let mut a = expander.get::<FheUint32>(0).unwrap().unwrap();
        let mut b = expander.get::<FheUint32>(1).unwrap().unwrap();

        // Test re-randomization
        if config.inner.cpk_re_randomization_params.is_some() {
            // Simulate a 256 bits nonce
            let nonce: [u8; 256 / 8] = core::array::from_fn(|_| rand::random());
            let compact_public_encryption_domain_separator = *b"TFHE_Enc";
            let rerand_domain_separator = *b"TFHE_Rrd";

            let mut re_rand_context = ReRandomizationContext::new(
                rerand_domain_separator,
                // First is the function description, second is a nonce
                [b"FheUint32 bin ops".as_slice(), nonce.as_slice()],
                compact_public_encryption_domain_separator,
            );

            re_rand_context.add_ciphertext(&a);
            re_rand_context.add_ciphertext(&b);

            let mut seed_gen = re_rand_context.finalize();

            match ServerKey::current_server_key_re_randomization_support().unwrap() {
                ReRandomizationSupport::NoSupport => {
                    panic!("This test runs rerand, the current ServerKey does not support it")
                }
                ReRandomizationSupport::LegacyDedicatedCPKWithKeySwitch => {
                    a.re_randomize(
                        ReRandomizationMode::UseLegacyCPKIfNeeded { cpk },
                        seed_gen.next_seed().unwrap(),
                    )
                    .unwrap();
                    b.re_randomize(
                        ReRandomizationMode::UseLegacyCPKIfNeeded { cpk },
                        seed_gen.next_seed().unwrap(),
                    )
                    .unwrap();
                }
                ReRandomizationSupport::DerivedCPKWithoutKeySwitch => {
                    a.re_randomize(
                        ReRandomizationMode::UseAvailableMode,
                        seed_gen.next_seed().unwrap(),
                    )
                    .unwrap();
                    b.re_randomize(
                        ReRandomizationMode::UseAvailableMode,
                        seed_gen.next_seed().unwrap(),
                    )
                    .unwrap();
                }
            }
        }

        let c = &a * &b;
        let d = &a & &b;

        let c_dec: u32 = c.decrypt(cks);
        let d_dec: u32 = d.decrypt(cks);

        assert_eq!(clear_a.wrapping_mul(clear_b), c_dec);
        assert_eq!(clear_a & clear_b, d_dec);

        let ns_c = c.squash_noise().unwrap();
        let ns_c_dec: u32 = ns_c.decrypt(cks);
        assert_eq!(clear_a.wrapping_mul(clear_b), ns_c_dec);

        let ns_d = d.squash_noise().unwrap();
        let ns_d_dec: u32 = ns_d.decrypt(cks);
        assert_eq!(clear_a & clear_b, ns_d_dec);

        let compressed_list = CompressedCiphertextListBuilder::new()
            .push(a)
            .push(b)
            .push(c)
            .push(d)
            .build()
            .unwrap();

        let a: FheUint32 = compressed_list.get(0).unwrap().unwrap();
        let da: u32 = a.decrypt(cks);
        assert_eq!(da, clear_a);
        let b: FheUint32 = compressed_list.get(1).unwrap().unwrap();
        let db: u32 = b.decrypt(cks);
        assert_eq!(db, clear_b);
        let c: FheUint32 = compressed_list.get(2).unwrap().unwrap();
        let dc: u32 = c.decrypt(cks);
        assert_eq!(dc, clear_a.wrapping_mul(clear_b));
        let d: FheUint32 = compressed_list.get(3).unwrap().unwrap();
        let db: u32 = d.decrypt(cks);
        assert_eq!(db, clear_a & clear_b);

        let ns_compressed_list = CompressedSquashedNoiseCiphertextListBuilder::new()
            .push(ns_c)
            .push(ns_d)
            .build()
            .unwrap();

        let ns_c: SquashedNoiseFheUint = ns_compressed_list.get(0).unwrap().unwrap();
        let dc: u32 = ns_c.decrypt(cks);
        assert_eq!(dc, clear_a.wrapping_mul(clear_b));
        let ns_d: SquashedNoiseFheUint = ns_compressed_list.get(1).unwrap().unwrap();
        let db: u32 = ns_d.decrypt(cks);
        assert_eq!(db, clear_a & clear_b);
    }
}