updated repo for publishing (#74)

This commit is contained in:
Jean-Philippe Bossuat
2025-08-17 14:57:39 +02:00
committed by GitHub
parent 0be569eca0
commit 62eb87cc07
244 changed files with 374 additions and 539 deletions

View File

@@ -0,0 +1,156 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxDft, VecZnxAutomorphism, VecZnxAutomorphismInplace, VecZnxBigAddSmallInplace,
VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume,
VmpApply, VmpApplyAdd, VmpApplyTmpBytes, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::layouts::{GGLWEAutomorphismKey, GLWECiphertext, Infos, prepared::GGLWEAutomorphismKeyPrepared};
impl GGLWEAutomorphismKey<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn automorphism_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GLWECiphertext::keyswitch_scratch_space(module, n, basek, k_out, k_in, k_ksk, digits, rank, rank)
}
pub fn automorphism_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GGLWEAutomorphismKey::automorphism_scratch_space(module, n, basek, k_out, k_out, k_ksk, digits, rank)
}
}
impl<DataSelf: DataMut> GGLWEAutomorphismKey<DataSelf> {
pub fn automorphism<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGLWEAutomorphismKey<DataLhs>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxAutomorphism
+ VecZnxAutomorphismInplace,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(
self.rank_in(),
lhs.rank_in(),
"ksk_out input rank: {} != ksk_in input rank: {}",
self.rank_in(),
lhs.rank_in()
);
assert_eq!(
lhs.rank_out(),
rhs.rank_in(),
"ksk_in output rank: {} != ksk_apply input rank: {}",
self.rank_out(),
rhs.rank_in()
);
assert_eq!(
self.rank_out(),
rhs.rank_out(),
"ksk_out output rank: {} != ksk_apply output rank: {}",
self.rank_out(),
rhs.rank_out()
);
assert!(
self.k() <= lhs.k(),
"output k={} cannot be greater than input k={}",
self.k(),
lhs.k()
)
}
let cols_out: usize = rhs.rank_out() + 1;
let p: i64 = lhs.p();
let p_inv = module.galois_element_inv(p);
(0..self.rank_in()).for_each(|col_i| {
(0..self.rows()).for_each(|row_j| {
let mut res_ct: GLWECiphertext<&mut [u8]> = self.at_mut(row_j, col_i);
let lhs_ct: GLWECiphertext<&[u8]> = lhs.at(row_j, col_i);
// Reverts the automorphism X^{-k}: (-pi^{-1}_{k}(s)a + s, a) to (-sa + pi_{k}(s), a)
(0..cols_out).for_each(|i| {
module.vec_znx_automorphism(lhs.p(), &mut res_ct.data, i, &lhs_ct.data, i);
});
// Key-switch (-sa + pi_{k}(s), a) to (-pi^{-1}_{k'}(s)a + pi_{k}(s), a)
res_ct.keyswitch_inplace(module, &rhs.key, scratch);
// Applies back the automorphism X^{-k}: (-pi^{-1}_{k'}(s)a + pi_{k}(s), a) to (-pi^{-1}_{k'+k}(s)a + s, a)
(0..cols_out).for_each(|i| {
module.vec_znx_automorphism_inplace(p_inv, &mut res_ct.data, i);
});
});
});
(self.rows().min(lhs.rows())..self.rows()).for_each(|row_i| {
(0..self.rank_in()).for_each(|col_j| {
self.at_mut(row_i, col_j).data.zero();
});
});
self.p = (lhs.p * rhs.p) % (module.cyclotomic_order() as i64);
}
pub fn automorphism_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxAutomorphism
+ VecZnxAutomorphismInplace,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B>,
{
unsafe {
let self_ptr: *mut GGLWEAutomorphismKey<DataSelf> = self as *mut GGLWEAutomorphismKey<DataSelf>;
self.automorphism(module, &*self_ptr, rhs, scratch);
}
}
}

View File

@@ -0,0 +1,194 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxBig, TakeVecZnxDft, VecZnxAutomorphismInplace, VecZnxBigAddSmallInplace, VecZnxBigAllocBytes,
VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxDftAddInplace, VecZnxDftAllocBytes, VecZnxDftCopy,
VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxDftToVecZnxBigTmpA, VecZnxNormalizeTmpBytes, VmpApply,
VmpApplyAdd, VmpApplyTmpBytes,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::layouts::{
GGSWCiphertext, GLWECiphertext, Infos,
prepared::{GGLWEAutomorphismKeyPrepared, GGLWETensorKeyPrepared},
};
impl GGSWCiphertext<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn automorphism_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ksk: usize,
digits_ksk: usize,
k_tsk: usize,
digits_tsk: usize,
rank: usize,
) -> usize
where
Module<B>:
VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigAllocBytes + VecZnxNormalizeTmpBytes + VecZnxBigNormalizeTmpBytes,
{
let out_size: usize = k_out.div_ceil(basek);
let ci_dft: usize = module.vec_znx_dft_alloc_bytes(n, rank + 1, out_size);
let ks_internal: usize =
GLWECiphertext::keyswitch_scratch_space(module, n, basek, k_out, k_in, k_ksk, digits_ksk, rank, rank);
let expand: usize = GGSWCiphertext::expand_row_scratch_space(module, n, basek, k_out, k_tsk, digits_tsk, rank);
ci_dft + (ks_internal | expand)
}
#[allow(clippy::too_many_arguments)]
pub fn automorphism_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ksk: usize,
digits_ksk: usize,
k_tsk: usize,
digits_tsk: usize,
rank: usize,
) -> usize
where
Module<B>:
VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigAllocBytes + VecZnxNormalizeTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GGSWCiphertext::automorphism_scratch_space(
module, n, basek, k_out, k_out, k_ksk, digits_ksk, k_tsk, digits_tsk, rank,
)
}
}
impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
pub fn automorphism<DataLhs: DataRef, DataAk: DataRef, DataTsk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGSWCiphertext<DataLhs>,
auto_key: &GGLWEAutomorphismKeyPrepared<DataAk, B>,
tensor_key: &GGLWETensorKeyPrepared<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxAutomorphismInplace
+ VecZnxBigAllocBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftCopy<B>
+ VecZnxDftAddInplace<B>
+ VecZnxDftToVecZnxBigTmpA<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnxBig<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), auto_key.n());
assert_eq!(lhs.n(), auto_key.n());
assert_eq!(
self.rank(),
lhs.rank(),
"ggsw_out rank: {} != ggsw_in rank: {}",
self.rank(),
lhs.rank()
);
assert_eq!(
self.rank(),
auto_key.rank(),
"ggsw_in rank: {} != auto_key rank: {}",
self.rank(),
auto_key.rank()
);
assert_eq!(
self.rank(),
tensor_key.rank(),
"ggsw_in rank: {} != tensor_key rank: {}",
self.rank(),
tensor_key.rank()
);
assert!(
scratch.available()
>= GGSWCiphertext::automorphism_scratch_space(
module,
self.n(),
self.basek(),
self.k(),
lhs.k(),
auto_key.k(),
auto_key.digits(),
tensor_key.k(),
tensor_key.digits(),
self.rank(),
)
)
};
self.automorphism_internal(module, lhs, auto_key, scratch);
self.expand_row(module, tensor_key, scratch);
}
pub fn automorphism_inplace<DataKsk: DataRef, DataTsk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
auto_key: &GGLWEAutomorphismKeyPrepared<DataKsk, B>,
tensor_key: &GGLWETensorKeyPrepared<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxAutomorphismInplace
+ VecZnxBigAllocBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftCopy<B>
+ VecZnxDftAddInplace<B>
+ VecZnxDftToVecZnxBigTmpA<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnxBig<B>,
{
unsafe {
let self_ptr: *mut GGSWCiphertext<DataSelf> = self as *mut GGSWCiphertext<DataSelf>;
self.automorphism(module, &*self_ptr, auto_key, tensor_key, scratch);
}
}
fn automorphism_internal<DataLhs: DataRef, DataAk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGSWCiphertext<DataLhs>,
auto_key: &GGLWEAutomorphismKeyPrepared<DataAk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxAutomorphismInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
// Keyswitch the j-th row of the col 0
(0..lhs.rows()).for_each(|row_i| {
// Key-switch column 0, i.e.
// col 0: (-(a0s0 + a1s1 + a2s2) + M[i], a0, a1, a2) -> (-(a0pi^-1(s0) + a1pi^-1(s1) + a2pi^-1(s2)) + M[i], a0, a1, a2)
self.at_mut(row_i, 0)
.automorphism(module, &lhs.at(row_i, 0), auto_key, scratch);
});
}
}

View File

@@ -0,0 +1,267 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxDft, VecZnxAutomorphismInplace, VecZnxBigAddSmallInplace, VecZnxBigAutomorphismInplace,
VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxBigSubSmallAInplace, VecZnxBigSubSmallBInplace,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VmpApply, VmpApplyAdd, VmpApplyTmpBytes,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch, VecZnxBig},
};
use crate::layouts::{GLWECiphertext, Infos, prepared::GGLWEAutomorphismKeyPrepared};
impl GLWECiphertext<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn automorphism_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
Self::keyswitch_scratch_space(module, n, basek, k_out, k_in, k_ksk, digits, rank, rank)
}
pub fn automorphism_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
Self::keyswitch_inplace_scratch_space(module, n, basek, k_out, k_ksk, digits, rank)
}
}
impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
pub fn automorphism<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxAutomorphismInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
self.keyswitch(module, lhs, &rhs.key, scratch);
(0..self.rank() + 1).for_each(|i| {
module.vec_znx_automorphism_inplace(rhs.p(), &mut self.data, i);
})
}
pub fn automorphism_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxAutomorphismInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
self.keyswitch_inplace(module, &rhs.key, scratch);
(0..self.rank() + 1).for_each(|i| {
module.vec_znx_automorphism_inplace(rhs.p(), &mut self.data, i);
})
}
pub fn automorphism_add<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxBigAutomorphismInplace<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
#[cfg(debug_assertions)]
{
self.assert_keyswitch(module, lhs, &rhs.key, scratch);
}
let (res_dft, scratch1) = scratch.take_vec_znx_dft(self.n(), self.cols(), rhs.size()); // TODO: optimise size
let mut res_big: VecZnxBig<_, B> = lhs.keyswitch_internal(module, res_dft, &rhs.key, scratch1);
(0..self.cols()).for_each(|i| {
module.vec_znx_big_automorphism_inplace(rhs.p(), &mut res_big, i);
module.vec_znx_big_add_small_inplace(&mut res_big, i, &lhs.data, i);
module.vec_znx_big_normalize(self.basek(), &mut self.data, i, &res_big, i, scratch1);
})
}
pub fn automorphism_add_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxBigAutomorphismInplace<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
unsafe {
let self_ptr: *mut GLWECiphertext<DataSelf> = self as *mut GLWECiphertext<DataSelf>;
self.automorphism_add(module, &*self_ptr, rhs, scratch);
}
}
pub fn automorphism_sub_ab<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxBigAutomorphismInplace<B>
+ VecZnxBigSubSmallAInplace<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
#[cfg(debug_assertions)]
{
self.assert_keyswitch(module, lhs, &rhs.key, scratch);
}
let (res_dft, scratch1) = scratch.take_vec_znx_dft(self.n(), self.cols(), rhs.size()); // TODO: optimise size
let mut res_big: VecZnxBig<_, B> = lhs.keyswitch_internal(module, res_dft, &rhs.key, scratch1);
(0..self.cols()).for_each(|i| {
module.vec_znx_big_automorphism_inplace(rhs.p(), &mut res_big, i);
module.vec_znx_big_sub_small_a_inplace(&mut res_big, i, &lhs.data, i);
module.vec_znx_big_normalize(self.basek(), &mut self.data, i, &res_big, i, scratch1);
})
}
pub fn automorphism_sub_ab_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxBigAutomorphismInplace<B>
+ VecZnxBigSubSmallAInplace<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
unsafe {
let self_ptr: *mut GLWECiphertext<DataSelf> = self as *mut GLWECiphertext<DataSelf>;
self.automorphism_sub_ab(module, &*self_ptr, rhs, scratch);
}
}
pub fn automorphism_sub_ba<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxBigAutomorphismInplace<B>
+ VecZnxBigSubSmallBInplace<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
#[cfg(debug_assertions)]
{
self.assert_keyswitch(module, lhs, &rhs.key, scratch);
}
let (res_dft, scratch1) = scratch.take_vec_znx_dft(self.n(), self.cols(), rhs.size()); // TODO: optimise size
let mut res_big: VecZnxBig<_, B> = lhs.keyswitch_internal(module, res_dft, &rhs.key, scratch1);
(0..self.cols()).for_each(|i| {
module.vec_znx_big_automorphism_inplace(rhs.p(), &mut res_big, i);
module.vec_znx_big_sub_small_b_inplace(&mut res_big, i, &lhs.data, i);
module.vec_znx_big_normalize(self.basek(), &mut self.data, i, &res_big, i, scratch1);
})
}
pub fn automorphism_sub_ba_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxBigAutomorphismInplace<B>
+ VecZnxBigSubSmallBInplace<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
unsafe {
let self_ptr: *mut GLWECiphertext<DataSelf> = self as *mut GLWECiphertext<DataSelf>;
self.automorphism_sub_ba(module, &*self_ptr, rhs, scratch);
}
}
}

View File

@@ -0,0 +1,3 @@
mod gglwe_atk;
mod ggsw_ct;
mod glwe_ct;

View File

@@ -0,0 +1,80 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxDft, VecZnxBigAddSmallInplace, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, ZnxView,
ZnxViewMut, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{
TakeGLWECt,
layouts::{GLWECiphertext, Infos, LWECiphertext, prepared::GLWEToLWESwitchingKeyPrepared},
};
impl LWECiphertext<Vec<u8>> {
pub fn from_glwe_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_lwe: usize,
k_glwe: usize,
k_ksk: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GLWECiphertext::bytes_of(n, basek, k_lwe, 1)
+ GLWECiphertext::keyswitch_scratch_space(module, n, basek, k_lwe, k_glwe, k_ksk, 1, rank, 1)
}
}
impl<DLwe: DataMut> LWECiphertext<DLwe> {
pub fn sample_extract<DGlwe: DataRef>(&mut self, a: &GLWECiphertext<DGlwe>) {
#[cfg(debug_assertions)]
{
assert!(self.n() <= a.n());
}
let min_size: usize = self.size().min(a.size());
let n: usize = self.n();
self.data.zero();
(0..min_size).for_each(|i| {
let data_lwe: &mut [i64] = self.data.at_mut(0, i);
data_lwe[0] = a.data.at(0, i)[0];
data_lwe[1..].copy_from_slice(&a.data.at(1, i)[..n]);
});
}
pub fn from_glwe<DGlwe, DKs, B: Backend>(
&mut self,
module: &Module<B>,
a: &GLWECiphertext<DGlwe>,
ks: &GLWEToLWESwitchingKeyPrepared<DKs, B>,
scratch: &mut Scratch<B>,
) where
DGlwe: DataRef,
DKs: DataRef,
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeGLWECt,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.basek(), a.basek());
assert_eq!(a.n(), ks.n());
}
let (mut tmp_glwe, scratch1) = scratch.take_glwe_ct(a.n(), a.basek(), self.k(), 1);
tmp_glwe.keyswitch(module, a, &ks.0, scratch1);
self.sample_extract(&tmp_glwe);
}
}

View File

@@ -0,0 +1,73 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxDft, VecZnxBigAddSmallInplace, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, ZnxView,
ZnxViewMut, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{
TakeGLWECt,
layouts::{GLWECiphertext, Infos, LWECiphertext, prepared::LWEToGLWESwitchingKeyPrepared},
};
impl GLWECiphertext<Vec<u8>> {
pub fn from_lwe_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_lwe: usize,
k_glwe: usize,
k_ksk: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GLWECiphertext::keyswitch_scratch_space(module, n, basek, k_glwe, k_lwe, k_ksk, 1, 1, rank)
+ GLWECiphertext::bytes_of(n, basek, k_lwe, 1)
}
}
impl<D: DataMut> GLWECiphertext<D> {
pub fn from_lwe<DLwe, DKsk, B: Backend>(
&mut self,
module: &Module<B>,
lwe: &LWECiphertext<DLwe>,
ksk: &LWEToGLWESwitchingKeyPrepared<DKsk, B>,
scratch: &mut Scratch<B>,
) where
DLwe: DataRef,
DKsk: DataRef,
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeGLWECt,
{
#[cfg(debug_assertions)]
{
assert!(lwe.n() <= self.n());
assert_eq!(self.basek(), self.basek());
}
let (mut glwe, scratch1) = scratch.take_glwe_ct(ksk.n(), lwe.basek(), lwe.k(), 1);
glwe.data.zero();
let n_lwe: usize = lwe.n();
(0..lwe.size()).for_each(|i| {
let data_lwe: &[i64] = lwe.data.at(0, i);
glwe.data.at_mut(0, i)[0] = data_lwe[0];
glwe.data.at_mut(1, i)[..n_lwe].copy_from_slice(&data_lwe[1..]);
});
self.keyswitch(module, &glwe, &ksk.0, scratch1);
}
}

View File

@@ -0,0 +1,2 @@
mod glwe_to_lwe;
mod lwe_to_glwe;

View File

@@ -0,0 +1,72 @@
use poulpy_backend::hal::{
api::{
DataViewMut, SvpApplyInplace, TakeVecZnxBig, TakeVecZnxDft, VecZnxBigAddInplace, VecZnxBigAddSmallInplace,
VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxNormalizeTmpBytes,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::layouts::{GLWECiphertext, GLWEPlaintext, Infos, prepared::GLWESecretPrepared};
impl GLWECiphertext<Vec<u8>> {
pub fn decrypt_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
where
Module<B>: VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes,
{
let size: usize = k.div_ceil(basek);
(module.vec_znx_normalize_tmp_bytes(n) | module.vec_znx_dft_alloc_bytes(n, 1, size))
+ module.vec_znx_dft_alloc_bytes(n, 1, size)
}
}
impl<DataSelf: DataRef> GLWECiphertext<DataSelf> {
pub fn decrypt<DataPt: DataMut, DataSk: DataRef, B: Backend>(
&self,
module: &Module<B>,
pt: &mut GLWEPlaintext<DataPt>,
sk: &GLWESecretPrepared<DataSk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + TakeVecZnxBig<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.rank(), sk.rank());
assert_eq!(self.n(), sk.n());
assert_eq!(pt.n(), sk.n());
}
let cols: usize = self.rank() + 1;
let (mut c0_big, scratch_1) = scratch.take_vec_znx_big(self.n(), 1, self.size()); // TODO optimize size when pt << ct
c0_big.data_mut().fill(0);
{
(1..cols).for_each(|i| {
// ci_dft = DFT(a[i]) * DFT(s[i])
let (mut ci_dft, _) = scratch_1.take_vec_znx_dft(self.n(), 1, self.size()); // TODO optimize size when pt << ct
module.vec_znx_dft_from_vec_znx(1, 0, &mut ci_dft, 0, &self.data, i);
module.svp_apply_inplace(&mut ci_dft, 0, &sk.data, i - 1);
let ci_big = module.vec_znx_dft_to_vec_znx_big_consume(ci_dft);
// c0_big += a[i] * s[i]
module.vec_znx_big_add_inplace(&mut c0_big, 0, &ci_big, 0);
});
}
// c0_big = (a * s) + (-a * s + m + e) = BIG(m + e)
module.vec_znx_big_add_small_inplace(&mut c0_big, 0, &self.data, 0);
// pt = norm(BIG(m + e))
module.vec_znx_big_normalize(self.basek(), &mut pt.data, 0, &c0_big, 0, scratch_1);
pt.basek = self.basek();
pt.k = pt.k().min(self.k());
}
}

View File

@@ -0,0 +1,42 @@
use poulpy_backend::hal::{
api::{ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxNormalizeInplace, ZnxView, ZnxViewMut},
layouts::{Backend, DataMut, DataRef, Module, ScratchOwned},
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl},
};
use crate::layouts::{Infos, LWECiphertext, LWEPlaintext, LWESecret, SetMetaData};
impl<DataSelf> LWECiphertext<DataSelf>
where
DataSelf: DataRef,
{
pub fn decrypt<DataPt, DataSk, B>(&self, module: &Module<B>, pt: &mut LWEPlaintext<DataPt>, sk: &LWESecret<DataSk>)
where
DataPt: DataMut,
DataSk: DataRef,
Module<B>: VecZnxNormalizeInplace<B>,
B: Backend + ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), sk.n());
}
(0..pt.size().min(self.size())).for_each(|i| {
pt.data.at_mut(0, i)[0] = self.data.at(0, i)[0]
+ self.data.at(0, i)[1..]
.iter()
.zip(sk.data.at(0, 0))
.map(|(x, y)| x * y)
.sum::<i64>();
});
module.vec_znx_normalize_inplace(
self.basek(),
&mut pt.data,
0,
ScratchOwned::alloc(size_of::<i64>()).borrow(),
);
pt.set_basek(self.basek());
pt.set_k(self.k().min(pt.size() * self.basek()));
}
}

View File

@@ -0,0 +1,2 @@
mod glwe_ct;
mod lwe_ct;

84
poulpy-core/src/dist.rs Normal file
View File

@@ -0,0 +1,84 @@
use std::io::{Read, Result, Write};
#[derive(Clone, Copy, Debug)]
pub enum Distribution {
TernaryFixed(usize), // Ternary with fixed Hamming weight
TernaryProb(f64), // Ternary with probabilistic Hamming weight
BinaryFixed(usize), // Binary with fixed Hamming weight
BinaryProb(f64), // Binary with probabilistic Hamming weight
BinaryBlock(usize), // Binary split in block of size 2^k
ZERO, // Debug mod
NONE, // Unitialized
}
const TAG_TERNARY_FIXED: u8 = 0;
const TAG_TERNARY_PROB: u8 = 1;
const TAG_BINARY_FIXED: u8 = 2;
const TAG_BINARY_PROB: u8 = 3;
const TAG_BINARY_BLOCK: u8 = 4;
const TAG_ZERO: u8 = 5;
const TAG_NONE: u8 = 6;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
impl Distribution {
pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
let word: u64 = match self {
Distribution::TernaryFixed(v) => (TAG_TERNARY_FIXED as u64) << 56 | (*v as u64),
Distribution::TernaryProb(p) => {
let bits = p.to_bits(); // f64 -> u64 bit representation
(TAG_TERNARY_PROB as u64) << 56 | (bits & 0x00FF_FFFF_FFFF_FFFF)
}
Distribution::BinaryFixed(v) => (TAG_BINARY_FIXED as u64) << 56 | (*v as u64),
Distribution::BinaryProb(p) => {
let bits = p.to_bits();
(TAG_BINARY_PROB as u64) << 56 | (bits & 0x00FF_FFFF_FFFF_FFFF)
}
Distribution::BinaryBlock(v) => (TAG_BINARY_BLOCK as u64) << 56 | (*v as u64),
Distribution::ZERO => (TAG_ZERO as u64) << 56,
Distribution::NONE => (TAG_NONE as u64) << 56,
};
writer.write_u64::<LittleEndian>(word)
}
pub fn read_from<R: Read>(reader: &mut R) -> Result<Self> {
let word = reader.read_u64::<LittleEndian>()?;
let tag = (word >> 56) as u8;
let payload = word & 0x00FF_FFFF_FFFF_FFFF;
let dist = match tag {
TAG_TERNARY_FIXED => Distribution::TernaryFixed(payload as usize),
TAG_TERNARY_PROB => Distribution::TernaryProb(f64::from_bits(payload)),
TAG_BINARY_FIXED => Distribution::BinaryFixed(payload as usize),
TAG_BINARY_PROB => Distribution::BinaryProb(f64::from_bits(payload)),
TAG_BINARY_BLOCK => Distribution::BinaryBlock(payload as usize),
TAG_ZERO => Distribution::ZERO,
TAG_NONE => Distribution::NONE,
_ => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Invalid tag",
));
}
};
Ok(dist)
}
}
impl PartialEq for Distribution {
fn eq(&self, other: &Self) -> bool {
use Distribution::*;
match (self, other) {
(TernaryFixed(a), TernaryFixed(b)) => a == b,
(TernaryProb(a), TernaryProb(b)) => a.to_bits() == b.to_bits(),
(BinaryFixed(a), BinaryFixed(b)) => a == b,
(BinaryProb(a), BinaryProb(b)) => a.to_bits() == b.to_bits(),
(BinaryBlock(a), BinaryBlock(b)) => a == b,
(ZERO, ZERO) => true,
(NONE, NONE) => true,
_ => false,
}
}
}
impl Eq for Distribution {}

View File

@@ -0,0 +1,104 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft,
VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphism, VecZnxBigNormalize, VecZnxDftAllocBytes,
VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize, VecZnxNormalizeInplace,
VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
source::Source,
};
use crate::{
TakeGLWESecret, TakeGLWESecretPrepared,
layouts::{
GLWESecret,
compressed::{GGLWEAutomorphismKeyCompressed, GGLWESwitchingKeyCompressed},
},
};
impl GGLWEAutomorphismKeyCompressed<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>: VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes + SvpPPolAllocBytes,
{
GGLWESwitchingKeyCompressed::encrypt_sk_scratch_space(module, n, basek, k, rank, rank) + GLWESecret::bytes_of(n, rank)
}
}
impl<DataSelf: DataMut> GGLWEAutomorphismKeyCompressed<DataSelf> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
p: i64,
sk: &GLWESecret<DataSk>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxAutomorphism
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ VecZnxSwithcDegree
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeGLWESecretPrepared<B>,
{
#[cfg(debug_assertions)]
{
use crate::layouts::Infos;
assert_eq!(self.n(), sk.n());
assert_eq!(self.rank_out(), self.rank_in());
assert_eq!(sk.rank(), self.rank());
assert!(
scratch.available()
>= GGLWEAutomorphismKeyCompressed::encrypt_sk_scratch_space(
module,
sk.n(),
self.basek(),
self.k(),
self.rank()
),
"scratch.available(): {} < AutomorphismKey::encrypt_sk_scratch_space(module, self.rank()={}, self.size()={}): {}",
scratch.available(),
self.rank(),
self.size(),
GGLWEAutomorphismKeyCompressed::encrypt_sk_scratch_space(module, sk.n(), self.basek(), self.k(), self.rank())
)
}
let (mut sk_out, scratch_1) = scratch.take_glwe_secret(sk.n(), sk.rank());
{
(0..self.rank()).for_each(|i| {
module.vec_znx_automorphism(
module.galois_element_inv(p),
&mut sk_out.data.as_vec_znx_mut(),
i,
&sk.data.as_vec_znx(),
i,
);
});
}
self.key
.encrypt_sk(module, sk, &sk_out, seed_xa, source_xe, sigma, scratch_1);
self.p = p;
}
}

View File

@@ -0,0 +1,137 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, TakeVecZnx, TakeVecZnxDft, VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace,
VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform,
VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
source::Source,
};
use crate::{
TakeGLWEPt,
encryption::glwe_encrypt_sk_internal,
layouts::{GGLWECiphertext, Infos, compressed::GGLWECiphertextCompressed, prepared::GLWESecretPrepared},
};
impl GGLWECiphertextCompressed<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
where
Module<B>: VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes,
{
GGLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k)
}
}
impl<D: DataMut> GGLWECiphertextCompressed<D> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretPrepared<DataSk, B>,
seed: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use poulpy_backend::hal::api::ZnxInfos;
assert_eq!(
self.rank_in(),
pt.cols(),
"self.rank_in(): {} != pt.cols(): {}",
self.rank_in(),
pt.cols()
);
assert_eq!(
self.rank_out(),
sk.rank(),
"self.rank_out(): {} != sk.rank(): {}",
self.rank_out(),
sk.rank()
);
assert_eq!(self.n(), sk.n());
assert_eq!(pt.n(), sk.n());
assert!(
scratch.available()
>= GGLWECiphertextCompressed::encrypt_sk_scratch_space(module, sk.n(), self.basek(), self.k()),
"scratch.available: {} < GGLWECiphertext::encrypt_sk_scratch_space(module, self.rank()={}, self.size()={}): {}",
scratch.available(),
self.rank(),
self.size(),
GGLWECiphertextCompressed::encrypt_sk_scratch_space(module, sk.n(), self.basek(), self.k())
);
assert!(
self.rows() * self.digits() * self.basek() <= self.k(),
"self.rows() : {} * self.digits() : {} * self.basek() : {} = {} >= self.k() = {}",
self.rows(),
self.digits(),
self.basek(),
self.rows() * self.digits() * self.basek(),
self.k()
);
}
let rows: usize = self.rows();
let digits: usize = self.digits();
let basek: usize = self.basek();
let k: usize = self.k();
let rank_in: usize = self.rank_in();
let cols: usize = self.rank_out() + 1;
let mut source_xa = Source::new(seed);
let (mut tmp_pt, scrach_1) = scratch.take_glwe_pt(sk.n(), basek, k);
(0..rank_in).for_each(|col_i| {
(0..rows).for_each(|row_i| {
// Adds the scalar_znx_pt to the i-th limb of the vec_znx_pt
tmp_pt.data.zero(); // zeroes for next iteration
module.vec_znx_add_scalar_inplace(
&mut tmp_pt.data,
0,
(digits - 1) + row_i * digits,
pt,
col_i,
);
module.vec_znx_normalize_inplace(basek, &mut tmp_pt.data, 0, scrach_1);
let (seed, mut source_xa_tmp) = source_xa.branch();
self.seed[col_i * rows + row_i] = seed;
glwe_encrypt_sk_internal(
module,
self.basek(),
self.k(),
&mut self.at_mut(row_i, col_i).data,
cols,
true,
Some((&tmp_pt, 0)),
sk,
&mut source_xa_tmp,
source_xe,
sigma,
scrach_1,
);
});
});
}
}

View File

@@ -0,0 +1,128 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft,
VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes,
VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
source::Source,
};
use crate::{
TakeGLWESecretPrepared,
layouts::{GGLWECiphertext, GLWESecret, compressed::GGLWESwitchingKeyCompressed, prepared::GLWESecretPrepared},
};
impl GGLWESwitchingKeyCompressed<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k: usize,
rank_in: usize,
rank_out: usize,
) -> usize
where
Module<B>: VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes + SvpPPolAllocBytes,
{
(GGLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k) | ScalarZnx::alloc_bytes(n, 1))
+ ScalarZnx::alloc_bytes(n, rank_in)
+ GLWESecretPrepared::bytes_of(module, n, rank_out)
}
}
impl<DataSelf: DataMut> GGLWESwitchingKeyCompressed<DataSelf> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataSkIn: DataRef, DataSkOut: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
sk_in: &GLWESecret<DataSkIn>,
sk_out: &GLWESecret<DataSkOut>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: SvpPrepare<B>
+ SvpPPolAllocBytes
+ VecZnxSwithcDegree
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeGLWESecretPrepared<B>,
{
#[cfg(debug_assertions)]
{
use crate::layouts::{GGLWESwitchingKey, Infos};
assert!(sk_in.n() <= module.n());
assert!(sk_out.n() <= module.n());
assert!(
scratch.available()
>= GGLWESwitchingKey::encrypt_sk_scratch_space(
module,
sk_out.n(),
self.basek(),
self.k(),
self.rank_in(),
self.rank_out()
),
"scratch.available()={} < GLWESwitchingKey::encrypt_sk_scratch_space={}",
scratch.available(),
GGLWESwitchingKey::encrypt_sk_scratch_space(
module,
sk_out.n(),
self.basek(),
self.k(),
self.rank_in(),
self.rank_out()
)
)
}
let n: usize = sk_in.n().max(sk_out.n());
let (mut sk_in_tmp, scratch1) = scratch.take_scalar_znx(n, sk_in.rank());
(0..sk_in.rank()).for_each(|i| {
module.vec_znx_switch_degree(
&mut sk_in_tmp.as_vec_znx_mut(),
i,
&sk_in.data.as_vec_znx(),
i,
);
});
let (mut sk_out_tmp, scratch2) = scratch1.take_glwe_secret_prepared(n, sk_out.rank());
{
let (mut tmp, _) = scratch2.take_scalar_znx(n, 1);
(0..sk_out.rank()).for_each(|i| {
module.vec_znx_switch_degree(&mut tmp.as_vec_znx_mut(), 0, &sk_out.data.as_vec_znx(), i);
module.svp_prepare(&mut sk_out_tmp.data, i, &tmp, 0);
});
}
self.key.encrypt_sk(
module,
&sk_in_tmp,
&sk_out_tmp,
seed_xa,
source_xe,
sigma,
scratch2,
);
self.sk_in_n = sk_in.n();
self.sk_out_n = sk_out.n();
}
}

View File

@@ -0,0 +1,111 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApply, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx,
TakeVecZnxBig, TakeVecZnxDft, VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxBigAllocBytes,
VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxDftToVecZnxBigTmpA,
VecZnxFillUniform, VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace,
VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
source::Source,
};
use crate::{
TakeGLWESecret, TakeGLWESecretPrepared,
layouts::{GGLWETensorKey, GLWESecret, Infos, compressed::GGLWETensorKeyCompressed, prepared::Prepare},
};
impl GGLWETensorKeyCompressed<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>:
SvpPPolAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes + VecZnxBigAllocBytes,
{
GGLWETensorKey::encrypt_sk_scratch_space(module, n, basek, k, rank)
}
}
impl<DataSelf: DataMut> GGLWETensorKeyCompressed<DataSelf> {
pub fn encrypt_sk<DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
sk: &GLWESecret<DataSk>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: SvpApply<B>
+ VecZnxDftToVecZnxBigTmpA<B>
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>,
Scratch<B>: ScratchAvailable
+ TakeScalarZnx
+ TakeVecZnxDft<B>
+ TakeGLWESecretPrepared<B>
+ ScratchAvailable
+ TakeVecZnx
+ TakeVecZnxBig<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.rank(), sk.rank());
assert_eq!(self.n(), sk.n());
}
let n: usize = sk.n();
let rank: usize = self.rank();
let (mut sk_dft_prep, scratch1) = scratch.take_glwe_secret_prepared(n, rank);
sk_dft_prep.prepare(module, sk, scratch1);
let (mut sk_dft, scratch2) = scratch1.take_vec_znx_dft(n, rank, 1);
(0..rank).for_each(|i| {
module.vec_znx_dft_from_vec_znx(1, 0, &mut sk_dft, i, &sk.data.as_vec_znx(), i);
});
let (mut sk_ij_big, scratch3) = scratch2.take_vec_znx_big(n, 1, 1);
let (mut sk_ij, scratch4) = scratch3.take_glwe_secret(n, 1);
let (mut sk_ij_dft, scratch5) = scratch4.take_vec_znx_dft(n, 1, 1);
let mut source_xa: Source = Source::new(seed_xa);
(0..rank).for_each(|i| {
(i..rank).for_each(|j| {
module.svp_apply(&mut sk_ij_dft, 0, &sk_dft_prep.data, j, &sk_dft, i);
module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut sk_ij_big, 0, &mut sk_ij_dft, 0);
module.vec_znx_big_normalize(
self.basek(),
&mut sk_ij.data.as_vec_znx_mut(),
0,
&sk_ij_big,
0,
scratch5,
);
let (seed_xa_tmp, _) = source_xa.branch();
self.at_mut(i, j)
.encrypt_sk(module, &sk_ij, sk, seed_xa_tmp, source_xe, sigma, scratch5);
});
})
}
}

View File

@@ -0,0 +1,106 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, TakeVecZnx, TakeVecZnxDft, VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace,
VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform,
VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
source::Source,
};
use crate::{
TakeGLWEPt,
encryption::glwe_encrypt_sk_internal,
layouts::{GGSWCiphertext, Infos, compressed::GGSWCiphertextCompressed, prepared::GLWESecretPrepared},
};
impl GGSWCiphertextCompressed<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>: VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes,
{
GGSWCiphertext::encrypt_sk_scratch_space(module, n, basek, k, rank)
}
}
impl<DataSelf: DataMut> GGSWCiphertextCompressed<DataSelf> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretPrepared<DataSk, B>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use poulpy_backend::hal::api::ZnxInfos;
assert_eq!(self.rank(), sk.rank());
assert_eq!(self.n(), sk.n());
assert_eq!(pt.n(), sk.n());
}
let basek: usize = self.basek();
let k: usize = self.k();
let rank: usize = self.rank();
let cols: usize = rank + 1;
let digits: usize = self.digits();
let (mut tmp_pt, scratch_1) = scratch.take_glwe_pt(self.n(), basek, k);
let mut source = Source::new(seed_xa);
self.seed = vec![[0u8; 32]; self.rows() * cols];
(0..self.rows()).for_each(|row_i| {
tmp_pt.data.zero();
// Adds the scalar_znx_pt to the i-th limb of the vec_znx_pt
module.vec_znx_add_scalar_inplace(&mut tmp_pt.data, 0, (digits - 1) + row_i * digits, pt, 0);
module.vec_znx_normalize_inplace(basek, &mut tmp_pt.data, 0, scratch_1);
(0..rank + 1).for_each(|col_j| {
// rlwe encrypt of vec_znx_pt into vec_znx_ct
let (seed, mut source_xa_tmp) = source.branch();
self.seed[row_i * cols + col_j] = seed;
glwe_encrypt_sk_internal(
module,
self.basek(),
self.k(),
&mut self.at_mut(row_i, col_j).data,
cols,
true,
Some((&tmp_pt, col_j)),
sk,
&mut source_xa_tmp,
source_xe,
sigma,
scratch_1,
);
});
});
}
}

View File

@@ -0,0 +1,107 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, TakeVecZnx, TakeVecZnxDft, VecZnxAddInplace, VecZnxAddNormal, VecZnxBigNormalize,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
source::Source,
};
use crate::{
encryption::glwe_ct::glwe_encrypt_sk_internal,
layouts::{GLWECiphertext, GLWEPlaintext, Infos, compressed::GLWECiphertextCompressed, prepared::GLWESecretPrepared},
};
impl GLWECiphertextCompressed<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
where
Module<B>: VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes,
{
GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k)
}
}
impl<D: DataMut> GLWECiphertextCompressed<D> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &GLWEPlaintext<DataPt>,
sk: &GLWESecretPrepared<DataSk, B>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
self.encrypt_sk_internal(
module,
Some((pt, 0)),
sk,
seed_xa,
source_xe,
sigma,
scratch,
);
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn encrypt_sk_internal<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: Option<(&GLWEPlaintext<DataPt>, usize)>,
sk: &GLWESecretPrepared<DataSk, B>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
let mut source_xa = Source::new(seed_xa);
let cols: usize = self.rank() + 1;
glwe_encrypt_sk_internal(
module,
self.basek(),
self.k(),
&mut self.data,
cols,
true,
pt,
sk,
&mut source_xa,
source_xe,
sigma,
scratch,
);
self.seed = seed_xa;
}
}

View File

@@ -0,0 +1,6 @@
mod gglwe_atk;
mod gglwe_ct;
mod gglwe_ksk;
mod gglwe_tsk;
mod ggsw_ct;
mod glwe_ct;

View File

@@ -0,0 +1,99 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft,
VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphism, VecZnxBigNormalize, VecZnxDftAllocBytes,
VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize, VecZnxNormalizeInplace,
VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
source::Source,
};
use crate::{
TakeGLWESecret, TakeGLWESecretPrepared,
layouts::{GGLWEAutomorphismKey, GGLWESwitchingKey, GLWESecret},
};
impl GGLWEAutomorphismKey<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>: SvpPPolAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes,
{
GGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, rank, rank) + GLWESecret::bytes_of(n, rank)
}
pub fn encrypt_pk_scratch_space<B: Backend>(module: &Module<B>, _n: usize, _basek: usize, _k: usize, _rank: usize) -> usize {
GGLWESwitchingKey::encrypt_pk_scratch_space(module, _n, _basek, _k, _rank, _rank)
}
}
impl<DataSelf: DataMut> GGLWEAutomorphismKey<DataSelf> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
p: i64,
sk: &GLWESecret<DataSk>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ VecZnxSwithcDegree
+ SvpPPolAllocBytes
+ VecZnxAutomorphism,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeGLWESecretPrepared<B>,
{
#[cfg(debug_assertions)]
{
use crate::layouts::Infos;
assert_eq!(self.n(), sk.n());
assert_eq!(self.rank_out(), self.rank_in());
assert_eq!(sk.rank(), self.rank());
assert!(
scratch.available()
>= GGLWEAutomorphismKey::encrypt_sk_scratch_space(module, sk.n(), self.basek(), self.k(), self.rank()),
"scratch.available(): {} < AutomorphismKey::encrypt_sk_scratch_space(module, self.rank()={}, self.size()={}): {}",
scratch.available(),
self.rank(),
self.size(),
GGLWEAutomorphismKey::encrypt_sk_scratch_space(module, sk.n(), self.basek(), self.k(), self.rank())
)
}
let (mut sk_out, scratch_1) = scratch.take_glwe_secret(sk.n(), sk.rank());
{
(0..self.rank()).for_each(|i| {
module.vec_znx_automorphism(
module.galois_element_inv(p),
&mut sk_out.data.as_vec_znx_mut(),
i,
&sk.data.as_vec_znx(),
i,
);
});
}
self.key
.encrypt_sk(module, sk, &sk_out, source_xa, source_xe, sigma, scratch_1);
self.p = p;
}
}

View File

@@ -0,0 +1,134 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, TakeVecZnx, TakeVecZnxDft, VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace,
VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform,
VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
source::Source,
};
use crate::{
TakeGLWEPt,
layouts::{GGLWECiphertext, GLWECiphertext, GLWEPlaintext, Infos, prepared::GLWESecretPrepared},
};
impl GGLWECiphertext<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
where
Module<B>: VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes,
{
GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k)
+ (GLWEPlaintext::byte_of(n, basek, k) | module.vec_znx_normalize_tmp_bytes(n))
}
pub fn encrypt_pk_scratch_space<B: Backend>(_module: &Module<B>, _n: usize, _basek: usize, _k: usize, _rank: usize) -> usize {
unimplemented!()
}
}
impl<DataSelf: DataMut> GGLWECiphertext<DataSelf> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretPrepared<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use poulpy_backend::hal::api::ZnxInfos;
assert_eq!(
self.rank_in(),
pt.cols(),
"self.rank_in(): {} != pt.cols(): {}",
self.rank_in(),
pt.cols()
);
assert_eq!(
self.rank_out(),
sk.rank(),
"self.rank_out(): {} != sk.rank(): {}",
self.rank_out(),
sk.rank()
);
assert_eq!(self.n(), sk.n());
assert_eq!(pt.n(), sk.n());
assert!(
scratch.available() >= GGLWECiphertext::encrypt_sk_scratch_space(module, sk.n(), self.basek(), self.k()),
"scratch.available: {} < GGLWECiphertext::encrypt_sk_scratch_space(module, self.rank()={}, self.size()={}): {}",
scratch.available(),
self.rank(),
self.size(),
GGLWECiphertext::encrypt_sk_scratch_space(module, sk.n(), self.basek(), self.k())
);
assert!(
self.rows() * self.digits() * self.basek() <= self.k(),
"self.rows() : {} * self.digits() : {} * self.basek() : {} = {} >= self.k() = {}",
self.rows(),
self.digits(),
self.basek(),
self.rows() * self.digits() * self.basek(),
self.k()
);
}
let rows: usize = self.rows();
let digits: usize = self.digits();
let basek: usize = self.basek();
let k: usize = self.k();
let rank_in: usize = self.rank_in();
let (mut tmp_pt, scrach_1) = scratch.take_glwe_pt(sk.n(), basek, k);
// For each input column (i.e. rank) produces a GGLWE ciphertext of rank_out+1 columns
//
// Example for ksk rank 2 to rank 3:
//
// (-(a0*s0 + a1*s1 + a2*s2) + s0', a0, a1, a2)
// (-(b0*s0 + b1*s1 + b2*s2) + s0', b0, b1, b2)
//
// Example ksk rank 2 to rank 1
//
// (-(a*s) + s0, a)
// (-(b*s) + s1, b)
(0..rank_in).for_each(|col_i| {
(0..rows).for_each(|row_i| {
// Adds the scalar_znx_pt to the i-th limb of the vec_znx_pt
tmp_pt.data.zero(); // zeroes for next iteration
module.vec_znx_add_scalar_inplace(
&mut tmp_pt.data,
0,
(digits - 1) + row_i * digits,
pt,
col_i,
);
module.vec_znx_normalize_inplace(basek, &mut tmp_pt.data, 0, scrach_1);
// rlwe encrypt of vec_znx_pt into vec_znx_ct
self.at_mut(row_i, col_i)
.encrypt_sk(module, &tmp_pt, sk, source_xa, source_xe, sigma, scrach_1);
});
});
}
}

View File

@@ -0,0 +1,139 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft,
VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes,
VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
source::Source,
};
use crate::{
TakeGLWESecretPrepared,
layouts::{GGLWECiphertext, GGLWESwitchingKey, GLWESecret, prepared::GLWESecretPrepared},
};
impl GGLWESwitchingKey<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k: usize,
rank_in: usize,
rank_out: usize,
) -> usize
where
Module<B>: SvpPPolAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes,
{
(GGLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k) | ScalarZnx::alloc_bytes(n, 1))
+ ScalarZnx::alloc_bytes(n, rank_in)
+ GLWESecretPrepared::bytes_of(module, n, rank_out)
}
pub fn encrypt_pk_scratch_space<B: Backend>(
module: &Module<B>,
_n: usize,
_basek: usize,
_k: usize,
_rank_in: usize,
_rank_out: usize,
) -> usize {
GGLWECiphertext::encrypt_pk_scratch_space(module, _n, _basek, _k, _rank_out)
}
}
impl<DataSelf: DataMut> GGLWESwitchingKey<DataSelf> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataSkIn: DataRef, DataSkOut: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
sk_in: &GLWESecret<DataSkIn>,
sk_out: &GLWESecret<DataSkOut>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ VecZnxSwithcDegree
+ SvpPPolAllocBytes,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeGLWESecretPrepared<B>,
{
#[cfg(debug_assertions)]
{
use crate::layouts::Infos;
assert!(sk_in.n() <= module.n());
assert!(sk_out.n() <= module.n());
assert!(
scratch.available()
>= GGLWESwitchingKey::encrypt_sk_scratch_space(
module,
sk_out.n(),
self.basek(),
self.k(),
self.rank_in(),
self.rank_out()
),
"scratch.available()={} < GLWESwitchingKey::encrypt_sk_scratch_space={}",
scratch.available(),
GGLWESwitchingKey::encrypt_sk_scratch_space(
module,
sk_out.n(),
self.basek(),
self.k(),
self.rank_in(),
self.rank_out()
)
)
}
let n: usize = sk_in.n().max(sk_out.n());
let (mut sk_in_tmp, scratch1) = scratch.take_scalar_znx(n, sk_in.rank());
(0..sk_in.rank()).for_each(|i| {
module.vec_znx_switch_degree(
&mut sk_in_tmp.as_vec_znx_mut(),
i,
&sk_in.data.as_vec_znx(),
i,
);
});
let (mut sk_out_tmp, scratch2) = scratch1.take_glwe_secret_prepared(n, sk_out.rank());
{
let (mut tmp, _) = scratch2.take_scalar_znx(n, 1);
(0..sk_out.rank()).for_each(|i| {
module.vec_znx_switch_degree(&mut tmp.as_vec_znx_mut(), 0, &sk_out.data.as_vec_znx(), i);
module.svp_prepare(&mut sk_out_tmp.data, i, &tmp, 0);
});
}
self.key.encrypt_sk(
module,
&sk_in_tmp,
&sk_out_tmp,
source_xa,
source_xe,
sigma,
scratch2,
);
self.sk_in_n = sk_in.n();
self.sk_out_n = sk_out.n();
}
}

View File

@@ -0,0 +1,109 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApply, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx, TakeVecZnxBig,
TakeVecZnxDft, VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxBigAllocBytes, VecZnxBigNormalize,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxDftToVecZnxBigTmpA, VecZnxFillUniform,
VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
source::Source,
};
use crate::{
TakeGLWESecret, TakeGLWESecretPrepared,
layouts::{
GGLWESwitchingKey, GGLWETensorKey, GLWESecret, Infos,
prepared::{GLWESecretPrepared, Prepare},
},
};
impl GGLWETensorKey<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>:
SvpPPolAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes + VecZnxBigAllocBytes,
{
GLWESecretPrepared::bytes_of(module, n, rank)
+ module.vec_znx_dft_alloc_bytes(n, rank, 1)
+ module.vec_znx_big_alloc_bytes(n, 1, 1)
+ module.vec_znx_dft_alloc_bytes(n, 1, 1)
+ GLWESecret::bytes_of(n, 1)
+ GGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, rank, rank)
}
}
impl<DataSelf: DataMut> GGLWETensorKey<DataSelf> {
pub fn encrypt_sk<DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
sk: &GLWESecret<DataSk>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: SvpApply<B>
+ VecZnxDftToVecZnxBigTmpA<B>
+ VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ VecZnxSwithcDegree
+ SvpPPolAllocBytes,
Scratch<B>:
TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeGLWESecretPrepared<B> + TakeVecZnxBig<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.rank(), sk.rank());
assert_eq!(self.n(), sk.n());
}
let n: usize = sk.n();
let rank: usize = self.rank();
let (mut sk_dft_prep, scratch1) = scratch.take_glwe_secret_prepared(n, rank);
sk_dft_prep.prepare(module, sk, scratch1);
let (mut sk_dft, scratch2) = scratch1.take_vec_znx_dft(n, rank, 1);
(0..rank).for_each(|i| {
module.vec_znx_dft_from_vec_znx(1, 0, &mut sk_dft, i, &sk.data.as_vec_znx(), i);
});
let (mut sk_ij_big, scratch3) = scratch2.take_vec_znx_big(n, 1, 1);
let (mut sk_ij, scratch4) = scratch3.take_glwe_secret(n, 1);
let (mut sk_ij_dft, scratch5) = scratch4.take_vec_znx_dft(n, 1, 1);
(0..rank).for_each(|i| {
(i..rank).for_each(|j| {
module.svp_apply(&mut sk_ij_dft, 0, &sk_dft_prep.data, j, &sk_dft, i);
module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut sk_ij_big, 0, &mut sk_ij_dft, 0);
module.vec_znx_big_normalize(
self.basek(),
&mut sk_ij.data.as_vec_znx_mut(),
0,
&sk_ij_big,
0,
scratch5,
);
self.at_mut(i, j)
.encrypt_sk(module, &sk_ij, sk, source_xa, source_xe, sigma, scratch5);
});
})
}
}

View File

@@ -0,0 +1,95 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, TakeVecZnx, TakeVecZnxDft, VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace,
VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform,
VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch, VecZnx},
source::Source,
};
use crate::{
TakeGLWEPt,
layouts::{GGSWCiphertext, GLWECiphertext, Infos, prepared::GLWESecretPrepared},
};
impl GGSWCiphertext<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>: VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes,
{
let size = k.div_ceil(basek);
GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k)
+ VecZnx::alloc_bytes(n, rank + 1, size)
+ VecZnx::alloc_bytes(n, 1, size)
+ module.vec_znx_dft_alloc_bytes(n, rank + 1, size)
}
}
impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretPrepared<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use poulpy_backend::hal::api::ZnxInfos;
assert_eq!(self.rank(), sk.rank());
assert_eq!(self.n(), sk.n());
assert_eq!(pt.n(), sk.n());
}
let basek: usize = self.basek();
let k: usize = self.k();
let rank: usize = self.rank();
let digits: usize = self.digits();
let (mut tmp_pt, scratch1) = scratch.take_glwe_pt(self.n(), basek, k);
(0..self.rows()).for_each(|row_i| {
tmp_pt.data.zero();
// Adds the scalar_znx_pt to the i-th limb of the vec_znx_pt
module.vec_znx_add_scalar_inplace(&mut tmp_pt.data, 0, (digits - 1) + row_i * digits, pt, 0);
module.vec_znx_normalize_inplace(basek, &mut tmp_pt.data, 0, scratch1);
(0..rank + 1).for_each(|col_j| {
// rlwe encrypt of vec_znx_pt into vec_znx_ct
self.at_mut(row_i, col_j).encrypt_sk_internal(
module,
Some((&tmp_pt, col_j)),
sk,
source_xa,
source_xe,
sigma,
scratch1,
);
});
});
}
}

View File

@@ -0,0 +1,426 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApply, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeSvpPPol, TakeVecZnx,
TakeVecZnxDft, VecZnxAddInplace, VecZnxAddNormal, VecZnxBigAddNormal, VecZnxBigAddSmallInplace, VecZnxBigAllocBytes,
VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform,
VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, ZnxInfos, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch, VecZnx, VecZnxBig},
source::Source,
};
use crate::{
SIX_SIGMA,
dist::Distribution,
layouts::{
GLWECiphertext, GLWEPlaintext, Infos,
prepared::{GLWEPublicKeyPrepared, GLWESecretPrepared},
},
};
impl GLWECiphertext<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
where
Module<B>: VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes,
{
let size: usize = k.div_ceil(basek);
module.vec_znx_normalize_tmp_bytes(n) + 2 * VecZnx::alloc_bytes(n, 1, size) + module.vec_znx_dft_alloc_bytes(n, 1, size)
}
pub fn encrypt_pk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
where
Module<B>: VecZnxDftAllocBytes + SvpPPolAllocBytes + VecZnxBigAllocBytes + VecZnxNormalizeTmpBytes,
{
let size: usize = k.div_ceil(basek);
((module.vec_znx_dft_alloc_bytes(n, 1, size) + module.vec_znx_big_alloc_bytes(n, 1, size)) | ScalarZnx::alloc_bytes(n, 1))
+ module.svp_ppol_alloc_bytes(n, 1)
+ module.vec_znx_normalize_tmp_bytes(n)
}
}
impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &GLWEPlaintext<DataPt>,
sk: &GLWESecretPrepared<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.rank(), sk.rank());
assert_eq!(sk.n(), self.n());
assert_eq!(pt.n(), self.n());
assert!(
scratch.available() >= GLWECiphertext::encrypt_sk_scratch_space(module, self.n(), self.basek(), self.k()),
"scratch.available(): {} < GLWECiphertext::encrypt_sk_scratch_space: {}",
scratch.available(),
GLWECiphertext::encrypt_sk_scratch_space(module, self.n(), self.basek(), self.k())
)
}
self.encrypt_sk_internal(
module,
Some((pt, 0)),
sk,
source_xa,
source_xe,
sigma,
scratch,
);
}
pub fn encrypt_zero_sk<DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
sk: &GLWESecretPrepared<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.rank(), sk.rank());
assert_eq!(sk.n(), self.n());
assert!(
scratch.available() >= GLWECiphertext::encrypt_sk_scratch_space(module, self.n(), self.basek(), self.k()),
"scratch.available(): {} < GLWECiphertext::encrypt_sk_scratch_space: {}",
scratch.available(),
GLWECiphertext::encrypt_sk_scratch_space(module, self.n(), self.basek(), self.k())
)
}
self.encrypt_sk_internal(
module,
None::<(&GLWEPlaintext<Vec<u8>>, usize)>,
sk,
source_xa,
source_xe,
sigma,
scratch,
);
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn encrypt_sk_internal<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: Option<(&GLWEPlaintext<DataPt>, usize)>,
sk: &GLWESecretPrepared<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
let cols: usize = self.rank() + 1;
glwe_encrypt_sk_internal(
module,
self.basek(),
self.k(),
&mut self.data,
cols,
false,
pt,
sk,
source_xa,
source_xe,
sigma,
scratch,
);
}
#[allow(clippy::too_many_arguments)]
pub fn encrypt_pk<DataPt: DataRef, DataPk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &GLWEPlaintext<DataPt>,
pk: &GLWEPublicKeyPrepared<DataPk, B>,
source_xu: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: SvpPrepare<B>
+ SvpApply<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddNormal<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeSvpPPol<B> + TakeScalarZnx + TakeVecZnxDft<B>,
{
self.encrypt_pk_internal::<DataPt, DataPk, B>(
module,
Some((pt, 0)),
pk,
source_xu,
source_xe,
sigma,
scratch,
);
}
pub fn encrypt_zero_pk<DataPk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pk: &GLWEPublicKeyPrepared<DataPk, B>,
source_xu: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: SvpPrepare<B>
+ SvpApply<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddNormal<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeSvpPPol<B> + TakeScalarZnx + TakeVecZnxDft<B>,
{
self.encrypt_pk_internal::<Vec<u8>, DataPk, B>(
module,
None::<(&GLWEPlaintext<Vec<u8>>, usize)>,
pk,
source_xu,
source_xe,
sigma,
scratch,
);
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn encrypt_pk_internal<DataPt: DataRef, DataPk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: Option<(&GLWEPlaintext<DataPt>, usize)>,
pk: &GLWEPublicKeyPrepared<DataPk, B>,
source_xu: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: SvpPrepare<B>
+ SvpApply<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddNormal<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeSvpPPol<B> + TakeScalarZnx + TakeVecZnxDft<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.basek(), pk.basek());
assert_eq!(self.n(), pk.n());
assert_eq!(self.rank(), pk.rank());
if let Some((pt, _)) = pt {
assert_eq!(pt.basek(), pk.basek());
assert_eq!(pt.n(), pk.n());
}
}
let basek: usize = pk.basek();
let size_pk: usize = pk.size();
let cols: usize = self.rank() + 1;
// Generates u according to the underlying secret distribution.
let (mut u_dft, scratch_1) = scratch.take_svp_ppol(self.n(), 1);
{
let (mut u, _) = scratch_1.take_scalar_znx(self.n(), 1);
match pk.dist {
Distribution::NONE => panic!(
"invalid public key: SecretDistribution::NONE, ensure it has been correctly intialized through \
Self::generate"
),
Distribution::TernaryFixed(hw) => u.fill_ternary_hw(0, hw, source_xu),
Distribution::TernaryProb(prob) => u.fill_ternary_prob(0, prob, source_xu),
Distribution::BinaryFixed(hw) => u.fill_binary_hw(0, hw, source_xu),
Distribution::BinaryProb(prob) => u.fill_binary_prob(0, prob, source_xu),
Distribution::BinaryBlock(block_size) => u.fill_binary_block(0, block_size, source_xu),
Distribution::ZERO => {}
}
module.svp_prepare(&mut u_dft, 0, &u, 0);
}
// ct[i] = pk[i] * u + ei (+ m if col = i)
(0..cols).for_each(|i| {
let (mut ci_dft, scratch_2) = scratch_1.take_vec_znx_dft(self.n(), 1, size_pk);
// ci_dft = DFT(u) * DFT(pk[i])
module.svp_apply(&mut ci_dft, 0, &u_dft, 0, &pk.data, i);
// ci_big = u * p[i]
let mut ci_big = module.vec_znx_dft_to_vec_znx_big_consume(ci_dft);
// ci_big = u * pk[i] + e
module.vec_znx_big_add_normal(
basek,
&mut ci_big,
0,
pk.k(),
source_xe,
sigma,
sigma * SIX_SIGMA,
);
// ci_big = u * pk[i] + e + m (if col = i)
if let Some((pt, col)) = pt
&& col == i
{
module.vec_znx_big_add_small_inplace(&mut ci_big, 0, &pt.data, 0);
}
// ct[i] = norm(ci_big)
module.vec_znx_big_normalize(basek, &mut self.data, i, &ci_big, 0, scratch_2);
});
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn glwe_encrypt_sk_internal<DataCt: DataMut, DataPt: DataRef, DataSk: DataRef, B: Backend>(
module: &Module<B>,
basek: usize,
k: usize,
ct: &mut VecZnx<DataCt>,
cols: usize,
compressed: bool,
pt: Option<(&GLWEPlaintext<DataPt>, usize)>,
sk: &GLWESecretPrepared<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
if compressed {
use poulpy_backend::hal::api::ZnxInfos;
assert_eq!(
ct.cols(),
1,
"invalid ciphertext: compressed tag=true but #cols={} != 1",
ct.cols()
)
}
}
let size: usize = ct.size();
let (mut c0, scratch_1) = scratch.take_vec_znx(ct.n(), 1, size);
c0.zero();
{
let (mut ci, scratch_2) = scratch_1.take_vec_znx(ct.n(), 1, size);
// ct[i] = uniform
// ct[0] -= c[i] * s[i],
(1..cols).for_each(|i| {
let col_ct: usize = if compressed { 0 } else { i };
// ct[i] = uniform (+ pt)
module.vec_znx_fill_uniform(basek, ct, col_ct, k, source_xa);
let (mut ci_dft, scratch_3) = scratch_2.take_vec_znx_dft(ct.n(), 1, size);
// ci = ct[i] - pt
// i.e. we act as we sample ct[i] already as uniform + pt
// and if there is a pt, then we subtract it before applying DFT
if let Some((pt, col)) = pt {
if i == col {
module.vec_znx_sub(&mut ci, 0, ct, col_ct, &pt.data, 0);
module.vec_znx_normalize_inplace(basek, &mut ci, 0, scratch_3);
module.vec_znx_dft_from_vec_znx(1, 0, &mut ci_dft, 0, &ci, 0);
} else {
module.vec_znx_dft_from_vec_znx(1, 0, &mut ci_dft, 0, ct, col_ct);
}
} else {
module.vec_znx_dft_from_vec_znx(1, 0, &mut ci_dft, 0, ct, col_ct);
}
module.svp_apply_inplace(&mut ci_dft, 0, &sk.data, i - 1);
let ci_big: VecZnxBig<&mut [u8], B> = module.vec_znx_dft_to_vec_znx_big_consume(ci_dft);
// use c[0] as buffer, which is overwritten later by the normalization step
module.vec_znx_big_normalize(basek, &mut ci, 0, &ci_big, 0, scratch_3);
// c0_tmp = -c[i] * s[i] (use c[0] as buffer)
module.vec_znx_sub_ab_inplace(&mut c0, 0, &ci, 0);
});
}
// c[0] += e
module.vec_znx_add_normal(basek, &mut c0, 0, k, source_xe, sigma, sigma * SIX_SIGMA);
// c[0] += m if col = 0
if let Some((pt, col)) = pt
&& col == 0
{
module.vec_znx_add_inplace(&mut c0, 0, &pt.data, 0);
}
// c[0] = norm(c[0])
module.vec_znx_normalize(basek, ct, 0, &c0, 0, scratch_1);
}

View File

@@ -0,0 +1,67 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, VecZnxAddInplace, VecZnxAddNormal, VecZnxBigNormalize,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace,
},
layouts::{Backend, DataMut, DataRef, Module, ScratchOwned},
oep::{ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeVecZnxDftImpl, TakeVecZnxImpl},
source::Source,
};
use crate::layouts::{GLWECiphertext, GLWEPublicKey, Infos, prepared::GLWESecretPrepared};
impl<D: DataMut> GLWEPublicKey<D> {
pub fn generate_from_sk<S: DataRef, B>(
&mut self,
module: &Module<B>,
sk: &GLWESecretPrepared<S, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
) where
Module<B>:,
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
B: Backend
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ TakeVecZnxDftImpl<B>
+ ScratchAvailableImpl<B>
+ TakeVecZnxImpl<B>,
{
#[cfg(debug_assertions)]
{
use crate::Distribution;
assert_eq!(self.n(), sk.n());
if sk.dist == Distribution::NONE {
panic!("invalid sk: SecretDistribution::NONE")
}
}
// Its ok to allocate scratch space here since pk is usually generated only once.
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GLWECiphertext::encrypt_sk_scratch_space(
module,
self.n(),
self.basek(),
self.k(),
));
let mut tmp: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(self.n(), self.basek(), self.k(), self.rank());
tmp.encrypt_zero_sk(module, sk, source_xa, source_xe, sigma, scratch.borrow());
self.dist = sk.dist;
}
}

View File

@@ -0,0 +1,82 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft,
VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphismInplace, VecZnxBigNormalize,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree, ZnxView, ZnxViewMut,
ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
source::Source,
};
use crate::{
TakeGLWESecret, TakeGLWESecretPrepared,
layouts::{GGLWESwitchingKey, GLWESecret, GLWEToLWESwitchingKey, LWESecret, prepared::GLWESecretPrepared},
};
impl GLWEToLWESwitchingKey<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank_in: usize) -> usize
where
Module<B>: SvpPPolAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes,
{
GLWESecretPrepared::bytes_of(module, n, rank_in)
+ (GGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, rank_in, 1) | GLWESecret::bytes_of(n, rank_in))
}
}
impl<D: DataMut> GLWEToLWESwitchingKey<D> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DLwe, DGlwe, B: Backend>(
&mut self,
module: &Module<B>,
sk_lwe: &LWESecret<DLwe>,
sk_glwe: &GLWESecret<DGlwe>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
DLwe: DataRef,
DGlwe: DataRef,
Module<B>: VecZnxAutomorphismInplace
+ VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ VecZnxSwithcDegree
+ SvpPPolAllocBytes,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeGLWESecretPrepared<B>,
{
#[cfg(debug_assertions)]
{
assert!(sk_lwe.n() <= module.n());
}
let (mut sk_lwe_as_glwe, scratch1) = scratch.take_glwe_secret(sk_glwe.n(), 1);
sk_lwe_as_glwe.data.zero();
sk_lwe_as_glwe.data.at_mut(0, 0)[..sk_lwe.n()].copy_from_slice(sk_lwe.data.at(0, 0));
module.vec_znx_automorphism_inplace(-1, &mut sk_lwe_as_glwe.data.as_vec_znx_mut(), 0);
self.0.encrypt_sk(
module,
sk_glwe,
&sk_lwe_as_glwe,
source_xa,
source_xe,
sigma,
scratch1,
);
}
}

View File

@@ -0,0 +1,82 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxAddNormal, VecZnxFillUniform, VecZnxNormalizeInplace, ZnxView, ZnxViewMut,
},
layouts::{Backend, DataMut, DataRef, Module, ScratchOwned, VecZnx},
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl},
source::Source,
};
use crate::{
SIX_SIGMA,
layouts::{Infos, LWECiphertext, LWEPlaintext, LWESecret},
};
impl<DataSelf: DataMut> LWECiphertext<DataSelf> {
pub fn encrypt_sk<DataPt, DataSk, B>(
&mut self,
module: &Module<B>,
pt: &LWEPlaintext<DataPt>,
sk: &LWESecret<DataSk>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
) where
DataPt: DataRef,
DataSk: DataRef,
Module<B>: VecZnxFillUniform + VecZnxAddNormal + VecZnxNormalizeInplace<B>,
B: Backend + ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), sk.n())
}
let basek: usize = self.basek();
let k: usize = self.k();
module.vec_znx_fill_uniform(basek, &mut self.data, 0, k, source_xa);
let mut tmp_znx: VecZnx<Vec<u8>> = VecZnx::alloc(1, 1, self.size());
let min_size = self.size().min(pt.size());
(0..min_size).for_each(|i| {
tmp_znx.at_mut(0, i)[0] = pt.data.at(0, i)[0]
- self.data.at(0, i)[1..]
.iter()
.zip(sk.data.at(0, 0))
.map(|(x, y)| x * y)
.sum::<i64>();
});
(min_size..self.size()).for_each(|i| {
tmp_znx.at_mut(0, i)[0] -= self.data.at(0, i)[1..]
.iter()
.zip(sk.data.at(0, 0))
.map(|(x, y)| x * y)
.sum::<i64>();
});
module.vec_znx_add_normal(
basek,
&mut self.data,
0,
k,
source_xe,
sigma,
sigma * SIX_SIGMA,
);
module.vec_znx_normalize_inplace(
basek,
&mut tmp_znx,
0,
ScratchOwned::alloc(size_of::<i64>()).borrow(),
);
(0..self.size()).for_each(|i| {
self.data.at_mut(0, i)[0] = tmp_znx.at(0, i)[0];
});
}
}

View File

@@ -0,0 +1,90 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft,
VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphismInplace, VecZnxBigNormalize,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree, ZnxView, ZnxViewMut,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
source::Source,
};
use crate::{
TakeGLWESecret, TakeGLWESecretPrepared,
layouts::{GGLWESwitchingKey, GLWESecret, Infos, LWESecret, LWESwitchingKey, prepared::GLWESecretPrepared},
};
impl LWESwitchingKey<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
where
Module<B>: SvpPPolAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes,
{
GLWESecret::bytes_of(n, 1)
+ GLWESecretPrepared::bytes_of(module, n, 1)
+ GGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, 1, 1)
}
}
impl<D: DataMut> LWESwitchingKey<D> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DIn, DOut, B: Backend>(
&mut self,
module: &Module<B>,
sk_lwe_in: &LWESecret<DIn>,
sk_lwe_out: &LWESecret<DOut>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
DIn: DataRef,
DOut: DataRef,
Module<B>: VecZnxAutomorphismInplace
+ VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ VecZnxSwithcDegree
+ SvpPPolAllocBytes,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeGLWESecretPrepared<B>,
{
#[cfg(debug_assertions)]
{
assert!(sk_lwe_in.n() <= self.n());
assert!(sk_lwe_out.n() <= self.n());
assert!(self.n() <= module.n());
}
let (mut sk_in_glwe, scratch1) = scratch.take_glwe_secret(self.n(), 1);
let (mut sk_out_glwe, scratch2) = scratch1.take_glwe_secret(self.n(), 1);
sk_out_glwe.data.at_mut(0, 0)[..sk_lwe_out.n()].copy_from_slice(sk_lwe_out.data.at(0, 0));
sk_out_glwe.data.at_mut(0, 0)[sk_lwe_out.n()..].fill(0);
module.vec_znx_automorphism_inplace(-1, &mut sk_out_glwe.data.as_vec_znx_mut(), 0);
sk_in_glwe.data.at_mut(0, 0)[..sk_lwe_in.n()].copy_from_slice(sk_lwe_in.data.at(0, 0));
sk_in_glwe.data.at_mut(0, 0)[sk_lwe_in.n()..].fill(0);
module.vec_znx_automorphism_inplace(-1, &mut sk_in_glwe.data.as_vec_znx_mut(), 0);
self.0.encrypt_sk(
module,
&sk_in_glwe,
&sk_out_glwe,
source_xa,
source_xe,
sigma,
scratch2,
);
}
}

View File

@@ -0,0 +1,80 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft,
VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphismInplace, VecZnxBigNormalize,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree, ZnxView, ZnxViewMut,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
source::Source,
};
use crate::{
TakeGLWESecret, TakeGLWESecretPrepared,
layouts::{GGLWESwitchingKey, GLWESecret, LWESecret, LWEToGLWESwitchingKey},
};
impl LWEToGLWESwitchingKey<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank_out: usize) -> usize
where
Module<B>: SvpPPolAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes,
{
GGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, 1, rank_out) + GLWESecret::bytes_of(n, 1)
}
}
impl<D: DataMut> LWEToGLWESwitchingKey<D> {
#[allow(clippy::too_many_arguments)]
pub fn encrypt_sk<DLwe, DGlwe, B: Backend>(
&mut self,
module: &Module<B>,
sk_lwe: &LWESecret<DLwe>,
sk_glwe: &GLWESecret<DGlwe>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
DLwe: DataRef,
DGlwe: DataRef,
Module<B>: VecZnxAutomorphismInplace
+ VecZnxAddScalarInplace
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ VecZnxSwithcDegree
+ SvpPPolAllocBytes,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeGLWESecretPrepared<B>,
{
#[cfg(debug_assertions)]
{
assert!(sk_lwe.n() <= module.n());
}
let (mut sk_lwe_as_glwe, scratch1) = scratch.take_glwe_secret(sk_glwe.n(), 1);
sk_lwe_as_glwe.data.at_mut(0, 0)[..sk_lwe.n()].copy_from_slice(sk_lwe.data.at(0, 0));
sk_lwe_as_glwe.data.at_mut(0, 0)[sk_lwe.n()..].fill(0);
module.vec_znx_automorphism_inplace(-1, &mut sk_lwe_as_glwe.data.as_vec_znx_mut(), 0);
self.0.encrypt_sk(
module,
&sk_lwe_as_glwe,
sk_glwe,
source_xa,
source_xe,
sigma,
scratch1,
);
}
}

View File

@@ -0,0 +1,14 @@
mod compressed;
mod gglwe_atk;
mod gglwe_ct;
mod gglwe_ksk;
mod gglwe_tsk;
mod ggsw_ct;
mod glwe_ct;
mod glwe_pk;
mod glwe_to_lwe_ksk;
mod lwe_ct;
mod lwe_ksk;
mod lwe_to_glwe_ksk;
pub(crate) use glwe_ct::glwe_encrypt_sk_internal;

View File

@@ -0,0 +1,84 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxDft, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxNormalizeTmpBytes, VmpApply, VmpApplyAdd, VmpApplyTmpBytes,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::layouts::{GGLWEAutomorphismKey, GGLWESwitchingKey, prepared::GGSWCiphertextPrepared};
impl GGLWEAutomorphismKey<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn external_product_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
ggsw_k: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxNormalizeTmpBytes,
{
GGLWESwitchingKey::external_product_scratch_space(module, n, basek, k_out, k_in, ggsw_k, digits, rank)
}
pub fn external_product_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
ggsw_k: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxNormalizeTmpBytes,
{
GGLWESwitchingKey::external_product_inplace_scratch_space(module, n, basek, k_out, ggsw_k, digits, rank)
}
}
impl<DataSelf: DataMut> GGLWEAutomorphismKey<DataSelf> {
pub fn external_product<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGLWEAutomorphismKey<DataLhs>,
rhs: &GGSWCiphertextPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
self.key.external_product(module, &lhs.key, rhs, scratch);
}
pub fn external_product_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGSWCiphertextPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
self.key.external_product_inplace(module, rhs, scratch);
}
}

View File

@@ -0,0 +1,136 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxDft, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxNormalizeTmpBytes, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::layouts::{GGLWESwitchingKey, GLWECiphertext, Infos, prepared::GGSWCiphertextPrepared};
impl GGLWESwitchingKey<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn external_product_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ggsw: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxNormalizeTmpBytes,
{
GLWECiphertext::external_product_scratch_space(module, n, basek, k_out, k_in, k_ggsw, digits, rank)
}
pub fn external_product_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ggsw: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxNormalizeTmpBytes,
{
GLWECiphertext::external_product_inplace_scratch_space(module, n, basek, k_out, k_ggsw, digits, rank)
}
}
impl<DataSelf: DataMut> GGLWESwitchingKey<DataSelf> {
pub fn external_product<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGLWESwitchingKey<DataLhs>,
rhs: &GGSWCiphertextPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
#[cfg(debug_assertions)]
{
assert_eq!(
self.rank_in(),
lhs.rank_in(),
"ksk_out input rank: {} != ksk_in input rank: {}",
self.rank_in(),
lhs.rank_in()
);
assert_eq!(
lhs.rank_out(),
rhs.rank(),
"ksk_in output rank: {} != ggsw rank: {}",
self.rank_out(),
rhs.rank()
);
assert_eq!(
self.rank_out(),
rhs.rank(),
"ksk_out output rank: {} != ggsw rank: {}",
self.rank_out(),
rhs.rank()
);
}
(0..self.rank_in()).for_each(|col_i| {
(0..self.rows()).for_each(|row_j| {
self.at_mut(row_j, col_i)
.external_product(module, &lhs.at(row_j, col_i), rhs, scratch);
});
});
(self.rows().min(lhs.rows())..self.rows()).for_each(|row_i| {
(0..self.rank_in()).for_each(|col_j| {
self.at_mut(row_i, col_j).data.zero();
});
});
}
pub fn external_product_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGSWCiphertextPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
#[cfg(debug_assertions)]
{
assert_eq!(
self.rank_out(),
rhs.rank(),
"ksk_out output rank: {} != ggsw rank: {}",
self.rank_out(),
rhs.rank()
);
}
(0..self.rank_in()).for_each(|col_i| {
(0..self.rows()).for_each(|row_j| {
self.at_mut(row_j, col_i)
.external_product_inplace(module, rhs, scratch);
});
});
}
}

View File

@@ -0,0 +1,148 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxDft, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxNormalizeTmpBytes, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::layouts::{GGSWCiphertext, GLWECiphertext, Infos, prepared::GGSWCiphertextPrepared};
impl GGSWCiphertext<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn external_product_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ggsw: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxNormalizeTmpBytes,
{
GLWECiphertext::external_product_scratch_space(module, n, basek, k_out, k_in, k_ggsw, digits, rank)
}
pub fn external_product_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ggsw: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxNormalizeTmpBytes,
{
GLWECiphertext::external_product_inplace_scratch_space(module, n, basek, k_out, k_ggsw, digits, rank)
}
}
impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
pub fn external_product<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGSWCiphertext<DataLhs>,
rhs: &GGSWCiphertextPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
#[cfg(debug_assertions)]
{
use crate::layouts::Infos;
assert_eq!(lhs.n(), self.n());
assert_eq!(rhs.n(), self.n());
assert_eq!(
self.rank(),
lhs.rank(),
"ggsw_out rank: {} != ggsw_in rank: {}",
self.rank(),
lhs.rank()
);
assert_eq!(
self.rank(),
rhs.rank(),
"ggsw_in rank: {} != ggsw_apply rank: {}",
self.rank(),
rhs.rank()
);
assert!(
scratch.available()
>= GGSWCiphertext::external_product_scratch_space(
module,
self.n(),
self.basek(),
self.k(),
lhs.k(),
rhs.k(),
rhs.digits(),
rhs.rank()
)
)
}
let min_rows: usize = self.rows().min(lhs.rows());
(0..self.rank() + 1).for_each(|col_i| {
(0..min_rows).for_each(|row_j| {
self.at_mut(row_j, col_i)
.external_product(module, &lhs.at(row_j, col_i), rhs, scratch);
});
(min_rows..self.rows()).for_each(|row_i| {
self.at_mut(row_i, col_i).data.zero();
});
});
}
pub fn external_product_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGSWCiphertextPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
#[cfg(debug_assertions)]
{
assert_eq!(rhs.n(), self.n());
assert_eq!(
self.rank(),
rhs.rank(),
"ggsw_out rank: {} != ggsw_apply: {}",
self.rank(),
rhs.rank()
);
}
(0..self.rank() + 1).for_each(|col_i| {
(0..self.rows()).for_each(|row_j| {
self.at_mut(row_j, col_i)
.external_product_inplace(module, rhs, scratch);
});
});
}
}

View File

@@ -0,0 +1,167 @@
use poulpy_backend::hal::{
api::{
DataViewMut, ScratchAvailable, TakeVecZnxDft, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxNormalizeTmpBytes, VmpApply, VmpApplyAdd, VmpApplyTmpBytes,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch, VecZnxBig},
};
use crate::layouts::{GLWECiphertext, Infos, prepared::GGSWCiphertextPrepared};
impl GLWECiphertext<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn external_product_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ggsw: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxNormalizeTmpBytes,
{
let in_size: usize = k_in.div_ceil(basek).div_ceil(digits);
let out_size: usize = k_out.div_ceil(basek);
let ggsw_size: usize = k_ggsw.div_ceil(basek);
let res_dft: usize = module.vec_znx_dft_alloc_bytes(n, rank + 1, ggsw_size);
let a_dft: usize = module.vec_znx_dft_alloc_bytes(n, rank + 1, in_size);
let vmp: usize = module.vmp_apply_tmp_bytes(
n,
out_size,
in_size,
in_size, // rows
rank + 1, // cols in
rank + 1, // cols out
ggsw_size,
);
let normalize: usize = module.vec_znx_normalize_tmp_bytes(n);
res_dft + a_dft + (vmp | normalize)
}
pub fn external_product_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ggsw: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxNormalizeTmpBytes,
{
Self::external_product_scratch_space(module, n, basek, k_out, k_out, k_ggsw, digits, rank)
}
}
impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
pub fn external_product<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &GGSWCiphertextPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
let basek: usize = self.basek();
#[cfg(debug_assertions)]
{
use poulpy_backend::hal::api::ScratchAvailable;
assert_eq!(rhs.rank(), lhs.rank());
assert_eq!(rhs.rank(), self.rank());
assert_eq!(self.basek(), basek);
assert_eq!(lhs.basek(), basek);
assert_eq!(rhs.n(), self.n());
assert_eq!(lhs.n(), self.n());
assert!(
scratch.available()
>= GLWECiphertext::external_product_scratch_space(
module,
self.n(),
self.basek(),
self.k(),
lhs.k(),
rhs.k(),
rhs.digits(),
rhs.rank(),
)
);
}
let cols: usize = rhs.rank() + 1;
let digits: usize = rhs.digits();
let (mut res_dft, scratch1) = scratch.take_vec_znx_dft(self.n(), cols, rhs.size()); // Todo optimise
let (mut a_dft, scratch2) = scratch1.take_vec_znx_dft(self.n(), cols, lhs.size().div_ceil(digits));
a_dft.data_mut().fill(0);
{
(0..digits).for_each(|di| {
// (lhs.size() + di) / digits = (a - (digit - di - 1)).div_ceil(digits)
a_dft.set_size((lhs.size() + di) / digits);
// Small optimization for digits > 2
// VMP produce some error e, and since we aggregate vmp * 2^{di * B}, then
// we also aggregate ei * 2^{di * B}, with the largest error being ei * 2^{(digits-1) * B}.
// As such we can ignore the last digits-2 limbs safely of the sum of vmp products.
// It is possible to further ignore the last digits-1 limbs, but this introduce
// ~0.5 to 1 bit of additional noise, and thus not chosen here to ensure that the same
// noise is kept with respect to the ideal functionality.
res_dft.set_size(rhs.size() - ((digits - di) as isize - 2).max(0) as usize);
(0..cols).for_each(|col_i| {
module.vec_znx_dft_from_vec_znx(digits, digits - 1 - di, &mut a_dft, col_i, &lhs.data, col_i);
});
if di == 0 {
module.vmp_apply(&mut res_dft, &a_dft, &rhs.data, scratch2);
} else {
module.vmp_apply_add(&mut res_dft, &a_dft, &rhs.data, di, scratch2);
}
});
}
let res_big: VecZnxBig<&mut [u8], B> = module.vec_znx_dft_to_vec_znx_big_consume(res_dft);
(0..cols).for_each(|i| {
module.vec_znx_big_normalize(basek, &mut self.data, i, &res_big, i, scratch1);
});
}
pub fn external_product_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGSWCiphertextPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
unsafe {
let self_ptr: *mut GLWECiphertext<DataSelf> = self as *mut GLWECiphertext<DataSelf>;
self.external_product(module, &*self_ptr, rhs, scratch);
}
}
}

View File

@@ -0,0 +1,4 @@
mod gglwe_atk;
mod gglwe_ksk;
mod ggsw_ct;
mod glwe_ct;

View File

@@ -0,0 +1,405 @@
use std::collections::HashMap;
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnx, TakeVecZnxDft, VecZnxAddInplace, VecZnxAutomorphismInplace, VecZnxBigAddSmallInplace,
VecZnxBigAutomorphismInplace, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxBigSubSmallBInplace, VecZnxCopy,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxNegateInplace, VecZnxNormalizeInplace,
VecZnxRotate, VecZnxRotateInplace, VecZnxRshInplace, VecZnxSub, VecZnxSubABInplace, VmpApply, VmpApplyAdd,
VmpApplyTmpBytes,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{
GLWEOperations, TakeGLWECt,
layouts::{GLWECiphertext, Infos, prepared::GGLWEAutomorphismKeyPrepared},
};
/// [GLWEPacker] enables only the fly GLWE packing
/// with constant memory of Log(N) ciphertexts.
/// Main difference with usual GLWE packing is that
/// the output is bit-reversed.
pub struct GLWEPacker {
accumulators: Vec<Accumulator>,
log_batch: usize,
counter: usize,
}
/// [Accumulator] stores intermediate packing result.
/// There are Log(N) such accumulators in a [GLWEPacker].
struct Accumulator {
data: GLWECiphertext<Vec<u8>>,
value: bool, // Implicit flag for zero ciphertext
control: bool, // Can be combined with incoming value
}
impl Accumulator {
/// Allocates a new [Accumulator].
///
/// #Arguments
///
/// * `module`: static backend FFT tables.
/// * `basek`: base 2 logarithm of the GLWE ciphertext in memory digit representation.
/// * `k`: base 2 precision of the GLWE ciphertext precision over the Torus.
/// * `rank`: rank of the GLWE ciphertext.
pub fn alloc(n: usize, basek: usize, k: usize, rank: usize) -> Self {
Self {
data: GLWECiphertext::alloc(n, basek, k, rank),
value: false,
control: false,
}
}
}
impl GLWEPacker {
/// Instantiates a new [GLWEPacker].
///
/// # Arguments
///
/// * `module`: static backend FFT tables.
/// * `log_batch`: packs coefficients which are multiples of X^{N/2^log_batch}.
/// i.e. with `log_batch=0` only the constant coefficient is packed
/// and N GLWE ciphertext can be packed. With `log_batch=2` all coefficients
/// which are multiples of X^{N/4} are packed. Meaning that N/4 ciphertexts
/// can be packed.
/// * `basek`: base 2 logarithm of the GLWE ciphertext in memory digit representation.
/// * `k`: base 2 precision of the GLWE ciphertext precision over the Torus.
/// * `rank`: rank of the GLWE ciphertext.
pub fn new(n: usize, log_batch: usize, basek: usize, k: usize, rank: usize) -> Self {
let mut accumulators: Vec<Accumulator> = Vec::<Accumulator>::new();
let log_n: usize = (usize::BITS - (n - 1).leading_zeros()) as _;
(0..log_n - log_batch).for_each(|_| accumulators.push(Accumulator::alloc(n, basek, k, rank)));
Self {
accumulators,
log_batch,
counter: 0,
}
}
/// Implicit reset of the internal state (to be called before a new packing procedure).
fn reset(&mut self) {
for i in 0..self.accumulators.len() {
self.accumulators[i].value = false;
self.accumulators[i].control = false;
}
self.counter = 0;
}
/// Number of scratch space bytes required to call [Self::add].
pub fn scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
ct_k: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
pack_core_scratch_space(module, n, basek, ct_k, k_ksk, digits, rank)
}
pub fn galois_elements<B: Backend>(module: &Module<B>) -> Vec<i64> {
GLWECiphertext::trace_galois_elements(module)
}
/// Adds a GLWE ciphertext to the [GLWEPacker].
/// #Arguments
///
/// * `module`: static backend FFT tables.
/// * `res`: space to append fully packed ciphertext. Only when the number
/// of packed ciphertexts reaches N/2^log_batch is a result written.
/// * `a`: ciphertext to pack. Can optionally give None to pack a 0 ciphertext.
/// * `auto_keys`: a [HashMap] containing the [AutomorphismKeyExec]s.
/// * `scratch`: scratch space of size at least [Self::scratch_space].
pub fn add<DataA: DataRef, DataAK: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
a: Option<&GLWECiphertext<DataA>>,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyPrepared<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxCopy
+ VecZnxRotateInplace
+ VecZnxSub
+ VecZnxNegateInplace
+ VecZnxRshInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxSubABInplace
+ VecZnxRotate
+ VecZnxAutomorphismInplace
+ VecZnxBigSubSmallBInplace<B>
+ VecZnxBigAutomorphismInplace<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
assert!(
self.counter < self.accumulators[0].data.n(),
"Packing limit of {} reached",
self.accumulators[0].data.n() >> self.log_batch
);
pack_core(
module,
a,
&mut self.accumulators,
self.log_batch,
auto_keys,
scratch,
);
self.counter += 1 << self.log_batch;
}
/// Flush result to`res`.
pub fn flush<Data: DataMut, B: Backend>(&mut self, module: &Module<B>, res: &mut GLWECiphertext<Data>)
where
Module<B>: VecZnxCopy,
{
assert!(self.counter == self.accumulators[0].data.n());
// Copy result GLWE into res GLWE
res.copy(
module,
&self.accumulators[module.log_n() - self.log_batch - 1].data,
);
self.reset();
}
}
fn pack_core_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
ct_k: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
combine_scratch_space(module, n, basek, ct_k, k_ksk, digits, rank)
}
fn pack_core<D: DataRef, DataAK: DataRef, B: Backend>(
module: &Module<B>,
a: Option<&GLWECiphertext<D>>,
accumulators: &mut [Accumulator],
i: usize,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyPrepared<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxCopy
+ VecZnxRotateInplace
+ VecZnxSub
+ VecZnxNegateInplace
+ VecZnxRshInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxSubABInplace
+ VecZnxRotate
+ VecZnxAutomorphismInplace
+ VecZnxBigSubSmallBInplace<B>
+ VecZnxBigAutomorphismInplace<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
let log_n: usize = module.log_n();
if i == log_n {
return;
}
// Isolate the first accumulator
let (acc_prev, acc_next) = accumulators.split_at_mut(1);
// Control = true accumlator is free to overide
if !acc_prev[0].control {
let acc_mut_ref: &mut Accumulator = &mut acc_prev[0]; // from split_at_mut
// No previous value -> copies and sets flags accordingly
if let Some(a_ref) = a {
acc_mut_ref.data.copy(module, a_ref);
acc_mut_ref.value = true
} else {
acc_mut_ref.value = false
}
acc_mut_ref.control = true; // Able to be combined on next call
} else {
// Compresses acc_prev <- combine(acc_prev, a).
combine(module, &mut acc_prev[0], a, i, auto_keys, scratch);
acc_prev[0].control = false;
// Propagates to next accumulator
if acc_prev[0].value {
pack_core(
module,
Some(&acc_prev[0].data),
acc_next,
i + 1,
auto_keys,
scratch,
);
} else {
pack_core(
module,
None::<&GLWECiphertext<Vec<u8>>>,
acc_next,
i + 1,
auto_keys,
scratch,
);
}
}
}
fn combine_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
ct_k: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GLWECiphertext::bytes_of(n, basek, ct_k, rank)
+ (GLWECiphertext::rsh_scratch_space(n)
| GLWECiphertext::automorphism_scratch_space(module, n, basek, ct_k, ct_k, k_ksk, digits, rank))
}
/// [combine] merges two ciphertexts together.
fn combine<D: DataRef, DataAK: DataRef, B: Backend>(
module: &Module<B>,
acc: &mut Accumulator,
b: Option<&GLWECiphertext<D>>,
i: usize,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyPrepared<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxCopy
+ VecZnxRotateInplace
+ VecZnxSub
+ VecZnxNegateInplace
+ VecZnxRshInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxSubABInplace
+ VecZnxRotate
+ VecZnxAutomorphismInplace
+ VecZnxBigSubSmallBInplace<B>
+ VecZnxBigAutomorphismInplace<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
let n: usize = acc.data.n();
let log_n: usize = (u64::BITS - (n - 1).leading_zeros()) as _;
let a: &mut GLWECiphertext<Vec<u8>> = &mut acc.data;
let basek: usize = a.basek();
let k: usize = a.k();
let rank: usize = a.rank();
let gal_el: i64 = if i == 0 {
-1
} else {
module.galois_element(1 << (i - 1))
};
let t: i64 = 1 << (log_n - i - 1);
// Goal is to evaluate: a = a + b*X^t + phi(a - b*X^t))
// We also use the identity: AUTO(a * X^t, g) = -X^t * AUTO(a, g)
// where t = 2^(log_n - i - 1) and g = 5^{2^(i - 1)}
// Different cases for wether a and/or b are zero.
//
// Implicite RSH without modulus switch, introduces extra I(X) * Q/2 on decryption.
// Necessary so that the scaling of the plaintext remains constant.
// It however is ok to do so here because coefficients are eventually
// either mapped to garbage or twice their value which vanishes I(X)
// since 2*(I(X) * Q/2) = I(X) * Q = 0 mod Q.
if acc.value {
if let Some(b) = b {
let (mut tmp_b, scratch_1) = scratch.take_glwe_ct(n, basek, k, rank);
// a = a * X^-t
a.rotate_inplace(module, -t);
// tmp_b = a * X^-t - b
tmp_b.sub(module, a, b);
tmp_b.rsh(module, 1);
// a = a * X^-t + b
a.add_inplace(module, b);
a.rsh(module, 1);
tmp_b.normalize_inplace(module, scratch_1);
// tmp_b = phi(a * X^-t - b)
if let Some(key) = auto_keys.get(&gal_el) {
tmp_b.automorphism_inplace(module, key, scratch_1);
} else {
panic!("auto_key[{}] not found", gal_el);
}
// a = a * X^-t + b - phi(a * X^-t - b)
a.sub_inplace_ab(module, &tmp_b);
a.normalize_inplace(module, scratch_1);
// a = a + b * X^t - phi(a * X^-t - b) * X^t
// = a + b * X^t - phi(a * X^-t - b) * - phi(X^t)
// = a + b * X^t + phi(a - b * X^t)
a.rotate_inplace(module, t);
} else {
a.rsh(module, 1);
// a = a + phi(a)
if let Some(key) = auto_keys.get(&gal_el) {
a.automorphism_add_inplace(module, key, scratch);
} else {
panic!("auto_key[{}] not found", gal_el);
}
}
} else if let Some(b) = b {
let (mut tmp_b, scratch_1) = scratch.take_glwe_ct(n, basek, k, rank);
tmp_b.rotate(module, 1 << (log_n - i - 1), b);
tmp_b.rsh(module, 1);
// a = (b* X^t - phi(b* X^t))
if let Some(key) = auto_keys.get(&gal_el) {
a.automorphism_sub_ba(module, &tmp_b, key, scratch_1);
} else {
panic!("auto_key[{}] not found", gal_el);
}
acc.value = true;
}
}

View File

@@ -0,0 +1,128 @@
use std::collections::HashMap;
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxDft, VecZnxBigAddSmallInplace, VecZnxBigAutomorphismInplace, VecZnxBigNormalize,
VecZnxBigNormalizeTmpBytes, VecZnxCopy, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume,
VecZnxRshInplace, VmpApply, VmpApplyAdd, VmpApplyTmpBytes,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{
layouts::{GLWECiphertext, prepared::GGLWEAutomorphismKeyPrepared},
operations::GLWEOperations,
};
impl GLWECiphertext<Vec<u8>> {
pub fn trace_galois_elements<B: Backend>(module: &Module<B>) -> Vec<i64> {
let mut gal_els: Vec<i64> = Vec::new();
(0..module.log_n()).for_each(|i| {
if i == 0 {
gal_els.push(-1);
} else {
gal_els.push(module.galois_element(1 << (i - 1)));
}
});
gal_els
}
#[allow(clippy::too_many_arguments)]
pub fn trace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
out_k: usize,
in_k: usize,
ksk_k: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
Self::automorphism_inplace_scratch_space(module, n, basek, out_k.min(in_k), ksk_k, digits, rank)
}
pub fn trace_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
out_k: usize,
ksk_k: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
Self::automorphism_inplace_scratch_space(module, n, basek, out_k, ksk_k, digits, rank)
}
}
impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
pub fn trace<DataLhs: DataRef, DataAK: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
start: usize,
end: usize,
lhs: &GLWECiphertext<DataLhs>,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyPrepared<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxBigAutomorphismInplace<B>
+ VecZnxRshInplace
+ VecZnxCopy,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
self.copy(module, lhs);
self.trace_inplace(module, start, end, auto_keys, scratch);
}
pub fn trace_inplace<DataAK: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
start: usize,
end: usize,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyPrepared<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxBigAutomorphismInplace<B>
+ VecZnxRshInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
(start..end).for_each(|i| {
self.rsh(module, 1);
let p: i64 = if i == 0 {
-1
} else {
module.galois_element(1 << (i - 1))
};
if let Some(key) = auto_keys.get(&p) {
self.automorphism_add_inplace(module, key, scratch);
} else {
panic!("auto_keys[{}] is empty", p)
}
});
}
}

View File

@@ -0,0 +1,221 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxDft, VecZnxBigAddSmallInplace, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::layouts::{
GGLWEAutomorphismKey, GGLWESwitchingKey, GLWECiphertext, Infos,
prepared::{GGLWEAutomorphismKeyPrepared, GGLWESwitchingKeyPrepared},
};
impl GGLWEAutomorphismKey<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn keyswitch_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GGLWESwitchingKey::keyswitch_scratch_space(module, n, basek, k_out, k_in, k_ksk, digits, rank, rank)
}
pub fn keyswitch_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GGLWESwitchingKey::keyswitch_inplace_scratch_space(module, n, basek, k_out, k_ksk, digits, rank)
}
}
impl<DataSelf: DataMut> GGLWEAutomorphismKey<DataSelf> {
pub fn keyswitch<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGLWEAutomorphismKey<DataLhs>,
rhs: &GGLWESwitchingKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
self.key.keyswitch(module, &lhs.key, rhs, scratch);
}
pub fn keyswitch_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGLWEAutomorphismKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
self.key.keyswitch_inplace(module, &rhs.key, scratch);
}
}
impl GGLWESwitchingKey<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn keyswitch_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ksk: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GLWECiphertext::keyswitch_scratch_space(
module, n, basek, k_out, k_in, k_ksk, digits, rank_in, rank_out,
)
}
pub fn keyswitch_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GLWECiphertext::keyswitch_inplace_scratch_space(module, n, basek, k_out, k_ksk, digits, rank)
}
}
impl<DataSelf: DataMut> GGLWESwitchingKey<DataSelf> {
pub fn keyswitch<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGLWESwitchingKey<DataLhs>,
rhs: &GGLWESwitchingKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(
self.rank_in(),
lhs.rank_in(),
"ksk_out input rank: {} != ksk_in input rank: {}",
self.rank_in(),
lhs.rank_in()
);
assert_eq!(
lhs.rank_out(),
rhs.rank_in(),
"ksk_in output rank: {} != ksk_apply input rank: {}",
self.rank_out(),
rhs.rank_in()
);
assert_eq!(
self.rank_out(),
rhs.rank_out(),
"ksk_out output rank: {} != ksk_apply output rank: {}",
self.rank_out(),
rhs.rank_out()
);
}
(0..self.rank_in()).for_each(|col_i| {
(0..self.rows()).for_each(|row_j| {
self.at_mut(row_j, col_i)
.keyswitch(module, &lhs.at(row_j, col_i), rhs, scratch);
});
});
(self.rows().min(lhs.rows())..self.rows()).for_each(|row_i| {
(0..self.rank_in()).for_each(|col_j| {
self.at_mut(row_i, col_j).data.zero();
});
});
}
pub fn keyswitch_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGLWESwitchingKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(
self.rank_out(),
rhs.rank_out(),
"ksk_out output rank: {} != ksk_apply output rank: {}",
self.rank_out(),
rhs.rank_out()
);
}
(0..self.rank_in()).for_each(|col_i| {
(0..self.rows()).for_each(|row_j| {
self.at_mut(row_j, col_i)
.keyswitch_inplace(module, rhs, scratch)
});
});
}
}

View File

@@ -0,0 +1,357 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnxBig, TakeVecZnxDft, VecZnxBigAddSmallInplace, VecZnxBigAllocBytes, VecZnxBigNormalize,
VecZnxBigNormalizeTmpBytes, VecZnxCopy, VecZnxDftAddInplace, VecZnxDftAllocBytes, VecZnxDftCopy, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxDftToVecZnxBigTmpA, VecZnxNormalizeTmpBytes, VmpApply, VmpApplyAdd, VmpApplyTmpBytes,
ZnxInfos,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch, VecZnx, VmpPMat},
};
use crate::{
layouts::{
GGLWECiphertext, GGSWCiphertext, GLWECiphertext, Infos,
prepared::{GGLWESwitchingKeyPrepared, GGLWETensorKeyPrepared},
},
operations::GLWEOperations,
};
impl GGSWCiphertext<Vec<u8>> {
pub(crate) fn expand_row_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
self_k: usize,
k_tsk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigAllocBytes + VecZnxNormalizeTmpBytes,
{
let tsk_size: usize = k_tsk.div_ceil(basek);
let self_size_out: usize = self_k.div_ceil(basek);
let self_size_in: usize = self_size_out.div_ceil(digits);
let tmp_dft_i: usize = module.vec_znx_dft_alloc_bytes(n, rank + 1, tsk_size);
let tmp_a: usize = module.vec_znx_dft_alloc_bytes(n, 1, self_size_in);
let vmp: usize = module.vmp_apply_tmp_bytes(
n,
self_size_out,
self_size_in,
self_size_in,
rank,
rank,
tsk_size,
);
let tmp_idft: usize = module.vec_znx_big_alloc_bytes(n, 1, tsk_size);
let norm: usize = module.vec_znx_normalize_tmp_bytes(n);
tmp_dft_i + ((tmp_a + vmp) | (tmp_idft + norm))
}
#[allow(clippy::too_many_arguments)]
pub fn keyswitch_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ksk: usize,
digits_ksk: usize,
k_tsk: usize,
digits_tsk: usize,
rank: usize,
) -> usize
where
Module<B>:
VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigAllocBytes + VecZnxNormalizeTmpBytes + VecZnxBigNormalizeTmpBytes,
{
let out_size: usize = k_out.div_ceil(basek);
let res_znx: usize = VecZnx::alloc_bytes(n, rank + 1, out_size);
let ci_dft: usize = module.vec_znx_dft_alloc_bytes(n, rank + 1, out_size);
let ks: usize = GLWECiphertext::keyswitch_scratch_space(module, n, basek, k_out, k_in, k_ksk, digits_ksk, rank, rank);
let expand_rows: usize = GGSWCiphertext::expand_row_scratch_space(module, n, basek, k_out, k_tsk, digits_tsk, rank);
let res_dft: usize = module.vec_znx_dft_alloc_bytes(n, rank + 1, out_size);
res_znx + ci_dft + (ks | expand_rows | res_dft)
}
#[allow(clippy::too_many_arguments)]
pub fn keyswitch_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ksk: usize,
digits_ksk: usize,
k_tsk: usize,
digits_tsk: usize,
rank: usize,
) -> usize
where
Module<B>:
VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigAllocBytes + VecZnxNormalizeTmpBytes + VecZnxBigNormalizeTmpBytes,
{
GGSWCiphertext::keyswitch_scratch_space(
module, n, basek, k_out, k_out, k_ksk, digits_ksk, k_tsk, digits_tsk, rank,
)
}
}
impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
pub fn from_gglwe<DataA, DataTsk, B: Backend>(
&mut self,
module: &Module<B>,
a: &GGLWECiphertext<DataA>,
tsk: &GGLWETensorKeyPrepared<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
DataA: DataRef,
DataTsk: DataRef,
Module<B>: VecZnxCopy
+ VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigAllocBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftCopy<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftAddInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxDftToVecZnxBigTmpA<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeVecZnxBig<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.rank(), a.rank());
assert_eq!(self.rows(), a.rows());
assert_eq!(self.n(), module.n());
assert_eq!(a.n(), module.n());
assert_eq!(tsk.n(), module.n());
}
(0..self.rows()).for_each(|row_i| {
self.at_mut(row_i, 0).copy(module, &a.at(row_i, 0));
});
self.expand_row(module, tsk, scratch);
}
pub fn keyswitch<DataLhs: DataRef, DataKsk: DataRef, DataTsk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGSWCiphertext<DataLhs>,
ksk: &GGLWESwitchingKeyPrepared<DataKsk, B>,
tsk: &GGLWETensorKeyPrepared<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftCopy<B>
+ VecZnxDftAddInplace<B>
+ VecZnxDftToVecZnxBigTmpA<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeVecZnxBig<B>,
{
self.keyswitch_internal(module, lhs, ksk, scratch);
self.expand_row(module, tsk, scratch);
}
pub fn keyswitch_inplace<DataKsk: DataRef, DataTsk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
ksk: &GGLWESwitchingKeyPrepared<DataKsk, B>,
tsk: &GGLWETensorKeyPrepared<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftCopy<B>
+ VecZnxDftAddInplace<B>
+ VecZnxDftToVecZnxBigTmpA<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeVecZnxBig<B>,
{
unsafe {
let self_ptr: *mut GGSWCiphertext<DataSelf> = self as *mut GGSWCiphertext<DataSelf>;
self.keyswitch(module, &*self_ptr, ksk, tsk, scratch);
}
}
pub fn expand_row<DataTsk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
tsk: &GGLWETensorKeyPrepared<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigAllocBytes
+ VecZnxNormalizeTmpBytes
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftCopy<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftAddInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxDftToVecZnxBigTmpA<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeVecZnxBig<B>,
{
assert!(
scratch.available()
>= GGSWCiphertext::expand_row_scratch_space(
module,
self.n(),
self.basek(),
self.k(),
tsk.k(),
tsk.digits(),
tsk.rank()
)
);
let n: usize = self.n();
let rank: usize = self.rank();
let cols: usize = rank + 1;
// Keyswitch the j-th row of the col 0
(0..self.rows()).for_each(|row_i| {
// Pre-compute DFT of (a0, a1, a2)
let (mut ci_dft, scratch1) = scratch.take_vec_znx_dft(n, cols, self.size());
(0..cols).for_each(|i| {
module.vec_znx_dft_from_vec_znx(1, 0, &mut ci_dft, i, &self.at(row_i, 0).data, i);
});
(1..cols).for_each(|col_j| {
// Example for rank 3:
//
// Note: M is a vector (m, Bm, B^2m, B^3m, ...), so each column is
// actually composed of that many rows and we focus on a specific row here
// implicitely given ci_dft.
//
// # Input
//
// col 0: (-(a0s0 + a1s1 + a2s2) + M[i], a0 , a1 , a2 )
// col 1: (0, 0, 0, 0)
// col 2: (0, 0, 0, 0)
// col 3: (0, 0, 0, 0)
//
// # Output
//
// col 0: (-(a0s0 + a1s1 + a2s2) + M[i], a0 , a1 , a2 )
// col 1: (-(b0s0 + b1s1 + b2s2) , b0 + M[i], b1 , b2 )
// col 2: (-(c0s0 + c1s1 + c2s2) , c0 , c1 + M[i], c2 )
// col 3: (-(d0s0 + d1s1 + d2s2) , d0 , d1 , d2 + M[i])
let digits: usize = tsk.digits();
let (mut tmp_dft_i, scratch2) = scratch1.take_vec_znx_dft(n, cols, tsk.size());
let (mut tmp_a, scratch3) = scratch2.take_vec_znx_dft(n, 1, ci_dft.size().div_ceil(digits));
{
// Performs a key-switch for each combination of s[i]*s[j], i.e. for a0, a1, a2
//
// # Example for col=1
//
// a0 * (-(f0s0 + f1s1 + f1s2) + s0^2, f0, f1, f2) = (-(a0f0s0 + a0f1s1 + a0f1s2) + a0s0^2, a0f0, a0f1, a0f2)
// +
// a1 * (-(g0s0 + g1s1 + g1s2) + s0s1, g0, g1, g2) = (-(a1g0s0 + a1g1s1 + a1g1s2) + a1s0s1, a1g0, a1g1, a1g2)
// +
// a2 * (-(h0s0 + h1s1 + h1s2) + s0s2, h0, h1, h2) = (-(a2h0s0 + a2h1s1 + a2h1s2) + a2s0s2, a2h0, a2h1, a2h2)
// =
// (-(x0s0 + x1s1 + x2s2) + s0(a0s0 + a1s1 + a2s2), x0, x1, x2)
(1..cols).for_each(|col_i| {
let pmat: &VmpPMat<DataTsk, B> = &tsk.at(col_i - 1, col_j - 1).key.data; // Selects Enc(s[i]s[j])
// Extracts a[i] and multipies with Enc(s[i]s[j])
(0..digits).for_each(|di| {
tmp_a.set_size((ci_dft.size() + di) / digits);
// Small optimization for digits > 2
// VMP produce some error e, and since we aggregate vmp * 2^{di * B}, then
// we also aggregate ei * 2^{di * B}, with the largest error being ei * 2^{(digits-1) * B}.
// As such we can ignore the last digits-2 limbs safely of the sum of vmp products.
// It is possible to further ignore the last digits-1 limbs, but this introduce
// ~0.5 to 1 bit of additional noise, and thus not chosen here to ensure that the same
// noise is kept with respect to the ideal functionality.
tmp_dft_i.set_size(tsk.size() - ((digits - di) as isize - 2).max(0) as usize);
module.vec_znx_dft_copy(digits, digits - 1 - di, &mut tmp_a, 0, &ci_dft, col_i);
if di == 0 && col_i == 1 {
module.vmp_apply(&mut tmp_dft_i, &tmp_a, pmat, scratch3);
} else {
module.vmp_apply_add(&mut tmp_dft_i, &tmp_a, pmat, di, scratch3);
}
});
});
}
// Adds -(sum a[i] * s[i]) + m) on the i-th column of tmp_idft_i
//
// (-(x0s0 + x1s1 + x2s2) + a0s0s0 + a1s0s1 + a2s0s2, x0, x1, x2)
// +
// (0, -(a0s0 + a1s1 + a2s2) + M[i], 0, 0)
// =
// (-(x0s0 + x1s1 + x2s2) + s0(a0s0 + a1s1 + a2s2), x0 -(a0s0 + a1s1 + a2s2) + M[i], x1, x2)
// =
// (-(x0s0 + x1s1 + x2s2), x0 + M[i], x1, x2)
module.vec_znx_dft_add_inplace(&mut tmp_dft_i, col_j, &ci_dft, 0);
let (mut tmp_idft, scratch3) = scratch2.take_vec_znx_big(n, 1, tsk.size());
(0..cols).for_each(|i| {
module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut tmp_idft, 0, &mut tmp_dft_i, i);
module.vec_znx_big_normalize(
self.basek(),
&mut self.at_mut(row_i, col_j).data,
i,
&tmp_idft,
0,
scratch3,
);
});
})
})
}
fn keyswitch_internal<DataLhs: DataRef, DataKsk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GGSWCiphertext<DataLhs>,
ksk: &GGLWESwitchingKeyPrepared<DataKsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B>,
{
// Keyswitch the j-th row of the col 0
(0..lhs.rows()).for_each(|row_i| {
// Key-switch column 0, i.e.
// col 0: (-(a0s0 + a1s1 + a2s2) + M[i], a0, a1, a2) -> (-(a0s0' + a1s1' + a2s2') + M[i], a0, a1, a2)
self.at_mut(row_i, 0)
.keyswitch(module, &lhs.at(row_i, 0), ksk, scratch);
})
}
}

View File

@@ -0,0 +1,306 @@
use poulpy_backend::hal::{
api::{
DataViewMut, ScratchAvailable, TakeVecZnxDft, VecZnxBigAddSmallInplace, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, ZnxInfos,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch, VecZnx, VecZnxBig, VecZnxDft, VmpPMat},
};
use crate::layouts::{GLWECiphertext, Infos, prepared::GGLWESwitchingKeyPrepared};
impl GLWECiphertext<Vec<u8>> {
#[allow(clippy::too_many_arguments)]
pub fn keyswitch_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_in: usize,
k_ksk: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
let in_size: usize = k_in.div_ceil(basek).div_ceil(digits);
let out_size: usize = k_out.div_ceil(basek);
let ksk_size: usize = k_ksk.div_ceil(basek);
let res_dft: usize = module.vec_znx_dft_alloc_bytes(n, rank_out + 1, ksk_size); // TODO OPTIMIZE
let ai_dft: usize = module.vec_znx_dft_alloc_bytes(n, rank_in, in_size);
let vmp: usize = module.vmp_apply_tmp_bytes(
n,
out_size,
in_size,
in_size,
rank_in,
rank_out + 1,
ksk_size,
) + module.vec_znx_dft_alloc_bytes(n, rank_in, in_size);
let normalize: usize = module.vec_znx_big_normalize_tmp_bytes(n);
res_dft + ((ai_dft + vmp) | normalize)
}
pub fn keyswitch_inplace_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_out: usize,
k_ksk: usize,
digits: usize,
rank: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
{
Self::keyswitch_scratch_space(module, n, basek, k_out, k_out, k_ksk, digits, rank, rank)
}
}
impl<DataSelf: DataRef> GLWECiphertext<DataSelf> {
#[allow(dead_code)]
pub(crate) fn assert_keyswitch<B: Backend, DataLhs, DataRhs>(
&self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &GGLWESwitchingKeyPrepared<DataRhs, B>,
scratch: &Scratch<B>,
) where
DataLhs: DataRef,
DataRhs: DataRef,
Module<B>: VecZnxDftAllocBytes + VmpApplyTmpBytes + VecZnxBigNormalizeTmpBytes,
Scratch<B>: ScratchAvailable,
{
let basek: usize = self.basek();
assert_eq!(
lhs.rank(),
rhs.rank_in(),
"lhs.rank(): {} != rhs.rank_in(): {}",
lhs.rank(),
rhs.rank_in()
);
assert_eq!(
self.rank(),
rhs.rank_out(),
"self.rank(): {} != rhs.rank_out(): {}",
self.rank(),
rhs.rank_out()
);
assert_eq!(self.basek(), basek);
assert_eq!(lhs.basek(), basek);
assert_eq!(rhs.n(), self.n());
assert_eq!(lhs.n(), self.n());
assert!(
scratch.available()
>= GLWECiphertext::keyswitch_scratch_space(
module,
self.n(),
self.basek(),
self.k(),
lhs.k(),
rhs.k(),
rhs.digits(),
rhs.rank_in(),
rhs.rank_out(),
),
"scratch.available()={} < GLWECiphertext::keyswitch_scratch_space(
module,
self.basek(),
self.k(),
lhs.k(),
rhs.k(),
rhs.digits(),
rhs.rank_in(),
rhs.rank_out(),
)={}",
scratch.available(),
GLWECiphertext::keyswitch_scratch_space(
module,
self.n(),
self.basek(),
self.k(),
lhs.k(),
rhs.k(),
rhs.digits(),
rhs.rank_in(),
rhs.rank_out(),
)
);
}
}
impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
pub fn keyswitch<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &GGLWESwitchingKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B>,
{
#[cfg(debug_assertions)]
{
self.assert_keyswitch(module, lhs, rhs, scratch);
}
let (res_dft, scratch1) = scratch.take_vec_znx_dft(self.n(), self.cols(), rhs.size()); // Todo optimise
let res_big: VecZnxBig<_, B> = lhs.keyswitch_internal(module, res_dft, rhs, scratch1);
(0..self.cols()).for_each(|i| {
module.vec_znx_big_normalize(self.basek(), &mut self.data, i, &res_big, i, scratch1);
})
}
pub fn keyswitch_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GGLWESwitchingKeyPrepared<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B>,
{
unsafe {
let self_ptr: *mut GLWECiphertext<DataSelf> = self as *mut GLWECiphertext<DataSelf>;
self.keyswitch(module, &*self_ptr, rhs, scratch);
}
}
}
impl<D: DataRef> GLWECiphertext<D> {
pub(crate) fn keyswitch_internal<B: Backend, DataRes, DataKey>(
&self,
module: &Module<B>,
res_dft: VecZnxDft<DataRes, B>,
rhs: &GGLWESwitchingKeyPrepared<DataKey, B>,
scratch: &mut Scratch<B>,
) -> VecZnxBig<DataRes, B>
where
DataRes: DataMut,
DataKey: DataRef,
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B>,
{
if rhs.digits() == 1 {
return keyswitch_vmp_one_digit(module, res_dft, &self.data, &rhs.key.data, scratch);
}
keyswitch_vmp_multiple_digits(
module,
res_dft,
&self.data,
&rhs.key.data,
rhs.digits(),
scratch,
)
}
}
fn keyswitch_vmp_one_digit<B: Backend, DataRes, DataIn, DataVmp>(
module: &Module<B>,
mut res_dft: VecZnxDft<DataRes, B>,
a: &VecZnx<DataIn>,
mat: &VmpPMat<DataVmp, B>,
scratch: &mut Scratch<B>,
) -> VecZnxBig<DataRes, B>
where
DataRes: DataMut,
DataIn: DataRef,
DataVmp: DataRef,
Module<B>:
VecZnxDftAllocBytes + VecZnxDftFromVecZnx<B> + VmpApply<B> + VecZnxDftToVecZnxBigConsume<B> + VecZnxBigAddSmallInplace<B>,
Scratch<B>: TakeVecZnxDft<B>,
{
let cols: usize = a.cols();
let (mut ai_dft, scratch1) = scratch.take_vec_znx_dft(a.n(), cols - 1, a.size());
(0..cols - 1).for_each(|col_i| {
module.vec_znx_dft_from_vec_znx(1, 0, &mut ai_dft, col_i, a, col_i + 1);
});
module.vmp_apply(&mut res_dft, &ai_dft, mat, scratch1);
let mut res_big: VecZnxBig<DataRes, B> = module.vec_znx_dft_to_vec_znx_big_consume(res_dft);
module.vec_znx_big_add_small_inplace(&mut res_big, 0, a, 0);
res_big
}
fn keyswitch_vmp_multiple_digits<B: Backend, DataRes, DataIn, DataVmp>(
module: &Module<B>,
mut res_dft: VecZnxDft<DataRes, B>,
a: &VecZnx<DataIn>,
mat: &VmpPMat<DataVmp, B>,
digits: usize,
scratch: &mut Scratch<B>,
) -> VecZnxBig<DataRes, B>
where
DataRes: DataMut,
DataIn: DataRef,
DataVmp: DataRef,
Module<B>: VecZnxDftAllocBytes
+ VecZnxDftFromVecZnx<B>
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>,
Scratch<B>: TakeVecZnxDft<B>,
{
let cols: usize = a.cols();
let size: usize = a.size();
let (mut ai_dft, scratch1) = scratch.take_vec_znx_dft(a.n(), cols - 1, size.div_ceil(digits));
ai_dft.data_mut().fill(0);
(0..digits).for_each(|di| {
ai_dft.set_size((size + di) / digits);
// Small optimization for digits > 2
// VMP produce some error e, and since we aggregate vmp * 2^{di * B}, then
// we also aggregate ei * 2^{di * B}, with the largest error being ei * 2^{(digits-1) * B}.
// As such we can ignore the last digits-2 limbs safely of the sum of vmp products.
// It is possible to further ignore the last digits-1 limbs, but this introduce
// ~0.5 to 1 bit of additional noise, and thus not chosen here to ensure that the same
// noise is kept with respect to the ideal functionality.
res_dft.set_size(mat.size() - ((digits - di) as isize - 2).max(0) as usize);
(0..cols - 1).for_each(|col_i| {
module.vec_znx_dft_from_vec_znx(digits, digits - di - 1, &mut ai_dft, col_i, a, col_i + 1);
});
if di == 0 {
module.vmp_apply(&mut res_dft, &ai_dft, mat, scratch1);
} else {
module.vmp_apply_add(&mut res_dft, &ai_dft, mat, di, scratch1);
}
});
res_dft.set_size(res_dft.max_size());
let mut res_big: VecZnxBig<DataRes, B> = module.vec_znx_dft_to_vec_znx_big_consume(res_dft);
module.vec_znx_big_add_small_inplace(&mut res_big, 0, a, 0);
res_big
}

View File

@@ -0,0 +1,87 @@
use poulpy_backend::hal::{
api::{
ScratchAvailable, TakeVecZnx, TakeVecZnxDft, VecZnxBigAddSmallInplace, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, ZnxView,
ZnxViewMut, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{
TakeGLWECt,
layouts::{GLWECiphertext, Infos, LWECiphertext, prepared::LWESwitchingKeyPrepared},
};
impl LWECiphertext<Vec<u8>> {
pub fn keyswitch_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
basek: usize,
k_lwe_out: usize,
k_lwe_in: usize,
k_ksk: usize,
) -> usize
where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
{
GLWECiphertext::bytes_of(n, basek, k_lwe_out.max(k_lwe_in), 1)
+ GLWECiphertext::keyswitch_inplace_scratch_space(module, n, basek, k_lwe_out, k_ksk, 1, 1)
}
}
impl<DLwe: DataMut> LWECiphertext<DLwe> {
pub fn keyswitch<A, DKs, B: Backend>(
&mut self,
module: &Module<B>,
a: &LWECiphertext<A>,
ksk: &LWESwitchingKeyPrepared<DKs, B>,
scratch: &mut Scratch<B>,
) where
A: DataRef,
DKs: DataRef,
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert!(self.n() <= module.n());
assert!(a.n() <= module.n());
assert_eq!(self.basek(), a.basek());
}
let max_k: usize = self.k().max(a.k());
let basek: usize = self.basek();
let (mut glwe, scratch1) = scratch.take_glwe_ct(ksk.n(), basek, max_k, 1);
glwe.data.zero();
let n_lwe: usize = a.n();
(0..a.size()).for_each(|i| {
let data_lwe: &[i64] = a.data.at(0, i);
glwe.data.at_mut(0, i)[0] = data_lwe[0];
glwe.data.at_mut(1, i)[..n_lwe].copy_from_slice(&data_lwe[1..]);
});
glwe.keyswitch_inplace(module, &ksk.0, scratch1);
self.sample_extract(&glwe);
}
}

View File

@@ -0,0 +1,4 @@
mod gglwe_ct;
mod ggsw_ct;
mod glwe_ct;
mod lwe_ct;

View File

@@ -0,0 +1,117 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{
GGLWEAutomorphismKey, Infos,
compressed::{Decompress, GGLWESwitchingKeyCompressed},
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GGLWEAutomorphismKeyCompressed<D: Data> {
pub(crate) key: GGLWESwitchingKeyCompressed<D>,
pub(crate) p: i64,
}
impl<D: DataRef> fmt::Debug for GGLWEAutomorphismKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GGLWEAutomorphismKeyCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.key.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GGLWEAutomorphismKeyCompressed<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.key.reset();
self.p = 0;
}
}
impl<D: DataRef> fmt::Display for GGLWEAutomorphismKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(AutomorphismKeyCompressed: p={}) {}", self.p, self.key)
}
}
impl GGLWEAutomorphismKeyCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
GGLWEAutomorphismKeyCompressed {
key: GGLWESwitchingKeyCompressed::alloc(n, basek, k, rows, digits, rank, rank),
p: 0,
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize {
GGLWESwitchingKeyCompressed::<Vec<u8>>::bytes_of(n, basek, k, rows, digits, rank)
}
}
impl<D: Data> Infos for GGLWEAutomorphismKeyCompressed<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.key.inner()
}
fn basek(&self) -> usize {
self.key.basek()
}
fn k(&self) -> usize {
self.key.k()
}
}
impl<D: Data> GGLWEAutomorphismKeyCompressed<D> {
pub fn rank(&self) -> usize {
self.key.rank()
}
pub fn digits(&self) -> usize {
self.key.digits()
}
pub fn rank_in(&self) -> usize {
self.key.rank_in()
}
pub fn rank_out(&self) -> usize {
self.key.rank_out()
}
}
impl<D: DataMut> ReaderFrom for GGLWEAutomorphismKeyCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.p = reader.read_u64::<LittleEndian>()? as i64;
self.key.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GGLWEAutomorphismKeyCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.p as u64)?;
self.key.write_to(writer)
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Decompress<B, GGLWEAutomorphismKeyCompressed<DR>> for GGLWEAutomorphismKey<D> {
fn decompress(&mut self, module: &Module<B>, other: &GGLWEAutomorphismKeyCompressed<DR>)
where
Module<B>: VecZnxFillUniform + VecZnxCopy,
{
self.key.decompress(module, &other.key);
self.p = other.p;
}
}

View File

@@ -0,0 +1,254 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{
GGLWECiphertext, Infos,
compressed::{Decompress, GLWECiphertextCompressed},
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GGLWECiphertextCompressed<D: Data> {
pub(crate) data: MatZnx<D>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) rank_out: usize,
pub(crate) digits: usize,
pub(crate) seed: Vec<[u8; 32]>,
}
impl<D: DataRef> fmt::Debug for GGLWECiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GGLWECiphertextCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GGLWECiphertextCompressed<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
self.k = 0;
self.digits = 0;
self.rank_out = 0;
self.seed = Vec::new();
}
}
impl<D: DataRef> fmt::Display for GGLWECiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"(GGLWECiphertextCompressed: basek={} k={} digits={}) {}",
self.basek, self.k, self.digits, self.data
)
}
}
impl GGLWECiphertextCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize, rank_out: usize) -> Self {
let size: usize = k.div_ceil(basek);
debug_assert!(
size > digits,
"invalid gglwe: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid gglwe: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
Self {
data: MatZnx::alloc(n, rows, rank_in, 1, size),
basek,
k,
rank_out,
digits,
seed: vec![[0u8; 32]; rows * rank_in],
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize) -> usize {
let size: usize = k.div_ceil(basek);
debug_assert!(
size > digits,
"invalid gglwe: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid gglwe: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
MatZnx::alloc_bytes(n, rows, rank_in, 1, rows)
}
}
impl<D: Data> Infos for GGLWECiphertextCompressed<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data> GGLWECiphertextCompressed<D> {
pub fn rank(&self) -> usize {
self.rank_out
}
pub fn digits(&self) -> usize {
self.digits
}
pub fn rank_in(&self) -> usize {
self.data.cols_in()
}
pub fn rank_out(&self) -> usize {
self.rank_out
}
}
impl<D: DataRef> GGLWECiphertextCompressed<D> {
pub(crate) fn at(&self, row: usize, col: usize) -> GLWECiphertextCompressed<&[u8]> {
GLWECiphertextCompressed {
data: self.data.at(row, col),
basek: self.basek,
k: self.k,
rank: self.rank_out,
seed: self.seed[self.rank_in() * row + col],
}
}
}
impl<D: DataMut> GGLWECiphertextCompressed<D> {
pub(crate) fn at_mut(&mut self, row: usize, col: usize) -> GLWECiphertextCompressed<&mut [u8]> {
let rank_in: usize = self.rank_in();
GLWECiphertextCompressed {
data: self.data.at_mut(row, col),
basek: self.basek,
k: self.k,
rank: self.rank_out,
seed: self.seed[rank_in * row + col], // Warning: value is copied and not borrow mut
}
}
}
impl<D: DataMut> ReaderFrom for GGLWECiphertextCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
self.digits = reader.read_u64::<LittleEndian>()? as usize;
self.rank_out = reader.read_u64::<LittleEndian>()? as usize;
let seed_len = reader.read_u64::<LittleEndian>()? as usize;
self.seed = vec![[0u8; 32]; seed_len];
for s in &mut self.seed {
reader.read_exact(s)?;
}
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GGLWECiphertextCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
writer.write_u64::<LittleEndian>(self.digits as u64)?;
writer.write_u64::<LittleEndian>(self.rank_out as u64)?;
writer.write_u64::<LittleEndian>(self.seed.len() as u64)?;
for s in &self.seed {
writer.write_all(s)?;
}
self.data.write_to(writer)
}
}
impl<D: DataMut, B: Backend, DR: DataRef> Decompress<B, GGLWECiphertextCompressed<DR>> for GGLWECiphertext<D> {
fn decompress(&mut self, module: &Module<B>, other: &GGLWECiphertextCompressed<DR>)
where
Module<B>: VecZnxFillUniform + VecZnxCopy,
{
#[cfg(debug_assertions)]
{
use poulpy_backend::hal::api::ZnxInfos;
assert_eq!(
self.n(),
other.data.n(),
"invalid receiver: self.n()={} != other.n()={}",
self.n(),
other.data.n()
);
assert_eq!(
self.size(),
other.size(),
"invalid receiver: self.size()={} != other.size()={}",
self.size(),
other.size()
);
assert_eq!(
self.rank_in(),
other.rank_in(),
"invalid receiver: self.rank_in()={} != other.rank_in()={}",
self.rank_in(),
other.rank_in()
);
assert_eq!(
self.rank_out(),
other.rank_out(),
"invalid receiver: self.rank_out()={} != other.rank_out()={}",
self.rank_out(),
other.rank_out()
);
assert_eq!(
self.rows(),
other.rows(),
"invalid receiver: self.rows()={} != other.rows()={}",
self.rows(),
other.rows()
);
}
let rank_in: usize = self.rank_in();
let rows: usize = self.rows();
(0..rank_in).for_each(|col_i| {
(0..rows).for_each(|row_i| {
self.at_mut(row_i, col_i)
.decompress(module, &other.at(row_i, col_i));
});
});
}
}

View File

@@ -0,0 +1,127 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{
GGLWESwitchingKey, Infos,
compressed::{Decompress, GGLWECiphertextCompressed},
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GGLWESwitchingKeyCompressed<D: Data> {
pub(crate) key: GGLWECiphertextCompressed<D>,
pub(crate) sk_in_n: usize, // Degree of sk_in
pub(crate) sk_out_n: usize, // Degree of sk_out
}
impl<D: DataRef> fmt::Debug for GGLWESwitchingKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GGLWESwitchingKeyCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.key.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GGLWESwitchingKeyCompressed<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.key.reset();
self.sk_in_n = 0;
self.sk_out_n = 0;
}
}
impl<D: DataRef> fmt::Display for GGLWESwitchingKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"(GLWESwitchingKeyCompressed: sk_in_n={} sk_out_n={}) {}",
self.sk_in_n, self.sk_out_n, self.key.data
)
}
}
impl<D: Data> Infos for GGLWESwitchingKeyCompressed<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.key.inner()
}
fn basek(&self) -> usize {
self.key.basek()
}
fn k(&self) -> usize {
self.key.k()
}
}
impl<D: Data> GGLWESwitchingKeyCompressed<D> {
pub fn rank(&self) -> usize {
self.key.rank()
}
pub fn digits(&self) -> usize {
self.key.digits()
}
pub fn rank_in(&self) -> usize {
self.key.rank_in()
}
pub fn rank_out(&self) -> usize {
self.key.rank_out()
}
}
impl GGLWESwitchingKeyCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize, rank_out: usize) -> Self {
GGLWESwitchingKeyCompressed {
key: GGLWECiphertextCompressed::alloc(n, basek, k, rows, digits, rank_in, rank_out),
sk_in_n: 0,
sk_out_n: 0,
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize) -> usize {
GGLWECiphertextCompressed::bytes_of(n, basek, k, rows, digits, rank_in)
}
}
impl<D: DataMut> ReaderFrom for GGLWESwitchingKeyCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.sk_in_n = reader.read_u64::<LittleEndian>()? as usize;
self.sk_out_n = reader.read_u64::<LittleEndian>()? as usize;
self.key.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GGLWESwitchingKeyCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.sk_in_n as u64)?;
writer.write_u64::<LittleEndian>(self.sk_out_n as u64)?;
self.key.write_to(writer)
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Decompress<B, GGLWESwitchingKeyCompressed<DR>> for GGLWESwitchingKey<D> {
fn decompress(&mut self, module: &Module<B>, other: &GGLWESwitchingKeyCompressed<DR>)
where
Module<B>: VecZnxFillUniform + VecZnxCopy,
{
self.key.decompress(module, &other.key);
self.sk_in_n = other.sk_in_n;
self.sk_out_n = other.sk_out_n;
}
}

View File

@@ -0,0 +1,165 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{
GGLWETensorKey, Infos,
compressed::{Decompress, GGLWESwitchingKeyCompressed},
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GGLWETensorKeyCompressed<D: Data> {
pub(crate) keys: Vec<GGLWESwitchingKeyCompressed<D>>,
}
impl<D: DataRef> fmt::Debug for GGLWETensorKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GGLWETensorKeyCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.keys
.iter_mut()
.for_each(|key: &mut GGLWESwitchingKeyCompressed<D>| key.fill_uniform(source))
}
}
impl<D: DataMut> Reset for GGLWETensorKeyCompressed<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.keys
.iter_mut()
.for_each(|key: &mut GGLWESwitchingKeyCompressed<D>| key.reset())
}
}
impl<D: DataRef> fmt::Display for GGLWETensorKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "(GLWETensorKeyCompressed)",)?;
for (i, key) in self.keys.iter().enumerate() {
write!(f, "{}: {}", i, key)?;
}
Ok(())
}
}
impl GGLWETensorKeyCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
let mut keys: Vec<GGLWESwitchingKeyCompressed<Vec<u8>>> = Vec::new();
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
(0..pairs).for_each(|_| {
keys.push(GGLWESwitchingKeyCompressed::alloc(
n, basek, k, rows, digits, 1, rank,
));
});
Self { keys }
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize {
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
pairs * GGLWESwitchingKeyCompressed::bytes_of(n, basek, k, rows, digits, 1)
}
}
impl<D: Data> Infos for GGLWETensorKeyCompressed<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.keys[0].inner()
}
fn basek(&self) -> usize {
self.keys[0].basek()
}
fn k(&self) -> usize {
self.keys[0].k()
}
}
impl<D: Data> GGLWETensorKeyCompressed<D> {
pub fn rank(&self) -> usize {
self.keys[0].rank()
}
pub fn digits(&self) -> usize {
self.keys[0].digits()
}
pub fn rank_in(&self) -> usize {
self.keys[0].rank_in()
}
pub fn rank_out(&self) -> usize {
self.keys[0].rank_out()
}
}
impl<D: DataMut> ReaderFrom for GGLWETensorKeyCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
let len: usize = reader.read_u64::<LittleEndian>()? as usize;
if self.keys.len() != len {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("self.keys.len()={} != read len={}", self.keys.len(), len),
));
}
for key in &mut self.keys {
key.read_from(reader)?;
}
Ok(())
}
}
impl<D: DataRef> WriterTo for GGLWETensorKeyCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.keys.len() as u64)?;
for key in &self.keys {
key.write_to(writer)?;
}
Ok(())
}
}
impl<D: DataMut> GGLWETensorKeyCompressed<D> {
pub(crate) fn at_mut(&mut self, mut i: usize, mut j: usize) -> &mut GGLWESwitchingKeyCompressed<D> {
if i > j {
std::mem::swap(&mut i, &mut j);
};
let rank: usize = self.rank();
&mut self.keys[i * rank + j - (i * (i + 1) / 2)]
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Decompress<B, GGLWETensorKeyCompressed<DR>> for GGLWETensorKey<D> {
fn decompress(&mut self, module: &Module<B>, other: &GGLWETensorKeyCompressed<DR>)
where
Module<B>: VecZnxFillUniform + VecZnxCopy,
{
#[cfg(debug_assertions)]
{
assert_eq!(
self.keys.len(),
other.keys.len(),
"invalid receiver: self.keys.len()={} != other.keys.len()={}",
self.keys.len(),
other.keys.len()
);
}
self.keys
.iter_mut()
.zip(other.keys.iter())
.for_each(|(a, b)| {
a.decompress(module, b);
});
}
}

View File

@@ -0,0 +1,207 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{
GGSWCiphertext, Infos,
compressed::{Decompress, GLWECiphertextCompressed},
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GGSWCiphertextCompressed<D: Data> {
pub(crate) data: MatZnx<D>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) digits: usize,
pub(crate) rank: usize,
pub(crate) seed: Vec<[u8; 32]>,
}
impl<D: DataRef> fmt::Debug for GGSWCiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.data)
}
}
impl<D: DataRef> fmt::Display for GGSWCiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"(GGSWCiphertextCompressed: basek={} k={} digits={}) {}",
self.basek, self.k, self.digits, self.data
)
}
}
impl<D: DataMut> Reset for GGSWCiphertextCompressed<D> {
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
self.k = 0;
self.digits = 0;
self.rank = 0;
self.seed = Vec::new();
}
}
impl<D: DataMut> FillUniform for GGSWCiphertextCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
}
impl GGSWCiphertextCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
let size: usize = k.div_ceil(basek);
debug_assert!(digits > 0, "invalid ggsw: `digits` == 0");
debug_assert!(
size > digits,
"invalid ggsw: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid ggsw: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
Self {
data: MatZnx::alloc(n, rows, rank + 1, 1, k.div_ceil(basek)),
basek,
k,
digits,
rank,
seed: Vec::new(),
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize {
let size: usize = k.div_ceil(basek);
debug_assert!(
size > digits,
"invalid ggsw: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid ggsw: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
MatZnx::alloc_bytes(n, rows, rank + 1, 1, size)
}
}
impl<D: DataRef> GGSWCiphertextCompressed<D> {
pub fn at(&self, row: usize, col: usize) -> GLWECiphertextCompressed<&[u8]> {
GLWECiphertextCompressed {
data: self.data.at(row, col),
basek: self.basek,
k: self.k,
rank: self.rank(),
seed: self.seed[row * (self.rank() + 1) + col],
}
}
}
impl<D: DataMut> GGSWCiphertextCompressed<D> {
pub fn at_mut(&mut self, row: usize, col: usize) -> GLWECiphertextCompressed<&mut [u8]> {
let rank: usize = self.rank();
GLWECiphertextCompressed {
data: self.data.at_mut(row, col),
basek: self.basek,
k: self.k,
rank,
seed: self.seed[row * (rank + 1) + col],
}
}
}
impl<D: Data> Infos for GGSWCiphertextCompressed<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data> GGSWCiphertextCompressed<D> {
pub fn rank(&self) -> usize {
self.rank
}
pub fn digits(&self) -> usize {
self.digits
}
}
impl<D: DataMut> ReaderFrom for GGSWCiphertextCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
self.digits = reader.read_u64::<LittleEndian>()? as usize;
self.rank = reader.read_u64::<LittleEndian>()? as usize;
let seed_len = reader.read_u64::<LittleEndian>()? as usize;
self.seed = vec![[0u8; 32]; seed_len];
for s in &mut self.seed {
reader.read_exact(s)?;
}
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GGSWCiphertextCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
writer.write_u64::<LittleEndian>(self.digits as u64)?;
writer.write_u64::<LittleEndian>(self.rank as u64)?;
writer.write_u64::<LittleEndian>(self.seed.len() as u64)?;
for s in &self.seed {
writer.write_all(s)?;
}
self.data.write_to(writer)
}
}
impl<D: DataMut, B: Backend, DR: DataRef> Decompress<B, GGSWCiphertextCompressed<DR>> for GGSWCiphertext<D> {
fn decompress(&mut self, module: &Module<B>, other: &GGSWCiphertextCompressed<DR>)
where
Module<B>: VecZnxFillUniform + VecZnxCopy,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.rank(), other.rank())
}
let rows: usize = self.rows();
let rank: usize = self.rank();
(0..rows).for_each(|row_i| {
(0..rank + 1).for_each(|col_j| {
self.at_mut(row_i, col_j)
.decompress(module, &other.at(row_i, col_j));
});
});
}
}

View File

@@ -0,0 +1,177 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, VecZnx, WriterTo},
source::Source,
};
use crate::layouts::{GLWECiphertext, Infos, compressed::Decompress};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GLWECiphertextCompressed<D: Data> {
pub(crate) data: VecZnx<D>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) rank: usize,
pub(crate) seed: [u8; 32],
}
impl<D: DataRef> fmt::Debug for GLWECiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataRef> fmt::Display for GLWECiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"GLWECiphertextCompressed: basek={} k={} rank={} seed={:?}: {}",
self.basek(),
self.k(),
self.rank,
self.seed,
self.data
)
}
}
impl<D: DataMut> Reset for GLWECiphertextCompressed<D> {
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
self.k = 0;
self.rank = 0;
self.seed = [0u8; 32];
}
}
impl<D: DataMut> FillUniform for GLWECiphertextCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
}
impl<D: Data> Infos for GLWECiphertextCompressed<D> {
type Inner = VecZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data> GLWECiphertextCompressed<D> {
pub fn rank(&self) -> usize {
self.rank
}
}
impl GLWECiphertextCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rank: usize) -> Self {
Self {
data: VecZnx::alloc(n, 1, k.div_ceil(basek)),
basek,
k,
rank,
seed: [0u8; 32],
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize) -> usize {
GLWECiphertext::bytes_of(n, basek, k, 1)
}
}
impl<D: DataMut> ReaderFrom for GLWECiphertextCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
self.rank = reader.read_u64::<LittleEndian>()? as usize;
reader.read_exact(&mut self.seed)?;
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GLWECiphertextCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
writer.write_u64::<LittleEndian>(self.rank as u64)?;
writer.write_all(&self.seed)?;
self.data.write_to(writer)
}
}
impl<D: DataMut, B: Backend, DR: DataRef> Decompress<B, GLWECiphertextCompressed<DR>> for GLWECiphertext<D> {
fn decompress(&mut self, module: &Module<B>, other: &GLWECiphertextCompressed<DR>)
where
Module<B>: VecZnxCopy + VecZnxFillUniform,
{
#[cfg(debug_assertions)]
{
use poulpy_backend::hal::api::ZnxInfos;
assert_eq!(
self.n(),
other.data.n(),
"invalid receiver: self.n()={} != other.n()={}",
self.n(),
other.data.n()
);
assert_eq!(
self.size(),
other.size(),
"invalid receiver: self.size()={} != other.size()={}",
self.size(),
other.size()
);
assert_eq!(
self.rank(),
other.rank(),
"invalid receiver: self.rank()={} != other.rank()={}",
self.rank(),
other.rank()
);
}
let mut source: Source = Source::new(other.seed);
self.decompress_internal(module, other, &mut source);
}
}
impl<D: DataMut> GLWECiphertext<D> {
pub(crate) fn decompress_internal<DataOther, B: Backend>(
&mut self,
module: &Module<B>,
other: &GLWECiphertextCompressed<DataOther>,
source: &mut Source,
) where
DataOther: DataRef,
Module<B>: VecZnxCopy + VecZnxFillUniform,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.rank(), other.rank())
}
let k: usize = other.k;
let basek: usize = other.basek;
let cols: usize = other.rank() + 1;
module.vec_znx_copy(&mut self.data, 0, &other.data, 0);
(1..cols).for_each(|i| {
module.vec_znx_fill_uniform(basek, &mut self.data, i, k, source);
});
self.basek = basek;
self.k = k;
}
}

View File

@@ -0,0 +1,117 @@
use std::fmt;
use poulpy_backend::hal::{
api::{FillUniform, Reset},
api::{
SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, VecZnxAddInplace, VecZnxAddNormal, VecZnxBigNormalize,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace,
},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{GLWEToLWESwitchingKey, Infos, compressed::GGLWESwitchingKeyCompressed};
#[derive(PartialEq, Eq, Clone)]
pub struct GLWEToLWESwitchingKeyCompressed<D: Data>(pub(crate) GGLWESwitchingKeyCompressed<D>);
impl<D: DataRef> fmt::Debug for GLWEToLWESwitchingKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GLWEToLWESwitchingKeyCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.0.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GLWEToLWESwitchingKeyCompressed<D> {
fn reset(&mut self) {
self.0.reset();
}
}
impl<D: DataRef> fmt::Display for GLWEToLWESwitchingKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(GLWEToLWESwitchingKeyCompressed) {}", self.0)
}
}
impl<D: Data> Infos for GLWEToLWESwitchingKeyCompressed<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.0.inner()
}
fn basek(&self) -> usize {
self.0.basek()
}
fn k(&self) -> usize {
self.0.k()
}
}
impl<D: Data> GLWEToLWESwitchingKeyCompressed<D> {
pub fn digits(&self) -> usize {
self.0.digits()
}
pub fn rank(&self) -> usize {
self.0.rank()
}
pub fn rank_in(&self) -> usize {
self.0.rank_in()
}
pub fn rank_out(&self) -> usize {
self.0.rank_out()
}
}
impl<D: DataMut> ReaderFrom for GLWEToLWESwitchingKeyCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.0.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GLWEToLWESwitchingKeyCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
self.0.write_to(writer)
}
}
impl GLWEToLWESwitchingKeyCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, rank_in: usize) -> Self {
Self(GGLWESwitchingKeyCompressed::alloc(
n, basek, k, rows, 1, rank_in, 1,
))
}
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank_in: usize) -> usize
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>,
{
GLWEToLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, rank_in)
}
}

View File

@@ -0,0 +1,131 @@
use std::fmt;
use poulpy_backend::hal::{
api::{FillUniform, Reset, VecZnxFillUniform, ZnxInfos, ZnxView, ZnxViewMut},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, VecZnx, WriterTo},
source::Source,
};
use crate::layouts::{Infos, LWECiphertext, SetMetaData, compressed::Decompress};
#[derive(PartialEq, Eq, Clone)]
pub struct LWECiphertextCompressed<D: Data> {
pub(crate) data: VecZnx<D>,
pub(crate) k: usize,
pub(crate) basek: usize,
pub(crate) seed: [u8; 32],
}
impl<D: DataRef> fmt::Debug for LWECiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataRef> fmt::Display for LWECiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"LWECiphertextCompressed: basek={} k={} seed={:?}: {}",
self.basek(),
self.k(),
self.seed,
self.data
)
}
}
impl<D: DataMut> Reset for LWECiphertextCompressed<D>
where
VecZnx<D>: Reset,
{
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
self.k = 0;
self.seed = [0u8; 32];
}
}
impl<D: DataMut> FillUniform for LWECiphertextCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
}
impl LWECiphertextCompressed<Vec<u8>> {
pub fn alloc(basek: usize, k: usize) -> Self {
Self {
data: VecZnx::alloc(1, 1, k.div_ceil(basek)),
k,
basek,
seed: [0u8; 32],
}
}
}
impl<D: Data> Infos for LWECiphertextCompressed<D>
where
VecZnx<D>: ZnxInfos,
{
type Inner = VecZnx<D>;
fn n(&self) -> usize {
&self.inner().n() - 1
}
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<DataSelf: DataMut> SetMetaData for LWECiphertextCompressed<DataSelf> {
fn set_k(&mut self, k: usize) {
self.k = k
}
fn set_basek(&mut self, basek: usize) {
self.basek = basek
}
}
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
impl<D: DataMut> ReaderFrom for LWECiphertextCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
reader.read_exact(&mut self.seed)?;
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for LWECiphertextCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
writer.write_all(&self.seed)?;
self.data.write_to(writer)
}
}
impl<D: DataMut, B: Backend, DR: DataRef> Decompress<B, LWECiphertextCompressed<DR>> for LWECiphertext<D> {
fn decompress(&mut self, module: &Module<B>, other: &LWECiphertextCompressed<DR>)
where
Module<B>: VecZnxFillUniform,
{
let mut source = Source::new(other.seed);
module.vec_znx_fill_uniform(other.basek(), &mut self.data, 0, other.k(), &mut source);
(0..self.size()).for_each(|i| {
self.data.at_mut(0, i)[0] = other.data.at(0, i)[0];
});
}
}

View File

@@ -0,0 +1,127 @@
use poulpy_backend::hal::{
api::{
FillUniform, Reset, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, VecZnxAddInplace, VecZnxAddNormal,
VecZnxBigNormalize, VecZnxCopy, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform,
VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace,
},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{
Infos, LWESwitchingKey,
compressed::{Decompress, GGLWESwitchingKeyCompressed},
};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct LWESwitchingKeyCompressed<D: Data>(pub(crate) GGLWESwitchingKeyCompressed<D>);
impl<D: DataRef> fmt::Debug for LWESwitchingKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for LWESwitchingKeyCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.0.fill_uniform(source);
}
}
impl<D: DataMut> Reset for LWESwitchingKeyCompressed<D> {
fn reset(&mut self) {
self.0.reset();
}
}
impl<D: DataRef> fmt::Display for LWESwitchingKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(LWESwitchingKeyCompressed) {}", self.0)
}
}
impl<D: Data> Infos for LWESwitchingKeyCompressed<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.0.inner()
}
fn basek(&self) -> usize {
self.0.basek()
}
fn k(&self) -> usize {
self.0.k()
}
}
impl<D: Data> LWESwitchingKeyCompressed<D> {
pub fn digits(&self) -> usize {
self.0.digits()
}
pub fn rank(&self) -> usize {
self.0.rank()
}
pub fn rank_in(&self) -> usize {
self.0.rank_in()
}
pub fn rank_out(&self) -> usize {
self.0.rank_out()
}
}
impl<D: DataMut> ReaderFrom for LWESwitchingKeyCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.0.read_from(reader)
}
}
impl<D: DataRef> WriterTo for LWESwitchingKeyCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
self.0.write_to(writer)
}
}
impl LWESwitchingKeyCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize) -> Self {
Self(GGLWESwitchingKeyCompressed::alloc(
n, basek, k, rows, 1, 1, 1,
))
}
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>,
{
LWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k)
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Decompress<B, LWESwitchingKeyCompressed<DR>> for LWESwitchingKey<D> {
fn decompress(&mut self, module: &Module<B>, other: &LWESwitchingKeyCompressed<DR>)
where
Module<B>: VecZnxCopy + VecZnxFillUniform,
{
self.0.decompress(module, &other.0);
}
}

View File

@@ -0,0 +1,128 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset},
api::{
SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, VecZnxAddInplace, VecZnxAddNormal, VecZnxBigNormalize,
VecZnxCopy, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace,
},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{
Infos, LWEToGLWESwitchingKey,
compressed::{Decompress, GGLWESwitchingKeyCompressed},
};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct LWEToGLWESwitchingKeyCompressed<D: Data>(pub(crate) GGLWESwitchingKeyCompressed<D>);
impl<D: DataRef> fmt::Debug for LWEToGLWESwitchingKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for LWEToGLWESwitchingKeyCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.0.fill_uniform(source);
}
}
impl<D: DataMut> Reset for LWEToGLWESwitchingKeyCompressed<D> {
fn reset(&mut self) {
self.0.reset();
}
}
impl<D: DataRef> fmt::Display for LWEToGLWESwitchingKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(LWEToGLWESwitchingKeyCompressed) {}", self.0)
}
}
impl<D: Data> Infos for LWEToGLWESwitchingKeyCompressed<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.0.inner()
}
fn basek(&self) -> usize {
self.0.basek()
}
fn k(&self) -> usize {
self.0.k()
}
}
impl<D: Data> LWEToGLWESwitchingKeyCompressed<D> {
pub fn digits(&self) -> usize {
self.0.digits()
}
pub fn rank(&self) -> usize {
self.0.rank()
}
pub fn rank_in(&self) -> usize {
self.0.rank_in()
}
pub fn rank_out(&self) -> usize {
self.0.rank_out()
}
}
impl<D: DataMut> ReaderFrom for LWEToGLWESwitchingKeyCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.0.read_from(reader)
}
}
impl<D: DataRef> WriterTo for LWEToGLWESwitchingKeyCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
self.0.write_to(writer)
}
}
impl LWEToGLWESwitchingKeyCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, rank_out: usize) -> Self {
Self(GGLWESwitchingKeyCompressed::alloc(
n, basek, k, rows, 1, 1, rank_out,
))
}
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank_out: usize) -> usize
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>,
{
LWEToGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, rank_out)
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Decompress<B, LWEToGLWESwitchingKeyCompressed<DR>> for LWEToGLWESwitchingKey<D> {
fn decompress(&mut self, module: &Module<B>, other: &LWEToGLWESwitchingKeyCompressed<DR>)
where
Module<B>: VecZnxCopy + VecZnxFillUniform,
{
self.0.decompress(module, &other.0);
}
}

View File

@@ -0,0 +1,32 @@
mod gglwe_atk;
mod gglwe_ct;
mod gglwe_ksk;
mod gglwe_tsk;
mod ggsw_ct;
mod glwe_ct;
mod glwe_to_lwe_ksk;
mod lwe_ct;
mod lwe_ksk;
mod lwe_to_glwe_ksk;
pub use gglwe_atk::*;
pub use gglwe_ct::*;
pub use gglwe_ksk::*;
pub use gglwe_tsk::*;
pub use ggsw_ct::*;
pub use glwe_ct::*;
pub use glwe_to_lwe_ksk::*;
pub use lwe_ct::*;
pub use lwe_ksk::*;
pub use lwe_to_glwe_ksk::*;
use poulpy_backend::hal::{
api::{VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Module},
};
pub trait Decompress<B: Backend, C> {
fn decompress(&mut self, module: &Module<B>, other: &C)
where
Module<B>: VecZnxFillUniform + VecZnxCopy;
}

View File

@@ -0,0 +1,121 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{GGLWESwitchingKey, GLWECiphertext, Infos};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GGLWEAutomorphismKey<D: Data> {
pub(crate) key: GGLWESwitchingKey<D>,
pub(crate) p: i64,
}
impl<D: DataRef> fmt::Debug for GGLWEAutomorphismKey<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GGLWEAutomorphismKey<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.key.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GGLWEAutomorphismKey<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.key.reset();
self.p = 0;
}
}
impl<D: DataRef> fmt::Display for GGLWEAutomorphismKey<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(AutomorphismKey: p={}) {}", self.p, self.key)
}
}
impl GGLWEAutomorphismKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
GGLWEAutomorphismKey {
key: GGLWESwitchingKey::alloc(n, basek, k, rows, digits, rank, rank),
p: 0,
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize {
GGLWESwitchingKey::bytes_of(n, basek, k, rows, digits, rank, rank)
}
}
impl<D: Data> Infos for GGLWEAutomorphismKey<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.key.inner()
}
fn basek(&self) -> usize {
self.key.basek()
}
fn k(&self) -> usize {
self.key.k()
}
}
impl<D: Data> GGLWEAutomorphismKey<D> {
pub fn p(&self) -> i64 {
self.p
}
pub fn digits(&self) -> usize {
self.key.digits()
}
pub fn rank(&self) -> usize {
self.key.rank()
}
pub fn rank_in(&self) -> usize {
self.key.rank_in()
}
pub fn rank_out(&self) -> usize {
self.key.rank_out()
}
}
impl<D: DataRef> GGLWEAutomorphismKey<D> {
pub fn at(&self, row: usize, col: usize) -> GLWECiphertext<&[u8]> {
self.key.at(row, col)
}
}
impl<D: DataMut> GGLWEAutomorphismKey<D> {
pub fn at_mut(&mut self, row: usize, col: usize) -> GLWECiphertext<&mut [u8]> {
self.key.at_mut(row, col)
}
}
impl<D: DataMut> ReaderFrom for GGLWEAutomorphismKey<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.p = reader.read_u64::<LittleEndian>()? as i64;
self.key.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GGLWEAutomorphismKey<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.p as u64)?;
self.key.write_to(writer)
}
}

View File

@@ -0,0 +1,168 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{GLWECiphertext, Infos};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GGLWECiphertext<D: Data> {
pub(crate) data: MatZnx<D>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) digits: usize,
}
impl<D: DataRef> fmt::Debug for GGLWECiphertext<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GGLWECiphertext<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GGLWECiphertext<D> {
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
self.k = 0;
self.digits = 0;
}
}
impl<D: DataRef> fmt::Display for GGLWECiphertext<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"(GGLWECiphertext: basek={} k={} digits={}) {}",
self.basek, self.k, self.digits, self.data
)
}
}
impl<D: DataRef> GGLWECiphertext<D> {
pub fn at(&self, row: usize, col: usize) -> GLWECiphertext<&[u8]> {
GLWECiphertext {
data: self.data.at(row, col),
basek: self.basek,
k: self.k,
}
}
}
impl<D: DataMut> GGLWECiphertext<D> {
pub fn at_mut(&mut self, row: usize, col: usize) -> GLWECiphertext<&mut [u8]> {
GLWECiphertext {
data: self.data.at_mut(row, col),
basek: self.basek,
k: self.k,
}
}
}
impl GGLWECiphertext<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize, rank_out: usize) -> Self {
let size: usize = k.div_ceil(basek);
debug_assert!(
size > digits,
"invalid gglwe: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid gglwe: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
Self {
data: MatZnx::alloc(n, rows, rank_in, rank_out + 1, size),
basek,
k,
digits,
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize, rank_out: usize) -> usize {
let size: usize = k.div_ceil(basek);
debug_assert!(
size > digits,
"invalid gglwe: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid gglwe: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
MatZnx::alloc_bytes(n, rows, rank_in, rank_out + 1, rows)
}
}
impl<D: Data> Infos for GGLWECiphertext<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data> GGLWECiphertext<D> {
pub fn rank(&self) -> usize {
self.data.cols_out() - 1
}
pub fn digits(&self) -> usize {
self.digits
}
pub fn rank_in(&self) -> usize {
self.data.cols_in()
}
pub fn rank_out(&self) -> usize {
self.data.cols_out() - 1
}
}
impl<D: DataMut> ReaderFrom for GGLWECiphertext<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
self.digits = reader.read_u64::<LittleEndian>()? as usize;
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GGLWECiphertext<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
writer.write_u64::<LittleEndian>(self.digits as u64)?;
self.data.write_to(writer)
}
}

View File

@@ -0,0 +1,134 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{GGLWECiphertext, GLWECiphertext, Infos};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GGLWESwitchingKey<D: Data> {
pub(crate) key: GGLWECiphertext<D>,
pub(crate) sk_in_n: usize, // Degree of sk_in
pub(crate) sk_out_n: usize, // Degree of sk_out
}
impl<D: DataRef> fmt::Debug for GGLWESwitchingKey<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataRef> fmt::Display for GGLWESwitchingKey<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"(GLWESwitchingKey: sk_in_n={} sk_out_n={}) {}",
self.sk_in_n, self.sk_out_n, self.key.data
)
}
}
impl<D: DataMut> FillUniform for GGLWESwitchingKey<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.key.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GGLWESwitchingKey<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.key.reset();
self.sk_in_n = 0;
self.sk_out_n = 0;
}
}
impl GGLWESwitchingKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize, rank_out: usize) -> Self {
GGLWESwitchingKey {
key: GGLWECiphertext::alloc(n, basek, k, rows, digits, rank_in, rank_out),
sk_in_n: 0,
sk_out_n: 0,
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize, rank_out: usize) -> usize {
GGLWECiphertext::<Vec<u8>>::bytes_of(n, basek, k, rows, digits, rank_in, rank_out)
}
}
impl<D: Data> Infos for GGLWESwitchingKey<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.key.inner()
}
fn basek(&self) -> usize {
self.key.basek()
}
fn k(&self) -> usize {
self.key.k()
}
}
impl<D: Data> GGLWESwitchingKey<D> {
pub fn rank(&self) -> usize {
self.key.data.cols_out() - 1
}
pub fn rank_in(&self) -> usize {
self.key.data.cols_in()
}
pub fn rank_out(&self) -> usize {
self.key.data.cols_out() - 1
}
pub fn digits(&self) -> usize {
self.key.digits()
}
pub fn sk_degree_in(&self) -> usize {
self.sk_in_n
}
pub fn sk_degree_out(&self) -> usize {
self.sk_out_n
}
}
impl<D: DataRef> GGLWESwitchingKey<D> {
pub fn at(&self, row: usize, col: usize) -> GLWECiphertext<&[u8]> {
self.key.at(row, col)
}
}
impl<D: DataMut> GGLWESwitchingKey<D> {
pub fn at_mut(&mut self, row: usize, col: usize) -> GLWECiphertext<&mut [u8]> {
self.key.at_mut(row, col)
}
}
impl<D: DataMut> ReaderFrom for GGLWESwitchingKey<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.sk_in_n = reader.read_u64::<LittleEndian>()? as usize;
self.sk_out_n = reader.read_u64::<LittleEndian>()? as usize;
self.key.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GGLWESwitchingKey<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.sk_in_n as u64)?;
writer.write_u64::<LittleEndian>(self.sk_out_n as u64)?;
self.key.write_to(writer)
}
}

View File

@@ -0,0 +1,148 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{GGLWESwitchingKey, Infos};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GGLWETensorKey<D: Data> {
pub(crate) keys: Vec<GGLWESwitchingKey<D>>,
}
impl<D: DataRef> fmt::Debug for GGLWETensorKey<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GGLWETensorKey<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.keys
.iter_mut()
.for_each(|key: &mut GGLWESwitchingKey<D>| key.fill_uniform(source))
}
}
impl<D: DataMut> Reset for GGLWETensorKey<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.keys
.iter_mut()
.for_each(|key: &mut GGLWESwitchingKey<D>| key.reset())
}
}
impl<D: DataRef> fmt::Display for GGLWETensorKey<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "(GLWETensorKey)",)?;
for (i, key) in self.keys.iter().enumerate() {
write!(f, "{}: {}", i, key)?;
}
Ok(())
}
}
impl GGLWETensorKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
let mut keys: Vec<GGLWESwitchingKey<Vec<u8>>> = Vec::new();
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
(0..pairs).for_each(|_| {
keys.push(GGLWESwitchingKey::alloc(n, basek, k, rows, digits, 1, rank));
});
Self { keys }
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize {
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
pairs * GGLWESwitchingKey::<Vec<u8>>::bytes_of(n, basek, k, rows, digits, 1, rank)
}
}
impl<D: Data> Infos for GGLWETensorKey<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.keys[0].inner()
}
fn basek(&self) -> usize {
self.keys[0].basek()
}
fn k(&self) -> usize {
self.keys[0].k()
}
}
impl<D: Data> GGLWETensorKey<D> {
pub fn rank(&self) -> usize {
self.keys[0].rank()
}
pub fn rank_in(&self) -> usize {
self.keys[0].rank_in()
}
pub fn rank_out(&self) -> usize {
self.keys[0].rank_out()
}
pub fn digits(&self) -> usize {
self.keys[0].digits()
}
}
impl<D: DataMut> GGLWETensorKey<D> {
// Returns a mutable reference to GLWESwitchingKey_{s}(s[i] * s[j])
pub fn at_mut(&mut self, mut i: usize, mut j: usize) -> &mut GGLWESwitchingKey<D> {
if i > j {
std::mem::swap(&mut i, &mut j);
};
let rank: usize = self.rank();
&mut self.keys[i * rank + j - (i * (i + 1) / 2)]
}
}
impl<D: DataRef> GGLWETensorKey<D> {
// Returns a reference to GLWESwitchingKey_{s}(s[i] * s[j])
pub fn at(&self, mut i: usize, mut j: usize) -> &GGLWESwitchingKey<D> {
if i > j {
std::mem::swap(&mut i, &mut j);
};
let rank: usize = self.rank();
&self.keys[i * rank + j - (i * (i + 1) / 2)]
}
}
impl<D: DataMut> ReaderFrom for GGLWETensorKey<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
let len: usize = reader.read_u64::<LittleEndian>()? as usize;
if self.keys.len() != len {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("self.keys.len()={} != read len={}", self.keys.len(), len),
));
}
for key in &mut self.keys {
key.read_from(reader)?;
}
Ok(())
}
}
impl<D: DataRef> WriterTo for GGLWETensorKey<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.keys.len() as u64)?;
for key in &self.keys {
key.write_to(writer)?;
}
Ok(())
}
}

View File

@@ -0,0 +1,162 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
source::Source,
};
use std::fmt;
use crate::layouts::{GLWECiphertext, Infos};
#[derive(PartialEq, Eq, Clone)]
pub struct GGSWCiphertext<D: Data> {
pub(crate) data: MatZnx<D>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) digits: usize,
}
impl<D: DataRef> fmt::Debug for GGSWCiphertext<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.data)
}
}
impl<D: DataRef> fmt::Display for GGSWCiphertext<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"(GGSWCiphertext: basek={} k={} digits={}) {}",
self.basek, self.k, self.digits, self.data
)
}
}
impl<D: DataMut> Reset for GGSWCiphertext<D> {
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
self.k = 0;
self.digits = 0;
}
}
impl<D: DataMut> FillUniform for GGSWCiphertext<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
}
impl<D: DataRef> GGSWCiphertext<D> {
pub fn at(&self, row: usize, col: usize) -> GLWECiphertext<&[u8]> {
GLWECiphertext {
data: self.data.at(row, col),
basek: self.basek,
k: self.k,
}
}
}
impl<D: DataMut> GGSWCiphertext<D> {
pub fn at_mut(&mut self, row: usize, col: usize) -> GLWECiphertext<&mut [u8]> {
GLWECiphertext {
data: self.data.at_mut(row, col),
basek: self.basek,
k: self.k,
}
}
}
impl GGSWCiphertext<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
let size: usize = k.div_ceil(basek);
debug_assert!(digits > 0, "invalid ggsw: `digits` == 0");
debug_assert!(
size > digits,
"invalid ggsw: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid ggsw: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
Self {
data: MatZnx::alloc(n, rows, rank + 1, rank + 1, k.div_ceil(basek)),
basek,
k,
digits,
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize {
let size: usize = k.div_ceil(basek);
debug_assert!(
size > digits,
"invalid ggsw: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid ggsw: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
MatZnx::alloc_bytes(n, rows, rank + 1, rank + 1, size)
}
}
impl<D: Data> Infos for GGSWCiphertext<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data> GGSWCiphertext<D> {
pub fn rank(&self) -> usize {
self.data.cols_out() - 1
}
pub fn digits(&self) -> usize {
self.digits
}
}
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
impl<D: DataMut> ReaderFrom for GGSWCiphertext<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
self.digits = reader.read_u64::<LittleEndian>()? as usize;
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GGSWCiphertext<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
writer.write_u64::<LittleEndian>(self.digits as u64)?;
self.data.write_to(writer)
}
}

View File

@@ -0,0 +1,152 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, ReaderFrom, ToOwnedDeep, VecZnx, VecZnxToMut, VecZnxToRef, WriterTo},
source::Source,
};
use crate::layouts::{Infos, SetMetaData};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GLWECiphertext<D: Data> {
pub data: VecZnx<D>,
pub basek: usize,
pub k: usize,
}
impl<D: DataRef> ToOwnedDeep for GLWECiphertext<D> {
type Owned = GLWECiphertext<Vec<u8>>;
fn to_owned_deep(&self) -> Self::Owned {
GLWECiphertext {
data: self.data.to_owned_deep(),
basek: self.basek,
k: self.k,
}
}
}
impl<D: DataRef> fmt::Debug for GLWECiphertext<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataRef> fmt::Display for GLWECiphertext<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"GLWECiphertext: basek={} k={}: {}",
self.basek(),
self.k(),
self.data
)
}
}
impl<D: DataMut> Reset for GLWECiphertext<D>
where
VecZnx<D>: Reset,
{
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
self.k = 0;
}
}
impl<D: DataMut> FillUniform for GLWECiphertext<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
}
impl GLWECiphertext<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rank: usize) -> Self {
Self {
data: VecZnx::alloc(n, rank + 1, k.div_ceil(basek)),
basek,
k,
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rank: usize) -> usize {
VecZnx::alloc_bytes(n, rank + 1, k.div_ceil(basek))
}
}
impl<D: Data> Infos for GLWECiphertext<D> {
type Inner = VecZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data> GLWECiphertext<D> {
pub fn rank(&self) -> usize {
self.cols() - 1
}
}
impl<D: DataMut> SetMetaData for GLWECiphertext<D> {
fn set_k(&mut self, k: usize) {
self.k = k
}
fn set_basek(&mut self, basek: usize) {
self.basek = basek
}
}
pub trait GLWECiphertextToRef: Infos {
fn to_ref(&self) -> GLWECiphertext<&[u8]>;
}
impl<D: DataRef> GLWECiphertextToRef for GLWECiphertext<D> {
fn to_ref(&self) -> GLWECiphertext<&[u8]> {
GLWECiphertext {
data: self.data.to_ref(),
basek: self.basek,
k: self.k,
}
}
}
pub trait GLWECiphertextToMut: Infos {
fn to_mut(&mut self) -> GLWECiphertext<&mut [u8]>;
}
impl<D: DataMut> GLWECiphertextToMut for GLWECiphertext<D> {
fn to_mut(&mut self) -> GLWECiphertext<&mut [u8]> {
GLWECiphertext {
data: self.data.to_mut(),
basek: self.basek,
k: self.k,
}
}
}
impl<D: DataMut> ReaderFrom for GLWECiphertext<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GLWECiphertext<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
self.data.write_to(writer)
}
}

View File

@@ -0,0 +1,73 @@
use poulpy_backend::hal::layouts::{Data, DataMut, DataRef, ReaderFrom, VecZnx, WriterTo};
use crate::{dist::Distribution, layouts::Infos};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
#[derive(PartialEq, Eq)]
pub struct GLWEPublicKey<D: Data> {
pub(crate) data: VecZnx<D>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) dist: Distribution,
}
impl GLWEPublicKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rank: usize) -> Self {
Self {
data: VecZnx::alloc(n, rank + 1, k.div_ceil(basek)),
basek,
k,
dist: Distribution::NONE,
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize, rank: usize) -> usize {
VecZnx::alloc_bytes(n, rank + 1, k.div_ceil(basek))
}
}
impl<D: Data> Infos for GLWEPublicKey<D> {
type Inner = VecZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data> GLWEPublicKey<D> {
pub fn rank(&self) -> usize {
self.cols() - 1
}
}
impl<D: DataMut> ReaderFrom for GLWEPublicKey<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
match Distribution::read_from(reader) {
Ok(dist) => self.dist = dist,
Err(e) => return Err(e),
}
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GLWEPublicKey<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
match self.dist.write_to(writer) {
Ok(()) => {}
Err(e) => return Err(e),
}
self.data.write_to(writer)
}
}

View File

@@ -0,0 +1,83 @@
use std::fmt;
use poulpy_backend::hal::layouts::{Data, DataMut, DataRef, VecZnx, VecZnxToMut, VecZnxToRef};
use crate::layouts::{GLWECiphertext, GLWECiphertextToMut, GLWECiphertextToRef, Infos, SetMetaData};
pub struct GLWEPlaintext<D: Data> {
pub data: VecZnx<D>,
pub basek: usize,
pub k: usize,
}
impl<D: DataRef> fmt::Display for GLWEPlaintext<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"GLWEPlaintext: basek={} k={}: {}",
self.basek(),
self.k(),
self.data
)
}
}
impl<D: Data> Infos for GLWEPlaintext<D> {
type Inner = VecZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: DataMut> SetMetaData for GLWEPlaintext<D> {
fn set_k(&mut self, k: usize) {
self.k = k
}
fn set_basek(&mut self, basek: usize) {
self.basek = basek
}
}
impl GLWEPlaintext<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize) -> Self {
Self {
data: VecZnx::alloc(n, 1, k.div_ceil(basek)),
basek,
k,
}
}
pub fn byte_of(n: usize, basek: usize, k: usize) -> usize {
VecZnx::alloc_bytes(n, 1, k.div_ceil(basek))
}
}
impl<D: DataRef> GLWECiphertextToRef for GLWEPlaintext<D> {
fn to_ref(&self) -> GLWECiphertext<&[u8]> {
GLWECiphertext {
data: self.data.to_ref(),
basek: self.basek,
k: self.k,
}
}
}
impl<D: DataMut> GLWECiphertextToMut for GLWEPlaintext<D> {
fn to_mut(&mut self) -> GLWECiphertext<&mut [u8]> {
GLWECiphertext {
data: self.data.to_mut(),
basek: self.basek,
k: self.k,
}
}
}

View File

@@ -0,0 +1,102 @@
use poulpy_backend::hal::{
api::{ZnxInfos, ZnxZero},
layouts::{Data, DataMut, DataRef, ReaderFrom, ScalarZnx, WriterTo},
source::Source,
};
use crate::dist::Distribution;
#[derive(PartialEq, Eq, Clone)]
pub struct GLWESecret<D: Data> {
pub(crate) data: ScalarZnx<D>,
pub(crate) dist: Distribution,
}
impl GLWESecret<Vec<u8>> {
pub fn alloc(n: usize, rank: usize) -> Self {
Self {
data: ScalarZnx::alloc(n, rank),
dist: Distribution::NONE,
}
}
pub fn bytes_of(n: usize, rank: usize) -> usize {
ScalarZnx::alloc_bytes(n, rank)
}
}
impl<D: Data> GLWESecret<D> {
pub fn n(&self) -> usize {
self.data.n()
}
pub fn log_n(&self) -> usize {
self.data.log_n()
}
pub fn rank(&self) -> usize {
self.data.cols()
}
}
impl<D: DataMut> GLWESecret<D> {
pub fn fill_ternary_prob(&mut self, prob: f64, source: &mut Source) {
(0..self.rank()).for_each(|i| {
self.data.fill_ternary_prob(i, prob, source);
});
self.dist = Distribution::TernaryProb(prob);
}
pub fn fill_ternary_hw(&mut self, hw: usize, source: &mut Source) {
(0..self.rank()).for_each(|i| {
self.data.fill_ternary_hw(i, hw, source);
});
self.dist = Distribution::TernaryFixed(hw);
}
pub fn fill_binary_prob(&mut self, prob: f64, source: &mut Source) {
(0..self.rank()).for_each(|i| {
self.data.fill_binary_prob(i, prob, source);
});
self.dist = Distribution::BinaryProb(prob);
}
pub fn fill_binary_hw(&mut self, hw: usize, source: &mut Source) {
(0..self.rank()).for_each(|i| {
self.data.fill_binary_hw(i, hw, source);
});
self.dist = Distribution::BinaryFixed(hw);
}
pub fn fill_binary_block(&mut self, block_size: usize, source: &mut Source) {
(0..self.rank()).for_each(|i| {
self.data.fill_binary_block(i, block_size, source);
});
self.dist = Distribution::BinaryBlock(block_size);
}
pub fn fill_zero(&mut self) {
self.data.zero();
self.dist = Distribution::ZERO;
}
}
impl<D: DataMut> ReaderFrom for GLWESecret<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
match Distribution::read_from(reader) {
Ok(dist) => self.dist = dist,
Err(e) => return Err(e),
}
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GLWESecret<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
match self.dist.write_to(writer) {
Ok(()) => {}
Err(e) => return Err(e),
}
self.data.write_to(writer)
}
}

View File

@@ -0,0 +1,89 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{GGLWESwitchingKey, Infos};
use std::fmt;
/// A special [GLWESwitchingKey] required to for the conversion from [GLWECiphertext] to [LWECiphertext].
#[derive(PartialEq, Eq, Clone)]
pub struct GLWEToLWESwitchingKey<D: Data>(pub(crate) GGLWESwitchingKey<D>);
impl<D: DataRef> fmt::Debug for GLWEToLWESwitchingKey<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GLWEToLWESwitchingKey<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.0.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GLWEToLWESwitchingKey<D> {
fn reset(&mut self) {
self.0.reset();
}
}
impl<D: DataRef> fmt::Display for GLWEToLWESwitchingKey<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(GLWEToLWESwitchingKey) {}", self.0)
}
}
impl<D: Data> Infos for GLWEToLWESwitchingKey<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.0.inner()
}
fn basek(&self) -> usize {
self.0.basek()
}
fn k(&self) -> usize {
self.0.k()
}
}
impl<D: Data> GLWEToLWESwitchingKey<D> {
pub fn digits(&self) -> usize {
self.0.digits()
}
pub fn rank(&self) -> usize {
self.0.rank()
}
pub fn rank_in(&self) -> usize {
self.0.rank_in()
}
pub fn rank_out(&self) -> usize {
self.0.rank_out()
}
}
impl<D: DataMut> ReaderFrom for GLWEToLWESwitchingKey<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.0.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GLWEToLWESwitchingKey<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
self.0.write_to(writer)
}
}
impl GLWEToLWESwitchingKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, rank_in: usize) -> Self {
Self(GGLWESwitchingKey::alloc(n, basek, k, rows, 1, rank_in, 1))
}
}

View File

@@ -0,0 +1,54 @@
use poulpy_backend::hal::api::ZnxInfos;
pub trait Infos {
type Inner: ZnxInfos;
fn inner(&self) -> &Self::Inner;
/// Returns the ring degree of the polynomials.
fn n(&self) -> usize {
self.inner().n()
}
/// Returns the base two logarithm of the ring dimension of the polynomials.
fn log_n(&self) -> usize {
self.inner().log_n()
}
/// Returns the number of rows.
fn rows(&self) -> usize {
self.inner().rows()
}
/// Returns the number of polynomials in each row.
fn cols(&self) -> usize {
self.inner().cols()
}
fn rank(&self) -> usize {
self.cols() - 1
}
/// Returns the number of size per polynomial.
fn size(&self) -> usize {
let size: usize = self.inner().size();
debug_assert!(size >= self.k().div_ceil(self.basek()));
size
}
/// Returns the total number of small polynomials.
fn poly_count(&self) -> usize {
self.rows() * self.cols() * self.size()
}
/// Returns the base 2 logarithm of the ciphertext base.
fn basek(&self) -> usize;
/// Returns the bit precision of the ciphertext.
fn k(&self) -> usize;
}
pub trait SetMetaData {
fn set_basek(&mut self, basek: usize);
fn set_k(&mut self, k: usize);
}

View File

@@ -0,0 +1,153 @@
use std::fmt;
use poulpy_backend::hal::{
api::{FillUniform, Reset, ZnxInfos},
layouts::{Data, DataMut, DataRef, ReaderFrom, VecZnx, VecZnxToMut, VecZnxToRef, WriterTo},
source::Source,
};
#[derive(PartialEq, Eq, Clone)]
pub struct LWECiphertext<D: Data> {
pub(crate) data: VecZnx<D>,
pub(crate) k: usize,
pub(crate) basek: usize,
}
impl<D: DataRef> LWECiphertext<D> {
pub fn data(&self) -> &VecZnx<D> {
&self.data
}
}
impl<D: DataMut> LWECiphertext<D> {
pub fn data_mut(&mut self) -> &VecZnx<D> {
&mut self.data
}
}
impl<D: DataRef> fmt::Debug for LWECiphertext<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataRef> fmt::Display for LWECiphertext<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"LWECiphertext: basek={} k={}: {}",
self.basek(),
self.k(),
self.data
)
}
}
impl<D: DataMut> Reset for LWECiphertext<D> {
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
self.k = 0;
}
}
impl<D: DataMut> FillUniform for LWECiphertext<D>
where
VecZnx<D>: FillUniform,
{
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
}
impl LWECiphertext<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize) -> Self {
Self {
data: VecZnx::alloc(n + 1, 1, k.div_ceil(basek)),
k,
basek,
}
}
}
impl<D: Data> Infos for LWECiphertext<D>
where
VecZnx<D>: ZnxInfos,
{
type Inner = VecZnx<D>;
fn n(&self) -> usize {
&self.inner().n() - 1
}
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<DataSelf: DataMut> SetMetaData for LWECiphertext<DataSelf> {
fn set_k(&mut self, k: usize) {
self.k = k
}
fn set_basek(&mut self, basek: usize) {
self.basek = basek
}
}
pub trait LWECiphertextToRef {
fn to_ref(&self) -> LWECiphertext<&[u8]>;
}
impl<D: DataRef> LWECiphertextToRef for LWECiphertext<D> {
fn to_ref(&self) -> LWECiphertext<&[u8]> {
LWECiphertext {
data: self.data.to_ref(),
basek: self.basek,
k: self.k,
}
}
}
pub trait LWECiphertextToMut {
#[allow(dead_code)]
fn to_mut(&mut self) -> LWECiphertext<&mut [u8]>;
}
impl<D: DataMut> LWECiphertextToMut for LWECiphertext<D> {
fn to_mut(&mut self) -> LWECiphertext<&mut [u8]> {
LWECiphertext {
data: self.data.to_mut(),
basek: self.basek,
k: self.k,
}
}
}
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crate::layouts::{Infos, SetMetaData};
impl<D: DataMut> ReaderFrom for LWECiphertext<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for LWECiphertext<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
self.data.write_to(writer)
}
}

View File

@@ -0,0 +1,88 @@
use std::fmt;
use poulpy_backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{GGLWESwitchingKey, Infos};
#[derive(PartialEq, Eq, Clone)]
pub struct LWESwitchingKey<D: Data>(pub(crate) GGLWESwitchingKey<D>);
impl LWESwitchingKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize) -> Self {
Self(GGLWESwitchingKey::alloc(n, basek, k, rows, 1, 1, 1))
}
}
impl<D: DataRef> fmt::Debug for LWESwitchingKey<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for LWESwitchingKey<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.0.fill_uniform(source);
}
}
impl<D: DataMut> Reset for LWESwitchingKey<D> {
fn reset(&mut self) {
self.0.reset();
}
}
impl<D: DataRef> fmt::Display for LWESwitchingKey<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(LWESwitchingKey) {}", self.0)
}
}
impl<D: Data> Infos for LWESwitchingKey<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.0.inner()
}
fn basek(&self) -> usize {
self.0.basek()
}
fn k(&self) -> usize {
self.0.k()
}
}
impl<D: Data> LWESwitchingKey<D> {
pub fn digits(&self) -> usize {
self.0.digits()
}
pub fn rank(&self) -> usize {
self.0.rank()
}
pub fn rank_in(&self) -> usize {
self.0.rank_in()
}
pub fn rank_out(&self) -> usize {
self.0.rank_out()
}
}
impl<D: DataMut> ReaderFrom for LWESwitchingKey<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.0.read_from(reader)
}
}
impl<D: DataRef> WriterTo for LWESwitchingKey<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
self.0.write_to(writer)
}
}

View File

@@ -0,0 +1,95 @@
use std::fmt;
use poulpy_backend::hal::layouts::{Data, DataMut, DataRef, VecZnx, VecZnxToMut, VecZnxToRef};
use crate::layouts::{Infos, SetMetaData};
pub struct LWEPlaintext<D: Data> {
pub(crate) data: VecZnx<D>,
pub(crate) k: usize,
pub(crate) basek: usize,
}
impl LWEPlaintext<Vec<u8>> {
pub fn alloc(basek: usize, k: usize) -> Self {
Self {
data: VecZnx::alloc(1, 1, k.div_ceil(basek)),
k,
basek,
}
}
}
impl<D: DataRef> fmt::Display for LWEPlaintext<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"LWEPlaintext: basek={} k={}: {}",
self.basek(),
self.k(),
self.data
)
}
}
impl<D: Data> Infos for LWEPlaintext<D> {
type Inner = VecZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: DataMut> SetMetaData for LWEPlaintext<D> {
fn set_k(&mut self, k: usize) {
self.k = k
}
fn set_basek(&mut self, basek: usize) {
self.basek = basek
}
}
pub trait LWEPlaintextToRef {
#[allow(dead_code)]
fn to_ref(&self) -> LWEPlaintext<&[u8]>;
}
impl<D: DataRef> LWEPlaintextToRef for LWEPlaintext<D> {
fn to_ref(&self) -> LWEPlaintext<&[u8]> {
LWEPlaintext {
data: self.data.to_ref(),
basek: self.basek,
k: self.k,
}
}
}
pub trait LWEPlaintextToMut {
#[allow(dead_code)]
fn to_mut(&mut self) -> LWEPlaintext<&mut [u8]>;
}
impl<D: DataMut> LWEPlaintextToMut for LWEPlaintext<D> {
fn to_mut(&mut self) -> LWEPlaintext<&mut [u8]> {
LWEPlaintext {
data: self.data.to_mut(),
basek: self.basek,
k: self.k,
}
}
}
impl<D: DataMut> LWEPlaintext<D> {
pub fn data_mut(&mut self) -> &mut VecZnx<D> {
&mut self.data
}
}

View File

@@ -0,0 +1,81 @@
use poulpy_backend::hal::{
api::{ZnxInfos, ZnxView, ZnxZero},
layouts::{Data, DataMut, DataRef, ScalarZnx},
source::Source,
};
use crate::dist::Distribution;
pub struct LWESecret<D: Data> {
pub(crate) data: ScalarZnx<D>,
pub(crate) dist: Distribution,
}
impl LWESecret<Vec<u8>> {
pub fn alloc(n: usize) -> Self {
Self {
data: ScalarZnx::alloc(n, 1),
dist: Distribution::NONE,
}
}
}
impl<D: DataRef> LWESecret<D> {
pub fn raw(&self) -> &[i64] {
self.data.at(0, 0)
}
pub fn dist(&self) -> Distribution {
self.dist
}
pub fn data(&self) -> &ScalarZnx<D> {
&self.data
}
}
impl<D: Data> LWESecret<D> {
pub fn n(&self) -> usize {
self.data.n()
}
pub fn log_n(&self) -> usize {
self.data.log_n()
}
pub fn rank(&self) -> usize {
self.data.cols()
}
}
impl<D: DataMut> LWESecret<D> {
pub fn fill_ternary_prob(&mut self, prob: f64, source: &mut Source) {
self.data.fill_ternary_prob(0, prob, source);
self.dist = Distribution::TernaryProb(prob);
}
pub fn fill_ternary_hw(&mut self, hw: usize, source: &mut Source) {
self.data.fill_ternary_hw(0, hw, source);
self.dist = Distribution::TernaryFixed(hw);
}
pub fn fill_binary_prob(&mut self, prob: f64, source: &mut Source) {
self.data.fill_binary_prob(0, prob, source);
self.dist = Distribution::BinaryProb(prob);
}
pub fn fill_binary_hw(&mut self, hw: usize, source: &mut Source) {
self.data.fill_binary_hw(0, hw, source);
self.dist = Distribution::BinaryFixed(hw);
}
pub fn fill_binary_block(&mut self, block_size: usize, source: &mut Source) {
self.data.fill_binary_block(0, block_size, source);
self.dist = Distribution::BinaryBlock(block_size);
}
pub fn fill_zero(&mut self) {
self.data.zero();
self.dist = Distribution::ZERO;
}
}

View File

@@ -0,0 +1,88 @@
use std::fmt;
use poulpy_backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
source::Source,
};
use crate::layouts::{GGLWESwitchingKey, Infos};
#[derive(PartialEq, Eq, Clone)]
pub struct LWEToGLWESwitchingKey<D: Data>(pub(crate) GGLWESwitchingKey<D>);
impl<D: DataRef> fmt::Debug for LWEToGLWESwitchingKey<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for LWEToGLWESwitchingKey<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.0.fill_uniform(source);
}
}
impl<D: DataMut> Reset for LWEToGLWESwitchingKey<D> {
fn reset(&mut self) {
self.0.reset();
}
}
impl<D: DataRef> fmt::Display for LWEToGLWESwitchingKey<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(LWEToGLWESwitchingKey) {}", self.0)
}
}
impl<D: Data> Infos for LWEToGLWESwitchingKey<D> {
type Inner = MatZnx<D>;
fn inner(&self) -> &Self::Inner {
self.0.inner()
}
fn basek(&self) -> usize {
self.0.basek()
}
fn k(&self) -> usize {
self.0.k()
}
}
impl<D: Data> LWEToGLWESwitchingKey<D> {
pub fn digits(&self) -> usize {
self.0.digits()
}
pub fn rank(&self) -> usize {
self.0.rank()
}
pub fn rank_in(&self) -> usize {
self.0.rank_in()
}
pub fn rank_out(&self) -> usize {
self.0.rank_out()
}
}
impl<D: DataMut> ReaderFrom for LWEToGLWESwitchingKey<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.0.read_from(reader)
}
}
impl<D: DataRef> WriterTo for LWEToGLWESwitchingKey<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
self.0.write_to(writer)
}
}
impl LWEToGLWESwitchingKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, rank_out: usize) -> Self {
Self(GGLWESwitchingKey::alloc(n, basek, k, rows, 1, 1, rank_out))
}
}

View File

@@ -0,0 +1,36 @@
mod gglwe_atk;
mod gglwe_ct;
mod gglwe_ksk;
mod gglwe_tsk;
mod ggsw_ct;
mod glwe_ct;
mod glwe_pk;
mod glwe_pt;
mod glwe_sk;
mod glwe_to_lwe_ksk;
mod infos;
mod lwe_ct;
mod lwe_ksk;
mod lwe_pt;
mod lwe_sk;
mod lwe_to_glwe_ksk;
pub mod compressed;
pub mod prepared;
pub use gglwe_atk::*;
pub use gglwe_ct::*;
pub use gglwe_ksk::*;
pub use gglwe_tsk::*;
pub use ggsw_ct::*;
pub use glwe_ct::*;
pub use glwe_pk::*;
pub use glwe_pt::*;
pub use glwe_sk::*;
pub use glwe_to_lwe_ksk::*;
pub use infos::*;
pub use lwe_ct::*;
pub use lwe_ksk::*;
pub use lwe_pt::*;
pub use lwe_sk::*;
pub use lwe_to_glwe_ksk::*;

View File

@@ -0,0 +1,101 @@
use poulpy_backend::hal::{
api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPrepare},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat},
};
use crate::layouts::{
GGLWEAutomorphismKey, Infos,
prepared::{GGLWESwitchingKeyPrepared, Prepare, PrepareAlloc},
};
#[derive(PartialEq, Eq)]
pub struct GGLWEAutomorphismKeyPrepared<D: Data, B: Backend> {
pub(crate) key: GGLWESwitchingKeyPrepared<D, B>,
pub(crate) p: i64,
}
impl<B: Backend> GGLWEAutomorphismKeyPrepared<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self
where
Module<B>: VmpPMatAlloc<B>,
{
GGLWEAutomorphismKeyPrepared::<Vec<u8>, B> {
key: GGLWESwitchingKeyPrepared::alloc(module, n, basek, k, rows, digits, rank, rank),
p: 0,
}
}
pub fn bytes_of(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize
where
Module<B>: VmpPMatAllocBytes,
{
GGLWESwitchingKeyPrepared::bytes_of(module, n, basek, k, rows, digits, rank, rank)
}
}
impl<D: Data, B: Backend> Infos for GGLWEAutomorphismKeyPrepared<D, B> {
type Inner = VmpPMat<D, B>;
fn inner(&self) -> &Self::Inner {
self.key.inner()
}
fn basek(&self) -> usize {
self.key.basek()
}
fn k(&self) -> usize {
self.key.k()
}
}
impl<D: Data, B: Backend> GGLWEAutomorphismKeyPrepared<D, B> {
pub fn p(&self) -> i64 {
self.p
}
pub fn digits(&self) -> usize {
self.key.digits()
}
pub fn rank(&self) -> usize {
self.key.rank()
}
pub fn rank_in(&self) -> usize {
self.key.rank_in()
}
pub fn rank_out(&self) -> usize {
self.key.rank_out()
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Prepare<B, GGLWEAutomorphismKey<DR>> for GGLWEAutomorphismKeyPrepared<D, B>
where
Module<B>: VmpPrepare<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &GGLWEAutomorphismKey<DR>, scratch: &mut Scratch<B>) {
self.key.prepare(module, &other.key, scratch);
self.p = other.p;
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, GGLWEAutomorphismKeyPrepared<Vec<u8>, B>> for GGLWEAutomorphismKey<D>
where
Module<B>: VmpPMatAlloc<B> + VmpPrepare<B>,
{
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> GGLWEAutomorphismKeyPrepared<Vec<u8>, B> {
let mut atk_prepared: GGLWEAutomorphismKeyPrepared<Vec<u8>, B> = GGLWEAutomorphismKeyPrepared::alloc(
module,
self.n(),
self.basek(),
self.k(),
self.rows(),
self.digits(),
self.rank(),
);
atk_prepared.prepare(module, self, scratch);
atk_prepared
}
}

View File

@@ -0,0 +1,156 @@
use poulpy_backend::hal::{
api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPrepare},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat},
};
use crate::layouts::{
GGLWECiphertext, Infos,
prepared::{Prepare, PrepareAlloc},
};
#[derive(PartialEq, Eq)]
pub struct GGLWECiphertextPrepared<D: Data, B: Backend> {
pub(crate) data: VmpPMat<D, B>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) digits: usize,
}
impl<B: Backend> GGLWECiphertextPrepared<Vec<u8>, B> {
#[allow(clippy::too_many_arguments)]
pub fn alloc(
module: &Module<B>,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> Self
where
Module<B>: VmpPMatAlloc<B>,
{
let size: usize = k.div_ceil(basek);
debug_assert!(
size > digits,
"invalid gglwe: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid gglwe: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
Self {
data: module.vmp_pmat_alloc(n, rows, rank_in, rank_out + 1, size),
basek,
k,
digits,
}
}
#[allow(clippy::too_many_arguments)]
pub fn bytes_of(
module: &Module<B>,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> usize
where
Module<B>: VmpPMatAllocBytes,
{
let size: usize = k.div_ceil(basek);
debug_assert!(
size > digits,
"invalid gglwe: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid gglwe: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
module.vmp_pmat_alloc_bytes(n, rows, rank_in, rank_out + 1, rows)
}
}
impl<D: Data, B: Backend> Infos for GGLWECiphertextPrepared<D, B> {
type Inner = VmpPMat<D, B>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data, B: Backend> GGLWECiphertextPrepared<D, B> {
pub fn rank(&self) -> usize {
self.data.cols_out() - 1
}
pub fn digits(&self) -> usize {
self.digits
}
pub fn rank_in(&self) -> usize {
self.data.cols_in()
}
pub fn rank_out(&self) -> usize {
self.data.cols_out() - 1
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Prepare<B, GGLWECiphertext<DR>> for GGLWECiphertextPrepared<D, B>
where
Module<B>: VmpPrepare<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &GGLWECiphertext<DR>, scratch: &mut Scratch<B>) {
module.vmp_prepare(&mut self.data, &other.data, scratch);
self.basek = other.basek;
self.k = other.k;
self.digits = other.digits;
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, GGLWECiphertextPrepared<Vec<u8>, B>> for GGLWECiphertext<D>
where
Module<B>: VmpPMatAlloc<B> + VmpPrepare<B>,
{
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> GGLWECiphertextPrepared<Vec<u8>, B> {
let mut atk_prepared: GGLWECiphertextPrepared<Vec<u8>, B> = GGLWECiphertextPrepared::alloc(
module,
self.n(),
self.basek(),
self.k(),
self.rows(),
self.digits(),
self.rank_in(),
self.rank_out(),
);
atk_prepared.prepare(module, self, scratch);
atk_prepared
}
}

View File

@@ -0,0 +1,129 @@
use poulpy_backend::hal::{
api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPrepare},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat},
};
use crate::layouts::{
GGLWESwitchingKey, Infos,
prepared::{GGLWECiphertextPrepared, Prepare, PrepareAlloc},
};
#[derive(PartialEq, Eq)]
pub struct GGLWESwitchingKeyPrepared<D: Data, B: Backend> {
pub(crate) key: GGLWECiphertextPrepared<D, B>,
pub(crate) sk_in_n: usize, // Degree of sk_in
pub(crate) sk_out_n: usize, // Degree of sk_out
}
impl<B: Backend> GGLWESwitchingKeyPrepared<Vec<u8>, B> {
#[allow(clippy::too_many_arguments)]
pub fn alloc(
module: &Module<B>,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> Self
where
Module<B>: VmpPMatAlloc<B>,
{
GGLWESwitchingKeyPrepared::<Vec<u8>, B> {
key: GGLWECiphertextPrepared::alloc(module, n, basek, k, rows, digits, rank_in, rank_out),
sk_in_n: 0,
sk_out_n: 0,
}
}
#[allow(clippy::too_many_arguments)]
pub fn bytes_of(
module: &Module<B>,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> usize
where
Module<B>: VmpPMatAllocBytes,
{
GGLWECiphertextPrepared::bytes_of(module, n, basek, k, rows, digits, rank_in, rank_out)
}
}
impl<D: Data, B: Backend> Infos for GGLWESwitchingKeyPrepared<D, B> {
type Inner = VmpPMat<D, B>;
fn inner(&self) -> &Self::Inner {
self.key.inner()
}
fn basek(&self) -> usize {
self.key.basek()
}
fn k(&self) -> usize {
self.key.k()
}
}
impl<D: Data, B: Backend> GGLWESwitchingKeyPrepared<D, B> {
pub fn rank(&self) -> usize {
self.key.data.cols_out() - 1
}
pub fn rank_in(&self) -> usize {
self.key.data.cols_in()
}
pub fn rank_out(&self) -> usize {
self.key.data.cols_out() - 1
}
pub fn digits(&self) -> usize {
self.key.digits()
}
pub fn sk_degree_in(&self) -> usize {
self.sk_in_n
}
pub fn sk_degree_out(&self) -> usize {
self.sk_out_n
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Prepare<B, GGLWESwitchingKey<DR>> for GGLWESwitchingKeyPrepared<D, B>
where
Module<B>: VmpPrepare<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &GGLWESwitchingKey<DR>, scratch: &mut Scratch<B>) {
self.key.prepare(module, &other.key, scratch);
self.sk_in_n = other.sk_in_n;
self.sk_out_n = other.sk_out_n;
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, GGLWESwitchingKeyPrepared<Vec<u8>, B>> for GGLWESwitchingKey<D>
where
Module<B>: VmpPMatAlloc<B> + VmpPrepare<B>,
{
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> GGLWESwitchingKeyPrepared<Vec<u8>, B> {
let mut atk_prepared: GGLWESwitchingKeyPrepared<Vec<u8>, B> = GGLWESwitchingKeyPrepared::alloc(
module,
self.n(),
self.basek(),
self.k(),
self.rows(),
self.digits(),
self.rank_in(),
self.rank_out(),
);
atk_prepared.prepare(module, self, scratch);
atk_prepared
}
}

View File

@@ -0,0 +1,131 @@
use poulpy_backend::hal::{
api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPrepare},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat},
};
use crate::layouts::{
GGLWETensorKey, Infos,
prepared::{GGLWESwitchingKeyPrepared, Prepare, PrepareAlloc},
};
#[derive(PartialEq, Eq)]
pub struct GGLWETensorKeyPrepared<D: Data, B: Backend> {
pub(crate) keys: Vec<GGLWESwitchingKeyPrepared<D, B>>,
}
impl<B: Backend> GGLWETensorKeyPrepared<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self
where
Module<B>: VmpPMatAlloc<B>,
{
let mut keys: Vec<GGLWESwitchingKeyPrepared<Vec<u8>, B>> = Vec::new();
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
(0..pairs).for_each(|_| {
keys.push(GGLWESwitchingKeyPrepared::alloc(
module, n, basek, k, rows, digits, 1, rank,
));
});
Self { keys }
}
pub fn bytes_of(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize
where
Module<B>: VmpPMatAllocBytes,
{
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
pairs * GGLWESwitchingKeyPrepared::bytes_of(module, n, basek, k, rows, digits, 1, rank)
}
}
impl<D: Data, B: Backend> Infos for GGLWETensorKeyPrepared<D, B> {
type Inner = VmpPMat<D, B>;
fn inner(&self) -> &Self::Inner {
self.keys[0].inner()
}
fn basek(&self) -> usize {
self.keys[0].basek()
}
fn k(&self) -> usize {
self.keys[0].k()
}
}
impl<D: Data, B: Backend> GGLWETensorKeyPrepared<D, B> {
pub fn rank(&self) -> usize {
self.keys[0].rank()
}
pub fn rank_in(&self) -> usize {
self.keys[0].rank_in()
}
pub fn rank_out(&self) -> usize {
self.keys[0].rank_out()
}
pub fn digits(&self) -> usize {
self.keys[0].digits()
}
}
impl<D: DataMut, B: Backend> GGLWETensorKeyPrepared<D, B> {
// Returns a mutable reference to GLWESwitchingKey_{s}(s[i] * s[j])
pub fn at_mut(&mut self, mut i: usize, mut j: usize) -> &mut GGLWESwitchingKeyPrepared<D, B> {
if i > j {
std::mem::swap(&mut i, &mut j);
};
let rank: usize = self.rank();
&mut self.keys[i * rank + j - (i * (i + 1) / 2)]
}
}
impl<D: DataRef, B: Backend> GGLWETensorKeyPrepared<D, B> {
// Returns a reference to GLWESwitchingKey_{s}(s[i] * s[j])
pub fn at(&self, mut i: usize, mut j: usize) -> &GGLWESwitchingKeyPrepared<D, B> {
if i > j {
std::mem::swap(&mut i, &mut j);
};
let rank: usize = self.rank();
&self.keys[i * rank + j - (i * (i + 1) / 2)]
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Prepare<B, GGLWETensorKey<DR>> for GGLWETensorKeyPrepared<D, B>
where
Module<B>: VmpPrepare<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &GGLWETensorKey<DR>, scratch: &mut Scratch<B>) {
#[cfg(debug_assertions)]
{
assert_eq!(self.keys.len(), other.keys.len());
}
self.keys
.iter_mut()
.zip(other.keys.iter())
.for_each(|(a, b)| {
a.prepare(module, b, scratch);
});
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, GGLWETensorKeyPrepared<Vec<u8>, B>> for GGLWETensorKey<D>
where
Module<B>: VmpPMatAlloc<B> + VmpPrepare<B>,
{
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> GGLWETensorKeyPrepared<Vec<u8>, B> {
let mut tsk_prepared: GGLWETensorKeyPrepared<Vec<u8>, B> = GGLWETensorKeyPrepared::alloc(
module,
self.n(),
self.basek(),
self.k(),
self.rows(),
self.digits(),
self.rank(),
);
tsk_prepared.prepare(module, self, scratch);
tsk_prepared
}
}

View File

@@ -0,0 +1,135 @@
use poulpy_backend::hal::{
api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPrepare},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat},
};
use crate::layouts::{
GGSWCiphertext, Infos,
prepared::{Prepare, PrepareAlloc},
};
#[derive(PartialEq, Eq)]
pub struct GGSWCiphertextPrepared<D: Data, B: Backend> {
pub(crate) data: VmpPMat<D, B>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) digits: usize,
}
impl<B: Backend> GGSWCiphertextPrepared<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self
where
Module<B>: VmpPMatAlloc<B>,
{
let size: usize = k.div_ceil(basek);
debug_assert!(digits > 0, "invalid ggsw: `digits` == 0");
debug_assert!(
size > digits,
"invalid ggsw: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid ggsw: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
Self {
data: module.vmp_pmat_alloc(n, rows, rank + 1, rank + 1, k.div_ceil(basek)),
basek,
k,
digits,
}
}
pub fn bytes_of(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> usize
where
Module<B>: VmpPMatAllocBytes,
{
let size: usize = k.div_ceil(basek);
debug_assert!(
size > digits,
"invalid ggsw: ceil(k/basek): {} <= digits: {}",
size,
digits
);
assert!(
rows * digits <= size,
"invalid ggsw: rows: {} * digits:{} > ceil(k/basek): {}",
rows,
digits,
size
);
module.vmp_pmat_alloc_bytes(n, rows, rank + 1, rank + 1, size)
}
}
impl<D: Data, B: Backend> Infos for GGSWCiphertextPrepared<D, B> {
type Inner = VmpPMat<D, B>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data, B: Backend> GGSWCiphertextPrepared<D, B> {
pub fn rank(&self) -> usize {
self.data.cols_out() - 1
}
pub fn digits(&self) -> usize {
self.digits
}
}
impl<D: DataRef, B: Backend> GGSWCiphertextPrepared<D, B> {
pub fn data(&self) -> &VmpPMat<D, B> {
&self.data
}
}
impl<D: DataMut, DR: DataRef, B: Backend> Prepare<B, GGSWCiphertext<DR>> for GGSWCiphertextPrepared<D, B>
where
Module<B>: VmpPrepare<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &GGSWCiphertext<DR>, scratch: &mut Scratch<B>) {
module.vmp_prepare(&mut self.data, &other.data, scratch);
self.k = other.k;
self.basek = other.basek;
self.digits = other.digits;
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, GGSWCiphertextPrepared<Vec<u8>, B>> for GGSWCiphertext<D>
where
Module<B>: VmpPMatAlloc<B> + VmpPrepare<B>,
{
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> GGSWCiphertextPrepared<Vec<u8>, B> {
let mut ggsw_prepared: GGSWCiphertextPrepared<Vec<u8>, B> = GGSWCiphertextPrepared::alloc(
module,
self.n(),
self.basek(),
self.k(),
self.rows(),
self.digits(),
self.rank(),
);
ggsw_prepared.prepare(module, self, scratch);
ggsw_prepared
}
}

View File

@@ -0,0 +1,177 @@
use poulpy_backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, VecZnx, WriterTo},
};
use crate::layouts::{GLWECiphertext, Infos, compressed::Decompress};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GLWECiphertextCompressed<D: Data> {
pub(crate) data: VecZnx<D>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) rank: usize,
pub(crate) seed: [u8; 32],
}
impl<D: DataRef> fmt::Debug for GLWECiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataRef> fmt::Display for GLWECiphertextCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"GLWECiphertextCompressed: basek={} k={} rank={} seed={:?}: {}",
self.basek(),
self.k(),
self.rank,
self.seed,
self.data
)
}
}
impl<D: DataMut> Reset for GLWECiphertextCompressed<D> {
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
self.k = 0;
self.rank = 0;
self.seed = [0u8; 32];
}
}
impl<D: DataMut> FillUniform for GLWECiphertextCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
}
impl<D: Data> Infos for GLWECiphertextCompressed<D> {
type Inner = VecZnx<D>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data> GLWECiphertextCompressed<D> {
pub fn rank(&self) -> usize {
self.rank
}
}
impl GLWECiphertextCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rank: usize) -> Self {
Self {
data: VecZnx::alloc(n, 1, k.div_ceil(basek)),
basek,
k,
rank,
seed: [0u8; 32],
}
}
pub fn bytes_of(n: usize, basek: usize, k: usize) -> usize {
GLWECiphertext::bytes_of(n, basek, k, 1)
}
}
impl<D: DataMut> ReaderFrom for GLWECiphertextCompressed<D> {
fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
self.k = reader.read_u64::<LittleEndian>()? as usize;
self.basek = reader.read_u64::<LittleEndian>()? as usize;
self.rank = reader.read_u64::<LittleEndian>()? as usize;
reader.read_exact(&mut self.seed)?;
self.data.read_from(reader)
}
}
impl<D: DataRef> WriterTo for GLWECiphertextCompressed<D> {
fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_u64::<LittleEndian>(self.k as u64)?;
writer.write_u64::<LittleEndian>(self.basek as u64)?;
writer.write_u64::<LittleEndian>(self.rank as u64)?;
writer.write_all(&self.seed)?;
self.data.write_to(writer)
}
}
impl<D: DataMut, B: Backend, DR: DataRef> Decompress<B, GLWECiphertextCompressed<DR>> for GLWECiphertext<D> {
fn decompress(&mut self, module: &Module<B>, other: &GLWECiphertextCompressed<DR>)
where
Module<B>: VecZnxCopy + VecZnxFillUniform,
{
#[cfg(debug_assertions)]
{
use poulpy_backend::hal::api::ZnxInfos;
assert_eq!(
self.n(),
other.data.n(),
"invalid receiver: self.n()={} != other.n()={}",
self.n(),
other.data.n()
);
assert_eq!(
self.size(),
other.size(),
"invalid receiver: self.size()={} != other.size()={}",
self.size(),
other.size()
);
assert_eq!(
self.rank(),
other.rank(),
"invalid receiver: self.rank()={} != other.rank()={}",
self.rank(),
other.rank()
);
}
let mut source: Source = Source::new(other.seed);
self.decompress_internal(module, other, &mut source);
}
}
impl<D: DataMut> GLWECiphertext<D> {
pub(crate) fn decompress_internal<DataOther, B: Backend>(
&mut self,
module: &Module<B>,
other: &GLWECiphertextCompressed<DataOther>,
source: &mut Source,
) where
DataOther: DataRef,
Module<B>: VecZnxCopy + VecZnxFillUniform,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.rank(), other.rank())
}
let k: usize = other.k;
let basek: usize = other.basek;
let cols: usize = other.rank() + 1;
module.vec_znx_copy(&mut self.data, 0, &other.data, 0);
(1..cols).for_each(|i| {
module.vec_znx_fill_uniform(basek, &mut self.data, i, k, source);
});
self.basek = basek;
self.k = k;
}
}

View File

@@ -0,0 +1,95 @@
use poulpy_backend::hal::{
api::{VecZnxDftAlloc, VecZnxDftAllocBytes, VecZnxDftFromVecZnx},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VecZnxDft},
};
use crate::{
dist::Distribution,
layouts::{
GLWEPublicKey, Infos,
prepared::{Prepare, PrepareAlloc},
},
};
#[derive(PartialEq, Eq)]
pub struct GLWEPublicKeyPrepared<D: Data, B: Backend> {
pub(crate) data: VecZnxDft<D, B>,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) dist: Distribution,
}
impl<D: Data, B: Backend> Infos for GLWEPublicKeyPrepared<D, B> {
type Inner = VecZnxDft<D, B>;
fn inner(&self) -> &Self::Inner {
&self.data
}
fn basek(&self) -> usize {
self.basek
}
fn k(&self) -> usize {
self.k
}
}
impl<D: Data, B: Backend> GLWEPublicKeyPrepared<D, B> {
pub fn rank(&self) -> usize {
self.cols() - 1
}
}
impl<B: Backend> GLWEPublicKeyPrepared<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> Self
where
Module<B>: VecZnxDftAlloc<B>,
{
Self {
data: module.vec_znx_dft_alloc(n, rank + 1, k.div_ceil(basek)),
basek,
k,
dist: Distribution::NONE,
}
}
pub fn bytes_of(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>: VecZnxDftAllocBytes,
{
module.vec_znx_dft_alloc_bytes(n, rank + 1, k.div_ceil(basek))
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, GLWEPublicKeyPrepared<Vec<u8>, B>> for GLWEPublicKey<D>
where
Module<B>: VecZnxDftAlloc<B> + VecZnxDftFromVecZnx<B>,
{
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> GLWEPublicKeyPrepared<Vec<u8>, B> {
let mut pk_prepared: GLWEPublicKeyPrepared<Vec<u8>, B> =
GLWEPublicKeyPrepared::alloc(module, self.n(), self.basek(), self.k(), self.rank());
pk_prepared.prepare(module, self, scratch);
pk_prepared
}
}
impl<DM: DataMut, DR: DataRef, B: Backend> Prepare<B, GLWEPublicKey<DR>> for GLWEPublicKeyPrepared<DM, B>
where
Module<B>: VecZnxDftFromVecZnx<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &GLWEPublicKey<DR>, _scratch: &mut Scratch<B>) {
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), other.n());
assert_eq!(self.size(), other.size());
}
(0..self.cols()).for_each(|i| {
module.vec_znx_dft_from_vec_znx(1, 0, &mut self.data, i, &other.data, i);
});
self.k = other.k;
self.basek = other.basek;
self.dist = other.dist;
}
}

View File

@@ -0,0 +1,77 @@
use poulpy_backend::hal::{
api::{SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, ZnxInfos},
layouts::{Backend, Data, DataMut, DataRef, Module, SvpPPol},
};
use crate::{
dist::Distribution,
layouts::{
GLWESecret,
prepared::{Prepare, PrepareAlloc},
},
};
pub struct GLWESecretPrepared<D: Data, B: Backend> {
pub(crate) data: SvpPPol<D, B>,
pub(crate) dist: Distribution,
}
impl<B: Backend> GLWESecretPrepared<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n: usize, rank: usize) -> Self
where
Module<B>: SvpPPolAlloc<B>,
{
Self {
data: module.svp_ppol_alloc(n, rank),
dist: Distribution::NONE,
}
}
pub fn bytes_of(module: &Module<B>, n: usize, rank: usize) -> usize
where
Module<B>: SvpPPolAllocBytes,
{
module.svp_ppol_alloc_bytes(n, rank)
}
}
impl<D: Data, B: Backend> GLWESecretPrepared<D, B> {
pub fn n(&self) -> usize {
self.data.n()
}
pub fn log_n(&self) -> usize {
self.data.log_n()
}
pub fn rank(&self) -> usize {
self.data.cols()
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, GLWESecretPrepared<Vec<u8>, B>> for GLWESecret<D>
where
Module<B>: SvpPrepare<B> + SvpPPolAlloc<B>,
{
fn prepare_alloc(
&self,
module: &Module<B>,
scratch: &mut poulpy_backend::hal::layouts::Scratch<B>,
) -> GLWESecretPrepared<Vec<u8>, B> {
let mut sk_dft: GLWESecretPrepared<Vec<u8>, B> = GLWESecretPrepared::alloc(module, self.n(), self.rank());
sk_dft.prepare(module, self, scratch);
sk_dft
}
}
impl<DM: DataMut, DR: DataRef, B: Backend> Prepare<B, GLWESecret<DR>> for GLWESecretPrepared<DM, B>
where
Module<B>: SvpPrepare<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &GLWESecret<DR>, _scratch: &mut poulpy_backend::hal::layouts::Scratch<B>) {
(0..self.rank()).for_each(|i| {
module.svp_prepare(&mut self.data, i, &other.data, i);
});
self.dist = other.dist
}
}

View File

@@ -0,0 +1,91 @@
use poulpy_backend::hal::{
api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPrepare},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat},
};
use crate::layouts::{
GLWEToLWESwitchingKey, Infos,
prepared::{GGLWESwitchingKeyPrepared, Prepare, PrepareAlloc},
};
#[derive(PartialEq, Eq)]
pub struct GLWEToLWESwitchingKeyPrepared<D: Data, B: Backend>(pub(crate) GGLWESwitchingKeyPrepared<D, B>);
impl<D: Data, B: Backend> Infos for GLWEToLWESwitchingKeyPrepared<D, B> {
type Inner = VmpPMat<D, B>;
fn inner(&self) -> &Self::Inner {
self.0.inner()
}
fn basek(&self) -> usize {
self.0.basek()
}
fn k(&self) -> usize {
self.0.k()
}
}
impl<D: Data, B: Backend> GLWEToLWESwitchingKeyPrepared<D, B> {
pub fn digits(&self) -> usize {
self.0.digits()
}
pub fn rank(&self) -> usize {
self.0.rank()
}
pub fn rank_in(&self) -> usize {
self.0.rank_in()
}
pub fn rank_out(&self) -> usize {
self.0.rank_out()
}
}
impl<B: Backend> GLWEToLWESwitchingKeyPrepared<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, rank_in: usize) -> Self
where
Module<B>: VmpPMatAlloc<B>,
{
Self(GGLWESwitchingKeyPrepared::alloc(
module, n, basek, k, rows, 1, rank_in, 1,
))
}
pub fn bytes_of(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize) -> usize
where
Module<B>: VmpPMatAllocBytes,
{
GGLWESwitchingKeyPrepared::<Vec<u8>, B>::bytes_of(module, n, basek, k, rows, digits, rank_in, 1)
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, GLWEToLWESwitchingKeyPrepared<Vec<u8>, B>> for GLWEToLWESwitchingKey<D>
where
Module<B>: VmpPrepare<B> + VmpPMatAlloc<B>,
{
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> GLWEToLWESwitchingKeyPrepared<Vec<u8>, B> {
let mut ksk_prepared: GLWEToLWESwitchingKeyPrepared<Vec<u8>, B> = GLWEToLWESwitchingKeyPrepared::alloc(
module,
self.0.n(),
self.0.basek(),
self.0.k(),
self.0.rows(),
self.0.rank_in(),
);
ksk_prepared.prepare(module, self, scratch);
ksk_prepared
}
}
impl<DM: DataMut, DR: DataRef, B: Backend> Prepare<B, GLWEToLWESwitchingKey<DR>> for GLWEToLWESwitchingKeyPrepared<DM, B>
where
Module<B>: VmpPrepare<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &GLWEToLWESwitchingKey<DR>, scratch: &mut Scratch<B>) {
self.0.prepare(module, &other.0, scratch);
}
}

View File

@@ -0,0 +1,90 @@
use poulpy_backend::hal::{
api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPrepare},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat},
};
use crate::layouts::{
Infos, LWESwitchingKey,
prepared::{GGLWESwitchingKeyPrepared, Prepare, PrepareAlloc},
};
#[derive(PartialEq, Eq)]
pub struct LWESwitchingKeyPrepared<D: Data, B: Backend>(pub(crate) GGLWESwitchingKeyPrepared<D, B>);
impl<D: Data, B: Backend> Infos for LWESwitchingKeyPrepared<D, B> {
type Inner = VmpPMat<D, B>;
fn inner(&self) -> &Self::Inner {
self.0.inner()
}
fn basek(&self) -> usize {
self.0.basek()
}
fn k(&self) -> usize {
self.0.k()
}
}
impl<D: Data, B: Backend> LWESwitchingKeyPrepared<D, B> {
pub fn digits(&self) -> usize {
self.0.digits()
}
pub fn rank(&self) -> usize {
self.0.rank()
}
pub fn rank_in(&self) -> usize {
self.0.rank_in()
}
pub fn rank_out(&self) -> usize {
self.0.rank_out()
}
}
impl<B: Backend> LWESwitchingKeyPrepared<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize) -> Self
where
Module<B>: VmpPMatAlloc<B>,
{
Self(GGLWESwitchingKeyPrepared::alloc(
module, n, basek, k, rows, 1, 1, 1,
))
}
pub fn bytes_of(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, digits: usize) -> usize
where
Module<B>: VmpPMatAllocBytes,
{
GGLWESwitchingKeyPrepared::<Vec<u8>, B>::bytes_of(module, n, basek, k, rows, digits, 1, 1)
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, LWESwitchingKeyPrepared<Vec<u8>, B>> for LWESwitchingKey<D>
where
Module<B>: VmpPrepare<B> + VmpPMatAlloc<B>,
{
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> LWESwitchingKeyPrepared<Vec<u8>, B> {
let mut ksk_prepared: LWESwitchingKeyPrepared<Vec<u8>, B> = LWESwitchingKeyPrepared::alloc(
module,
self.0.n(),
self.0.basek(),
self.0.k(),
self.0.rows(),
);
ksk_prepared.prepare(module, self, scratch);
ksk_prepared
}
}
impl<DM: DataMut, DR: DataRef, B: Backend> Prepare<B, LWESwitchingKey<DR>> for LWESwitchingKeyPrepared<DM, B>
where
Module<B>: VmpPrepare<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &LWESwitchingKey<DR>, scratch: &mut Scratch<B>) {
self.0.prepare(module, &other.0, scratch);
}
}

View File

@@ -0,0 +1,92 @@
use poulpy_backend::hal::{
api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPrepare},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat},
};
use crate::layouts::{
Infos, LWEToGLWESwitchingKey,
prepared::{GGLWESwitchingKeyPrepared, Prepare, PrepareAlloc},
};
/// A special [GLWESwitchingKey] required to for the conversion from [LWECiphertext] to [GLWECiphertext].
#[derive(PartialEq, Eq)]
pub struct LWEToGLWESwitchingKeyPrepared<D: Data, B: Backend>(pub(crate) GGLWESwitchingKeyPrepared<D, B>);
impl<D: Data, B: Backend> Infos for LWEToGLWESwitchingKeyPrepared<D, B> {
type Inner = VmpPMat<D, B>;
fn inner(&self) -> &Self::Inner {
self.0.inner()
}
fn basek(&self) -> usize {
self.0.basek()
}
fn k(&self) -> usize {
self.0.k()
}
}
impl<D: Data, B: Backend> LWEToGLWESwitchingKeyPrepared<D, B> {
pub fn digits(&self) -> usize {
self.0.digits()
}
pub fn rank(&self) -> usize {
self.0.rank()
}
pub fn rank_in(&self) -> usize {
self.0.rank_in()
}
pub fn rank_out(&self) -> usize {
self.0.rank_out()
}
}
impl<B: Backend> LWEToGLWESwitchingKeyPrepared<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, rank_out: usize) -> Self
where
Module<B>: VmpPMatAlloc<B>,
{
Self(GGLWESwitchingKeyPrepared::alloc(
module, n, basek, k, rows, 1, 1, rank_out,
))
}
pub fn bytes_of(module: &Module<B>, n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_out: usize) -> usize
where
Module<B>: VmpPMatAllocBytes,
{
GGLWESwitchingKeyPrepared::<Vec<u8>, B>::bytes_of(module, n, basek, k, rows, digits, 1, rank_out)
}
}
impl<D: DataRef, B: Backend> PrepareAlloc<B, LWEToGLWESwitchingKeyPrepared<Vec<u8>, B>> for LWEToGLWESwitchingKey<D>
where
Module<B>: VmpPrepare<B> + VmpPMatAlloc<B>,
{
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> LWEToGLWESwitchingKeyPrepared<Vec<u8>, B> {
let mut ksk_prepared: LWEToGLWESwitchingKeyPrepared<Vec<u8>, B> = LWEToGLWESwitchingKeyPrepared::alloc(
module,
self.0.n(),
self.0.basek(),
self.0.k(),
self.0.rows(),
self.0.rank_out(),
);
ksk_prepared.prepare(module, self, scratch);
ksk_prepared
}
}
impl<DM: DataMut, DR: DataRef, B: Backend> Prepare<B, LWEToGLWESwitchingKey<DR>> for LWEToGLWESwitchingKeyPrepared<DM, B>
where
Module<B>: VmpPrepare<B>,
{
fn prepare(&mut self, module: &Module<B>, other: &LWEToGLWESwitchingKey<DR>, scratch: &mut Scratch<B>) {
self.0.prepare(module, &other.0, scratch);
}
}

View File

@@ -0,0 +1,30 @@
mod gglwe_atk;
mod gglwe_ct;
mod gglwe_ksk;
mod gglwe_tsk;
mod ggsw_ct;
mod glwe_pk;
mod glwe_sk;
mod glwe_to_lwe_ksk;
mod lwe_ksk;
mod lwe_to_glwe_ksk;
pub use gglwe_atk::*;
pub use gglwe_ct::*;
pub use gglwe_ksk::*;
pub use gglwe_tsk::*;
pub use ggsw_ct::*;
pub use glwe_pk::*;
pub use glwe_sk::*;
pub use glwe_to_lwe_ksk::*;
pub use lwe_ksk::*;
pub use lwe_to_glwe_ksk::*;
use poulpy_backend::hal::layouts::{Backend, Module, Scratch};
pub trait PrepareAlloc<B: Backend, T> {
fn prepare_alloc(&self, module: &Module<B>, scratch: &mut Scratch<B>) -> T;
}
pub trait Prepare<B: Backend, T> {
fn prepare(&mut self, module: &Module<B>, other: &T, scratch: &mut Scratch<B>);
}

24
poulpy-core/src/lib.rs Normal file
View File

@@ -0,0 +1,24 @@
mod automorphism;
mod conversion;
mod decryption;
mod dist;
mod encryption;
mod external_product;
mod glwe_packing;
mod glwe_trace;
mod keyswitching;
mod noise;
mod operations;
mod scratch;
mod utils;
pub use operations::*;
pub mod layouts;
pub use dist::*;
pub use glwe_packing::*;
pub use scratch::*;
pub(crate) const SIX_SIGMA: f64 = 6.0;
pub mod tests;

View File

@@ -0,0 +1,73 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, VecZnxBigAddInplace, VecZnxBigAddSmallInplace,
VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume,
VecZnxNormalizeTmpBytes, VecZnxSubScalarInplace, ZnxZero,
},
layouts::{Backend, DataRef, Module, ScalarZnx, ScratchOwned},
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeVecZnxBigImpl, TakeVecZnxDftImpl},
};
use crate::layouts::{GGLWECiphertext, GLWECiphertext, GLWEPlaintext, Infos, prepared::GLWESecretPrepared};
impl<D: DataRef> GGLWECiphertext<D> {
pub fn assert_noise<B, DataSk, DataWant>(
self,
module: &Module<B>,
sk: &GLWESecretPrepared<DataSk, B>,
pt_want: &ScalarZnx<DataWant>,
max_noise: f64,
) where
DataSk: DataRef,
DataWant: DataRef,
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxSubScalarInplace,
B: Backend + TakeVecZnxDftImpl<B> + TakeVecZnxBigImpl<B> + ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
{
let digits: usize = self.digits();
let basek: usize = self.basek();
let k: usize = self.k();
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GLWECiphertext::decrypt_scratch_space(
module,
self.n(),
basek,
k,
));
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(self.n(), basek, k);
(0..self.rank_in()).for_each(|col_i| {
(0..self.rows()).for_each(|row_i| {
self.at(row_i, col_i)
.decrypt(module, &mut pt, sk, scratch.borrow());
module.vec_znx_sub_scalar_inplace(
&mut pt.data,
0,
(digits - 1) + row_i * digits,
pt_want,
col_i,
);
let noise_have: f64 = pt.data.std(basek, 0).log2();
assert!(
noise_have <= max_noise,
"noise_have: {} > max_noise: {}",
noise_have,
max_noise
);
pt.data.zero();
});
});
}
}

View File

@@ -0,0 +1,145 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, VecZnxAddScalarInplace, VecZnxBigAddInplace,
VecZnxBigAddSmallInplace, VecZnxBigAlloc, VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes,
VecZnxDftAlloc, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxDftToVecZnxBigTmpA,
VecZnxNormalizeTmpBytes, VecZnxSubABInplace, ZnxZero,
},
layouts::{Backend, DataRef, Module, ScalarZnx, ScratchOwned, VecZnxBig, VecZnxDft},
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeVecZnxBigImpl, TakeVecZnxDftImpl},
};
use crate::layouts::{GGSWCiphertext, GLWECiphertext, GLWEPlaintext, Infos, prepared::GLWESecretPrepared};
impl<D: DataRef> GGSWCiphertext<D> {
pub fn assert_noise<B, DataSk, DataScalar, F>(
&self,
module: &Module<B>,
sk_prepared: &GLWESecretPrepared<DataSk, B>,
pt_want: &ScalarZnx<DataScalar>,
max_noise: F,
) where
DataSk: DataRef,
DataScalar: DataRef,
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxBigAlloc<B>
+ VecZnxDftAlloc<B>
+ VecZnxBigNormalizeTmpBytes
+ VecZnxDftToVecZnxBigTmpA<B>
+ VecZnxAddScalarInplace
+ VecZnxSubABInplace,
B: Backend + TakeVecZnxDftImpl<B> + TakeVecZnxBigImpl<B> + ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
F: Fn(usize) -> f64,
{
let basek: usize = self.basek();
let k: usize = self.k();
let digits: usize = self.digits();
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(self.n(), basek, k);
let mut pt_have: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(self.n(), basek, k);
let mut pt_dft: VecZnxDft<Vec<u8>, B> = module.vec_znx_dft_alloc(self.n(), 1, self.size());
let mut pt_big: VecZnxBig<Vec<u8>, B> = module.vec_znx_big_alloc(self.n(), 1, self.size());
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GLWECiphertext::decrypt_scratch_space(module, self.n(), basek, k) | module.vec_znx_normalize_tmp_bytes(self.n()),
);
(0..self.rank() + 1).for_each(|col_j| {
(0..self.rows()).for_each(|row_i| {
module.vec_znx_add_scalar_inplace(&mut pt.data, 0, (digits - 1) + row_i * digits, pt_want, 0);
// mul with sk[col_j-1]
if col_j > 0 {
module.vec_znx_dft_from_vec_znx(1, 0, &mut pt_dft, 0, &pt.data, 0);
module.svp_apply_inplace(&mut pt_dft, 0, &sk_prepared.data, col_j - 1);
module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut pt_big, 0, &mut pt_dft, 0);
module.vec_znx_big_normalize(basek, &mut pt.data, 0, &pt_big, 0, scratch.borrow());
}
self.at(row_i, col_j)
.decrypt(module, &mut pt_have, sk_prepared, scratch.borrow());
module.vec_znx_sub_ab_inplace(&mut pt_have.data, 0, &pt.data, 0);
let std_pt: f64 = pt_have.data.std(basek, 0).log2();
let noise: f64 = max_noise(col_j);
println!("{} {}", std_pt, noise);
assert!(std_pt <= noise, "{} > {}", std_pt, noise);
pt.data.zero();
});
});
}
}
impl<D: DataRef> GGSWCiphertext<D> {
pub fn print_noise<B, DataSk, DataScalar>(
&self,
module: &Module<B>,
sk_prepared: &GLWESecretPrepared<DataSk, B>,
pt_want: &ScalarZnx<DataScalar>,
) where
DataSk: DataRef,
DataScalar: DataRef,
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxBigAlloc<B>
+ VecZnxDftAlloc<B>
+ VecZnxBigNormalizeTmpBytes
+ VecZnxDftToVecZnxBigTmpA<B>
+ VecZnxAddScalarInplace
+ VecZnxSubABInplace,
B: Backend + TakeVecZnxDftImpl<B> + TakeVecZnxBigImpl<B> + ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
{
let basek: usize = self.basek();
let k: usize = self.k();
let digits: usize = self.digits();
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(self.n(), basek, k);
let mut pt_have: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(self.n(), basek, k);
let mut pt_dft: VecZnxDft<Vec<u8>, B> = module.vec_znx_dft_alloc(self.n(), 1, self.size());
let mut pt_big: VecZnxBig<Vec<u8>, B> = module.vec_znx_big_alloc(self.n(), 1, self.size());
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GLWECiphertext::decrypt_scratch_space(module, self.n(), basek, k) | module.vec_znx_normalize_tmp_bytes(module.n()),
);
(0..self.rank() + 1).for_each(|col_j| {
(0..self.rows()).for_each(|row_i| {
module.vec_znx_add_scalar_inplace(&mut pt.data, 0, (digits - 1) + row_i * digits, pt_want, 0);
// mul with sk[col_j-1]
if col_j > 0 {
module.vec_znx_dft_from_vec_znx(1, 0, &mut pt_dft, 0, &pt.data, 0);
module.svp_apply_inplace(&mut pt_dft, 0, &sk_prepared.data, col_j - 1);
module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut pt_big, 0, &mut pt_dft, 0);
module.vec_znx_big_normalize(basek, &mut pt.data, 0, &pt_big, 0, scratch.borrow());
}
self.at(row_i, col_j)
.decrypt(module, &mut pt_have, sk_prepared, scratch.borrow());
module.vec_znx_sub_ab_inplace(&mut pt_have.data, 0, &pt.data, 0);
let std_pt: f64 = pt_have.data.std(basek, 0).log2();
println!("col: {} row: {}: {}", col_j, row_i, std_pt);
pt.data.zero();
});
});
}
}

View File

@@ -0,0 +1,57 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, VecZnxBigAddInplace, VecZnxBigAddSmallInplace,
VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSubABInplace,
},
layouts::{Backend, DataRef, Module, ScratchOwned},
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeVecZnxBigImpl, TakeVecZnxDftImpl},
};
use crate::{
layouts::GLWEPlaintext,
layouts::prepared::GLWESecretPrepared,
layouts::{GLWECiphertext, Infos},
};
impl<D: DataRef> GLWECiphertext<D> {
pub fn assert_noise<B, DataSk, DataPt>(
&self,
module: &Module<B>,
sk_prepared: &GLWESecretPrepared<DataSk, B>,
pt_want: &GLWEPlaintext<DataPt>,
max_noise: f64,
) where
DataSk: DataRef,
DataPt: DataRef,
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxSubABInplace
+ VecZnxNormalizeInplace<B>,
B: Backend + TakeVecZnxDftImpl<B> + TakeVecZnxBigImpl<B> + ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
{
let mut pt_have: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(self.n(), self.basek(), self.k());
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GLWECiphertext::decrypt_scratch_space(
module,
self.n(),
self.basek(),
self.k(),
));
self.decrypt(module, &mut pt_have, sk_prepared, scratch.borrow());
module.vec_znx_sub_ab_inplace(&mut pt_have.data, 0, &pt_want.data, 0);
module.vec_znx_normalize_inplace(self.basek(), &mut pt_have.data, 0, scratch.borrow());
let noise_have: f64 = pt_have.data.std(self.basek(), 0).log2();
assert!(noise_have <= max_noise, "{} {}", noise_have, max_noise);
}
}

View File

@@ -0,0 +1,151 @@
mod gglwe_ct;
mod ggsw_ct;
mod glwe_ct;
#[allow(clippy::too_many_arguments)]
#[allow(dead_code)]
pub(crate) fn var_noise_gglwe_product(
n: f64,
basek: usize,
var_xs: f64,
var_msg: f64,
var_a_err: f64,
var_gct_err_lhs: f64,
var_gct_err_rhs: f64,
rank_in: f64,
a_logq: usize,
b_logq: usize,
) -> f64 {
let a_logq: usize = a_logq.min(b_logq);
let a_cols: usize = a_logq.div_ceil(basek);
let b_scale: f64 = (b_logq as f64).exp2();
let a_scale: f64 = ((b_logq - a_logq) as f64).exp2();
let base: f64 = (basek as f64).exp2();
let var_base: f64 = base * base / 12f64;
// lhs = a_cols * n * (var_base * var_gct_err_lhs + var_e_a * var_msg * p^2)
// rhs = a_cols * n * var_base * var_gct_err_rhs * var_xs
let mut noise: f64 = (a_cols as f64) * n * var_base * (var_gct_err_lhs + var_xs * var_gct_err_rhs);
noise += var_msg * var_a_err * a_scale * a_scale * n;
noise *= rank_in;
noise /= b_scale * b_scale;
noise
}
#[allow(clippy::too_many_arguments)]
#[allow(dead_code)]
pub(crate) fn log2_std_noise_gglwe_product(
n: f64,
basek: usize,
var_xs: f64,
var_msg: f64,
var_a_err: f64,
var_gct_err_lhs: f64,
var_gct_err_rhs: f64,
rank_in: f64,
a_logq: usize,
b_logq: usize,
) -> f64 {
let mut noise: f64 = var_noise_gglwe_product(
n,
basek,
var_xs,
var_msg,
var_a_err,
var_gct_err_lhs,
var_gct_err_rhs,
rank_in,
a_logq,
b_logq,
);
noise = noise.sqrt();
noise.log2().min(-1.0).max(-(a_logq as f64)) // max noise is [-2^{-1}, 2^{-1}]
}
#[allow(clippy::too_many_arguments)]
#[allow(dead_code)]
pub(crate) fn noise_ggsw_product(
n: f64,
basek: usize,
var_xs: f64,
var_msg: f64,
var_a0_err: f64,
var_a1_err: f64,
var_gct_err_lhs: f64,
var_gct_err_rhs: f64,
rank: f64,
k_in: usize,
k_ggsw: usize,
) -> f64 {
let a_logq: usize = k_in.min(k_ggsw);
let a_cols: usize = a_logq.div_ceil(basek);
let b_scale: f64 = (k_ggsw as f64).exp2();
let a_scale: f64 = ((k_ggsw - a_logq) as f64).exp2();
let base: f64 = (basek as f64).exp2();
let var_base: f64 = base * base / 12f64;
// lhs = a_cols * n * (var_base * var_gct_err_lhs + var_e_a * var_msg * p^2)
// rhs = a_cols * n * var_base * var_gct_err_rhs * var_xs
let mut noise: f64 = (rank + 1.0) * (a_cols as f64) * n * var_base * (var_gct_err_lhs + var_xs * var_gct_err_rhs);
noise += var_msg * var_a0_err * a_scale * a_scale * n;
noise += var_msg * var_a1_err * a_scale * a_scale * n * var_xs * rank;
noise = noise.sqrt();
noise /= b_scale;
noise.log2().min(-1.0) // max noise is [-2^{-1}, 2^{-1}]
}
#[allow(clippy::too_many_arguments)]
#[allow(dead_code)]
pub(crate) fn noise_ggsw_keyswitch(
n: f64,
basek: usize,
col: usize,
var_xs: f64,
var_a_err: f64,
var_gct_err_lhs: f64,
var_gct_err_rhs: f64,
rank: f64,
k_ct: usize,
k_ksk: usize,
k_tsk: usize,
) -> f64 {
let var_si_x_sj: f64 = n * var_xs * var_xs;
// Initial KS for col = 0
let mut noise: f64 = var_noise_gglwe_product(
n,
basek,
var_xs,
var_xs,
var_a_err,
var_gct_err_lhs,
var_gct_err_rhs,
rank,
k_ct,
k_ksk,
);
// Other GGSW reconstruction for col > 0
if col > 0 {
noise += var_noise_gglwe_product(
n,
basek,
var_xs,
var_si_x_sj,
var_a_err + 1f64 / 12.0,
var_gct_err_lhs,
var_gct_err_rhs,
rank,
k_ct,
k_tsk,
);
noise += n * noise * var_xs * 0.5;
}
noise = noise.sqrt();
noise.log2().min(-1.0) // max noise is [-2^{-1}, 2^{-1}]
}

View File

@@ -0,0 +1,345 @@
use poulpy_backend::hal::{
api::{
VecZnxAdd, VecZnxAddInplace, VecZnxCopy, VecZnxMulXpMinusOne, VecZnxMulXpMinusOneInplace, VecZnxNegateInplace,
VecZnxNormalize, VecZnxNormalizeInplace, VecZnxRotate, VecZnxRotateInplace, VecZnxRshInplace, VecZnxSub,
VecZnxSubABInplace, VecZnxSubBAInplace, ZnxZero,
},
layouts::{Backend, DataMut, Module, Scratch, VecZnx},
};
use crate::layouts::{GLWECiphertext, GLWECiphertextToMut, GLWECiphertextToRef, GLWEPlaintext, Infos, SetMetaData};
impl<D> GLWEOperations for GLWEPlaintext<D>
where
D: DataMut,
GLWEPlaintext<D>: GLWECiphertextToMut + Infos + SetMetaData,
{
}
impl<D: DataMut> GLWEOperations for GLWECiphertext<D> where GLWECiphertext<D>: GLWECiphertextToMut + Infos + SetMetaData {}
pub trait GLWEOperations: GLWECiphertextToMut + SetMetaData + Sized {
fn add<A, B, BACKEND: Backend>(&mut self, module: &Module<BACKEND>, a: &A, b: &B)
where
A: GLWECiphertextToRef,
B: GLWECiphertextToRef,
Module<BACKEND>: VecZnxAdd + VecZnxCopy,
{
#[cfg(debug_assertions)]
{
assert_eq!(a.n(), self.n());
assert_eq!(b.n(), self.n());
assert_eq!(a.basek(), b.basek());
assert!(self.rank() >= a.rank().max(b.rank()));
}
let min_col: usize = a.rank().min(b.rank()) + 1;
let max_col: usize = a.rank().max(b.rank() + 1);
let self_col: usize = self.rank() + 1;
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
let a_ref: &GLWECiphertext<&[u8]> = &a.to_ref();
let b_ref: &GLWECiphertext<&[u8]> = &b.to_ref();
(0..min_col).for_each(|i| {
module.vec_znx_add(&mut self_mut.data, i, &a_ref.data, i, &b_ref.data, i);
});
if a.rank() > b.rank() {
(min_col..max_col).for_each(|i| {
module.vec_znx_copy(&mut self_mut.data, i, &a_ref.data, i);
});
} else {
(min_col..max_col).for_each(|i| {
module.vec_znx_copy(&mut self_mut.data, i, &b_ref.data, i);
});
}
let size: usize = self_mut.size();
(max_col..self_col).for_each(|i| {
(0..size).for_each(|j| {
self_mut.data.zero_at(i, j);
});
});
self.set_basek(a.basek());
self.set_k(set_k_binary(self, a, b));
}
fn add_inplace<A, BACKEND: Backend>(&mut self, module: &Module<BACKEND>, a: &A)
where
A: GLWECiphertextToRef + Infos,
Module<BACKEND>: VecZnxAddInplace,
{
#[cfg(debug_assertions)]
{
assert_eq!(a.n(), self.n());
assert_eq!(self.basek(), a.basek());
assert!(self.rank() >= a.rank())
}
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
let a_ref: &GLWECiphertext<&[u8]> = &a.to_ref();
(0..a.rank() + 1).for_each(|i| {
module.vec_znx_add_inplace(&mut self_mut.data, i, &a_ref.data, i);
});
self.set_k(set_k_unary(self, a))
}
fn sub<A, B, BACKEND: Backend>(&mut self, module: &Module<BACKEND>, a: &A, b: &B)
where
A: GLWECiphertextToRef,
B: GLWECiphertextToRef,
Module<BACKEND>: VecZnxSub + VecZnxCopy + VecZnxNegateInplace,
{
#[cfg(debug_assertions)]
{
assert_eq!(a.n(), self.n());
assert_eq!(b.n(), self.n());
assert_eq!(a.basek(), b.basek());
assert!(self.rank() >= a.rank().max(b.rank()));
}
let min_col: usize = a.rank().min(b.rank()) + 1;
let max_col: usize = a.rank().max(b.rank() + 1);
let self_col: usize = self.rank() + 1;
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
let a_ref: &GLWECiphertext<&[u8]> = &a.to_ref();
let b_ref: &GLWECiphertext<&[u8]> = &b.to_ref();
(0..min_col).for_each(|i| {
module.vec_znx_sub(&mut self_mut.data, i, &a_ref.data, i, &b_ref.data, i);
});
if a.rank() > b.rank() {
(min_col..max_col).for_each(|i| {
module.vec_znx_copy(&mut self_mut.data, i, &a_ref.data, i);
});
} else {
(min_col..max_col).for_each(|i| {
module.vec_znx_copy(&mut self_mut.data, i, &b_ref.data, i);
module.vec_znx_negate_inplace(&mut self_mut.data, i);
});
}
let size: usize = self_mut.size();
(max_col..self_col).for_each(|i| {
(0..size).for_each(|j| {
self_mut.data.zero_at(i, j);
});
});
self.set_basek(a.basek());
self.set_k(set_k_binary(self, a, b));
}
fn sub_inplace_ab<A, BACKEND: Backend>(&mut self, module: &Module<BACKEND>, a: &A)
where
A: GLWECiphertextToRef + Infos,
Module<BACKEND>: VecZnxSubABInplace,
{
#[cfg(debug_assertions)]
{
assert_eq!(a.n(), self.n());
assert_eq!(self.basek(), a.basek());
assert!(self.rank() >= a.rank())
}
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
let a_ref: &GLWECiphertext<&[u8]> = &a.to_ref();
(0..a.rank() + 1).for_each(|i| {
module.vec_znx_sub_ab_inplace(&mut self_mut.data, i, &a_ref.data, i);
});
self.set_k(set_k_unary(self, a))
}
fn sub_inplace_ba<A, BACKEND: Backend>(&mut self, module: &Module<BACKEND>, a: &A)
where
A: GLWECiphertextToRef + Infos,
Module<BACKEND>: VecZnxSubBAInplace,
{
#[cfg(debug_assertions)]
{
assert_eq!(a.n(), self.n());
assert_eq!(self.basek(), a.basek());
assert!(self.rank() >= a.rank())
}
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
let a_ref: &GLWECiphertext<&[u8]> = &a.to_ref();
(0..a.rank() + 1).for_each(|i| {
module.vec_znx_sub_ba_inplace(&mut self_mut.data, i, &a_ref.data, i);
});
self.set_k(set_k_unary(self, a))
}
fn rotate<A, B: Backend>(&mut self, module: &Module<B>, k: i64, a: &A)
where
A: GLWECiphertextToRef + Infos,
Module<B>: VecZnxRotate,
{
#[cfg(debug_assertions)]
{
assert_eq!(a.n(), self.n());
assert_eq!(self.rank(), a.rank())
}
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
let a_ref: &GLWECiphertext<&[u8]> = &a.to_ref();
(0..a.rank() + 1).for_each(|i| {
module.vec_znx_rotate(k, &mut self_mut.data, i, &a_ref.data, i);
});
self.set_basek(a.basek());
self.set_k(set_k_unary(self, a))
}
fn rotate_inplace<B: Backend>(&mut self, module: &Module<B>, k: i64)
where
Module<B>: VecZnxRotateInplace,
{
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
(0..self_mut.rank() + 1).for_each(|i| {
module.vec_znx_rotate_inplace(k, &mut self_mut.data, i);
});
}
fn mul_xp_minus_one<A, B: Backend>(&mut self, module: &Module<B>, k: i64, a: &A)
where
A: GLWECiphertextToRef + Infos,
Module<B>: VecZnxMulXpMinusOne,
{
#[cfg(debug_assertions)]
{
assert_eq!(a.n(), self.n());
assert_eq!(self.rank(), a.rank())
}
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
let a_ref: &GLWECiphertext<&[u8]> = &a.to_ref();
(0..a.rank() + 1).for_each(|i| {
module.vec_znx_mul_xp_minus_one(k, &mut self_mut.data, i, &a_ref.data, i);
});
self.set_basek(a.basek());
self.set_k(set_k_unary(self, a))
}
fn mul_xp_minus_one_inplace<B: Backend>(&mut self, module: &Module<B>, k: i64)
where
Module<B>: VecZnxMulXpMinusOneInplace,
{
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
(0..self_mut.rank() + 1).for_each(|i| {
module.vec_znx_mul_xp_minus_one_inplace(k, &mut self_mut.data, i);
});
}
fn copy<A, B: Backend>(&mut self, module: &Module<B>, a: &A)
where
A: GLWECiphertextToRef + Infos,
Module<B>: VecZnxCopy,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), a.n());
assert_eq!(self.rank(), a.rank());
}
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
let a_ref: &GLWECiphertext<&[u8]> = &a.to_ref();
(0..self_mut.rank() + 1).for_each(|i| {
module.vec_znx_copy(&mut self_mut.data, i, &a_ref.data, i);
});
self.set_k(a.k().min(self.size() * self.basek()));
self.set_basek(a.basek());
}
fn rsh<B: Backend>(&mut self, module: &Module<B>, k: usize)
where
Module<B>: VecZnxRshInplace,
{
let basek: usize = self.basek();
module.vec_znx_rsh_inplace(basek, k, &mut self.to_mut().data);
}
fn normalize<A, B: Backend>(&mut self, module: &Module<B>, a: &A, scratch: &mut Scratch<B>)
where
A: GLWECiphertextToRef,
Module<B>: VecZnxNormalize<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), a.n());
assert_eq!(self.rank(), a.rank());
}
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
let a_ref: &GLWECiphertext<&[u8]> = &a.to_ref();
(0..self_mut.rank() + 1).for_each(|i| {
module.vec_znx_normalize(a.basek(), &mut self_mut.data, i, &a_ref.data, i, scratch);
});
self.set_basek(a.basek());
self.set_k(a.k().min(self.k()));
}
fn normalize_inplace<B: Backend>(&mut self, module: &Module<B>, scratch: &mut Scratch<B>)
where
Module<B>: VecZnxNormalizeInplace<B>,
{
let self_mut: &mut GLWECiphertext<&mut [u8]> = &mut self.to_mut();
(0..self_mut.rank() + 1).for_each(|i| {
module.vec_znx_normalize_inplace(self_mut.basek(), &mut self_mut.data, i, scratch);
});
}
}
impl GLWECiphertext<Vec<u8>> {
pub fn rsh_scratch_space(n: usize) -> usize {
VecZnx::rsh_scratch_space(n)
}
}
// c = op(a, b)
fn set_k_binary(c: &impl Infos, a: &impl Infos, b: &impl Infos) -> usize {
// If either operands is a ciphertext
if a.rank() != 0 || b.rank() != 0 {
// If a is a plaintext (but b ciphertext)
let k = if a.rank() == 0 {
b.k()
// If b is a plaintext (but a ciphertext)
} else if b.rank() == 0 {
a.k()
// If a & b are both ciphertexts
} else {
a.k().min(b.k())
};
k.min(c.k())
// If a & b are both plaintexts
} else {
c.k()
}
}
// a = op(a, b)
fn set_k_unary(a: &impl Infos, b: &impl Infos) -> usize {
if a.rank() != 0 || b.rank() != 0 {
a.k().min(b.k())
} else {
a.k()
}
}

View File

@@ -0,0 +1,3 @@
mod glwe;
pub use glwe::*;

950
poulpy-core/src/scratch.rs Normal file
View File

@@ -0,0 +1,950 @@
use poulpy_backend::hal::{
api::{TakeMatZnx, TakeScalarZnx, TakeSvpPPol, TakeVecZnx, TakeVecZnxDft, TakeVmpPMat},
layouts::{Backend, DataRef, Scratch},
oep::{TakeMatZnxImpl, TakeScalarZnxImpl, TakeSvpPPolImpl, TakeVecZnxDftImpl, TakeVecZnxImpl, TakeVmpPMatImpl},
};
use crate::{
dist::Distribution,
layouts::{
GGLWEAutomorphismKey, GGLWECiphertext, GGLWESwitchingKey, GGLWETensorKey, GGSWCiphertext, GLWECiphertext, GLWEPlaintext,
GLWEPublicKey, GLWESecret, Infos,
prepared::{
GGLWEAutomorphismKeyPrepared, GGLWECiphertextPrepared, GGLWESwitchingKeyPrepared, GGLWETensorKeyPrepared,
GGSWCiphertextPrepared, GLWEPublicKeyPrepared, GLWESecretPrepared,
},
},
};
pub trait TakeLike<'a, B: Backend, T> {
type Output;
fn take_like(&'a mut self, template: &T) -> (Self::Output, &'a mut Self);
}
pub trait TakeGLWECt {
fn take_glwe_ct(&mut self, n: usize, basek: usize, k: usize, rank: usize) -> (GLWECiphertext<&mut [u8]>, &mut Self);
}
pub trait TakeGLWECtSlice {
fn take_glwe_ct_slice(
&mut self,
size: usize,
n: usize,
basek: usize,
k: usize,
rank: usize,
) -> (Vec<GLWECiphertext<&mut [u8]>>, &mut Self);
}
pub trait TakeGLWEPt<B: Backend> {
fn take_glwe_pt(&mut self, n: usize, basek: usize, k: usize) -> (GLWEPlaintext<&mut [u8]>, &mut Self);
}
pub trait TakeGGLWE {
#[allow(clippy::too_many_arguments)]
fn take_gglwe(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> (GGLWECiphertext<&mut [u8]>, &mut Self);
}
pub trait TakeGGLWEPrepared<B: Backend> {
#[allow(clippy::too_many_arguments)]
fn take_gglwe_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> (GGLWECiphertextPrepared<&mut [u8], B>, &mut Self);
}
pub trait TakeGGSW {
fn take_ggsw(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGSWCiphertext<&mut [u8]>, &mut Self);
}
pub trait TakeGGSWPrepared<B: Backend> {
fn take_ggsw_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGSWCiphertextPrepared<&mut [u8], B>, &mut Self);
}
pub trait TakeGLWESecret {
fn take_glwe_secret(&mut self, n: usize, rank: usize) -> (GLWESecret<&mut [u8]>, &mut Self);
}
pub trait TakeGLWESecretPrepared<B: Backend> {
fn take_glwe_secret_prepared(&mut self, n: usize, rank: usize) -> (GLWESecretPrepared<&mut [u8], B>, &mut Self);
}
pub trait TakeGLWEPk {
fn take_glwe_pk(&mut self, n: usize, basek: usize, k: usize, rank: usize) -> (GLWEPublicKey<&mut [u8]>, &mut Self);
}
pub trait TakeGLWEPkPrepared<B: Backend> {
fn take_glwe_pk_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rank: usize,
) -> (GLWEPublicKeyPrepared<&mut [u8], B>, &mut Self);
}
pub trait TakeGLWESwitchingKey {
#[allow(clippy::too_many_arguments)]
fn take_glwe_switching_key(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> (GGLWESwitchingKey<&mut [u8]>, &mut Self);
}
pub trait TakeGLWESwitchingKeyPrepared<B: Backend> {
#[allow(clippy::too_many_arguments)]
fn take_glwe_switching_key_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> (GGLWESwitchingKeyPrepared<&mut [u8], B>, &mut Self);
}
pub trait TakeTensorKey {
fn take_tensor_key(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGLWETensorKey<&mut [u8]>, &mut Self);
}
pub trait TakeTensorKeyPrepared<B: Backend> {
fn take_tensor_key_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGLWETensorKeyPrepared<&mut [u8], B>, &mut Self);
}
pub trait TakeAutomorphismKey {
fn take_automorphism_key(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGLWEAutomorphismKey<&mut [u8]>, &mut Self);
}
pub trait TakeAutomorphismKeyPrepared<B: Backend> {
fn take_automorphism_key_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGLWEAutomorphismKeyPrepared<&mut [u8], B>, &mut Self);
}
impl<B: Backend> TakeGLWECt for Scratch<B>
where
Scratch<B>: TakeVecZnx,
{
fn take_glwe_ct(&mut self, n: usize, basek: usize, k: usize, rank: usize) -> (GLWECiphertext<&mut [u8]>, &mut Self) {
let (data, scratch) = self.take_vec_znx(n, rank + 1, k.div_ceil(basek));
(GLWECiphertext { data, basek, k }, scratch)
}
}
impl<'a, B, D> TakeLike<'a, B, GLWECiphertext<D>> for Scratch<B>
where
B: Backend + TakeVecZnxImpl<B>,
D: DataRef,
{
type Output = GLWECiphertext<&'a mut [u8]>;
fn take_like(&'a mut self, template: &GLWECiphertext<D>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_vec_znx_impl(self, template.n(), template.cols(), template.size());
(
GLWECiphertext {
data,
basek: template.basek(),
k: template.k(),
},
scratch,
)
}
}
impl<B: Backend> TakeGLWECtSlice for Scratch<B>
where
Scratch<B>: TakeVecZnx,
{
fn take_glwe_ct_slice(
&mut self,
size: usize,
n: usize,
basek: usize,
k: usize,
rank: usize,
) -> (Vec<GLWECiphertext<&mut [u8]>>, &mut Self) {
let mut scratch: &mut Scratch<B> = self;
let mut cts: Vec<GLWECiphertext<&mut [u8]>> = Vec::with_capacity(size);
for _ in 0..size {
let (ct, new_scratch) = scratch.take_glwe_ct(n, basek, k, rank);
scratch = new_scratch;
cts.push(ct);
}
(cts, scratch)
}
}
impl<B: Backend> TakeGLWEPt<B> for Scratch<B>
where
Scratch<B>: TakeVecZnx,
{
fn take_glwe_pt(&mut self, n: usize, basek: usize, k: usize) -> (GLWEPlaintext<&mut [u8]>, &mut Self) {
let (data, scratch) = self.take_vec_znx(n, 1, k.div_ceil(basek));
(GLWEPlaintext { data, basek, k }, scratch)
}
}
impl<'a, B, D> TakeLike<'a, B, GLWEPlaintext<D>> for Scratch<B>
where
B: Backend + TakeVecZnxImpl<B>,
D: DataRef,
{
type Output = GLWEPlaintext<&'a mut [u8]>;
fn take_like(&'a mut self, template: &GLWEPlaintext<D>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_vec_znx_impl(self, template.n(), template.cols(), template.size());
(
GLWEPlaintext {
data,
basek: template.basek(),
k: template.k(),
},
scratch,
)
}
}
impl<B: Backend> TakeGGLWE for Scratch<B>
where
Scratch<B>: TakeMatZnx,
{
fn take_gglwe(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> (GGLWECiphertext<&mut [u8]>, &mut Self) {
let (data, scratch) = self.take_mat_znx(
n,
rows.div_ceil(digits),
rank_in,
rank_out + 1,
k.div_ceil(basek),
);
(
GGLWECiphertext {
data,
basek,
k,
digits,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GGLWECiphertext<D>> for Scratch<B>
where
B: Backend + TakeMatZnxImpl<B>,
D: DataRef,
{
type Output = GGLWECiphertext<&'a mut [u8]>;
fn take_like(&'a mut self, template: &GGLWECiphertext<D>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_mat_znx_impl(
self,
template.n(),
template.rows(),
template.data.cols_in(),
template.data.cols_out(),
template.size(),
);
(
GGLWECiphertext {
data,
basek: template.basek(),
k: template.k(),
digits: template.digits(),
},
scratch,
)
}
}
impl<B: Backend> TakeGGLWEPrepared<B> for Scratch<B>
where
Scratch<B>: TakeVmpPMat<B>,
{
fn take_gglwe_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> (GGLWECiphertextPrepared<&mut [u8], B>, &mut Self) {
let (data, scratch) = self.take_vmp_pmat(
n,
rows.div_ceil(digits),
rank_in,
rank_out + 1,
k.div_ceil(basek),
);
(
GGLWECiphertextPrepared {
data,
basek,
k,
digits,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GGLWECiphertextPrepared<D, B>> for Scratch<B>
where
B: Backend + TakeVmpPMatImpl<B>,
D: DataRef,
{
type Output = GGLWECiphertextPrepared<&'a mut [u8], B>;
fn take_like(&'a mut self, template: &GGLWECiphertextPrepared<D, B>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_vmp_pmat_impl(
self,
template.n(),
template.rows(),
template.data.cols_in(),
template.data.cols_out(),
template.size(),
);
(
GGLWECiphertextPrepared {
data,
basek: template.basek(),
k: template.k(),
digits: template.digits(),
},
scratch,
)
}
}
impl<B: Backend> TakeGGSW for Scratch<B>
where
Scratch<B>: TakeMatZnx,
{
fn take_ggsw(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGSWCiphertext<&mut [u8]>, &mut Self) {
let (data, scratch) = self.take_mat_znx(
n,
rows.div_ceil(digits),
rank + 1,
rank + 1,
k.div_ceil(basek),
);
(
GGSWCiphertext {
data,
basek,
k,
digits,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GGSWCiphertext<D>> for Scratch<B>
where
B: Backend + TakeMatZnxImpl<B>,
D: DataRef,
{
type Output = GGSWCiphertext<&'a mut [u8]>;
fn take_like(&'a mut self, template: &GGSWCiphertext<D>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_mat_znx_impl(
self,
template.n(),
template.rows(),
template.data.cols_in(),
template.data.cols_out(),
template.size(),
);
(
GGSWCiphertext {
data,
basek: template.basek(),
k: template.k(),
digits: template.digits(),
},
scratch,
)
}
}
impl<B: Backend> TakeGGSWPrepared<B> for Scratch<B>
where
Scratch<B>: TakeVmpPMat<B>,
{
fn take_ggsw_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGSWCiphertextPrepared<&mut [u8], B>, &mut Self) {
let (data, scratch) = self.take_vmp_pmat(
n,
rows.div_ceil(digits),
rank + 1,
rank + 1,
k.div_ceil(basek),
);
(
GGSWCiphertextPrepared {
data,
basek,
k,
digits,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GGSWCiphertextPrepared<D, B>> for Scratch<B>
where
B: Backend + TakeVmpPMatImpl<B>,
D: DataRef,
{
type Output = GGSWCiphertextPrepared<&'a mut [u8], B>;
fn take_like(&'a mut self, template: &GGSWCiphertextPrepared<D, B>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_vmp_pmat_impl(
self,
template.n(),
template.rows(),
template.data.cols_in(),
template.data.cols_out(),
template.size(),
);
(
GGSWCiphertextPrepared {
data,
basek: template.basek(),
k: template.k(),
digits: template.digits(),
},
scratch,
)
}
}
impl<B: Backend> TakeGLWEPk for Scratch<B>
where
Scratch<B>: TakeVecZnx,
{
fn take_glwe_pk(&mut self, n: usize, basek: usize, k: usize, rank: usize) -> (GLWEPublicKey<&mut [u8]>, &mut Self) {
let (data, scratch) = self.take_vec_znx(n, rank + 1, k.div_ceil(basek));
(
GLWEPublicKey {
data,
k,
basek,
dist: Distribution::NONE,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GLWEPublicKey<D>> for Scratch<B>
where
B: Backend + TakeVecZnxImpl<B>,
D: DataRef,
{
type Output = GLWEPublicKey<&'a mut [u8]>;
fn take_like(&'a mut self, template: &GLWEPublicKey<D>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_vec_znx_impl(self, template.n(), template.cols(), template.size());
(
GLWEPublicKey {
data,
basek: template.basek(),
k: template.k(),
dist: template.dist,
},
scratch,
)
}
}
impl<B: Backend> TakeGLWEPkPrepared<B> for Scratch<B>
where
Scratch<B>: TakeVecZnxDft<B>,
{
fn take_glwe_pk_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rank: usize,
) -> (GLWEPublicKeyPrepared<&mut [u8], B>, &mut Self) {
let (data, scratch) = self.take_vec_znx_dft(n, rank + 1, k.div_ceil(basek));
(
GLWEPublicKeyPrepared {
data,
k,
basek,
dist: Distribution::NONE,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GLWEPublicKeyPrepared<D, B>> for Scratch<B>
where
B: Backend + TakeVecZnxDftImpl<B>,
D: DataRef,
{
type Output = GLWEPublicKeyPrepared<&'a mut [u8], B>;
fn take_like(&'a mut self, template: &GLWEPublicKeyPrepared<D, B>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_vec_znx_dft_impl(self, template.n(), template.cols(), template.size());
(
GLWEPublicKeyPrepared {
data,
basek: template.basek(),
k: template.k(),
dist: template.dist,
},
scratch,
)
}
}
impl<B: Backend> TakeGLWESecret for Scratch<B>
where
Scratch<B>: TakeScalarZnx,
{
fn take_glwe_secret(&mut self, n: usize, rank: usize) -> (GLWESecret<&mut [u8]>, &mut Self) {
let (data, scratch) = self.take_scalar_znx(n, rank);
(
GLWESecret {
data,
dist: Distribution::NONE,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GLWESecret<D>> for Scratch<B>
where
B: Backend + TakeScalarZnxImpl<B>,
D: DataRef,
{
type Output = GLWESecret<&'a mut [u8]>;
fn take_like(&'a mut self, template: &GLWESecret<D>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_scalar_znx_impl(self, template.n(), template.rank());
(
GLWESecret {
data,
dist: template.dist,
},
scratch,
)
}
}
impl<B: Backend> TakeGLWESecretPrepared<B> for Scratch<B>
where
Scratch<B>: TakeSvpPPol<B>,
{
fn take_glwe_secret_prepared(&mut self, n: usize, rank: usize) -> (GLWESecretPrepared<&mut [u8], B>, &mut Self) {
let (data, scratch) = self.take_svp_ppol(n, rank);
(
GLWESecretPrepared {
data,
dist: Distribution::NONE,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GLWESecretPrepared<D, B>> for Scratch<B>
where
B: Backend + TakeSvpPPolImpl<B>,
D: DataRef,
{
type Output = GLWESecretPrepared<&'a mut [u8], B>;
fn take_like(&'a mut self, template: &GLWESecretPrepared<D, B>) -> (Self::Output, &'a mut Self) {
let (data, scratch) = B::take_svp_ppol_impl(self, template.n(), template.rank());
(
GLWESecretPrepared {
data,
dist: template.dist,
},
scratch,
)
}
}
impl<B: Backend> TakeGLWESwitchingKey for Scratch<B>
where
Scratch<B>: TakeMatZnx,
{
fn take_glwe_switching_key(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> (GGLWESwitchingKey<&mut [u8]>, &mut Self) {
let (data, scratch) = self.take_gglwe(n, basek, k, rows, digits, rank_in, rank_out);
(
GGLWESwitchingKey {
key: data,
sk_in_n: 0,
sk_out_n: 0,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GGLWESwitchingKey<D>> for Scratch<B>
where
Scratch<B>: TakeLike<'a, B, GGLWECiphertext<D>, Output = GGLWECiphertext<&'a mut [u8]>>,
B: Backend + TakeMatZnxImpl<B>,
D: DataRef,
{
type Output = GGLWESwitchingKey<&'a mut [u8]>;
fn take_like(&'a mut self, template: &GGLWESwitchingKey<D>) -> (Self::Output, &'a mut Self) {
let (key, scratch) = self.take_like(&template.key);
(
GGLWESwitchingKey {
key,
sk_in_n: template.sk_in_n,
sk_out_n: template.sk_out_n,
},
scratch,
)
}
}
impl<B: Backend> TakeGLWESwitchingKeyPrepared<B> for Scratch<B>
where
Scratch<B>: TakeGGLWEPrepared<B>,
{
fn take_glwe_switching_key_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
) -> (GGLWESwitchingKeyPrepared<&mut [u8], B>, &mut Self) {
let (data, scratch) = self.take_gglwe_prepared(n, basek, k, rows, digits, rank_in, rank_out);
(
GGLWESwitchingKeyPrepared {
key: data,
sk_in_n: 0,
sk_out_n: 0,
},
scratch,
)
}
}
impl<'a, B, D> TakeLike<'a, B, GGLWESwitchingKeyPrepared<D, B>> for Scratch<B>
where
Scratch<B>: TakeLike<'a, B, GGLWECiphertextPrepared<D, B>, Output = GGLWECiphertextPrepared<&'a mut [u8], B>>,
B: Backend + TakeMatZnxImpl<B>,
D: DataRef,
{
type Output = GGLWESwitchingKeyPrepared<&'a mut [u8], B>;
fn take_like(&'a mut self, template: &GGLWESwitchingKeyPrepared<D, B>) -> (Self::Output, &'a mut Self) {
let (key, scratch) = self.take_like(&template.key);
(
GGLWESwitchingKeyPrepared {
key,
sk_in_n: template.sk_in_n,
sk_out_n: template.sk_out_n,
},
scratch,
)
}
}
impl<B: Backend> TakeAutomorphismKey for Scratch<B>
where
Scratch<B>: TakeMatZnx,
{
fn take_automorphism_key(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGLWEAutomorphismKey<&mut [u8]>, &mut Self) {
let (data, scratch) = self.take_glwe_switching_key(n, basek, k, rows, digits, rank, rank);
(GGLWEAutomorphismKey { key: data, p: 0 }, scratch)
}
}
impl<'a, B, D> TakeLike<'a, B, GGLWEAutomorphismKey<D>> for Scratch<B>
where
Scratch<B>: TakeLike<'a, B, GGLWESwitchingKey<D>, Output = GGLWESwitchingKey<&'a mut [u8]>>,
B: Backend + TakeMatZnxImpl<B>,
D: DataRef,
{
type Output = GGLWEAutomorphismKey<&'a mut [u8]>;
fn take_like(&'a mut self, template: &GGLWEAutomorphismKey<D>) -> (Self::Output, &'a mut Self) {
let (key, scratch) = self.take_like(&template.key);
(GGLWEAutomorphismKey { key, p: template.p }, scratch)
}
}
impl<B: Backend> TakeAutomorphismKeyPrepared<B> for Scratch<B>
where
Scratch<B>: TakeGLWESwitchingKeyPrepared<B>,
{
fn take_automorphism_key_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGLWEAutomorphismKeyPrepared<&mut [u8], B>, &mut Self) {
let (data, scratch) = self.take_glwe_switching_key_prepared(n, basek, k, rows, digits, rank, rank);
(GGLWEAutomorphismKeyPrepared { key: data, p: 0 }, scratch)
}
}
impl<'a, B, D> TakeLike<'a, B, GGLWEAutomorphismKeyPrepared<D, B>> for Scratch<B>
where
Scratch<B>: TakeLike<'a, B, GGLWESwitchingKeyPrepared<D, B>, Output = GGLWESwitchingKeyPrepared<&'a mut [u8], B>>,
B: Backend + TakeMatZnxImpl<B>,
D: DataRef,
{
type Output = GGLWEAutomorphismKeyPrepared<&'a mut [u8], B>;
fn take_like(&'a mut self, template: &GGLWEAutomorphismKeyPrepared<D, B>) -> (Self::Output, &'a mut Self) {
let (key, scratch) = self.take_like(&template.key);
(GGLWEAutomorphismKeyPrepared { key, p: template.p }, scratch)
}
}
impl<B: Backend> TakeTensorKey for Scratch<B>
where
Scratch<B>: TakeMatZnx,
{
fn take_tensor_key(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGLWETensorKey<&mut [u8]>, &mut Self) {
let mut keys: Vec<GGLWESwitchingKey<&mut [u8]>> = Vec::new();
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
let mut scratch: &mut Scratch<B> = self;
if pairs != 0 {
let (gglwe, s) = scratch.take_glwe_switching_key(n, basek, k, rows, digits, 1, rank);
scratch = s;
keys.push(gglwe);
}
for _ in 1..pairs {
let (gglwe, s) = scratch.take_glwe_switching_key(n, basek, k, rows, digits, 1, rank);
scratch = s;
keys.push(gglwe);
}
(GGLWETensorKey { keys }, scratch)
}
}
impl<'a, B, D> TakeLike<'a, B, GGLWETensorKey<D>> for Scratch<B>
where
Scratch<B>: TakeLike<'a, B, GGLWESwitchingKey<D>, Output = GGLWESwitchingKey<&'a mut [u8]>>,
B: Backend + TakeMatZnxImpl<B>,
D: DataRef,
{
type Output = GGLWETensorKey<&'a mut [u8]>;
fn take_like(&'a mut self, template: &GGLWETensorKey<D>) -> (Self::Output, &'a mut Self) {
let mut keys: Vec<GGLWESwitchingKey<&mut [u8]>> = Vec::new();
let pairs: usize = template.keys.len();
let mut scratch: &mut Scratch<B> = self;
if pairs != 0 {
let (gglwe, s) = scratch.take_like(template.at(0, 0));
scratch = s;
keys.push(gglwe);
}
for _ in 1..pairs {
let (gglwe, s) = scratch.take_like(template.at(0, 0));
scratch = s;
keys.push(gglwe);
}
(GGLWETensorKey { keys }, scratch)
}
}
impl<B: Backend> TakeTensorKeyPrepared<B> for Scratch<B>
where
Scratch<B>: TakeVmpPMat<B>,
{
fn take_tensor_key_prepared(
&mut self,
n: usize,
basek: usize,
k: usize,
rows: usize,
digits: usize,
rank: usize,
) -> (GGLWETensorKeyPrepared<&mut [u8], B>, &mut Self) {
let mut keys: Vec<GGLWESwitchingKeyPrepared<&mut [u8], B>> = Vec::new();
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
let mut scratch: &mut Scratch<B> = self;
if pairs != 0 {
let (gglwe, s) = scratch.take_glwe_switching_key_prepared(n, basek, k, rows, digits, 1, rank);
scratch = s;
keys.push(gglwe);
}
for _ in 1..pairs {
let (gglwe, s) = scratch.take_glwe_switching_key_prepared(n, basek, k, rows, digits, 1, rank);
scratch = s;
keys.push(gglwe);
}
(GGLWETensorKeyPrepared { keys }, scratch)
}
}
impl<'a, B, D> TakeLike<'a, B, GGLWETensorKeyPrepared<D, B>> for Scratch<B>
where
Scratch<B>: TakeLike<'a, B, GGLWESwitchingKeyPrepared<D, B>, Output = GGLWESwitchingKeyPrepared<&'a mut [u8], B>>,
B: Backend + TakeMatZnxImpl<B>,
D: DataRef,
{
type Output = GGLWETensorKeyPrepared<&'a mut [u8], B>;
fn take_like(&'a mut self, template: &GGLWETensorKeyPrepared<D, B>) -> (Self::Output, &'a mut Self) {
let mut keys: Vec<GGLWESwitchingKeyPrepared<&mut [u8], B>> = Vec::new();
let pairs: usize = template.keys.len();
let mut scratch: &mut Scratch<B> = self;
if pairs != 0 {
let (gglwe, s) = scratch.take_like(template.at(0, 0));
scratch = s;
keys.push(gglwe);
}
for _ in 1..pairs {
let (gglwe, s) = scratch.take_like(template.at(0, 0));
scratch = s;
keys.push(gglwe);
}
(GGLWETensorKeyPrepared { keys }, scratch)
}
}

View File

@@ -0,0 +1,361 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, VecZnxAddInplace,
VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphism, VecZnxAutomorphismInplace, VecZnxBigAddInplace,
VecZnxBigAddSmallInplace, VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxCopy,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSubScalarInplace,
VecZnxSwithcDegree, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, VmpPMatAlloc, VmpPrepare,
},
layouts::{Backend, Module, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl,
},
source::Source,
};
use crate::{
layouts::{
GGLWEAutomorphismKey, GLWEPlaintext, GLWESecret, Infos,
prepared::{GGLWEAutomorphismKeyPrepared, GLWESecretPrepared, Prepare, PrepareAlloc},
},
noise::log2_std_noise_gglwe_product,
};
#[allow(clippy::too_many_arguments)]
pub fn test_gglwe_automorphism_key_automorphism<B>(
module: &Module<B>,
p0: i64,
p1: i64,
basek: usize,
digits: usize,
k_in: usize,
k_out: usize,
k_apply: usize,
sigma: f64,
rank: usize,
) where
Module<B>: VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxAutomorphism
+ VecZnxAutomorphismInplace
+ SvpPPolAllocBytes
+ VecZnxDftAllocBytes
+ VecZnxNormalizeTmpBytes
+ VmpPMatAlloc<B>
+ VmpPrepare<B>
+ SvpPrepare<B>
+ SvpApplyInplace<B>
+ VecZnxAddScalarInplace
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ VecZnxSwithcDegree
+ SvpPPolAlloc<B>
+ VecZnxBigAddInplace<B>
+ VecZnxSubScalarInplace,
B: Backend
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxImpl<B>
+ TakeSvpPPolImpl<B>
+ TakeVecZnxBigImpl<B>,
{
let n: usize = module.n();
let digits_in: usize = 1;
let rows_in: usize = k_in / (basek * digits);
let rows_apply: usize = k_in.div_ceil(basek * digits);
let mut auto_key_in: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_in, rows_in, digits_in, rank);
let mut auto_key_out: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_out, rows_in, digits_in, rank);
let mut auto_key_apply: GGLWEAutomorphismKey<Vec<u8>> =
GGLWEAutomorphismKey::alloc(n, basek, k_apply, rows_apply, digits, rank);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GGLWEAutomorphismKey::encrypt_sk_scratch_space(module, n, basek, k_apply, rank)
| GGLWEAutomorphismKey::automorphism_scratch_space(module, n, basek, k_out, k_in, k_apply, digits, rank),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
// gglwe_{s1}(s0) = s0 -> s1
auto_key_in.encrypt_sk(
module,
p0,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
// gglwe_{s2}(s1) -> s1 -> s2
auto_key_apply.encrypt_sk(
module,
p1,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut auto_key_apply_prepared: GGLWEAutomorphismKeyPrepared<Vec<u8>, B> =
GGLWEAutomorphismKeyPrepared::alloc(module, n, basek, k_apply, rows_apply, digits, rank);
auto_key_apply_prepared.prepare(module, &auto_key_apply, scratch.borrow());
// gglwe_{s1}(s0) (x) gglwe_{s2}(s1) = gglwe_{s2}(s0)
auto_key_out.automorphism(
module,
&auto_key_in,
&auto_key_apply_prepared,
scratch.borrow(),
);
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_out);
let mut sk_auto: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_auto.fill_zero(); // Necessary to avoid panic of unfilled sk
(0..rank).for_each(|i| {
module.vec_znx_automorphism(
module.galois_element_inv(p0 * p1),
&mut sk_auto.data.as_vec_znx_mut(),
i,
&sk.data.as_vec_znx(),
i,
);
});
let sk_auto_dft: GLWESecretPrepared<Vec<u8>, B> = sk_auto.prepare_alloc(module, scratch.borrow());
(0..auto_key_out.rank_in()).for_each(|col_i| {
(0..auto_key_out.rows()).for_each(|row_i| {
auto_key_out
.at(row_i, col_i)
.decrypt(module, &mut pt, &sk_auto_dft, scratch.borrow());
module.vec_znx_sub_scalar_inplace(
&mut pt.data,
0,
(digits_in - 1) + row_i * digits_in,
&sk.data,
col_i,
);
let noise_have: f64 = pt.data.std(basek, 0).log2();
let noise_want: f64 = log2_std_noise_gglwe_product(
n as f64,
basek * digits,
0.5,
0.5,
0f64,
sigma * sigma,
0f64,
rank as f64,
k_out,
k_apply,
);
assert!(
noise_have < noise_want + 0.5,
"{} {}",
noise_have,
noise_want
);
});
});
}
#[allow(clippy::too_many_arguments)]
pub fn test_gglwe_automorphism_key_automorphism_inplace<B>(
module: &Module<B>,
p0: i64,
p1: i64,
basek: usize,
digits: usize,
k_in: usize,
k_apply: usize,
sigma: f64,
rank: usize,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxAutomorphism
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ VecZnxAutomorphism
+ VecZnxAutomorphismInplace
+ VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxSubScalarInplace
+ VecZnxCopy
+ VmpPMatAlloc<B>
+ VmpPrepare<B>,
B: Backend
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxImpl<B>
+ TakeSvpPPolImpl<B>
+ TakeVecZnxBigImpl<B>,
{
let n: usize = module.n();
let digits_in: usize = 1;
let rows_in: usize = k_in / (basek * digits);
let rows_apply: usize = k_in.div_ceil(basek * digits);
let mut auto_key: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_in, rows_in, digits_in, rank);
let mut auto_key_apply: GGLWEAutomorphismKey<Vec<u8>> =
GGLWEAutomorphismKey::alloc(n, basek, k_apply, rows_apply, digits, rank);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GGLWEAutomorphismKey::encrypt_sk_scratch_space(module, n, basek, k_apply, rank)
| GGLWEAutomorphismKey::automorphism_inplace_scratch_space(module, n, basek, k_in, k_apply, digits, rank),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
// gglwe_{s1}(s0) = s0 -> s1
auto_key.encrypt_sk(
module,
p0,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
// gglwe_{s2}(s1) -> s1 -> s2
auto_key_apply.encrypt_sk(
module,
p1,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut auto_key_apply_prepared: GGLWEAutomorphismKeyPrepared<Vec<u8>, B> =
GGLWEAutomorphismKeyPrepared::alloc(module, n, basek, k_apply, rows_apply, digits, rank);
auto_key_apply_prepared.prepare(module, &auto_key_apply, scratch.borrow());
// gglwe_{s1}(s0) (x) gglwe_{s2}(s1) = gglwe_{s2}(s0)
auto_key.automorphism_inplace(module, &auto_key_apply_prepared, scratch.borrow());
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_in);
let mut sk_auto: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_auto.fill_zero(); // Necessary to avoid panic of unfilled sk
(0..rank).for_each(|i| {
module.vec_znx_automorphism(
module.galois_element_inv(p0 * p1),
&mut sk_auto.data.as_vec_znx_mut(),
i,
&sk.data.as_vec_znx(),
i,
);
});
let sk_auto_dft: GLWESecretPrepared<Vec<u8>, B> = sk_auto.prepare_alloc(module, scratch.borrow());
(0..auto_key.rank_in()).for_each(|col_i| {
(0..auto_key.rows()).for_each(|row_i| {
auto_key
.at(row_i, col_i)
.decrypt(module, &mut pt, &sk_auto_dft, scratch.borrow());
module.vec_znx_sub_scalar_inplace(
&mut pt.data,
0,
(digits_in - 1) + row_i * digits_in,
&sk.data,
col_i,
);
let noise_have: f64 = pt.data.std(basek, 0).log2();
let noise_want: f64 = log2_std_noise_gglwe_product(
n as f64,
basek * digits,
0.5,
0.5,
0f64,
sigma * sigma,
0f64,
rank as f64,
k_in,
k_apply,
);
assert!(
noise_have < noise_want + 0.5,
"{} {}",
noise_have,
noise_want
);
});
});
}

View File

@@ -0,0 +1,333 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApply, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare,
VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphism, VecZnxAutomorphismInplace,
VecZnxBigAddInplace, VecZnxBigAddSmallInplace, VecZnxBigAlloc, VecZnxBigAllocBytes, VecZnxBigNormalize,
VecZnxBigNormalizeTmpBytes, VecZnxCopy, VecZnxDftAddInplace, VecZnxDftAlloc, VecZnxDftAllocBytes, VecZnxDftCopy,
VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxDftToVecZnxBigTmpA, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree, VmpApply,
VmpApplyAdd, VmpApplyTmpBytes, VmpPMatAlloc, VmpPrepare,
},
layouts::{Backend, Module, ScalarZnx, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl, VecZnxBigAllocBytesImpl, VecZnxDftAllocBytesImpl,
},
source::Source,
};
use crate::{
layouts::{
GGLWEAutomorphismKey, GGLWETensorKey, GGSWCiphertext, GLWESecret,
prepared::{GGLWEAutomorphismKeyPrepared, GGLWETensorKeyPrepared, GLWESecretPrepared, Prepare, PrepareAlloc},
},
noise::noise_ggsw_keyswitch,
};
#[allow(clippy::too_many_arguments)]
pub fn test_ggsw_automorphism<B>(
p: i64,
module: &Module<B>,
basek: usize,
k_out: usize,
k_in: usize,
k_ksk: usize,
k_tsk: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxBigAlloc<B>
+ VecZnxDftAlloc<B>
+ VecZnxBigNormalizeTmpBytes
+ VecZnxDftToVecZnxBigTmpA<B>
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxAddScalarInplace
+ VecZnxCopy
+ VecZnxSubABInplace
+ VmpPMatAlloc<B>
+ VmpPrepare<B>
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftCopy<B>
+ VecZnxDftAddInplace<B>
+ VecZnxFillUniform
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpApply<B>
+ VecZnxSwithcDegree
+ VecZnxAutomorphismInplace
+ VecZnxAutomorphism,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>,
{
let n: usize = module.n();
let rows: usize = k_in.div_ceil(basek * digits);
let rows_in: usize = k_in.div_euclid(basek * digits);
let digits_in: usize = 1;
let mut ct_in: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_in, rows_in, digits_in, rank);
let mut ct_out: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_out, rows_in, digits_in, rank);
let mut tensor_key: GGLWETensorKey<Vec<u8>> = GGLWETensorKey::alloc(n, basek, k_tsk, rows, digits, rank);
let mut auto_key: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_ksk, rows, digits, rank);
let mut pt_scalar: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GGSWCiphertext::encrypt_sk_scratch_space(module, n, basek, k_in, rank)
| GGLWEAutomorphismKey::encrypt_sk_scratch_space(module, n, basek, k_ksk, rank)
| GGLWETensorKey::encrypt_sk_scratch_space(module, n, basek, k_tsk, rank)
| GGSWCiphertext::automorphism_scratch_space(
module, n, basek, k_out, k_in, k_ksk, digits, k_tsk, digits, rank,
),
);
let var_xs: f64 = 0.5;
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(var_xs, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
auto_key.encrypt_sk(
module,
p,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
tensor_key.encrypt_sk(
module,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
pt_scalar.fill_ternary_hw(0, n, &mut source_xs);
ct_in.encrypt_sk(
module,
&pt_scalar,
&sk_prepared,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut auto_key_prepared: GGLWEAutomorphismKeyPrepared<Vec<u8>, B> =
GGLWEAutomorphismKeyPrepared::alloc(module, n, basek, k_ksk, rows, digits, rank);
auto_key_prepared.prepare(module, &auto_key, scratch.borrow());
let mut tsk_prepared: GGLWETensorKeyPrepared<Vec<u8>, B> =
GGLWETensorKeyPrepared::alloc(module, n, basek, k_tsk, rows, digits, rank);
tsk_prepared.prepare(module, &tensor_key, scratch.borrow());
ct_out.automorphism(
module,
&ct_in,
&auto_key_prepared,
&tsk_prepared,
scratch.borrow(),
);
module.vec_znx_automorphism_inplace(p, &mut pt_scalar.as_vec_znx_mut(), 0);
let max_noise = |col_j: usize| -> f64 {
noise_ggsw_keyswitch(
n as f64,
basek * digits,
col_j,
var_xs,
0f64,
sigma * sigma,
0f64,
rank as f64,
k_in,
k_ksk,
k_tsk,
) + 0.5
};
ct_out.assert_noise(module, &sk_prepared, &pt_scalar, max_noise);
}
#[allow(clippy::too_many_arguments)]
pub fn test_ggsw_automorphism_inplace<B>(
p: i64,
module: &Module<B>,
basek: usize,
k_ct: usize,
k_ksk: usize,
k_tsk: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxBigAlloc<B>
+ VecZnxDftAlloc<B>
+ VecZnxBigNormalizeTmpBytes
+ VecZnxDftToVecZnxBigTmpA<B>
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxAddScalarInplace
+ VecZnxCopy
+ VecZnxSubABInplace
+ VmpPMatAlloc<B>
+ VmpPrepare<B>
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxDftCopy<B>
+ VecZnxDftAddInplace<B>
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ VecZnxFillUniform
+ SvpApply<B>
+ VecZnxSwithcDegree
+ VecZnxAutomorphismInplace
+ VecZnxAutomorphism,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>,
{
let n: usize = module.n();
let rows: usize = k_ct.div_ceil(digits * basek);
let rows_in: usize = k_ct.div_euclid(basek * digits);
let digits_in: usize = 1;
let mut ct: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_ct, rows_in, digits_in, rank);
let mut tensor_key: GGLWETensorKey<Vec<u8>> = GGLWETensorKey::alloc(n, basek, k_tsk, rows, digits, rank);
let mut auto_key: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_ksk, rows, digits, rank);
let mut pt_scalar: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GGSWCiphertext::encrypt_sk_scratch_space(module, n, basek, k_ct, rank)
| GGLWEAutomorphismKey::encrypt_sk_scratch_space(module, n, basek, k_ksk, rank)
| GGLWETensorKey::encrypt_sk_scratch_space(module, n, basek, k_tsk, rank)
| GGSWCiphertext::automorphism_inplace_scratch_space(module, n, basek, k_ct, k_ksk, digits, k_tsk, digits, rank),
);
let var_xs: f64 = 0.5;
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(var_xs, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
auto_key.encrypt_sk(
module,
p,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
tensor_key.encrypt_sk(
module,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
pt_scalar.fill_ternary_hw(0, n, &mut source_xs);
ct.encrypt_sk(
module,
&pt_scalar,
&sk_prepared,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut auto_key_prepared: GGLWEAutomorphismKeyPrepared<Vec<u8>, B> =
GGLWEAutomorphismKeyPrepared::alloc(module, n, basek, k_ksk, rows, digits, rank);
auto_key_prepared.prepare(module, &auto_key, scratch.borrow());
let mut tsk_prepared: GGLWETensorKeyPrepared<Vec<u8>, B> =
GGLWETensorKeyPrepared::alloc(module, n, basek, k_tsk, rows, digits, rank);
tsk_prepared.prepare(module, &tensor_key, scratch.borrow());
ct.automorphism_inplace(module, &auto_key_prepared, &tsk_prepared, scratch.borrow());
module.vec_znx_automorphism_inplace(p, &mut pt_scalar.as_vec_znx_mut(), 0);
let max_noise = |col_j: usize| -> f64 {
noise_ggsw_keyswitch(
n as f64,
basek * digits,
col_j,
var_xs,
0f64,
sigma * sigma,
0f64,
rank as f64,
k_ct,
k_ksk,
k_tsk,
) + 0.5
};
ct.assert_noise(module, &sk_prepared, &pt_scalar, max_noise);
}

View File

@@ -0,0 +1,271 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, VecZnxAddInplace,
VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphism, VecZnxAutomorphismInplace, VecZnxBigAddInplace,
VecZnxBigAddSmallInplace, VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxDftAllocBytes,
VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize, VecZnxNormalizeInplace,
VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree, VmpApply, VmpApplyAdd, VmpApplyTmpBytes,
VmpPMatAlloc, VmpPrepare,
},
layouts::{Backend, Module, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl,
},
source::Source,
};
use crate::{
layouts::{
GGLWEAutomorphismKey, GLWECiphertext, GLWEPlaintext, GLWESecret, Infos,
prepared::{GGLWEAutomorphismKeyPrepared, GLWESecretPrepared, Prepare, PrepareAlloc},
},
noise::log2_std_noise_gglwe_product,
};
#[allow(clippy::too_many_arguments)]
pub fn test_glwe_automorphism<B>(
module: &Module<B>,
basek: usize,
p: i64,
k_out: usize,
k_in: usize,
k_ksk: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxAutomorphism
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ VecZnxAutomorphismInplace
+ VmpPMatAlloc<B>
+ VmpPrepare<B>,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>,
{
let n: usize = module.n();
let rows: usize = k_in.div_ceil(basek * digits);
let mut autokey: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_ksk, rows, digits, rank);
let mut ct_in: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_in, rank);
let mut ct_out: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_out, rank);
let mut pt_want: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_in);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
module.vec_znx_fill_uniform(basek, &mut pt_want.data, 0, k_in, &mut source_xa);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GGLWEAutomorphismKey::encrypt_sk_scratch_space(module, n, basek, autokey.k(), rank)
| GLWECiphertext::decrypt_scratch_space(module, n, basek, ct_out.k())
| GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, ct_in.k())
| GLWECiphertext::automorphism_scratch_space(
module,
n,
basek,
ct_out.k(),
ct_in.k(),
autokey.k(),
digits,
rank,
),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
autokey.encrypt_sk(
module,
p,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ct_in.encrypt_sk(
module,
&pt_want,
&sk_prepared,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut autokey_prepared: GGLWEAutomorphismKeyPrepared<Vec<u8>, B> =
GGLWEAutomorphismKeyPrepared::alloc(module, n, basek, k_ksk, rows, digits, rank);
autokey_prepared.prepare(module, &autokey, scratch.borrow());
ct_out.automorphism(module, &ct_in, &autokey_prepared, scratch.borrow());
let max_noise: f64 = log2_std_noise_gglwe_product(
module.n() as f64,
basek * digits,
0.5,
0.5,
0f64,
sigma * sigma,
0f64,
rank as f64,
k_in,
k_ksk,
);
module.vec_znx_automorphism_inplace(p, &mut pt_want.data, 0);
ct_out.assert_noise(module, &sk_prepared, &pt_want, max_noise + 1.0);
}
#[allow(clippy::too_many_arguments)]
pub fn test_glwe_automorphism_inplace<B>(
module: &Module<B>,
basek: usize,
p: i64,
k_ct: usize,
k_ksk: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxAutomorphism
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ VecZnxAutomorphismInplace
+ VmpPMatAlloc<B>
+ VmpPrepare<B>,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>,
{
let n: usize = module.n();
let rows: usize = k_ct.div_ceil(basek * digits);
let mut autokey: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_ksk, rows, digits, rank);
let mut ct: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_ct, rank);
let mut pt_want: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_ct);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
module.vec_znx_fill_uniform(basek, &mut pt_want.data, 0, k_ct, &mut source_xa);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GGLWEAutomorphismKey::encrypt_sk_scratch_space(module, n, basek, autokey.k(), rank)
| GLWECiphertext::decrypt_scratch_space(module, n, basek, ct.k())
| GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, ct.k())
| GLWECiphertext::automorphism_inplace_scratch_space(module, n, basek, ct.k(), autokey.k(), digits, rank),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
autokey.encrypt_sk(
module,
p,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ct.encrypt_sk(
module,
&pt_want,
&sk_prepared,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut autokey_prepared: GGLWEAutomorphismKeyPrepared<Vec<u8>, B> =
GGLWEAutomorphismKeyPrepared::alloc(module, n, basek, k_ksk, rows, digits, rank);
autokey_prepared.prepare(module, &autokey, scratch.borrow());
ct.automorphism_inplace(module, &autokey_prepared, scratch.borrow());
let max_noise: f64 = log2_std_noise_gglwe_product(
module.n() as f64,
basek * digits,
0.5,
0.5,
0f64,
sigma * sigma,
0f64,
rank as f64,
k_ct,
k_ksk,
);
module.vec_znx_automorphism_inplace(p, &mut pt_want.data, 0);
ct.assert_noise(module, &sk_prepared, &pt_want, max_noise + 1.0);
}

View File

@@ -0,0 +1,7 @@
mod gglwe_atk;
mod ggsw_ct;
mod glwe_ct;
pub use gglwe_atk::*;
pub use ggsw_ct::*;
pub use glwe_ct::*;

View File

@@ -0,0 +1,244 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, VecZnxAddInplace,
VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphismInplace, VecZnxBigAddInplace, VecZnxBigAddSmallInplace,
VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxDftAllocBytes, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes,
VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, VmpPMatAlloc, VmpPrepare,
ZnxView,
},
layouts::{Backend, Module, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl,
},
source::Source,
};
use crate::layouts::{
GLWECiphertext, GLWEPlaintext, GLWESecret, GLWEToLWESwitchingKey, Infos, LWECiphertext, LWEPlaintext, LWESecret,
LWEToGLWESwitchingKey,
prepared::{GLWESecretPrepared, GLWEToLWESwitchingKeyPrepared, LWEToGLWESwitchingKeyPrepared, PrepareAlloc},
};
pub fn test_lwe_to_glwe<B>(module: &Module<B>)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxAddScalarInplace
+ VmpPMatAlloc<B>
+ VmpPrepare<B>
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxBigNormalizeTmpBytes
+ VecZnxSwithcDegree
+ VecZnxAutomorphismInplace,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>,
{
let n: usize = module.n();
let basek: usize = 17;
let sigma: f64 = 3.2;
let rank: usize = 2;
let n_lwe: usize = 22;
let k_lwe_ct: usize = 2 * basek;
let k_lwe_pt: usize = 8;
let k_glwe_ct: usize = 3 * basek;
let k_ksk: usize = k_lwe_ct + basek;
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
LWEToGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k_ksk, rank)
| GLWECiphertext::from_lwe_scratch_space(module, n, basek, k_lwe_ct, k_glwe_ct, k_ksk, rank)
| GLWECiphertext::decrypt_scratch_space(module, n, basek, k_glwe_ct),
);
let mut sk_glwe: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_glwe.fill_ternary_prob(0.5, &mut source_xs);
let sk_glwe_prepared: GLWESecretPrepared<Vec<u8>, B> = sk_glwe.prepare_alloc(module, scratch.borrow());
let mut sk_lwe: LWESecret<Vec<u8>> = LWESecret::alloc(n_lwe);
sk_lwe.fill_ternary_prob(0.5, &mut source_xs);
let data: i64 = 17;
let mut lwe_pt: LWEPlaintext<Vec<u8>> = LWEPlaintext::alloc(basek, k_lwe_pt);
lwe_pt.encode_i64(data, k_lwe_pt);
let mut lwe_ct: LWECiphertext<Vec<u8>> = LWECiphertext::alloc(n_lwe, basek, k_lwe_ct);
lwe_ct.encrypt_sk(
module,
&lwe_pt,
&sk_lwe,
&mut source_xa,
&mut source_xe,
sigma,
);
let mut ksk: LWEToGLWESwitchingKey<Vec<u8>> = LWEToGLWESwitchingKey::alloc(n, basek, k_ksk, lwe_ct.size(), rank);
ksk.encrypt_sk(
module,
&sk_lwe,
&sk_glwe,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut glwe_ct: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_glwe_ct, rank);
let ksk_prepared: LWEToGLWESwitchingKeyPrepared<Vec<u8>, B> = ksk.prepare_alloc(module, scratch.borrow());
glwe_ct.from_lwe(module, &lwe_ct, &ksk_prepared, scratch.borrow());
let mut glwe_pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_glwe_ct);
glwe_ct.decrypt(module, &mut glwe_pt, &sk_glwe_prepared, scratch.borrow());
assert_eq!(glwe_pt.data.at(0, 0)[0], lwe_pt.data.at(0, 0)[0]);
}
pub fn test_glwe_to_lwe<B>(module: &Module<B>)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxAddScalarInplace
+ VmpPMatAlloc<B>
+ VmpPrepare<B>
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxBigNormalizeTmpBytes
+ VecZnxSwithcDegree
+ VecZnxAutomorphismInplace,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>,
{
let n: usize = module.n();
let basek: usize = 17;
let sigma: f64 = 3.2;
let rank: usize = 2;
let n_lwe: usize = 22;
let k_lwe_ct: usize = 2 * basek;
let k_lwe_pt: usize = 8;
let k_glwe_ct: usize = 3 * basek;
let k_ksk: usize = k_lwe_ct + basek;
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
LWEToGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k_ksk, rank)
| LWECiphertext::from_glwe_scratch_space(module, n, basek, k_lwe_ct, k_glwe_ct, k_ksk, rank)
| GLWECiphertext::decrypt_scratch_space(module, n, basek, k_glwe_ct),
);
let mut sk_glwe: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_glwe.fill_ternary_prob(0.5, &mut source_xs);
let sk_glwe_prepared: GLWESecretPrepared<Vec<u8>, B> = sk_glwe.prepare_alloc(module, scratch.borrow());
let mut sk_lwe = LWESecret::alloc(n_lwe);
sk_lwe.fill_ternary_prob(0.5, &mut source_xs);
let data: i64 = 17;
let mut glwe_pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_glwe_ct);
glwe_pt.encode_coeff_i64(data, k_lwe_pt, 0);
let mut glwe_ct = GLWECiphertext::alloc(n, basek, k_glwe_ct, rank);
glwe_ct.encrypt_sk(
module,
&glwe_pt,
&sk_glwe_prepared,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut ksk: GLWEToLWESwitchingKey<Vec<u8>> = GLWEToLWESwitchingKey::alloc(n, basek, k_ksk, glwe_ct.size(), rank);
ksk.encrypt_sk(
module,
&sk_lwe,
&sk_glwe,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut lwe_ct: LWECiphertext<Vec<u8>> = LWECiphertext::alloc(n_lwe, basek, k_lwe_ct);
let ksk_prepared: GLWEToLWESwitchingKeyPrepared<Vec<u8>, B> = ksk.prepare_alloc(module, scratch.borrow());
lwe_ct.from_glwe(module, &glwe_ct, &ksk_prepared, scratch.borrow());
let mut lwe_pt: LWEPlaintext<Vec<u8>> = LWEPlaintext::alloc(basek, k_lwe_ct);
lwe_ct.decrypt(module, &mut lwe_pt, &sk_lwe);
assert_eq!(glwe_pt.data.at(0, 0)[0], lwe_pt.data.at(0, 0)[0]);
}

View File

@@ -0,0 +1,215 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, VecZnxAddInplace,
VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphism, VecZnxAutomorphismInplace, VecZnxBigAddInplace,
VecZnxBigAddSmallInplace, VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxCopy,
VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSubScalarInplace,
VecZnxSwithcDegree, VmpApply, VmpApplyAdd, VmpApplyTmpBytes, VmpPMatAlloc, VmpPrepare,
},
layouts::{Backend, Module, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl,
},
source::Source,
};
use crate::layouts::{
GGLWEAutomorphismKey, GLWESecret,
compressed::{Decompress, GGLWEAutomorphismKeyCompressed},
prepared::{GLWESecretPrepared, PrepareAlloc},
};
pub fn test_gglwe_automorphisk_key_encrypt_sk<B>(
module: &Module<B>,
basek: usize,
k_ksk: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxAutomorphism
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ VecZnxAutomorphismInplace
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxSubScalarInplace
+ VecZnxCopy
+ VmpPMatAlloc<B>
+ VmpPrepare<B>,
B: Backend
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxImpl<B>
+ TakeSvpPPolImpl<B>
+ TakeVecZnxBigImpl<B>,
{
let n: usize = module.n();
let rows: usize = (k_ksk - digits * basek) / (digits * basek);
let mut atk: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_ksk, rows, digits, rank);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GGLWEAutomorphismKey::encrypt_sk_scratch_space(
module, n, basek, k_ksk, rank,
));
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let p = -5;
atk.encrypt_sk(
module,
p,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut sk_out: GLWESecret<Vec<u8>> = sk.clone();
(0..atk.rank()).for_each(|i| {
module.vec_znx_automorphism(
module.galois_element_inv(p),
&mut sk_out.data.as_vec_znx_mut(),
i,
&sk.data.as_vec_znx(),
i,
);
});
let sk_out_prepared: GLWESecretPrepared<Vec<u8>, B> = sk_out.prepare_alloc(module, scratch.borrow());
atk.key
.key
.assert_noise(module, &sk_out_prepared, &sk.data, sigma);
}
pub fn test_gglwe_automorphisk_key_compressed_encrypt_sk<B>(
module: &Module<B>,
basek: usize,
k_ksk: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxAutomorphism
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ VecZnxAutomorphismInplace
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxSubScalarInplace
+ VecZnxCopy
+ VmpPMatAlloc<B>
+ VmpPrepare<B>,
B: Backend
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxImpl<B>
+ TakeSvpPPolImpl<B>
+ TakeVecZnxBigImpl<B>,
{
let n: usize = module.n();
let rows: usize = (k_ksk - digits * basek) / (digits * basek);
let mut atk_compressed: GGLWEAutomorphismKeyCompressed<Vec<u8>> =
GGLWEAutomorphismKeyCompressed::alloc(n, basek, k_ksk, rows, digits, rank);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GGLWEAutomorphismKey::encrypt_sk_scratch_space(
module, n, basek, k_ksk, rank,
));
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let p = -5;
let seed_xa: [u8; 32] = [1u8; 32];
atk_compressed.encrypt_sk(
module,
p,
&sk,
seed_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut sk_out: GLWESecret<Vec<u8>> = sk.clone();
(0..atk_compressed.rank()).for_each(|i| {
module.vec_znx_automorphism(
module.galois_element_inv(p),
&mut sk_out.data.as_vec_znx_mut(),
i,
&sk.data.as_vec_znx(),
i,
);
});
let sk_out_prepared = sk_out.prepare_alloc(module, scratch.borrow());
let mut atk: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_ksk, rows, digits, rank);
atk.decompress(module, &atk_compressed);
atk.key
.key
.assert_noise(module, &sk_out_prepared, &sk.data, sigma);
}

View File

@@ -0,0 +1,186 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, VecZnxAddInplace,
VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxBigAddInplace, VecZnxBigAddSmallInplace, VecZnxBigAllocBytes,
VecZnxBigNormalize, VecZnxCopy, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform,
VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSubScalarInplace,
VecZnxSwithcDegree, VmpPMatAlloc, VmpPrepare,
},
layouts::{Backend, Module, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl, VecZnxBigAllocBytesImpl, VecZnxDftAllocBytesImpl,
},
source::Source,
};
use crate::layouts::{
GGLWESwitchingKey, GLWESecret,
compressed::{Decompress, GGLWESwitchingKeyCompressed},
prepared::{GLWESecretPrepared, PrepareAlloc},
};
pub fn test_gglwe_switching_key_encrypt_sk<B>(
module: &Module<B>,
basek: usize,
k_ksk: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
sigma: f64,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxSubScalarInplace
+ VecZnxCopy
+ VmpPMatAlloc<B>
+ VmpPrepare<B>,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>,
{
let n: usize = module.n();
let rows: usize = (k_ksk - digits * basek) / (digits * basek);
let mut ksk: GGLWESwitchingKey<Vec<u8>> = GGLWESwitchingKey::alloc(n, basek, k_ksk, rows, digits, rank_in, rank_out);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GGLWESwitchingKey::encrypt_sk_scratch_space(
module, n, basek, k_ksk, rank_in, rank_out,
));
let mut sk_in: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_in);
sk_in.fill_ternary_prob(0.5, &mut source_xs);
let mut sk_out: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_out);
sk_out.fill_ternary_prob(0.5, &mut source_xs);
let sk_out_prepared: GLWESecretPrepared<Vec<u8>, B> = sk_out.prepare_alloc(module, scratch.borrow());
ksk.encrypt_sk(
module,
&sk_in,
&sk_out,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ksk.key
.assert_noise(module, &sk_out_prepared, &sk_in.data, sigma);
}
pub fn test_gglwe_switching_key_compressed_encrypt_sk<B>(
module: &Module<B>,
basek: usize,
k_ksk: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
sigma: f64,
) where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxSubScalarInplace
+ VecZnxCopy
+ VmpPMatAlloc<B>
+ VmpPrepare<B>,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>,
{
let n: usize = module.n();
let rows: usize = (k_ksk - digits * basek) / (digits * basek);
let mut ksk_compressed: GGLWESwitchingKeyCompressed<Vec<u8>> =
GGLWESwitchingKeyCompressed::alloc(n, basek, k_ksk, rows, digits, rank_in, rank_out);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GGLWESwitchingKeyCompressed::encrypt_sk_scratch_space(
module, n, basek, k_ksk, rank_in, rank_out,
));
let mut sk_in: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_in);
sk_in.fill_ternary_prob(0.5, &mut source_xs);
let mut sk_out: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_out);
sk_out.fill_ternary_prob(0.5, &mut source_xs);
let sk_out_prepared: GLWESecretPrepared<Vec<u8>, B> = sk_out.prepare_alloc(module, scratch.borrow());
let seed_xa = [1u8; 32];
ksk_compressed.encrypt_sk(
module,
&sk_in,
&sk_out,
seed_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut ksk: GGLWESwitchingKey<Vec<u8>> = GGLWESwitchingKey::alloc(n, basek, k_ksk, rows, digits, rank_in, rank_out);
ksk.decompress(module, &ksk_compressed);
ksk.key
.assert_noise(module, &sk_out_prepared, &sk_in.data, sigma);
}

View File

@@ -0,0 +1,180 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, VecZnxAddInplace,
VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxBigAddInplace, VecZnxBigAddSmallInplace, VecZnxBigAlloc,
VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxCopy, VecZnxDftAlloc, VecZnxDftAllocBytes,
VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxDftToVecZnxBigTmpA, VecZnxFillUniform, VecZnxNormalize,
VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VmpPMatAlloc, VmpPrepare,
},
layouts::{Backend, Module, ScalarZnx, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl, VecZnxBigAllocBytesImpl, VecZnxDftAllocBytesImpl,
},
source::Source,
};
use crate::layouts::{
GGSWCiphertext, GLWESecret,
compressed::{Decompress, GGSWCiphertextCompressed},
prepared::{GLWESecretPrepared, PrepareAlloc},
};
pub fn test_ggsw_encrypt_sk<B>(module: &Module<B>, basek: usize, k: usize, digits: usize, rank: usize, sigma: f64)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxAddScalarInplace
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxCopy
+ VmpPMatAlloc<B>
+ VmpPrepare<B>
+ VecZnxBigAlloc<B>
+ VecZnxDftAlloc<B>
+ VecZnxBigNormalizeTmpBytes
+ VecZnxDftToVecZnxBigTmpA<B>,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>,
{
let n: usize = module.n();
let rows: usize = (k - digits * basek) / (digits * basek);
let mut ct: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k, rows, digits, rank);
let mut pt_scalar: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
pt_scalar.fill_ternary_hw(0, n, &mut source_xs);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GGSWCiphertext::encrypt_sk_scratch_space(
module, n, basek, k, rank,
));
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
ct.encrypt_sk(
module,
&pt_scalar,
&sk_prepared,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let noise_f = |_col_i: usize| -(k as f64) + sigma.log2() + 0.5;
ct.assert_noise(module, &sk_prepared, &pt_scalar, noise_f);
}
pub fn test_ggsw_compressed_encrypt_sk<B>(module: &Module<B>, basek: usize, k: usize, digits: usize, rank: usize, sigma: f64)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxAddScalarInplace
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxCopy
+ VmpPMatAlloc<B>
+ VmpPrepare<B>
+ VecZnxBigAlloc<B>
+ VecZnxDftAlloc<B>
+ VecZnxBigNormalizeTmpBytes
+ VecZnxDftToVecZnxBigTmpA<B>,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>,
{
let n: usize = module.n();
let rows: usize = (k - digits * basek) / (digits * basek);
let mut ct_compressed: GGSWCiphertextCompressed<Vec<u8>> = GGSWCiphertextCompressed::alloc(n, basek, k, rows, digits, rank);
let mut pt_scalar: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
pt_scalar.fill_ternary_hw(0, n, &mut source_xs);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GGSWCiphertextCompressed::encrypt_sk_scratch_space(
module, n, basek, k, rank,
));
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
let seed_xa: [u8; 32] = [1u8; 32];
ct_compressed.encrypt_sk(
module,
&pt_scalar,
&sk_prepared,
seed_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let noise_f = |_col_i: usize| -(k as f64) + sigma.log2() + 0.5;
let mut ct: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k, rows, digits, rank);
ct.decompress(module, &ct_compressed);
ct.assert_noise(module, &sk_prepared, &pt_scalar, noise_f);
}

View File

@@ -0,0 +1,375 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApply, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare,
VecZnxAddInplace, VecZnxAddNormal, VecZnxBigAddInplace, VecZnxBigAddNormal, VecZnxBigAddSmallInplace,
VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxCopy, VecZnxDftAlloc, VecZnxDftAllocBytes, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes,
VecZnxSub, VecZnxSubABInplace,
},
layouts::{Backend, Module, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl,
},
source::Source,
};
use crate::{
layouts::{
GLWECiphertext, GLWEPlaintext, GLWEPublicKey, GLWESecret, Infos,
compressed::{Decompress, GLWECiphertextCompressed},
prepared::{GLWEPublicKeyPrepared, GLWESecretPrepared, PrepareAlloc},
},
operations::GLWEOperations,
};
pub fn test_glwe_encrypt_sk<B>(module: &Module<B>, basek: usize, k_ct: usize, k_pt: usize, sigma: f64, rank: usize)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ SvpPPolAllocBytes
+ SvpPrepare<B>
+ SvpApply<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddNormal<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>,
{
let n = module.n();
let mut ct: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_ct, rank);
let mut pt_want: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_pt);
let mut pt_have: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_pt);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, ct.k())
| GLWECiphertext::decrypt_scratch_space(module, n, basek, ct.k()),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
module.vec_znx_fill_uniform(basek, &mut pt_want.data, 0, k_pt, &mut source_xa);
ct.encrypt_sk(
module,
&pt_want,
&sk_prepared,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ct.decrypt(module, &mut pt_have, &sk_prepared, scratch.borrow());
pt_want.sub_inplace_ab(module, &pt_have);
let noise_have: f64 = pt_want.data.std(basek, 0) * (ct.k() as f64).exp2();
let noise_want: f64 = sigma;
assert!(noise_have <= noise_want + 0.2);
}
pub fn test_glwe_compressed_encrypt_sk<B>(module: &Module<B>, basek: usize, k_ct: usize, k_pt: usize, sigma: f64, rank: usize)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ SvpPPolAllocBytes
+ SvpPrepare<B>
+ SvpApply<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddNormal<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ VecZnxCopy,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>,
{
let n = module.n();
let mut ct_compressed: GLWECiphertextCompressed<Vec<u8>> = GLWECiphertextCompressed::alloc(n, basek, k_ct, rank);
let mut pt_want: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_pt);
let mut pt_have: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_pt);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GLWECiphertextCompressed::encrypt_sk_scratch_space(module, n, basek, k_ct)
| GLWECiphertext::decrypt_scratch_space(module, n, basek, k_ct),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
module.vec_znx_fill_uniform(basek, &mut pt_want.data, 0, k_pt, &mut source_xa);
let seed_xa: [u8; 32] = [1u8; 32];
ct_compressed.encrypt_sk(
module,
&pt_want,
&sk_prepared,
seed_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut ct: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_ct, rank);
ct.decompress(module, &ct_compressed);
ct.decrypt(module, &mut pt_have, &sk_prepared, scratch.borrow());
pt_want.sub_inplace_ab(module, &pt_have);
let noise_have: f64 = pt_want.data.std(basek, 0) * (ct.k() as f64).exp2();
let noise_want: f64 = sigma;
assert!(
noise_have <= noise_want + 0.2,
"{} <= {}",
noise_have,
noise_want + 0.2
);
}
pub fn test_glwe_encrypt_zero_sk<B>(module: &Module<B>, basek: usize, k_ct: usize, sigma: f64, rank: usize)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ SvpPPolAllocBytes
+ SvpPrepare<B>
+ SvpApply<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddNormal<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>,
{
let n = module.n();
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_ct);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([1u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GLWECiphertext::decrypt_scratch_space(module, n, basek, k_ct)
| GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k_ct),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
let mut ct: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_ct, rank);
ct.encrypt_zero_sk(
module,
&sk_prepared,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ct.decrypt(module, &mut pt, &sk_prepared, scratch.borrow());
assert!((sigma - pt.data.std(basek, 0) * (k_ct as f64).exp2()) <= 0.2);
}
pub fn test_glwe_encrypt_pk<B>(module: &Module<B>, basek: usize, k_ct: usize, k_pk: usize, sigma: f64, rank: usize)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxCopy
+ VecZnxDftAlloc<B>
+ SvpApply<B>
+ VecZnxBigAddNormal<B>,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>,
{
let n: usize = module.n();
let mut ct: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_ct, rank);
let mut pt_have: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_ct);
let mut pt_want: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_ct);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut source_xu: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, ct.k())
| GLWECiphertext::decrypt_scratch_space(module, n, basek, ct.k())
| GLWECiphertext::encrypt_pk_scratch_space(module, n, basek, k_pk),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
let mut pk: GLWEPublicKey<Vec<u8>> = GLWEPublicKey::alloc(n, basek, k_pk, rank);
pk.generate_from_sk(module, &sk_prepared, &mut source_xa, &mut source_xe, sigma);
module.vec_znx_fill_uniform(basek, &mut pt_want.data, 0, k_ct, &mut source_xa);
let pk_prepared: GLWEPublicKeyPrepared<Vec<u8>, B> = pk.prepare_alloc(module, scratch.borrow());
ct.encrypt_pk(
module,
&pt_want,
&pk_prepared,
&mut source_xu,
&mut source_xe,
sigma,
scratch.borrow(),
);
ct.decrypt(module, &mut pt_have, &sk_prepared, scratch.borrow());
pt_want.sub_inplace_ab(module, &pt_have);
let noise_have: f64 = pt_want.data.std(basek, 0).log2();
let noise_want: f64 = ((((rank as f64) + 1.0) * n as f64 * 0.5 * sigma * sigma).sqrt()).log2() - (k_ct as f64);
assert!(
noise_have <= noise_want + 0.2,
"{} {}",
noise_have,
noise_want
);
}

View File

@@ -0,0 +1,248 @@
use poulpy_backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApply, SvpApplyInplace, SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare,
VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxBigAddInplace, VecZnxBigAddSmallInplace, VecZnxBigAlloc,
VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxCopy, VecZnxDftAlloc, VecZnxDftAllocBytes, VecZnxDftFromVecZnx,
VecZnxDftToVecZnxBigConsume, VecZnxDftToVecZnxBigTmpA, VecZnxFillUniform, VecZnxNormalize, VecZnxNormalizeInplace,
VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSubScalarInplace, VecZnxSwithcDegree,
},
layouts::{Backend, Module, ScratchOwned, VecZnxDft},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl, VecZnxBigAllocBytesImpl, VecZnxDftAllocBytesImpl,
},
source::Source,
};
use crate::layouts::{
GGLWETensorKey, GLWEPlaintext, GLWESecret, Infos,
compressed::{Decompress, GGLWETensorKeyCompressed},
prepared::{GLWESecretPrepared, PrepareAlloc},
};
pub fn test_glwe_tensor_key_encrypt_sk<B>(module: &Module<B>, basek: usize, k: usize, sigma: f64, rank: usize)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxCopy
+ VecZnxDftAlloc<B>
+ SvpApply<B>
+ VecZnxBigAlloc<B>
+ VecZnxDftToVecZnxBigTmpA<B>
+ VecZnxAddScalarInplace
+ VecZnxSwithcDegree
+ VecZnxSubScalarInplace,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>,
{
let n: usize = module.n();
let rows: usize = k / basek;
let mut tensor_key: GGLWETensorKey<Vec<u8>> = GGLWETensorKey::alloc(n, basek, k, rows, 1, rank);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut source_xa: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GGLWETensorKey::encrypt_sk_scratch_space(
module,
n,
basek,
tensor_key.k(),
rank,
));
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
tensor_key.encrypt_sk(
module,
&sk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k);
let mut sk_ij_dft = module.vec_znx_dft_alloc(n, 1, 1);
let mut sk_ij_big = module.vec_znx_big_alloc(n, 1, 1);
let mut sk_ij: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, 1);
let mut sk_dft: VecZnxDft<Vec<u8>, B> = module.vec_znx_dft_alloc(n, rank, 1);
(0..rank).for_each(|i| {
module.vec_znx_dft_from_vec_znx(1, 0, &mut sk_dft, i, &sk.data.as_vec_znx(), i);
});
(0..rank).for_each(|i| {
(0..rank).for_each(|j| {
module.svp_apply(&mut sk_ij_dft, 0, &sk_prepared.data, j, &sk_dft, i);
module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut sk_ij_big, 0, &mut sk_ij_dft, 0);
module.vec_znx_big_normalize(
basek,
&mut sk_ij.data.as_vec_znx_mut(),
0,
&sk_ij_big,
0,
scratch.borrow(),
);
(0..tensor_key.rank_in()).for_each(|col_i| {
(0..tensor_key.rows()).for_each(|row_i| {
tensor_key
.at(i, j)
.at(row_i, col_i)
.decrypt(module, &mut pt, &sk_prepared, scratch.borrow());
module.vec_znx_sub_scalar_inplace(&mut pt.data, 0, row_i, &sk_ij.data, col_i);
let std_pt: f64 = pt.data.std(basek, 0) * (k as f64).exp2();
assert!((sigma - std_pt).abs() <= 0.5, "{} {}", sigma, std_pt);
});
});
})
})
}
pub fn test_glwe_tensor_key_compressed_encrypt_sk<B>(module: &Module<B>, basek: usize, k: usize, sigma: f64, rank: usize)
where
Module<B>: VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub
+ SvpPrepare<B>
+ SvpPPolAllocBytes
+ SvpPPolAlloc<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigAllocBytes
+ VecZnxBigAddInplace<B>
+ VecZnxCopy
+ VecZnxDftAlloc<B>
+ SvpApply<B>
+ VecZnxBigAlloc<B>
+ VecZnxDftToVecZnxBigTmpA<B>
+ VecZnxAddScalarInplace
+ VecZnxSwithcDegree
+ VecZnxSubScalarInplace,
B: Backend
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>,
{
let n: usize = module.n();
let rows: usize = k / basek;
let mut tensor_key_compressed: GGLWETensorKeyCompressed<Vec<u8>> =
GGLWETensorKeyCompressed::alloc(n, basek, k, rows, 1, rank);
let mut source_xs: Source = Source::new([0u8; 32]);
let mut source_xe: Source = Source::new([0u8; 32]);
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(GGLWETensorKeyCompressed::encrypt_sk_scratch_space(
module,
n,
basek,
tensor_key_compressed.k(),
rank,
));
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_prepared: GLWESecretPrepared<Vec<u8>, B> = sk.prepare_alloc(module, scratch.borrow());
let seed_xa: [u8; 32] = [1u8; 32];
tensor_key_compressed.encrypt_sk(
module,
&sk,
seed_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut tensor_key: GGLWETensorKey<Vec<u8>> = GGLWETensorKey::alloc(n, basek, k, rows, 1, rank);
tensor_key.decompress(module, &tensor_key_compressed);
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k);
let mut sk_ij_dft = module.vec_znx_dft_alloc(n, 1, 1);
let mut sk_ij_big = module.vec_znx_big_alloc(n, 1, 1);
let mut sk_ij: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, 1);
let mut sk_dft: VecZnxDft<Vec<u8>, B> = module.vec_znx_dft_alloc(n, rank, 1);
(0..rank).for_each(|i| {
module.vec_znx_dft_from_vec_znx(1, 0, &mut sk_dft, i, &sk.data.as_vec_znx(), i);
});
(0..rank).for_each(|i| {
(0..rank).for_each(|j| {
module.svp_apply(&mut sk_ij_dft, 0, &sk_prepared.data, j, &sk_dft, i);
module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut sk_ij_big, 0, &mut sk_ij_dft, 0);
module.vec_znx_big_normalize(
basek,
&mut sk_ij.data.as_vec_znx_mut(),
0,
&sk_ij_big,
0,
scratch.borrow(),
);
(0..tensor_key.rank_in()).for_each(|col_i| {
(0..tensor_key.rows()).for_each(|row_i| {
tensor_key
.at(i, j)
.at(row_i, col_i)
.decrypt(module, &mut pt, &sk_prepared, scratch.borrow());
module.vec_znx_sub_scalar_inplace(&mut pt.data, 0, row_i, &sk_ij.data, col_i);
let std_pt: f64 = pt.data.std(basek, 0) * (k as f64).exp2();
assert!((sigma - std_pt).abs() <= 0.5, "{} {}", sigma, std_pt);
});
});
})
})
}

Some files were not shown because too many files have changed in this diff Show More