client.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. use crate::{
  2. arith::*, discrete_gaussian::*, gadget::*, number_theory::*, params::*, poly::*, util::*,
  3. };
  4. use rand::Rng;
  5. use std::{iter::once, mem::size_of};
  6. fn new_vec_raw<'a>(
  7. params: &'a Params,
  8. num: usize,
  9. rows: usize,
  10. cols: usize,
  11. ) -> Vec<PolyMatrixRaw<'a>> {
  12. let mut v = Vec::with_capacity(num);
  13. for _ in 0..num {
  14. v.push(PolyMatrixRaw::zero(params, rows, cols));
  15. }
  16. v
  17. }
  18. fn serialize_polymatrix(vec: &mut Vec<u8>, a: &PolyMatrixRaw) {
  19. for i in 0..a.rows * a.cols * a.params.poly_len {
  20. vec.extend_from_slice(&u64::to_ne_bytes(a.data[i]));
  21. }
  22. }
  23. fn serialize_vec_polymatrix(vec: &mut Vec<u8>, a: &Vec<PolyMatrixRaw>) {
  24. for i in 0..a.len() {
  25. serialize_polymatrix(vec, &a[i]);
  26. }
  27. }
  28. fn mat_sz_bytes(a: &PolyMatrixRaw) -> usize {
  29. a.rows * a.cols * a.params.poly_len * size_of::<u64>()
  30. }
  31. fn deserialize_polymatrix(a: &mut PolyMatrixRaw, data: &[u8]) -> usize {
  32. for (i, chunk) in data.chunks(size_of::<u64>()).enumerate() {
  33. a.data[i] = u64::from_ne_bytes(chunk.try_into().unwrap());
  34. }
  35. mat_sz_bytes(a)
  36. }
  37. fn deserialize_vec_polymatrix(a: &mut Vec<PolyMatrixRaw>, data: &[u8]) -> usize {
  38. let mut chunks = data.chunks(mat_sz_bytes(&a[0]));
  39. let mut bytes_read = 0;
  40. for i in 0..a.len() {
  41. bytes_read += deserialize_polymatrix(&mut a[i], chunks.next().unwrap());
  42. }
  43. bytes_read
  44. }
  45. pub struct PublicParameters<'a> {
  46. pub v_packing: Vec<PolyMatrixNTT<'a>>, // Ws
  47. pub v_expansion_left: Option<Vec<PolyMatrixNTT<'a>>>,
  48. pub v_expansion_right: Option<Vec<PolyMatrixNTT<'a>>>,
  49. pub v_conversion: Option<Vec<PolyMatrixNTT<'a>>>, // V
  50. }
  51. impl<'a> PublicParameters<'a> {
  52. pub fn init(params: &'a Params) -> Self {
  53. if params.expand_queries {
  54. PublicParameters {
  55. v_packing: Vec::new(),
  56. v_expansion_left: Some(Vec::new()),
  57. v_expansion_right: Some(Vec::new()),
  58. v_conversion: Some(Vec::new()),
  59. }
  60. } else {
  61. PublicParameters {
  62. v_packing: Vec::new(),
  63. v_expansion_left: None,
  64. v_expansion_right: None,
  65. v_conversion: None,
  66. }
  67. }
  68. }
  69. fn from_ntt_alloc_vec(v: &Vec<PolyMatrixNTT<'a>>) -> Option<Vec<PolyMatrixRaw<'a>>> {
  70. Some(v.iter().map(from_ntt_alloc).collect())
  71. }
  72. fn from_ntt_alloc_opt_vec(
  73. v: &Option<Vec<PolyMatrixNTT<'a>>>,
  74. ) -> Option<Vec<PolyMatrixRaw<'a>>> {
  75. Some(v.as_ref()?.iter().map(from_ntt_alloc).collect())
  76. }
  77. fn to_ntt_alloc_vec(v: &Vec<PolyMatrixRaw<'a>>) -> Option<Vec<PolyMatrixNTT<'a>>> {
  78. Some(v.iter().map(to_ntt_alloc).collect())
  79. }
  80. pub fn to_raw(&self) -> Vec<Option<Vec<PolyMatrixRaw>>> {
  81. vec![
  82. Self::from_ntt_alloc_vec(&self.v_packing),
  83. Self::from_ntt_alloc_opt_vec(&self.v_expansion_left),
  84. Self::from_ntt_alloc_opt_vec(&self.v_expansion_right),
  85. Self::from_ntt_alloc_opt_vec(&self.v_conversion),
  86. ]
  87. }
  88. pub fn serialize(&self) -> Vec<u8> {
  89. let mut data = Vec::new();
  90. for v in self.to_raw().iter() {
  91. if v.is_some() {
  92. serialize_vec_polymatrix(&mut data, v.as_ref().unwrap());
  93. }
  94. }
  95. data
  96. }
  97. pub fn deserialize(params: &'a Params, data: &[u8]) -> Self {
  98. assert_eq!(params.setup_bytes(), data.len());
  99. let mut idx = 0;
  100. let mut v_packing = new_vec_raw(params, params.n, params.n + 1, params.t_conv);
  101. idx += deserialize_vec_polymatrix(&mut v_packing, &data[idx..]);
  102. if params.expand_queries {
  103. let mut v_expansion_left = new_vec_raw(params, params.g(), 2, params.t_exp_left);
  104. idx += deserialize_vec_polymatrix(&mut v_expansion_left, &data[idx..]);
  105. let mut v_expansion_right =
  106. new_vec_raw(params, params.stop_round() + 1, 2, params.t_exp_right);
  107. idx += deserialize_vec_polymatrix(&mut v_expansion_right, &data[idx..]);
  108. let mut v_conversion = new_vec_raw(params, 1, 2, 2 * params.t_conv);
  109. _ = deserialize_vec_polymatrix(&mut v_conversion, &data[idx..]);
  110. Self {
  111. v_packing: Self::to_ntt_alloc_vec(&v_packing).unwrap(),
  112. v_expansion_left: Self::to_ntt_alloc_vec(&v_expansion_left),
  113. v_expansion_right: Self::to_ntt_alloc_vec(&v_expansion_right),
  114. v_conversion: Self::to_ntt_alloc_vec(&v_conversion),
  115. }
  116. } else {
  117. Self {
  118. v_packing: Self::to_ntt_alloc_vec(&v_packing).unwrap(),
  119. v_expansion_left: None,
  120. v_expansion_right: None,
  121. v_conversion: None,
  122. }
  123. }
  124. }
  125. }
  126. pub struct Query<'a> {
  127. pub ct: Option<PolyMatrixRaw<'a>>,
  128. pub v_buf: Option<Vec<u64>>,
  129. pub v_ct: Option<Vec<PolyMatrixRaw<'a>>>,
  130. }
  131. impl<'a> Query<'a> {
  132. pub fn empty() -> Self {
  133. Query {
  134. ct: None,
  135. v_ct: None,
  136. v_buf: None,
  137. }
  138. }
  139. pub fn serialize(&self) -> Vec<u8> {
  140. let mut data = Vec::new();
  141. if self.ct.is_some() {
  142. let ct = self.ct.as_ref().unwrap();
  143. serialize_polymatrix(&mut data, &ct);
  144. }
  145. if self.v_buf.is_some() {
  146. let v_buf = self.v_buf.as_ref().unwrap();
  147. data.extend(v_buf.iter().map(|x| x.to_ne_bytes()).flatten());
  148. }
  149. if self.v_ct.is_some() {
  150. let v_ct = self.v_ct.as_ref().unwrap();
  151. for x in v_ct {
  152. serialize_polymatrix(&mut data, x);
  153. }
  154. }
  155. data
  156. }
  157. pub fn deserialize(params: &'a Params, data: &[u8]) -> Self {
  158. let mut out = Query::empty();
  159. if params.expand_queries {
  160. let mut ct = PolyMatrixRaw::zero(params, 2, 1);
  161. deserialize_polymatrix(&mut ct, data);
  162. out.ct = Some(ct);
  163. } else {
  164. let v_buf_bytes = params.query_v_buf_bytes();
  165. let v_buf = (&data[..v_buf_bytes])
  166. .chunks(size_of::<u64>())
  167. .map(|x| u64::from_ne_bytes(x.try_into().unwrap()))
  168. .collect();
  169. out.v_buf = Some(v_buf);
  170. let mut v_ct = new_vec_raw(params, params.db_dim_2, 2, 2 * params.t_gsw);
  171. deserialize_vec_polymatrix(&mut v_ct, &data[v_buf_bytes..]);
  172. out.v_ct = Some(v_ct);
  173. }
  174. out
  175. }
  176. }
  177. pub struct Client<'a, TRng: Rng> {
  178. params: &'a Params,
  179. sk_gsw: PolyMatrixRaw<'a>,
  180. pub sk_reg: PolyMatrixRaw<'a>,
  181. sk_gsw_full: PolyMatrixRaw<'a>,
  182. sk_reg_full: PolyMatrixRaw<'a>,
  183. dg: DiscreteGaussian<'a, TRng>,
  184. pub g: usize,
  185. pub stop_round: usize,
  186. }
  187. fn matrix_with_identity<'a>(p: &PolyMatrixRaw<'a>) -> PolyMatrixRaw<'a> {
  188. assert_eq!(p.cols, 1);
  189. let mut r = PolyMatrixRaw::zero(p.params, p.rows, p.rows + 1);
  190. r.copy_into(p, 0, 0);
  191. r.copy_into(&PolyMatrixRaw::identity(p.params, p.rows, p.rows), 0, 1);
  192. r
  193. }
  194. fn params_with_moduli(params: &Params, moduli: &Vec<u64>) -> Params {
  195. Params::init(
  196. params.poly_len,
  197. moduli,
  198. params.noise_width,
  199. params.n,
  200. params.pt_modulus,
  201. params.q2_bits,
  202. params.t_conv,
  203. params.t_exp_left,
  204. params.t_exp_right,
  205. params.t_gsw,
  206. params.expand_queries,
  207. params.db_dim_1,
  208. params.db_dim_2,
  209. params.instances,
  210. params.db_item_size,
  211. )
  212. }
  213. impl<'a, TRng: Rng> Client<'a, TRng> {
  214. pub fn init(params: &'a Params, rng: &'a mut TRng) -> Self {
  215. let sk_gsw_dims = params.get_sk_gsw();
  216. let sk_reg_dims = params.get_sk_reg();
  217. let sk_gsw = PolyMatrixRaw::zero(params, sk_gsw_dims.0, sk_gsw_dims.1);
  218. let sk_reg = PolyMatrixRaw::zero(params, sk_reg_dims.0, sk_reg_dims.1);
  219. let sk_gsw_full = matrix_with_identity(&sk_gsw);
  220. let sk_reg_full = matrix_with_identity(&sk_reg);
  221. let dg = DiscreteGaussian::init(params, rng);
  222. let further_dims = params.db_dim_2;
  223. let num_expanded = 1usize << params.db_dim_1;
  224. let num_bits_to_gen = params.t_gsw * further_dims + num_expanded;
  225. let g = log2_ceil_usize(num_bits_to_gen);
  226. let stop_round = log2_ceil_usize(params.t_gsw * further_dims);
  227. Self {
  228. params,
  229. sk_gsw,
  230. sk_reg,
  231. sk_gsw_full,
  232. sk_reg_full,
  233. dg,
  234. g,
  235. stop_round,
  236. }
  237. }
  238. pub fn get_rng(&mut self) -> &mut TRng {
  239. &mut self.dg.rng
  240. }
  241. fn get_fresh_gsw_public_key(&mut self, m: usize) -> PolyMatrixRaw<'a> {
  242. let params = self.params;
  243. let n = params.n;
  244. let a = PolyMatrixRaw::random_rng(params, 1, m, self.get_rng());
  245. let e = PolyMatrixRaw::noise(params, n, m, &mut self.dg);
  246. let a_inv = -&a;
  247. let b_p = &self.sk_gsw.ntt() * &a.ntt();
  248. let b = &e.ntt() + &b_p;
  249. let p = stack(&a_inv, &b.raw());
  250. p
  251. }
  252. fn get_regev_sample(&mut self) -> PolyMatrixNTT<'a> {
  253. let params = self.params;
  254. let a = PolyMatrixRaw::random_rng(params, 1, 1, self.get_rng());
  255. let e = PolyMatrixRaw::noise(params, 1, 1, &mut self.dg);
  256. let b_p = &self.sk_reg.ntt() * &a.ntt();
  257. let b = &e.ntt() + &b_p;
  258. let mut p = PolyMatrixNTT::zero(params, 2, 1);
  259. p.copy_into(&(-&a).ntt(), 0, 0);
  260. p.copy_into(&b, 1, 0);
  261. p
  262. }
  263. fn get_fresh_reg_public_key(&mut self, m: usize) -> PolyMatrixNTT<'a> {
  264. let params = self.params;
  265. let mut p = PolyMatrixNTT::zero(params, 2, m);
  266. for i in 0..m {
  267. p.copy_into(&self.get_regev_sample(), 0, i);
  268. }
  269. p
  270. }
  271. fn encrypt_matrix_gsw(&mut self, ag: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  272. let mx = ag.cols;
  273. let p = self.get_fresh_gsw_public_key(mx);
  274. let res = &(p.ntt()) + &(ag.pad_top(1));
  275. res
  276. }
  277. pub fn encrypt_matrix_reg(&mut self, a: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  278. let m = a.cols;
  279. let p = self.get_fresh_reg_public_key(m);
  280. &p + &a.pad_top(1)
  281. }
  282. pub fn decrypt_matrix_reg(&mut self, a: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  283. &self.sk_reg_full.ntt() * a
  284. }
  285. pub fn decrypt_matrix_gsw(&mut self, a: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  286. &self.sk_gsw_full.ntt() * a
  287. }
  288. fn generate_expansion_params(
  289. &mut self,
  290. num_exp: usize,
  291. m_exp: usize,
  292. ) -> Vec<PolyMatrixNTT<'a>> {
  293. let params = self.params;
  294. let g_exp = build_gadget(params, 1, m_exp);
  295. let g_exp_ntt = g_exp.ntt();
  296. let mut res = Vec::new();
  297. for i in 0..num_exp {
  298. let t = (params.poly_len / (1 << i)) + 1;
  299. let tau_sk_reg = automorph_alloc(&self.sk_reg, t);
  300. let prod = &tau_sk_reg.ntt() * &g_exp_ntt;
  301. let w_exp_i = self.encrypt_matrix_reg(&prod);
  302. res.push(w_exp_i);
  303. }
  304. res
  305. }
  306. pub fn generate_keys(&mut self) -> PublicParameters<'a> {
  307. let params = self.params;
  308. self.dg.sample_matrix(&mut self.sk_gsw);
  309. self.dg.sample_matrix(&mut self.sk_reg);
  310. self.sk_gsw_full = matrix_with_identity(&self.sk_gsw);
  311. self.sk_reg_full = matrix_with_identity(&self.sk_reg);
  312. let sk_reg_ntt = to_ntt_alloc(&self.sk_reg);
  313. let mut pp = PublicParameters::init(params);
  314. // Params for packing
  315. let gadget_conv = build_gadget(params, 1, params.t_conv);
  316. let gadget_conv_ntt = to_ntt_alloc(&gadget_conv);
  317. for i in 0..params.n {
  318. let scaled = scalar_multiply_alloc(&sk_reg_ntt, &gadget_conv_ntt);
  319. let mut ag = PolyMatrixNTT::zero(params, params.n, params.t_conv);
  320. ag.copy_into(&scaled, i, 0);
  321. let w = self.encrypt_matrix_gsw(&ag);
  322. pp.v_packing.push(w);
  323. }
  324. if params.expand_queries {
  325. // Params for expansion
  326. pp.v_expansion_left = Some(self.generate_expansion_params(self.g, params.t_exp_left));
  327. pp.v_expansion_right =
  328. Some(self.generate_expansion_params(self.stop_round + 1, params.t_exp_right));
  329. // Params for converison
  330. let g_conv = build_gadget(params, 2, 2 * params.t_conv);
  331. let sk_reg_ntt = self.sk_reg.ntt();
  332. let sk_reg_squared_ntt = &sk_reg_ntt * &sk_reg_ntt;
  333. pp.v_conversion = Some(Vec::from_iter(once(PolyMatrixNTT::zero(
  334. params,
  335. 2,
  336. 2 * params.t_conv,
  337. ))));
  338. for i in 0..2 * params.t_conv {
  339. let sigma;
  340. if i % 2 == 0 {
  341. let val = g_conv.get_poly(0, i)[0];
  342. sigma = &sk_reg_squared_ntt * &single_poly(params, val).ntt();
  343. } else {
  344. let val = g_conv.get_poly(1, i)[0];
  345. sigma = &sk_reg_ntt * &single_poly(params, val).ntt();
  346. }
  347. let ct = self.encrypt_matrix_reg(&sigma);
  348. pp.v_conversion.as_mut().unwrap()[0].copy_into(&ct, 0, i);
  349. }
  350. }
  351. pp
  352. }
  353. pub fn generate_query(&mut self, idx_target: usize) -> Query<'a> {
  354. let params = self.params;
  355. let further_dims = params.db_dim_2;
  356. let idx_dim0 = idx_target / (1 << further_dims);
  357. let idx_further = idx_target % (1 << further_dims);
  358. let scale_k = params.modulus / params.pt_modulus;
  359. let bits_per = get_bits_per(params, params.t_gsw);
  360. let mut query = Query::empty();
  361. if params.expand_queries {
  362. // pack query into single ciphertext
  363. let mut sigma = PolyMatrixRaw::zero(params, 1, 1);
  364. sigma.data[2 * idx_dim0] = scale_k;
  365. for i in 0..further_dims as u64 {
  366. let bit: u64 = ((idx_further as u64) & (1 << i)) >> i;
  367. for j in 0..params.t_gsw {
  368. let val = (1u64 << (bits_per * j)) * bit;
  369. let idx = (i as usize) * params.t_gsw + (j as usize);
  370. sigma.data[2 * idx + 1] = val;
  371. }
  372. }
  373. let inv_2_g_first = invert_uint_mod(1 << self.g, params.modulus).unwrap();
  374. let inv_2_g_rest = invert_uint_mod(1 << (self.stop_round + 1), params.modulus).unwrap();
  375. for i in 0..params.poly_len / 2 {
  376. sigma.data[2 * i] =
  377. multiply_uint_mod(sigma.data[2 * i], inv_2_g_first, params.modulus);
  378. sigma.data[2 * i + 1] =
  379. multiply_uint_mod(sigma.data[2 * i + 1], inv_2_g_rest, params.modulus);
  380. }
  381. query.ct = Some(from_ntt_alloc(
  382. &self.encrypt_matrix_reg(&to_ntt_alloc(&sigma)),
  383. ));
  384. } else {
  385. let num_expanded = 1 << params.db_dim_1;
  386. let mut sigma_v = Vec::<PolyMatrixNTT>::new();
  387. // generate regev ciphertexts
  388. let reg_cts_buf_words = num_expanded * 2 * params.poly_len;
  389. let mut reg_cts_buf = vec![0u64; reg_cts_buf_words];
  390. let mut reg_cts = Vec::<PolyMatrixNTT>::new();
  391. for i in 0..num_expanded {
  392. let value = ((i == idx_dim0) as u64) * scale_k;
  393. let sigma = PolyMatrixRaw::single_value(&params, value);
  394. reg_cts.push(self.encrypt_matrix_reg(&to_ntt_alloc(&sigma)));
  395. }
  396. // reorient into server's preferred indexing
  397. reorient_reg_ciphertexts(self.params, reg_cts_buf.as_mut_slice(), &reg_cts);
  398. // generate GSW ciphertexts
  399. for i in 0..further_dims {
  400. let bit = ((idx_further as u64) & (1 << (i as u64))) >> (i as u64);
  401. let mut ct_gsw = PolyMatrixNTT::zero(&params, 2, 2 * params.t_gsw);
  402. for j in 0..params.t_gsw {
  403. let value = (1u64 << (bits_per * j)) * bit;
  404. let sigma = PolyMatrixRaw::single_value(&params, value);
  405. let sigma_ntt = to_ntt_alloc(&sigma);
  406. let ct = &self.encrypt_matrix_reg(&sigma_ntt);
  407. ct_gsw.copy_into(ct, 0, 2 * j + 1);
  408. let prod = &to_ntt_alloc(&self.sk_reg) * &sigma_ntt;
  409. let ct = &self.encrypt_matrix_reg(&prod);
  410. ct_gsw.copy_into(ct, 0, 2 * j);
  411. }
  412. sigma_v.push(ct_gsw);
  413. }
  414. query.v_buf = Some(reg_cts_buf);
  415. query.v_ct = Some(sigma_v.iter().map(|x| from_ntt_alloc(x)).collect());
  416. }
  417. query
  418. }
  419. pub fn decode_response(&self, data: &[u8]) -> Vec<u8> {
  420. /*
  421. 0. NTT over q2 the secret key
  422. 1. read first row in q2_bit chunks
  423. 2. read rest in q1_bit chunks
  424. 3. NTT over q2 the first row
  425. 4. Multiply the results of (0) and (3)
  426. 5. Divide and round correctly
  427. */
  428. let params = self.params;
  429. let p = params.pt_modulus;
  430. let p_bits = log2_ceil(params.pt_modulus);
  431. let q1 = 4 * params.pt_modulus;
  432. let q1_bits = log2_ceil(q1) as usize;
  433. let q2 = Q2_VALUES[params.q2_bits as usize];
  434. let q2_bits = params.q2_bits as usize;
  435. let q2_params = params_with_moduli(params, &vec![q2]);
  436. // this only needs to be done during keygen
  437. let mut sk_gsw_q2 = PolyMatrixRaw::zero(&q2_params, params.n, 1);
  438. for i in 0..params.poly_len * params.n {
  439. sk_gsw_q2.data[i] = recenter(self.sk_gsw.data[i], params.modulus, q2);
  440. }
  441. let mut sk_gsw_q2_ntt = PolyMatrixNTT::zero(&q2_params, params.n, 1);
  442. to_ntt(&mut sk_gsw_q2_ntt, &sk_gsw_q2);
  443. let mut result = PolyMatrixRaw::zero(&params, params.instances * params.n, params.n);
  444. let mut bit_offs = 0;
  445. for instance in 0..params.instances {
  446. // this must be done during decoding
  447. let mut first_row = PolyMatrixRaw::zero(&q2_params, 1, params.n);
  448. let mut rest_rows = PolyMatrixRaw::zero(&params, params.n, params.n);
  449. for i in 0..params.n * params.poly_len {
  450. first_row.data[i] = read_arbitrary_bits(data, bit_offs, q2_bits);
  451. bit_offs += q2_bits;
  452. }
  453. for i in 0..params.n * params.n * params.poly_len {
  454. rest_rows.data[i] = read_arbitrary_bits(data, bit_offs, q1_bits);
  455. bit_offs += q1_bits;
  456. }
  457. let mut first_row_q2 = PolyMatrixNTT::zero(&q2_params, 1, params.n);
  458. to_ntt(&mut first_row_q2, &first_row);
  459. let sk_prod = (&sk_gsw_q2_ntt * &first_row_q2).raw();
  460. let q1_i64 = q1 as i64;
  461. let q2_i64 = q2 as i64;
  462. let p_i128 = p as i128;
  463. for i in 0..params.n * params.n * params.poly_len {
  464. let mut val_first = sk_prod.data[i] as i64;
  465. if val_first >= q2_i64 / 2 {
  466. val_first -= q2_i64;
  467. }
  468. let mut val_rest = rest_rows.data[i] as i64;
  469. if val_rest >= q1_i64 / 2 {
  470. val_rest -= q1_i64;
  471. }
  472. let denom = (q2 * (q1 / p)) as i64;
  473. let mut r = val_first * q1_i64;
  474. r += val_rest * q2_i64;
  475. // divide r by q2, rounding
  476. let sign: i64 = if r >= 0 { 1 } else { -1 };
  477. let mut res = ((r + sign * (denom / 2)) as i128) / (denom as i128);
  478. res = (res + (denom as i128 / p_i128) * (p_i128) + 2 * (p_i128)) % (p_i128);
  479. let idx = instance * params.n * params.n * params.poly_len + i;
  480. result.data[idx] = res as u64;
  481. }
  482. }
  483. // println!("{:?}", result.data);
  484. let trials = params.n * params.n;
  485. let chunks = params.instances * trials;
  486. let bytes_per_chunk = f64::ceil(params.db_item_size as f64 / chunks as f64) as usize;
  487. let logp = log2(params.pt_modulus);
  488. let modp_words_per_chunk = f64::ceil((bytes_per_chunk * 8) as f64 / logp as f64) as usize;
  489. result.to_vec(p_bits as usize, modp_words_per_chunk)
  490. }
  491. }
  492. #[cfg(test)]
  493. mod test {
  494. use rand::thread_rng;
  495. use super::*;
  496. fn assert_first8(m: &[u64], gold: [u64; 8]) {
  497. let got: [u64; 8] = m[0..8].try_into().unwrap();
  498. assert_eq!(got, gold);
  499. }
  500. fn get_params() -> Params {
  501. get_short_keygen_params()
  502. }
  503. #[test]
  504. fn init_is_correct() {
  505. let params = get_params();
  506. let mut rng = thread_rng();
  507. let client = Client::init(&params, &mut rng);
  508. assert_eq!(client.stop_round, 5);
  509. assert_eq!(client.g, 10);
  510. assert_eq!(*client.params, params);
  511. }
  512. #[test]
  513. fn keygen_is_correct() {
  514. let params = get_params();
  515. let mut seeded_rng = get_static_seeded_rng();
  516. let mut client = Client::init(&params, &mut seeded_rng);
  517. let pub_params = client.generate_keys();
  518. assert_first8(
  519. pub_params.v_conversion.unwrap()[0].data.as_slice(),
  520. [
  521. 122680182, 165987256, 137892309, 95732358, 221787731, 13233184, 156136764,
  522. 259944211,
  523. ],
  524. );
  525. assert_first8(
  526. client.sk_gsw.data.as_slice(),
  527. [
  528. 66974689739603965,
  529. 66974689739603965,
  530. 0,
  531. 1,
  532. 0,
  533. 5,
  534. 66974689739603967,
  535. 2,
  536. ],
  537. );
  538. }
  539. fn public_parameters_serialization_is_correct_for_params(params: Params) {
  540. let mut seeded_rng = get_static_seeded_rng();
  541. let mut client = Client::init(&params, &mut seeded_rng);
  542. let pub_params = client.generate_keys();
  543. assert_eq!(client.stop_round, params.stop_round());
  544. let serialized1 = pub_params.serialize();
  545. let deserialized1 = PublicParameters::deserialize(&params, &serialized1);
  546. let serialized2 = deserialized1.serialize();
  547. assert_eq!(serialized1, serialized2);
  548. }
  549. #[test]
  550. fn public_parameters_serialization_is_correct() {
  551. public_parameters_serialization_is_correct_for_params(get_params())
  552. }
  553. #[test]
  554. fn no_expansion_public_parameters_serialization_is_correct() {
  555. public_parameters_serialization_is_correct_for_params(get_no_expansion_testing_params())
  556. }
  557. fn query_serialization_is_correct_for_params(params: Params) {
  558. let mut seeded_rng = get_static_seeded_rng();
  559. let mut client = Client::init(&params, &mut seeded_rng);
  560. _ = client.generate_keys();
  561. let query = client.generate_query(1);
  562. let serialized1 = query.serialize();
  563. let deserialized1 = Query::deserialize(&params, &serialized1);
  564. let serialized2 = deserialized1.serialize();
  565. assert_eq!(serialized1, serialized2);
  566. }
  567. #[test]
  568. fn query_serialization_is_correct() {
  569. query_serialization_is_correct_for_params(get_params())
  570. }
  571. #[test]
  572. fn no_expansion_query_serialization_is_correct() {
  573. query_serialization_is_correct_for_params(get_no_expansion_testing_params())
  574. }
  575. }