poulpy/poulpy-schemes/src/bin_fhe/bdd_arithmetic/ciphertexts/fhe_uint.rs
poulpy-schemes/src/bin_fhe/bdd_arithmetic/ciphertexts/fhe_uint.rsRaw
1use poulpy_core::{
2 GLWEAdd, GLWECopy, GLWEDecrypt, GLWEEncryptSk, GLWEKeyswitch, GLWENoise, GLWEPacking, GLWERotate, GLWESub, GLWETrace,
3 LWEFromGLWE, ScratchTakeCore,
4 layouts::{
5 Base2K, Degree, GGLWEInfos, GGLWEPreparedToRef, GLWE, GLWEAutomorphismKeyHelper, GLWEInfos, GLWELayout,
6 GLWEPlaintextLayout, GLWESecretPreparedToRef, GLWEToMut, GLWEToRef, GetGaloisElement, LWEInfos, LWEToMut, Rank,
7 TorusPrecision,
8 },
9};
10use poulpy_hal::{
11 api::ModuleLogN,
12 layouts::{Backend, Data, DataMut, DataRef, Scratch, Stats},
13 source::Source,
14};
15use std::{collections::HashMap, marker::PhantomData};
16
17use crate::bin_fhe::bdd_arithmetic::{Cmux, FheUintPrepared, FromBits, GetGGSWBit, ToBits, UnsignedInteger};
18
19/// An FHE ciphertext encrypting the bits of an [UnsignedInteger].
20pub struct FheUint<D: Data, T: UnsignedInteger> {
21 pub(crate) bits: GLWE<D>,
22 pub(crate) _phantom: PhantomData<T>,
23}
24
25impl<T: UnsignedInteger> FheUint<Vec<u8>, T> {
26 pub fn alloc_from_infos<A>(infos: &A) -> Self
27 where
28 A: GLWEInfos,
29 {
30 Self::alloc(infos.n(), infos.base2k(), infos.k(), infos.rank())
31 }
32
33 pub fn alloc(n: Degree, base2k: Base2K, k: TorusPrecision, rank: Rank) -> Self {
34 Self {
35 bits: GLWE::alloc(n, base2k, k, rank),
36 _phantom: PhantomData,
37 }
38 }
39}
40
41impl<'a, T: UnsignedInteger> FheUint<&'a mut [u8], T> {
42 pub fn from_glwe_to_mut<G>(glwe: &'a mut G) -> Self
43 where
44 G: GLWEToMut,
45 {
46 FheUint {
47 bits: glwe.to_mut(),
48 _phantom: PhantomData,
49 }
50 }
51}
52
53impl<'a, T: UnsignedInteger> FheUint<&'a [u8], T> {
54 pub fn from_glwe_to_ref<G>(glwe: &'a G) -> Self
55 where
56 G: GLWEToRef,
57 {
58 FheUint {
59 bits: glwe.to_ref(),
60 _phantom: PhantomData,
61 }
62 }
63}
64
65impl<D: DataRef, T: UnsignedInteger> LWEInfos for FheUint<D, T> {
66 fn base2k(&self) -> poulpy_core::layouts::Base2K {
67 self.bits.base2k()
68 }
69
70 fn k(&self) -> poulpy_core::layouts::TorusPrecision {
71 self.bits.k()
72 }
73
74 fn n(&self) -> poulpy_core::layouts::Degree {
75 self.bits.n()
76 }
77}
78
79impl<D: DataRef, T: UnsignedInteger> GLWEInfos for FheUint<D, T> {
80 fn rank(&self) -> poulpy_core::layouts::Rank {
81 self.bits.rank()
82 }
83}
84
85impl<D: DataMut, T: UnsignedInteger + ToBits> FheUint<D, T> {
86 pub fn encrypt_sk<S, M, BE: Backend>(
87 &mut self,
88 module: &M,
89 data: T,
90 sk_glwe: &S,
91 source_xa: &mut Source,
92 source_xe: &mut Source,
93 scratch: &mut Scratch<BE>,
94 ) where
95 S: GLWESecretPreparedToRef<BE> + GLWEInfos,
96 M: ModuleLogN + GLWEEncryptSk<BE>,
97 Scratch<BE>: ScratchTakeCore<BE>,
98 {
99 #[cfg(debug_assertions)]
100 {
101 assert!(module.n().is_multiple_of(T::BITS as usize));
102 assert_eq!(self.n(), module.n() as u32);
103 assert_eq!(sk_glwe.n(), module.n() as u32);
104 }
105
106 let mut data_bits: Vec<i64> = vec![0i64; module.n()];
107
108 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
109
110 // Interleaves bytes
111 for i in 0..T::BITS as usize {
112 data_bits[T::bit_index(i) << log_gap] = data.bit(i) as i64
113 }
114
115 let pt_infos = GLWEPlaintextLayout {
116 n: self.n(),
117 base2k: self.base2k(),
118 k: 2_usize.into(),
119 };
120
121 let (mut pt, scratch_1) = scratch.take_glwe_plaintext(&pt_infos);
122
123 pt.encode_vec_i64(&data_bits, TorusPrecision(2));
124 self.bits.encrypt_sk(module, &pt, sk_glwe, source_xa, source_xe, scratch_1);
125 }
126}
127
128impl<D: DataRef, T: UnsignedInteger + FromBits> FheUint<D, T> {
129 pub fn noise<S, M, BE: Backend>(&self, module: &M, want: u32, sk: &S, scratch: &mut Scratch<BE>) -> Stats
130 where
131 S: GLWESecretPreparedToRef<BE> + GLWEInfos,
132 M: ModuleLogN + GLWEDecrypt<BE> + GLWENoise<BE>,
133 Scratch<BE>: ScratchTakeCore<BE>,
134 {
135 #[cfg(debug_assertions)]
136 {
137 assert!(module.n().is_multiple_of(T::BITS as usize));
138 assert_eq!(self.n(), module.n() as u32);
139 assert_eq!(sk.n(), module.n() as u32);
140 }
141
142 let (mut pt, scratch_1) = scratch.take_glwe_plaintext(self);
143 let mut data_bits = vec![0i64; module.n()];
144 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
145 for i in 0..T::BITS as usize {
146 data_bits[T::bit_index(i) << log_gap] = want.bit(i) as i64
147 }
148 pt.encode_vec_i64(&data_bits, TorusPrecision(2));
149 self.bits.noise(module, &pt, sk, scratch_1)
150 }
151
152 pub fn decrypt<S, M, BE: Backend>(&self, module: &M, sk_glwe: &S, scratch: &mut Scratch<BE>) -> T
153 where
154 S: GLWESecretPreparedToRef<BE> + GLWEInfos,
155 M: ModuleLogN + GLWEDecrypt<BE>,
156 Scratch<BE>: ScratchTakeCore<BE>,
157 {
158 #[cfg(debug_assertions)]
159 {
160 assert!(module.n().is_multiple_of(T::BITS as usize));
161 assert_eq!(self.n(), module.n() as u32);
162 assert_eq!(sk_glwe.n(), module.n() as u32);
163 }
164
165 let pt_infos = GLWEPlaintextLayout {
166 n: self.n(),
167 base2k: self.base2k(),
168 k: 1_usize.into(),
169 };
170
171 let (mut pt, scratch_1) = scratch.take_glwe_plaintext(&pt_infos);
172
173 self.bits.decrypt(module, &mut pt, sk_glwe, scratch_1);
174
175 let mut data_bits: Vec<i64> = vec![0i64; module.n()];
176 pt.decode_vec_i64(&mut data_bits, TorusPrecision(2));
177
178 let mut bits: Vec<u8> = vec![0u8; T::BITS as usize];
179
180 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
181
182 // Retrives from interleaved bytes
183 for i in 0..T::BITS as usize {
184 bits[i] = data_bits[T::bit_index(i) << log_gap] as u8
185 }
186
187 T::from_bits(&bits)
188 }
189}
190
191impl<D: DataMut, T: UnsignedInteger> FheUint<D, T> {
192 /// Packs Vec<GLWE(bit[i])> into [FheUint].
193 pub fn pack<G, M, K, H, BE: Backend>(&mut self, module: &M, mut bits: Vec<G>, keys: &H, scratch: &mut Scratch<BE>)
194 where
195 G: GLWEToMut + GLWEInfos,
196 M: ModuleLogN + GLWEPacking<BE> + GLWECopy,
197 K: GGLWEPreparedToRef<BE> + GetGaloisElement + GGLWEInfos,
198 H: GLWEAutomorphismKeyHelper<K, BE>,
199 Scratch<BE>: ScratchTakeCore<BE>,
200 {
201 // Repacks the GLWE ciphertexts bits
202 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
203 let mut cts: HashMap<usize, &mut G> = HashMap::new();
204 for (i, ct) in bits.iter_mut().enumerate().take(T::BITS as usize) {
205 cts.insert(T::bit_index(i) << log_gap, ct);
206 }
207
208 module.glwe_pack(&mut self.bits, cts, log_gap, keys, scratch);
209 }
210
211 #[allow(clippy::too_many_arguments)]
212 // Self <- ((a.rotate_right(dst<<4) & 0xFFFF_0000) | (b.rotate_right(src<<4) & 0x0000_FFFF)).rotate_left(dst<<4);
213 pub fn splice_u16<A, B, H, K, M, BE: Backend>(
214 &mut self,
215 module: &M,
216 dst: usize,
217 src: usize,
218 a: &A,
219 b: &B,
220 keys: &H,
221 scratch: &mut Scratch<BE>,
222 ) where
223 A: GLWEToRef + GLWEInfos,
224 B: GLWEToRef + GLWEInfos,
225 H: GLWEAutomorphismKeyHelper<K, BE>,
226 K: GGLWEPreparedToRef<BE> + GGLWEInfos + GetGaloisElement,
227 M: ModuleLogN + GLWERotate<BE> + GLWETrace<BE> + GLWESub + GLWEAdd + GLWECopy,
228 Scratch<BE>: ScratchTakeBDD<T, BE>,
229 {
230 assert!(dst < (T::BITS >> 4) as usize);
231 assert!(src < (T::BITS >> 4) as usize);
232
233 let (mut tmp, scratch_1) = scratch.take_fhe_uint(self);
234 tmp.splice_u8(module, dst << 1, src << 1, a, b, keys, scratch_1);
235 self.splice_u8(module, (dst << 1) + 1, (src << 1) + 1, &tmp, b, keys, scratch_1);
236 }
237
238 #[allow(clippy::too_many_arguments)]
239 // Self <- ((a.rotate_right(dst<<3) & 0xFFFF_FF00) | (b.rotate_right(src<<3) & 0x0000_00FF)).rotate_left(dst<<3);
240 pub fn splice_u8<A, B, H, K, M, BE: Backend>(
241 &mut self,
242 module: &M,
243 dst: usize,
244 src: usize,
245 a: &A,
246 b: &B,
247 keys: &H,
248 scratch: &mut Scratch<BE>,
249 ) where
250 A: GLWEToRef + GLWEInfos,
251 B: GLWEToRef + GLWEInfos,
252 H: GLWEAutomorphismKeyHelper<K, BE>,
253 K: GGLWEPreparedToRef<BE> + GGLWEInfos + GetGaloisElement,
254 M: ModuleLogN + GLWERotate<BE> + GLWETrace<BE> + GLWESub + GLWEAdd + GLWECopy,
255 Scratch<BE>: ScratchTakeBDD<T, BE>,
256 {
257 assert!(dst < (T::BITS >> 3) as usize);
258 assert!(src < (T::BITS >> 3) as usize);
259
260 // 1) Zero the byte receiver
261 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
262 let trace_start = (T::LOG_BITS - T::LOG_BYTES) as usize;
263 let rot: i64 = (T::bit_index(dst << 3) << log_gap) as i64;
264
265 module.glwe_copy(self, a);
266
267 self.zero_byte(module, dst, keys, scratch);
268
269 // Isolate the byte to transfer from a
270 let (mut tmp_fhe_uint_byte, scratch_1) = scratch.take_fhe_uint(b);
271
272 // Move a[byte_a] into a[dst]
273 module.glwe_rotate(-((T::bit_index(src << 3) << log_gap) as i64), &mut tmp_fhe_uint_byte, b);
274
275 // Zeroes all other bytes
276 module.glwe_trace_inplace(&mut tmp_fhe_uint_byte, trace_start, keys, scratch_1);
277
278 // Moves back self[0] to self[byte_tg]
279 module.glwe_rotate_inplace(rot, &mut tmp_fhe_uint_byte, scratch_1);
280
281 // Add self[0] += a[0]
282 module.glwe_add_inplace(&mut self.bits, &tmp_fhe_uint_byte);
283 }
284}
285
286impl<D: DataMut, T: UnsignedInteger> GLWEToMut for FheUint<D, T> {
287 fn to_mut(&mut self) -> GLWE<&mut [u8]> {
288 self.bits.to_mut()
289 }
290}
291
292pub trait ScratchTakeBDD<T: UnsignedInteger, BE: Backend>
293where
294 Self: ScratchTakeCore<BE>,
295{
296 fn take_fhe_uint<A>(&mut self, infos: &A) -> (FheUint<&mut [u8], T>, &mut Self)
297 where
298 A: GLWEInfos,
299 {
300 let (glwe, scratch) = self.take_glwe(infos);
301 (
302 FheUint {
303 bits: glwe,
304 _phantom: PhantomData,
305 },
306 scratch,
307 )
308 }
309}
310
311impl<T: UnsignedInteger, BE: Backend> ScratchTakeBDD<T, BE> for Scratch<BE> where Self: ScratchTakeCore<BE> {}
312
313impl<D: DataRef, T: UnsignedInteger> FheUint<D, T> {
314 pub fn get_bit_lwe<R, KGLWE, KLWE, M, BE: Backend>(
315 &self,
316 module: &M,
317 bit: usize,
318 res: &mut R,
319 ks_glwe: Option<&KGLWE>,
320 ks_lwe: &KLWE,
321 scratch: &mut Scratch<BE>,
322 ) where
323 R: LWEToMut,
324 KGLWE: GGLWEPreparedToRef<BE> + GGLWEInfos,
325 KLWE: GGLWEPreparedToRef<BE> + GGLWEInfos,
326 M: ModuleLogN + LWEFromGLWE<BE> + GLWERotate<BE> + GLWEKeyswitch<BE>,
327 Scratch<BE>: ScratchTakeCore<BE>,
328 {
329 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
330 if let Some(ks_glwe) = ks_glwe {
331 let (mut res_tmp, scratch_1) = scratch.take_glwe(&GLWELayout {
332 n: self.n(),
333 base2k: ks_lwe.base2k(),
334 k: ks_lwe.k().min(self.k()),
335 rank: ks_lwe.rank_out(),
336 });
337 module.glwe_keyswitch(&mut res_tmp, self, ks_glwe, scratch_1);
338 res.to_mut()
339 .from_glwe(module, &res_tmp, T::bit_index(bit) << log_gap, ks_lwe, scratch_1);
340 } else {
341 res.to_mut()
342 .from_glwe(module, self, T::bit_index(bit) << log_gap, ks_lwe, scratch);
343 }
344 }
345
346 pub fn get_bit_glwe<R, K, M, H, BE: Backend>(&self, module: &M, bit: usize, res: &mut R, keys: &H, scratch: &mut Scratch<BE>)
347 where
348 R: GLWEToMut,
349 K: GGLWEPreparedToRef<BE> + GGLWEInfos,
350 M: ModuleLogN + GLWERotate<BE> + GLWETrace<BE>,
351 H: GLWEAutomorphismKeyHelper<K, BE>,
352 K: GGLWEPreparedToRef<BE> + GGLWEInfos + GetGaloisElement,
353 Scratch<BE>: ScratchTakeCore<BE>,
354 {
355 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
356 let rot = (T::bit_index(bit) << log_gap) as i64;
357 module.glwe_rotate(-rot, res, self);
358 module.glwe_trace_inplace(res, 0, keys, scratch);
359 }
360
361 pub fn get_byte<R, K, M, H, BE: Backend>(&self, module: &M, byte: usize, res: &mut R, keys: &H, scratch: &mut Scratch<BE>)
362 where
363 R: GLWEToMut,
364 K: GGLWEPreparedToRef<BE> + GGLWEInfos,
365 M: ModuleLogN + GLWERotate<BE> + GLWETrace<BE>,
366 H: GLWEAutomorphismKeyHelper<K, BE>,
367 K: GGLWEPreparedToRef<BE> + GGLWEInfos + GetGaloisElement,
368 Scratch<BE>: ScratchTakeCore<BE>,
369 {
370 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
371 let trace_start = (T::LOG_BITS - T::LOG_BYTES) as usize;
372 let rot = (T::bit_index(byte << 3) << log_gap) as i64;
373 module.glwe_rotate(-rot, res, self);
374 module.glwe_trace_inplace(res, trace_start, keys, scratch);
375 }
376}
377
378impl<D: DataRef, T: UnsignedInteger> GLWEToRef for FheUint<D, T> {
379 fn to_ref(&self) -> GLWE<&[u8]> {
380 self.bits.to_ref()
381 }
382}
383
384impl<D: DataMut, T: UnsignedInteger> FheUint<D, T> {
385 pub fn from_fhe_uint_prepared<M, DR, H, K, BE: Backend>(
386 &mut self,
387 module: &M,
388 other: &FheUintPrepared<DR, T, BE>,
389 keys: &H,
390 scratch: &mut Scratch<BE>,
391 ) where
392 DR: DataRef,
393 M: Cmux<BE> + ModuleLogN + GLWEPacking<BE> + GLWECopy,
394 Scratch<BE>: ScratchTakeCore<BE>,
395 K: GGLWEPreparedToRef<BE> + GetGaloisElement + GGLWEInfos,
396 H: GLWEAutomorphismKeyHelper<K, BE>,
397 {
398 let zero: GLWE<Vec<u8>> = GLWE::alloc_from_infos(self);
399 let mut one: GLWE<Vec<u8>> = GLWE::alloc_from_infos(self);
400 one.data_mut().encode_coeff_i64(self.base2k().into(), 0, 2, 0, 1);
401
402 let (mut out_bits, scratch_1) = scratch.take_glwe_slice(T::BITS as usize, self);
403
404 for (i, bits) in out_bits.iter_mut().enumerate().take(T::BITS as usize) {
405 module.cmux(bits, &one, &zero, &other.get_bit(i), scratch_1);
406 }
407
408 self.pack(module, out_bits, keys, scratch_1);
409 }
410
411 pub fn zero_byte<M, K, H, BE: Backend>(&mut self, module: &M, byte: usize, keys: &H, scratch: &mut Scratch<BE>)
412 where
413 H: GLWEAutomorphismKeyHelper<K, BE>,
414 K: GGLWEPreparedToRef<BE> + GGLWEInfos + GetGaloisElement,
415 M: ModuleLogN + GLWERotate<BE> + GLWETrace<BE> + GLWESub + GLWEAdd + GLWECopy,
416 Scratch<BE>: ScratchTakeBDD<T, BE>,
417 {
418 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
419 let trace_start = (T::LOG_BITS - T::LOG_BYTES) as usize;
420 let rot: i64 = (T::bit_index(byte << 3) << log_gap) as i64;
421
422 // Move a to self and align byte
423 module.glwe_rotate_inplace(-rot, &mut self.bits, scratch);
424
425 // Stores this byte (everything else zeroed) into tmp_trace
426 let (mut tmp_trace, scratch_1) = scratch.take_glwe(self);
427 module.glwe_trace(&mut tmp_trace, trace_start, self, keys, scratch_1);
428
429 // Subtracts to self to zero it
430 module.glwe_sub_inplace(&mut self.bits, &tmp_trace);
431
432 // Move a to self and align byte
433 module.glwe_rotate_inplace(rot, &mut self.bits, scratch);
434 }
435
436 pub fn sext<M, H, K, BE>(&mut self, module: &M, byte: usize, keys: &H, scratch: &mut Scratch<BE>)
437 where
438 M:,
439 H: GLWEAutomorphismKeyHelper<K, BE>,
440 K: GGLWEPreparedToRef<BE> + GGLWEInfos + GetGaloisElement,
441 BE: Backend,
442 M: ModuleLogN + GLWERotate<BE> + GLWETrace<BE> + GLWEAdd + GLWESub + GLWECopy,
443 Scratch<BE>: ScratchTakeCore<BE>,
444 {
445 assert!(byte < (1 << T::LOG_BYTES));
446
447 let log_gap: usize = module.log_n() - T::LOG_BITS as usize;
448 let rot: i64 = (T::bit_index((byte << 3) + 7) << log_gap) as i64;
449
450 let (mut sext, scratch_1) = scratch.take_glwe(self);
451
452 // Extract MSB
453 module.glwe_rotate(-rot, &mut sext, &self.bits);
454 module.glwe_trace_inplace(&mut sext, 0, keys, scratch_1);
455
456 // Replicates MSB in byte
457 for i in 0..3 {
458 let (mut tmp, _) = scratch_1.take_glwe(self);
459 module.glwe_rotate(((1 << T::LOG_BYTES) << log_gap) << i, &mut tmp, &sext);
460 module.glwe_add_inplace(&mut sext, &tmp);
461 }
462
463 // Splice sext
464 let (mut tmp, scratch_2) = scratch_1.take_glwe(self);
465 for i in (byte + 1)..(1 << T::LOG_BYTES) as usize {
466 FheUint::<&mut [u8], T>::from_glwe_to_mut(&mut tmp).splice_u8(module, i, 0, &self.bits, &sext, keys, scratch_2);
467 module.glwe_copy(&mut self.bits, &tmp);
468 }
469 }
470}