core refactoring (#69)

This commit is contained in:
Jean-Philippe Bossuat
2025-08-14 17:20:28 +02:00
committed by GitHub
parent 6303346eef
commit 8d9897b88b
167 changed files with 7972 additions and 6821 deletions

View File

@@ -1,4 +1,4 @@
use core::{GGSWCiphertext, GGSWCiphertextExec, GLWECiphertext, GLWESecret, GLWESecretExec, Infos};
use core::layouts::{prepared::{GGSWCiphertextExec, GLWESecretExec}, GGSWCiphertext, GLWECiphertext, GLWESecret, Infos};
use std::hint::black_box;
use backend::{

View File

@@ -1,7 +1,4 @@
use core::{
AutomorphismKey, AutomorphismKeyExec, GLWECiphertext, GLWESecret, GLWESecretExec, GLWESwitchingKey, GLWESwitchingKeyExec,
Infos,
};
use core::layouts::{prepared::{GGLWEAutomorphismKeyExec, GGLWESwitchingKeyExec, GLWESecretExec}, GGLWEAutomorphismKey, GGLWESwitchingKey, GLWECiphertext, GLWESecret, Infos};
use std::{hint::black_box, time::Duration};
use backend::{
@@ -43,12 +40,12 @@ fn bench_keyswitch_glwe_fft64(c: &mut Criterion) {
let rows: usize = p.k_ct_in.div_ceil(p.basek * digits);
let sigma: f64 = 3.2;
let mut ksk: AutomorphismKey<Vec<u8>> = AutomorphismKey::alloc(n, basek, k_grlwe, rows, digits, rank_out);
let mut ksk: GGLWEAutomorphismKey<Vec<u8>> = GGLWEAutomorphismKey::alloc(n, basek, k_grlwe, rows, digits, rank_out);
let mut ct_in: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_rlwe_in, rank_in);
let mut ct_out: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_rlwe_out, rank_out);
let mut scratch: ScratchOwned<FFT64> = ScratchOwned::alloc(
GLWESwitchingKey::encrypt_sk_scratch_space(&module, n, basek, ksk.k(), rank_in, rank_out)
GGLWESwitchingKey::encrypt_sk_scratch_space(&module, n, basek, ksk.k(), rank_in, rank_out)
| GLWECiphertext::encrypt_sk_scratch_space(&module, n, basek, ct_in.k())
| GLWECiphertext::keyswitch_scratch_space(
&module,
@@ -93,7 +90,7 @@ fn bench_keyswitch_glwe_fft64(c: &mut Criterion) {
scratch.borrow(),
);
let ksk_exec: AutomorphismKeyExec<Vec<u8>, _> = AutomorphismKeyExec::from(&module, &ksk, scratch.borrow());
let ksk_exec: GGLWEAutomorphismKeyExec<Vec<u8>, _> = GGLWEAutomorphismKeyExec::from(&module, &ksk, scratch.borrow());
move || {
black_box(ct_out.automorphism(&module, &ct_in, &ksk_exec, scratch.borrow()));
@@ -149,11 +146,11 @@ fn bench_keyswitch_glwe_inplace_fft64(c: &mut Criterion) {
let rows: usize = p.k_ct.div_ceil(p.basek);
let sigma: f64 = 3.2;
let mut ksk: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::alloc(n, basek, k_ksk, rows, digits, rank, rank);
let mut ksk: GGLWESwitchingKey<Vec<u8>> = GGLWESwitchingKey::alloc(n, basek, k_ksk, rows, digits, rank, rank);
let mut ct: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_ct, rank);
let mut scratch: ScratchOwned<FFT64> = ScratchOwned::alloc(
GLWESwitchingKey::encrypt_sk_scratch_space(&module, n, basek, ksk.k(), rank, rank)
GGLWESwitchingKey::encrypt_sk_scratch_space(&module, n, basek, ksk.k(), rank, rank)
| GLWECiphertext::encrypt_sk_scratch_space(&module, n, basek, ct.k())
| GLWECiphertext::keyswitch_inplace_scratch_space(&module, n, basek, ct.k(), ksk.k(), digits, rank),
);
@@ -188,7 +185,7 @@ fn bench_keyswitch_glwe_inplace_fft64(c: &mut Criterion) {
scratch.borrow(),
);
let ksk_exec: GLWESwitchingKeyExec<Vec<u8>, FFT64> = GLWESwitchingKeyExec::from(&module, &ksk, scratch.borrow());
let ksk_exec: GGLWESwitchingKeyExec<Vec<u8>, FFT64> = GGLWESwitchingKeyExec::from(&module, &ksk, scratch.borrow());
move || {
black_box(ct.keyswitch_inplace(&module, &ksk_exec, scratch.borrow()));

View File

@@ -3,9 +3,12 @@ use backend::hal::{
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{AutomorphismKey, AutomorphismKeyExec, GLWECiphertext, GLWEKeyswitchFamily, Infos};
use crate::{
layouts::{GGLWEAutomorphismKey, GLWECiphertext, Infos, prepared::GGLWEAutomorphismKeyExec},
trait_families::GLWEKeyswitchFamily,
};
impl AutomorphismKey<Vec<u8>> {
impl GGLWEAutomorphismKey<Vec<u8>> {
pub fn automorphism_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
@@ -34,16 +37,16 @@ impl AutomorphismKey<Vec<u8>> {
where
Module<B>: GLWEKeyswitchFamily<B>,
{
AutomorphismKey::automorphism_scratch_space(module, n, basek, k_out, k_out, k_ksk, digits, rank)
GGLWEAutomorphismKey::automorphism_scratch_space(module, n, basek, k_out, k_out, k_ksk, digits, rank)
}
}
impl<DataSelf: DataMut> AutomorphismKey<DataSelf> {
impl<DataSelf: DataMut> GGLWEAutomorphismKey<DataSelf> {
pub fn automorphism<'a, DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &AutomorphismKey<DataLhs>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
lhs: &GGLWEAutomorphismKey<DataLhs>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxAutomorphism + VecZnxAutomorphismInplace,
@@ -117,14 +120,14 @@ impl<DataSelf: DataMut> AutomorphismKey<DataSelf> {
pub fn automorphism_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxAutomorphism + VecZnxAutomorphismInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
unsafe {
let self_ptr: *mut AutomorphismKey<DataSelf> = self as *mut AutomorphismKey<DataSelf>;
let self_ptr: *mut GGLWEAutomorphismKey<DataSelf> = self as *mut GGLWEAutomorphismKey<DataSelf>;
self.automorphism(&module, &*self_ptr, rhs, scratch);
}
}

View File

@@ -4,7 +4,11 @@ use backend::hal::{
};
use crate::{
AutomorphismKeyExec, GGSWCiphertext, GGSWKeySwitchFamily, GLWECiphertext, GLWEKeyswitchFamily, GLWETensorKeyExec, Infos,
layouts::{
GGSWCiphertext, GLWECiphertext, Infos,
prepared::{GGLWEAutomorphismKeyExec, GGLWETensorKeyExec},
},
trait_families::{GGSWKeySwitchFamily, GLWEKeyswitchFamily},
};
impl GGSWCiphertext<Vec<u8>> {
@@ -56,8 +60,8 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
&mut self,
module: &Module<B>,
lhs: &GGSWCiphertext<DataLhs>,
auto_key: &AutomorphismKeyExec<DataAk, B>,
tensor_key: &GLWETensorKeyExec<DataTsk, B>,
auto_key: &GGLWEAutomorphismKeyExec<DataAk, B>,
tensor_key: &GGLWETensorKeyExec<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + GGSWKeySwitchFamily<B> + VecZnxAutomorphismInplace + VecZnxNormalizeTmpBytes,
@@ -65,8 +69,6 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
{
#[cfg(debug_assertions)]
{
use crate::Infos;
assert_eq!(self.n(), auto_key.n());
assert_eq!(lhs.n(), auto_key.n());
@@ -115,8 +117,8 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
pub fn automorphism_inplace<DataKsk: DataRef, DataTsk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
auto_key: &AutomorphismKeyExec<DataKsk, B>,
tensor_key: &GLWETensorKeyExec<DataTsk, B>,
auto_key: &GGLWEAutomorphismKeyExec<DataKsk, B>,
tensor_key: &GGLWETensorKeyExec<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + GGSWKeySwitchFamily<B> + VecZnxAutomorphismInplace + VecZnxNormalizeTmpBytes,
@@ -132,7 +134,7 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
&mut self,
module: &Module<B>,
lhs: &GGSWCiphertext<DataLhs>,
auto_key: &AutomorphismKeyExec<DataAk, B>,
auto_key: &GGLWEAutomorphismKeyExec<DataAk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + GGSWKeySwitchFamily<B> + VecZnxAutomorphismInplace + VecZnxNormalizeTmpBytes,

View File

@@ -6,7 +6,10 @@ use backend::hal::{
layouts::{Backend, DataMut, DataRef, Module, Scratch, VecZnxBig},
};
use crate::{AutomorphismKeyExec, GLWECiphertext, GLWEKeyswitchFamily, Infos, glwe::keyswitch::keyswitch};
use crate::{
layouts::{GLWECiphertext, Infos, prepared::GGLWEAutomorphismKeyExec},
trait_families::GLWEKeyswitchFamily,
};
impl GLWECiphertext<Vec<u8>> {
pub fn automorphism_scratch_space<B: Backend>(
@@ -46,7 +49,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxAutomorphismInplace,
@@ -61,7 +64,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
pub fn automorphism_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxAutomorphismInplace,
@@ -77,7 +80,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxBigAutomorphismInplace<B>,
@@ -88,7 +91,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
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> = keyswitch(module, res_dft, lhs, &rhs.key, scratch1);
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);
@@ -99,7 +102,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
pub fn automorphism_add_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxBigAutomorphismInplace<B>,
@@ -115,7 +118,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxBigAutomorphismInplace<B> + VecZnxBigSubSmallAInplace<B>,
@@ -126,7 +129,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
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> = keyswitch(module, res_dft, lhs, &rhs.key, scratch1);
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);
@@ -137,7 +140,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
pub fn automorphism_sub_ab_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxBigAutomorphismInplace<B> + VecZnxBigSubSmallAInplace<B>,
@@ -153,7 +156,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxBigAutomorphismInplace<B> + VecZnxBigSubSmallBInplace<B>,
@@ -164,7 +167,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
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> = keyswitch(module, res_dft, lhs, &rhs.key, scratch1);
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);
@@ -175,7 +178,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
pub fn automorphism_sub_ba_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + VecZnxBigAutomorphismInplace<B> + VecZnxBigSubSmallBInplace<B>,

View File

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

View File

@@ -1,482 +0,0 @@
use backend::hal::{
api::{
ScratchAvailable, SvpApply, SvpPPolAllocBytes, TakeVecZnx, TakeVecZnxBig, TakeVecZnxDft, TakeVecZnxDftSlice,
TakeVecZnxSlice, VecZnxAddInplace, VecZnxBigAddSmallInplace, VecZnxBigAllocBytes, VecZnxBigNormalizeTmpBytes, VecZnxCopy,
VecZnxDftAdd, VecZnxDftAddInplace, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftSubABInplace, VecZnxDftToVecZnxBig,
VecZnxDftToVecZnxBigTmpBytes, VecZnxDftZero, VecZnxMulXpMinusOneInplace, VecZnxNormalize, VecZnxNormalizeInplace,
VecZnxRotate, VecZnxSubABInplace, VmpApplyTmpBytes, ZnxView, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch, SvpPPol, VecZnx},
};
use itertools::izip;
use crate::{
GLWECiphertext, GLWECiphertextToMut, GLWEExternalProductFamily, GLWEOps, Infos, LWECiphertext, LWECiphertextToRef,
LookUpTableRotationDirection, TakeGLWECt,
blind_rotation::{key::BlindRotationKeyCGGIExec, lut::LookUpTable},
dist::Distribution,
};
pub trait CCGIBlindRotationFamily<B: Backend> = VecZnxBigAllocBytes
+ VecZnxDftAllocBytes
+ SvpPPolAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VecZnxDftToVecZnxBigTmpBytes
+ VecZnxDftToVecZnxBig<B>
+ VecZnxDftAdd<B>
+ VecZnxDftAddInplace<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftZero<B>
+ SvpApply<B>
+ VecZnxDftSubABInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ GLWEExternalProductFamily<B>
+ VecZnxRotate
+ VecZnxAddInplace
+ VecZnxSubABInplace
+ VecZnxNormalize<B>
+ VecZnxNormalizeInplace<B>
+ VecZnxCopy
+ VecZnxMulXpMinusOneInplace;
pub fn cggi_blind_rotate_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
block_size: usize,
extension_factor: usize,
basek: usize,
k_res: usize,
k_brk: usize,
rows: usize,
rank: usize,
) -> usize
where
Module<B>: CCGIBlindRotationFamily<B>,
{
let brk_size: usize = k_brk.div_ceil(basek);
if block_size > 1 {
let cols: usize = rank + 1;
let acc_dft: usize = module.vec_znx_dft_alloc_bytes(n, cols, rows) * extension_factor;
let acc_big: usize = module.vec_znx_big_alloc_bytes(n, 1, brk_size);
let vmp_res: usize = module.vec_znx_dft_alloc_bytes(n, cols, brk_size) * extension_factor;
let vmp_xai: usize = module.vec_znx_dft_alloc_bytes(n, 1, brk_size);
let acc_dft_add: usize = vmp_res;
let vmp: usize = module.vmp_apply_tmp_bytes(n, brk_size, rows, rows, 2, 2, brk_size); // GGSW product: (1 x 2) x (2 x 2)
let acc: usize;
if extension_factor > 1 {
acc = VecZnx::alloc_bytes(n, cols, k_res.div_ceil(basek)) * extension_factor;
} else {
acc = 0;
}
return acc
+ acc_dft
+ acc_dft_add
+ vmp_res
+ vmp_xai
+ (vmp | (acc_big + (module.vec_znx_big_normalize_tmp_bytes(n) | module.vec_znx_dft_to_vec_znx_big_tmp_bytes(n))));
} else {
GLWECiphertext::bytes_of(n, basek, k_res, rank)
+ GLWECiphertext::external_product_scratch_space(module, n, basek, k_res, k_res, k_brk, 1, rank)
}
}
pub fn cggi_blind_rotate<DataRes, DataIn, DataBrk, B: Backend>(
module: &Module<B>,
res: &mut GLWECiphertext<DataRes>,
lwe: &LWECiphertext<DataIn>,
lut: &LookUpTable,
brk: &BlindRotationKeyCGGIExec<DataBrk, B>,
scratch: &mut Scratch<B>,
) where
DataRes: DataMut,
DataIn: DataRef,
DataBrk: DataRef,
Module<B>: CCGIBlindRotationFamily<B>,
Scratch<B>: TakeVecZnxDftSlice<B> + TakeVecZnxDft<B> + TakeVecZnxBig<B> + TakeVecZnx + ScratchAvailable + TakeVecZnxSlice,
{
match brk.dist {
Distribution::BinaryBlock(_) | Distribution::BinaryFixed(_) | Distribution::BinaryProb(_) | Distribution::ZERO => {
if lut.extension_factor() > 1 {
cggi_blind_rotate_block_binary_extended(module, res, lwe, lut, brk, scratch);
} else if brk.block_size() > 1 {
cggi_blind_rotate_block_binary(module, res, lwe, lut, brk, scratch);
} else {
cggi_blind_rotate_binary_standard(module, res, lwe, lut, brk, scratch);
}
}
// TODO: ternary distribution ?
_ => panic!(
"invalid BlindRotationKeyCGGI distribution: must be BinaryBlock, BinaryFixed or BinaryProb (or ZERO for debugging)"
),
}
}
pub(crate) fn cggi_blind_rotate_block_binary_extended<DataRes, DataIn, DataBrk, B: Backend>(
module: &Module<B>,
res: &mut GLWECiphertext<DataRes>,
lwe: &LWECiphertext<DataIn>,
lut: &LookUpTable,
brk: &BlindRotationKeyCGGIExec<DataBrk, B>,
scratch: &mut Scratch<B>,
) where
DataRes: DataMut,
DataIn: DataRef,
DataBrk: DataRef,
Module<B>: CCGIBlindRotationFamily<B>,
Scratch<B>: TakeVecZnxDftSlice<B> + TakeVecZnxDft<B> + TakeVecZnxBig<B> + TakeVecZnxSlice,
{
let n_glwe: usize = brk.n();
let extension_factor: usize = lut.extension_factor();
let basek: usize = res.basek();
let rows: usize = brk.rows();
let cols: usize = res.rank() + 1;
let (mut acc, scratch1) = scratch.take_vec_znx_slice(extension_factor, n_glwe, cols, res.size());
let (mut acc_dft, scratch2) = scratch1.take_vec_znx_dft_slice(extension_factor, n_glwe, cols, rows);
let (mut vmp_res, scratch3) = scratch2.take_vec_znx_dft_slice(extension_factor, n_glwe, cols, brk.size());
let (mut acc_add_dft, scratch4) = scratch3.take_vec_znx_dft_slice(extension_factor, n_glwe, cols, brk.size());
let (mut vmp_xai, scratch5) = scratch4.take_vec_znx_dft(n_glwe, 1, brk.size());
(0..extension_factor).for_each(|i| {
acc[i].zero();
});
let x_pow_a: &Vec<SvpPPol<Vec<u8>, B>>;
if let Some(b) = &brk.x_pow_a {
x_pow_a = b
} else {
panic!("invalid key: x_pow_a has not been initialized")
}
let mut lwe_2n: Vec<i64> = vec![0i64; lwe.n() + 1]; // TODO: from scratch space
let lwe_ref: LWECiphertext<&[u8]> = lwe.to_ref();
let two_n: usize = 2 * n_glwe;
let two_n_ext: usize = 2 * lut.domain_size();
mod_switch_2n(two_n_ext, &mut lwe_2n, &lwe_ref, lut.rotation_direction());
let a: &[i64] = &lwe_2n[1..];
let b_pos: usize = ((lwe_2n[0] + two_n_ext as i64) & (two_n_ext - 1) as i64) as usize;
let b_hi: usize = b_pos / extension_factor;
let b_lo: usize = b_pos & (extension_factor - 1);
for (i, j) in (0..b_lo).zip(extension_factor - b_lo..extension_factor) {
module.vec_znx_rotate(b_hi as i64 + 1, &mut acc[i], 0, &lut.data[j], 0);
}
for (i, j) in (b_lo..extension_factor).zip(0..extension_factor - b_lo) {
module.vec_znx_rotate(b_hi as i64, &mut acc[i], 0, &lut.data[j], 0);
}
let block_size: usize = brk.block_size();
izip!(
a.chunks_exact(block_size),
brk.data.chunks_exact(block_size)
)
.for_each(|(ai, ski)| {
(0..extension_factor).for_each(|i| {
(0..cols).for_each(|j| {
module.vec_znx_dft_from_vec_znx(1, 0, &mut acc_dft[i], j, &acc[i], j);
});
module.vec_znx_dft_zero(&mut acc_add_dft[i])
});
// TODO: first & last iterations can be optimized
izip!(ai.iter(), ski.iter()).for_each(|(aii, skii)| {
let ai_pos: usize = ((aii + two_n_ext as i64) & (two_n_ext - 1) as i64) as usize;
let ai_hi: usize = ai_pos / extension_factor;
let ai_lo: usize = ai_pos & (extension_factor - 1);
// vmp_res = DFT(acc) * BRK[i]
(0..extension_factor).for_each(|i| {
module.vmp_apply(&mut vmp_res[i], &acc_dft[i], &skii.data, scratch5);
});
// Trivial case: no rotation between polynomials, we can directly multiply with (X^{-ai} - 1)
if ai_lo == 0 {
// Sets acc_add_dft[i] = (acc[i] * sk) * X^{-ai} - (acc[i] * sk)
if ai_hi != 0 {
// DFT X^{-ai}
(0..extension_factor).for_each(|j| {
(0..cols).for_each(|i| {
module.svp_apply(&mut vmp_xai, 0, &x_pow_a[ai_hi], 0, &vmp_res[j], i);
module.vec_znx_dft_add_inplace(&mut acc_add_dft[j], i, &vmp_xai, 0);
module.vec_znx_dft_sub_ab_inplace(&mut acc_add_dft[j], i, &vmp_res[j], i);
});
});
}
// Non trivial case: rotation between polynomials
// In this case we can't directly multiply with (X^{-ai} - 1) because of the
// ring homomorphism R^{N} -> prod R^{N/extension_factor}, so we split the
// computation in two steps: acc_add_dft = (acc * sk) * (-1) + (acc * sk) * X^{-ai}
} else {
// Sets acc_add_dft[0..ai_lo] += (acc[extension_factor - ai_lo..extension_factor] * sk) * X^{-ai+1}
if (ai_hi + 1) & (two_n - 1) != 0 {
for (i, j) in (0..ai_lo).zip(extension_factor - ai_lo..extension_factor) {
(0..cols).for_each(|k| {
module.svp_apply(&mut vmp_xai, 0, &x_pow_a[ai_hi + 1], 0, &vmp_res[j], k);
module.vec_znx_dft_add_inplace(&mut acc_add_dft[i], k, &vmp_xai, 0);
module.vec_znx_dft_sub_ab_inplace(&mut acc_add_dft[i], k, &vmp_res[i], k);
});
}
}
// Sets acc_add_dft[ai_lo..extension_factor] += (acc[0..extension_factor - ai_lo] * sk) * X^{-ai}
if ai_hi != 0 {
// Sets acc_add_dft[ai_lo..extension_factor] += (acc[0..extension_factor - ai_lo] * sk) * X^{-ai}
for (i, j) in (ai_lo..extension_factor).zip(0..extension_factor - ai_lo) {
(0..cols).for_each(|k| {
module.svp_apply(&mut vmp_xai, 0, &x_pow_a[ai_hi], 0, &vmp_res[j], k);
module.vec_znx_dft_add_inplace(&mut acc_add_dft[i], k, &vmp_xai, 0);
module.vec_znx_dft_sub_ab_inplace(&mut acc_add_dft[i], k, &vmp_res[i], k);
});
}
}
}
});
{
let (mut acc_add_big, scratch7) = scratch5.take_vec_znx_big(n_glwe, 1, brk.size());
(0..extension_factor).for_each(|j| {
(0..cols).for_each(|i| {
module.vec_znx_dft_to_vec_znx_big(&mut acc_add_big, 0, &acc_add_dft[j], i, scratch7);
module.vec_znx_big_add_small_inplace(&mut acc_add_big, 0, &acc[j], i);
module.vec_znx_big_normalize(basek, &mut acc[j], i, &acc_add_big, 0, scratch7);
});
});
}
});
(0..cols).for_each(|i| {
module.vec_znx_copy(&mut res.data, i, &acc[0], i);
});
}
pub(crate) fn cggi_blind_rotate_block_binary<DataRes, DataIn, DataBrk, B: Backend>(
module: &Module<B>,
res: &mut GLWECiphertext<DataRes>,
lwe: &LWECiphertext<DataIn>,
lut: &LookUpTable,
brk: &BlindRotationKeyCGGIExec<DataBrk, B>,
scratch: &mut Scratch<B>,
) where
DataRes: DataMut,
DataIn: DataRef,
DataBrk: DataRef,
Module<B>: CCGIBlindRotationFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + TakeVecZnxBig<B>,
{
let n_glwe: usize = brk.n();
let mut lwe_2n: Vec<i64> = vec![0i64; lwe.n() + 1]; // TODO: from scratch space
let mut out_mut: GLWECiphertext<&mut [u8]> = res.to_mut();
let lwe_ref: LWECiphertext<&[u8]> = lwe.to_ref();
let two_n: usize = n_glwe << 1;
let basek: usize = brk.basek();
let rows: usize = brk.rows();
let cols: usize = out_mut.rank() + 1;
mod_switch_2n(
2 * lut.domain_size(),
&mut lwe_2n,
&lwe_ref,
lut.rotation_direction(),
);
let a: &[i64] = &lwe_2n[1..];
let b: i64 = lwe_2n[0];
out_mut.data.zero();
// Initialize out to X^{b} * LUT(X)
module.vec_znx_rotate(b, &mut out_mut.data, 0, &lut.data[0], 0);
let block_size: usize = brk.block_size();
// ACC + [sum DFT(X^ai -1) * (DFT(ACC) x BRKi)]
let (mut acc_dft, scratch1) = scratch.take_vec_znx_dft(n_glwe, cols, rows);
let (mut vmp_res, scratch2) = scratch1.take_vec_znx_dft(n_glwe, cols, brk.size());
let (mut acc_add_dft, scratch3) = scratch2.take_vec_znx_dft(n_glwe, cols, brk.size());
let (mut vmp_xai, scratch4) = scratch3.take_vec_znx_dft(n_glwe, 1, brk.size());
let x_pow_a: &Vec<SvpPPol<Vec<u8>, B>>;
if let Some(b) = &brk.x_pow_a {
x_pow_a = b
} else {
panic!("invalid key: x_pow_a has not been initialized")
}
izip!(
a.chunks_exact(block_size),
brk.data.chunks_exact(block_size)
)
.for_each(|(ai, ski)| {
(0..cols).for_each(|j| {
module.vec_znx_dft_from_vec_znx(1, 0, &mut acc_dft, j, &out_mut.data, j);
});
module.vec_znx_dft_zero(&mut acc_add_dft);
izip!(ai.iter(), ski.iter()).for_each(|(aii, skii)| {
let ai_pos: usize = ((aii + two_n as i64) & (two_n - 1) as i64) as usize;
// vmp_res = DFT(acc) * BRK[i]
module.vmp_apply(&mut vmp_res, &acc_dft, &skii.data, scratch4);
// DFT(X^ai -1) * (DFT(acc) * BRK[i])
(0..cols).for_each(|i| {
module.svp_apply(&mut vmp_xai, 0, &x_pow_a[ai_pos], 0, &vmp_res, i);
module.vec_znx_dft_add_inplace(&mut acc_add_dft, i, &vmp_xai, 0);
module.vec_znx_dft_sub_ab_inplace(&mut acc_add_dft, i, &vmp_res, i);
});
});
{
let (mut acc_add_big, scratch5) = scratch4.take_vec_znx_big(n_glwe, 1, brk.size());
(0..cols).for_each(|i| {
module.vec_znx_dft_to_vec_znx_big(&mut acc_add_big, 0, &acc_add_dft, i, scratch5);
module.vec_znx_big_add_small_inplace(&mut acc_add_big, 0, &out_mut.data, i);
module.vec_znx_big_normalize(basek, &mut out_mut.data, i, &acc_add_big, 0, scratch5);
});
}
});
}
pub(crate) fn cggi_blind_rotate_binary_standard<DataRes, DataIn, DataBrk, B: Backend>(
module: &Module<B>,
res: &mut GLWECiphertext<DataRes>,
lwe: &LWECiphertext<DataIn>,
lut: &LookUpTable,
brk: &BlindRotationKeyCGGIExec<DataBrk, B>,
scratch: &mut Scratch<B>,
) where
DataRes: DataMut,
DataIn: DataRef,
DataBrk: DataRef,
Module<B>: CCGIBlindRotationFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + TakeVecZnxBig<B> + TakeVecZnx + ScratchAvailable,
{
#[cfg(debug_assertions)]
{
assert_eq!(
res.n(),
brk.n(),
"res.n(): {} != brk.n(): {}",
res.n(),
brk.n()
);
assert_eq!(
lut.domain_size(),
brk.n(),
"lut.n(): {} != brk.n(): {}",
lut.domain_size(),
brk.n()
);
assert_eq!(
res.rank(),
brk.rank(),
"res.rank(): {} != brk.rank(): {}",
res.rank(),
brk.rank()
);
assert_eq!(
lwe.n(),
brk.data.len(),
"lwe.n(): {} != brk.data.len(): {}",
lwe.n(),
brk.data.len()
);
}
let mut lwe_2n: Vec<i64> = vec![0i64; lwe.n() + 1]; // TODO: from scratch space
let mut out_mut: GLWECiphertext<&mut [u8]> = res.to_mut();
let lwe_ref: LWECiphertext<&[u8]> = lwe.to_ref();
let basek: usize = brk.basek();
mod_switch_2n(
2 * lut.domain_size(),
&mut lwe_2n,
&lwe_ref,
lut.rotation_direction(),
);
let a: &[i64] = &lwe_2n[1..];
let b: i64 = lwe_2n[0];
out_mut.data.zero();
// Initialize out to X^{b} * LUT(X)
module.vec_znx_rotate(b, &mut out_mut.data, 0, &lut.data[0], 0);
// ACC + [sum DFT(X^ai -1) * (DFT(ACC) x BRKi)]
let (mut acc_tmp, scratch1) = scratch.take_glwe_ct(out_mut.n(), basek, out_mut.k(), out_mut.rank());
// TODO: see if faster by skipping normalization in external product and keeping acc in big coeffs
// TODO: first iteration can be optimized to be a gglwe product
izip!(a.iter(), brk.data.iter()).for_each(|(ai, ski)| {
// acc_tmp = sk[i] * acc
acc_tmp.external_product(module, &out_mut, ski, scratch1);
// acc_tmp = (sk[i] * acc) * (X^{ai} - 1)
acc_tmp.mul_xp_minus_one_inplace(module, *ai);
// acc = acc + (sk[i] * acc) * (X^{ai} - 1)
out_mut.add_inplace(module, &acc_tmp);
});
// We can normalize only at the end because we add normalized values in [-2^{basek-1}, 2^{basek-1}]
// on top of each others, thus ~ 2^{63-basek} additions are supported before overflow.
out_mut.normalize_inplace(module, scratch1);
}
pub(crate) fn mod_switch_2n(n: usize, res: &mut [i64], lwe: &LWECiphertext<&[u8]>, rot_dir: LookUpTableRotationDirection) {
let basek: usize = lwe.basek();
let log2n: usize = usize::BITS as usize - (n - 1).leading_zeros() as usize + 1;
res.copy_from_slice(&lwe.data.at(0, 0));
match rot_dir {
LookUpTableRotationDirection::Left => {
res.iter_mut().for_each(|x| *x = -*x);
}
LookUpTableRotationDirection::Right => {}
}
if basek > log2n {
let diff: usize = basek - log2n;
res.iter_mut().for_each(|x| {
*x = div_round_by_pow2(x, diff);
})
} else {
let rem: usize = basek - (log2n % basek);
let size: usize = log2n.div_ceil(basek);
(1..size).for_each(|i| {
if i == size - 1 && rem != basek {
let k_rem: usize = basek - rem;
izip!(lwe.data.at(0, i).iter(), res.iter_mut()).for_each(|(x, y)| {
*y = (*y << k_rem) + (x >> rem);
});
} else {
izip!(lwe.data.at(0, i).iter(), res.iter_mut()).for_each(|(x, y)| {
*y = (*y << basek) + x;
});
}
})
}
}
#[inline(always)]
fn div_round_by_pow2(x: &i64, k: usize) -> i64 {
(x + (1 << (k - 1))) >> k
}

View File

@@ -1,356 +0,0 @@
use backend::hal::{
api::{
FillUniform, Reset, ScratchAvailable, SvpPPolAlloc, SvpPrepare, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace,
ZnxInfos, ZnxView, ZnxViewMut,
},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, ScalarZnx, ScalarZnxToRef, Scratch, SvpPPol, WriterTo},
};
use sampling::source::Source;
use crate::{
Distribution, GGSWCiphertext, GGSWCiphertextExec, GGSWEncryptSkFamily, GGSWLayoutFamily, GLWESecretExec, Infos, LWESecret,
};
use std::fmt;
#[derive(Clone)]
pub struct BlindRotationKeyCGGI<D: Data> {
pub(crate) keys: Vec<GGSWCiphertext<D>>,
pub(crate) dist: Distribution,
}
impl<D: DataRef> fmt::Debug for BlindRotationKeyCGGI<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: Data> PartialEq for BlindRotationKeyCGGI<D> {
fn eq(&self, other: &Self) -> bool {
if self.keys.len() != other.keys.len() {
return false;
}
for (a, b) in self.keys.iter().zip(other.keys.iter()) {
if a != b {
return false;
}
}
self.dist == other.dist
}
}
impl<D: Data> Eq for BlindRotationKeyCGGI<D> {}
impl<D: DataRef> fmt::Display for BlindRotationKeyCGGI<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, key) in self.keys.iter().enumerate() {
write!(f, "key[{}]: {}", i, key)?;
}
writeln!(f, "{:?}", self.dist)
}
}
impl<D: DataMut> Reset for BlindRotationKeyCGGI<D> {
fn reset(&mut self) {
self.keys.iter_mut().for_each(|key| key.reset());
self.dist = Distribution::NONE;
}
}
impl<D: DataMut> FillUniform for BlindRotationKeyCGGI<D> {
fn fill_uniform(&mut self, source: &mut sampling::source::Source) {
self.keys
.iter_mut()
.for_each(|key| key.fill_uniform(source));
}
}
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
impl<D: DataMut> ReaderFrom for BlindRotationKeyCGGI<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),
}
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 BlindRotationKeyCGGI<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),
}
writer.write_u64::<LittleEndian>(self.keys.len() as u64)?;
for key in &self.keys {
key.write_to(writer)?;
}
Ok(())
}
}
impl BlindRotationKeyCGGI<Vec<u8>> {
pub fn alloc(n_gglwe: usize, n_lwe: usize, basek: usize, k: usize, rows: usize, rank: usize) -> Self {
let mut data: Vec<GGSWCiphertext<Vec<u8>>> = Vec::with_capacity(n_lwe);
(0..n_lwe).for_each(|_| data.push(GGSWCiphertext::alloc(n_gglwe, basek, k, rows, 1, rank)));
Self {
keys: data,
dist: Distribution::NONE,
}
}
pub fn generate_from_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>: GGSWEncryptSkFamily<B>,
{
GGSWCiphertext::encrypt_sk_scratch_space(module, n, basek, k, rank)
}
}
impl<D: DataRef> BlindRotationKeyCGGI<D> {
#[allow(dead_code)]
pub(crate) fn n(&self) -> usize {
self.keys[0].n()
}
#[allow(dead_code)]
pub(crate) fn rows(&self) -> usize {
self.keys[0].rows()
}
#[allow(dead_code)]
pub(crate) fn k(&self) -> usize {
self.keys[0].k()
}
#[allow(dead_code)]
pub(crate) fn size(&self) -> usize {
self.keys[0].size()
}
#[allow(dead_code)]
pub(crate) fn rank(&self) -> usize {
self.keys[0].rank()
}
pub(crate) fn basek(&self) -> usize {
self.keys[0].basek()
}
#[allow(dead_code)]
pub(crate) fn block_size(&self) -> usize {
match self.dist {
Distribution::BinaryBlock(value) => value,
_ => 1,
}
}
}
impl<D: DataMut> BlindRotationKeyCGGI<D> {
pub fn generate_from_sk<DataSkGLWE, DataSkLWE, B: Backend>(
&mut self,
module: &Module<B>,
sk_glwe: &GLWESecretExec<DataSkGLWE, B>,
sk_lwe: &LWESecret<DataSkLWE>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
DataSkGLWE: DataRef,
DataSkLWE: DataRef,
Module<B>: GGSWEncryptSkFamily<B> + VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.keys.len(), sk_lwe.n());
assert!(sk_glwe.n() <= module.n());
assert_eq!(sk_glwe.rank(), self.keys[0].rank());
match sk_lwe.dist {
Distribution::BinaryBlock(_)
| Distribution::BinaryFixed(_)
| Distribution::BinaryProb(_)
| Distribution::ZERO => {}
_ => panic!(
"invalid GLWESecret distribution: must be BinaryBlock, BinaryFixed or BinaryProb (or ZERO for debugging)"
),
}
}
self.dist = sk_lwe.dist;
let mut pt: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(sk_glwe.n(), 1);
let sk_ref: ScalarZnx<&[u8]> = sk_lwe.data.to_ref();
self.keys.iter_mut().enumerate().for_each(|(i, ggsw)| {
pt.at_mut(0, 0)[0] = sk_ref.at(0, 0)[i];
ggsw.encrypt_sk(module, &pt, sk_glwe, source_xa, source_xe, sigma, scratch);
});
}
}
#[derive(PartialEq, Eq)]
pub struct BlindRotationKeyCGGIExec<D: Data, B: Backend> {
pub(crate) data: Vec<GGSWCiphertextExec<D, B>>,
pub(crate) dist: Distribution,
pub(crate) x_pow_a: Option<Vec<SvpPPol<Vec<u8>, B>>>,
}
impl<D: Data, B: Backend> BlindRotationKeyCGGIExec<D, B> {
#[allow(dead_code)]
pub(crate) fn n(&self) -> usize {
self.data[0].n()
}
#[allow(dead_code)]
pub(crate) fn rows(&self) -> usize {
self.data[0].rows()
}
#[allow(dead_code)]
pub(crate) fn k(&self) -> usize {
self.data[0].k()
}
#[allow(dead_code)]
pub(crate) fn size(&self) -> usize {
self.data[0].size()
}
#[allow(dead_code)]
pub(crate) fn rank(&self) -> usize {
self.data[0].rank()
}
pub(crate) fn basek(&self) -> usize {
self.data[0].basek()
}
pub(crate) fn block_size(&self) -> usize {
match self.dist {
Distribution::BinaryBlock(value) => value,
_ => 1,
}
}
}
pub trait BlindRotationKeyCGGIExecLayoutFamily<B: Backend> = GGSWLayoutFamily<B> + SvpPPolAlloc<B> + SvpPrepare<B>;
impl<B: Backend> BlindRotationKeyCGGIExec<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n_glwe: usize, n_lwe: usize, basek: usize, k: usize, rows: usize, rank: usize) -> Self
where
Module<B>: BlindRotationKeyCGGIExecLayoutFamily<B>,
{
let mut data: Vec<GGSWCiphertextExec<Vec<u8>, B>> = Vec::with_capacity(n_lwe);
(0..n_lwe).for_each(|_| {
data.push(GGSWCiphertextExec::alloc(
module, n_glwe, basek, k, rows, 1, rank,
))
});
Self {
data,
dist: Distribution::NONE,
x_pow_a: None,
}
}
pub fn from<DataOther>(module: &Module<B>, other: &BlindRotationKeyCGGI<DataOther>, scratch: &mut Scratch<B>) -> Self
where
DataOther: DataRef,
Module<B>: BlindRotationKeyCGGIExecLayoutFamily<B>,
{
let mut brk: BlindRotationKeyCGGIExec<Vec<u8>, B> = Self::alloc(
module,
other.n(),
other.keys.len(),
other.basek(),
other.k(),
other.rows(),
other.rank(),
);
brk.prepare(module, other, scratch);
brk
}
}
impl<D: DataMut, B: Backend> BlindRotationKeyCGGIExec<D, B> {
pub fn prepare<DataOther>(&mut self, module: &Module<B>, other: &BlindRotationKeyCGGI<DataOther>, scratch: &mut Scratch<B>)
where
DataOther: DataRef,
Module<B>: BlindRotationKeyCGGIExecLayoutFamily<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.data.len(), other.keys.len());
}
let n: usize = other.n();
self.data
.iter_mut()
.zip(other.keys.iter())
.for_each(|(ggsw_exec, other)| {
ggsw_exec.prepare(module, other, scratch);
});
self.dist = other.dist;
match other.dist {
Distribution::BinaryBlock(_) => {
let mut x_pow_a: Vec<SvpPPol<Vec<u8>, B>> = Vec::with_capacity(n << 1);
let mut buf: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
(0..n << 1).for_each(|i| {
let mut res: SvpPPol<Vec<u8>, B> = module.svp_ppol_alloc(n, 1);
set_xai_plus_y(module, i, 0, &mut res, &mut buf);
x_pow_a.push(res);
});
self.x_pow_a = Some(x_pow_a);
}
_ => {}
}
}
}
pub fn set_xai_plus_y<A, C, B: Backend>(module: &Module<B>, ai: usize, y: i64, res: &mut SvpPPol<A, B>, buf: &mut ScalarZnx<C>)
where
A: DataMut,
C: DataMut,
Module<B>: SvpPrepare<B>,
{
let n: usize = res.n();
{
let raw: &mut [i64] = buf.at_mut(0, 0);
if ai < n {
raw[ai] = 1;
} else {
raw[(ai - n) & (n - 1)] = -1;
}
raw[0] += y;
}
module.svp_prepare(res, 0, buf, 0);
{
let raw: &mut [i64] = buf.at_mut(0, 0);
if ai < n {
raw[ai] = 0;
} else {
raw[(ai - n) & (n - 1)] = 0;
}
raw[0] = 0;
}
}

View File

@@ -1,212 +0,0 @@
use backend::hal::{
api::{FillUniform, Reset, ScratchAvailable, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, ZnxView, ZnxViewMut},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, ScalarZnx, ScalarZnxToRef, Scratch, WriterTo},
};
use sampling::source::Source;
use crate::{Distribution, GGSWCiphertextCompressed, GGSWEncryptSkFamily, GLWESecretExec, Infos, LWESecret};
use std::fmt;
#[derive(Clone)]
pub struct BlindRotationKeyCGGICompressed<D: Data> {
pub(crate) keys: Vec<GGSWCiphertextCompressed<D>>,
pub(crate) dist: Distribution,
}
impl<D: DataRef> fmt::Debug for BlindRotationKeyCGGICompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: Data> PartialEq for BlindRotationKeyCGGICompressed<D> {
fn eq(&self, other: &Self) -> bool {
if self.keys.len() != other.keys.len() {
return false;
}
for (a, b) in self.keys.iter().zip(other.keys.iter()) {
if a != b {
return false;
}
}
self.dist == other.dist
}
}
impl<D: Data> Eq for BlindRotationKeyCGGICompressed<D> {}
impl<D: DataRef> fmt::Display for BlindRotationKeyCGGICompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, key) in self.keys.iter().enumerate() {
write!(f, "key[{}]: {}", i, key)?;
}
writeln!(f, "{:?}", self.dist)
}
}
impl<D: DataMut> Reset for BlindRotationKeyCGGICompressed<D> {
fn reset(&mut self) {
self.keys.iter_mut().for_each(|key| key.reset());
self.dist = Distribution::NONE;
}
}
impl<D: DataMut> FillUniform for BlindRotationKeyCGGICompressed<D> {
fn fill_uniform(&mut self, source: &mut sampling::source::Source) {
self.keys
.iter_mut()
.for_each(|key| key.fill_uniform(source));
}
}
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
impl<D: DataMut> ReaderFrom for BlindRotationKeyCGGICompressed<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),
}
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 BlindRotationKeyCGGICompressed<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),
}
writer.write_u64::<LittleEndian>(self.keys.len() as u64)?;
for key in &self.keys {
key.write_to(writer)?;
}
Ok(())
}
}
impl BlindRotationKeyCGGICompressed<Vec<u8>> {
pub fn alloc(n_gglwe: usize, n_lwe: usize, basek: usize, k: usize, rows: usize, rank: usize) -> Self {
let mut data: Vec<GGSWCiphertextCompressed<Vec<u8>>> = Vec::with_capacity(n_lwe);
(0..n_lwe).for_each(|_| {
data.push(GGSWCiphertextCompressed::alloc(
n_gglwe, basek, k, rows, 1, rank,
))
});
Self {
keys: data,
dist: Distribution::NONE,
}
}
pub fn generate_from_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>: GGSWEncryptSkFamily<B>,
{
GGSWCiphertextCompressed::encrypt_sk_scratch_space(module, n, basek, k, rank)
}
}
impl<D: DataRef> BlindRotationKeyCGGICompressed<D> {
#[allow(dead_code)]
pub(crate) fn n(&self) -> usize {
self.keys[0].n()
}
#[allow(dead_code)]
pub(crate) fn rows(&self) -> usize {
self.keys[0].rows()
}
#[allow(dead_code)]
pub(crate) fn k(&self) -> usize {
self.keys[0].k()
}
#[allow(dead_code)]
pub(crate) fn size(&self) -> usize {
self.keys[0].size()
}
#[allow(dead_code)]
pub(crate) fn rank(&self) -> usize {
self.keys[0].rank()
}
#[allow(dead_code)]
pub(crate) fn basek(&self) -> usize {
self.keys[0].basek()
}
#[allow(dead_code)]
pub(crate) fn block_size(&self) -> usize {
match self.dist {
Distribution::BinaryBlock(value) => value,
_ => 1,
}
}
}
impl<D: DataMut> BlindRotationKeyCGGICompressed<D> {
pub fn generate_from_sk<DataSkGLWE, DataSkLWE, B: Backend>(
&mut self,
module: &Module<B>,
sk_glwe: &GLWESecretExec<DataSkGLWE, B>,
sk_lwe: &LWESecret<DataSkLWE>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
DataSkGLWE: DataRef,
DataSkLWE: DataRef,
Module<B>: GGSWEncryptSkFamily<B> + VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.keys.len(), sk_lwe.n());
assert!(sk_glwe.n() <= module.n());
assert_eq!(sk_glwe.rank(), self.keys[0].rank());
match sk_lwe.dist {
Distribution::BinaryBlock(_)
| Distribution::BinaryFixed(_)
| Distribution::BinaryProb(_)
| Distribution::ZERO => {}
_ => panic!(
"invalid GLWESecret distribution: must be BinaryBlock, BinaryFixed or BinaryProb (or ZERO for debugging)"
),
}
}
self.dist = sk_lwe.dist;
let mut pt: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(sk_glwe.n(), 1);
let sk_ref: ScalarZnx<&[u8]> = sk_lwe.data.to_ref();
let mut source_xa: Source = Source::new(seed_xa);
self.keys.iter_mut().enumerate().for_each(|(i, ggsw)| {
pt.at_mut(0, 0)[0] = sk_ref.at(0, 0)[i];
ggsw.encrypt_sk(
module,
&pt,
sk_glwe,
source_xa.new_seed(),
source_xe,
sigma,
scratch,
);
});
}
}

View File

@@ -1,197 +0,0 @@
use backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxCopy, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxRotateInplace,
VecZnxSwithcDegree, ZnxInfos, ZnxViewMut,
},
layouts::{Backend, Module, ScratchOwned, VecZnx},
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl},
};
#[derive(Debug, Clone, Copy)]
pub enum LookUpTableRotationDirection {
Left,
Right,
}
pub struct LookUpTable {
pub(crate) data: Vec<VecZnx<Vec<u8>>>,
pub(crate) rot_dir: LookUpTableRotationDirection,
pub(crate) basek: usize,
pub(crate) k: usize,
pub(crate) drift: usize,
}
impl LookUpTable {
pub fn alloc(n: usize, basek: usize, k: usize, extension_factor: usize) -> Self {
#[cfg(debug_assertions)]
{
assert!(
extension_factor & (extension_factor - 1) == 0,
"extension_factor must be a power of two but is: {}",
extension_factor
);
}
let size: usize = k.div_ceil(basek);
let mut data: Vec<VecZnx<Vec<u8>>> = Vec::with_capacity(extension_factor);
(0..extension_factor).for_each(|_| {
data.push(VecZnx::alloc(n, 1, size));
});
Self {
data,
basek,
k,
drift: 0,
rot_dir: LookUpTableRotationDirection::Left,
}
}
pub fn log_extension_factor(&self) -> usize {
(usize::BITS - (self.extension_factor() - 1).leading_zeros()) as _
}
pub fn extension_factor(&self) -> usize {
self.data.len()
}
pub fn domain_size(&self) -> usize {
self.data.len() * self.data[0].n()
}
pub fn rotation_direction(&self) -> LookUpTableRotationDirection {
self.rot_dir
}
// By default X^{-dec(lwe)} is computed during the blind rotation.
// Setting [reverse_rotation] to true will reverse the sign of
// rotation of the LUT by instead evaluating X^{dec(lwe)} during
// the blind rotation.
pub fn set_rotation_direction(&mut self, rot_dir: LookUpTableRotationDirection) {
self.rot_dir = rot_dir
}
pub fn set<B: Backend>(&mut self, module: &Module<B>, f: &Vec<i64>, k: usize)
where
Module<B>: VecZnxRotateInplace + VecZnxNormalizeInplace<B> + VecZnxNormalizeTmpBytes + VecZnxSwithcDegree + VecZnxCopy,
B: ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
{
assert!(f.len() <= module.n());
let basek: usize = self.basek;
// Get the number minimum limb to store the message modulus
let limbs: usize = k.div_ceil(basek);
#[cfg(debug_assertions)]
{
assert!(f.len() <= module.n());
assert!(
(max_bit_size(f) + (k % basek) as u32) < i64::BITS,
"overflow: max(|f|) << (k%basek) > i64::BITS"
);
assert!(limbs <= self.data[0].size());
}
// Scaling factor
let mut scale = 1;
if k % basek != 0 {
scale <<= basek - (k % basek);
}
// #elements in lookup table
let f_len: usize = f.len();
// If LUT size > TakeScalarZnx
let domain_size: usize = self.domain_size();
let size: usize = self.k.div_ceil(self.basek);
// Equivalent to AUTO([f(0), -f(n-1), -f(n-2), ..., -f(1)], -1)
let mut lut_full: VecZnx<Vec<u8>> = VecZnx::alloc(domain_size, 1, size);
let lut_at: &mut [i64] = lut_full.at_mut(0, limbs - 1);
let step: usize = domain_size.div_round(f_len);
f.iter().enumerate().for_each(|(i, fi)| {
let start: usize = i * step;
let end: usize = start + step;
lut_at[start..end].fill(fi * scale);
});
let drift: usize = step >> 1;
// Rotates half the step to the left
module.vec_znx_rotate_inplace(-(drift as i64), &mut lut_full, 0);
let n_large: usize = lut_full.n();
module.vec_znx_normalize_inplace(
self.basek,
&mut lut_full,
0,
ScratchOwned::alloc(module.vec_znx_normalize_tmp_bytes(n_large)).borrow(),
);
if self.extension_factor() > 1 {
(0..self.extension_factor()).for_each(|i| {
module.vec_znx_switch_degree(&mut self.data[i], 0, &lut_full, 0);
if i < self.extension_factor() {
module.vec_znx_rotate_inplace(-1, &mut lut_full, 0);
}
});
} else {
module.vec_znx_copy(&mut self.data[0], 0, &lut_full, 0);
}
self.drift = drift
}
#[allow(dead_code)]
pub(crate) fn rotate<B: Backend>(&mut self, module: &Module<B>, k: i64)
where
Module<B>: VecZnxRotateInplace,
{
let extension_factor: usize = self.extension_factor();
let two_n: usize = 2 * self.data[0].n();
let two_n_ext: usize = two_n * extension_factor;
let k_pos: usize = ((k + two_n_ext as i64) % two_n_ext as i64) as usize;
let k_hi: usize = k_pos / extension_factor;
let k_lo: usize = k_pos % extension_factor;
(0..extension_factor - k_lo).for_each(|i| {
module.vec_znx_rotate_inplace(k_hi as i64, &mut self.data[i], 0);
});
(extension_factor - k_lo..extension_factor).for_each(|i| {
module.vec_znx_rotate_inplace(k_hi as i64 + 1, &mut self.data[i], 0);
});
self.data.rotate_right(k_lo as usize);
}
}
pub(crate) trait DivRound {
fn div_round(self, rhs: Self) -> Self;
}
impl DivRound for usize {
#[inline]
fn div_round(self, rhs: Self) -> Self {
(self + rhs / 2) / rhs
}
}
fn max_bit_size(vec: &[i64]) -> u32 {
vec.iter()
.map(|&v| {
if v == 0 {
0
} else {
v.unsigned_abs().ilog2() + 1
}
})
.max()
.unwrap_or(0)
}

View File

@@ -1,12 +0,0 @@
mod cggi;
mod key;
mod key_compressed;
mod lut;
pub use cggi::*;
pub use key::*;
pub use key_compressed::*;
pub use lut::*;
#[cfg(test)]
mod tests;

View File

@@ -1,39 +0,0 @@
use backend::{
hal::{api::ModuleNew, layouts::Module},
implementation::cpu_spqlios::FFT64,
};
use crate::blind_rotation::tests::{
generic_cggi::blind_rotatio_test,
generic_lut::{test_lut_extended, test_lut_standard},
};
#[test]
fn lut_standard() {
let module: Module<FFT64> = Module::<FFT64>::new(32);
test_lut_standard(&module);
}
#[test]
fn lut_extended() {
let module: Module<FFT64> = Module::<FFT64>::new(32);
test_lut_extended(&module);
}
#[test]
fn standard() {
let module: Module<FFT64> = Module::<FFT64>::new(512);
blind_rotatio_test(&module, 224, 1, 1);
}
#[test]
fn block_binary() {
let module: Module<FFT64> = Module::<FFT64>::new(512);
blind_rotatio_test(&module, 224, 7, 1);
}
#[test]
fn block_binary_extended() {
let module: Module<FFT64> = Module::<FFT64>::new(512);
blind_rotatio_test(&module, 224, 7, 2);
}

View File

@@ -1,155 +0,0 @@
use backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxEncodeCoeffsi64, VecZnxFillUniform,
VecZnxRotateInplace, VecZnxSub, VecZnxSwithcDegree, ZnxView,
},
layouts::{Backend, Module, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeVecZnxBigImpl, TakeVecZnxDftImpl,
TakeVecZnxDftSliceImpl, TakeVecZnxImpl, TakeVecZnxSliceImpl, VecZnxBigAllocBytesImpl, VecZnxDftAllocBytesImpl,
},
};
use sampling::source::Source;
use crate::{
BlindRotationKeyCGGI, BlindRotationKeyCGGIExec, BlindRotationKeyCGGIExecLayoutFamily, CCGIBlindRotationFamily,
GLWECiphertext, GLWEDecryptFamily, GLWEPlaintext, GLWESecret, GLWESecretExec, GLWESecretFamily, Infos, LWECiphertext,
LWECiphertextToRef, LWEPlaintext, LWESecret, LookUpTable, cggi_blind_rotate, cggi_blind_rotate_scratch_space, mod_switch_2n,
};
pub(crate) trait CGGITestModuleFamily<B: Backend> = CCGIBlindRotationFamily<B>
+ GLWESecretFamily<B>
+ GLWEDecryptFamily<B>
+ BlindRotationKeyCGGIExecLayoutFamily<B>
+ VecZnxFillUniform
+ VecZnxAddNormal
+ VecZnxAddScalarInplace
+ VecZnxEncodeCoeffsi64
+ VecZnxRotateInplace
+ VecZnxSwithcDegree
+ VecZnxSub;
pub(crate) trait CGGITestScratchFamily<B: Backend> = VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeVecZnxDftSliceImpl<B>
+ ScratchAvailableImpl<B>
+ TakeVecZnxImpl<B>
+ TakeVecZnxSliceImpl<B>;
pub(crate) fn blind_rotatio_test<B: Backend>(module: &Module<B>, n_lwe: usize, block_size: usize, extension_factor: usize)
where
Module<B>: CGGITestModuleFamily<B>,
B: CGGITestScratchFamily<B>,
{
let n: usize = module.n();
let basek: usize = 19;
let k_lwe: usize = 24;
let k_brk: usize = 3 * basek;
let rows_brk: usize = 2; // Ensures first limb is noise-free.
let k_lut: usize = 1 * basek;
let k_res: usize = 2 * basek;
let rank: usize = 1;
let message_modulus: usize = 1 << 4;
let mut source_xs: Source = Source::new([2u8; 32]);
let mut source_xe: Source = Source::new([2u8; 32]);
let mut source_xa: Source = Source::new([1u8; 32]);
let mut sk_glwe: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_glwe.fill_ternary_prob(0.5, &mut source_xs);
let sk_glwe_dft: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_glwe);
let mut sk_lwe: LWESecret<Vec<u8>> = LWESecret::alloc(n_lwe);
sk_lwe.fill_binary_block(block_size, &mut source_xs);
let mut scratch: ScratchOwned<B> = ScratchOwned::<B>::alloc(BlindRotationKeyCGGI::generate_from_sk_scratch_space(
module, n, basek, k_brk, rank,
));
let mut scratch_br: ScratchOwned<B> = ScratchOwned::<B>::alloc(cggi_blind_rotate_scratch_space(
module,
n,
block_size,
extension_factor,
basek,
k_res,
k_brk,
rows_brk,
rank,
));
let mut brk: BlindRotationKeyCGGI<Vec<u8>> = BlindRotationKeyCGGI::alloc(n, n_lwe, basek, k_brk, rows_brk, rank);
brk.generate_from_sk(
module,
&sk_glwe_dft,
&sk_lwe,
&mut source_xa,
&mut source_xe,
3.2,
scratch.borrow(),
);
let mut lwe: LWECiphertext<Vec<u8>> = LWECiphertext::alloc(n_lwe, basek, k_lwe);
let mut pt_lwe: LWEPlaintext<Vec<u8>> = LWEPlaintext::alloc(basek, k_lwe);
let x: i64 = 2;
let bits: usize = 8;
module.encode_coeff_i64(basek, &mut pt_lwe.data, 0, bits, 0, x, bits);
lwe.encrypt_sk(
module,
&pt_lwe,
&sk_lwe,
&mut source_xa,
&mut source_xe,
3.2,
);
let mut f: Vec<i64> = vec![0i64; message_modulus];
f.iter_mut()
.enumerate()
.for_each(|(i, x)| *x = 2 * (i as i64) + 1);
let mut lut: LookUpTable = LookUpTable::alloc(n, basek, k_lut, extension_factor);
lut.set(module, &f, message_modulus);
let mut res: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_res, rank);
let brk_exec: BlindRotationKeyCGGIExec<Vec<u8>, B> = BlindRotationKeyCGGIExec::from(module, &brk, scratch_br.borrow());
cggi_blind_rotate(module, &mut res, &lwe, &lut, &brk_exec, scratch_br.borrow());
let mut pt_have: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_res);
res.decrypt(module, &mut pt_have, &sk_glwe_dft, scratch.borrow());
let mut lwe_2n: Vec<i64> = vec![0i64; lwe.n() + 1]; // TODO: from scratch space
mod_switch_2n(
2 * lut.domain_size(),
&mut lwe_2n,
&lwe.to_ref(),
lut.rotation_direction(),
);
let pt_want: i64 = (lwe_2n[0]
+ lwe_2n[1..]
.iter()
.zip(sk_lwe.data.at(0, 0))
.map(|(x, y)| x * y)
.sum::<i64>())
& (2 * lut.domain_size() - 1) as i64;
lut.rotate(module, pt_want);
// First limb should be exactly equal (test are parameterized such that the noise does not reach
// the first limb)
assert_eq!(pt_have.data.at(0, 0), lut.data[0].at(0, 0));
}

View File

@@ -1,95 +0,0 @@
use std::vec;
use backend::hal::{
api::{
VecZnxCopy, VecZnxDecodeVeci64, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxRotateInplace, VecZnxSwithcDegree,
},
layouts::{Backend, Module},
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl},
};
use crate::{DivRound, LookUpTable};
pub(crate) fn test_lut_standard<B: Backend>(module: &Module<B>)
where
Module<B>: VecZnxRotateInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxSwithcDegree
+ VecZnxCopy
+ VecZnxDecodeVeci64,
B: ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
{
let n: usize = module.n();
let basek: usize = 20;
let k_lut: usize = 40;
let message_modulus: usize = 16;
let extension_factor: usize = 1;
let log_scale: usize = basek + 1;
let mut f: Vec<i64> = vec![0i64; message_modulus];
f.iter_mut()
.enumerate()
.for_each(|(i, x)| *x = (i as i64) - 8);
let mut lut: LookUpTable = LookUpTable::alloc(n, basek, k_lut, extension_factor);
lut.set(module, &f, log_scale);
let half_step: i64 = lut.domain_size().div_round(message_modulus << 1) as i64;
lut.rotate(module, half_step);
let step: usize = lut.domain_size().div_round(message_modulus);
let mut lut_dec: Vec<i64> = vec![0i64; module.n()];
module.decode_vec_i64(basek, &lut.data[0], 0, log_scale, &mut lut_dec);
(0..lut.domain_size()).step_by(step).for_each(|i| {
(0..step).for_each(|_| {
assert_eq!(f[i / step] % message_modulus as i64, lut_dec[i]);
});
});
}
pub(crate) fn test_lut_extended<B: Backend>(module: &Module<B>)
where
Module<B>: VecZnxRotateInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxSwithcDegree
+ VecZnxCopy
+ VecZnxDecodeVeci64,
B: ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
{
let n: usize = module.n();
let basek: usize = 20;
let k_lut: usize = 40;
let message_modulus: usize = 16;
let extension_factor: usize = 4;
let log_scale: usize = basek + 1;
let mut f: Vec<i64> = vec![0i64; message_modulus];
f.iter_mut()
.enumerate()
.for_each(|(i, x)| *x = (i as i64) - 8);
let mut lut: LookUpTable = LookUpTable::alloc(n, basek, k_lut, extension_factor);
lut.set(&module, &f, log_scale);
let half_step: i64 = lut.domain_size().div_round(message_modulus << 1) as i64;
lut.rotate(&module, half_step);
let step: usize = module.n().div_round(message_modulus);
let mut lut_dec: Vec<i64> = vec![0i64; module.n()];
(0..extension_factor).for_each(|ext| {
module.decode_vec_i64(basek, &lut.data[ext], 0, log_scale, &mut lut_dec);
(0..module.n()).step_by(step).for_each(|i| {
(0..step).for_each(|_| {
assert_eq!(f[i / step] % message_modulus as i64, lut_dec[i]);
});
});
});
}

View File

@@ -1,15 +0,0 @@
use backend::hal::tests::serialization::test_reader_writer_interface;
use crate::{BlindRotationKeyCGGI, BlindRotationKeyCGGICompressed};
#[test]
fn test_cggi_blind_rotation_key_serialization() {
let original: BlindRotationKeyCGGI<Vec<u8>> = BlindRotationKeyCGGI::alloc(256, 64, 12, 54, 2, 2);
test_reader_writer_interface(original);
}
#[test]
fn test_cggi_blind_rotation_key_compressed_serialization() {
let original: BlindRotationKeyCGGICompressed<Vec<u8>> = BlindRotationKeyCGGICompressed::alloc(256, 64, 12, 54, 2, 2);
test_reader_writer_interface(original);
}

View File

@@ -1,396 +0,0 @@
use backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxAddScalarInplace, VecZnxAutomorphism, VecZnxAutomorphismInplace, VecZnxCopy,
VecZnxStd, VecZnxSubScalarInplace, VecZnxSwithcDegree,
},
layouts::{Backend, Module, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl,
},
};
use sampling::source::Source;
use crate::{
AutomorphismKey, AutomorphismKeyCompressed, AutomorphismKeyEncryptSkFamily, AutomorphismKeyExec, GGLWEExecLayoutFamily,
GLWEDecryptFamily, GLWEKeyswitchFamily, GLWEPlaintext, GLWESecret, GLWESecretExec, Infos,
noise::log2_std_noise_gglwe_product,
};
pub(crate) trait AutomorphismTestModuleFamily<B: Backend> = AutomorphismKeyEncryptSkFamily<B>
+ GLWEKeyswitchFamily<B>
+ VecZnxAutomorphism
+ GGLWEExecLayoutFamily<B>
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ VecZnxAutomorphism
+ VecZnxAutomorphismInplace
+ GLWEDecryptFamily<B>
+ VecZnxSubScalarInplace
+ VecZnxStd
+ VecZnxCopy;
pub(crate) trait AutomorphismTestScratchFamily<B: Backend> = ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxDftImpl<B>
+ TakeVecZnxImpl<B>
+ TakeSvpPPolImpl<B>
+ TakeVecZnxBigImpl<B>;
pub(crate) fn test_automorphisk_key_encrypt_sk<B: Backend>(
module: &Module<B>,
basek: usize,
k_ksk: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: AutomorphismTestModuleFamily<B>,
B: AutomorphismTestScratchFamily<B>,
{
let n: usize = TakeScalarZnx;
let rows: usize = (k_ksk - digits * basek) / (digits * basek);
let mut atk: AutomorphismKey<Vec<u8>> = AutomorphismKey::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(AutomorphismKey::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_exec = GLWESecretExec::from(module, &sk_out);
atk.key
.key
.assert_noise(module, &sk_out_exec, &sk.data, sigma);
}
pub(crate) fn test_automorphisk_key_encrypt_sk_compressed<B: Backend>(
module: &Module<B>,
basek: usize,
k_ksk: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: AutomorphismTestModuleFamily<B>,
B: AutomorphismTestScratchFamily<B>,
{
let n: usize = TakeScalarZnx;
let rows: usize = (k_ksk - digits * basek) / (digits * basek);
let mut atk_compressed: AutomorphismKeyCompressed<Vec<u8>> =
AutomorphismKeyCompressed::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(AutomorphismKey::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_exec = GLWESecretExec::from(module, &sk_out);
let mut atk: AutomorphismKey<Vec<u8>> = AutomorphismKey::alloc(n, basek, k_ksk, rows, digits, rank);
atk.decompress(module, &atk_compressed);
atk.key
.key
.assert_noise(module, &sk_out_exec, &sk.data, sigma);
}
pub(crate) fn test_gglwe_automorphism<B: Backend>(
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>: AutomorphismTestModuleFamily<B>,
B: AutomorphismTestScratchFamily<B>,
{
let n: usize = TakeScalarZnx;
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: AutomorphismKey<Vec<u8>> = AutomorphismKey::alloc(n, basek, k_in, rows_in, digits_in, rank);
let mut auto_key_out: AutomorphismKey<Vec<u8>> = AutomorphismKey::alloc(n, basek, k_out, rows_in, digits_in, rank);
let mut auto_key_apply: AutomorphismKey<Vec<u8>> = AutomorphismKey::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(
AutomorphismKey::encrypt_sk_scratch_space(module, n, basek, k_apply, rank)
| AutomorphismKey::automorphism_scratch_space(module, n, basek, k_out, k_in, k_apply, digits, rank),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(TakeScalarZnx, 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_exec: AutomorphismKeyExec<Vec<u8>, B> =
AutomorphismKeyExec::alloc(module, n, basek, k_apply, rows_apply, digits, rank);
auto_key_apply_exec.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_exec, scratch.borrow());
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(TakeScalarZnx, basek, k_out);
let mut sk_auto: GLWESecret<Vec<u8>> = GLWESecret::alloc(TakeScalarZnx, 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: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_auto);
(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 = module.vec_znx_std(basek, &pt.data, 0).log2();
let noise_want: f64 = log2_std_noise_gglwe_product(
TakeScalarZnx 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
);
});
});
}
pub(crate) fn test_gglwe_automorphism_inplace<B: Backend>(
module: &Module<B>,
p0: i64,
p1: i64,
basek: usize,
digits: usize,
k_in: usize,
k_apply: usize,
sigma: f64,
rank: usize,
) where
Module<B>: AutomorphismTestModuleFamily<B>,
B: AutomorphismTestScratchFamily<B>,
{
let n: usize = TakeScalarZnx;
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: AutomorphismKey<Vec<u8>> = AutomorphismKey::alloc(n, basek, k_in, rows_in, digits_in, rank);
let mut auto_key_apply: AutomorphismKey<Vec<u8>> = AutomorphismKey::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(
AutomorphismKey::encrypt_sk_scratch_space(module, n, basek, k_apply, rank)
| AutomorphismKey::automorphism_inplace_scratch_space(module, n, basek, k_in, k_apply, digits, rank),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(TakeScalarZnx, 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_exec: AutomorphismKeyExec<Vec<u8>, B> =
AutomorphismKeyExec::alloc(module, n, basek, k_apply, rows_apply, digits, rank);
auto_key_apply_exec.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_exec, scratch.borrow());
let mut pt: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(TakeScalarZnx, basek, k_in);
let mut sk_auto: GLWESecret<Vec<u8>> = GLWESecret::alloc(TakeScalarZnx, 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: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_auto);
(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 = module.vec_znx_std(basek, &pt.data, 0).log2();
let noise_want: f64 = log2_std_noise_gglwe_product(
TakeScalarZnx 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

@@ -1,321 +0,0 @@
use backend::hal::{
api::{ScratchAvailable, SvpPPolAlloc, SvpPrepare, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, ZnxView, ZnxViewMut},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, ScalarZnx, ScalarZnxToRef, Scratch, SvpPPol, WriterTo},
};
use sampling::source::Source;
use crate::{
Distribution, GGSWCiphertext, GGSWCiphertextExec, GGSWEncryptSkFamily, GGSWLayoutFamily, GLWESecretExec, Infos, LWESecret,
};
pub struct BlindRotationKeyCGGI<D: Data> {
pub(crate) keys: Vec<GGSWCiphertext<D>>,
pub(crate) dist: Distribution,
}
impl<D: Data> PartialEq for BlindRotationKeyCGGI<D> {
fn eq(&self, other: &Self) -> bool {
if self.keys.len() != other.keys.len() {
return false;
}
for (a, b) in self.keys.iter().zip(other.keys.iter()) {
if a != b {
return false;
}
}
self.dist == other.dist
}
}
impl<D: Data> Eq for BlindRotationKeyCGGI<D> {}
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
impl<D: DataMut> ReaderFrom for BlindRotationKeyCGGI<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),
}
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 BlindRotationKeyCGGI<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),
}
writer.write_u64::<LittleEndian>(self.keys.len() as u64)?;
for key in &self.keys {
key.write_to(writer)?;
}
Ok(())
}
}
impl BlindRotationKeyCGGI<Vec<u8>> {
pub fn alloc(n_gglwe: usize, n_lwe: usize, basek: usize, k: usize, rows: usize, rank: usize) -> Self {
let mut data: Vec<GGSWCiphertext<Vec<u8>>> = Vec::with_capacity(n_lwe);
(0..n_lwe).for_each(|_| data.push(GGSWCiphertext::alloc(n_gglwe, basek, k, rows, 1, rank)));
Self {
keys: data,
dist: Distribution::NONE,
}
}
pub fn generate_from_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
where
Module<B>: GGSWEncryptSkFamily<B>,
{
GGSWCiphertext::encrypt_sk_scratch_space(module, n, basek, k, rank)
}
}
impl<D: DataRef> BlindRotationKeyCGGI<D> {
#[allow(dead_code)]
pub(crate) fn n(&self) -> usize {
self.keys[0].n()
}
#[allow(dead_code)]
pub(crate) fn rows(&self) -> usize {
self.keys[0].rows()
}
#[allow(dead_code)]
pub(crate) fn k(&self) -> usize {
self.keys[0].k()
}
#[allow(dead_code)]
pub(crate) fn size(&self) -> usize {
self.keys[0].size()
}
#[allow(dead_code)]
pub(crate) fn rank(&self) -> usize {
self.keys[0].rank()
}
pub(crate) fn basek(&self) -> usize {
self.keys[0].basek()
}
#[allow(dead_code)]
pub(crate) fn block_size(&self) -> usize {
match self.dist {
Distribution::BinaryBlock(value) => value,
_ => 1,
}
}
}
impl<D: DataMut> BlindRotationKeyCGGI<D> {
pub fn generate_from_sk<DataSkGLWE, DataSkLWE, B: Backend>(
&mut self,
module: &Module<B>,
sk_glwe: &GLWESecretExec<DataSkGLWE, B>,
sk_lwe: &LWESecret<DataSkLWE>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
DataSkGLWE: DataRef,
DataSkLWE: DataRef,
Module<B>: GGSWEncryptSkFamily<B> + VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.keys.len(), sk_lwe.n());
assert!(sk_glwe.n() <= TakeScalarZnx);
assert_eq!(sk_glwe.rank(), self.keys[0].rank());
match sk_lwe.dist {
Distribution::BinaryBlock(_)
| Distribution::BinaryFixed(_)
| Distribution::BinaryProb(_)
| Distribution::ZERO => {}
_ => panic!(
"invalid GLWESecret distribution: must be BinaryBlock, BinaryFixed or BinaryProb (or ZERO for debugging)"
),
}
}
self.dist = sk_lwe.dist;
let mut pt: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(sk_glwe.n(), 1);
let sk_ref: ScalarZnx<&[u8]> = sk_lwe.data.to_ref();
self.keys.iter_mut().enumerate().for_each(|(i, ggsw)| {
pt.at_mut(0, 0)[0] = sk_ref.at(0, 0)[i];
ggsw.encrypt_sk(module, &pt, sk_glwe, source_xa, source_xe, sigma, scratch);
});
}
}
#[derive(PartialEq, Eq)]
pub struct BlindRotationKeyCGGIExec<D: Data, B: Backend> {
pub(crate) data: Vec<GGSWCiphertextExec<D, B>>,
pub(crate) dist: Distribution,
pub(crate) x_pow_a: Option<Vec<SvpPPol<Vec<u8>, B>>>,
}
impl<D: Data, B: Backend> BlindRotationKeyCGGIExec<D, B> {
#[allow(dead_code)]
pub(crate) fn n(&self) -> usize {
self.data[0].n()
}
#[allow(dead_code)]
pub(crate) fn rows(&self) -> usize {
self.data[0].rows()
}
#[allow(dead_code)]
pub(crate) fn k(&self) -> usize {
self.data[0].k()
}
#[allow(dead_code)]
pub(crate) fn size(&self) -> usize {
self.data[0].size()
}
#[allow(dead_code)]
pub(crate) fn rank(&self) -> usize {
self.data[0].rank()
}
pub(crate) fn basek(&self) -> usize {
self.data[0].basek()
}
pub(crate) fn block_size(&self) -> usize {
match self.dist {
Distribution::BinaryBlock(value) => value,
_ => 1,
}
}
}
pub trait BlindRotationKeyCGGIExecLayoutFamily<B: Backend> = GGSWLayoutFamily<B> + SvpPPolAlloc<B> + SvpPrepare<B>;
impl<B: Backend> BlindRotationKeyCGGIExec<Vec<u8>, B> {
pub fn alloc(module: &Module<B>, n_glwe: usize, n_lwe: usize, basek: usize, k: usize, rows: usize, rank: usize) -> Self
where
Module<B>: BlindRotationKeyCGGIExecLayoutFamily<B>,
{
let mut data: Vec<GGSWCiphertextExec<Vec<u8>, B>> = Vec::with_capacity(n_lwe);
(0..n_lwe).for_each(|_| {
data.push(GGSWCiphertextExec::alloc(
module, n_glwe, basek, k, rows, 1, rank,
))
});
Self {
data,
dist: Distribution::NONE,
x_pow_a: None,
}
}
pub fn from<DataOther>(module: &Module<B>, other: &BlindRotationKeyCGGI<DataOther>, scratch: &mut Scratch<B>) -> Self
where
DataOther: DataRef,
Module<B>: BlindRotationKeyCGGIExecLayoutFamily<B>,
{
let mut brk: BlindRotationKeyCGGIExec<Vec<u8>, B> = Self::alloc(
module,
other.n(),
other.keys.len(),
other.basek(),
other.k(),
other.rows(),
other.rank(),
);
brk.prepare(module, other, scratch);
brk
}
}
impl<D: DataMut, B: Backend> BlindRotationKeyCGGIExec<D, B> {
pub fn prepare<DataOther>(&mut self, module: &Module<B>, other: &BlindRotationKeyCGGI<DataOther>, scratch: &mut Scratch<B>)
where
DataOther: DataRef,
Module<B>: BlindRotationKeyCGGIExecLayoutFamily<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.data.len(), other.keys.len());
}
let n: usize = other.n();
self.data
.iter_mut()
.zip(other.keys.iter())
.for_each(|(ggsw_exec, other)| {
ggsw_exec.prepare(module, other, scratch);
});
self.dist = other.dist;
match other.dist {
Distribution::BinaryBlock(_) => {
let mut x_pow_a: Vec<SvpPPol<Vec<u8>, B>> = Vec::with_capacity(n << 1);
let mut buf: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
(0..n << 1).for_each(|i| {
let mut res: SvpPPol<Vec<u8>, B> = module.svp_ppol_alloc(n, 1);
set_xai_plus_y(module, i, 0, &mut res, &mut buf);
x_pow_a.push(res);
});
self.x_pow_a = Some(x_pow_a);
}
_ => {}
}
}
}
pub fn set_xai_plus_y<A, C, B: Backend>(module: &Module<B>, ai: usize, y: i64, res: &mut SvpPPol<A, B>, buf: &mut ScalarZnx<C>)
where
A: DataMut,
C: DataMut,
Module<B>: SvpPrepare<B>,
{
let n: usize = res.n();
{
let raw: &mut [i64] = buf.at_mut(0, 0);
if ai < n {
raw[ai] = 1;
} else {
raw[(ai - n) & (n - 1)] = -1;
}
raw[0] += y;
}
module.svp_prepare(res, 0, buf, 0);
{
let raw: &mut [i64] = buf.at_mut(0, 0);
if ai < n {
raw[ai] = 0;
} else {
raw[(ai - n) & (n - 1)] = 0;
}
raw[0] = 0;
}
}

View File

@@ -1,4 +0,0 @@
mod cpu_spqlios;
mod generic_cggi;
mod generic_lut;
mod generic_serialization;

View File

@@ -1,508 +0,0 @@
use std::{collections::HashMap, time::Instant, usize};
use backend::hal::{
api::{
ScratchAvailable, TakeMatZnx, TakeScalarZnx, TakeSvpPPol, TakeVecZnx, TakeVecZnxBig, TakeVecZnxDft, TakeVecZnxDftSlice,
TakeVecZnxSlice, VecZnxAddInplace, VecZnxAddScalarInplace, VecZnxAutomorphism, VecZnxAutomorphismInplace,
VecZnxBigAutomorphismInplace, VecZnxBigSubSmallBInplace, VecZnxCopy, VecZnxDftCopy, VecZnxDftToVecZnxBigTmpA,
VecZnxNegateInplace, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxRotateInplace, VecZnxRshInplace, VecZnxSub,
VecZnxSubABInplace, VecZnxSwithcDegree,
},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch},
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl},
};
use sampling::source::Source;
use crate::{
AutomorphismKey, AutomorphismKeyEncryptSkFamily, AutomorphismKeyExec, BlindRotationKeyCGGI, BlindRotationKeyCGGIExec,
BlindRotationKeyCGGIExecLayoutFamily, CCGIBlindRotationFamily, GGSWCiphertext, GGSWEncryptSkFamily, GLWECiphertext, GLWEOps,
GLWESecret, GLWESecretExec, GLWESecretFamily, GLWETensorKey, GLWETensorKeyEncryptSkFamily, GLWETensorKeyExec,
GLWETraceFamily, Infos, LWECiphertext, LWESecret, LookUpTable, LookUpTableRotationDirection, TakeGGLWE, TakeGLWECt,
cggi_blind_rotate,
};
pub struct CircuitBootstrappingKeyCGGI<D: Data> {
pub(crate) brk: BlindRotationKeyCGGI<D>,
pub(crate) tsk: GLWETensorKey<Vec<u8>>,
pub(crate) atk: HashMap<i64, AutomorphismKey<Vec<u8>>>,
}
impl CircuitBootstrappingKeyCGGI<Vec<u8>> {
pub fn generate<DLwe, DGlwe, B: Backend>(
module: &Module<B>,
basek: usize,
sk_lwe: &LWESecret<DLwe>,
sk_glwe: &GLWESecret<DGlwe>,
k_brk: usize,
rows_brk: usize,
k_trace: usize,
rows_trace: usize,
k_tsk: usize,
rows_tsk: usize,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) -> Self
where
Module<B>: GLWESecretFamily<B>
+ GGSWEncryptSkFamily<B>
+ VecZnxAddScalarInplace
+ AutomorphismKeyEncryptSkFamily<B>
+ VecZnxAutomorphism
+ VecZnxSwithcDegree
+ GLWETensorKeyEncryptSkFamily<B>,
DLwe: DataRef,
DGlwe: DataRef,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeSvpPPol<B> + TakeVecZnxBig<B>,
{
let mut auto_keys: HashMap<i64, AutomorphismKey<Vec<u8>>> = HashMap::new();
let gal_els: Vec<i64> = GLWECiphertext::trace_galois_elements(&module);
gal_els.iter().for_each(|gal_el| {
let mut key: AutomorphismKey<Vec<u8>> =
AutomorphismKey::alloc(sk_glwe.n(), basek, k_trace, rows_trace, 1, sk_glwe.rank());
key.encrypt_sk(
&module, *gal_el, &sk_glwe, source_xa, source_xe, sigma, scratch,
);
auto_keys.insert(*gal_el, key);
});
let sk_glwe_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_glwe);
let mut brk: BlindRotationKeyCGGI<Vec<u8>> = BlindRotationKeyCGGI::alloc(
sk_glwe.n(),
sk_lwe.n(),
basek,
k_brk,
rows_brk,
sk_glwe.rank(),
);
brk.generate_from_sk(
module,
&sk_glwe_exec,
sk_lwe,
source_xa,
source_xe,
sigma,
scratch,
);
let mut tsk: GLWETensorKey<Vec<u8>> = GLWETensorKey::alloc(sk_glwe.n(), basek, k_tsk, rows_tsk, 1, sk_glwe.rank());
tsk.encrypt_sk(module, &sk_glwe, source_xa, source_xe, sigma, scratch);
Self {
brk,
atk: auto_keys,
tsk,
}
}
}
pub struct CircuitBootstrappingKeyCGGIExec<D: Data, B: Backend> {
pub(crate) brk: BlindRotationKeyCGGIExec<D, B>,
pub(crate) tsk: GLWETensorKeyExec<Vec<u8>, B>,
pub(crate) atk: HashMap<i64, AutomorphismKeyExec<Vec<u8>, B>>,
}
impl<B: Backend> CircuitBootstrappingKeyCGGIExec<Vec<u8>, B> {
pub fn from<DataOther: DataRef>(
module: &Module<B>,
other: &CircuitBootstrappingKeyCGGI<DataOther>,
scratch: &mut Scratch<B>,
) -> CircuitBootstrappingKeyCGGIExec<Vec<u8>, B>
where
Module<B>: BlindRotationKeyCGGIExecLayoutFamily<B>,
{
let brk: BlindRotationKeyCGGIExec<Vec<u8>, B> = BlindRotationKeyCGGIExec::from(module, &other.brk, scratch);
let tsk: GLWETensorKeyExec<Vec<u8>, B> = GLWETensorKeyExec::from(module, &other.tsk, scratch);
let mut atk: HashMap<i64, AutomorphismKeyExec<Vec<u8>, B>> = HashMap::new();
for (key, value) in &other.atk {
atk.insert(*key, AutomorphismKeyExec::from(module, value, scratch));
}
CircuitBootstrappingKeyCGGIExec { brk, tsk, atk }
}
}
pub trait CGGICircuitBootstrapFamily<B: Backend> = VecZnxRotateInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxNormalizeTmpBytes
+ CCGIBlindRotationFamily<B>
+ VecZnxSwithcDegree
+ VecZnxBigAutomorphismInplace<B>
+ VecZnxRshInplace
+ VecZnxDftCopy<B>
+ VecZnxDftToVecZnxBigTmpA<B>
+ VecZnxSub
+ VecZnxAddInplace
+ VecZnxNegateInplace
+ VecZnxCopy
+ VecZnxSubABInplace
+ GLWETraceFamily<B>
+ VecZnxRotateInplace
+ VecZnxAutomorphismInplace
+ VecZnxBigSubSmallBInplace<B>;
pub fn circuit_bootstrap_to_constant_cggi<DRes, DLwe, DBrk, B: Backend>(
module: &Module<B>,
res: &mut GGSWCiphertext<DRes>,
lwe: &LWECiphertext<DLwe>,
log_domain: usize,
extension_factor: usize,
key: &CircuitBootstrappingKeyCGGIExec<DBrk, B>,
scratch: &mut Scratch<B>,
) where
DRes: DataMut,
DLwe: DataRef,
DBrk: DataRef,
Module<B>: CGGICircuitBootstrapFamily<B>,
B: ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
Scratch<B>: TakeVecZnx
+ TakeVecZnxDftSlice<B>
+ TakeVecZnxBig<B>
+ TakeVecZnxDft<B>
+ TakeMatZnx
+ ScratchAvailable
+ TakeVecZnxSlice,
{
circuit_bootstrap_core_cggi(
false,
module,
0,
res,
lwe,
log_domain,
extension_factor,
key,
scratch,
);
}
pub fn circuit_bootstrap_to_exponent_cggi<DRes, DLwe, DBrk, B: Backend>(
module: &Module<B>,
log_gap_out: usize,
res: &mut GGSWCiphertext<DRes>,
lwe: &LWECiphertext<DLwe>,
log_domain: usize,
extension_factor: usize,
key: &CircuitBootstrappingKeyCGGIExec<DBrk, B>,
scratch: &mut Scratch<B>,
) where
DRes: DataMut,
DLwe: DataRef,
DBrk: DataRef,
Module<B>: CGGICircuitBootstrapFamily<B>,
B: ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
Scratch<B>: TakeVecZnx
+ TakeVecZnxDftSlice<B>
+ TakeVecZnxBig<B>
+ TakeVecZnxDft<B>
+ TakeMatZnx
+ ScratchAvailable
+ TakeVecZnxSlice,
{
circuit_bootstrap_core_cggi(
true,
module,
log_gap_out,
res,
lwe,
log_domain,
extension_factor,
key,
scratch,
);
}
pub fn circuit_bootstrap_core_cggi<DRes, DLwe, DBrk, B: Backend>(
to_exponent: bool,
module: &Module<B>,
log_gap_out: usize,
res: &mut GGSWCiphertext<DRes>,
lwe: &LWECiphertext<DLwe>,
log_domain: usize,
extension_factor: usize,
key: &CircuitBootstrappingKeyCGGIExec<DBrk, B>,
scratch: &mut Scratch<B>,
) where
DRes: DataMut,
DLwe: DataRef,
DBrk: DataRef,
Module<B>: CGGICircuitBootstrapFamily<B>,
B: ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
Scratch<B>: TakeGGLWE<B>
+ TakeVecZnxDftSlice<B>
+ TakeVecZnxBig<B>
+ TakeVecZnxDft<B>
+ TakeVecZnx
+ ScratchAvailable
+ TakeVecZnxSlice,
{
#[cfg(debug_assertions)]
{
use crate::Infos;
assert_eq!(res.n(), key.brk.n());
assert_eq!(lwe.basek(), key.brk.basek());
assert_eq!(res.basek(), key.brk.basek());
}
let n: usize = res.n();
let basek: usize = res.basek();
let rows: usize = res.rows();
let rank: usize = res.rank();
let k: usize = res.k();
let alpha: usize = rows.next_power_of_two();
let mut f: Vec<i64> = vec![0i64; (1 << log_domain) * alpha];
if to_exponent {
(0..rows).for_each(|i| {
f[i] = 1 << (basek * (rows - 1 - i));
});
} else {
(0..1 << log_domain).for_each(|j| {
(0..rows).for_each(|i| {
f[j * alpha + i] = j as i64 * (1 << (basek * (rows - 1 - i)));
});
});
}
// Lut precision, basically must be able to hold the decomposition power basis of the GGSW
let mut lut: LookUpTable = LookUpTable::alloc(n, basek, basek * rows, extension_factor);
lut.set(module, &f, basek * rows);
if to_exponent {
lut.set_rotation_direction(LookUpTableRotationDirection::Right);
}
// TODO: separate GGSW k from output of blind rotation k
let (mut res_glwe, scratch1) = scratch.take_glwe_ct(n, basek, k, rank);
let (mut tmp_gglwe, scratch2) = scratch1.take_gglwe(n, basek, k, rows, 1, rank, rank);
let now: Instant = Instant::now();
cggi_blind_rotate(module, &mut res_glwe, &lwe, &lut, &key.brk, scratch2);
println!("cggi_blind_rotate: {} ms", now.elapsed().as_millis());
let gap: usize = 2 * lut.drift / lut.extension_factor();
let log_gap_in: usize = (usize::BITS - (gap * alpha - 1).leading_zeros()) as _;
(0..rows).for_each(|i| {
let mut tmp_glwe: GLWECiphertext<&mut [u8]> = tmp_gglwe.at_mut(i, 0);
if to_exponent {
let now: Instant = Instant::now();
// Isolates i-th LUT and moves coefficients according to requested gap.
post_process(
module,
&mut tmp_glwe,
&res_glwe,
log_gap_in,
log_gap_out,
log_domain,
&key.atk,
scratch2,
);
println!("post_process: {} ms", now.elapsed().as_millis());
} else {
tmp_glwe.trace(module, 0, module.log_n(), &res_glwe, &key.atk, scratch2);
}
if i < rows {
res_glwe.rotate_inplace(module, -(gap as i64));
}
});
// Expands GGLWE to GGSW using GGLWE(s^2)
res.from_gglwe(module, &tmp_gglwe, &key.tsk, scratch2);
}
fn post_process<DataRes, DataA, B: Backend>(
module: &Module<B>,
res: &mut GLWECiphertext<DataRes>,
a: &GLWECiphertext<DataA>,
log_gap_in: usize,
log_gap_out: usize,
log_domain: usize,
auto_keys: &HashMap<i64, AutomorphismKeyExec<Vec<u8>, B>>,
scratch: &mut Scratch<B>,
) where
DataRes: DataMut,
DataA: DataRef,
Module<B>: CGGICircuitBootstrapFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
let log_n: usize = module.log_n();
let mut cts: HashMap<usize, GLWECiphertext<Vec<u8>>> = HashMap::new();
// First partial trace, vanishes all coefficients which are not multiples of gap_in
// [1, 1, 1, 1, 0, 0, 0, ..., 0, 0, -1, -1, -1, -1] -> [1, 0, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0]
res.trace(
module,
module.log_n() - log_gap_in as usize + 1,
log_n,
&a,
auto_keys,
scratch,
);
// TODO: optimize with packing and final partial trace
// If gap_out < gap_in, then we need to repack, i.e. reduce the cap between coefficients.
if log_gap_in != log_gap_out {
let steps: i32 = 1 << log_domain;
(0..steps).for_each(|i| {
if i != 0 {
res.rotate_inplace(module, -(1 << log_gap_in));
}
cts.insert(i as usize * (1 << log_gap_out), res.clone());
});
let now: Instant = Instant::now();
pack(module, &mut cts, log_gap_out, auto_keys, scratch);
println!("pack: {} ms", now.elapsed().as_millis());
let packed: GLWECiphertext<Vec<u8>> = cts.remove(&0).unwrap();
res.trace(
module,
log_n - log_gap_out,
log_n,
&packed,
auto_keys,
scratch,
);
}
}
pub fn pack<D: DataMut, B: Backend>(
module: &Module<B>,
cts: &mut HashMap<usize, GLWECiphertext<D>>,
log_gap_out: usize,
auto_keys: &HashMap<i64, AutomorphismKeyExec<Vec<u8>, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: CGGICircuitBootstrapFamily<B>,
Scratch<B>: TakeVecZnx + TakeVecZnxDft<B> + ScratchAvailable,
{
let log_n: usize = module.log_n();
let basek: usize = cts.get(&0).unwrap().basek();
let k: usize = cts.get(&0).unwrap().k();
let rank: usize = cts.get(&0).unwrap().rank();
(0..log_n - log_gap_out).for_each(|i| {
let now: Instant = Instant::now();
let t = 16.min(1 << (log_n - 1 - i));
let auto_key: &AutomorphismKeyExec<Vec<u8>, B>;
if i == 0 {
auto_key = auto_keys.get(&-1).unwrap()
} else {
auto_key = auto_keys.get(&module.galois_element(1 << (i - 1))).unwrap();
}
(0..t).for_each(|j| {
let mut a: Option<GLWECiphertext<D>> = cts.remove(&j);
let mut b: Option<GLWECiphertext<D>> = cts.remove(&(j + t));
combine(
module,
basek,
k,
rank,
a.as_mut(),
b.as_mut(),
i,
auto_key,
scratch,
);
if let Some(a) = a {
cts.insert(j, a);
} else if let Some(b) = b {
cts.insert(j, b);
}
});
println!("combine: {} us", now.elapsed().as_micros());
});
}
fn combine<A: DataMut, D: DataMut, DataAK: DataRef, B: Backend>(
module: &Module<B>,
basek: usize,
k: usize,
rank: usize,
a: Option<&mut GLWECiphertext<A>>,
b: Option<&mut GLWECiphertext<D>>,
i: usize,
auto_key: &AutomorphismKeyExec<DataAK, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: CGGICircuitBootstrapFamily<B>,
Scratch<B>: TakeVecZnx + TakeVecZnxDft<B> + ScratchAvailable,
{
// 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 let Some(a) = a {
let n: usize = a.n();
let log_n: usize = (u64::BITS - (n - 1).leading_zeros()) as _;
let t: i64 = 1 << (log_n - i - 1);
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)
tmp_b.automorphism_inplace(module, auto_key, scratch_1);
// 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)
a.automorphism_add_inplace(module, auto_key, scratch);
}
} else {
if let Some(b) = b {
let n: usize = b.n();
let log_n: usize = (u64::BITS - (n - 1).leading_zeros()) as _;
let t: i64 = 1 << (log_n - i - 1);
let (mut tmp_b, scratch_1) = scratch.take_glwe_ct(n, basek, k, rank);
tmp_b.rotate(module, t, b);
tmp_b.rsh(module, 1);
// a = (b* X^t - phi(b* X^t))
b.automorphism_sub_ba(module, &tmp_b, auto_key, scratch_1);
}
}
}

View File

@@ -1,6 +0,0 @@
mod circuit_bootstrapping;
pub use circuit_bootstrapping::*;
#[cfg(test)]
mod test_fft64;

View File

@@ -1,357 +0,0 @@
use std::time::Instant;
use backend::{
hal::{
api::{
ModuleNew, ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphism,
VecZnxEncodeCoeffsi64, VecZnxFillUniform, VecZnxNormalizeInplace, VecZnxRotateInplace, VecZnxStd, VecZnxSwithcDegree,
ZnxView, ZnxViewMut,
},
layouts::{Backend, Module, ScalarZnx, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeMatZnxImpl, TakeScalarZnxImpl,
TakeSvpPPolImpl, TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxDftSliceImpl, TakeVecZnxImpl, TakeVecZnxSliceImpl,
},
},
implementation::cpu_spqlios::FFT64,
};
use sampling::source::Source;
use crate::{
AutomorphismKeyEncryptSkFamily, BlindRotationKeyCGGIExecLayoutFamily, GGSWAssertNoiseFamily, GGSWCiphertext,
GGSWCiphertextExec, GGSWEncryptSkFamily, GLWECiphertext, GLWEDecryptFamily, GLWEPlaintext, GLWESecret, GLWESecretExec,
GLWESecretFamily, GLWETensorKeyEncryptSkFamily, LWECiphertext, LWESecret,
circuit_bootstrapping::circuit_bootstrapping::{
CGGICircuitBootstrapFamily, CircuitBootstrappingKeyCGGI, CircuitBootstrappingKeyCGGIExec,
circuit_bootstrap_to_constant_cggi, circuit_bootstrap_to_exponent_cggi,
},
lwe::LWEPlaintext,
};
#[test]
fn test_to_exponent() {
let module: Module<FFT64> = Module::<FFT64>::new(256);
to_exponent(&module);
}
fn to_exponent<B: Backend>(module: &Module<B>)
where
Module<B>: GLWESecretFamily<B>
+ VecZnxEncodeCoeffsi64
+ VecZnxFillUniform
+ VecZnxAddNormal
+ VecZnxNormalizeInplace<B>
+ GLWESecretFamily<B>
+ GGSWEncryptSkFamily<B>
+ VecZnxAddScalarInplace
+ AutomorphismKeyEncryptSkFamily<B>
+ VecZnxAutomorphism
+ VecZnxSwithcDegree
+ GLWETensorKeyEncryptSkFamily<B>
+ BlindRotationKeyCGGIExecLayoutFamily<B>
+ CGGICircuitBootstrapFamily<B>
+ GLWEDecryptFamily<B>
+ GGSWAssertNoiseFamily<B>
+ VecZnxStd,
B: ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ TakeVecZnxDftImpl<B>
+ ScratchAvailableImpl<B>
+ TakeVecZnxImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeSvpPPolImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeVecZnxDftSliceImpl<B>
+ TakeMatZnxImpl<B>
+ TakeVecZnxSliceImpl<B>,
{
let n: usize = module.n();
let basek: usize = 17;
let extension_factor: usize = 1;
let rank: usize = 1;
let sigma: f64 = 3.2;
let n_lwe: usize = 77;
let k_lwe_pt: usize = 4;
let k_lwe_ct: usize = 22;
let block_size: usize = 7;
let k_brk: usize = 5 * basek;
let rows_brk: usize = 4;
let k_trace: usize = 5 * basek;
let rows_trace: usize = 4;
let k_tsk: usize = 5 * basek;
let rows_tsk: usize = 4;
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(1 << 23);
let mut source_xs: Source = Source::new([1u8; 32]);
let mut source_xa: Source = Source::new([1u8; 32]);
let mut source_xe: Source = Source::new([1u8; 32]);
let mut sk_lwe: LWESecret<Vec<u8>> = LWESecret::alloc(n_lwe);
sk_lwe.fill_binary_block(block_size, &mut source_xs);
let mut sk_glwe: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_glwe.fill_ternary_prob(0.5, &mut source_xs);
let sk_glwe_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_glwe);
let data: i64 = 1;
let mut pt_lwe: LWEPlaintext<Vec<u8>> = LWEPlaintext::alloc(basek, k_lwe_pt);
module.encode_coeff_i64(basek, &mut pt_lwe.data, 0, k_lwe_pt + 2, 0, data, k_lwe_pt);
println!("pt_lwe: {}", pt_lwe.data);
let mut ct_lwe: LWECiphertext<Vec<u8>> = LWECiphertext::alloc(n_lwe, basek, k_lwe_ct);
ct_lwe.encrypt_sk(
module,
&pt_lwe,
&sk_lwe,
&mut source_xa,
&mut source_xe,
sigma,
);
let now: Instant = Instant::now();
let cbt_key: CircuitBootstrappingKeyCGGI<Vec<u8>> = CircuitBootstrappingKeyCGGI::generate(
module,
basek,
&sk_lwe,
&sk_glwe,
k_brk,
rows_brk,
k_trace,
rows_trace,
k_tsk,
rows_tsk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
println!("CBT-KGEN: {} ms", now.elapsed().as_millis());
let k_ggsw_res: usize = 4 * basek;
let rows_ggsw_res: usize = 2;
let mut res: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_ggsw_res, rows_ggsw_res, 1, rank);
let log_gap_out = 1;
let cbt_exec: CircuitBootstrappingKeyCGGIExec<Vec<u8>, B> =
CircuitBootstrappingKeyCGGIExec::from(module, &cbt_key, scratch.borrow());
let now: Instant = Instant::now();
circuit_bootstrap_to_exponent_cggi(
module,
log_gap_out,
&mut res,
&ct_lwe,
k_lwe_pt,
extension_factor,
&cbt_exec,
scratch.borrow(),
);
println!("CBT: {} ms", now.elapsed().as_millis());
// X^{data * 2^log_gap_out}
let mut pt_ggsw: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
pt_ggsw.at_mut(0, 0)[0] = 1;
module.vec_znx_rotate_inplace(data * (1 << log_gap_out), &mut pt_ggsw.as_vec_znx_mut(), 0);
res.print_noise(module, &sk_glwe_exec, &pt_ggsw);
let k_glwe: usize = k_ggsw_res;
let mut ct_glwe: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_glwe, rank);
let mut pt_glwe: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, basek);
pt_glwe.data.at_mut(0, 0)[0] = 1 << (basek - 2);
ct_glwe.encrypt_sk(
module,
&pt_glwe,
&sk_glwe_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let res_exec: GGSWCiphertextExec<Vec<u8>, B> = GGSWCiphertextExec::from(module, &res, scratch.borrow());
ct_glwe.external_product_inplace(module, &res_exec, scratch.borrow());
let mut pt_res: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_glwe);
ct_glwe.decrypt(module, &mut pt_res, &sk_glwe_exec, scratch.borrow());
// Parameters are set such that the first limb should be noiseless.
let mut pt_want: Vec<i64> = vec![0i64; module.n()];
pt_want[data as usize * (1 << log_gap_out)] = pt_glwe.data.at(0, 0)[0];
assert_eq!(pt_res.data.at(0, 0), pt_want);
}
#[test]
fn test_to_constant() {
let module: Module<FFT64> = Module::<FFT64>::new(256);
to_constant(&module);
}
fn to_constant<B: Backend>(module: &Module<B>)
where
Module<B>: GLWESecretFamily<B>
+ VecZnxEncodeCoeffsi64
+ VecZnxFillUniform
+ VecZnxAddNormal
+ VecZnxNormalizeInplace<B>
+ GLWESecretFamily<B>
+ GGSWEncryptSkFamily<B>
+ VecZnxAddScalarInplace
+ AutomorphismKeyEncryptSkFamily<B>
+ VecZnxAutomorphism
+ VecZnxSwithcDegree
+ GLWETensorKeyEncryptSkFamily<B>
+ BlindRotationKeyCGGIExecLayoutFamily<B>
+ CGGICircuitBootstrapFamily<B>
+ GLWEDecryptFamily<B>
+ GGSWAssertNoiseFamily<B>
+ VecZnxStd,
B: ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ TakeVecZnxDftImpl<B>
+ ScratchAvailableImpl<B>
+ TakeVecZnxImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeSvpPPolImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeVecZnxDftSliceImpl<B>
+ TakeMatZnxImpl<B>
+ TakeVecZnxSliceImpl<B>,
{
let n = module.n();
let basek: usize = 14;
let extension_factor: usize = 1;
let rank: usize = 2;
let sigma: f64 = 3.2;
let n_lwe: usize = 77;
let k_lwe_pt: usize = 1;
let k_lwe_ct: usize = 13;
let block_size: usize = 7;
let k_brk: usize = 5 * basek;
let rows_brk: usize = 3;
let k_trace: usize = 5 * basek;
let rows_trace: usize = 4;
let k_tsk: usize = 5 * basek;
let rows_tsk: usize = 4;
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(1 << 23);
let mut source_xs: Source = Source::new([1u8; 32]);
let mut source_xa: Source = Source::new([1u8; 32]);
let mut source_xe: Source = Source::new([1u8; 32]);
let mut sk_lwe: LWESecret<Vec<u8>> = LWESecret::alloc(n_lwe);
sk_lwe.fill_binary_block(block_size, &mut source_xs);
let mut sk_glwe: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_glwe.fill_ternary_prob(0.5, &mut source_xs);
let sk_glwe_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_glwe);
let data: i64 = 1;
let mut pt_lwe: LWEPlaintext<Vec<u8>> = LWEPlaintext::alloc(basek, k_lwe_pt);
module.encode_coeff_i64(basek, &mut pt_lwe.data, 0, k_lwe_pt + 2, 0, data, k_lwe_pt);
println!("pt_lwe: {}", pt_lwe.data);
let mut ct_lwe: LWECiphertext<Vec<u8>> = LWECiphertext::alloc(n_lwe, basek, k_lwe_ct);
ct_lwe.encrypt_sk(
module,
&pt_lwe,
&sk_lwe,
&mut source_xa,
&mut source_xe,
sigma,
);
let now: Instant = Instant::now();
let cbt_key: CircuitBootstrappingKeyCGGI<Vec<u8>> = CircuitBootstrappingKeyCGGI::generate(
module,
basek,
&sk_lwe,
&sk_glwe,
k_brk,
rows_brk,
k_trace,
rows_trace,
k_tsk,
rows_tsk,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
println!("CBT-KGEN: {} ms", now.elapsed().as_millis());
let k_ggsw_res: usize = 4 * basek;
let rows_ggsw_res: usize = 3;
let mut res: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_ggsw_res, rows_ggsw_res, 1, rank);
let cbt_exec: CircuitBootstrappingKeyCGGIExec<Vec<u8>, B> =
CircuitBootstrappingKeyCGGIExec::from(module, &cbt_key, scratch.borrow());
let now: Instant = Instant::now();
circuit_bootstrap_to_constant_cggi(
module,
&mut res,
&ct_lwe,
k_lwe_pt,
extension_factor,
&cbt_exec,
scratch.borrow(),
);
println!("CBT: {} ms", now.elapsed().as_millis());
// X^{data * 2^log_gap_out}
let mut pt_ggsw: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
pt_ggsw.at_mut(0, 0)[0] = data;
res.print_noise(module, &sk_glwe_exec, &pt_ggsw);
let k_glwe: usize = k_ggsw_res;
let mut ct_glwe: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(n, basek, k_glwe, rank);
let mut pt_glwe: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, basek);
pt_glwe.data.at_mut(0, 0)[0] = 1 << (basek - k_lwe_pt - 1);
ct_glwe.encrypt_sk(
module,
&pt_glwe,
&sk_glwe_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let res_exec: GGSWCiphertextExec<Vec<u8>, B> = GGSWCiphertextExec::from(module, &res, scratch.borrow());
ct_glwe.external_product_inplace(module, &res_exec, scratch.borrow());
let mut pt_res: GLWEPlaintext<Vec<u8>> = GLWEPlaintext::alloc(n, basek, k_glwe);
ct_glwe.decrypt(module, &mut pt_res, &sk_glwe_exec, scratch.borrow());
// Parameters are set such that the first limb should be noiseless.
let mut pt_want: Vec<i64> = vec![0i64; module.n()];
pt_want[0] = pt_glwe.data.at(0, 0)[0] * data;
assert_eq!(pt_res.data.at(0, 0), pt_want);
}

View File

@@ -1 +0,0 @@
mod circuit_bootstrapping;

View File

@@ -0,0 +1,70 @@
use backend::hal::{
api::{ScratchAvailable, TakeVecZnx, TakeVecZnxDft, ZnxView, ZnxViewMut, ZnxZero},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{
TakeGLWECt,
layouts::{GLWECiphertext, Infos, LWECiphertext, prepared::GLWEToLWESwitchingKeyExec},
};
use crate::trait_families::GLWEKeyswitchFamily;
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>: GLWEKeyswitchFamily<B>,
{
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: &GLWEToLWESwitchingKeyExec<DKs, B>,
scratch: &mut Scratch<B>,
) where
DGlwe: DataRef,
DKs: DataRef,
Module<B>: GLWEKeyswitchFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[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,63 @@
use backend::hal::{
api::{ScratchAvailable, TakeVecZnx, TakeVecZnxDft, ZnxView, ZnxViewMut, ZnxZero},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{
TakeGLWECt,
layouts::{GLWECiphertext, Infos, LWECiphertext, prepared::LWEToGLWESwitchingKeyExec},
};
use crate::trait_families::GLWEKeyswitchFamily;
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>: GLWEKeyswitchFamily<B>,
{
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: &LWEToGLWESwitchingKeyExec<DKsk, B>,
scratch: &mut Scratch<B>,
) where
DLwe: DataRef,
DKsk: DataRef,
Module<B>: GLWEKeyswitchFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[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

@@ -1,23 +1,15 @@
use backend::hal::{
api::{
DataViewMut, SvpApplyInplace, TakeVecZnxBig, TakeVecZnxDft, VecZnxBigAddInplace, VecZnxBigAddSmallInplace,
VecZnxBigAllocBytes, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume,
VecZnxNormalizeTmpBytes,
VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxNormalizeTmpBytes,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{GLWECiphertext, GLWEPlaintext, GLWESecretExec, Infos};
pub trait GLWEDecryptFamily<B: Backend> = VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddInplace<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes;
use crate::{
layouts::{GLWECiphertext, GLWEPlaintext, Infos, prepared::GLWESecretExec},
trait_families::GLWEDecryptFamily,
};
impl GLWECiphertext<Vec<u8>> {
pub fn decrypt_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize

View File

@@ -4,7 +4,7 @@ use backend::hal::{
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl},
};
use crate::{Infos, LWECiphertext, LWESecret, SetMetaData, lwe::LWEPlaintext};
use crate::layouts::{Infos, LWECiphertext, LWEPlaintext, LWESecret, SetMetaData};
impl<DataSelf> LWECiphertext<DataSelf>
where

View File

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

View File

@@ -0,0 +1,88 @@
use backend::hal::{
api::{
ScratchAvailable, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxAutomorphism,
VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWESecret, TakeGLWESecretExec,
layouts::{
GLWESecret, Infos,
compressed::{GGLWEAutomorphismKeyCompressed, GGLWESwitchingKeyCompressed},
},
};
use crate::trait_families::{GGLWEAutomorphismKeyEncryptSkFamily, GLWESecretExecModuleFamily};
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>: GGLWEAutomorphismKeyEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
GGLWESwitchingKeyCompressed::encrypt_sk_scratch_space(module, n, basek, k, rank, rank) + GLWESecret::bytes_of(n, rank)
}
}
impl<DataSelf: DataMut> GGLWEAutomorphismKeyCompressed<DataSelf> {
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>: GGLWEAutomorphismKeyEncryptSkFamily<B>
+ VecZnxSwithcDegree
+ VecZnxAutomorphism
+ VecZnxAddScalarInplace
+ GLWESecretExecModuleFamily<B>,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
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,121 @@
use backend::hal::{
api::{ScratchAvailable, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxNormalizeInplace, ZnxZero},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWEPt,
encryption::glwe_encrypt_sk_internal,
layouts::{GGLWECiphertext, Infos, compressed::GGLWECiphertextCompressed, prepared::GLWESecretExec},
};
use crate::trait_families::{GGLWEEncryptSkFamily, GGLWESwitchingKeyEncryptSkFamily};
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>: GGLWESwitchingKeyEncryptSkFamily<B>,
{
GGLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k)
}
}
impl<D: DataMut> GGLWECiphertextCompressed<D> {
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretExec<DataSk, B>,
seed: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GGLWEEncryptSkFamily<B> + VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use 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,109 @@
use backend::hal::{
api::{ScratchAvailable, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxSwithcDegree},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWESecretExec,
layouts::{
GGLWECiphertext, GLWESecret, GGLWESwitchingKey, Infos, compressed::GGLWESwitchingKeyCompressed, prepared::GLWESecretExec,
},
};
use crate::trait_families::{GGLWESwitchingKeyEncryptSkFamily, GLWESecretExecModuleFamily};
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>: GGLWESwitchingKeyEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
(GGLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k) | ScalarZnx::alloc_bytes(n, 1))
+ ScalarZnx::alloc_bytes(n, rank_in)
+ GLWESecretExec::bytes_of(module, n, rank_out)
}
}
impl<DataSelf: DataMut> GGLWESwitchingKeyCompressed<DataSelf> {
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>:
GGLWESwitchingKeyEncryptSkFamily<B> + VecZnxSwithcDegree + VecZnxAddScalarInplace + GLWESecretExecModuleFamily<B>,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
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_exec(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,85 @@
use backend::hal::{
api::{
ScratchAvailable, SvpApply, TakeScalarZnx, TakeVecZnx, TakeVecZnxBig, TakeVecZnxDft, VecZnxAddScalarInplace,
VecZnxDftToVecZnxBigTmpA, VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWESecret, TakeGLWESecretExec,
layouts::{GGLWETensorKey, GLWESecret, Infos, compressed::GGLWETensorKeyCompressed},
trait_families::GLWEDecryptFamily,
};
use crate::trait_families::{GGLWETensorKeyEncryptSkFamily, GLWESecretExecModuleFamily};
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>: GGLWETensorKeyEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
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>: GGLWETensorKeyEncryptSkFamily<B> + VecZnxSwithcDegree + VecZnxAddScalarInplace + GLWESecretExecModuleFamily<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeVecZnxBig<B> + TakeGLWESecretExec<B> + TakeScalarZnx + TakeVecZnx,
{
#[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_exec(n, rank);
sk_dft_prep.prepare(module, &sk);
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

@@ -1,82 +1,16 @@
use backend::hal::{
api::{ScratchAvailable, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxNormalizeInplace, ZnxZero},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch, VecZnx},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
};
use sampling::source::Source;
use crate::{
GGLWEEncryptSkFamily, GGSWCiphertext, GGSWCiphertextCompressed, GLWECiphertext, GLWEEncryptSkFamily, GLWESecretExec, Infos,
TakeGLWEPt, encrypt_sk_internal,
TakeGLWEPt,
encryption::glwe_encrypt_sk_internal,
layouts::{GGSWCiphertext, Infos, compressed::GGSWCiphertextCompressed, prepared::GLWESecretExec},
};
pub trait GGSWEncryptSkFamily<B: Backend> = GLWEEncryptSkFamily<B>;
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>: GGSWEncryptSkFamily<B>,
{
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> {
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretExec<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GGSWEncryptSkFamily<B> + VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use 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,
);
});
});
}
}
use crate::trait_families::GGSWEncryptSkFamily;
impl GGSWCiphertextCompressed<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank: usize) -> usize
@@ -136,7 +70,7 @@ impl<DataSelf: DataMut> GGSWCiphertextCompressed<DataSelf> {
self.seed[row_i * cols + col_j] = seed;
encrypt_sk_internal(
glwe_encrypt_sk_internal(
module,
self.basek(),
self.k(),

View File

@@ -0,0 +1,79 @@
use backend::hal::{
api::{ScratchAvailable, TakeVecZnx, TakeVecZnxDft},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use sampling::source::Source;
use crate::{
encryption::glwe_ct::glwe_encrypt_sk_internal,
layouts::{GLWECiphertext, GLWEPlaintext, Infos, compressed::GLWECiphertextCompressed, prepared::GLWESecretExec},
};
use crate::trait_families::GLWEEncryptSkFamily;
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>: GLWEEncryptSkFamily<B>,
{
GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k)
}
}
impl<D: DataMut> GLWECiphertextCompressed<D> {
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &GLWEPlaintext<DataPt>,
sk: &GLWESecretExec<DataSk, B>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEEncryptSkFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
self.encrypt_sk_internal(
module,
Some((pt, 0)),
sk,
seed_xa,
source_xe,
sigma,
scratch,
);
}
pub(crate) fn encrypt_sk_internal<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: Option<(&GLWEPlaintext<DataPt>, usize)>,
sk: &GLWESecretExec<DataSk, B>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEEncryptSkFamily<B>,
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,83 @@
use backend::hal::{
api::{
ScratchAvailable, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxAutomorphism,
VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWESecret, TakeGLWESecretExec,
layouts::{GGLWEAutomorphismKey, GLWESecret, GGLWESwitchingKey, Infos},
};
use crate::trait_families::{GGLWEAutomorphismKeyEncryptSkFamily, GLWESecretExecModuleFamily};
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>: GGLWEAutomorphismKeyEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
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> {
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>: GGLWEAutomorphismKeyEncryptSkFamily<B>
+ VecZnxAutomorphism
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ GLWESecretExecModuleFamily<B>,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
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,121 @@
use backend::hal::{
api::{
ScratchAvailable, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes,
ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWEPt,
layouts::{GGLWECiphertext, GLWECiphertext, GLWEPlaintext, Infos, prepared::GLWESecretExec},
};
use crate::trait_families::GGLWEEncryptSkFamily;
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>: GGLWEEncryptSkFamily<B>,
{
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> {
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretExec<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GGLWEEncryptSkFamily<B> + VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use 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,118 @@
use backend::hal::{
api::{ScratchAvailable, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxSwithcDegree},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWESecretExec,
layouts::{GGLWECiphertext, GLWESecret, GGLWESwitchingKey, Infos, prepared::GLWESecretExec},
};
use crate::trait_families::{GGLWESwitchingKeyEncryptSkFamily, GLWESecretExecModuleFamily};
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>: GGLWESwitchingKeyEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
(GGLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k) | ScalarZnx::alloc_bytes(n, 1))
+ ScalarZnx::alloc_bytes(n, rank_in)
+ GLWESecretExec::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> {
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>:
GGLWESwitchingKeyEncryptSkFamily<B> + VecZnxSwithcDegree + VecZnxAddScalarInplace + GLWESecretExecModuleFamily<B>,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
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_exec(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,87 @@
use backend::hal::{
api::{
ScratchAvailable, SvpApply, TakeScalarZnx, TakeVecZnx, TakeVecZnxBig, TakeVecZnxDft, VecZnxAddScalarInplace,
VecZnxBigAllocBytes, VecZnxDftToVecZnxBigTmpA, VecZnxSwithcDegree,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWESecret, TakeGLWESecretExec,
layouts::{GGLWETensorKey, GLWESecret, GGLWESwitchingKey, Infos, prepared::GLWESecretExec},
trait_families::GLWEDecryptFamily,
};
use crate::trait_families::{GGLWETensorKeyEncryptSkFamily, GLWESecretExecModuleFamily};
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>: GGLWETensorKeyEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
GLWESecretExec::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>: GGLWETensorKeyEncryptSkFamily<B> + VecZnxSwithcDegree + VecZnxAddScalarInplace + GLWESecretExecModuleFamily<B>,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeVecZnxBig<B> + TakeGLWESecretExec<B> + TakeScalarZnx + TakeVecZnx,
{
#[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_exec(n, rank);
sk_dft_prep.prepare(module, &sk);
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,81 @@
use backend::hal::{
api::{ScratchAvailable, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxNormalizeInplace, ZnxZero},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch, VecZnx},
};
use sampling::source::Source;
use crate::{
TakeGLWEPt,
layouts::{GGSWCiphertext, GLWECiphertext, Infos, prepared::GLWESecretExec},
};
use crate::trait_families::GLWEEncryptSkFamily;
pub trait GGSWEncryptSkFamily<B: Backend> = GLWEEncryptSkFamily<B>;
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>: GGSWEncryptSkFamily<B>,
{
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> {
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretExec<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GGSWEncryptSkFamily<B> + VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use 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

@@ -1,44 +1,23 @@
use 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,
ScratchAvailable, SvpApply, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeSvpPPol, TakeVecZnx, TakeVecZnxDft,
VecZnxBigAddNormal, VecZnxBigAddSmallInplace, VecZnxBigNormalize, VecZnxDftAllocBytes, VecZnxDftToVecZnxBigConsume,
ZnxInfos, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch, VecZnx, VecZnxBig},
};
use sampling::source::Source;
use crate::{
GLWECiphertext, GLWECiphertextCompressed, GLWEPlaintext, GLWEPublicKeyExec, GLWESecretExec, Infos, SIX_SIGMA,
SIX_SIGMA,
dist::Distribution,
layouts::{
GLWECiphertext, GLWEPlaintext, Infos,
prepared::{GLWEPublicKeyExec, GLWESecretExec},
},
trait_families::{GLWEEncryptPkFamily, GLWEEncryptSkFamily},
};
pub trait GLWEEncryptSkFamily<B: Backend> = VecZnxDftAllocBytes
+ VecZnxBigNormalize<B>
+ VecZnxDftFromVecZnx<B>
+ SvpApplyInplace<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxNormalizeTmpBytes
+ VecZnxFillUniform
+ VecZnxSubABInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxAddNormal
+ VecZnxNormalize<B>
+ VecZnxSub;
pub trait GLWEEncryptPkFamily<B: Backend> = VecZnxDftAllocBytes
+ VecZnxBigAllocBytes
+ SvpPPolAllocBytes
+ SvpPrepare<B>
+ SvpApply<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddNormal<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes;
impl GLWECiphertext<Vec<u8>> {
pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize) -> usize
where
@@ -144,7 +123,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
let cols: usize = self.rank() + 1;
encrypt_sk_internal(
glwe_encrypt_sk_internal(
module,
self.basek(),
self.k(),
@@ -296,73 +275,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
}
}
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>: GLWEEncryptSkFamily<B>,
{
GLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k)
}
}
impl<D: DataMut> GLWECiphertextCompressed<D> {
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &GLWEPlaintext<DataPt>,
sk: &GLWESecretExec<DataSk, B>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEEncryptSkFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
self.encrypt_sk_internal(
module,
Some((pt, 0)),
sk,
seed_xa,
source_xe,
sigma,
scratch,
);
}
pub(crate) fn encrypt_sk_internal<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: Option<(&GLWEPlaintext<DataPt>, usize)>,
sk: &GLWESecretExec<DataSk, B>,
seed_xa: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEEncryptSkFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
let mut source_xa = Source::new(seed_xa);
let cols: usize = self.rank() + 1;
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;
}
}
pub(crate) fn encrypt_sk_internal<DataCt: DataMut, DataPt: DataRef, DataSk: DataRef, B: Backend>(
pub(crate) fn glwe_encrypt_sk_internal<DataCt: DataMut, DataPt: DataRef, DataSk: DataRef, B: Backend>(
module: &Module<B>,
basek: usize,
k: usize,
@@ -382,6 +295,8 @@ pub(crate) fn encrypt_sk_internal<DataCt: DataMut, DataPt: DataRef, DataSk: Data
#[cfg(debug_assertions)]
{
if compressed {
use backend::hal::api::ZnxInfos;
assert_eq!(
ct.cols(),
1,

View File

@@ -0,0 +1,53 @@
use backend::hal::{
api::{ScratchOwnedAlloc, ScratchOwnedBorrow},
layouts::{Backend, DataMut, DataRef, Module, ScratchOwned},
oep::{ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeVecZnxDftImpl, TakeVecZnxImpl},
};
use sampling::source::Source;
use crate::{
dist::Distribution,
layouts::{GLWECiphertext, GLWEPublicKey, Infos, prepared::GLWESecretExec},
};
use crate::trait_families::GLWEEncryptSkFamily;
impl<D: DataMut> GLWEPublicKey<D> {
pub fn generate_from_sk<S: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
sk: &GLWESecretExec<S, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
) where
Module<B>: GLWEEncryptSkFamily<B>,
B: ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ TakeVecZnxDftImpl<B>
+ ScratchAvailableImpl<B>
+ TakeVecZnxImpl<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), sk.n());
match 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,67 @@
use backend::hal::{
api::{
ScratchAvailable, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxAutomorphismInplace,
VecZnxSwithcDegree, ZnxView, ZnxViewMut, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWESecret, TakeGLWESecretExec,
layouts::{GLWESecret, GGLWESwitchingKey, GLWEToLWESwitchingKey, LWESecret, prepared::GLWESecretExec},
};
use crate::trait_families::{GGLWEEncryptSkFamily, GGLWESwitchingKeyEncryptSkFamily, GLWESecretExecModuleFamily};
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>: GGLWEEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
GLWESecretExec::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> {
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>: GGLWESwitchingKeyEncryptSkFamily<B>
+ VecZnxAutomorphismInplace
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ GLWESecretExecModuleFamily<B>,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + TakeVecZnx,
{
#[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 backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxAddNormal, VecZnxFillUniform, VecZnxNormalizeInplace, ZnxView, ZnxViewMut,
},
layouts::{Backend, DataMut, DataRef, Module, ScratchOwned, VecZnx},
oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl},
};
use sampling::source::Source;
use crate::{
SIX_SIGMA,
layouts::{Infos, LWECiphertext, LWEPlaintext, LWESecret},
};
impl<DataSelf: DataMut> LWECiphertext<DataSelf> {
pub fn encrypt_sk<DataPt, DataSk, B: Backend>(
&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: 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,76 @@
use backend::hal::{
api::{
ScratchAvailable, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxAutomorphismInplace,
VecZnxSwithcDegree, ZnxView, ZnxViewMut,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWESecret, TakeGLWESecretExec,
layouts::{GLWESecret, GGLWESwitchingKey, Infos, LWESecret, LWESwitchingKey, prepared::GLWESecretExec},
};
use crate::trait_families::{GGLWEEncryptSkFamily, GGLWESwitchingKeyEncryptSkFamily, GLWESecretExecModuleFamily};
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>: GGLWEEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
GLWESecret::bytes_of(n, 1)
+ GLWESecretExec::bytes_of(module, n, 1)
+ GGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, 1, 1)
}
}
impl<D: DataMut> LWESwitchingKey<D> {
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>: GGLWESwitchingKeyEncryptSkFamily<B>
+ VecZnxAutomorphismInplace
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ GLWESecretExecModuleFamily<B>,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + TakeVecZnx,
{
#[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,66 @@
use backend::hal::{
api::{
ScratchAvailable, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft, VecZnxAddScalarInplace, VecZnxAutomorphismInplace,
VecZnxSwithcDegree, ZnxView, ZnxViewMut,
},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use sampling::source::Source;
use crate::{
TakeGLWESecret, TakeGLWESecretExec,
layouts::{GLWESecret, GGLWESwitchingKey, LWESecret, LWEToGLWESwitchingKey},
};
use crate::trait_families::{GGLWEEncryptSkFamily, GGLWESwitchingKeyEncryptSkFamily, GLWESecretExecModuleFamily};
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>: GGLWEEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
GGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, 1, rank_out) + GLWESecret::bytes_of(n, 1)
}
}
impl<D: DataMut> LWEToGLWESwitchingKey<D> {
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>: GGLWESwitchingKeyEncryptSkFamily<B>
+ VecZnxAutomorphismInplace
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ GLWESecretExecModuleFamily<B>,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + TakeVecZnx,
{
#[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,69 @@
use backend::hal::{
api::{ScratchAvailable, TakeVecZnxDft},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{
layouts::{GGLWEAutomorphismKey, GGLWESwitchingKey, prepared::GGSWCiphertextExec},
trait_families::GLWEExternalProductFamily,
};
impl GGLWEAutomorphismKey<Vec<u8>> {
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>: GLWEExternalProductFamily<B>,
{
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>: GLWEExternalProductFamily<B>,
{
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: &GGSWCiphertextExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEExternalProductFamily<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: &GGSWCiphertextExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEExternalProductFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
self.key.external_product_inplace(module, rhs, scratch);
}
}

View File

@@ -3,9 +3,12 @@ use backend::hal::{
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{AutomorphismKey, GGSWCiphertextExec, GLWECiphertext, GLWEExternalProductFamily, GLWESwitchingKey, Infos};
use crate::{
layouts::{GLWECiphertext, GGLWESwitchingKey, Infos, prepared::GGSWCiphertextExec},
trait_families::GLWEExternalProductFamily,
};
impl GLWESwitchingKey<Vec<u8>> {
impl GGLWESwitchingKey<Vec<u8>> {
pub fn external_product_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
@@ -38,11 +41,11 @@ impl GLWESwitchingKey<Vec<u8>> {
}
}
impl<DataSelf: DataMut> GLWESwitchingKey<DataSelf> {
impl<DataSelf: DataMut> GGLWESwitchingKey<DataSelf> {
pub fn external_product<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GLWESwitchingKey<DataLhs>,
lhs: &GGLWESwitchingKey<DataLhs>,
rhs: &GGSWCiphertextExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
@@ -116,63 +119,3 @@ impl<DataSelf: DataMut> GLWESwitchingKey<DataSelf> {
});
}
}
impl AutomorphismKey<Vec<u8>> {
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>: GLWEExternalProductFamily<B>,
{
GLWESwitchingKey::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>: GLWEExternalProductFamily<B>,
{
GLWESwitchingKey::external_product_inplace_scratch_space(module, n, basek, k_out, ggsw_k, digits, rank)
}
}
impl<DataSelf: DataMut> AutomorphismKey<DataSelf> {
pub fn external_product<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &AutomorphismKey<DataLhs>,
rhs: &GGSWCiphertextExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEExternalProductFamily<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: &GGSWCiphertextExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEExternalProductFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
{
self.key.external_product_inplace(module, rhs, scratch);
}
}

View File

@@ -3,7 +3,10 @@ use backend::hal::{
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{GGSWCiphertext, GGSWCiphertextExec, GLWECiphertext, GLWEExternalProductFamily, Infos};
use crate::{
layouts::{GGSWCiphertext, GLWECiphertext, Infos, prepared::GGSWCiphertextExec},
trait_families::GLWEExternalProductFamily,
};
impl GGSWCiphertext<Vec<u8>> {
pub fn external_product_scratch_space<B: Backend>(
@@ -51,7 +54,7 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
{
#[cfg(debug_assertions)]
{
use crate::{GGSWCiphertext, Infos};
use crate::layouts::Infos;
assert_eq!(lhs.n(), self.n());
assert_eq!(rhs.n(), self.n());

View File

@@ -6,16 +6,10 @@ use backend::hal::{
layouts::{Backend, DataMut, DataRef, Module, Scratch, VecZnxBig},
};
use crate::{GGSWCiphertextExec, GLWECiphertext, Infos};
pub trait GLWEExternalProductFamily<B: Backend> = VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigNormalize<B>
+ VecZnxNormalizeTmpBytes;
use crate::{
layouts::{GLWECiphertext, Infos, prepared::GGSWCiphertextExec},
trait_families::GLWEExternalProductFamily,
};
impl GLWECiphertext<Vec<u8>> {
pub fn external_product_scratch_space<B: Backend>(

View File

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

View File

@@ -1,702 +0,0 @@
use backend::hal::{
api::{
ScratchAvailable, SvpApply, TakeScalarZnx, TakeVecZnx, TakeVecZnxBig, TakeVecZnxDft, VecZnxAddScalarInplace,
VecZnxAutomorphism, VecZnxBigAllocBytes, VecZnxDftToVecZnxBigTmpA, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes,
VecZnxSwithcDegree, ZnxZero,
},
layouts::{Backend, DataMut, DataRef, Module, ScalarZnx, Scratch},
};
use sampling::source::Source;
use crate::{
AutomorphismKey, AutomorphismKeyCompressed, GGLWECiphertext, GGLWECiphertextCompressed, GLWECiphertext, GLWEDecryptFamily,
GLWEEncryptSkFamily, GLWEPlaintext, GLWESecret, GLWESecretExec, GLWESecretFamily, GLWESwitchingKey,
GLWESwitchingKeyCompressed, GLWETensorKey, GLWETensorKeyCompressed, Infos, TakeGLWEPt, TakeGLWESecret, TakeGLWESecretExec,
encrypt_sk_internal,
};
pub trait GGLWEEncryptSkFamily<B: Backend> = GLWEEncryptSkFamily<B> + GLWESecretFamily<B>;
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>: GGLWEEncryptSkFamily<B>,
{
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> {
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretExec<DataSk, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GGLWEEncryptSkFamily<B> + VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use 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);
});
});
}
}
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>: GLWESwitchingKeyEncryptSkFamily<B>,
{
GGLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k)
}
}
impl<D: DataMut> GGLWECiphertextCompressed<D> {
pub fn encrypt_sk<DataPt: DataRef, DataSk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
pt: &ScalarZnx<DataPt>,
sk: &GLWESecretExec<DataSk, B>,
seed: [u8; 32],
source_xe: &mut Source,
sigma: f64,
scratch: &mut Scratch<B>,
) where
Module<B>: GGLWEEncryptSkFamily<B> + VecZnxAddScalarInplace,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
use 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;
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,
);
});
});
}
}
pub trait GLWESwitchingKeyEncryptSkFamily<B: Backend> = GGLWEEncryptSkFamily<B>;
impl GLWESwitchingKey<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>: GLWESwitchingKeyEncryptSkFamily<B>,
{
(GGLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k) | ScalarZnx::alloc_bytes(n, 1))
+ ScalarZnx::alloc_bytes(n, rank_in)
+ GLWESecretExec::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> GLWESwitchingKey<DataSelf> {
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>: GLWESwitchingKeyEncryptSkFamily<B> + VecZnxSwithcDegree + VecZnxAddScalarInplace,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert!(sk_in.n() <= module.n());
assert!(sk_out.n() <= module.n());
assert!(
scratch.available()
>= GLWESwitchingKey::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(),
GLWESwitchingKey::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_exec(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();
}
}
impl GLWESwitchingKeyCompressed<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>: GLWESwitchingKeyEncryptSkFamily<B>,
{
(GGLWECiphertext::encrypt_sk_scratch_space(module, n, basek, k) | ScalarZnx::alloc_bytes(n, 1))
+ ScalarZnx::alloc_bytes(n, rank_in)
+ GLWESecretExec::bytes_of(module, n, rank_out)
}
}
impl<DataSelf: DataMut> GLWESwitchingKeyCompressed<DataSelf> {
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>: GLWESwitchingKeyEncryptSkFamily<B> + VecZnxSwithcDegree + VecZnxAddScalarInplace,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + ScratchAvailable + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert!(sk_in.n() <= module.n());
assert!(sk_out.n() <= module.n());
assert!(
scratch.available()
>= GLWESwitchingKey::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(),
GLWESwitchingKey::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_exec(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();
}
}
pub trait AutomorphismKeyEncryptSkFamily<B: Backend> = GGLWEEncryptSkFamily<B>;
impl AutomorphismKey<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>: AutomorphismKeyEncryptSkFamily<B>,
{
GLWESwitchingKey::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 {
GLWESwitchingKey::encrypt_pk_scratch_space(module, _n, _basek, _k, _rank, _rank)
}
}
impl<DataSelf: DataMut> AutomorphismKey<DataSelf> {
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>: AutomorphismKeyEncryptSkFamily<B> + VecZnxAutomorphism + VecZnxSwithcDegree + VecZnxAddScalarInplace,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), sk.n());
assert_eq!(self.rank_out(), self.rank_in());
assert_eq!(sk.rank(), self.rank());
assert!(
scratch.available()
>= AutomorphismKey::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(),
AutomorphismKey::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;
}
}
impl AutomorphismKeyCompressed<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>: AutomorphismKeyEncryptSkFamily<B>,
{
GLWESwitchingKeyCompressed::encrypt_sk_scratch_space(module, n, basek, k, rank, rank) + GLWESecret::bytes_of(n, rank)
}
}
impl<DataSelf: DataMut> AutomorphismKeyCompressed<DataSelf> {
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>: AutomorphismKeyEncryptSkFamily<B> + VecZnxSwithcDegree + VecZnxAutomorphism + VecZnxAddScalarInplace,
Scratch<B>: ScratchAvailable + TakeScalarZnx + TakeVecZnxDft<B> + TakeGLWESecretExec<B> + TakeVecZnx,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), sk.n());
assert_eq!(self.rank_out(), self.rank_in());
assert_eq!(sk.rank(), self.rank());
assert!(
scratch.available()
>= AutomorphismKeyCompressed::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(),
AutomorphismKeyCompressed::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;
}
}
pub trait GLWETensorKeyEncryptSkFamily<B: Backend> =
GGLWEEncryptSkFamily<B> + VecZnxBigAllocBytes + VecZnxDftToVecZnxBigTmpA<B> + SvpApply<B>;
impl GLWETensorKey<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>: GLWETensorKeyEncryptSkFamily<B>,
{
GLWESecretExec::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)
+ GLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, rank, rank)
}
}
impl<DataSelf: DataMut> GLWETensorKey<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>: GLWETensorKeyEncryptSkFamily<B> + VecZnxSwithcDegree + VecZnxAddScalarInplace,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeVecZnxBig<B> + TakeGLWESecretExec<B> + TakeScalarZnx + TakeVecZnx,
{
#[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_exec(n, rank);
sk_dft_prep.prepare(module, &sk);
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);
});
})
}
}
impl GLWETensorKeyCompressed<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>: GLWETensorKeyEncryptSkFamily<B>,
{
GLWETensorKey::encrypt_sk_scratch_space(module, n, basek, k, rank)
}
}
impl<DataSelf: DataMut> GLWETensorKeyCompressed<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>: GLWETensorKeyEncryptSkFamily<B> + VecZnxSwithcDegree + VecZnxAddScalarInplace,
Scratch<B>: ScratchAvailable + TakeVecZnxDft<B> + TakeVecZnxBig<B> + TakeGLWESecretExec<B> + TakeScalarZnx + TakeVecZnx,
{
#[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_exec(n, rank);
sk_dft_prep.prepare(module, &sk);
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

@@ -1,541 +0,0 @@
use backend::hal::{
api::{FillUniform, Reset, VmpPMatAlloc, VmpPMatAllocBytes, VmpPMatPrepare},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
};
use crate::{GLWECiphertext, Infos};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
pub trait GGLWEExecLayoutFamily<B: Backend> = VmpPMatAlloc<B> + VmpPMatAllocBytes + VmpPMatPrepare<B>;
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 sampling::source::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: 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)
}
}
#[derive(PartialEq, Eq, Clone)]
pub struct GLWESwitchingKey<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 GLWESwitchingKey<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataRef> fmt::Display for GLWESwitchingKey<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 GLWESwitchingKey<D> {
fn fill_uniform(&mut self, source: &mut sampling::source::Source) {
self.key.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GLWESwitchingKey<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.key.reset();
self.sk_in_n = 0;
self.sk_out_n = 0;
}
}
impl GLWESwitchingKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize, rank_out: usize) -> Self {
GLWESwitchingKey {
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 GLWESwitchingKey<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> GLWESwitchingKey<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> GLWESwitchingKey<D> {
pub fn at(&self, row: usize, col: usize) -> GLWECiphertext<&[u8]> {
self.key.at(row, col)
}
}
impl<D: DataMut> GLWESwitchingKey<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 GLWESwitchingKey<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 GLWESwitchingKey<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)
}
}
#[derive(PartialEq, Eq, Clone)]
pub struct AutomorphismKey<D: Data> {
pub(crate) key: GLWESwitchingKey<D>,
pub(crate) p: i64,
}
impl<D: DataRef> fmt::Debug for AutomorphismKey<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for AutomorphismKey<D> {
fn fill_uniform(&mut self, source: &mut sampling::source::Source) {
self.key.fill_uniform(source);
}
}
impl<D: DataMut> Reset for AutomorphismKey<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.key.reset();
self.p = 0;
}
}
impl<D: DataRef> fmt::Display for AutomorphismKey<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(AutomorphismKey: p={}) {}", self.p, self.key)
}
}
impl AutomorphismKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
AutomorphismKey {
key: GLWESwitchingKey::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 {
GLWESwitchingKey::bytes_of(n, basek, k, rows, digits, rank, rank)
}
}
impl<D: Data> Infos for AutomorphismKey<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> AutomorphismKey<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> AutomorphismKey<D> {
pub fn at(&self, row: usize, col: usize) -> GLWECiphertext<&[u8]> {
self.key.at(row, col)
}
}
impl<D: DataMut> AutomorphismKey<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 AutomorphismKey<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 AutomorphismKey<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)
}
}
#[derive(PartialEq, Eq, Clone)]
pub struct GLWETensorKey<D: Data> {
pub(crate) keys: Vec<GLWESwitchingKey<D>>,
}
impl<D: DataRef> fmt::Debug for GLWETensorKey<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GLWETensorKey<D> {
fn fill_uniform(&mut self, source: &mut sampling::source::Source) {
self.keys
.iter_mut()
.for_each(|key: &mut GLWESwitchingKey<D>| key.fill_uniform(source))
}
}
impl<D: DataMut> Reset for GLWETensorKey<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.keys
.iter_mut()
.for_each(|key: &mut GLWESwitchingKey<D>| key.reset())
}
}
impl<D: DataRef> fmt::Display for GLWETensorKey<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 GLWETensorKey<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
let mut keys: Vec<GLWESwitchingKey<Vec<u8>>> = Vec::new();
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
(0..pairs).for_each(|_| {
keys.push(GLWESwitchingKey::alloc(n, basek, k, rows, digits, 1, rank));
});
Self { keys: 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 * GLWESwitchingKey::<Vec<u8>>::bytes_of(n, basek, k, rows, digits, 1, rank)
}
}
impl<D: Data> Infos for GLWETensorKey<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> GLWETensorKey<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> GLWETensorKey<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 GLWESwitchingKey<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> GLWETensorKey<D> {
// Returns a reference to GLWESwitchingKey_{s}(s[i] * s[j])
pub fn at(&self, mut i: usize, mut j: usize) -> &GLWESwitchingKey<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 GLWETensorKey<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 GLWETensorKey<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

@@ -1,626 +0,0 @@
use backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
};
use crate::{AutomorphismKey, Decompress, GGLWECiphertext, GLWECiphertextCompressed, GLWESwitchingKey, GLWETensorKey, Infos};
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 sampling::source::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: 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 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));
});
});
}
}
#[derive(PartialEq, Eq, Clone)]
pub struct GLWESwitchingKeyCompressed<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 GLWESwitchingKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GLWESwitchingKeyCompressed<D> {
fn fill_uniform(&mut self, source: &mut sampling::source::Source) {
self.key.fill_uniform(source);
}
}
impl<D: DataMut> Reset for GLWESwitchingKeyCompressed<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 GLWESwitchingKeyCompressed<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 GLWESwitchingKeyCompressed<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> GLWESwitchingKeyCompressed<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 GLWESwitchingKeyCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank_in: usize, rank_out: usize) -> Self {
GLWESwitchingKeyCompressed {
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 GLWESwitchingKeyCompressed<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 GLWESwitchingKeyCompressed<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> GLWESwitchingKey<D> {
pub fn decompress<DataOther: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
other: &GLWESwitchingKeyCompressed<DataOther>,
) 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;
}
}
#[derive(PartialEq, Eq, Clone)]
pub struct AutomorphismKeyCompressed<D: Data> {
pub(crate) key: GLWESwitchingKeyCompressed<D>,
pub(crate) p: i64,
}
impl<D: DataRef> fmt::Debug for AutomorphismKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for AutomorphismKeyCompressed<D> {
fn fill_uniform(&mut self, source: &mut sampling::source::Source) {
self.key.fill_uniform(source);
}
}
impl<D: DataMut> Reset for AutomorphismKeyCompressed<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.key.reset();
self.p = 0;
}
}
impl<D: DataRef> fmt::Display for AutomorphismKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(AutomorphismKeyCompressed: p={}) {}", self.p, self.key)
}
}
impl AutomorphismKeyCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
AutomorphismKeyCompressed {
key: GLWESwitchingKeyCompressed::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 {
GLWESwitchingKeyCompressed::<Vec<u8>>::bytes_of(n, basek, k, rows, digits, rank)
}
}
impl<D: Data> Infos for AutomorphismKeyCompressed<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> AutomorphismKeyCompressed<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 AutomorphismKeyCompressed<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 AutomorphismKeyCompressed<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> AutomorphismKey<D> {
pub fn decompress<DataOther: DataRef, B: Backend>(&mut self, module: &Module<B>, other: &AutomorphismKeyCompressed<DataOther>)
where
Module<B>: VecZnxFillUniform + VecZnxCopy,
{
self.key.decompress(module, &other.key);
self.p = other.p;
}
}
#[derive(PartialEq, Eq, Clone)]
pub struct GLWETensorKeyCompressed<D: Data> {
pub(crate) keys: Vec<GLWESwitchingKeyCompressed<D>>,
}
impl<D: DataRef> fmt::Debug for GLWETensorKeyCompressed<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl<D: DataMut> FillUniform for GLWETensorKeyCompressed<D> {
fn fill_uniform(&mut self, source: &mut sampling::source::Source) {
self.keys
.iter_mut()
.for_each(|key: &mut GLWESwitchingKeyCompressed<D>| key.fill_uniform(source))
}
}
impl<D: DataMut> Reset for GLWETensorKeyCompressed<D>
where
MatZnx<D>: Reset,
{
fn reset(&mut self) {
self.keys
.iter_mut()
.for_each(|key: &mut GLWESwitchingKeyCompressed<D>| key.reset())
}
}
impl<D: DataRef> fmt::Display for GLWETensorKeyCompressed<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 GLWETensorKeyCompressed<Vec<u8>> {
pub fn alloc(n: usize, basek: usize, k: usize, rows: usize, digits: usize, rank: usize) -> Self {
let mut keys: Vec<GLWESwitchingKeyCompressed<Vec<u8>>> = Vec::new();
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
(0..pairs).for_each(|_| {
keys.push(GLWESwitchingKeyCompressed::alloc(
n, basek, k, rows, digits, 1, rank,
));
});
Self { keys: 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 * GLWESwitchingKeyCompressed::bytes_of(n, basek, k, rows, digits, 1)
}
}
impl<D: Data> Infos for GLWETensorKeyCompressed<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> GLWETensorKeyCompressed<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 GLWETensorKeyCompressed<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 GLWETensorKeyCompressed<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> GLWETensorKeyCompressed<D> {
pub(crate) fn at_mut(&mut self, mut i: usize, mut j: usize) -> &mut GLWESwitchingKeyCompressed<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> GLWETensorKey<D> {
pub fn decompress<DataOther: DataRef, B: Backend>(&mut self, module: &Module<B>, other: &GLWETensorKeyCompressed<DataOther>)
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

@@ -1,465 +0,0 @@
use backend::hal::{
api::{VmpPMatAlloc, VmpPMatAllocBytes, VmpPMatPrepare},
layouts::{Backend, Data, DataMut, DataRef, Module, Scratch, VmpPMat},
};
use crate::{AutomorphismKey, GGLWECiphertext, GGLWEExecLayoutFamily, GLWESwitchingKey, GLWETensorKey, Infos};
#[derive(PartialEq, Eq)]
pub struct GGLWECiphertextExec<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> GGLWECiphertextExec<Vec<u8>, B> {
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>: GGLWEExecLayoutFamily<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: basek,
k,
digits,
}
}
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>: GGLWEExecLayoutFamily<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
);
module.vmp_pmat_alloc_bytes(n, rows, rank_in, rank_out + 1, rows)
}
}
impl<D: Data, B: Backend> Infos for GGLWECiphertextExec<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> GGLWECiphertextExec<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, B: Backend> GGLWECiphertextExec<D, B> {
pub fn prepare<DataOther>(&mut self, module: &Module<B>, other: &GGLWECiphertext<DataOther>, scratch: &mut Scratch<B>)
where
DataOther: DataRef,
Module<B>: GGLWEExecLayoutFamily<B>,
{
module.vmp_prepare(&mut self.data, &other.data, scratch);
self.basek = other.basek;
self.k = other.k;
self.digits = other.digits;
}
}
#[derive(PartialEq, Eq)]
pub struct GLWESwitchingKeyExec<D: Data, B: Backend> {
pub(crate) key: GGLWECiphertextExec<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> GLWESwitchingKeyExec<Vec<u8>, B> {
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>: GGLWEExecLayoutFamily<B>,
{
GLWESwitchingKeyExec::<Vec<u8>, B> {
key: GGLWECiphertextExec::alloc(module, n, basek, k, rows, digits, rank_in, rank_out),
sk_in_n: 0,
sk_out_n: 0,
}
}
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>: GGLWEExecLayoutFamily<B>,
{
GGLWECiphertextExec::bytes_of(module, n, basek, k, rows, digits, rank_in, rank_out)
}
pub fn from<DataOther: DataRef>(module: &Module<B>, other: &GLWESwitchingKey<DataOther>, scratch: &mut Scratch<B>) -> Self
where
Module<B>: GGLWEExecLayoutFamily<B>,
{
let mut ksk_exec: GLWESwitchingKeyExec<Vec<u8>, B> = Self::alloc(
module,
other.n(),
other.basek(),
other.k(),
other.rows(),
other.digits(),
other.rank_in(),
other.rank_out(),
);
ksk_exec.prepare(module, other, scratch);
ksk_exec
}
}
impl<D: Data, B: Backend> Infos for GLWESwitchingKeyExec<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> GLWESwitchingKeyExec<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, B: Backend> GLWESwitchingKeyExec<D, B> {
pub fn prepare<DataOther>(&mut self, module: &Module<B>, other: &GLWESwitchingKey<DataOther>, scratch: &mut Scratch<B>)
where
DataOther: DataRef,
Module<B>: GGLWEExecLayoutFamily<B>,
{
self.key.prepare(module, &other.key, scratch);
self.sk_in_n = other.sk_in_n;
self.sk_out_n = other.sk_out_n;
}
}
#[derive(PartialEq, Eq)]
pub struct AutomorphismKeyExec<D: Data, B: Backend> {
pub(crate) key: GLWESwitchingKeyExec<D, B>,
pub(crate) p: i64,
}
impl<B: Backend> AutomorphismKeyExec<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>: GGLWEExecLayoutFamily<B>,
{
AutomorphismKeyExec::<Vec<u8>, B> {
key: GLWESwitchingKeyExec::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>: GGLWEExecLayoutFamily<B>,
{
GLWESwitchingKeyExec::bytes_of(module, n, basek, k, rows, digits, rank, rank)
}
pub fn from<DataOther: DataRef>(module: &Module<B>, other: &AutomorphismKey<DataOther>, scratch: &mut Scratch<B>) -> Self
where
Module<B>: GGLWEExecLayoutFamily<B>,
{
let mut atk_exec: AutomorphismKeyExec<Vec<u8>, B> = Self::alloc(
module,
other.n(),
other.basek(),
other.k(),
other.rows(),
other.digits(),
other.rank(),
);
atk_exec.prepare(module, other, scratch);
atk_exec
}
}
impl<D: DataMut, B: Backend> AutomorphismKeyExec<D, B> {
pub fn prepare<DataOther>(&mut self, module: &Module<B>, other: &AutomorphismKey<DataOther>, scratch: &mut Scratch<B>)
where
DataOther: DataRef,
Module<B>: GGLWEExecLayoutFamily<B>,
{
self.key.prepare(module, &other.key, scratch);
self.p = other.p;
}
}
impl<D: Data, B: Backend> Infos for AutomorphismKeyExec<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> AutomorphismKeyExec<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()
}
}
#[derive(PartialEq, Eq)]
pub struct GLWETensorKeyExec<D: Data, B: Backend> {
pub(crate) keys: Vec<GLWESwitchingKeyExec<D, B>>,
}
impl<B: Backend> GLWETensorKeyExec<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>: GGLWEExecLayoutFamily<B>,
{
let mut keys: Vec<GLWESwitchingKeyExec<Vec<u8>, B>> = Vec::new();
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
(0..pairs).for_each(|_| {
keys.push(GLWESwitchingKeyExec::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>: GGLWEExecLayoutFamily<B>,
{
let pairs: usize = (((rank + 1) * rank) >> 1).max(1);
pairs * GLWESwitchingKeyExec::bytes_of(module, n, basek, k, rows, digits, 1, rank)
}
pub fn from<D: DataRef>(
module: &Module<B>,
other: &GLWETensorKey<D>,
scratch: &mut Scratch<B>,
) -> GLWETensorKeyExec<Vec<u8>, B>
where
Module<B>: GGLWEExecLayoutFamily<B>,
{
let mut tsk_exec: GLWETensorKeyExec<Vec<u8>, B> = Self::alloc(
module,
other.n(),
other.basek(),
other.k(),
other.rows(),
other.digits(),
other.rank(),
);
tsk_exec.prepare(module, other, scratch);
tsk_exec
}
}
impl<D: Data, B: Backend> Infos for GLWETensorKeyExec<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> GLWETensorKeyExec<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> GLWETensorKeyExec<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 GLWESwitchingKeyExec<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> GLWETensorKeyExec<D, B> {
// Returns a reference to GLWESwitchingKey_{s}(s[i] * s[j])
pub fn at(&self, mut i: usize, mut j: usize) -> &GLWESwitchingKeyExec<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, B: Backend> GLWETensorKeyExec<D, B> {
pub fn prepare<DataOther>(&mut self, module: &Module<B>, other: &GLWETensorKey<DataOther>, scratch: &mut Scratch<B>)
where
DataOther: DataRef,
Module<B>: GGLWEExecLayoutFamily<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);
});
}
}

View File

@@ -1,16 +0,0 @@
mod automorphism;
mod encryption;
mod external_product;
mod keyswitch;
mod layout;
mod layouts_compressed;
mod layouts_exec;
mod noise;
pub use encryption::*;
pub use layout::*;
pub use layouts_compressed::*;
pub use layouts_exec::*;
#[cfg(test)]
mod tests;

View File

@@ -1 +0,0 @@
mod fft64;

View File

@@ -1,54 +0,0 @@
use backend::hal::tests::serialization::test_reader_writer_interface;
use crate::{
AutomorphismKey, AutomorphismKeyCompressed, GGLWECiphertext, GGLWECiphertextCompressed, GLWESwitchingKey,
GLWESwitchingKeyCompressed, GLWETensorKey, GLWETensorKeyCompressed,
};
#[test]
fn test_gglwe_serialization() {
let original: GGLWECiphertext<Vec<u8>> = GGLWECiphertext::alloc(1024, 12, 54, 3, 1, 2, 2);
test_reader_writer_interface(original);
}
#[test]
fn test_gglwe_compressed_serialization() {
let original: GGLWECiphertextCompressed<Vec<u8>> = GGLWECiphertextCompressed::alloc(1024, 12, 54, 3, 1, 2, 2);
test_reader_writer_interface(original);
}
#[test]
fn test_glwe_switching_key_serialization() {
let original: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::alloc(1024, 12, 54, 3, 1, 2, 2);
test_reader_writer_interface(original);
}
#[test]
fn test_glwe_switching_key_compressed_serialization() {
let original: GLWESwitchingKeyCompressed<Vec<u8>> = GLWESwitchingKeyCompressed::alloc(1024, 12, 54, 3, 1, 2, 2);
test_reader_writer_interface(original);
}
#[test]
fn test_automorphism_key_serialization() {
let original: AutomorphismKey<Vec<u8>> = AutomorphismKey::alloc(1024, 12, 54, 3, 1, 2);
test_reader_writer_interface(original);
}
#[test]
fn test_automorphism_key_compressed_serialization() {
let original: AutomorphismKeyCompressed<Vec<u8>> = AutomorphismKeyCompressed::alloc(1024, 12, 54, 3, 1, 2);
test_reader_writer_interface(original);
}
#[test]
fn test_tensor_key_serialization() {
let original: GLWETensorKey<Vec<u8>> = GLWETensorKey::alloc(1024, 12, 54, 3, 1, 2);
test_reader_writer_interface(original);
}
#[test]
fn test_tensor_key_compressed_serialization() {
let original: GLWETensorKeyCompressed<Vec<u8>> = GLWETensorKeyCompressed::alloc(1024, 12, 54, 3, 1, 2);
test_reader_writer_interface(original);
}

View File

@@ -1,578 +0,0 @@
use backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxAddScalarInplace, VecZnxCopy, VecZnxRotateInplace, VecZnxStd,
VecZnxSubScalarInplace, VecZnxSwithcDegree, ZnxViewMut,
},
layouts::{Backend, Module, ScalarZnx, ScalarZnxToMut, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl, VecZnxBigAllocBytesImpl, VecZnxDftAllocBytesImpl,
},
};
use sampling::source::Source;
use crate::{
GGLWEEncryptSkFamily, GGLWEExecLayoutFamily, GGSWCiphertext, GGSWCiphertextExec, GGSWLayoutFamily, GLWEDecryptFamily,
GLWEExternalProductFamily, GLWEKeyswitchFamily, GLWESecret, GLWESecretExec, GLWESwitchingKey, GLWESwitchingKeyCompressed,
GLWESwitchingKeyEncryptSkFamily, GLWESwitchingKeyExec,
noise::{log2_std_noise_gglwe_product, noise_ggsw_product},
};
pub(crate) trait TestModuleFamily<B: Backend> = GGLWEEncryptSkFamily<B>
+ GLWEDecryptFamily<B>
+ VecZnxSwithcDegree
+ VecZnxAddScalarInplace
+ VecZnxStd
+ VecZnxSubScalarInplace
+ VecZnxCopy;
pub(crate) trait TestScratchFamily<B: Backend> = TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>;
pub(crate) fn test_gglwe_encrypt_sk<B: Backend>(
module: &Module<B>,
basek: usize,
k_ksk: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
sigma: f64,
) where
Module<B>: TestModuleFamily<B>,
B: TestScratchFamily<B>,
{
let n: usize = module.n();
let rows: usize = (k_ksk - digits * basek) / (digits * basek);
let mut ksk: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::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(GLWESwitchingKey::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_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_out);
ksk.encrypt_sk(
module,
&sk_in,
&sk_out,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ksk.key
.assert_noise(module, &sk_out_exec, &sk_in.data, sigma);
}
pub(crate) fn test_gglwe_encrypt_sk_compressed<B: Backend>(
module: &Module<B>,
basek: usize,
k_ksk: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
sigma: f64,
) where
Module<B>: TestModuleFamily<B>,
B: TestScratchFamily<B>,
{
let n: usize = module.n();
let rows: usize = (k_ksk - digits * basek) / (digits * basek);
let mut ksk_compressed: GLWESwitchingKeyCompressed<Vec<u8>> =
GLWESwitchingKeyCompressed::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(GLWESwitchingKeyCompressed::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_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_out);
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: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::alloc(n, basek, k_ksk, rows, digits, rank_in, rank_out);
ksk.decompress(module, &ksk_compressed);
ksk.key
.assert_noise(module, &sk_out_exec, &sk_in.data, sigma);
}
pub(crate) fn test_gglwe_keyswitch<B: Backend>(
module: &Module<B>,
basek: usize,
k_out: usize,
k_in: usize,
k_ksk: usize,
digits: usize,
rank_in_s0s1: usize,
rank_out_s0s1: usize,
rank_out_s1s2: usize,
sigma: f64,
) where
Module<B>:
TestModuleFamily<B> + GGLWEEncryptSkFamily<B> + GLWEDecryptFamily<B> + GLWEKeyswitchFamily<B> + GGLWEExecLayoutFamily<B>,
B: TestScratchFamily<B>,
{
let n: usize = module.n();
let rows: usize = k_in.div_ceil(basek * digits);
let digits_in: usize = 1;
let mut ct_gglwe_s0s1: GLWESwitchingKey<Vec<u8>> =
GLWESwitchingKey::alloc(n, basek, k_in, rows, digits_in, rank_in_s0s1, rank_out_s0s1);
let mut ct_gglwe_s1s2: GLWESwitchingKey<Vec<u8>> =
GLWESwitchingKey::alloc(n, basek, k_ksk, rows, digits, rank_out_s0s1, rank_out_s1s2);
let mut ct_gglwe_s0s2: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::alloc(
n,
basek,
k_out,
rows,
digits_in,
rank_in_s0s1,
rank_out_s1s2,
);
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_enc: ScratchOwned<B> = ScratchOwned::alloc(GLWESwitchingKey::encrypt_sk_scratch_space(
module,
n,
basek,
k_ksk,
rank_in_s0s1 | rank_out_s0s1,
rank_out_s0s1 | rank_out_s1s2,
));
let mut scratch_apply: ScratchOwned<B> = ScratchOwned::alloc(GLWESwitchingKey::keyswitch_scratch_space(
module,
n,
basek,
k_out,
k_in,
k_ksk,
digits,
ct_gglwe_s1s2.rank_in(),
ct_gglwe_s1s2.rank_out(),
));
let mut sk0: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_in_s0s1);
sk0.fill_ternary_prob(0.5, &mut source_xs);
let mut sk1: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_out_s0s1);
sk1.fill_ternary_prob(0.5, &mut source_xs);
let mut sk2: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_out_s1s2);
sk2.fill_ternary_prob(0.5, &mut source_xs);
let sk2_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk2);
// gglwe_{s1}(s0) = s0 -> s1
ct_gglwe_s0s1.encrypt_sk(
module,
&sk0,
&sk1,
&mut source_xa,
&mut source_xe,
sigma,
scratch_enc.borrow(),
);
// gglwe_{s2}(s1) -> s1 -> s2
ct_gglwe_s1s2.encrypt_sk(
module,
&sk1,
&sk2,
&mut source_xa,
&mut source_xe,
sigma,
scratch_enc.borrow(),
);
let ct_gglwe_s1s2_exec: GLWESwitchingKeyExec<Vec<u8>, B> =
GLWESwitchingKeyExec::from(module, &ct_gglwe_s1s2, scratch_apply.borrow());
// gglwe_{s1}(s0) (x) gglwe_{s2}(s1) = gglwe_{s2}(s0)
ct_gglwe_s0s2.keyswitch(
module,
&ct_gglwe_s0s1,
&ct_gglwe_s1s2_exec,
scratch_apply.borrow(),
);
let max_noise: f64 = log2_std_noise_gglwe_product(
n as f64,
basek * digits,
0.5,
0.5,
0f64,
sigma * sigma,
0f64,
rank_out_s0s1 as f64,
k_in,
k_ksk,
);
ct_gglwe_s0s2
.key
.assert_noise(module, &sk2_exec, &sk0.data, max_noise + 0.5);
}
pub(crate) fn test_gglwe_keyswitch_inplace<B: Backend>(
module: &Module<B>,
basek: usize,
k_ct: usize,
k_ksk: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
sigma: f64,
) where
Module<B>: TestModuleFamily<B>
+ GLWESwitchingKeyEncryptSkFamily<B>
+ GLWEKeyswitchFamily<B>
+ GGLWEExecLayoutFamily<B>
+ GLWEDecryptFamily<B>,
B: TestScratchFamily<B>,
{
let n: usize = module.n();
let rows: usize = k_ct.div_ceil(basek * digits);
let digits_in: usize = 1;
let mut ct_gglwe_s0s1: GLWESwitchingKey<Vec<u8>> =
GLWESwitchingKey::alloc(n, basek, k_ct, rows, digits_in, rank_in, rank_out);
let mut ct_gglwe_s1s2: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::alloc(n, basek, k_ksk, rows, digits, rank_out, 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_enc: ScratchOwned<B> = ScratchOwned::alloc(GLWESwitchingKey::encrypt_sk_scratch_space(
module,
n,
basek,
k_ksk,
rank_in | rank_out,
rank_out,
));
let mut scratch_apply: ScratchOwned<B> = ScratchOwned::alloc(GLWESwitchingKey::keyswitch_inplace_scratch_space(
module, n, basek, k_ct, k_ksk, digits, rank_out,
));
let var_xs: f64 = 0.5;
let mut sk0: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_in);
sk0.fill_ternary_prob(var_xs, &mut source_xs);
let mut sk1: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_out);
sk1.fill_ternary_prob(var_xs, &mut source_xs);
let mut sk2: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_out);
sk2.fill_ternary_prob(var_xs, &mut source_xs);
let sk2_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk2);
// gglwe_{s1}(s0) = s0 -> s1
ct_gglwe_s0s1.encrypt_sk(
module,
&sk0,
&sk1,
&mut source_xa,
&mut source_xe,
sigma,
scratch_enc.borrow(),
);
// gglwe_{s2}(s1) -> s1 -> s2
ct_gglwe_s1s2.encrypt_sk(
module,
&sk1,
&sk2,
&mut source_xa,
&mut source_xe,
sigma,
scratch_enc.borrow(),
);
let ct_gglwe_s1s2_exec: GLWESwitchingKeyExec<Vec<u8>, B> =
GLWESwitchingKeyExec::from(module, &ct_gglwe_s1s2, scratch_apply.borrow());
// gglwe_{s1}(s0) (x) gglwe_{s2}(s1) = gglwe_{s2}(s0)
ct_gglwe_s0s1.keyswitch_inplace(module, &ct_gglwe_s1s2_exec, scratch_apply.borrow());
let ct_gglwe_s0s2: GLWESwitchingKey<Vec<u8>> = ct_gglwe_s0s1;
let max_noise: f64 = log2_std_noise_gglwe_product(
n as f64,
basek * digits,
var_xs,
var_xs,
0f64,
sigma * sigma,
0f64,
rank_out as f64,
k_ct,
k_ksk,
);
ct_gglwe_s0s2
.key
.assert_noise(module, &sk2_exec, &sk0.data, max_noise + 0.5);
}
pub(crate) fn test_gglwe_external_product<B: Backend>(
module: &Module<B>,
basek: usize,
k_out: usize,
k_in: usize,
k_ggsw: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
sigma: f64,
) where
Module<B>: TestModuleFamily<B>
+ GLWESwitchingKeyEncryptSkFamily<B>
+ GLWEExternalProductFamily<B>
+ GGSWLayoutFamily<B>
+ GLWEDecryptFamily<B>
+ VecZnxRotateInplace,
B: TestScratchFamily<B>,
{
let n: usize = module.n();
let rows: usize = k_in.div_ceil(basek * digits);
let digits_in: usize = 1;
let mut ct_gglwe_in: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::alloc(n, basek, k_in, rows, digits_in, rank_in, rank_out);
let mut ct_gglwe_out: GLWESwitchingKey<Vec<u8>> =
GLWESwitchingKey::alloc(n, basek, k_out, rows, digits_in, rank_in, rank_out);
let mut ct_rgsw: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_ggsw, rows, digits, rank_out);
let mut pt_rgsw: 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(
GLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k_in, rank_in, rank_out)
| GLWESwitchingKey::external_product_scratch_space(module, n, basek, k_out, k_in, k_ggsw, digits, rank_out)
| GGSWCiphertext::encrypt_sk_scratch_space(module, n, basek, k_ggsw, rank_out),
);
let r: usize = 1;
pt_rgsw.to_mut().raw_mut()[r] = 1; // X^{r}
let var_xs: f64 = 0.5;
let mut sk_in: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_in);
sk_in.fill_ternary_prob(var_xs, &mut source_xs);
let mut sk_out: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_out);
sk_out.fill_ternary_prob(var_xs, &mut source_xs);
let sk_out_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_out);
// gglwe_{s1}(s0) = s0 -> s1
ct_gglwe_in.encrypt_sk(
module,
&sk_in,
&sk_out,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ct_rgsw.encrypt_sk(
module,
&pt_rgsw,
&sk_out_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut ct_rgsw_exec: GGSWCiphertextExec<Vec<u8>, B> =
GGSWCiphertextExec::alloc(module, n, basek, k_ggsw, rows, digits, rank_out);
ct_rgsw_exec.prepare(module, &ct_rgsw, scratch.borrow());
// gglwe_(m) (x) RGSW_(X^k) = gglwe_(m * X^k)
ct_gglwe_out.external_product(module, &ct_gglwe_in, &ct_rgsw_exec, scratch.borrow());
(0..rank_in).for_each(|i| {
module.vec_znx_rotate_inplace(r as i64, &mut sk_in.data.as_vec_znx_mut(), i); // * X^{r}
});
let var_gct_err_lhs: f64 = sigma * sigma;
let var_gct_err_rhs: f64 = 0f64;
let var_msg: f64 = 1f64 / n as f64; // X^{k}
let var_a0_err: f64 = sigma * sigma;
let var_a1_err: f64 = 1f64 / 12f64;
let max_noise: f64 = noise_ggsw_product(
n as f64,
basek * digits,
var_xs,
var_msg,
var_a0_err,
var_a1_err,
var_gct_err_lhs,
var_gct_err_rhs,
rank_out as f64,
k_in,
k_ggsw,
);
ct_gglwe_out
.key
.assert_noise(module, &sk_out_exec, &sk_in.data, max_noise + 0.5);
}
pub(crate) fn test_gglwe_external_product_inplace<B: Backend>(
module: &Module<B>,
basek: usize,
k_ct: usize,
k_ggsw: usize,
digits: usize,
rank_in: usize,
rank_out: usize,
sigma: f64,
) where
Module<B>: TestModuleFamily<B>
+ GLWESwitchingKeyEncryptSkFamily<B>
+ GLWEExternalProductFamily<B>
+ GGSWLayoutFamily<B>
+ GLWEDecryptFamily<B>
+ VecZnxRotateInplace,
B: TestScratchFamily<B>,
{
let n: usize = module.n();
let rows: usize = k_ct.div_ceil(basek * digits);
let digits_in: usize = 1;
let mut ct_gglwe: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::alloc(n, basek, k_ct, rows, digits_in, rank_in, rank_out);
let mut ct_rgsw: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_ggsw, rows, digits, rank_out);
let mut pt_rgsw: 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(
GLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k_ct, rank_in, rank_out)
| GLWESwitchingKey::external_product_inplace_scratch_space(module, n, basek, k_ct, k_ggsw, digits, rank_out)
| GGSWCiphertext::encrypt_sk_scratch_space(module, n, basek, k_ggsw, rank_out),
);
let r: usize = 1;
pt_rgsw.to_mut().raw_mut()[r] = 1; // X^{r}
let var_xs: f64 = 0.5;
let mut sk_in: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_in);
sk_in.fill_ternary_prob(var_xs, &mut source_xs);
let mut sk_out: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank_out);
sk_out.fill_ternary_prob(var_xs, &mut source_xs);
let sk_out_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_out);
// gglwe_{s1}(s0) = s0 -> s1
ct_gglwe.encrypt_sk(
module,
&sk_in,
&sk_out,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ct_rgsw.encrypt_sk(
module,
&pt_rgsw,
&sk_out_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut ct_rgsw_exec: GGSWCiphertextExec<Vec<u8>, B> =
GGSWCiphertextExec::alloc(module, n, basek, k_ggsw, rows, digits, rank_out);
ct_rgsw_exec.prepare(module, &ct_rgsw, scratch.borrow());
// gglwe_(m) (x) RGSW_(X^k) = gglwe_(m * X^k)
ct_gglwe.external_product_inplace(module, &ct_rgsw_exec, scratch.borrow());
(0..rank_in).for_each(|i| {
module.vec_znx_rotate_inplace(r as i64, &mut sk_in.data.as_vec_znx_mut(), i); // * X^{r}
});
let var_gct_err_lhs: f64 = sigma * sigma;
let var_gct_err_rhs: f64 = 0f64;
let var_msg: f64 = 1f64 / n as f64; // X^{k}
let var_a0_err: f64 = sigma * sigma;
let var_a1_err: f64 = 1f64 / 12f64;
let max_noise: f64 = noise_ggsw_product(
n as f64,
basek * digits,
var_xs,
var_msg,
var_a0_err,
var_a1_err,
var_gct_err_lhs,
var_gct_err_rhs,
rank_out as f64,
k_ct,
k_ggsw,
);
ct_gglwe
.key
.assert_noise(module, &sk_out_exec, &sk_in.data, max_noise + 0.5);
}

View File

@@ -1,5 +0,0 @@
mod cpu_spqlios;
mod generic_serialization;
mod generics_automorphism_key;
mod generics_gglwe;
mod generics_tensor_key;

View File

@@ -1,18 +0,0 @@
mod automorphism;
mod encryption;
mod external_product;
mod keyswitch;
mod layout;
mod layout_compressed;
mod layout_exec;
mod noise;
pub use encryption::*;
pub use keyswitch::*;
pub use layout::*;
pub use layout_compressed::*;
pub use layout_exec::*;
pub use noise::*;
#[cfg(test)]
mod test;

View File

@@ -1 +0,0 @@
mod fft64;

View File

@@ -1,15 +0,0 @@
use backend::hal::tests::serialization::test_reader_writer_interface;
use crate::{GGSWCiphertext, GGSWCiphertextCompressed};
#[test]
fn ggsw_test_serialization() {
let original: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(1024, 12, 54, 3, 1, 2);
test_reader_writer_interface(original);
}
#[test]
fn ggsw_test_compressed_serialization() {
let original: GGSWCiphertextCompressed<Vec<u8>> = GGSWCiphertextCompressed::alloc(1024, 12, 54, 3, 1, 2);
test_reader_writer_interface(original);
}

View File

@@ -1,781 +0,0 @@
use backend::hal::{
api::{
ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxAddScalarInplace, VecZnxAutomorphism, VecZnxAutomorphismInplace, VecZnxCopy,
VecZnxRotateInplace, VecZnxStd, VecZnxSubABInplace, VecZnxSwithcDegree, ZnxViewMut,
},
layouts::{Backend, Module, ScalarZnx, ScalarZnxToMut, ScratchOwned},
oep::{
ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeScalarZnxImpl, TakeSvpPPolImpl,
TakeVecZnxBigImpl, TakeVecZnxDftImpl, TakeVecZnxImpl, VecZnxBigAllocBytesImpl, VecZnxDftAllocBytesImpl,
},
};
use sampling::source::Source;
use crate::{
AutomorphismKey, AutomorphismKeyExec, Decompress, GGLWEExecLayoutFamily, GGSWAssertNoiseFamily, GGSWCiphertext,
GGSWCiphertextCompressed, GGSWCiphertextExec, GGSWEncryptSkFamily, GGSWKeySwitchFamily, GLWESecret, GLWESecretExec,
GLWESecretFamily, GLWESwitchingKey, GLWESwitchingKeyEncryptSkFamily, GLWESwitchingKeyExec, GLWETensorKey,
GLWETensorKeyEncryptSkFamily, GLWETensorKeyExec,
noise::{noise_ggsw_keyswitch, noise_ggsw_product},
};
pub(crate) trait TestModuleFamily<B: Backend> = GLWESecretFamily<B>
+ GGSWEncryptSkFamily<B>
+ GGSWAssertNoiseFamily<B>
+ VecZnxAddScalarInplace
+ VecZnxSubABInplace
+ VecZnxStd
+ VecZnxCopy;
pub(crate) trait TestScratchFamily<B: Backend> = TakeVecZnxDftImpl<B>
+ TakeVecZnxBigImpl<B>
+ TakeSvpPPolImpl<B>
+ ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ ScratchAvailableImpl<B>
+ TakeScalarZnxImpl<B>
+ TakeVecZnxImpl<B>
+ VecZnxDftAllocBytesImpl<B>
+ VecZnxBigAllocBytesImpl<B>
+ TakeSvpPPolImpl<B>;
pub(crate) fn test_encrypt_sk<B: Backend>(module: &Module<B>, basek: usize, k: usize, digits: usize, rank: usize, sigma: f64)
where
Module<B>: TestModuleFamily<B>,
B: TestScratchFamily<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 mut sk_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk);
sk_exec.prepare(module, &sk);
ct.encrypt_sk(
module,
&pt_scalar,
&sk_exec,
&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_exec, &pt_scalar, &noise_f);
}
pub(crate) fn test_encrypt_sk_compressed<B: Backend>(
module: &Module<B>,
basek: usize,
k: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: TestModuleFamily<B>,
B: TestScratchFamily<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 mut sk_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk);
sk_exec.prepare(module, &sk);
let seed_xa: [u8; 32] = [1u8; 32];
ct_compressed.encrypt_sk(
module,
&pt_scalar,
&sk_exec,
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_exec, &pt_scalar, &noise_f);
}
pub(crate) fn test_keyswitch<B: Backend>(
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>: TestModuleFamily<B>
+ GGSWAssertNoiseFamily<B>
+ GGSWKeySwitchFamily<B>
+ GLWESwitchingKeyEncryptSkFamily<B>
+ GLWETensorKeyEncryptSkFamily<B>
+ GGLWEExecLayoutFamily<B>
+ VecZnxSwithcDegree,
B: TestScratchFamily<B> + VecZnxDftAllocBytesImpl<B> + VecZnxBigAllocBytesImpl<B> + TakeSvpPPolImpl<B>,
{
let n: usize = module.n();
let rows: usize = k_in.div_ceil(digits * basek);
let digits_in: usize = 1;
let mut ct_in: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_in, rows, digits_in, rank);
let mut ct_out: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_out, rows, digits_in, rank);
let mut tsk: GLWETensorKey<Vec<u8>> = GLWETensorKey::alloc(n, basek, k_ksk, rows, digits, rank);
let mut ksk: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::alloc(n, basek, k_ksk, rows, digits, rank, 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)
| GLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k_ksk, rank, rank)
| GLWETensorKey::encrypt_sk_scratch_space(module, n, basek, k_tsk, rank)
| GGSWCiphertext::keyswitch_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_in: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_in.fill_ternary_prob(var_xs, &mut source_xs);
let sk_in_dft: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_in);
let mut sk_out: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_out.fill_ternary_prob(var_xs, &mut source_xs);
let sk_out_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_out);
ksk.encrypt_sk(
module,
&sk_in,
&sk_out,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
tsk.encrypt_sk(
module,
&sk_out,
&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_in_dft,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut ksk_exec: GLWESwitchingKeyExec<Vec<u8>, B> =
GLWESwitchingKeyExec::alloc(module, n, basek, k_ksk, rows, digits, rank, rank);
let mut tsk_exec: GLWETensorKeyExec<Vec<u8>, B> = GLWETensorKeyExec::alloc(module, n, basek, k_ksk, rows, digits, rank);
ksk_exec.prepare(module, &ksk, scratch.borrow());
tsk_exec.prepare(module, &tsk, scratch.borrow());
ct_out.keyswitch(module, &ct_in, &ksk_exec, &tsk_exec, scratch.borrow());
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_out_exec, &pt_scalar, &max_noise);
}
pub(crate) fn test_keyswitch_inplace<B: Backend>(
module: &Module<B>,
basek: usize,
k_ct: usize,
k_ksk: usize,
k_tsk: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: TestModuleFamily<B>
+ GGSWAssertNoiseFamily<B>
+ GGSWKeySwitchFamily<B>
+ GLWESwitchingKeyEncryptSkFamily<B>
+ GLWETensorKeyEncryptSkFamily<B>
+ GGLWEExecLayoutFamily<B>
+ VecZnxSwithcDegree,
B: TestScratchFamily<B>,
{
let n: usize = module.n();
let rows: usize = k_ct.div_ceil(digits * basek);
let digits_in: usize = 1;
let mut ct: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_ct, rows, digits_in, rank);
let mut tsk: GLWETensorKey<Vec<u8>> = GLWETensorKey::alloc(n, basek, k_tsk, rows, digits, rank);
let mut ksk: GLWESwitchingKey<Vec<u8>> = GLWESwitchingKey::alloc(n, basek, k_ksk, rows, digits, rank, 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)
| GLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k_ksk, rank, rank)
| GLWETensorKey::encrypt_sk_scratch_space(module, n, basek, k_tsk, rank)
| GGSWCiphertext::keyswitch_inplace_scratch_space(module, n, basek, k_ct, k_ksk, digits, k_tsk, digits, rank),
);
let var_xs: f64 = 0.5;
let mut sk_in: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_in.fill_ternary_prob(var_xs, &mut source_xs);
let sk_in_dft: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_in);
let mut sk_out: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk_out.fill_ternary_prob(var_xs, &mut source_xs);
let sk_out_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk_out);
ksk.encrypt_sk(
module,
&sk_in,
&sk_out,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
tsk.encrypt_sk(
module,
&sk_out,
&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_in_dft,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut ksk_exec: GLWESwitchingKeyExec<Vec<u8>, B> =
GLWESwitchingKeyExec::alloc(module, n, basek, k_ksk, rows, digits, rank, rank);
let mut tsk_exec: GLWETensorKeyExec<Vec<u8>, B> = GLWETensorKeyExec::alloc(module, n, basek, k_ksk, rows, digits, rank);
ksk_exec.prepare(module, &ksk, scratch.borrow());
tsk_exec.prepare(module, &tsk, scratch.borrow());
ct.keyswitch_inplace(module, &ksk_exec, &tsk_exec, scratch.borrow());
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_out_exec, &pt_scalar, &max_noise);
}
pub(crate) fn test_automorphism<B: Backend>(
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>: TestModuleFamily<B>
+ GGSWAssertNoiseFamily<B>
+ GGSWKeySwitchFamily<B>
+ GLWESwitchingKeyEncryptSkFamily<B>
+ GLWETensorKeyEncryptSkFamily<B>
+ GGLWEExecLayoutFamily<B>
+ VecZnxSwithcDegree
+ VecZnxAutomorphismInplace
+ VecZnxAutomorphismInplace
+ VecZnxAutomorphism,
B: TestScratchFamily<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: GLWETensorKey<Vec<u8>> = GLWETensorKey::alloc(n, basek, k_tsk, rows, digits, rank);
let mut auto_key: AutomorphismKey<Vec<u8>> = AutomorphismKey::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)
| AutomorphismKey::encrypt_sk_scratch_space(module, n, basek, k_ksk, rank)
| GLWETensorKey::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_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk);
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_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut auto_key_exec: AutomorphismKeyExec<Vec<u8>, B> =
AutomorphismKeyExec::alloc(module, n, basek, k_ksk, rows, digits, rank);
auto_key_exec.prepare(module, &auto_key, scratch.borrow());
let mut tsk_exec: GLWETensorKeyExec<Vec<u8>, B> = GLWETensorKeyExec::alloc(module, n, basek, k_tsk, rows, digits, rank);
tsk_exec.prepare(module, &tensor_key, scratch.borrow());
ct_out.automorphism(module, &ct_in, &auto_key_exec, &tsk_exec, 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_exec, &pt_scalar, &max_noise);
}
pub(crate) fn test_automorphism_inplace<B: Backend>(
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>: TestModuleFamily<B>
+ GGSWAssertNoiseFamily<B>
+ GGSWKeySwitchFamily<B>
+ GLWESwitchingKeyEncryptSkFamily<B>
+ GLWETensorKeyEncryptSkFamily<B>
+ GGLWEExecLayoutFamily<B>
+ VecZnxSwithcDegree
+ VecZnxAutomorphismInplace
+ VecZnxAutomorphism
+ VecZnxAutomorphismInplace,
B: TestScratchFamily<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: GLWETensorKey<Vec<u8>> = GLWETensorKey::alloc(n, basek, k_tsk, rows, digits, rank);
let mut auto_key: AutomorphismKey<Vec<u8>> = AutomorphismKey::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)
| AutomorphismKey::encrypt_sk_scratch_space(module, n, basek, k_ksk, rank)
| GLWETensorKey::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_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk);
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_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut auto_key_exec: AutomorphismKeyExec<Vec<u8>, B> =
AutomorphismKeyExec::alloc(module, n, basek, k_ksk, rows, digits, rank);
auto_key_exec.prepare(module, &auto_key, scratch.borrow());
let mut tsk_exec: GLWETensorKeyExec<Vec<u8>, B> = GLWETensorKeyExec::alloc(module, n, basek, k_tsk, rows, digits, rank);
tsk_exec.prepare(module, &tensor_key, scratch.borrow());
ct.automorphism_inplace(module, &auto_key_exec, &tsk_exec, 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_exec, &pt_scalar, &max_noise);
}
pub(crate) fn test_external_product<B: Backend>(
module: &Module<B>,
basek: usize,
k_in: usize,
k_out: usize,
k_ggsw: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: TestModuleFamily<B>
+ GGSWAssertNoiseFamily<B>
+ GGSWKeySwitchFamily<B>
+ GLWESwitchingKeyEncryptSkFamily<B>
+ GLWETensorKeyEncryptSkFamily<B>
+ GGLWEExecLayoutFamily<B>
+ VecZnxRotateInplace,
B: TestScratchFamily<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_ggsw_lhs_in: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_in, rows_in, digits_in, rank);
let mut ct_ggsw_lhs_out: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_out, rows_in, digits_in, rank);
let mut ct_ggsw_rhs: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_ggsw, rows, digits, rank);
let mut pt_ggsw_lhs: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
let mut pt_ggsw_rhs: 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_ggsw_lhs.fill_ternary_prob(0, 0.5, &mut source_xs);
let k: usize = 1;
pt_ggsw_rhs.to_mut().raw_mut()[k] = 1; //X^{k}
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GGSWCiphertext::encrypt_sk_scratch_space(module, n, basek, k_ggsw, rank)
| GGSWCiphertext::external_product_scratch_space(module, n, basek, k_out, k_in, k_ggsw, digits, rank),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk);
ct_ggsw_rhs.encrypt_sk(
module,
&pt_ggsw_rhs,
&sk_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ct_ggsw_lhs_in.encrypt_sk(
module,
&pt_ggsw_lhs,
&sk_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut ct_rhs_exec: GGSWCiphertextExec<Vec<u8>, B> = GGSWCiphertextExec::alloc(module, n, basek, k_ggsw, rows, digits, rank);
ct_rhs_exec.prepare(module, &ct_ggsw_rhs, scratch.borrow());
ct_ggsw_lhs_out.external_product(module, &ct_ggsw_lhs_in, &ct_rhs_exec, scratch.borrow());
module.vec_znx_rotate_inplace(k as i64, &mut pt_ggsw_lhs.as_vec_znx_mut(), 0);
let var_gct_err_lhs: f64 = sigma * sigma;
let var_gct_err_rhs: f64 = 0f64;
let var_msg: f64 = 1f64 / n as f64; // X^{k}
let var_a0_err: f64 = sigma * sigma;
let var_a1_err: f64 = 1f64 / 12f64;
let max_noise = |_col_j: usize| -> f64 {
noise_ggsw_product(
n as f64,
basek * digits,
0.5,
var_msg,
var_a0_err,
var_a1_err,
var_gct_err_lhs,
var_gct_err_rhs,
rank as f64,
k_in,
k_ggsw,
) + 0.5
};
ct_ggsw_lhs_out.assert_noise(module, &sk_exec, &pt_ggsw_lhs, &max_noise);
}
pub(crate) fn test_external_product_inplace<B: Backend>(
module: &Module<B>,
basek: usize,
k_ct: usize,
k_ggsw: usize,
digits: usize,
rank: usize,
sigma: f64,
) where
Module<B>: TestModuleFamily<B>
+ GGSWAssertNoiseFamily<B>
+ GGSWKeySwitchFamily<B>
+ GLWESwitchingKeyEncryptSkFamily<B>
+ GLWETensorKeyEncryptSkFamily<B>
+ GGLWEExecLayoutFamily<B>
+ VecZnxRotateInplace,
B: TestScratchFamily<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_ggsw_lhs: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_ct, rows_in, digits_in, rank);
let mut ct_ggsw_rhs: GGSWCiphertext<Vec<u8>> = GGSWCiphertext::alloc(n, basek, k_ggsw, rows, digits, rank);
let mut pt_ggsw_lhs: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(n, 1);
let mut pt_ggsw_rhs: 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_ggsw_lhs.fill_ternary_prob(0, 0.5, &mut source_xs);
let k: usize = 1;
pt_ggsw_rhs.to_mut().raw_mut()[k] = 1; //X^{k}
let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(
GGSWCiphertext::encrypt_sk_scratch_space(module, n, basek, k_ggsw, rank)
| GGSWCiphertext::external_product_inplace_scratch_space(module, n, basek, k_ct, k_ggsw, digits, rank),
);
let mut sk: GLWESecret<Vec<u8>> = GLWESecret::alloc(n, rank);
sk.fill_ternary_prob(0.5, &mut source_xs);
let sk_exec: GLWESecretExec<Vec<u8>, B> = GLWESecretExec::from(module, &sk);
ct_ggsw_rhs.encrypt_sk(
module,
&pt_ggsw_rhs,
&sk_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
ct_ggsw_lhs.encrypt_sk(
module,
&pt_ggsw_lhs,
&sk_exec,
&mut source_xa,
&mut source_xe,
sigma,
scratch.borrow(),
);
let mut ct_rhs_exec: GGSWCiphertextExec<Vec<u8>, B> = GGSWCiphertextExec::alloc(module, n, basek, k_ggsw, rows, digits, rank);
ct_rhs_exec.prepare(module, &ct_ggsw_rhs, scratch.borrow());
ct_ggsw_lhs.external_product_inplace(module, &ct_rhs_exec, scratch.borrow());
module.vec_znx_rotate_inplace(k as i64, &mut pt_ggsw_lhs.as_vec_znx_mut(), 0);
let var_gct_err_lhs: f64 = sigma * sigma;
let var_gct_err_rhs: f64 = 0f64;
let var_msg: f64 = 1f64 / n as f64; // X^{k}
let var_a0_err: f64 = sigma * sigma;
let var_a1_err: f64 = 1f64 / 12f64;
let max_noise = |_col_j: usize| -> f64 {
noise_ggsw_product(
n as f64,
basek * digits,
0.5,
var_msg,
var_a0_err,
var_a1_err,
var_gct_err_lhs,
var_gct_err_rhs,
rank as f64,
k_ct,
k_ggsw,
) + 0.5
};
ct_ggsw_lhs.assert_noise(module, &sk_exec, &pt_ggsw_lhs, &max_noise);
}

View File

@@ -1,3 +0,0 @@
mod cpu_spqlios;
mod generic_serialization;
mod generic_tests;

View File

@@ -1,28 +0,0 @@
mod automorphism;
mod decryption;
mod encryption;
mod external_product;
mod keyswitch;
mod layout;
mod noise;
mod ops;
mod packing;
mod plaintext;
mod public_key;
mod secret;
mod trace;
#[cfg(test)]
mod tests;
pub use decryption::*;
pub use encryption::*;
pub use external_product::*;
pub use keyswitch::*;
pub use layout::*;
pub use ops::GLWEOps;
pub use packing::*;
pub use plaintext::*;
pub use public_key::*;
pub use secret::*;
pub use trace::*;

View File

@@ -1,204 +0,0 @@
use backend::hal::{
api::{ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxDftAlloc, VecZnxDftAllocBytes, VecZnxDftFromVecZnx},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, Scratch, ScratchOwned, VecZnx, VecZnxDft, WriterTo},
oep::{ScratchAvailableImpl, ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl, TakeVecZnxDftImpl, TakeVecZnxImpl},
};
use sampling::source::Source;
use crate::{GLWECiphertext, GLWEEncryptSkFamily, GLWESecretExec, Infos, dist::Distribution};
pub trait GLWEPublicKeyFamily<B: Backend> = GLWEEncryptSkFamily<B>;
#[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: basek,
k: 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> GLWEPublicKey<D> {
pub fn generate_from_sk<S: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
sk: &GLWESecretExec<S, B>,
source_xa: &mut Source,
source_xe: &mut Source,
sigma: f64,
) where
Module<B>: GLWEPublicKeyFamily<B>,
B: ScratchOwnedAllocImpl<B>
+ ScratchOwnedBorrowImpl<B>
+ TakeVecZnxDftImpl<B>
+ ScratchAvailableImpl<B>
+ TakeVecZnxImpl<B>,
{
#[cfg(debug_assertions)]
{
assert_eq!(self.n(), sk.n());
match 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;
}
}
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
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)
}
}
#[derive(PartialEq, Eq)]
pub struct GLWEPublicKeyExec<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 GLWEPublicKeyExec<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> GLWEPublicKeyExec<D, B> {
pub fn rank(&self) -> usize {
self.cols() - 1
}
}
impl<B: Backend> GLWEPublicKeyExec<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: basek,
k: 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))
}
pub fn from<DataOther>(module: &Module<B>, other: &GLWEPublicKey<DataOther>, scratch: &mut Scratch<B>) -> Self
where
DataOther: DataRef,
Module<B>: VecZnxDftAlloc<B> + VecZnxDftFromVecZnx<B>,
{
let mut pk_exec: GLWEPublicKeyExec<Vec<u8>, B> =
GLWEPublicKeyExec::alloc(module, other.n(), other.basek(), other.k(), other.rank());
pk_exec.prepare(module, other, scratch);
pk_exec
}
}
impl<D: DataMut, B: Backend> GLWEPublicKeyExec<D, B> {
pub fn prepare<DataOther>(&mut self, module: &Module<B>, other: &GLWEPublicKey<DataOther>, _scratch: &mut Scratch<B>)
where
DataOther: DataRef,
Module<B>: VecZnxDftFromVecZnx<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

@@ -1 +0,0 @@
mod fft64;

View File

@@ -1,15 +0,0 @@
use backend::hal::tests::serialization::test_reader_writer_interface;
use crate::{GLWECiphertext, GLWECiphertextCompressed};
#[test]
fn test_serialization() {
let original: GLWECiphertext<Vec<u8>> = GLWECiphertext::alloc(1024, 12, 54, 3);
test_reader_writer_interface(original);
}
#[test]
fn test_compressed_serialization() {
let original: GLWECiphertextCompressed<Vec<u8>> = GLWECiphertextCompressed::alloc(1024, 12, 54, 3);
test_reader_writer_interface(original);
}

View File

@@ -1,8 +0,0 @@
mod cpu_spqlios;
mod generic_automorphism;
mod generic_encryption;
mod generic_external_product;
mod generic_keyswitch;
mod generic_serialization;
mod packing;
mod trace;

View File

@@ -1,29 +1,16 @@
use std::collections::HashMap;
use backend::hal::{
api::{
ScratchAvailable, TakeVecZnx, TakeVecZnxDft, VecZnxAddInplace, VecZnxAutomorphismInplace, VecZnxBigAutomorphismInplace,
VecZnxBigSubSmallBInplace, VecZnxCopy, VecZnxNegateInplace, VecZnxNormalizeInplace, VecZnxRotate, VecZnxRotateInplace,
VecZnxRshInplace, VecZnxSub, VecZnxSubABInplace,
},
api::{ScratchAvailable, TakeVecZnx, TakeVecZnxDft, VecZnxCopy},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{AutomorphismKeyExec, GLWECiphertext, GLWEKeyswitchFamily, GLWEOps, Infos, TakeGLWECt};
use crate::{
GLWEOperations, TakeGLWECt,
layouts::{GLWECiphertext, Infos, prepared::GGLWEAutomorphismKeyExec},
};
pub trait GLWEPackingFamily<B: Backend> = GLWEKeyswitchFamily<B>
+ VecZnxCopy
+ VecZnxRotateInplace
+ VecZnxSub
+ VecZnxNegateInplace
+ VecZnxRshInplace
+ VecZnxAddInplace
+ VecZnxNormalizeInplace<B>
+ VecZnxSubABInplace
+ VecZnxRotate
+ VecZnxAutomorphismInplace
+ VecZnxBigSubSmallBInplace<B>
+ VecZnxBigAutomorphismInplace<B>;
use crate::trait_families::{GLWEKeyswitchFamily, GLWEPackingFamily};
/// [GLWEPacker] enables only the fly GLWE packing
/// with constant memory of Log(N) ciphertexts.
@@ -128,7 +115,7 @@ impl GLWEPacker {
&mut self,
module: &Module<B>,
a: Option<&GLWECiphertext<DataA>>,
auto_keys: &HashMap<i64, AutomorphismKeyExec<DataAK, B>>,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyExec<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEPackingFamily<B>,
@@ -187,7 +174,7 @@ fn pack_core<D: DataRef, DataAK: DataRef, B: Backend>(
a: Option<&GLWECiphertext<D>>,
accumulators: &mut [Accumulator],
i: usize,
auto_keys: &HashMap<i64, AutomorphismKeyExec<DataAK, B>>,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyExec<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEPackingFamily<B>,
@@ -265,7 +252,7 @@ fn combine<D: DataRef, DataAK: DataRef, B: Backend>(
acc: &mut Accumulator,
b: Option<&GLWECiphertext<D>>,
i: usize,
auto_keys: &HashMap<i64, AutomorphismKeyExec<DataAK, B>>,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyExec<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEPackingFamily<B>,

View File

@@ -1,13 +1,13 @@
use std::collections::HashMap;
use backend::hal::{
api::{ScratchAvailable, TakeVecZnxDft, VecZnxBigAutomorphismInplace, VecZnxCopy, VecZnxRshInplace},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
use backend::hal::layouts::{Backend, DataMut, DataRef, Module, Scratch};
use crate::{
layouts::{GLWECiphertext, prepared::GGLWEAutomorphismKeyExec},
operations::GLWEOperations,
};
use crate::{AutomorphismKeyExec, GLWECiphertext, GLWECiphertextToMut, GLWEKeyswitchFamily, GLWEOps, Infos, SetMetaData};
pub trait GLWETraceFamily<B: Backend> = GLWEKeyswitchFamily<B> + VecZnxCopy + VecZnxRshInplace + VecZnxBigAutomorphismInplace<B>;
use crate::trait_families::{GLWETraceModuleFamily, GLWETraceScratchFamily};
impl GLWECiphertext<Vec<u8>> {
pub fn trace_galois_elements<B: Backend>(module: &Module<B>) -> Vec<i64> {
@@ -33,7 +33,7 @@ impl GLWECiphertext<Vec<u8>> {
rank: usize,
) -> usize
where
Module<B>: GLWEKeyswitchFamily<B>,
Module<B>: GLWETraceModuleFamily<B>,
{
Self::automorphism_inplace_scratch_space(module, n, basek, out_k.min(in_k), ksk_k, digits, rank)
}
@@ -48,27 +48,24 @@ impl GLWECiphertext<Vec<u8>> {
rank: usize,
) -> usize
where
Module<B>: GLWEKeyswitchFamily<B>,
Module<B>: GLWETraceModuleFamily<B>,
{
Self::automorphism_inplace_scratch_space(module, n, basek, out_k, ksk_k, digits, rank)
}
}
impl<DataSelf: DataMut> GLWECiphertext<DataSelf>
where
GLWECiphertext<DataSelf>: GLWECiphertextToMut + Infos + SetMetaData,
{
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, AutomorphismKeyExec<DataAK, B>>,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyExec<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWETraceFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
Module<B>: GLWETraceModuleFamily<B>,
Scratch<B>: GLWETraceScratchFamily<B>,
{
self.copy(module, lhs);
self.trace_inplace(module, start, end, auto_keys, scratch);
@@ -79,11 +76,11 @@ where
module: &Module<B>,
start: usize,
end: usize,
auto_keys: &HashMap<i64, AutomorphismKeyExec<DataAK, B>>,
auto_keys: &HashMap<i64, GGLWEAutomorphismKeyExec<DataAK, B>>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWETraceFamily<B>,
Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable,
Module<B>: GLWETraceModuleFamily<B>,
Scratch<B>: GLWETraceScratchFamily<B>,
{
(start..end).for_each(|i| {
self.rsh(module, 1);

View File

@@ -4,10 +4,14 @@ use backend::hal::{
};
use crate::{
AutomorphismKey, AutomorphismKeyExec, GLWECiphertext, GLWEKeyswitchFamily, GLWESwitchingKey, GLWESwitchingKeyExec, Infos,
layouts::{
GGLWEAutomorphismKey, GLWECiphertext, GGLWESwitchingKey, Infos,
prepared::{GGLWEAutomorphismKeyExec, GGLWESwitchingKeyExec},
},
trait_families::GLWEKeyswitchFamily,
};
impl AutomorphismKey<Vec<u8>> {
impl GGLWEAutomorphismKey<Vec<u8>> {
pub fn keyswitch_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
@@ -21,7 +25,7 @@ impl AutomorphismKey<Vec<u8>> {
where
Module<B>: GLWEKeyswitchFamily<B>,
{
GLWESwitchingKey::keyswitch_scratch_space(module, n, basek, k_out, k_in, k_ksk, digits, rank, rank)
GGLWESwitchingKey::keyswitch_scratch_space(module, n, basek, k_out, k_in, k_ksk, digits, rank, rank)
}
pub fn keyswitch_inplace_scratch_space<B: Backend>(
@@ -36,16 +40,16 @@ impl AutomorphismKey<Vec<u8>> {
where
Module<B>: GLWEKeyswitchFamily<B>,
{
GLWESwitchingKey::keyswitch_inplace_scratch_space(module, n, basek, k_out, k_ksk, digits, rank)
GGLWESwitchingKey::keyswitch_inplace_scratch_space(module, n, basek, k_out, k_ksk, digits, rank)
}
}
impl<DataSelf: DataMut> AutomorphismKey<DataSelf> {
impl<DataSelf: DataMut> GGLWEAutomorphismKey<DataSelf> {
pub fn keyswitch<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &AutomorphismKey<DataLhs>,
rhs: &GLWESwitchingKeyExec<DataRhs, B>,
lhs: &GGLWEAutomorphismKey<DataLhs>,
rhs: &GGLWESwitchingKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B>,
@@ -57,7 +61,7 @@ impl<DataSelf: DataMut> AutomorphismKey<DataSelf> {
pub fn keyswitch_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &AutomorphismKeyExec<DataRhs, B>,
rhs: &GGLWEAutomorphismKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B>,
@@ -67,7 +71,7 @@ impl<DataSelf: DataMut> AutomorphismKey<DataSelf> {
}
}
impl GLWESwitchingKey<Vec<u8>> {
impl GGLWESwitchingKey<Vec<u8>> {
pub fn keyswitch_scratch_space<B: Backend>(
module: &Module<B>,
n: usize,
@@ -103,12 +107,12 @@ impl GLWESwitchingKey<Vec<u8>> {
}
}
impl<DataSelf: DataMut> GLWESwitchingKey<DataSelf> {
impl<DataSelf: DataMut> GGLWESwitchingKey<DataSelf> {
pub fn keyswitch<DataLhs: DataRef, DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
lhs: &GLWESwitchingKey<DataLhs>,
rhs: &GLWESwitchingKeyExec<DataRhs, B>,
lhs: &GGLWESwitchingKey<DataLhs>,
rhs: &GGLWESwitchingKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B>,
@@ -156,7 +160,7 @@ impl<DataSelf: DataMut> GLWESwitchingKey<DataSelf> {
pub fn keyswitch_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GLWESwitchingKeyExec<DataRhs, B>,
rhs: &GGLWESwitchingKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B>,

View File

@@ -7,12 +7,14 @@ use backend::hal::{
};
use crate::{
GGLWECiphertext, GGSWCiphertext, GLWECiphertext, GLWEKeyswitchFamily, GLWEOps, GLWESwitchingKeyExec, GLWETensorKeyExec, Infos,
layouts::{
GGLWECiphertext, GGSWCiphertext, GLWECiphertext, Infos,
prepared::{GGLWESwitchingKeyExec, GGLWETensorKeyExec},
},
operations::GLWEOperations,
trait_families::{GGSWKeySwitchFamily, GLWEKeyswitchFamily},
};
pub trait GGSWKeySwitchFamily<B> =
GLWEKeyswitchFamily<B> + VecZnxBigAllocBytes + VecZnxDftCopy<B> + VecZnxDftAddInplace<B> + VecZnxDftToVecZnxBigTmpA<B>;
impl GGSWCiphertext<Vec<u8>> {
pub(crate) fn expand_row_scratch_space<B: Backend>(
module: &Module<B>,
@@ -95,7 +97,7 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
&mut self,
module: &Module<B>,
a: &GGLWECiphertext<DataA>,
tsk: &GLWETensorKeyExec<DataTsk, B>,
tsk: &GGLWETensorKeyExec<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
DataA: DataRef,
@@ -121,8 +123,8 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
&mut self,
module: &Module<B>,
lhs: &GGSWCiphertext<DataLhs>,
ksk: &GLWESwitchingKeyExec<DataKsk, B>,
tsk: &GLWETensorKeyExec<DataTsk, B>,
ksk: &GGLWESwitchingKeyExec<DataKsk, B>,
tsk: &GGLWETensorKeyExec<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + GGSWKeySwitchFamily<B> + VecZnxNormalizeTmpBytes,
@@ -135,8 +137,8 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
pub fn keyswitch_inplace<DataKsk: DataRef, DataTsk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
ksk: &GLWESwitchingKeyExec<DataKsk, B>,
tsk: &GLWETensorKeyExec<DataTsk, B>,
ksk: &GGLWESwitchingKeyExec<DataKsk, B>,
tsk: &GGLWETensorKeyExec<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + GGSWKeySwitchFamily<B> + VecZnxNormalizeTmpBytes,
@@ -151,7 +153,7 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
pub fn expand_row<DataTsk: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
tsk: &GLWETensorKeyExec<DataTsk, B>,
tsk: &GGLWETensorKeyExec<DataTsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GGSWKeySwitchFamily<B> + VecZnxNormalizeTmpBytes,
@@ -276,7 +278,7 @@ impl<DataSelf: DataMut> GGSWCiphertext<DataSelf> {
&mut self,
module: &Module<B>,
lhs: &GGSWCiphertext<DataLhs>,
ksk: &GLWESwitchingKeyExec<DataKsk, B>,
ksk: &GGLWESwitchingKeyExec<DataKsk, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B> + GGSWKeySwitchFamily<B> + VecZnxNormalizeTmpBytes,

View File

@@ -6,18 +6,10 @@ use backend::hal::{
layouts::{Backend, DataMut, DataRef, Module, Scratch, VecZnx, VecZnxBig, VecZnxDft, VmpPMat},
};
use crate::{GLWECiphertext, GLWESwitchingKeyExec, Infos};
pub trait GLWEKeyswitchFamily<B: Backend> = VecZnxDftAllocBytes
+ VmpApplyTmpBytes
+ VecZnxBigNormalizeTmpBytes
+ VmpApplyTmpBytes
+ VmpApply<B>
+ VmpApplyAdd<B>
+ VecZnxDftFromVecZnx<B>
+ VecZnxDftToVecZnxBigConsume<B>
+ VecZnxBigAddSmallInplace<B>
+ VecZnxBigNormalize<B>;
use crate::{
layouts::{GLWECiphertext, Infos, prepared::GGLWESwitchingKeyExec},
trait_families::GLWEKeyswitchFamily,
};
impl GLWECiphertext<Vec<u8>> {
pub fn keyswitch_scratch_space<B: Backend>(
@@ -52,25 +44,6 @@ impl GLWECiphertext<Vec<u8>> {
return res_dft + ((ai_dft + vmp) | normalize);
}
pub fn keyswitch_from_fourier_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>: GLWEKeyswitchFamily<B>,
{
Self::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,
@@ -92,7 +65,7 @@ impl<DataSelf: DataRef> GLWECiphertext<DataSelf> {
&self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &GLWESwitchingKeyExec<DataRhs, B>,
rhs: &GGLWESwitchingKeyExec<DataRhs, B>,
scratch: &Scratch<B>,
) where
DataLhs: DataRef,
@@ -163,7 +136,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
&mut self,
module: &Module<B>,
lhs: &GLWECiphertext<DataLhs>,
rhs: &GLWESwitchingKeyExec<DataRhs, B>,
rhs: &GGLWESwitchingKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B>,
@@ -174,7 +147,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
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> = keyswitch(module, res_dft, lhs, rhs, scratch1);
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);
})
@@ -183,7 +156,7 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
pub fn keyswitch_inplace<DataRhs: DataRef, B: Backend>(
&mut self,
module: &Module<B>,
rhs: &GLWESwitchingKeyExec<DataRhs, B>,
rhs: &GGLWESwitchingKeyExec<DataRhs, B>,
scratch: &mut Scratch<B>,
) where
Module<B>: GLWEKeyswitchFamily<B>,
@@ -196,32 +169,33 @@ impl<DataSelf: DataMut> GLWECiphertext<DataSelf> {
}
}
pub(crate) fn keyswitch<B: Backend, DataRes, DataIn, DataKey>(
module: &Module<B>,
res_dft: VecZnxDft<DataRes, B>,
lhs: &GLWECiphertext<DataIn>,
rhs: &GLWESwitchingKeyExec<DataKey, B>,
scratch: &mut Scratch<B>,
) -> VecZnxBig<DataRes, B>
where
DataRes: DataMut,
DataIn: DataRef,
DataKey: DataRef,
Module<B>: GLWEKeyswitchFamily<B>,
Scratch<B>: TakeVecZnxDft<B>,
{
if rhs.digits() == 1 {
return keyswitch_vmp_one_digit(module, res_dft, &lhs.data, &rhs.key.data, 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: &GGLWESwitchingKeyExec<DataKey, B>,
scratch: &mut Scratch<B>,
) -> VecZnxBig<DataRes, B>
where
DataRes: DataMut,
DataKey: DataRef,
Module<B>: GLWEKeyswitchFamily<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,
&lhs.data,
&rhs.key.data,
rhs.digits(),
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>(

View File

@@ -0,0 +1,68 @@
use backend::hal::{
api::{ScratchAvailable, TakeVecZnx, TakeVecZnxDft, ZnxView, ZnxViewMut, ZnxZero},
layouts::{Backend, DataMut, DataRef, Module, Scratch},
};
use crate::{
TakeGLWECt,
layouts::{GLWECiphertext, Infos, LWECiphertext, prepared::LWESwitchingKeyExec},
};
use crate::trait_families::GLWEKeyswitchFamily;
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>: GLWEKeyswitchFamily<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: &LWESwitchingKeyExec<DKs, B>,
scratch: &mut Scratch<B>,
) where
A: DataRef,
DKs: DataRef,
Module<B>: GLWEKeyswitchFamily<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,115 @@
use backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
};
use crate::layouts::{GGLWEAutomorphismKey, Infos, compressed::GGLWESwitchingKeyCompressed};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
use crate::trait_families::Decompress;
#[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 sampling::source::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,252 @@
use backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
};
use crate::layouts::{GGLWECiphertext, Infos, compressed::GLWECiphertextCompressed};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
use crate::trait_families::Decompress;
#[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 sampling::source::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: 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 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,126 @@
use backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
};
use crate::{
layouts::{GGLWESwitchingKey, Infos, compressed::GGLWECiphertextCompressed},
trait_families::Decompress,
};
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 sampling::source::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,163 @@
use backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
};
use crate::layouts::{GGLWETensorKey, Infos, compressed::GGLWESwitchingKeyCompressed};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
use crate::trait_families::Decompress;
#[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 sampling::source::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: 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

@@ -3,7 +3,10 @@ use backend::hal::{
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
};
use crate::{Decompress, GGSWCiphertext, GLWECiphertextCompressed, Infos};
use crate::{
layouts::{GGSWCiphertext, Infos, compressed::GLWECiphertextCompressed},
trait_families::Decompress,
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;

View File

@@ -1,160 +1,15 @@
use backend::hal::{
api::{FillUniform, Reset, VecZnxCopy, VecZnxFillUniform, ZnxInfos},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, VecZnx, VecZnxToMut, VecZnxToRef, WriterTo},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, VecZnx, WriterTo},
};
use sampling::source::Source;
use crate::{Decompress, GLWEOps, Infos, SetMetaData};
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> 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>
where
VecZnx<D>: FillUniform,
{
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: DataRef> GLWECiphertext<D> {
pub fn clone(&self) -> GLWECiphertext<Vec<u8>> {
GLWECiphertext {
data: self.data.clone(),
basek: self.basek(),
k: self.k(),
}
}
}
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> GLWEOps for GLWECiphertext<D> where GLWECiphertext<D>: GLWECiphertextToMut + Infos + SetMetaData {}
use crate::{
layouts::{GLWECiphertext, Infos},
trait_families::{Decompress, DecompressFamily},
};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
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)
}
}
use std::fmt;
#[derive(PartialEq, Eq, Clone)]
pub struct GLWECiphertextCompressed<D: Data> {
@@ -185,10 +40,7 @@ impl<D: DataRef> fmt::Display for GLWECiphertextCompressed<D> {
}
}
impl<D: DataMut> Reset for GLWECiphertextCompressed<D>
where
VecZnx<D>: Reset,
{
impl<D: DataMut> Reset for GLWECiphertextCompressed<D> {
fn reset(&mut self) {
self.data.reset();
self.basek = 0;
@@ -198,10 +50,7 @@ where
}
}
impl<D: DataMut> FillUniform for GLWECiphertextCompressed<D>
where
VecZnx<D>: FillUniform,
{
impl<D: DataMut> FillUniform for GLWECiphertextCompressed<D> {
fn fill_uniform(&mut self, source: &mut Source) {
self.data.fill_uniform(source);
}
@@ -268,7 +117,7 @@ impl<D: DataRef> WriterTo for GLWECiphertextCompressed<D> {
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>: VecZnxFillUniform + VecZnxCopy,
Module<B>: DecompressFamily<B>,
{
#[cfg(debug_assertions)]
{
@@ -307,7 +156,7 @@ impl<D: DataMut> GLWECiphertext<D> {
source: &mut Source,
) where
DataOther: DataRef,
Module<B>: VecZnxFillUniform + VecZnxCopy,
Module<B>: DecompressFamily<B>,
{
#[cfg(debug_assertions)]
{

View File

@@ -0,0 +1,98 @@
use std::fmt;
use backend::hal::{
api::{FillUniform, Reset},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
};
use crate::layouts::{GLWEToLWESwitchingKey, Infos, compressed::GGLWESwitchingKeyCompressed};
use crate::trait_families::{GGLWEEncryptSkFamily, GLWESecretExecModuleFamily};
#[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 sampling::source::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>: GGLWEEncryptSkFamily<B> + GLWESecretExecModuleFamily<B>,
{
GLWEToLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, rank_in)
}
}

View File

@@ -0,0 +1,134 @@
use std::fmt;
use backend::hal::{
api::{FillUniform, Reset, VecZnxFillUniform, ZnxInfos, ZnxView, ZnxViewMut},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, VecZnx, WriterTo},
};
use sampling::source::Source;
use crate::{
layouts::{Infos, LWECiphertext, SetMetaData},
trait_families::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: k,
basek: 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(&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,106 @@
use backend::hal::{
api::{FillUniform, Reset},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
};
use crate::layouts::{Infos, LWESwitchingKey, compressed::GGLWESwitchingKeyCompressed};
use std::fmt;
use crate::trait_families::{Decompress, GGLWEEncryptSkFamily, GLWESecretExecModuleFamily};
#[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 sampling::source::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>: GGLWEEncryptSkFamily<B> + GLWESecretExecModuleFamily<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>: crate::trait_families::DecompressFamily<B>,
{
self.0.decompress(module, &other.0);
}
}

View File

@@ -0,0 +1,109 @@
use backend::hal::{
api::{FillUniform, Reset},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, Module, ReaderFrom, WriterTo},
};
use crate::{
layouts::{Infos, LWEToGLWESwitchingKey, compressed::GGLWESwitchingKeyCompressed},
trait_families::Decompress,
};
use std::fmt;
use crate::trait_families::{GGLWEEncryptSkFamily, GLWESecretExecModuleFamily};
#[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 sampling::source::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>: GGLWEEncryptSkFamily<B> + GLWESecretExecModuleFamily<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>: crate::trait_families::DecompressFamily<B>,
{
self.0.decompress(module, &other.0);
}
}

View File

@@ -0,0 +1,21 @@
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::*;

View File

@@ -0,0 +1,120 @@
use backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
};
use crate::layouts::{GLWECiphertext, GGLWESwitchingKey, 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 sampling::source::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,167 @@
use backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
};
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 sampling::source::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: 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,133 @@
use backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
};
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 sampling::source::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,147 @@
use backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
};
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 sampling::source::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: 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

@@ -1,12 +1,10 @@
use backend::hal::{
api::{FillUniform, Reset, VmpPMatAlloc, VmpPMatAllocBytes, VmpPMatPrepare},
layouts::{Backend, Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
};
use std::fmt;
use crate::{GLWECiphertext, Infos};
pub trait GGSWLayoutFamily<B: Backend> = VmpPMatAlloc<B> + VmpPMatAllocBytes + VmpPMatPrepare<B>;
use crate::layouts::{GLWECiphertext, Infos};
#[derive(PartialEq, Eq, Clone)]
pub struct GGSWCiphertext<D: Data> {

151
core/src/layouts/glwe_ct.rs Normal file
View File

@@ -0,0 +1,151 @@
use backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, ReaderFrom, VecZnx, VecZnxToMut, VecZnxToRef, WriterTo},
};
use sampling::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> 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: DataRef> GLWECiphertext<D> {
pub fn clone(&self) -> GLWECiphertext<Vec<u8>> {
GLWECiphertext {
data: self.data.clone(),
basek: self.basek(),
k: self.k(),
}
}
}
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 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: basek,
k: 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

@@ -1,6 +1,6 @@
use backend::hal::layouts::{Data, DataMut, DataRef, VecZnx, VecZnxToMut, VecZnxToRef};
use crate::{GLWECiphertext, GLWECiphertextToMut, GLWECiphertextToRef, GLWEOps, Infos, SetMetaData};
use crate::layouts::{GLWECiphertext, GLWECiphertextToMut, GLWECiphertextToRef, Infos, SetMetaData};
pub struct GLWEPlaintext<D: Data> {
pub data: VecZnx<D>,
@@ -67,10 +67,3 @@ impl<D: DataMut> GLWECiphertextToMut for GLWEPlaintext<D> {
}
}
}
impl<D> GLWEOps for GLWEPlaintext<D>
where
D: DataMut,
GLWEPlaintext<D>: GLWECiphertextToMut + Infos + SetMetaData,
{
}

View File

@@ -1,13 +1,11 @@
use backend::hal::{
api::{SvpPPolAlloc, SvpPPolAllocBytes, SvpPrepare, ZnxInfos, ZnxZero},
layouts::{Backend, Data, DataMut, DataRef, Module, ReaderFrom, ScalarZnx, SvpPPol, WriterTo},
api::{ZnxInfos, ZnxZero},
layouts::{Data, DataMut, DataRef, ReaderFrom, ScalarZnx, WriterTo},
};
use sampling::source::Source;
use crate::dist::Distribution;
pub trait GLWESecretFamily<B: Backend> = SvpPrepare<B> + SvpPPolAllocBytes + SvpPPolAlloc<B>;
#[derive(PartialEq, Eq, Clone)]
pub struct GLWESecret<D: Data> {
pub(crate) data: ScalarZnx<D>,
@@ -102,66 +100,3 @@ impl<D: DataRef> WriterTo for GLWESecret<D> {
self.data.write_to(writer)
}
}
pub struct GLWESecretExec<D: Data, B: Backend> {
pub(crate) data: SvpPPol<D, B>,
pub(crate) dist: Distribution,
}
impl<B: Backend> GLWESecretExec<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<B: Backend> GLWESecretExec<Vec<u8>, B> {
pub fn from<D>(module: &Module<B>, sk: &GLWESecret<D>) -> Self
where
D: DataRef,
Module<B>: SvpPrepare<B> + SvpPPolAlloc<B>,
{
let mut sk_dft: GLWESecretExec<Vec<u8>, B> = Self::alloc(module, sk.n(), sk.rank());
sk_dft.prepare(module, sk);
sk_dft
}
}
impl<D: Data, B: Backend> GLWESecretExec<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: DataMut, B: Backend> GLWESecretExec<D, B> {
pub(crate) fn prepare<O>(&mut self, module: &Module<B>, sk: &GLWESecret<O>)
where
O: DataRef,
Module<B>: SvpPrepare<B>,
{
(0..self.rank()).for_each(|i| {
module.svp_prepare(&mut self.data, i, &sk.data, i);
});
self.dist = sk.dist
}
}

View File

@@ -0,0 +1,88 @@
use backend::hal::{
api::{FillUniform, Reset},
layouts::{Data, DataMut, DataRef, MatZnx, ReaderFrom, WriterTo},
};
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 sampling::source::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

@@ -1,7 +1,4 @@
use backend::hal::{
api::{VecZnxCopy, VecZnxFillUniform, ZnxInfos},
layouts::{Backend, Module},
};
use backend::hal::api::ZnxInfos;
pub trait Infos {
type Inner: ZnxInfos;
@@ -55,9 +52,3 @@ pub trait SetMetaData {
fn set_basek(&mut self, basek: usize);
fn set_k(&mut self, k: usize);
}
pub trait Decompress<B: Backend, C> {
fn decompress(&mut self, module: &Module<B>, other: &C)
where
Module<B>: VecZnxFillUniform + VecZnxCopy;
}

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