arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/core/src/decryption/glwe_ct.rs
core/src/decryption/glwe_ct.rsRaw
 1use backend::hal::{
 2    api::{
 3        DataViewMut, SvpApplyInplace, TakeVecZnxBig, TakeVecZnxDft, VecZnxBigAddInplace, VecZnxBigAddSmallInplace,
 4        VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxNormalizeTmpBytes,
 5    },
 6    layouts::{Backend, DataMut, DataRef, Module, Scratch},
 7};
 8
 9use crate::{
10    layouts::{GLWECiphertext, GLWEPlaintext, Infos, prepared::GLWESecretPrepared},
11    trait_families::GLWEDecryptFamily,
12};
13
14impl GLWECiphertext<Vec<u8>> {
15    pub fn decrypt_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
16    where
17        Module<B>: GLWEDecryptFamily<B>,
18    {
19        let size: usize = k.div_ceil(basek);
20        (module.vec_znx_normalize_tmp_bytes(n) | module.vec_znx_dft_alloc_bytes(n, 1, size))
21            + module.vec_znx_dft_alloc_bytes(n, 1, size)
22    }
23}
24
25impl<DataSelf: DataRef> GLWECiphertext<DataSelf> {
26    pub fn decrypt<DataPt: DataMut, DataSk: DataRef, B: Backend>(
27        &self,
28        module: &Module<B>,
29        pt: &mut GLWEPlaintext<DataPt>,
30        sk: &GLWESecretPrepared<DataSk, B>,
31        scratch: &mut Scratch<B>,
32    ) where
33        Module<B>: GLWEDecryptFamily<B>,
34        Scratch<B>: TakeVecZnxDft<B> + TakeVecZnxBig<B>,
35    {
36        #[cfg(debug_assertions)]
37        {
38            assert_eq!(self.rank(), sk.rank());
39            assert_eq!(self.n(), sk.n());
40            assert_eq!(pt.n(), sk.n());
41        }
42
43        let cols: usize = self.rank() + 1;
44
45        let (mut c0_big, scratch_1) = scratch.take_vec_znx_big(self.n(), 1, self.size()); // TODO optimize size when pt << ct
46        c0_big.data_mut().fill(0);
47
48        {
49            (1..cols).for_each(|i| {
50                // ci_dft = DFT(a[i]) * DFT(s[i])
51                let (mut ci_dft, _) = scratch_1.take_vec_znx_dft(self.n(), 1, self.size()); // TODO optimize size when pt << ct
52                module.vec_znx_dft_from_vec_znx(1, 0, &mut ci_dft, 0, &self.data, i);
53                module.svp_apply_inplace(&mut ci_dft, 0, &sk.data, i - 1);
54                let ci_big = module.vec_znx_dft_to_vec_znx_big_consume(ci_dft);
55
56                // c0_big += a[i] * s[i]
57                module.vec_znx_big_add_inplace(&mut c0_big, 0, &ci_big, 0);
58            });
59        }
60
61        // c0_big = (a * s) + (-a * s + m + e) = BIG(m + e)
62        module.vec_znx_big_add_small_inplace(&mut c0_big, 0, &self.data, 0);
63
64        // pt = norm(BIG(m + e))
65        module.vec_znx_big_normalize(self.basek(), &mut pt.data, 0, &mut c0_big, 0, scratch_1);
66
67        pt.basek = self.basek();
68        pt.k = pt.k().min(self.k());
69    }
70}