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
// This module contains all the operations and functions used in the sha256 function, implemented
// with homomorphic boolean operations. Both the bitwise operations, which serve as the building
// blocks for other functions, and the adders employ parallel processing techniques.

use rayon::prelude::*;
use std::array;
use tfhe::boolean::prelude::{BinaryBooleanGates, Ciphertext, ServerKey};

// Implementation of a Carry Save Adder, which computes sum and carry sequences very efficiently. We
// then add the final sum and carry values to obtain the result. CSAs are useful to speed up
// sequential additions
pub fn csa(
    a: &[Ciphertext; 32],
    b: &[Ciphertext; 32],
    c: &[Ciphertext; 32],
    sk: &ServerKey,
) -> ([Ciphertext; 32], [Ciphertext; 32]) {
    let (carry, sum) = rayon::join(|| maj(a, b, c, sk), || xor(a, &xor(b, c, sk), sk));

    // perform a left shift by one to discard the carry-out and set the carry-in to 0
    let mut shifted_carry = trivial_bools(&[false; 32], sk);
    for (i, elem) in carry.into_iter().enumerate() {
        if i == 0 {
            continue;
        } else {
            shifted_carry[i - 1] = elem;
        }
    }

    (sum, shifted_carry)
}

pub fn add(
    a: &[Ciphertext; 32],
    b: &[Ciphertext; 32],
    ladner_fischer_opt: bool,
    sk: &ServerKey,
) -> [Ciphertext; 32] {
    let (propagate, generate) = rayon::join(|| xor(a, b, sk), || and(a, b, sk));

    let carry = if ladner_fischer_opt {
        ladner_fischer(&propagate, &generate, sk)
    } else {
        brent_kung(&propagate, &generate, sk)
    };

    xor(&propagate, &carry, sk)
}

// Implementation of the Brent Kung parallel prefix algorithm
// This function computes the carry signals in parallel while minimizing the number of homomorphic
// operations
fn brent_kung(
    propagate: &[Ciphertext; 32],
    generate: &[Ciphertext; 32],
    sk: &ServerKey,
) -> [Ciphertext; 32] {
    let mut propagate = propagate.clone();
    let mut generate = generate.clone();

    for d in 0..5 {
        // first 5 stages
        let stride = 1 << d;

        let indices: Vec<(usize, usize)> = (0..32 - stride)
            .rev()
            .step_by(2 * stride)
            .map(|i| i + 1 - stride)
            .enumerate()
            .collect();

        let updates: Vec<(usize, Ciphertext, Ciphertext)> = indices
            .into_par_iter()
            .map(|(n, index)| {
                let new_p;
                let new_g;

                if n == 0 {
                    // grey cell
                    new_p = propagate[index].clone();
                    new_g = sk.or(
                        &generate[index],
                        &sk.and(&generate[index + stride], &propagate[index]),
                    );
                } else {
                    // black cell
                    new_p = sk.and(&propagate[index], &propagate[index + stride]);
                    new_g = sk.or(
                        &generate[index],
                        &sk.and(&generate[index + stride], &propagate[index]),
                    );
                }

                (index, new_p, new_g)
            })
            .collect();

        for (index, new_p, new_g) in updates {
            propagate[index] = new_p;
            generate[index] = new_g;
        }

        if d == 4 {
            let mut cells = 0;
            for d_2 in 0..4 {
                // last 4 stages
                let stride = 1 << (4 - d_2 - 1);
                cells += 1 << d_2;

                let indices: Vec<(usize, usize)> = (0..cells)
                    .map(|cell| (cell, stride + 2 * stride * cell))
                    .collect();

                let updates: Vec<(usize, Ciphertext)> = indices
                    .into_par_iter()
                    .map(|(_, index)| {
                        let new_g = sk.or(
                            &generate[index],
                            &sk.and(&generate[index + stride], &propagate[index]),
                        );

                        (index, new_g)
                    })
                    .collect();

                for (index, new_g) in updates {
                    generate[index] = new_g;
                }
            }
        }
    }

    let mut carry = trivial_bools(&[false; 32], sk);
    carry[..31].clone_from_slice(&generate[1..(31 + 1)]);

    carry
}

// Implementation of the Ladner Fischer parallel prefix algorithm
// This function may perform better than the previous one when many threads are available as it has
// less stages
fn ladner_fischer(
    propagate: &[Ciphertext; 32],
    generate: &[Ciphertext; 32],
    sk: &ServerKey,
) -> [Ciphertext; 32] {
    let mut propagate = propagate.clone();
    let mut generate = generate.clone();

    for d in 0..5 {
        let stride = 1 << d;

        let indices: Vec<(usize, usize)> = (0..32 - stride)
            .rev()
            .step_by(2 * stride)
            .flat_map(|i| (0..stride).map(move |count| (i, count)))
            .collect();

        let updates: Vec<(usize, Ciphertext, Ciphertext)> = indices
            .into_par_iter()
            .map(|(i, count)| {
                let index = i - count; // current column

                let p = propagate[i + 1].clone(); // propagate from a previous column
                let g = generate[i + 1].clone(); // generate from a previous column
                let new_p;
                let new_g;

                if index < 32 - (2 * stride) {
                    // black cell
                    new_p = sk.and(&propagate[index], &p);
                    new_g = sk.or(&generate[index], &sk.and(&g, &propagate[index]));
                } else {
                    // grey cell
                    new_p = propagate[index].clone();
                    new_g = sk.or(&generate[index], &sk.and(&g, &propagate[index]));
                }
                (index, new_p, new_g)
            })
            .collect();

        for (index, new_p, new_g) in updates {
            propagate[index] = new_p;
            generate[index] = new_g;
        }
    }

    let mut carry = trivial_bools(&[false; 32], sk);
    carry[..31].clone_from_slice(&generate[1..(31 + 1)]);

    carry
}

// 2 (homomorphic) bitwise ops
pub fn sigma0(x: &[Ciphertext; 32], sk: &ServerKey) -> [Ciphertext; 32] {
    let a = rotate_right(x, 7);
    let b = rotate_right(x, 18);
    let c = shift_right(x, 3, sk);
    xor(&xor(&a, &b, sk), &c, sk)
}

pub fn sigma1(x: &[Ciphertext; 32], sk: &ServerKey) -> [Ciphertext; 32] {
    let a = rotate_right(x, 17);
    let b = rotate_right(x, 19);
    let c = shift_right(x, 10, sk);
    xor(&xor(&a, &b, sk), &c, sk)
}

pub fn sigma_upper_case_0(x: &[Ciphertext; 32], sk: &ServerKey) -> [Ciphertext; 32] {
    let a = rotate_right(x, 2);
    let b = rotate_right(x, 13);
    let c = rotate_right(x, 22);
    xor(&xor(&a, &b, sk), &c, sk)
}

pub fn sigma_upper_case_1(x: &[Ciphertext; 32], sk: &ServerKey) -> [Ciphertext; 32] {
    let a = rotate_right(x, 6);
    let b = rotate_right(x, 11);
    let c = rotate_right(x, 25);
    xor(&xor(&a, &b, sk), &c, sk)
}

// 0 bitwise ops
fn rotate_right(x: &[Ciphertext; 32], n: usize) -> [Ciphertext; 32] {
    let mut result = x.clone();
    result.rotate_right(n);
    result
}

fn shift_right(x: &[Ciphertext; 32], n: usize, sk: &ServerKey) -> [Ciphertext; 32] {
    let mut result = x.clone();
    result.rotate_right(n);
    result[..n].fill_with(|| sk.trivial_encrypt(false));
    result
}

// 1 bitwise op
pub fn ch(
    x: &[Ciphertext; 32],
    y: &[Ciphertext; 32],
    z: &[Ciphertext; 32],
    sk: &ServerKey,
) -> [Ciphertext; 32] {
    mux(x, y, z, sk)
}

// 4 bitwise ops
pub fn maj(
    x: &[Ciphertext; 32],
    y: &[Ciphertext; 32],
    z: &[Ciphertext; 32],
    sk: &ServerKey,
) -> [Ciphertext; 32] {
    let (lhs, rhs) = rayon::join(|| and(x, &xor(y, z, sk), sk), || and(y, z, sk));
    xor(&lhs, &rhs, sk)
}

// Parallelized homomorphic bitwise ops
// Building block for most of the previous functions
fn xor(a: &[Ciphertext; 32], b: &[Ciphertext; 32], sk: &ServerKey) -> [Ciphertext; 32] {
    let mut result = a.clone();
    result
        .par_iter_mut()
        .zip(a.par_iter().zip(b.par_iter()))
        .for_each(|(dst, (lhs, rhs))| *dst = sk.xor(lhs, rhs));
    result
}

fn and(a: &[Ciphertext; 32], b: &[Ciphertext; 32], sk: &ServerKey) -> [Ciphertext; 32] {
    let mut result = a.clone();
    result
        .par_iter_mut()
        .zip(a.par_iter().zip(b.par_iter()))
        .for_each(|(dst, (lhs, rhs))| *dst = sk.and(lhs, rhs));
    result
}

fn mux(
    condition: &[Ciphertext; 32],
    then: &[Ciphertext; 32],
    otherwise: &[Ciphertext; 32],
    sk: &ServerKey,
) -> [Ciphertext; 32] {
    let mut result = condition.clone();
    result
        .par_iter_mut()
        .zip(
            condition
                .par_iter()
                .zip(then.par_iter().zip(otherwise.par_iter())),
        )
        .for_each(|(dst, (condition, (then, other)))| *dst = sk.mux(condition, then, other));
    result
}

// Trivial encryption of 32 bools
pub fn trivial_bools(bools: &[bool; 32], sk: &ServerKey) -> [Ciphertext; 32] {
    array::from_fn(|i| sk.trivial_encrypt(bools[i]))
}

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

    fn to_bool_array(arr: [i32; 32]) -> [bool; 32] {
        let mut bool_arr = [false; 32];
        for i in 0..32 {
            if arr[i] == 1 {
                bool_arr[i] = true;
            }
        }
        bool_arr
    }
    fn encrypt(bools: &[bool; 32], ck: &ClientKey) -> [Ciphertext; 32] {
        array::from_fn(|i| ck.encrypt(bools[i]))
    }

    fn decrypt(bools: &[Ciphertext; 32], ck: &ClientKey) -> [bool; 32] {
        array::from_fn(|i| ck.decrypt(&bools[i]))
    }

    #[test]
    fn test_add_modulo_2_32() {
        let (ck, sk) = gen_keys();

        let a = encrypt(
            &to_bool_array([
                0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1,
                1, 0, 0, 1,
            ]),
            &ck,
        );
        let b = encrypt(
            &to_bool_array([
                0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0,
                1, 0, 1, 1,
            ]),
            &ck,
        );
        let c = encrypt(
            &to_bool_array([
                0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0,
                1, 1, 0, 0,
            ]),
            &ck,
        );
        let d = encrypt(
            &to_bool_array([
                0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1,
                1, 0, 0, 0,
            ]),
            &ck,
        );
        let e = encrypt(
            &to_bool_array([
                0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0,
                1, 1, 0, 0,
            ]),
            &ck,
        );

        let (sum, carry) = csa(&c, &d, &e, &sk);
        let (sum, carry) = csa(&b, &sum, &carry, &sk);
        let (sum, carry) = csa(&a, &sum, &carry, &sk);
        let output = add(&sum, &carry, false, &sk);

        let result = decrypt(&output, &ck);
        let expected = to_bool_array([
            0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0,
            1, 0, 0,
        ]);

        assert_eq!(result, expected);
    }

    #[test]
    fn test_sigma0() {
        let (ck, sk) = gen_keys();

        let input = encrypt(
            &to_bool_array([
                0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0,
                1, 1, 1, 1,
            ]),
            &ck,
        );
        let output = sigma0(&input, &sk);
        let result = decrypt(&output, &ck);
        let expected = to_bool_array([
            1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1,
            0, 1, 1,
        ]);

        assert_eq!(result, expected);
    } //the other sigmas are implemented in the same way

    #[test]
    fn test_ch() {
        let (ck, sk) = gen_keys();

        let e = encrypt(
            &to_bool_array([
                0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1,
                1, 1, 1, 1,
            ]),
            &ck,
        );
        let f = encrypt(
            &to_bool_array([
                1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0,
                1, 1, 0, 0,
            ]),
            &ck,
        );
        let g = encrypt(
            &to_bool_array([
                0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0,
                1, 0, 1, 1,
            ]),
            &ck,
        );

        let output = ch(&e, &f, &g, &sk);
        let result = decrypt(&output, &ck);
        let expected = to_bool_array([
            0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1,
            1, 0, 0,
        ]);

        assert_eq!(result, expected);
    }

    #[test]
    fn test_maj() {
        let (ck, sk) = gen_keys();

        let a = encrypt(
            &to_bool_array([
                0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0,
                0, 1, 1, 1,
            ]),
            &ck,
        );
        let b = encrypt(
            &to_bool_array([
                1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0,
                0, 1, 0, 1,
            ]),
            &ck,
        );
        let c = encrypt(
            &to_bool_array([
                0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1,
                0, 0, 1, 0,
            ]),
            &ck,
        );

        let output = maj(&a, &b, &c, &sk);
        let result = decrypt(&output, &ck);
        let expected = to_bool_array([
            0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0,
            1, 1, 1,
        ]);

        assert_eq!(result, expected);
    }
}