tfhe/core_crypto/entities/
lwe_ciphertext.rs

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
//! Module containing the definition of the [`LweCiphertext`].

use tfhe_versionable::Versionize;

use crate::conformance::ParameterSetConformant;
use crate::core_crypto::backward_compatibility::entities::lwe_ciphertext::LweCiphertextVersions;
use crate::core_crypto::commons::parameters::*;
use crate::core_crypto::commons::traits::*;
use crate::core_crypto::prelude::misc::check_encrypted_content_respects_mod;

/// A convenience structure to easily manipulate the body of an [`LweCiphertext`].
#[derive(Clone, Debug)]
pub struct LweBody<Scalar: UnsignedInteger> {
    pub data: Scalar,
    ciphertext_modulus: CiphertextModulus<Scalar>,
}

#[derive(Debug)]
pub struct LweBodyRef<'a, Scalar: UnsignedInteger> {
    pub data: &'a Scalar,
    ciphertext_modulus: CiphertextModulus<Scalar>,
}

#[derive(Debug)]
pub struct LweBodyRefMut<'a, Scalar: UnsignedInteger> {
    pub data: &'a mut Scalar,
    ciphertext_modulus: CiphertextModulus<Scalar>,
}

impl<Scalar: UnsignedInteger> LweBody<Scalar> {
    pub fn new(data: Scalar, ciphertext_modulus: CiphertextModulus<Scalar>) -> Self {
        Self {
            data,
            ciphertext_modulus,
        }
    }

    pub fn ciphertext_modulus(&self) -> CiphertextModulus<Scalar> {
        self.ciphertext_modulus
    }
}

impl<'outer, T: UnsignedInteger> LweBodyRef<'outer, T> {
    pub fn new(data: &'outer T, ciphertext_modulus: CiphertextModulus<T>) -> Self {
        Self {
            data,
            ciphertext_modulus,
        }
    }

    pub fn ciphertext_modulus(&self) -> CiphertextModulus<T> {
        self.ciphertext_modulus
    }
}

impl<'outer, T: UnsignedInteger> LweBodyRefMut<'outer, T> {
    pub fn new(data: &'outer mut T, ciphertext_modulus: CiphertextModulus<T>) -> Self {
        Self {
            data,
            ciphertext_modulus,
        }
    }

    pub fn ciphertext_modulus(&self) -> CiphertextModulus<T> {
        self.ciphertext_modulus
    }
}

impl<'data, T: UnsignedInteger> CreateFrom<&'data [T]> for LweBodyRef<'data, T> {
    type Metadata = LweBodyCreationMetadata<T>;

    #[inline]
    fn create_from(from: &[T], meta: Self::Metadata) -> LweBodyRef<T> {
        let LweBodyCreationMetadata { ciphertext_modulus } = meta;
        LweBodyRef {
            data: &from[0],
            ciphertext_modulus,
        }
    }
}

impl<'data, T: UnsignedInteger> CreateFrom<&'data mut [T]> for LweBodyRefMut<'data, T> {
    type Metadata = LweBodyCreationMetadata<T>;

    #[inline]
    fn create_from(from: &mut [T], meta: Self::Metadata) -> LweBodyRefMut<T> {
        let LweBodyCreationMetadata { ciphertext_modulus } = meta;
        LweBodyRefMut {
            data: &mut from[0],
            ciphertext_modulus,
        }
    }
}

#[derive(Clone, Debug)]
pub struct LweBodyList<C: Container>
where
    C::Element: UnsignedInteger,
{
    data: C,
    ciphertext_modulus: CiphertextModulus<C::Element>,
}

pub type LweBodyListView<'data, Scalar> = LweBodyList<&'data [Scalar]>;
pub type LweBodyListMutView<'data, Scalar> = LweBodyList<&'data mut [Scalar]>;

impl<T: UnsignedInteger, C: Container<Element = T>> AsRef<[T]> for LweBodyList<C> {
    fn as_ref(&self) -> &[T] {
        self.data.as_ref()
    }
}

impl<T: UnsignedInteger, C: ContainerMut<Element = T>> AsMut<[T]> for LweBodyList<C> {
    fn as_mut(&mut self) -> &mut [T] {
        self.data.as_mut()
    }
}

impl<'data, T: UnsignedInteger> CreateFrom<&'data [T]> for LweBodyListView<'data, T> {
    type Metadata = LweBodyListCreationMetadata<T>;

    #[inline]
    fn create_from(from: &[T], meta: Self::Metadata) -> LweBodyListView<'_, T> {
        let LweBodyListCreationMetadata { ciphertext_modulus } = meta;
        LweBodyList {
            data: from,
            ciphertext_modulus,
        }
    }
}

impl<'data, T: UnsignedInteger> CreateFrom<&'data mut [T]> for LweBodyListMutView<'data, T> {
    type Metadata = LweBodyListCreationMetadata<T>;

    #[inline]
    fn create_from(from: &mut [T], meta: Self::Metadata) -> LweBodyListMutView<'_, T> {
        let LweBodyListCreationMetadata { ciphertext_modulus } = meta;
        LweBodyList {
            data: from,
            ciphertext_modulus,
        }
    }
}

impl<Scalar: UnsignedInteger, C: Container<Element = Scalar>> LweBodyList<C> {
    pub fn from_container(container: C, ciphertext_modulus: CiphertextModulus<Scalar>) -> Self {
        Self {
            data: container,
            ciphertext_modulus,
        }
    }

    pub fn lwe_body_count(&self) -> LweBodyCount {
        LweBodyCount(self.data.container_len())
    }

    pub fn ciphertext_modulus(&self) -> CiphertextModulus<Scalar> {
        self.ciphertext_modulus
    }
}

/// Metadata used in the [`CreateFrom`] implementation to create [`LweBody`] entities.
#[derive(Clone, Copy)]
pub struct LweBodyCreationMetadata<Scalar: UnsignedInteger> {
    pub ciphertext_modulus: CiphertextModulus<Scalar>,
}

/// Metadata used in the [`CreateFrom`] implementation to create [`LweBodyList`] entities.
#[derive(Clone, Copy)]
pub struct LweBodyListCreationMetadata<Scalar: UnsignedInteger> {
    pub ciphertext_modulus: CiphertextModulus<Scalar>,
}

impl<Scalar: UnsignedInteger, C: Container<Element = Scalar>> ContiguousEntityContainer
    for LweBodyList<C>
{
    type Element = C::Element;

    type EntityViewMetadata = LweBodyCreationMetadata<Self::Element>;

    type EntityView<'this> = LweBodyRef<'this, Self::Element>
    where
        Self: 'this;

    type SelfViewMetadata = LweBodyListCreationMetadata<Self::Element>;

    type SelfView<'this> = LweBodyListView<'this,Self::Element>
    where
        Self: 'this;

    fn get_entity_view_creation_metadata(&self) -> Self::EntityViewMetadata {
        LweBodyCreationMetadata {
            ciphertext_modulus: self.ciphertext_modulus(),
        }
    }

    fn get_entity_view_pod_size(&self) -> usize {
        1
    }

    fn get_self_view_creation_metadata(&self) -> Self::SelfViewMetadata {
        LweBodyListCreationMetadata {
            ciphertext_modulus: self.ciphertext_modulus(),
        }
    }
}

impl<Scalar: UnsignedInteger, C: ContainerMut<Element = Scalar>> ContiguousEntityContainerMut
    for LweBodyList<C>
{
    type EntityMutView<'this> = LweBodyRefMut<'this, Self::Element>
    where
        Self: 'this;

    type SelfMutView<'this> = LweBodyListMutView<'this, Self::Element>
    where
        Self: 'this;
}

#[derive(Clone, Debug)]
pub struct LweMask<C: Container>
where
    C::Element: UnsignedInteger,
{
    data: C,
    ciphertext_modulus: CiphertextModulus<C::Element>,
}

/// A convenience structure to easily manipulate the mask of an [`LweCiphertext`].
impl<Scalar: UnsignedInteger, C: Container<Element = Scalar>> LweMask<C> {
    /// Create an [`LweMask`] from an existing container.
    ///
    /// # Note
    ///
    /// This docstring exhibits [`LweMask`] primitives usage.
    ///
    /// ```rust
    /// use tfhe::core_crypto::prelude::*;
    ///
    /// // DISCLAIMER: these toy example parameters are not guaranteed to be secure or yield correct
    /// // computations
    /// // Define parameters for LweMask creation
    /// let lwe_dimension = LweDimension(600);
    /// let ciphertext_modulus = CiphertextModulus::new_native();
    ///
    /// let lwe_mask = LweMask::from_container(vec![0u64; lwe_dimension.0], ciphertext_modulus);
    ///
    /// assert_eq!(lwe_mask.lwe_dimension(), lwe_dimension);
    /// assert_eq!(lwe_mask.ciphertext_modulus(), ciphertext_modulus);
    /// ```
    pub fn from_container(container: C, ciphertext_modulus: CiphertextModulus<C::Element>) -> Self {
        Self {
            data: container,
            ciphertext_modulus,
        }
    }

    /// Return the [`LweDimension`] of the [`LweMask`].
    ///
    /// See [`LweMask::from_container`] for usage.
    pub fn lwe_dimension(&self) -> LweDimension {
        LweDimension(self.data.container_len())
    }

    /// Return the [`CiphertextModulus`] of the [`LweMask`].
    ///
    /// See [`LweMask::from_container`] for usage.
    pub fn ciphertext_modulus(&self) -> CiphertextModulus<C::Element> {
        self.ciphertext_modulus
    }
}

impl<T: UnsignedInteger, C: Container<Element = T>> AsRef<[T]> for LweMask<C> {
    fn as_ref(&self) -> &[T] {
        self.data.as_ref()
    }
}

impl<T: UnsignedInteger, C: ContainerMut<Element = T>> AsMut<[T]> for LweMask<C> {
    fn as_mut(&mut self) -> &mut [T] {
        self.data.as_mut()
    }
}

impl<'data, T: UnsignedInteger> CreateFrom<&'data [T]> for LweMask<&'data [T]> {
    type Metadata = LweMaskCreationMetadata<T>;

    #[inline]
    fn create_from(from: &[T], meta: Self::Metadata) -> LweMask<&[T]> {
        let LweMaskCreationMetadata { ciphertext_modulus } = meta;
        LweMask {
            data: from,
            ciphertext_modulus,
        }
    }
}

impl<'data, T: UnsignedInteger> CreateFrom<&'data mut [T]> for LweMask<&'data mut [T]> {
    type Metadata = LweMaskCreationMetadata<T>;

    #[inline]
    fn create_from(from: &mut [T], meta: Self::Metadata) -> LweMask<&mut [T]> {
        let LweMaskCreationMetadata { ciphertext_modulus } = meta;
        LweMask {
            data: from,
            ciphertext_modulus,
        }
    }
}

#[derive(Clone, Debug)]
pub struct LweMaskList<C: Container>
where
    C::Element: UnsignedInteger,
{
    data: C,
    lwe_dimension: LweDimension,
    ciphertext_modulus: CiphertextModulus<C::Element>,
}

pub type LweMaskListView<'data, Scalar> = LweMaskList<&'data [Scalar]>;
pub type LweMaskListMutView<'data, Scalar> = LweMaskList<&'data mut [Scalar]>;

pub fn lwe_mask_list_size(lwe_dimension: LweDimension, lwe_mask_count: LweMaskCount) -> usize {
    lwe_dimension.0 * lwe_mask_count.0
}

impl<T: UnsignedInteger, C: Container<Element = T>> AsRef<[T]> for LweMaskList<C> {
    fn as_ref(&self) -> &[T] {
        self.data.as_ref()
    }
}

impl<T: UnsignedInteger, C: ContainerMut<Element = T>> AsMut<[T]> for LweMaskList<C> {
    fn as_mut(&mut self) -> &mut [T] {
        self.data.as_mut()
    }
}

impl<'data, T: UnsignedInteger> CreateFrom<&'data [T]> for LweMaskListView<'data, T> {
    type Metadata = LweMaskListCreationMetadata<T>;

    #[inline]
    fn create_from(from: &[T], meta: Self::Metadata) -> LweMaskListView<'_, T> {
        let LweMaskListCreationMetadata {
            lwe_dimension,
            ciphertext_modulus,
        } = meta;
        LweMaskList {
            data: from,
            lwe_dimension,
            ciphertext_modulus,
        }
    }
}

impl<'data, T: UnsignedInteger> CreateFrom<&'data mut [T]> for LweMaskListMutView<'data, T> {
    type Metadata = LweMaskListCreationMetadata<T>;

    #[inline]
    fn create_from(from: &mut [T], meta: Self::Metadata) -> LweMaskListMutView<'_, T> {
        let LweMaskListCreationMetadata {
            lwe_dimension,
            ciphertext_modulus,
        } = meta;
        LweMaskList {
            data: from,
            lwe_dimension,
            ciphertext_modulus,
        }
    }
}

impl<Scalar: UnsignedInteger, C: Container<Element = Scalar>> LweMaskList<C> {
    pub fn from_container(
        container: C,
        lwe_dimension: LweDimension,
        ciphertext_modulus: CiphertextModulus<Scalar>,
    ) -> Self {
        assert!(
            container.container_len() % lwe_dimension.0 == 0,
            "The provided container length is not valid. \
        It needs to be dividable by lwe_dimension. \
        Got container length: {} and lwe_dimension: {lwe_dimension:?}.",
            container.container_len()
        );

        Self {
            data: container,
            lwe_dimension,
            ciphertext_modulus,
        }
    }

    pub fn lwe_dimension(&self) -> LweDimension {
        self.lwe_dimension
    }

    pub fn lwe_mask_count(&self) -> LweMaskCount {
        LweMaskCount(self.data.container_len() / self.lwe_dimension.0)
    }

    pub fn lwe_mask_list_size(&self) -> usize {
        lwe_mask_list_size(self.lwe_dimension(), self.lwe_mask_count())
    }

    pub fn ciphertext_modulus(&self) -> CiphertextModulus<Scalar> {
        self.ciphertext_modulus
    }
}

/// Metadata used in the [`CreateFrom`] implementation to create [`LweMask`] entities.
#[derive(Clone, Copy)]
pub struct LweMaskCreationMetadata<Scalar: UnsignedInteger> {
    pub ciphertext_modulus: CiphertextModulus<Scalar>,
}

/// Metadata used in the [`CreateFrom`] implementation to create [`LweMaskList`] entities.
#[derive(Clone, Copy)]
pub struct LweMaskListCreationMetadata<Scalar: UnsignedInteger> {
    pub lwe_dimension: LweDimension,
    pub ciphertext_modulus: CiphertextModulus<Scalar>,
}

impl<Scalar: UnsignedInteger, C: Container<Element = Scalar>> ContiguousEntityContainer
    for LweMaskList<C>
{
    type Element = C::Element;

    type EntityViewMetadata = LweMaskCreationMetadata<Self::Element>;

    type EntityView<'this> = LweMask<&'this [Self::Element]>
    where
        Self: 'this;

    type SelfViewMetadata = LweMaskListCreationMetadata<Self::Element>;

    type SelfView<'this> = LweMaskListView<'this, Self::Element>
    where
        Self: 'this;

    fn get_entity_view_creation_metadata(&self) -> Self::EntityViewMetadata {
        LweMaskCreationMetadata {
            ciphertext_modulus: self.ciphertext_modulus(),
        }
    }

    fn get_entity_view_pod_size(&self) -> usize {
        self.lwe_dimension().0
    }

    fn get_self_view_creation_metadata(&self) -> Self::SelfViewMetadata {
        LweMaskListCreationMetadata {
            lwe_dimension: self.lwe_dimension(),
            ciphertext_modulus: self.ciphertext_modulus(),
        }
    }
}

impl<Scalar: UnsignedInteger, C: ContainerMut<Element = Scalar>> ContiguousEntityContainerMut
    for LweMaskList<C>
{
    type EntityMutView<'this> = LweMask<&'this mut [Self::Element]>
    where
        Self: 'this;

    type SelfMutView<'this> = LweMaskListMutView<'this,Self::Element>
    where
        Self: 'this;
}

/// An [`LWE ciphertext`](`LweCiphertext`).
///
/// # Formal Definition
///
/// ## LWE Ciphertext
///
/// An LWE ciphertext is an encryption of a plaintext.
/// It is secure under the hardness assumption called Learning With Errors (LWE).
/// It is a specialization of
/// [`GLWE ciphertext`](`crate::core_crypto::entities::GlweCiphertext`).
///
/// We indicate an LWE ciphertext of a plaintext $\mathsf{pt} \in\mathbb{Z}\_q$ as the following
/// couple: $$\mathsf{ct} = \left( \vec{a} , b\right) \in \mathsf{LWE}^n\_{\vec{s}}( \mathsf{pt}
/// )\subseteq \mathbb{Z}\_q^{(n+1)}$$ We call $q$ the ciphertext modulus and $n$ the LWE dimension.
///
/// ## LWE dimension
/// It corresponds to the number of element in the LWE secret key.
/// In an LWE ciphertext, it is the length of the vector $\vec{a}$.
/// At [`encryption`](`crate::core_crypto::algorithms::encrypt_lwe_ciphertext`) time, it is
/// the number of uniformly random integers generated.
///
/// ## LWE Encryption
/// ###### inputs:
/// - $\mathsf{pt}\in\mathbb{Z}\_q$: a plaintext
/// - $\vec{s}\in\mathbb{Z}\_q^n$: a secret key
/// - $\mathcal{D\_{\sigma^2,\mu}}$: a normal distribution of variance $\sigma^2$ and a mean $\mu$
///
/// ###### outputs:
/// - $\mathsf{ct} = \left( \vec{a} , b\right) \in \mathsf{LWE}^n\_{\vec{s}}( \mathsf{pt} )\subseteq
///   \mathbb{Z}\_q^{(n+1)}$: an LWE ciphertext
///
/// ###### algorithm:
/// 1. uniformly sample a vector $\vec{a}\in\mathbb{Z}\_q^n$
/// 2. sample an integer error term $e \hookleftarrow \mathcal{D\_{\sigma^2,\mu}}$
/// 3. compute $b = \left\langle \vec{a} , \vec{s} \right\rangle + \mathsf{pt} + e \in\mathbb{Z}\_q$
/// 4. output $\left( \vec{a} , b\right)$
///
/// ## LWE Decryption
/// ###### inputs:
/// - $\mathsf{ct} = \left( \vec{a} , b\right) \in \mathsf{LWE}^n\_{\vec{s}}( \mathsf{pt} )\subseteq
///   \mathbb{Z}\_q^{(n+1)}$: an LWE ciphertext
/// - $\vec{s}\in\mathbb{Z}\_q^n$: a secret key
///
/// ###### outputs:
/// - $\mathsf{pt}\in\mathbb{Z}\_q$: a plaintext
///
/// ###### algorithm:
/// 1. compute $\mathsf{pt} = b - \left\langle \vec{a} , \vec{s} \right\rangle \in\mathbb{Z}\_q$
/// 3. output $\mathsf{pt}$
///
/// **Remark:** Observe that the decryption is followed by a decoding phase that will contain a
/// rounding.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Versionize)]
#[versionize(LweCiphertextVersions)]
pub struct LweCiphertext<C: Container>
where
    C::Element: UnsignedInteger,
{
    data: C,
    ciphertext_modulus: CiphertextModulus<C::Element>,
}

impl<T: UnsignedInteger, C: Container<Element = T>> AsRef<[T]> for LweCiphertext<C> {
    fn as_ref(&self) -> &[T] {
        self.data.as_ref()
    }
}

impl<T: UnsignedInteger, C: ContainerMut<Element = T>> AsMut<[T]> for LweCiphertext<C> {
    fn as_mut(&mut self) -> &mut [T] {
        self.data.as_mut()
    }
}

// This accessor is used to create invalid objects and test the conformance functions
// But these functions should not be used in other contexts, hence the `#[cfg(test)]`
#[cfg(test)]
#[allow(dead_code)]
impl<C: Container> LweCiphertext<C>
where
    C::Element: UnsignedInteger,
{
    pub(crate) fn get_mut_ciphertext_modulus(&mut self) -> &mut CiphertextModulus<C::Element> {
        &mut self.ciphertext_modulus
    }
}

/// Return the number of mask samples used during encryption of an [`LweCiphertext`] given an
/// [`LweDimension`].
pub fn lwe_ciphertext_encryption_mask_sample_count(
    lwe_dimension: LweDimension,
) -> EncryptionMaskSampleCount {
    EncryptionMaskSampleCount(lwe_dimension.0)
}

/// Return the number of noise samples required to encrypt an [`LweCiphertext`].
pub fn lwe_ciphertext_encryption_noise_sample_count() -> EncryptionNoiseSampleCount {
    EncryptionNoiseSampleCount(1)
}

impl<Scalar: UnsignedInteger, C: Container<Element = Scalar>> LweCiphertext<C> {
    /// Create an [`LweCiphertext`] from an existing container.
    ///
    /// # Note
    ///
    /// This function only wraps a container in the appropriate type. If you want to encrypt data
    /// you need to use [`crate::core_crypto::algorithms::encrypt_lwe_ciphertext`] using this
    /// ciphertext as output.
    ///
    /// This docstring exhibits [`LweCiphertext`] primitives usage.
    ///
    /// ```rust
    /// use tfhe::core_crypto::prelude::*;
    ///
    /// // DISCLAIMER: these toy example parameters are not guaranteed to be secure or yield correct
    /// // computations
    /// // Define parameters for LweCiphertext creation
    /// let lwe_size = LweSize(601);
    /// let ciphertext_modulus = CiphertextModulus::new_native();
    ///
    /// // Create a new LweCiphertext
    /// let mut lwe = LweCiphertext::new(0u64, lwe_size, ciphertext_modulus);
    ///
    /// assert_eq!(lwe.lwe_size(), lwe_size);
    /// assert_eq!(lwe.get_mask().lwe_dimension(), lwe_size.to_lwe_dimension());
    /// assert_eq!(
    ///     lwe.get_mut_mask().lwe_dimension(),
    ///     lwe_size.to_lwe_dimension()
    /// );
    /// assert_eq!(lwe.ciphertext_modulus(), ciphertext_modulus);
    ///
    /// // Demonstrate how to recover the allocated container
    /// let underlying_container: Vec<u64> = lwe.into_container();
    ///
    /// // Recreate a ciphertext using from_container
    /// let mut lwe = LweCiphertext::from_container(underlying_container, ciphertext_modulus);
    ///
    /// assert_eq!(lwe.lwe_size(), lwe_size);
    /// assert_eq!(lwe.get_mask().lwe_dimension(), lwe_size.to_lwe_dimension());
    /// assert_eq!(
    ///     lwe.get_mut_mask().lwe_dimension(),
    ///     lwe_size.to_lwe_dimension()
    /// );
    /// assert_eq!(lwe.ciphertext_modulus(), ciphertext_modulus);
    /// ```
    pub fn from_container(container: C, ciphertext_modulus: CiphertextModulus<C::Element>) -> Self {
        assert!(
            container.container_len() > 0,
            "Got an empty container to create an LweCiphertext"
        );
        Self {
            data: container,
            ciphertext_modulus,
        }
    }

    /// Return the [`LweSize`] of the [`LweCiphertext`].
    ///
    /// See [`LweCiphertext::from_container`] for usage.
    pub fn lwe_size(&self) -> LweSize {
        LweSize(self.data.container_len())
    }

    /// Return immutable views to the [`LweMask`] and [`LweBody`] of an [`LweCiphertext`].
    pub fn get_mask_and_body(&self) -> (LweMask<&[Scalar]>, LweBodyRef<'_, Scalar>) {
        let (body, mask) = self.data.as_ref().split_last().unwrap();
        let ciphertext_modulus = self.ciphertext_modulus();

        (
            LweMask::from_container(mask, ciphertext_modulus),
            LweBodyRef {
                data: body,
                ciphertext_modulus,
            },
        )
    }

    /// Return an immutable view to the [`LweBody`] of an [`LweCiphertext`].
    pub fn get_body(&self) -> LweBodyRef<'_, Scalar> {
        let body = self.data.as_ref().last().unwrap();
        let ciphertext_modulus = self.ciphertext_modulus();

        LweBodyRef {
            data: body,
            ciphertext_modulus,
        }
    }

    /// Return an immutable view to the [`LweMask`] of an [`LweCiphertext`].
    ///
    /// See [`LweCiphertext::from_container`] for usage.
    pub fn get_mask(&self) -> LweMask<&[Scalar]> {
        LweMask::from_container(
            &self.as_ref()[0..self.lwe_size().to_lwe_dimension().0],
            self.ciphertext_modulus(),
        )
    }

    /// Return a view of the [`LweCiphertext`]. This is useful if an algorithm takes a view by
    /// value.
    pub fn as_view(&self) -> LweCiphertextView<'_, Scalar> {
        LweCiphertextView::from_container(self.as_ref(), self.ciphertext_modulus())
    }

    /// Consume the entity and return its underlying container.
    ///
    /// See [`LweCiphertext::from_container`] for usage.
    pub fn into_container(self) -> C {
        self.data
    }

    /// Return the [`CiphertextModulus`] of the [`LweCiphertext`].
    ///
    /// See [`LweCiphertext::from_container`] for usage.
    pub fn ciphertext_modulus(&self) -> CiphertextModulus<C::Element> {
        self.ciphertext_modulus
    }
}

impl<Scalar: UnsignedInteger, C: ContainerMut<Element = Scalar>> LweCiphertext<C> {
    /// Mutable variant of [`LweCiphertext::get_mask_and_body`].
    pub fn get_mut_mask_and_body(&mut self) -> (LweMask<&mut [Scalar]>, LweBodyRefMut<'_, Scalar>) {
        let ciphertext_modulus = self.ciphertext_modulus();
        let (body, mask) = self.data.as_mut().split_last_mut().unwrap();

        (
            LweMask::from_container(mask, ciphertext_modulus),
            LweBodyRefMut {
                data: body,
                ciphertext_modulus,
            },
        )
    }

    /// Mutable variant of [`LweCiphertext::get_body`].
    pub fn get_mut_body(&mut self) -> LweBodyRefMut<'_, Scalar> {
        let ciphertext_modulus = self.ciphertext_modulus();
        let body = self.data.as_mut().last_mut().unwrap();

        LweBodyRefMut {
            data: body,
            ciphertext_modulus,
        }
    }

    /// Mutable variant of [`LweCiphertext::get_mask`].
    ///
    /// See [`LweCiphertext::from_container`] for usage.
    pub fn get_mut_mask(&mut self) -> LweMask<&mut [Scalar]> {
        let lwe_dimension = self.lwe_size().to_lwe_dimension();
        let ciphertext_modulus = self.ciphertext_modulus();

        LweMask::from_container(&mut self.as_mut()[0..lwe_dimension.0], ciphertext_modulus)
    }

    /// Mutable variant of [`LweCiphertext::as_view`].
    pub fn as_mut_view(&mut self) -> LweCiphertextMutView<'_, Scalar> {
        let ciphertext_modulus = self.ciphertext_modulus();
        LweCiphertextMutView::from_container(self.as_mut(), ciphertext_modulus)
    }
}

/// An [`LweCiphertext`] owning the memory for its own storage.
pub type LweCiphertextOwned<Scalar> = LweCiphertext<Vec<Scalar>>;
/// An [`LweCiphertext`] immutably borrowing memory for its own storage.
pub type LweCiphertextView<'data, Scalar> = LweCiphertext<&'data [Scalar]>;
/// An [`LweCiphertext`] mutably borrowing memory for its own storage.
pub type LweCiphertextMutView<'data, Scalar> = LweCiphertext<&'data mut [Scalar]>;

/// Structure to store the expected properties of a ciphertext
/// Can be used on a server to check if client inputs are well formed
/// before running a computation on them
#[derive(Copy, Clone)]
pub struct LweCiphertextParameters<T: UnsignedInteger> {
    pub lwe_dim: LweDimension,
    pub ct_modulus: CiphertextModulus<T>,
    pub ms_decompression_method: MsDecompressionType,
}

#[derive(Copy, Clone)]
pub enum MsDecompressionType {
    ClassicPbs,
    MultiBitPbs(LweBskGroupingFactor),
}

impl<C: Container> ParameterSetConformant for LweCiphertext<C>
where
    C::Element: UnsignedInteger,
{
    type ParameterSet = LweCiphertextParameters<C::Element>;

    fn is_conformant(&self, lwe_ct_parameters: &LweCiphertextParameters<C::Element>) -> bool {
        let Self {
            data,
            ciphertext_modulus,
        } = self;

        check_encrypted_content_respects_mod(data, lwe_ct_parameters.ct_modulus)
            && self.lwe_size() == lwe_ct_parameters.lwe_dim.to_lwe_size()
            && *ciphertext_modulus == lwe_ct_parameters.ct_modulus
    }
}

impl<Scalar: UnsignedInteger> LweCiphertextOwned<Scalar> {
    /// Allocate memory and create a new owned [`LweCiphertext`].
    ///
    /// # Note
    ///
    /// This function allocates a vector of the appropriate size and wraps it in the appropriate
    /// type. If you want to encrypt data you need to use
    /// [`crate::core_crypto::algorithms::encrypt_lwe_ciphertext`] using this ciphertext as
    /// output.
    ///
    /// See [`LweCiphertext::from_container`] for usage.
    pub fn new(
        fill_with: Scalar,
        lwe_size: LweSize,
        ciphertext_modulus: CiphertextModulus<Scalar>,
    ) -> Self {
        Self::from_container(vec![fill_with; lwe_size.0], ciphertext_modulus)
    }
}

/// Metadata used in the [`CreateFrom`] implementation to create [`LweCiphertext`] entities.
#[derive(Clone, Copy)]
pub struct LweCiphertextCreationMetadata<Scalar: UnsignedInteger> {
    pub ciphertext_modulus: CiphertextModulus<Scalar>,
}

impl<Scalar: UnsignedInteger, C: Container<Element = Scalar>> CreateFrom<C> for LweCiphertext<C> {
    type Metadata = LweCiphertextCreationMetadata<C::Element>;

    #[inline]
    fn create_from(from: C, meta: Self::Metadata) -> Self {
        let LweCiphertextCreationMetadata { ciphertext_modulus } = meta;
        Self::from_container(from, ciphertext_modulus)
    }
}