phantom-zone/src/pbs.rs
src/pbs.rsRaw
1use std::{fmt::Display, marker::PhantomData};
2
3use num_traits::{FromPrimitive, One, PrimInt, ToPrimitive, Zero};
4
5use crate::{
6 backend::{ArithmeticOps, Modulus, ShoupMatrixFMA, VectorOps},
7 decomposer::Decomposer,
8 lwe::lwe_key_switch,
9 ntt::Ntt,
10 random::DefaultSecureRng,
11 rgsw::{
12 galois_auto, galois_auto_shoup, rlwe_by_rgsw, rlwe_by_rgsw_shoup, IsTrivial, RlweCiphertext,
13 },
14 Matrix, MatrixEntity, MatrixMut, RowMut,
15};
16pub(crate) trait PbsKey {
17 type RgswCt;
18 type AutoKey;
19 type LweKskKey;
20
21 /// RGSW ciphertext of LWE secret elements
22 fn rgsw_ct_lwe_si(&self, si: usize) -> &Self::RgswCt;
23 /// Key for automorphism with g^k. For -g use k = 0
24 fn galois_key_for_auto(&self, k: usize) -> &Self::AutoKey;
25 /// LWE ksk to key switch from RLWE secret to LWE secret
26 fn lwe_ksk(&self) -> &Self::LweKskKey;
27}
28
29pub(crate) trait WithShoupRepr: AsRef<Self::M> {
30 type M;
31 fn shoup_repr(&self) -> &Self::M;
32}
33
34pub(crate) trait PbsInfo {
35 type M: Matrix;
36 type Modulus: Modulus<Element = <Self::M as Matrix>::MatElement>;
37 type NttOp: Ntt<Element = <Self::M as Matrix>::MatElement>;
38 type D: Decomposer<Element = <Self::M as Matrix>::MatElement>;
39
40 // Although both types have same bounds, they can be different types. For ex,
41 // type RlweModOp may only support native modulus, where LweModOp may only
42 // support prime modulus, etc.
43 type RlweModOp: ArithmeticOps<Element = <Self::M as Matrix>::MatElement>
44 + ShoupMatrixFMA<<Self::M as Matrix>::R>;
45 type LweModOp: VectorOps<Element = <Self::M as Matrix>::MatElement>
46 + ArithmeticOps<Element = <Self::M as Matrix>::MatElement>;
47
48 fn rlwe_q(&self) -> &Self::Modulus;
49 fn lwe_q(&self) -> &Self::Modulus;
50 fn br_q(&self) -> usize;
51 fn rlwe_n(&self) -> usize;
52 fn lwe_n(&self) -> usize;
53 /// Embedding fator for ring X^{q}+1 inside
54 fn embedding_factor(&self) -> usize;
55 /// Window size
56 fn w(&self) -> usize;
57 /// generator g
58 fn g(&self) -> isize;
59 /// Decomposers
60 fn lwe_decomposer(&self) -> &Self::D;
61 fn rlwe_rgsw_decomposer(&self) -> &(Self::D, Self::D);
62 fn auto_decomposer(&self) -> &Self::D;
63
64 /// Modulus operators
65 fn modop_lweq(&self) -> &Self::LweModOp;
66 fn modop_rlweq(&self) -> &Self::RlweModOp;
67
68 /// Ntt operators
69 fn nttop_rlweq(&self) -> &Self::NttOp;
70
71 /// Maps a \in Z^*_{q} to discrete log k, with generator g (i.e. g^k =
72 /// a). Returned vector is of size q that stores dlog of a at `vec[a]`.
73 /// For any a, if k is s.t. a = g^{k}, then k is expressed as k. If k is s.t
74 /// a = -g^{k}, then k is expressed as k=k+q/4
75 fn g_k_dlog_map(&self) -> &[usize];
76 /// Returns auto map and index vector for g^k. For -g use k == 0.
77 fn rlwe_auto_map(&self, k: usize) -> &(Vec<usize>, Vec<bool>);
78}
79
80/// - Mod down
81/// - key switching
82/// - mod down
83/// - blind rotate
84pub(crate) fn pbs<
85 M: MatrixMut + MatrixEntity,
86 MShoup: WithShoupRepr<M = M>,
87 P: PbsInfo<M = M>,
88 K: PbsKey<RgswCt = MShoup, AutoKey = MShoup, LweKskKey = M>,
89>(
90 pbs_info: &P,
91 test_vec: &M::R,
92 lwe_in: &mut M::R,
93 pbs_key: &K,
94 scratch_lwe_vec: &mut M::R,
95 scratch_blind_rotate_matrix: &mut M,
96) where
97 <M as Matrix>::R: RowMut,
98 M::MatElement: PrimInt + FromPrimitive + One + Copy + Zero + Display,
99{
100 let rlwe_q = pbs_info.rlwe_q();
101 let lwe_q = pbs_info.lwe_q();
102 let br_q = pbs_info.br_q();
103 let rlwe_qf64 = rlwe_q.q_as_f64().unwrap();
104 let lwe_qf64 = lwe_q.q_as_f64().unwrap();
105 let br_qf64 = br_q.to_f64().unwrap();
106 let rlwe_n = pbs_info.rlwe_n();
107
108 // moddown Q -> Q_ks
109 lwe_in.as_mut().iter_mut().for_each(|v| {
110 *v =
111 M::MatElement::from_f64(((v.to_f64().unwrap() * lwe_qf64) / rlwe_qf64).round()).unwrap()
112 });
113
114 // key switch RLWE secret to LWE secret
115 // let now = std::time::Instant::now();
116 scratch_lwe_vec.as_mut().fill(M::MatElement::zero());
117 lwe_key_switch(
118 scratch_lwe_vec,
119 lwe_in,
120 pbs_key.lwe_ksk(),
121 pbs_info.modop_lweq(),
122 pbs_info.lwe_decomposer(),
123 );
124 // println!("Time: {:?}", now.elapsed());
125
126 // odd mowdown Q_ks -> q
127 let g_k_dlog_map = pbs_info.g_k_dlog_map();
128 let mut g_k_si = vec![vec![]; br_q >> 1];
129 scratch_lwe_vec
130 .as_ref()
131 .iter()
132 .skip(1)
133 .enumerate()
134 .for_each(|(index, v)| {
135 let odd_v = mod_switch_odd(v.to_f64().unwrap(), lwe_qf64, br_qf64);
136 // dlog `k` for `odd_v` is stored as `k` if odd_v = +g^{k}. If odd_v = -g^{k},
137 // then `k` is stored as `q/4 + k`.
138 let k = g_k_dlog_map[odd_v];
139 // assert!(k != 0);
140 g_k_si[k].push(index);
141 });
142
143 // handle b and set trivial test RLWE
144 let g = pbs_info.g() as usize;
145 let g_times_b = (g * mod_switch_odd(
146 scratch_lwe_vec.as_ref()[0].to_f64().unwrap(),
147 lwe_qf64,
148 br_qf64,
149 )) % (br_q);
150 // v = (v(X) * X^{g*b}) mod X^{q/2}+1
151 let br_qby2 = br_q >> 1;
152 let mut gb_monomial_sign = true;
153 let mut gb_monomial_exp = g_times_b;
154 // X^{g*b} mod X^{q/2}+1
155 if gb_monomial_exp > br_qby2 {
156 gb_monomial_exp -= br_qby2;
157 gb_monomial_sign = false
158 }
159 // monomial mul
160 let mut trivial_rlwe_test_poly = RlweCiphertext::<_, DefaultSecureRng> {
161 data: M::zeros(2, rlwe_n),
162 is_trivial: true,
163 _phatom: PhantomData,
164 };
165 if pbs_info.embedding_factor() == 1 {
166 monomial_mul(
167 test_vec.as_ref(),
168 trivial_rlwe_test_poly.get_row_mut(1).as_mut(),
169 gb_monomial_exp,
170 gb_monomial_sign,
171 br_qby2,
172 pbs_info.modop_rlweq(),
173 );
174 } else {
175 // use lwe_in to store the `t = v(X) * X^{g*2} mod X^{q/2}+1` temporarily. This
176 // works because q/2 <= N (where N is lwe_in LWE dimension) always.
177 monomial_mul(
178 test_vec.as_ref(),
179 &mut lwe_in.as_mut()[..br_qby2],
180 gb_monomial_exp,
181 gb_monomial_sign,
182 br_qby2,
183 pbs_info.modop_rlweq(),
184 );
185
186 // emebed poly `t` in ring X^{q/2}+1 inside the bigger ring X^{N}+1
187 let embed_factor = pbs_info.embedding_factor();
188 let partb_trivial_rlwe = trivial_rlwe_test_poly.get_row_mut(1);
189 lwe_in.as_ref()[..br_qby2]
190 .iter()
191 .enumerate()
192 .for_each(|(index, v)| {
193 partb_trivial_rlwe[embed_factor * index] = *v;
194 });
195 }
196
197 // let now = std::time::Instant::now();
198 // blind rotate
199 blind_rotation(
200 &mut trivial_rlwe_test_poly,
201 scratch_blind_rotate_matrix,
202 pbs_info.g(),
203 pbs_info.w(),
204 br_q,
205 &g_k_si,
206 pbs_info.rlwe_rgsw_decomposer(),
207 pbs_info.auto_decomposer(),
208 pbs_info.nttop_rlweq(),
209 pbs_info.modop_rlweq(),
210 pbs_info,
211 pbs_key,
212 );
213 // println!("Blind rotation time: {:?}", now.elapsed());
214
215 // sample extract
216 sample_extract(lwe_in, &trivial_rlwe_test_poly, pbs_info.modop_rlweq(), 0);
217}
218
219/// LMKCY+ Blind rotation
220///
221/// gk_to_si: [g^0, ..., g^{q/2-1}, -g^0, -g^1, .., -g^{q/2-1}]
222fn blind_rotation<
223 MT: IsTrivial + MatrixMut,
224 Mmut: MatrixMut<MatElement = MT::MatElement>,
225 D: Decomposer<Element = MT::MatElement>,
226 NttOp: Ntt<Element = MT::MatElement>,
227 ModOp: ArithmeticOps<Element = MT::MatElement> + ShoupMatrixFMA<Mmut::R>,
228 MShoup: WithShoupRepr<M = Mmut>,
229 K: PbsKey<RgswCt = MShoup, AutoKey = MShoup>,
230 P: PbsInfo<M = Mmut>,
231>(
232 trivial_rlwe_test_poly: &mut MT,
233 scratch_matrix: &mut Mmut,
234 _g: isize,
235 w: usize,
236 q: usize,
237 gk_to_si: &[Vec<usize>],
238 rlwe_rgsw_decomposer: &(D, D),
239 auto_decomposer: &D,
240 ntt_op: &NttOp,
241 mod_op: &ModOp,
242 parameters: &P,
243 pbs_key: &K,
244) where
245 <Mmut as Matrix>::R: RowMut,
246 Mmut::MatElement: Copy + Zero,
247 <MT as Matrix>::R: RowMut,
248{
249 let q_by_4 = q >> 2;
250 let mut count = 0;
251 // -(g^k)
252 let mut v = 0;
253 for i in (1..q_by_4).rev() {
254 // dbg!(q_by_4 + i);
255 let s_indices = &gk_to_si[q_by_4 + i];
256
257 s_indices.iter().for_each(|s_index| {
258 // let new = std::time::Instant::now();
259 let ct = pbs_key.rgsw_ct_lwe_si(*s_index);
260 rlwe_by_rgsw_shoup(
261 trivial_rlwe_test_poly,
262 ct.as_ref(),
263 ct.shoup_repr(),
264 scratch_matrix,
265 rlwe_rgsw_decomposer,
266 ntt_op,
267 mod_op,
268 );
269 // println!("Rlwe x Rgsw time: {:?}", new.elapsed());
270 });
271 v += 1;
272
273 if gk_to_si[q_by_4 + i - 1].len() != 0 || v == w || i == 1 {
274 let (auto_map_index, auto_map_sign) = parameters.rlwe_auto_map(v);
275
276 // let now = std::time::Instant::now();
277 let auto_key = pbs_key.galois_key_for_auto(v);
278 galois_auto_shoup(
279 trivial_rlwe_test_poly,
280 auto_key.as_ref(),
281 auto_key.shoup_repr(),
282 scratch_matrix,
283 &auto_map_index,
284 &auto_map_sign,
285 mod_op,
286 ntt_op,
287 auto_decomposer,
288 );
289 // println!("Auto time: {:?}", now.elapsed());
290
291 count += 1;
292 v = 0;
293 }
294 }
295
296 // -(g^0)
297 {
298 gk_to_si[q_by_4].iter().for_each(|s_index| {
299 let ct = pbs_key.rgsw_ct_lwe_si(*s_index);
300 rlwe_by_rgsw_shoup(
301 trivial_rlwe_test_poly,
302 ct.as_ref(),
303 ct.shoup_repr(),
304 scratch_matrix,
305 rlwe_rgsw_decomposer,
306 ntt_op,
307 mod_op,
308 );
309 });
310
311 let (auto_map_index, auto_map_sign) = parameters.rlwe_auto_map(0);
312 let auto_key = pbs_key.galois_key_for_auto(0);
313 galois_auto_shoup(
314 trivial_rlwe_test_poly,
315 auto_key.as_ref(),
316 auto_key.shoup_repr(),
317 scratch_matrix,
318 &auto_map_index,
319 &auto_map_sign,
320 mod_op,
321 ntt_op,
322 auto_decomposer,
323 );
324 count += 1;
325 }
326
327 // +(g^k)
328 let mut v = 0;
329 for i in (1..q_by_4).rev() {
330 let s_indices = &gk_to_si[i];
331 s_indices.iter().for_each(|s_index| {
332 let ct = pbs_key.rgsw_ct_lwe_si(*s_index);
333 rlwe_by_rgsw_shoup(
334 trivial_rlwe_test_poly,
335 ct.as_ref(),
336 ct.shoup_repr(),
337 scratch_matrix,
338 rlwe_rgsw_decomposer,
339 ntt_op,
340 mod_op,
341 );
342 });
343 v += 1;
344
345 if gk_to_si[i - 1].len() != 0 || v == w || i == 1 {
346 let (auto_map_index, auto_map_sign) = parameters.rlwe_auto_map(v);
347 let auto_key = pbs_key.galois_key_for_auto(v);
348 galois_auto_shoup(
349 trivial_rlwe_test_poly,
350 auto_key.as_ref(),
351 auto_key.shoup_repr(),
352 scratch_matrix,
353 &auto_map_index,
354 &auto_map_sign,
355 mod_op,
356 ntt_op,
357 auto_decomposer,
358 );
359 v = 0;
360 count += 1;
361 }
362 }
363
364 // +(g^0)
365 gk_to_si[0].iter().for_each(|s_index| {
366 let ct = pbs_key.rgsw_ct_lwe_si(*s_index);
367 rlwe_by_rgsw_shoup(
368 trivial_rlwe_test_poly,
369 ct.as_ref(),
370 ct.shoup_repr(),
371 scratch_matrix,
372 rlwe_rgsw_decomposer,
373 ntt_op,
374 mod_op,
375 );
376 });
377 // println!("Auto count: {count}");
378}
379
380fn mod_switch_odd(v: f64, from_q: f64, to_q: f64) -> usize {
381 let odd_v = (((v * to_q) / (from_q)).floor()).to_usize().unwrap();
382 //TODO(Jay): check correctness of this
383 odd_v + ((odd_v & 1) ^ 1)
384}
385
386// TODO(Jay): Add tests for sample extract
387pub(crate) fn sample_extract<M: Matrix + MatrixMut, ModOp: ArithmeticOps<Element = M::MatElement>>(
388 lwe_out: &mut M::R,
389 rlwe_in: &M,
390 mod_op: &ModOp,
391 index: usize,
392) where
393 <M as Matrix>::R: RowMut,
394 M::MatElement: Copy,
395{
396 let ring_size = rlwe_in.dimension().1;
397
398 // index..=0
399 let to = &mut lwe_out.as_mut()[1..];
400 let from = rlwe_in.get_row_slice(0);
401 for i in 0..index + 1 {
402 to[i] = from[index - i];
403 }
404
405 // -(N..index)
406 for i in index + 1..ring_size {
407 to[i] = mod_op.neg(&from[ring_size + index - i]);
408 }
409
410 // set b
411 lwe_out.as_mut()[0] = *rlwe_in.get(1, index);
412}
413
414/// Monomial multiplication (p(X)*X^{mon_exp})
415///
416/// - p_out: Output is written to p_out and independent of values in p_out
417fn monomial_mul<El, ModOp: ArithmeticOps<Element = El>>(
418 p_in: &[El],
419 p_out: &mut [El],
420 mon_exp: usize,
421 mon_sign: bool,
422 ring_size: usize,
423 mod_op: &ModOp,
424) where
425 El: Copy,
426{
427 debug_assert!(p_in.as_ref().len() == ring_size);
428 debug_assert!(p_in.as_ref().len() == p_out.as_ref().len());
429 debug_assert!(mon_exp < ring_size);
430
431 p_in.as_ref().iter().enumerate().for_each(|(index, v)| {
432 let mut to_index = index + mon_exp;
433 let mut to_sign = mon_sign;
434 if to_index >= ring_size {
435 to_index = to_index - ring_size;
436 to_sign = !to_sign;
437 }
438
439 if !to_sign {
440 p_out.as_mut()[to_index] = mod_op.neg(v);
441 } else {
442 p_out.as_mut()[to_index] = *v;
443 }
444 });
445}