arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/poulpy-schemes/src/tfhe/bdd_arithmetic/ciphertexts/fhe_uint.rs
poulpy-schemes/src/tfhe/bdd_arithmetic/ciphertexts/fhe_uint.rsRaw
  1use poulpy_core::{
  2    GLWEAdd, GLWECopy, GLWEDecrypt, GLWEEncryptSk, GLWEPacking, GLWERotate, GLWESub, GLWETrace, LWEFromGLWE, ScratchTakeCore,
  3    layouts::{
  4        Base2K, Degree, GGLWEInfos, GGLWEPreparedToRef, GLWE, GLWEAutomorphismKeyHelper, GLWEInfos, GLWEPlaintextLayout,
  5        GLWESecretPreparedToRef, GLWEToMut, GLWEToRef, GetGaloisElement, LWEInfos, LWEToMut, Rank, TorusPrecision,
  6    },
  7};
  8use poulpy_hal::{
  9    api::ModuleLogN,
 10    layouts::{Backend, Data, DataMut, DataRef, Scratch},
 11    source::Source,
 12};
 13use std::{collections::HashMap, marker::PhantomData};
 14
 15use crate::tfhe::bdd_arithmetic::{FromBits, ToBits, UnsignedInteger};
 16
 17/// An FHE ciphertext encrypting the bits of an [UnsignedInteger].
 18pub struct FheUint<D: Data, T: UnsignedInteger> {
 19    pub(crate) bits: GLWE<D>,
 20    pub(crate) _phantom: PhantomData<T>,
 21}
 22
 23impl<T: UnsignedInteger> FheUint<Vec<u8>, T> {
 24    pub fn alloc_from_infos<A>(infos: &A) -> Self
 25    where
 26        A: GLWEInfos,
 27    {
 28        Self::alloc(infos.n(), infos.base2k(), infos.k(), infos.rank())
 29    }
 30
 31    pub fn alloc(n: Degree, base2k: Base2K, k: TorusPrecision, rank: Rank) -> Self {
 32        Self {
 33            bits: GLWE::alloc(n, base2k, k, rank),
 34            _phantom: PhantomData,
 35        }
 36    }
 37}
 38
 39impl<'a, T: UnsignedInteger> FheUint<&'a mut [u8], T> {
 40    pub fn from_glwe_to_mut<G>(glwe: &'a mut G) -> Self
 41    where
 42        G: GLWEToMut,
 43    {
 44        FheUint {
 45            bits: glwe.to_mut(),
 46            _phantom: PhantomData,
 47        }
 48    }
 49}
 50
 51impl<D: DataRef, T: UnsignedInteger> LWEInfos for FheUint<D, T> {
 52    fn base2k(&self) -> poulpy_core::layouts::Base2K {
 53        self.bits.base2k()
 54    }
 55
 56    fn k(&self) -> poulpy_core::layouts::TorusPrecision {
 57        self.bits.k()
 58    }
 59
 60    fn n(&self) -> poulpy_core::layouts::Degree {
 61        self.bits.n()
 62    }
 63}
 64
 65impl<D: DataRef, T: UnsignedInteger> GLWEInfos for FheUint<D, T> {
 66    fn rank(&self) -> poulpy_core::layouts::Rank {
 67        self.bits.rank()
 68    }
 69}
 70
 71impl<D: DataMut, T: UnsignedInteger + ToBits> FheUint<D, T> {
 72    pub fn encrypt_sk<S, M, BE: Backend>(
 73        &mut self,
 74        module: &M,
 75        data: T,
 76        sk: &S,
 77        source_xa: &mut Source,
 78        source_xe: &mut Source,
 79        scratch: &mut Scratch<BE>,
 80    ) where
 81        S: GLWESecretPreparedToRef<BE> + GLWEInfos,
 82        M: ModuleLogN + GLWEEncryptSk<BE>,
 83        Scratch<BE>: ScratchTakeCore<BE>,
 84    {
 85        #[cfg(debug_assertions)]
 86        {
 87            assert!(module.n().is_multiple_of(T::BITS as usize));
 88            assert_eq!(self.n(), module.n() as u32);
 89            assert_eq!(sk.n(), module.n() as u32);
 90        }
 91
 92        let mut data_bits: Vec<i64> = vec![0i64; module.n()];
 93
 94        let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
 95
 96        // Interleaves bytes
 97        for i in 0..T::BITS as usize {
 98            data_bits[T::bit_index(i) << log_gap] = data.bit(i) as i64
 99        }
100
101        let pt_infos = GLWEPlaintextLayout {
102            n: self.n(),
103            base2k: self.base2k(),
104            k: 1_usize.into(),
105        };
106
107        let (mut pt, scratch_1) = scratch.take_glwe_plaintext(&pt_infos);
108
109        pt.encode_vec_i64(&data_bits, TorusPrecision(2));
110        self.bits
111            .encrypt_sk(module, &pt, sk, source_xa, source_xe, scratch_1);
112    }
113}
114
115impl<D: DataRef, T: UnsignedInteger + FromBits> FheUint<D, T> {
116    pub fn decrypt<S, M, BE: Backend>(&self, module: &M, sk: &S, scratch: &mut Scratch<BE>) -> T
117    where
118        S: GLWESecretPreparedToRef<BE> + GLWEInfos,
119        M: ModuleLogN + GLWEDecrypt<BE>,
120        Scratch<BE>: ScratchTakeCore<BE>,
121    {
122        #[cfg(debug_assertions)]
123        {
124            assert!(module.n().is_multiple_of(T::BITS as usize));
125            assert_eq!(self.n(), module.n() as u32);
126            assert_eq!(sk.n(), module.n() as u32);
127        }
128
129        let pt_infos = GLWEPlaintextLayout {
130            n: self.n(),
131            base2k: self.base2k(),
132            k: 1_usize.into(),
133        };
134
135        let (mut pt, scratch_1) = scratch.take_glwe_plaintext(&pt_infos);
136
137        self.bits.decrypt(module, &mut pt, sk, scratch_1);
138
139        let mut data_bits: Vec<i64> = vec![0i64; module.n()];
140        pt.decode_vec_i64(&mut data_bits, TorusPrecision(2));
141
142        let mut bits: Vec<u8> = vec![0u8; T::BITS as usize];
143
144        let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
145
146        // Retrives from interleaved bytes
147        for i in 0..T::BITS as usize {
148            bits[i] = data_bits[T::bit_index(i) << log_gap] as u8
149        }
150
151        T::from_bits(&bits)
152    }
153}
154
155impl<D: DataMut, T: UnsignedInteger> FheUint<D, T> {
156    /// Packs Vec<GLWE(bit[i])> into [FheUint].
157    pub fn pack<G, M, K, H, BE: Backend>(&mut self, module: &M, mut bits: Vec<G>, keys: &H, scratch: &mut Scratch<BE>)
158    where
159        G: GLWEToMut + GLWEToRef + GLWEInfos,
160        M: ModuleLogN + GLWEPacking<BE> + GLWECopy,
161        K: GGLWEPreparedToRef<BE> + GetGaloisElement + GGLWEInfos,
162        H: GLWEAutomorphismKeyHelper<K, BE>,
163        Scratch<BE>: ScratchTakeCore<BE>,
164    {
165        // Repacks the GLWE ciphertexts bits
166        let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
167        let mut cts: HashMap<usize, &mut G> = HashMap::new();
168        for (i, ct) in bits.iter_mut().enumerate().take(T::BITS as usize) {
169            cts.insert(T::bit_index(i) << log_gap, ct);
170        }
171
172        module.glwe_pack(&mut self.bits, cts, log_gap, keys, scratch);
173    }
174
175    #[allow(clippy::too_many_arguments)]
176    pub fn splice_u16<A, B, H, K, M, BE: Backend>(
177        &mut self,
178        module: &M,
179        dst: usize,
180        src: usize,
181        a: &A,
182        b: &B,
183        keys: &H,
184        scratch: &mut Scratch<BE>,
185    ) where
186        A: GLWEToRef + GLWEInfos,
187        B: GLWEToRef + GLWEInfos,
188        H: GLWEAutomorphismKeyHelper<K, BE>,
189        K: GGLWEPreparedToRef<BE> + GGLWEInfos + GetGaloisElement,
190        M: ModuleLogN + GLWERotate<BE> + GLWETrace<BE> + GLWESub + GLWEAdd + GLWECopy,
191        Scratch<BE>: ScratchTakeBDD<T, BE>,
192    {
193        assert!(dst < (T::BITS >> 4) as usize);
194        assert!(src < (T::BITS >> 4) as usize);
195
196        let (mut tmp, scratch_1) = scratch.take_fhe_uint(self);
197        tmp.splice_u8(module, dst << 1, src << 1, a, b, keys, scratch_1);
198        self.splice_u8(
199            module,
200            (dst << 1) + 1,
201            (src << 1) + 1,
202            &tmp,
203            b,
204            keys,
205            scratch_1,
206        );
207    }
208
209    #[allow(clippy::too_many_arguments)]
210    // Store on the receiver a where the byte_a-th byte of a has been replaced by byte_src2 of src2.
211    pub fn splice_u8<A, B, H, K, M, BE: Backend>(
212        &mut self,
213        module: &M,
214        dst: usize,
215        src: usize,
216        a: &A,
217        b: &B,
218        keys: &H,
219        scratch: &mut Scratch<BE>,
220    ) where
221        A: GLWEToRef + GLWEInfos,
222        B: GLWEToRef + GLWEInfos,
223        H: GLWEAutomorphismKeyHelper<K, BE>,
224        K: GGLWEPreparedToRef<BE> + GGLWEInfos + GetGaloisElement,
225        M: ModuleLogN + GLWERotate<BE> + GLWETrace<BE> + GLWESub + GLWEAdd + GLWECopy,
226        Scratch<BE>: ScratchTakeBDD<T, BE>,
227    {
228        assert!(dst < (T::BITS >> 3) as usize);
229        assert!(src < (T::BITS >> 3) as usize);
230
231        // 1) Zero the byte receiver
232        let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
233        let trace_start = (T::LOG_BITS - T::LOG_BYTES) as usize;
234        let rot: i64 = (T::bit_index(dst << 3) << log_gap) as i64;
235
236        // Move a to self and align byte
237        module.glwe_rotate(-rot, &mut self.bits, a);
238
239        // Stores this byte (everything else zeroed) into tmp_trace
240        let (mut tmp_trace, scratch_1) = scratch.take_glwe(a);
241        module.glwe_trace(
242            &mut tmp_trace,
243            trace_start,
244            module.log_n(),
245            self,
246            keys,
247            scratch_1,
248        );
249
250        // Subtracts to self to zero it
251        module.glwe_sub_inplace(&mut self.bits, &tmp_trace);
252
253        // Isolate the byte to transfer from a
254        let (mut tmp_fhe_uint_byte, scratch_1) = scratch.take_fhe_uint(b);
255
256        // Move a[byte_a] into a[0]
257        module.glwe_rotate(
258            -((T::bit_index(src << 3) << log_gap) as i64),
259            &mut tmp_fhe_uint_byte,
260            b,
261        );
262
263        // Zeroes all other bytes
264        module.glwe_trace_inplace(
265            &mut tmp_fhe_uint_byte,
266            trace_start,
267            module.log_n(),
268            keys,
269            scratch_1,
270        );
271
272        // Add self[0] += a[0]
273        module.glwe_add_inplace(&mut self.bits, &tmp_fhe_uint_byte);
274
275        // Moves back self[0] to self[byte_tg]
276        module.glwe_rotate_inplace(rot, &mut self.bits, scratch);
277    }
278}
279
280impl<D: DataMut, T: UnsignedInteger> GLWEToMut for FheUint<D, T> {
281    fn to_mut(&mut self) -> GLWE<&mut [u8]> {
282        self.bits.to_mut()
283    }
284}
285
286pub trait ScratchTakeBDD<T: UnsignedInteger, BE: Backend>
287where
288    Self: ScratchTakeCore<BE>,
289{
290    fn take_fhe_uint<A>(&mut self, infos: &A) -> (FheUint<&mut [u8], T>, &mut Self)
291    where
292        A: GLWEInfos,
293    {
294        let (glwe, scratch) = self.take_glwe(infos);
295        (
296            FheUint {
297                bits: glwe,
298                _phantom: PhantomData,
299            },
300            scratch,
301        )
302    }
303}
304
305impl<T: UnsignedInteger, BE: Backend> ScratchTakeBDD<T, BE> for Scratch<BE> where Self: ScratchTakeCore<BE> {}
306
307impl<D: DataRef, T: UnsignedInteger> FheUint<D, T> {
308    pub fn get_bit<R, K, M, BE: Backend>(&self, module: &M, bit: usize, res: &mut R, ks: &K, scratch: &mut Scratch<BE>)
309    where
310        R: LWEToMut,
311        K: GGLWEPreparedToRef<BE> + GGLWEInfos,
312        M: ModuleLogN + LWEFromGLWE<BE> + GLWERotate<BE>,
313        Scratch<BE>: ScratchTakeCore<BE>,
314    {
315        let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
316        res.to_mut()
317            .from_glwe(module, self, T::bit_index(bit) << log_gap, ks, scratch);
318    }
319}
320
321impl<D: DataRef, T: UnsignedInteger> GLWEToRef for FheUint<D, T> {
322    fn to_ref(&self) -> GLWE<&[u8]> {
323        self.bits.to_ref()
324    }
325}