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