arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/poulpy-core/src/noise/glwe.rs
poulpy-core/src/noise/glwe.rsRaw
 1use poulpy_hal::layouts::{Backend, DataRef, Module, Scratch, Stats};
 2
 3use crate::{
 4    GLWENormalize, GLWESub, ScratchTakeCore,
 5    decryption::GLWEDecrypt,
 6    layouts::{GLWE, GLWEInfos, GLWEPlaintext, GLWEToRef, LWEInfos, prepared::GLWESecretPreparedToRef},
 7};
 8
 9impl<D: DataRef> GLWE<D> {
10    pub fn noise<M, P, S, BE: Backend>(&self, module: &M, pt_want: &P, sk_prepared: &S, scratch: &mut Scratch<BE>) -> Stats
11    where
12        M: GLWENoise<BE>,
13        P: GLWEToRef,
14        S: GLWESecretPreparedToRef<BE> + GLWEInfos,
15    {
16        module.glwe_noise(self, pt_want, sk_prepared, scratch)
17    }
18}
19
20pub trait GLWENoise<BE: Backend> {
21    fn glwe_noise_tmp_bytes<A>(&self, infos: &A) -> usize
22    where
23        A: GLWEInfos;
24
25    fn glwe_noise<R, P, S>(&self, res: &R, pt_want: &P, sk_prepared: &S, scratch: &mut Scratch<BE>) -> Stats
26    where
27        R: GLWEToRef + GLWEInfos,
28        P: GLWEToRef,
29        S: GLWESecretPreparedToRef<BE> + GLWEInfos;
30}
31
32impl<BE: Backend> GLWENoise<BE> for Module<BE>
33where
34    Module<BE>: GLWEDecrypt<BE> + GLWESub + GLWENormalize<BE>,
35    Scratch<BE>: ScratchTakeCore<BE>,
36{
37    fn glwe_noise_tmp_bytes<A>(&self, infos: &A) -> usize
38    where
39        A: GLWEInfos,
40    {
41        GLWEPlaintext::bytes_of_from_infos(infos) + self.glwe_normalize_tmp_bytes().max(self.glwe_decrypt_tmp_bytes(infos))
42    }
43
44    fn glwe_noise<R, P, S>(&self, res: &R, pt_want: &P, sk_prepared: &S, scratch: &mut Scratch<BE>) -> Stats
45    where
46        R: GLWEToRef + GLWEInfos,
47        P: GLWEToRef,
48        S: GLWESecretPreparedToRef<BE> + GLWEInfos,
49    {
50        let (mut pt_have, scratch_1) = scratch.take_glwe_plaintext(res);
51        self.glwe_decrypt(res, &mut pt_have, sk_prepared, scratch_1);
52        // println!("pt_have: {pt_have}");
53        // println!("pt_want: {}", pt_want.to_ref());
54        self.glwe_sub_inplace(&mut pt_have, pt_want);
55        self.glwe_normalize_inplace(&mut pt_have, scratch_1);
56        pt_have.data.stats(pt_have.base2k().into(), 0)
57    }
58}