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
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
use std::ops::RangeInclusive;

use serde::{Deserialize, Serialize};
use tfhe_safe_serialize::{EnumSet, Named};
use tfhe_versionable::Versionize;

use crate::core_crypto::prelude::UnsignedInteger;
use crate::shortint::backward_compatibility::parameters::{
    DedicatedCompactPublicKeyParametersVersions, MetaParametersVersions,
    ReRandomizationConfigurationVersions,
};
use crate::shortint::parameters::{
    Backend, CompactPublicKeyEncryptionParameters, CompressionParameters,
    MetaNoiseSquashingParameters, ReRandomizationParameters, ShortintKeySwitchingParameters,
    SupportedCompactPkeZkScheme,
};
use crate::shortint::{
    AtomicPatternParameters, CarryModulus, EncryptionKeyChoice, MessageModulus,
    MultiBitPBSParameters, PBSParameters,
};

#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize, Versionize)]
#[versionize(DedicatedCompactPublicKeyParametersVersions)]
pub struct DedicatedCompactPublicKeyParameters {
    /// Parameters used by the dedicated compact public key
    pub pke_params: CompactPublicKeyEncryptionParameters,
    /// Parameters used to key switch from the compact public key
    /// parameters to compute parameters
    pub ksk_params: ShortintKeySwitchingParameters,
    /// Parameters to key switch from the compact public key
    /// to rerand state
    pub re_randomization_parameters: Option<ShortintKeySwitchingParameters>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Versionize)]
#[versionize(ReRandomizationConfigurationVersions)]
/// An enum to indicate how the [`MetaParameters`] should resolve [`ReRandomizationParameters`].
pub enum ReRandomizationConfiguration {
    /// Use a provided [`DedicatedCompactPublicKeyParameters`] as long as the
    /// [`ShortintKeySwitchingParameters`] parameters allow to go to the compute parameters under
    /// the correct key. In the KS_PBS case (which is the only supported case) it means going to
    /// ciphertexts encrypted under the large key.
    LegacyDedicatedCompactPublicKeyWithKeySwitch,
    /// [`CompactPublicKeyEncryptionParameters`]
    /// will be derived from the available compute parameters and the corresponding secret key
    /// should correspond to the encryption key of the compute parameters. The parameters are
    /// restricted to the KS_PBS case (encryption under the large key).
    DerivedCompactPublicKeyWithoutKeySwitch,
}

#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize, Versionize)]
#[versionize(MetaParametersVersions)]
pub struct MetaParameters {
    pub backend: Backend,
    /// The parameters used by ciphertext when doing computations
    pub compute_parameters: AtomicPatternParameters,
    /// Parameters when using a dedicated compact public key
    /// (For smaller and more efficient CompactCiphertextList)
    pub dedicated_compact_public_key_parameters: Option<DedicatedCompactPublicKeyParameters>,
    /// Parameters for compression CompressedCiphertextList
    pub compression_parameters: Option<CompressionParameters>,
    /// Parameters for noise squashing
    pub noise_squashing_parameters: Option<MetaNoiseSquashingParameters>,
    /// Configuration to use for re-randomization
    pub rerand_configuration: Option<ReRandomizationConfiguration>,
}

impl Named for MetaParameters {
    const NAME: &str = "shortint::MetaParameters";
}

impl MetaParameters {
    pub fn noise_distribution_kind(&self) -> NoiseDistributionKind {
        match self.compute_parameters {
            AtomicPatternParameters::Standard(pbsparameters) => match pbsparameters {
                PBSParameters::PBS(pbs) => pbs.lwe_noise_distribution.kind(),
                PBSParameters::MultiBitPBS(multi_bit_pbs) => {
                    multi_bit_pbs.lwe_noise_distribution.kind()
                }
            },
            AtomicPatternParameters::KeySwitch32(key_switch32_pbsparameters) => {
                key_switch32_pbsparameters.lwe_noise_distribution.kind()
            }
        }
    }

    pub fn failure_probability(&self) -> Log2PFail {
        Log2PFail(self.compute_parameters.log2_p_fail())
    }

    pub fn rerandomization_parameters(&self) -> Option<ReRandomizationParameters> {
        match (
            self.rerand_configuration,
            self.dedicated_compact_public_key_parameters,
        ) {
            (
                Some(ReRandomizationConfiguration::LegacyDedicatedCompactPublicKeyWithKeySwitch),
                Some(DedicatedCompactPublicKeyParameters {
                    pke_params: _,
                    ksk_params: _,
                    re_randomization_parameters: Some(re_randomization_parameters),
                }),
            ) => Some(ReRandomizationParameters::LegacyDedicatedCPKWithKeySwitch {
                rerand_ksk_params: re_randomization_parameters,
            }),
            // Irrespective of the presence of dedicated CPK params if we ask for derived CPK for
            // rerand we should generate one
            (Some(ReRandomizationConfiguration::DerivedCompactPublicKeyWithoutKeySwitch), _) => {
                Some(ReRandomizationParameters::DerivedCPKWithoutKeySwitch)
            }
            _ => None,
        }
    }

    const fn dedicated_cpk_is_valid_has_no_rerand(&self) -> bool {
        let Some(params) = self.dedicated_compact_public_key_parameters else {
            // No params is valid
            return true;
        };
        let pke_valid = params.pke_params.is_valid();
        pke_valid && params.re_randomization_parameters.is_none()
    }

    pub const fn is_valid(&self) -> bool {
        if let Some(rerand_configuration) = self.rerand_configuration {
            match rerand_configuration {
                ReRandomizationConfiguration::LegacyDedicatedCompactPublicKeyWithKeySwitch => {
                    let Some(params) = self.dedicated_compact_public_key_parameters else {
                        // we need params in the legacy case
                        return false;
                    };

                    let pke_valid = params.pke_params.is_valid();
                    // Legacy case, KSK needs to be present and target the big key for rerand
                    match params.re_randomization_parameters {
                        Some(rerand_ksk) => {
                            pke_valid
                                && matches!(rerand_ksk.destination_key, EncryptionKeyChoice::Big)
                        }
                        None => false,
                    }
                }
                ReRandomizationConfiguration::DerivedCompactPublicKeyWithoutKeySwitch => {
                    let pke_params =
                        CompactPublicKeyEncryptionParameters::from_shortint_parameter_set(
                            crate::shortint::ShortintParameterSet::from_atomic_pattern_params(
                                self.compute_parameters,
                            ),
                        );
                    // need to match to be const
                    let derived_params_are_ok = match pke_params {
                        Ok(pke_params) => pke_params.is_valid(),
                        Err(_) => return false,
                    };

                    derived_params_are_ok && self.dedicated_cpk_is_valid_has_no_rerand()
                }
            }
        } else {
            // No rerand config, check pke is valid and that there is no legacy rerand params
            self.dedicated_cpk_is_valid_has_no_rerand()
        }
    }

    pub const fn validate(self) -> Self {
        if self.is_valid() {
            return self;
        }

        panic!("Invalid MetaParameters",);
    }
}

/// Represents the type of noise distribution used in cryptographic operations.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum NoiseDistributionKind {
    Gaussian = 0,
    TUniform = 1,
}

impl From<NoiseDistributionKind> for usize {
    fn from(value: NoiseDistributionKind) -> Self {
        match value {
            NoiseDistributionKind::Gaussian => 0,
            NoiseDistributionKind::TUniform => 1,
        }
    }
}

/// Struct to express the allowed noise distribution kinds for parameter selection.
///
/// This struct is used to specify which [`NoiseDistributionKind`]s are acceptable
/// when searching for compatible cryptographic parameters.
#[derive(Debug, Copy, Clone)]
pub struct NoiseDistributionChoice(EnumSet<NoiseDistributionKind>);

impl NoiseDistributionChoice {
    /// Creates a new empty choice, i.e. no distributions are allowed.
    ///
    /// Starting point for building a custom choice by then [Self::allow] noise distributions.
    pub fn new() -> Self {
        Self(EnumSet::new())
    }

    /// Creates new choice that allows all noise distributions.
    pub fn allow_all() -> Self {
        Self::new()
            .allow(NoiseDistributionKind::Gaussian)
            .allow(NoiseDistributionKind::TUniform)
    }

    /// Adds a noise distribution kind to the choice.
    ///
    /// `kind` will be allowed
    pub fn allow(mut self, kind: NoiseDistributionKind) -> Self {
        self.0.insert(kind);
        self
    }

    /// Removes a noise distribution kind from the choice.
    ///
    /// `kind` won't be allowed
    pub fn deny(mut self, kind: NoiseDistributionKind) -> Self {
        self.0.remove(kind);
        self
    }

    fn is_compatible(&self, params: &MetaParameters) -> bool {
        self.0.contains(params.noise_distribution_kind())
    }
}

impl Default for NoiseDistributionChoice {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: UnsignedInteger> super::DynamicDistribution<T> {
    fn kind(&self) -> NoiseDistributionKind {
        match self {
            Self::Gaussian(_) => NoiseDistributionKind::Gaussian,
            Self::TUniform(_) => NoiseDistributionKind::TUniform,
        }
    }
}

/// Represents a constraint on a value
#[derive(Debug)]
pub enum Constraint<T> {
    /// The value must be less than (<) the specified constraint
    LessThan(T),
    /// The value must be less than or equal (<=) tothe specified constraint
    LessThanOrEqual(T),
    /// The value must be greater than (>) the specified constraint
    GreaterThan(T),
    /// The value must be greater than or equal (>=) tothe specified constraint
    GreaterThanOrEqual(T),
    /// The value must be equal to the specified constraint
    Equal(T),
    /// The value must be within the given range (min..=max)
    Within(RangeInclusive<T>),
}

impl<T> Constraint<T>
where
    T: PartialOrd + PartialEq,
{
    fn is_compatible(&self, value: &T) -> bool {
        match self {
            Self::LessThan(v) => value < v,
            Self::LessThanOrEqual(v) => value <= v,
            Self::GreaterThan(v) => value > v,
            Self::GreaterThanOrEqual(v) => value >= v,
            Self::Equal(v) => value == v,
            Self::Within(range) => range.contains(value),
        }
    }
}

/// Represents the failure probability in logarithmic scale.
///
/// Log2PFail(-x) = failure probability of 2^-128
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
pub struct Log2PFail(pub f64);

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Version(pub u8, pub u8);

impl Version {
    pub fn major(self) -> u8 {
        self.0
    }
    pub fn minor(self) -> u8 {
        self.1
    }

    pub fn current() -> Self {
        let major = env!("CARGO_PKG_VERSION_MAJOR")
            .parse::<u8>()
            .expect("Failed to parse major version");
        let minor = env!("CARGO_PKG_VERSION_MINOR")
            .parse::<u8>()
            .expect("Failed to parse minor version");
        Self(major, minor)
    }
}

/// Allows specification of constraints for the multi-bit PBS
pub struct MultiBitPBSChoice {
    pub(crate) grouping_factor: Constraint<usize>,
}

impl MultiBitPBSChoice {
    /// Creates a new choice with the given `grouping_factor`
    pub fn new(grouping_factor: Constraint<usize>) -> Self {
        Self { grouping_factor }
    }

    fn is_compatible(&self, params: &MultiBitPBSParameters) -> bool {
        self.grouping_factor
            .is_compatible(&params.grouping_factor.0)
    }
}

/// Choices for the AtomicPattern
///
/// 3 Atomic Patterns are available
///
/// * Classic PBS
/// * Multi-Bit PBS
/// * Keyswitch 32-bit
pub struct AtomicPatternChoice {
    classical: bool,
    multibit: Option<MultiBitPBSChoice>,
    keyswitch32: bool,
}

impl AtomicPatternChoice {
    /// Creates a choice which will not allow any atomic pattern
    pub fn new() -> Self {
        Self {
            classical: false,
            multibit: None,
            keyswitch32: false,
        }
    }

    /// Sets the possible choice for classic PBS
    pub fn classic_pbs(mut self, allowed: bool) -> Self {
        self.classical = allowed;
        self
    }

    /// Sets the possible choice for multi-bit PBS
    pub fn multi_bit_pbs(mut self, constraints: Option<MultiBitPBSChoice>) -> Self {
        self.multibit = constraints;
        self
    }

    /// Sets the choice for Keyswitch32
    pub fn keyswitch32(mut self, allowed: bool) -> Self {
        self.keyswitch32 = allowed;
        self
    }

    fn is_compatible(&self, ap: &AtomicPatternParameters) -> bool {
        match ap {
            AtomicPatternParameters::Standard(pbs_params) => match pbs_params {
                PBSParameters::PBS(_) => self.classical,
                PBSParameters::MultiBitPBS(multi_bit_params) => self
                    .multibit
                    .as_ref()
                    .is_some_and(|constraints| constraints.is_compatible(multi_bit_params)),
            },
            AtomicPatternParameters::KeySwitch32(_) => self.keyswitch32,
        }
    }

    fn default_for_device(device: Backend) -> Self {
        match device {
            Backend::Cpu => Self::default_cpu(),
            Backend::CudaGpu => Self::default_gpu(),
        }
    }

    fn default_cpu() -> Self {
        Self {
            classical: true,
            multibit: None,
            keyswitch32: false,
        }
    }

    fn default_gpu() -> Self {
        Self {
            classical: false,
            multibit: Some(MultiBitPBSChoice::new(Constraint::LessThanOrEqual(4))),
            keyswitch32: false,
        }
    }
}

impl Default for AtomicPatternChoice {
    fn default() -> Self {
        Self::new()
    }
}

/// Constraints for the Zero-Knowledge proofs used within Compact Public Encryption
#[derive(Copy, Clone, Debug)]
pub struct CompactPkeZkSchemeChoice(EnumSet<SupportedCompactPkeZkScheme>);

impl CompactPkeZkSchemeChoice {
    pub fn new() -> Self {
        Self(EnumSet::new())
    }

    pub fn not_used() -> Self {
        Self::new().allow(SupportedCompactPkeZkScheme::ZkNotSupported)
    }

    pub fn allow_all() -> Self {
        Self::new()
            .allow(SupportedCompactPkeZkScheme::V1)
            .allow(SupportedCompactPkeZkScheme::V2)
    }

    pub fn allow(mut self, v: SupportedCompactPkeZkScheme) -> Self {
        self.0.insert(v);
        self
    }

    pub fn deny(mut self, v: SupportedCompactPkeZkScheme) -> Self {
        self.0.remove(v);
        self
    }

    fn is_compatible(&self, v: SupportedCompactPkeZkScheme) -> bool {
        if self.0.contains(SupportedCompactPkeZkScheme::ZkNotSupported) {
            true
        } else {
            self.0.contains(v)
        }
    }
}

impl Default for CompactPkeZkSchemeChoice {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Copy, Clone, Debug)]
pub struct PkeKeyswitchTargetChoice(EnumSet<EncryptionKeyChoice>);

impl PkeKeyswitchTargetChoice {
    pub fn new() -> Self {
        Self(EnumSet::new())
    }

    pub fn allow_all() -> Self {
        Self::new()
            .allow(EncryptionKeyChoice::Big)
            .allow(EncryptionKeyChoice::Small)
    }

    pub fn allow(mut self, v: EncryptionKeyChoice) -> Self {
        self.0.insert(v);
        self
    }

    pub fn deny(mut self, v: EncryptionKeyChoice) -> Self {
        self.0.remove(v);
        self
    }

    fn is_compatible(&self, v: EncryptionKeyChoice) -> bool {
        self.0.contains(v)
    }
}

impl Default for PkeKeyswitchTargetChoice {
    fn default() -> Self {
        Self::new()
    }
}

/// Constraints for the dedicated compact public key
pub struct DedicatedPublicKeyChoice {
    zk_scheme: CompactPkeZkSchemeChoice,
    pke_keyswitch_target: PkeKeyswitchTargetChoice,
}

impl DedicatedPublicKeyChoice {
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the Zero-Knowledge scheme constraints
    pub fn with_zk_scheme(mut self, zk_scheme: CompactPkeZkSchemeChoice) -> Self {
        self.zk_scheme = zk_scheme;
        self
    }

    /// Sets the keyswitch constraints scheme constraints
    pub fn with_pke_switch(mut self, pke_switch: PkeKeyswitchTargetChoice) -> Self {
        self.pke_keyswitch_target = pke_switch;
        self
    }

    fn is_compatible(&self, dedicated_pk_params: &DedicatedCompactPublicKeyParameters) -> bool {
        self.pke_keyswitch_target
            .is_compatible(dedicated_pk_params.ksk_params.destination_key)
            && self
                .zk_scheme
                .is_compatible(dedicated_pk_params.pke_params.zk_scheme)
    }
}

impl Default for DedicatedPublicKeyChoice {
    fn default() -> Self {
        Self {
            zk_scheme: CompactPkeZkSchemeChoice::allow_all(),
            pke_keyswitch_target: PkeKeyswitchTargetChoice::allow_all(),
        }
    }
}

/// Choices for the noise squashing
#[derive(Copy, Clone, Debug)]
pub enum NoiseSquashingChoice {
    /// Noise squashing required, with or without compression
    Yes { with_compression: bool },
    /// No noise squashing required
    No,
}

impl NoiseSquashingChoice {
    fn is_compatible(self, params: Option<&MetaNoiseSquashingParameters>) -> bool {
        match (self, params) {
            (Self::Yes { .. }, None) => false,
            (Self::Yes { with_compression }, Some(params)) => {
                params.compression_parameters.is_some() == with_compression
            }
            (Self::No, None | Some(_)) => true,
        }
    }
}

/// Choices for the re-randomization
#[derive(Copy, Clone, Debug)]
pub enum ReRandomizationChoice {
    /// Re-rand with legacy technique
    YesWithLegacyTechnique,
    /// Re-rand wit new technique
    YesWithoutKeySwitch,
    /// No re-rand
    No,
}

impl ReRandomizationChoice {
    fn is_compatible(self, parameters: &MetaParameters) -> bool {
        match self {
            Self::YesWithLegacyTechnique => parameters
                .dedicated_compact_public_key_parameters
                .is_some_and(|p| p.re_randomization_parameters.is_some()),
            Self::YesWithoutKeySwitch => {
                CompactPublicKeyEncryptionParameters::try_from(parameters.compute_parameters)
                    .is_ok_and(|p| p.is_valid())
            }
            Self::No => true,
        }
    }
}

const KNOWN_PARAMETERS: [(Version, &[(&MetaParameters, &str)]); 3] = [
    (Version(1, 4), &super::v1_4::VEC_ALL_META_PARAMETERS),
    (Version(1, 5), &super::v1_5::VEC_ALL_META_PARAMETERS),
    (Version(1, 6), &super::v1_6::VEC_ALL_META_PARAMETERS),
];

/// Struct that allows to search for known parameters of TFHE-RS given some
/// constraints/choices.
///
/// # Note
///
/// Only parameters starting from version 1.4 can be found
pub struct MetaParametersFinder {
    msg_modulus: MessageModulus,
    carry_modulus: CarryModulus,
    failure_probability: Constraint<Log2PFail>,
    version: Version,
    backend: Backend,
    atomic_pattern_choice: AtomicPatternChoice,
    noise_distribution: NoiseDistributionChoice,
    dedicated_compact_public_key_choice: Option<DedicatedPublicKeyChoice>,
    use_compression: bool,
    noise_squashing_choice: NoiseSquashingChoice,
    re_randomization_choice: ReRandomizationChoice,
}

impl MetaParametersFinder {
    /// Creates a finder with the given pfail constraint, version and target backend
    ///
    /// * The default message and carry modulus are both 2^2
    /// * The atomic pattern constraints depends on the `backend`
    /// * No other extra 'features' like compression, dedicated public key encryption, noise
    ///   squashing are 'enabled'
    pub fn new(pfail: Constraint<Log2PFail>, backend: Backend) -> Self {
        Self {
            msg_modulus: MessageModulus(4),
            carry_modulus: CarryModulus(4),
            failure_probability: pfail,
            version: Version::current(),
            backend,
            atomic_pattern_choice: AtomicPatternChoice::default_for_device(backend),
            dedicated_compact_public_key_choice: None,
            use_compression: false,
            noise_squashing_choice: NoiseSquashingChoice::No,
            noise_distribution: NoiseDistributionChoice::allow_all(),
            re_randomization_choice: ReRandomizationChoice::No,
        }
    }

    pub fn with_version(mut self, version: Version) -> Self {
        self.version = version;
        self
    }

    /// Sets the noise distribution choice
    pub const fn with_noise_distribution(
        mut self,
        noise_distribution: NoiseDistributionChoice,
    ) -> Self {
        self.noise_distribution = noise_distribution;
        self
    }

    /// Sets the atomic pattern choice
    pub const fn with_atomic_pattern(mut self, atomic_pattern_choice: AtomicPatternChoice) -> Self {
        self.atomic_pattern_choice = atomic_pattern_choice;
        self
    }

    /// Sets the dedicated compact public key choice
    pub const fn with_dedicated_compact_public_key(
        mut self,
        choice: Option<DedicatedPublicKeyChoice>,
    ) -> Self {
        self.dedicated_compact_public_key_choice = choice;
        self
    }

    /// Sets whether compression is desired
    pub const fn with_compression(mut self, enabled: bool) -> Self {
        self.use_compression = enabled;
        self
    }

    /// Sets the noise squashing choice
    pub const fn with_noise_squashing(mut self, choice: NoiseSquashingChoice) -> Self {
        self.noise_squashing_choice = choice;
        self
    }

    /// Sets the block modulus
    ///
    /// Only MessageModulus is required as MessageModulus == CarryModulus is forced
    pub const fn with_block_modulus(mut self, message_modulus: MessageModulus) -> Self {
        self.msg_modulus = message_modulus;
        self.carry_modulus = CarryModulus(message_modulus.0);
        self
    }

    pub const fn with_re_randomization(mut self, choice: ReRandomizationChoice) -> Self {
        self.re_randomization_choice = choice;
        self
    }

    /// Checks if the meta parameter is compatible with the choices of the finder
    ///
    /// A parameter that has more capabilities (e.g. compression), when the user did not ask for
    /// compression is deemed compatible because we can remove the compression params from the
    /// struct.
    fn is_compatible(&self, parameters: &MetaParameters) -> bool {
        if self.backend != parameters.backend {
            return false;
        }

        if self.msg_modulus != parameters.compute_parameters.message_modulus()
            || self.carry_modulus != parameters.compute_parameters.carry_modulus()
        {
            return false;
        }

        if !self
            .failure_probability
            .is_compatible(&parameters.failure_probability())
        {
            return false;
        }

        if !self.noise_distribution.is_compatible(parameters) {
            return false;
        }

        if !self
            .atomic_pattern_choice
            .is_compatible(&parameters.compute_parameters)
        {
            return false;
        }

        match (
            self.dedicated_compact_public_key_choice.as_ref(),
            &parameters.dedicated_compact_public_key_parameters,
        ) {
            (None, None | Some(_)) => {}
            (Some(_), None) => return false,
            (Some(choice), Some(params)) => {
                if !choice.is_compatible(params) {
                    return false;
                }
            }
        }

        if !self.re_randomization_choice.is_compatible(parameters) {
            return false;
        }

        if self.use_compression && parameters.compression_parameters.is_none() {
            return false;
        }

        if !self
            .noise_squashing_choice
            .is_compatible(parameters.noise_squashing_parameters.as_ref())
        {
            return false;
        }

        true
    }

    /// Returns None if the parameters are not compatible
    /// Returns Some(_) if the parameters are compatible
    ///     The returned params may come from more 'capable' parameters
    ///     where unnecessary params were removed
    fn fit(&self, parameters: &MetaParameters) -> Option<MetaParameters> {
        if self.is_compatible(parameters) {
            let mut result = *parameters;

            match self.re_randomization_choice {
                ReRandomizationChoice::YesWithLegacyTechnique => (),
                ReRandomizationChoice::YesWithoutKeySwitch => (),
                ReRandomizationChoice::No => {
                    result.rerand_configuration = None;
                }
            }

            if self.dedicated_compact_public_key_choice.is_some() {
                // There is a CPK choice
                if !matches!(
                    self.re_randomization_choice,
                    ReRandomizationChoice::YesWithLegacyTechnique
                ) {
                    // Remove the legacy re_randomization_parameters if we did not ask for a legacy
                    // rerand
                    if let Some(pke_params) =
                        result.dedicated_compact_public_key_parameters.as_mut()
                    {
                        pke_params.re_randomization_parameters = None;
                    }
                }
            } else {
                // There is no CPK choice
                // Nuke CPK params only if we did not ask for ReRand with legacy params
                if !matches!(
                    self.re_randomization_choice,
                    ReRandomizationChoice::YesWithLegacyTechnique
                ) {
                    result.dedicated_compact_public_key_parameters = None;
                }
            }

            if !self.use_compression {
                result.compression_parameters = None;
            }

            match self.noise_squashing_choice {
                NoiseSquashingChoice::Yes { with_compression } => {
                    if !with_compression {
                        if let Some(ns_params) = result.noise_squashing_parameters.as_mut() {
                            ns_params.compression_parameters.take();
                        }
                    }
                }
                NoiseSquashingChoice::No => result.noise_squashing_parameters = None,
            }

            Some(result)
        } else {
            None
        }
    }

    /// Returns all known meta parameter that satisfy the choices
    pub fn find_all(&self) -> Vec<MetaParameters> {
        self.named_find_all().into_iter().map(|(p, _)| p).collect()
    }

    /// Tries to find parameters that matches the constraints/choices
    ///
    /// Returns Some(_) if at least 1 compatible parameter was found,
    /// None otherwise
    ///
    /// If more than one parameter is found, this function will apply its
    /// own set of rule to select one of them:
    /// * The parameter with highest pfail is prioritized
    /// * CPU will favor classical PBS, with TUniform
    /// * GPU will favor multi-bit PBS, with TUniform
    /// * ZKV2 is prioritized
    pub fn find(&self) -> Option<MetaParameters> {
        let mut candidates = self.named_find_all();

        if candidates.is_empty() {
            return None;
        }

        if candidates.len() == 1 {
            return candidates.pop().map(|(param, _)| param);
        }

        fn filter_candidates(
            candidates: Vec<(MetaParameters, &str)>,
            filter: impl Fn(&(MetaParameters, &str)) -> bool,
        ) -> Vec<(MetaParameters, &str)> {
            let filtered = candidates
                .iter()
                .copied()
                .filter(filter)
                .collect::<Vec<_>>();

            // The filter keeps elements, based on what tfhe-rs sees as better default
            // However, it's possible, that the input candidates list does not include
            // anything that matches the filter
            // e.g. the use selected MultiBitPBS on CPU, but our cpu filter prefers ClassicPBS
            // therefor nothing will match, so we return the original list instead
            if filtered.is_empty() {
                candidates
            } else {
                filtered
            }
        }

        let candidates = filter_candidates(candidates, |(params, _)| {
            if let Some(pke_params) = params.dedicated_compact_public_key_parameters {
                return pke_params.pke_params.zk_scheme == SupportedCompactPkeZkScheme::V2;
            }
            true
        });

        let mut candidates = match self.backend {
            // On CPU we prefer Classical PBS with TUniform
            Backend::Cpu => filter_candidates(candidates, |(params, _)| {
                matches!(
                    params.compute_parameters,
                    AtomicPatternParameters::Standard(PBSParameters::PBS(_))
                ) && params.noise_distribution_kind() == NoiseDistributionKind::TUniform
            }),
            // On GPU we prefer MultiBit PBS with TUniform
            Backend::CudaGpu => filter_candidates(candidates, |(params, _)| {
                matches!(
                    params.compute_parameters,
                    AtomicPatternParameters::Standard(PBSParameters::MultiBitPBS(_))
                ) && params.noise_distribution_kind() == NoiseDistributionKind::TUniform
            }),
        };

        // highest failure probability is the last element,
        // and higher failure probability means better performance
        //
        // Since pfails are negative e.g: -128, -40 for 2^-128 and 2^-40
        // the closest pfail to the constraint is the last one
        candidates.sort_by(|(a, _), (b, _)| {
            a.failure_probability()
                .partial_cmp(&b.failure_probability())
                .unwrap()
        });

        candidates.last().copied().map(|(params, _)| params)
    }

    /// Returns all known meta parameter that satisfy the choices
    ///
    /// This also returns the name of the original params, as it could help to make
    /// debugging easier
    fn named_find_all(&self) -> Vec<(MetaParameters, &'static str)> {
        let mut candidates = Vec::new();

        for (version, parameter_list) in KNOWN_PARAMETERS.iter() {
            if *version != self.version {
                continue; // Skip parameters from different versions
            }

            for (parameters, name) in *parameter_list {
                if let Some(params) = self.fit(parameters) {
                    candidates.push((params, *name));
                }
            }
        }

        candidates
    }
}

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

    #[test]
    fn test_parameter_finder() {
        {
            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-64.0)),
                Backend::Cpu,
            )
            .with_compression(true)
            .with_noise_squashing(NoiseSquashingChoice::Yes {
                with_compression: true,
            })
            .with_version(Version(1, 4));

            let params = finder.find();

            let mut expected =
                super::super::v1_4::meta::cpu::V1_4_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_BIG_ZKV1_TUNIFORM_2M128;
            expected.dedicated_compact_public_key_parameters = None;
            expected.rerand_configuration = None;
            assert_eq!(params, Some(expected));

            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-64.0)),
                Backend::Cpu,
            )
            .with_version(Version(1, 4))
            .with_atomic_pattern(AtomicPatternChoice::new().classic_pbs(true))
            .with_compression(true)
            .with_noise_squashing(NoiseSquashingChoice::Yes {
                with_compression: true,
            });
            let params = finder.find();
            assert_eq!(params.unwrap(), expected);
        }

        {
            // Try to find multi-bit params for CPU
            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-40.0)),
                Backend::Cpu,
            )
            .with_version(Version(1, 4))
            .with_atomic_pattern(
                AtomicPatternChoice::new()
                    .multi_bit_pbs(Some(MultiBitPBSChoice::new(Constraint::LessThanOrEqual(4)))),
            );
            let params = finder.find();
            assert_eq!(
                params,
                Some(super::super::v1_4::meta::cpu::V1_4_META_PARAM_CPU_2_2_MULTI_BIT_GROUP_4_KS_PBS_GAUSSIAN_2M40)
            );

            // Try to find multi-bit params for GPU
            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-40.0)),
                Backend::CudaGpu,
            )
            .with_version(Version(1, 4))
            .with_atomic_pattern(
                AtomicPatternChoice::new()
                    .multi_bit_pbs(Some(MultiBitPBSChoice::new(Constraint::LessThanOrEqual(4)))),
            );
            let params = finder.find();

            let mut expected =
                super::super::v1_4::meta::gpu::V1_4_META_PARAM_GPU_2_2_MULTI_BIT_GROUP_3_KS_PBS_TUNIFORM_2M40;
            expected.dedicated_compact_public_key_parameters = None;

            assert_eq!(params, Some(expected));
        }
    }
    #[test]
    fn test_parameter_finder_dedicated_pke() {
        {
            // Select BIG, and dont care about ZK
            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-64.0)),
                Backend::Cpu,
            )
            .with_version(Version(1, 4))
            .with_dedicated_compact_public_key(Some(
                DedicatedPublicKeyChoice::new()
                    .with_zk_scheme(CompactPkeZkSchemeChoice::not_used())
                    .with_pke_switch(
                        PkeKeyswitchTargetChoice::new().allow(EncryptionKeyChoice::Big),
                    ),
            ));

            let params = finder.find();

            let mut expected =
                super::super::v1_4::meta::cpu::V1_4_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_BIG_ZKV2_TUNIFORM_2M128;
            expected.compression_parameters = None;
            expected.noise_squashing_parameters = None;
            expected
                .dedicated_compact_public_key_parameters
                .as_mut()
                .unwrap()
                .re_randomization_parameters = None;
            expected.rerand_configuration = None;
            assert_eq!(params, Some(expected));

            // Select SMALL, and dont care about ZK
            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-64.0)),
                Backend::Cpu,
            )
            .with_version(Version(1, 4))
            .with_dedicated_compact_public_key(Some(
                DedicatedPublicKeyChoice::new()
                    .with_zk_scheme(CompactPkeZkSchemeChoice::not_used())
                    .with_pke_switch(
                        PkeKeyswitchTargetChoice::new().allow(EncryptionKeyChoice::Small),
                    ),
            ))
            .with_re_randomization(ReRandomizationChoice::YesWithLegacyTechnique);

            let params = finder.find();

            let mut expected =
                super::super::v1_4::meta::cpu::V1_4_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_SMALL_ZKV2_TUNIFORM_2M128;
            expected.compression_parameters = None;
            expected.noise_squashing_parameters = None;
            assert_eq!(params, Some(expected));
        }
    }

    #[test]
    fn test_parameter_finder_ks32() {
        let finder =
            MetaParametersFinder::new(Constraint::LessThanOrEqual(Log2PFail(-64.0)), Backend::Cpu)
                .with_version(Version(1, 4))
                .with_atomic_pattern(AtomicPatternChoice::new().keyswitch32(true));

        let params = finder.find();

        let expected =
            super::super::v1_4::meta::cpu::V1_4_META_PARAM_CPU_2_2_KS32_PBS_TUNIFORM_2M128;

        assert_eq!(params, Some(expected));
    }

    #[test]
    fn test_parameter_finder_rerand() {
        {
            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-64.0)),
                Backend::Cpu,
            )
            .with_compression(true)
            .with_noise_squashing(NoiseSquashingChoice::Yes {
                with_compression: true,
            })
            .with_version(Version(1, 6))
            .with_re_randomization(ReRandomizationChoice::YesWithLegacyTechnique);

            let params = finder.find();

            assert_eq!(params, None);
        }

        {
            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-64.0)),
                Backend::Cpu,
            )
            .with_compression(true)
            .with_noise_squashing(NoiseSquashingChoice::Yes {
                with_compression: true,
            })
            .with_version(Version(1, 5))
            .with_re_randomization(ReRandomizationChoice::YesWithLegacyTechnique);

            let params = finder.find();

            let expected =
                super::super::v1_5::meta::cpu::V1_5_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_BIG_ZKV2_TUNIFORM_2M128;
            assert_eq!(params, Some(expected));
        }

        {
            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-64.0)),
                Backend::Cpu,
            )
            .with_compression(true)
            .with_noise_squashing(NoiseSquashingChoice::Yes {
                with_compression: true,
            })
            .with_version(Version(1, 6))
            .with_re_randomization(ReRandomizationChoice::YesWithoutKeySwitch);

            let params = finder.find();

            let mut expected =
                super::super::v1_6::meta::cpu::V1_6_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_BIG_ZKV2_TUNIFORM_2M128;
            expected.dedicated_compact_public_key_parameters = None;
            assert_eq!(params, Some(expected));
        }

        {
            let finder = MetaParametersFinder::new(
                Constraint::LessThanOrEqual(Log2PFail(-64.0)),
                Backend::Cpu,
            )
            .with_compression(true)
            .with_noise_squashing(NoiseSquashingChoice::Yes {
                with_compression: true,
            })
            .with_version(Version(1, 5))
            .with_re_randomization(ReRandomizationChoice::No)
            .with_dedicated_compact_public_key(Some(DedicatedPublicKeyChoice::new()));

            let params = finder.find();

            let mut expected =
                super::super::v1_5::meta::cpu::V1_5_META_PARAM_CPU_2_2_KS_PBS_PKE_TO_BIG_ZKV2_TUNIFORM_2M128;
            expected
                .dedicated_compact_public_key_parameters
                .as_mut()
                .unwrap()
                .re_randomization_parameters = None;
            expected.rerand_configuration = None;
            assert_eq!(params, Some(expected));
        }
    }
}