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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
use serde::{Deserialize, Serialize};
use tfhe_versionable::Versionize;

use crate::backward_compatibility::kv_store::CompressedKVStoreVersions;
use crate::high_level_api::global_state;
use crate::high_level_api::integers::FheIntegerType;
use crate::high_level_api::keys::InternalServerKey;
use crate::integer::block_decomposition::Decomposable;
use crate::integer::ciphertext::{Compressible, Expandable};
use crate::integer::server_key::{
    CompressedKVStore as CompressedIntegerKVStore, KVStore as IntegerKVStore,
};
use crate::prelude::CastInto;
use crate::{FheBool, IntegerId, ReRandomizationMetadata, Tag};
use std::fmt::Display;

#[derive(Clone)]
enum InnerKVStore<Key, T>
where
    T: FheIntegerType,
{
    Cpu(IntegerKVStore<Key, <T::Id as IntegerId>::InnerCpu>),
}

/// The KVStore is a specialized encrypted HashMap
///
/// * Keys are clear numbers
/// * Values are FheInt or FheUint
///
/// This stores allows to insert, removed, get using clear keys.
/// It also allows to do some operations using encrypted keys.
///
/// To serialize a KVStore it must first be compressed with [KVStore::compress]
///
/// # Tag System
///
/// Ciphertexts inserted into the KVStore will drop their tag.
/// Operations on the KVStore that return a ciphertext will set a tag
/// using the currently set server key.
/// Even operations that do not require FHE operations will require
/// a server key to be set in order to set the tag
#[derive(Clone)]
pub struct KVStore<Key, T>
where
    T: FheIntegerType,
{
    inner: InnerKVStore<Key, T>,
}

impl<Key, T> KVStore<Key, T>
where
    T: FheIntegerType,
{
    /// Creates a new empty `KVStore`.
    pub fn new() -> Self {
        Self {
            inner: InnerKVStore::Cpu(IntegerKVStore::new()),
        }
    }

    /// Returns the number of key-value pairs in the store.
    pub fn len(&self) -> usize {
        match &self.inner {
            InnerKVStore::Cpu(kvstore) => kvstore.len(),
        }
    }

    /// Returns `true` if the store contains no key-value pairs
    pub fn is_empty(&self) -> bool {
        match &self.inner {
            InnerKVStore::Cpu(kvstore) => kvstore.is_empty(),
        }
    }

    /// Inserts a key-value pair.
    ///
    /// Returns the old value if there was any
    pub fn insert_with_clear_key(&mut self, key: Key, value: T) -> Option<T>
    where
        Key: Ord,
    {
        #[allow(unreachable_patterns)]
        global_state::with_internal_keys(|server_key| match (server_key, &mut self.inner) {
            (InternalServerKey::Cpu(cpu_key), InnerKVStore::Cpu(inner_store)) => {
                let inner = inner_store.insert(key, value.into_cpu())?;
                Some(T::from_cpu(
                    inner,
                    cpu_key.tag.clone(),
                    ReRandomizationMetadata::default(),
                ))
            }
            #[cfg(feature = "gpu")]
            (InternalServerKey::Cuda(_cuda_key), _) => {
                panic!("GPU does not support KVStore yet")
            }
            #[cfg(feature = "hpu")]
            (InternalServerKey::Hpu(_device), _) => {
                panic!("HPU does not support KVStore yet")
            }
            _ => panic!("The KVStore's current backend does not match the current key backend"),
        })
    }

    /// Updates the value in a key-value pair.
    ///
    /// Returns the old value if there was any
    /// Returns None if the key had no previous value
    ///
    /// If your key is encrypted see [Self::update]
    ///
    ///
    /// # Note
    ///
    /// Contraty to [Self::insert_with_clear_key], this does not insert the key,value pair
    /// if its not present
    pub fn update_with_clear_key(&mut self, key: &Key, value: T) -> Option<T>
    where
        Key: Ord,
    {
        #[allow(unreachable_patterns)]
        global_state::with_internal_keys(|server_key| match (server_key, &mut self.inner) {
            (InternalServerKey::Cpu(cpu_key), InnerKVStore::Cpu(inner_store)) => {
                inner_store.get_mut(key).map_or_else(
                    || None,
                    |old_value_ref| {
                        let old_value = std::mem::replace(old_value_ref, value.into_cpu());
                        Some(T::from_cpu(
                            old_value,
                            cpu_key.tag.clone(),
                            ReRandomizationMetadata::default(),
                        ))
                    },
                )
            }
            #[cfg(feature = "gpu")]
            (InternalServerKey::Cuda(_cuda_key), _) => {
                panic!("GPU does not support KVStore yet")
            }
            #[cfg(feature = "hpu")]
            (InternalServerKey::Hpu(_device), _) => {
                panic!("HPU does not support KVStore yet")
            }
            _ => panic!("The KVStore's current backend does not match the current key backend"),
        })
    }

    /// Removes a key-value pair.
    ///
    /// Returns Some(_) if the key was present, None otherwise
    ///
    /// # Note
    ///
    /// Even though no FHE computations are done, a server key must
    /// be set when calling this function is order to set the Tag of the resulting ciphertext
    pub fn remove_with_clear_key(&mut self, key: &Key) -> Option<T>
    where
        Key: Ord,
    {
        #[allow(unreachable_patterns)]
        global_state::with_internal_keys(|server_key| match (server_key, &mut self.inner) {
            (InternalServerKey::Cpu(cpu_key), InnerKVStore::Cpu(inner_store)) => {
                let inner = inner_store.remove(key)?;
                Some(T::from_cpu(
                    inner,
                    cpu_key.tag.clone(),
                    ReRandomizationMetadata::default(),
                ))
            }
            #[cfg(feature = "gpu")]
            (InternalServerKey::Cuda(_cuda_key), _) => {
                panic!("GPU does not support KVStore yet")
            }
            #[cfg(feature = "hpu")]
            (InternalServerKey::Hpu(_device), _) => {
                panic!("HPU does not support KVStore yet")
            }
            _ => panic!("The KVStore's current backend does not match the current key backend"),
        })
    }

    /// Returns the value associated to a key.
    ///
    /// Returns Some(_) if the key was present, None otherwise
    ///
    /// If your key is encrypted see [Self::get]
    ///
    /// # Note
    ///
    /// Even though no FHE computations are done, a server key must
    /// be set when calling this function is order to set the Tag of the resulting ciphertext
    pub fn get_with_clear_key(&self, key: &Key) -> Option<T>
    where
        Key: Ord,
    {
        #[allow(unreachable_patterns)]
        global_state::with_internal_keys(|server_key| match (server_key, &self.inner) {
            (InternalServerKey::Cpu(cpu_key), InnerKVStore::Cpu(inner_store)) => {
                let inner = inner_store.get(key)?;
                Some(T::from_cpu(
                    inner.clone(),
                    cpu_key.tag.clone(),
                    ReRandomizationMetadata::default(),
                ))
            }
            #[cfg(feature = "gpu")]
            (InternalServerKey::Cuda(_cuda_key), _) => {
                panic!("GPU does not support KVStore yet")
            }
            #[cfg(feature = "hpu")]
            (InternalServerKey::Hpu(_device), _) => {
                panic!("HPU does not support KVStore yet")
            }
            _ => panic!("The KVStore's current backend does not match the current key backend"),
        })
    }
}

impl<Key, T> Default for KVStore<Key, T>
where
    T: FheIntegerType,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<Key, T> KVStore<Key, T>
where
    Key: Decomposable + CastInto<usize> + Ord,
    T: FheIntegerType,
{
    /// Gets the value corresponding to the encrypted key.
    ///
    /// Returns the encrypted value and an encrypted boolean.
    /// The boolean is an encryption of true if the key was present,
    /// thus the value is meaningful.
    ///
    /// If your key is clear see [Self::get_with_clear_key]
    pub fn get<EK>(&self, encrypted_key: &EK) -> (T, FheBool)
    where
        EK: FheIntegerType,
        EK::Id: IntegerId<
            InnerCpu = <T::Id as IntegerId>::InnerCpu,
            InnerGpu = <T::Id as IntegerId>::InnerGpu,
        >,
    {
        #[allow(unreachable_patterns)]
        global_state::with_internal_keys(|key| match (key, &self.inner) {
            (InternalServerKey::Cpu(cpu_key), InnerKVStore::Cpu(inner_store)) => {
                let (inner_ct, inner_bool) = cpu_key
                    .pbs_key()
                    .kv_store_get(inner_store, &*encrypted_key.on_cpu());
                (
                    T::from_cpu(
                        inner_ct,
                        cpu_key.tag.clone(),
                        ReRandomizationMetadata::default(),
                    ),
                    FheBool::new(
                        inner_bool,
                        cpu_key.tag.clone(),
                        ReRandomizationMetadata::default(),
                    ),
                )
            }
            #[cfg(feature = "gpu")]
            (InternalServerKey::Cuda(_cuda_key), _) => {
                panic!("GPU does not support KVStore yet")
            }
            #[cfg(feature = "hpu")]
            (InternalServerKey::Hpu(_device), _) => {
                panic!("HPU does not support KVStore yet")
            }
            _ => panic!("The KVStore's current backend does not match the current key backend"),
        })
    }

    /// Replaces the value corresponding to the encrypted key.
    ///
    /// i.e. `kvstore[encrypted_value] = new_value`
    ///
    /// The boolean is an encryption of true if the key was present,
    /// thus the value is was replaced.
    ///
    /// If your key is clear see [Self::update_with_clear_key]
    pub fn update<EK>(&mut self, encrypted_key: &EK, new_value: &T) -> FheBool
    where
        EK: FheIntegerType,
        EK::Id: IntegerId<
            InnerCpu = <T::Id as IntegerId>::InnerCpu,
            InnerGpu = <T::Id as IntegerId>::InnerGpu,
        >,
    {
        #[allow(unreachable_patterns)]
        global_state::with_internal_keys(|key| match (key, &mut self.inner) {
            (InternalServerKey::Cpu(cpu_key), InnerKVStore::Cpu(inner_store)) => {
                let inner = cpu_key.pbs_key().kv_store_update(
                    inner_store,
                    &*encrypted_key.on_cpu(),
                    &*new_value.on_cpu(),
                );
                FheBool::new(
                    inner,
                    cpu_key.tag.clone(),
                    ReRandomizationMetadata::default(),
                )
            }
            #[cfg(feature = "gpu")]
            (InternalServerKey::Cuda(_cuda_key), _) => {
                panic!("GPU does not support KVStore yet")
            }
            #[cfg(feature = "hpu")]
            (InternalServerKey::Hpu(_device), _) => {
                panic!("HPU does not support KVStore yet")
            }
            _ => panic!("The KVStore's current backend does not match the current key backend"),
        })
    }

    /// Replaces the value corresponding to the encrypted key, with the
    /// result of applying the function to the current value.
    ///
    /// i.e. `kvstore[encrypted_value] = func(kvstore[encrypted_value])`
    ///
    /// Returns (old_value, new_value, check)
    ///
    /// The `check` boolean is an encryption of true if the key was present,
    /// thus the value is was replaced.
    pub fn map<EK, F>(&mut self, encrypted_key: &EK, func: F) -> (T, T, FheBool)
    where
        EK: FheIntegerType,
        EK::Id: IntegerId<
            InnerCpu = <T::Id as IntegerId>::InnerCpu,
            InnerGpu = <T::Id as IntegerId>::InnerGpu,
        >,
        F: Fn(T) -> T,
    {
        #[allow(unreachable_patterns)]
        global_state::with_internal_keys(|key| match (key, &mut self.inner) {
            (InternalServerKey::Cpu(cpu_key), InnerKVStore::Cpu(inner_store)) => {
                let (inner_old, inner_new, inner_bool) = cpu_key.pbs_key().kv_store_map(
                    inner_store,
                    &*encrypted_key.on_cpu(),
                    |radix| {
                        let wrapped =
                            T::from_cpu(radix, Tag::default(), ReRandomizationMetadata::default());
                        let wrapped_result = func(wrapped);
                        wrapped_result.into_cpu()
                    },
                );
                (
                    T::from_cpu(
                        inner_old,
                        cpu_key.tag.clone(),
                        ReRandomizationMetadata::default(),
                    ),
                    T::from_cpu(
                        inner_new,
                        cpu_key.tag.clone(),
                        ReRandomizationMetadata::default(),
                    ),
                    FheBool::new(
                        inner_bool,
                        cpu_key.tag.clone(),
                        ReRandomizationMetadata::default(),
                    ),
                )
            }
            #[cfg(feature = "gpu")]
            (InternalServerKey::Cuda(_cuda_key), _) => {
                panic!("GPU does not support KVStore yet")
            }
            #[cfg(feature = "hpu")]
            (InternalServerKey::Hpu(_device), _) => {
                panic!("HPU does not support KVStore yet")
            }
            _ => panic!("The KVStore's current backend does not match the current key backend"),
        })
    }

    /// Compressed the KVStore, making it serializable
    pub fn compress(&self) -> crate::Result<CompressedKVStore<Key, T>>
    where
        Key: Copy + Display + Ord,
        <T::Id as IntegerId>::InnerCpu: Compressible + Clone,
    {
        #[allow(unreachable_patterns)]
        global_state::with_internal_keys(|key| match (key, &self.inner) {
            (InternalServerKey::Cpu(cpu_key), InnerKVStore::Cpu(inner_store)) => {
                let comp_key = cpu_key
                    .key
                    .compression_key
                    .as_ref()
                    .ok_or(crate::high_level_api::errors::UninitializedCompressionKey)?;
                let compressed_inner = inner_store.compress(comp_key);
                Ok(CompressedKVStore {
                    inner: compressed_inner,
                })
            }
            #[cfg(feature = "gpu")]
            (InternalServerKey::Cuda(_cuda_key), _) => {
                panic!("GPU does not support KVStore yet")
            }
            #[cfg(feature = "hpu")]
            (InternalServerKey::Hpu(_device), _) => {
                panic!("HPU does not support KVStore yet")
            }
            _ => panic!("The KVStore's current backend does not match the current key backend"),
        })
    }
}

/// Compressed KVStore
///
/// This type is the serializable and deserializable form of a KVStore
#[derive(Serialize, Deserialize, Versionize)]
#[versionize(CompressedKVStoreVersions)]
pub struct CompressedKVStore<Key, Value>
where
    Value: FheIntegerType,
{
    inner: CompressedIntegerKVStore<Key, <Value::Id as IntegerId>::InnerCpu>,
}

macro_rules! impl_named_for_kv_store {
    ($Key:ty) => {
        impl<Id> crate::named::Named for CompressedKVStore<$Key, crate::high_level_api::FheUint<Id>>
        where
            Id: crate::high_level_api::FheUintId,
        {
            const NAME: &'static str = concat!(
                "high_level_api::CompressedKVStore<",
                stringify!($Key),
                ", high_level_api::FheUint>"
            );
        }

        impl<Id> crate::named::Named for CompressedKVStore<$Key, crate::high_level_api::FheInt<Id>>
        where
            Id: crate::high_level_api::FheIntId,
        {
            const NAME: &'static str = concat!(
                "high_level_api::CompressedKVStore<",
                stringify!($Key),
                ", high_level_api::FheInt>"
            );
        }
    };
}

impl_named_for_kv_store!(u8);
impl_named_for_kv_store!(u16);
impl_named_for_kv_store!(u32);
impl_named_for_kv_store!(u64);
impl_named_for_kv_store!(u128);
impl_named_for_kv_store!(i8);
impl_named_for_kv_store!(i16);
impl_named_for_kv_store!(i32);
impl_named_for_kv_store!(i64);
impl_named_for_kv_store!(i128);

impl<Key, Value> CompressedKVStore<Key, Value>
where
    Value: FheIntegerType,
{
    /// Decompressed the KVStore
    ///
    /// Returns an error if:
    /// * A key does not have a corresponding value
    /// * A value does not have the same number of blocks as the others.
    /// * If the requested value type is not compatible with the data stored
    ///
    /// Both these errors indicate corrupted or malformed data
    pub fn decompress(&self) -> crate::Result<KVStore<Key, Value>>
    where
        <Value::Id as IntegerId>::InnerCpu: Expandable,
        Key: Copy + Display + Ord,
    {
        global_state::try_with_internal_keys(|key| match key {
            Some(InternalServerKey::Cpu(cpu_key)) => {
                let decomp_key = cpu_key
                    .key
                    .decompression_key
                    .as_ref()
                    .ok_or(crate::high_level_api::errors::UninitializedDecompressionKey)?;
                let inner_kv_store = self.inner.decompress(decomp_key)?;

                let Some(actual_block_count) = inner_kv_store.blocks_per_radix() else {
                    return Ok(KVStore::new()); // The KVstore was empty
                };

                let expected_block_count = Value::Id::num_blocks(cpu_key.message_modulus());

                if actual_block_count.get() != expected_block_count {
                    return Err(crate::error!("Inconsistent block count in KVStore: expected {expected_block_count} but got {actual_block_count}"));
                }

                Ok(KVStore {
                    inner: InnerKVStore::Cpu(inner_kv_store),
                })
            }
            #[cfg(feature = "gpu")]
            Some(InternalServerKey::Cuda(_cuda_key)) => {
                panic!("Decompressing KVStore to GPU is not implemented yet")
            }
            #[cfg(feature = "hpu")]
            Some(InternalServerKey::Hpu(_device)) => {
                panic!("Decompressing KVStore to HPU is not implemented yet")
            }
            None => Err(crate::high_level_api::errors::UninitializedServerKey.into()),
        })
    }
}

#[cfg(test)]
mod test {
    use crate::core_crypto::prelude::Numeric;
    use crate::high_level_api::kv_store::CompressedKVStore;
    use crate::prelude::*;
    use crate::{ClientKey, FheInt32, FheIntegerType, FheUint32, FheUint64, FheUint8, KVStore};
    use rand::prelude::*;
    use std::collections::BTreeMap;

    fn create_kv_store<K, V, FheType>(
        num_keys: usize,
        ck: &ClientKey,
    ) -> (KVStore<K, FheType>, BTreeMap<K, V>)
    where
        K: Numeric + CastInto<usize> + Ord,
        V: Numeric,
        rand::distributions::Standard:
            rand::distributions::Distribution<K> + rand::distributions::Distribution<V>,
        FheType: FheIntegerType + FheEncrypt<V, ClientKey>,
    {
        assert!((K::MAX).cast_into() >= num_keys);
        let mut rng = rand::thread_rng();

        let mut kv_store = KVStore::new();
        let mut clear_store = BTreeMap::new();
        while kv_store.len() != num_keys {
            let k = rng.gen::<K>();
            let v = rng.gen::<V>();

            let e_v = FheType::encrypt(v, ck);

            let _ = kv_store.insert_with_clear_key(k, e_v);
            let _ = clear_store.insert(k, v);
        }

        assert_eq!(kv_store.len(), clear_store.len());

        (kv_store, clear_store)
    }

    fn kv_store_get_test_case(ck: &ClientKey) {
        let num_keys = 10;
        let num_tests = 10;

        let (kv_store, clear_store) = create_kv_store::<u8, u32, FheUint32>(num_keys, ck);
        let mut rng = rand::thread_rng();

        for _ in 0..num_tests {
            let k = rng.gen::<u8>();
            let e_k = FheUint8::encrypt(k, ck);

            let (e_v, e_is_some) = kv_store.get(&e_k);
            let is_some = e_is_some.decrypt(ck);
            let v: u32 = e_v.decrypt(ck);

            if let Some(expected_value) = clear_store.get(&k) {
                assert_eq!(v, *expected_value);
                assert!(is_some);
            } else {
                assert!(!is_some);
                assert_eq!(v, 0);
            }
        }
    }

    fn kv_store_update_test_case(ck: &ClientKey) {
        let num_keys = 10;
        let num_tests = 10;

        let (mut kv_store, mut clear_store) = create_kv_store::<u8, u32, FheUint32>(num_keys, ck);
        let mut rng = rand::thread_rng();

        for _ in 0..num_tests {
            let k = rng.gen::<u8>();
            let e_k = FheUint8::encrypt(k, ck);

            let new_value = rng.gen::<u32>();
            let e_new_value = FheUint32::encrypt(new_value, ck);

            let e_was_updated = kv_store.update(&e_k, &e_new_value);
            let was_updated = e_was_updated.decrypt(ck);

            let is_contained = clear_store.contains_key(&k);
            if is_contained {
                let _ = clear_store.insert(k, new_value);
            }
            assert_eq!(was_updated, is_contained);
        }

        for (k, expected_v) in clear_store.iter() {
            let e_k = FheUint8::encrypt(*k, ck);

            let (e_v, e_is_some) = kv_store.get(&e_k);
            let is_some = e_is_some.decrypt(ck);
            let v: u32 = e_v.decrypt(ck);
            assert!(is_some);
            assert_eq!(v, *expected_v);
        }
    }

    fn kv_store_map_test_case(ck: &ClientKey) {
        let num_keys = 10;
        let num_tests = 10;

        let (mut kv_store, mut clear_store) = create_kv_store::<u8, u32, FheUint32>(num_keys, ck);
        let mut rng = rand::thread_rng();

        for _ in 0..num_tests {
            let k = rng.gen::<u8>();
            let e_k = FheUint8::encrypt(k, ck);

            let expected_new_value = rng.gen::<u32>();

            let (e_old_value, e_new_value, e_was_updated) =
                kv_store.map(&e_k, |_old| FheUint32::encrypt(expected_new_value, ck));
            let was_updated = e_was_updated.decrypt(ck);
            let new_value: u32 = e_new_value.decrypt(ck);
            let old_value: u32 = e_old_value.decrypt(ck);

            if let Some(expected_old_value) = clear_store.get(&k).copied() {
                assert_eq!(old_value, expected_old_value);
                let _ = clear_store.insert(k, expected_new_value);
                assert_eq!(new_value, expected_new_value);
                assert!(was_updated);
            } else {
                assert!(!was_updated);
            }
        }

        for (k, expected_v) in clear_store.iter() {
            let e_k = FheUint8::encrypt(*k, ck);

            let (e_v, e_is_some) = kv_store.get(&e_k);
            let is_some = e_is_some.decrypt(ck);
            let v: u32 = e_v.decrypt(ck);
            assert!(is_some);
            assert_eq!(v, *expected_v);
        }
    }

    fn kv_store_serialization_test_case(ck: &ClientKey) {
        let num_keys = 10;

        let (kv_store, clear_store) = create_kv_store::<u8, u32, FheUint32>(num_keys, ck);

        let compressed = kv_store.compress().unwrap();

        let mut data = vec![];
        crate::safe_serialization::safe_serialize(&compressed, &mut data, 1 << 30).unwrap();

        // Key type is incorrect
        let maybe_compressed = crate::safe_serialization::safe_deserialize::<
            CompressedKVStore<u16, FheUint32>,
        >(data.as_slice(), 1 << 30);
        // safe_deserialize catch the error
        assert!(maybe_compressed.is_err());

        let maybe_compressed = crate::safe_serialization::safe_deserialize::<
            CompressedKVStore<u8, FheInt32>,
        >(data.as_slice(), 1 << 30);
        assert!(maybe_compressed.is_err());

        // Invalid value types
        let compressed = crate::safe_serialization::safe_deserialize::<
            CompressedKVStore<u8, FheUint8>,
        >(data.as_slice(), 1 << 30)
        .unwrap();
        assert!(compressed.decompress().is_err());

        let compressed = crate::safe_serialization::safe_deserialize::<
            CompressedKVStore<u8, FheUint64>,
        >(data.as_slice(), 1 << 30)
        .unwrap();
        assert!(compressed.decompress().is_err());

        let compressed = crate::safe_serialization::safe_deserialize::<
            CompressedKVStore<u8, FheUint32>,
        >(data.as_slice(), 1 << 30)
        .unwrap();

        let kv_store = compressed.decompress().unwrap();

        for (k, expected_v) in clear_store.iter() {
            let e_k = FheUint8::encrypt(*k, ck);

            let (e_v, e_is_some) = kv_store.get(&e_k);
            let is_some = e_is_some.decrypt(ck);
            let v: u32 = e_v.decrypt(ck);
            assert!(is_some);
            assert_eq!(v, *expected_v);
        }
    }

    mod cpu {
        use crate::shortint::parameters::COMP_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
        use crate::{set_server_key, ConfigBuilder};

        use super::*;

        pub(crate) fn setup_default_cpu() -> ClientKey {
            let config = ConfigBuilder::default()
                .enable_compression(COMP_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128)
                .build();

            let client_key = ClientKey::generate(config);
            let csks = crate::CompressedServerKey::new(&client_key);
            let server_key = csks.decompress();

            set_server_key(server_key);

            client_key
        }

        #[test]
        fn test_kv_store_get() {
            let ck = setup_default_cpu();

            kv_store_get_test_case(&ck);
        }

        #[test]
        fn test_kv_store_update() {
            let ck = setup_default_cpu();

            kv_store_update_test_case(&ck);
        }

        #[test]
        fn test_kv_store_map() {
            let ck = setup_default_cpu();

            kv_store_map_test_case(&ck);
        }

        #[test]
        fn test_kv_store_serialization() {
            let ck = setup_default_cpu();

            kv_store_serialization_test_case(&ck);
        }
    }
}