client.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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. assert_eq!(params.query_bytes(), data.len());
  159. let mut out = Query::empty();
  160. if params.expand_queries {
  161. let mut ct = PolyMatrixRaw::zero(params, 2, 1);
  162. deserialize_polymatrix(&mut ct, data);
  163. out.ct = Some(ct);
  164. } else {
  165. let v_buf_bytes = params.query_v_buf_bytes();
  166. let v_buf = (&data[..v_buf_bytes])
  167. .chunks(size_of::<u64>())
  168. .map(|x| u64::from_ne_bytes(x.try_into().unwrap()))
  169. .collect();
  170. out.v_buf = Some(v_buf);
  171. let mut v_ct = new_vec_raw(params, params.db_dim_2, 2, 2 * params.t_gsw);
  172. deserialize_vec_polymatrix(&mut v_ct, &data[v_buf_bytes..]);
  173. out.v_ct = Some(v_ct);
  174. }
  175. out
  176. }
  177. }
  178. pub struct Client<'a, TRng: Rng> {
  179. params: &'a Params,
  180. sk_gsw: PolyMatrixRaw<'a>,
  181. pub sk_reg: PolyMatrixRaw<'a>,
  182. sk_gsw_full: PolyMatrixRaw<'a>,
  183. sk_reg_full: PolyMatrixRaw<'a>,
  184. dg: DiscreteGaussian<'a, TRng>,
  185. pub g: usize,
  186. pub stop_round: usize,
  187. }
  188. fn matrix_with_identity<'a>(p: &PolyMatrixRaw<'a>) -> PolyMatrixRaw<'a> {
  189. assert_eq!(p.cols, 1);
  190. let mut r = PolyMatrixRaw::zero(p.params, p.rows, p.rows + 1);
  191. r.copy_into(p, 0, 0);
  192. r.copy_into(&PolyMatrixRaw::identity(p.params, p.rows, p.rows), 0, 1);
  193. r
  194. }
  195. fn params_with_moduli(params: &Params, moduli: &Vec<u64>) -> Params {
  196. Params::init(
  197. params.poly_len,
  198. moduli,
  199. params.noise_width,
  200. params.n,
  201. params.pt_modulus,
  202. params.q2_bits,
  203. params.t_conv,
  204. params.t_exp_left,
  205. params.t_exp_right,
  206. params.t_gsw,
  207. params.expand_queries,
  208. params.db_dim_1,
  209. params.db_dim_2,
  210. params.instances,
  211. params.db_item_size,
  212. )
  213. }
  214. impl<'a, TRng: Rng> Client<'a, TRng> {
  215. pub fn init(params: &'a Params, rng: &'a mut TRng) -> Self {
  216. let sk_gsw_dims = params.get_sk_gsw();
  217. let sk_reg_dims = params.get_sk_reg();
  218. let sk_gsw = PolyMatrixRaw::zero(params, sk_gsw_dims.0, sk_gsw_dims.1);
  219. let sk_reg = PolyMatrixRaw::zero(params, sk_reg_dims.0, sk_reg_dims.1);
  220. let sk_gsw_full = matrix_with_identity(&sk_gsw);
  221. let sk_reg_full = matrix_with_identity(&sk_reg);
  222. let dg = DiscreteGaussian::init(params, rng);
  223. let further_dims = params.db_dim_2;
  224. let num_expanded = 1usize << params.db_dim_1;
  225. let num_bits_to_gen = params.t_gsw * further_dims + num_expanded;
  226. let g = log2_ceil_usize(num_bits_to_gen);
  227. let stop_round = log2_ceil_usize(params.t_gsw * further_dims);
  228. Self {
  229. params,
  230. sk_gsw,
  231. sk_reg,
  232. sk_gsw_full,
  233. sk_reg_full,
  234. dg,
  235. g,
  236. stop_round,
  237. }
  238. }
  239. pub fn get_rng(&mut self) -> &mut TRng {
  240. &mut self.dg.rng
  241. }
  242. fn get_fresh_gsw_public_key(&mut self, m: usize) -> PolyMatrixRaw<'a> {
  243. let params = self.params;
  244. let n = params.n;
  245. let a = PolyMatrixRaw::random_rng(params, 1, m, self.get_rng());
  246. let e = PolyMatrixRaw::noise(params, n, m, &mut self.dg);
  247. let a_inv = -&a;
  248. let b_p = &self.sk_gsw.ntt() * &a.ntt();
  249. let b = &e.ntt() + &b_p;
  250. let p = stack(&a_inv, &b.raw());
  251. p
  252. }
  253. fn get_regev_sample(&mut self) -> PolyMatrixNTT<'a> {
  254. let params = self.params;
  255. let a = PolyMatrixRaw::random_rng(params, 1, 1, self.get_rng());
  256. let e = PolyMatrixRaw::noise(params, 1, 1, &mut self.dg);
  257. let b_p = &self.sk_reg.ntt() * &a.ntt();
  258. let b = &e.ntt() + &b_p;
  259. let mut p = PolyMatrixNTT::zero(params, 2, 1);
  260. p.copy_into(&(-&a).ntt(), 0, 0);
  261. p.copy_into(&b, 1, 0);
  262. p
  263. }
  264. fn get_fresh_reg_public_key(&mut self, m: usize) -> PolyMatrixNTT<'a> {
  265. let params = self.params;
  266. let mut p = PolyMatrixNTT::zero(params, 2, m);
  267. for i in 0..m {
  268. p.copy_into(&self.get_regev_sample(), 0, i);
  269. }
  270. p
  271. }
  272. fn encrypt_matrix_gsw(&mut self, ag: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  273. let mx = ag.cols;
  274. let p = self.get_fresh_gsw_public_key(mx);
  275. let res = &(p.ntt()) + &(ag.pad_top(1));
  276. res
  277. }
  278. pub fn encrypt_matrix_reg(&mut self, a: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  279. let m = a.cols;
  280. let p = self.get_fresh_reg_public_key(m);
  281. &p + &a.pad_top(1)
  282. }
  283. pub fn decrypt_matrix_reg(&mut self, a: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  284. &self.sk_reg_full.ntt() * a
  285. }
  286. pub fn decrypt_matrix_gsw(&mut self, a: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  287. &self.sk_gsw_full.ntt() * a
  288. }
  289. fn generate_expansion_params(
  290. &mut self,
  291. num_exp: usize,
  292. m_exp: usize,
  293. ) -> Vec<PolyMatrixNTT<'a>> {
  294. let params = self.params;
  295. let g_exp = build_gadget(params, 1, m_exp);
  296. let g_exp_ntt = g_exp.ntt();
  297. let mut res = Vec::new();
  298. for i in 0..num_exp {
  299. let t = (params.poly_len / (1 << i)) + 1;
  300. let tau_sk_reg = automorph_alloc(&self.sk_reg, t);
  301. let prod = &tau_sk_reg.ntt() * &g_exp_ntt;
  302. let w_exp_i = self.encrypt_matrix_reg(&prod);
  303. res.push(w_exp_i);
  304. }
  305. res
  306. }
  307. pub fn generate_keys(&mut self) -> PublicParameters<'a> {
  308. let params = self.params;
  309. self.dg.sample_matrix(&mut self.sk_gsw);
  310. self.dg.sample_matrix(&mut self.sk_reg);
  311. self.sk_gsw_full = matrix_with_identity(&self.sk_gsw);
  312. self.sk_reg_full = matrix_with_identity(&self.sk_reg);
  313. let sk_reg_ntt = to_ntt_alloc(&self.sk_reg);
  314. let mut pp = PublicParameters::init(params);
  315. // Params for packing
  316. let gadget_conv = build_gadget(params, 1, params.t_conv);
  317. let gadget_conv_ntt = to_ntt_alloc(&gadget_conv);
  318. for i in 0..params.n {
  319. let scaled = scalar_multiply_alloc(&sk_reg_ntt, &gadget_conv_ntt);
  320. let mut ag = PolyMatrixNTT::zero(params, params.n, params.t_conv);
  321. ag.copy_into(&scaled, i, 0);
  322. let w = self.encrypt_matrix_gsw(&ag);
  323. pp.v_packing.push(w);
  324. }
  325. if params.expand_queries {
  326. // Params for expansion
  327. pp.v_expansion_left = Some(self.generate_expansion_params(self.g, params.t_exp_left));
  328. pp.v_expansion_right =
  329. Some(self.generate_expansion_params(self.stop_round + 1, params.t_exp_right));
  330. // Params for converison
  331. let g_conv = build_gadget(params, 2, 2 * params.t_conv);
  332. let sk_reg_ntt = self.sk_reg.ntt();
  333. let sk_reg_squared_ntt = &sk_reg_ntt * &sk_reg_ntt;
  334. pp.v_conversion = Some(Vec::from_iter(once(PolyMatrixNTT::zero(
  335. params,
  336. 2,
  337. 2 * params.t_conv,
  338. ))));
  339. for i in 0..2 * params.t_conv {
  340. let sigma;
  341. if i % 2 == 0 {
  342. let val = g_conv.get_poly(0, i)[0];
  343. sigma = &sk_reg_squared_ntt * &single_poly(params, val).ntt();
  344. } else {
  345. let val = g_conv.get_poly(1, i)[0];
  346. sigma = &sk_reg_ntt * &single_poly(params, val).ntt();
  347. }
  348. let ct = self.encrypt_matrix_reg(&sigma);
  349. pp.v_conversion.as_mut().unwrap()[0].copy_into(&ct, 0, i);
  350. }
  351. }
  352. pp
  353. }
  354. pub fn generate_query(&mut self, idx_target: usize) -> Query<'a> {
  355. let params = self.params;
  356. let further_dims = params.db_dim_2;
  357. let idx_dim0 = idx_target / (1 << further_dims);
  358. let idx_further = idx_target % (1 << further_dims);
  359. let scale_k = params.modulus / params.pt_modulus;
  360. let bits_per = get_bits_per(params, params.t_gsw);
  361. let mut query = Query::empty();
  362. if params.expand_queries {
  363. // pack query into single ciphertext
  364. let mut sigma = PolyMatrixRaw::zero(params, 1, 1);
  365. sigma.data[2 * idx_dim0] = scale_k;
  366. for i in 0..further_dims as u64 {
  367. let bit: u64 = ((idx_further as u64) & (1 << i)) >> i;
  368. for j in 0..params.t_gsw {
  369. let val = (1u64 << (bits_per * j)) * bit;
  370. let idx = (i as usize) * params.t_gsw + (j as usize);
  371. sigma.data[2 * idx + 1] = val;
  372. }
  373. }
  374. let inv_2_g_first = invert_uint_mod(1 << self.g, params.modulus).unwrap();
  375. let inv_2_g_rest = invert_uint_mod(1 << (self.stop_round + 1), params.modulus).unwrap();
  376. for i in 0..params.poly_len / 2 {
  377. sigma.data[2 * i] =
  378. multiply_uint_mod(sigma.data[2 * i], inv_2_g_first, params.modulus);
  379. sigma.data[2 * i + 1] =
  380. multiply_uint_mod(sigma.data[2 * i + 1], inv_2_g_rest, params.modulus);
  381. }
  382. query.ct = Some(from_ntt_alloc(
  383. &self.encrypt_matrix_reg(&to_ntt_alloc(&sigma)),
  384. ));
  385. } else {
  386. let num_expanded = 1 << params.db_dim_1;
  387. let mut sigma_v = Vec::<PolyMatrixNTT>::new();
  388. // generate regev ciphertexts
  389. let reg_cts_buf_words = num_expanded * 2 * params.poly_len;
  390. let mut reg_cts_buf = vec![0u64; reg_cts_buf_words];
  391. let mut reg_cts = Vec::<PolyMatrixNTT>::new();
  392. for i in 0..num_expanded {
  393. let value = ((i == idx_dim0) as u64) * scale_k;
  394. let sigma = PolyMatrixRaw::single_value(&params, value);
  395. reg_cts.push(self.encrypt_matrix_reg(&to_ntt_alloc(&sigma)));
  396. }
  397. // reorient into server's preferred indexing
  398. reorient_reg_ciphertexts(self.params, reg_cts_buf.as_mut_slice(), &reg_cts);
  399. // generate GSW ciphertexts
  400. for i in 0..further_dims {
  401. let bit = ((idx_further as u64) & (1 << (i as u64))) >> (i as u64);
  402. let mut ct_gsw = PolyMatrixNTT::zero(&params, 2, 2 * params.t_gsw);
  403. for j in 0..params.t_gsw {
  404. let value = (1u64 << (bits_per * j)) * bit;
  405. let sigma = PolyMatrixRaw::single_value(&params, value);
  406. let sigma_ntt = to_ntt_alloc(&sigma);
  407. let ct = &self.encrypt_matrix_reg(&sigma_ntt);
  408. ct_gsw.copy_into(ct, 0, 2 * j + 1);
  409. let prod = &to_ntt_alloc(&self.sk_reg) * &sigma_ntt;
  410. let ct = &self.encrypt_matrix_reg(&prod);
  411. ct_gsw.copy_into(ct, 0, 2 * j);
  412. }
  413. sigma_v.push(ct_gsw);
  414. }
  415. query.v_buf = Some(reg_cts_buf);
  416. query.v_ct = Some(sigma_v.iter().map(|x| from_ntt_alloc(x)).collect());
  417. }
  418. query
  419. }
  420. pub fn decode_response(&self, data: &[u8]) -> Vec<u8> {
  421. /*
  422. 0. NTT over q2 the secret key
  423. 1. read first row in q2_bit chunks
  424. 2. read rest in q1_bit chunks
  425. 3. NTT over q2 the first row
  426. 4. Multiply the results of (0) and (3)
  427. 5. Divide and round correctly
  428. */
  429. let params = self.params;
  430. let p = params.pt_modulus;
  431. let p_bits = log2_ceil(params.pt_modulus);
  432. let q1 = 4 * params.pt_modulus;
  433. let q1_bits = log2_ceil(q1) as usize;
  434. let q2 = Q2_VALUES[params.q2_bits as usize];
  435. let q2_bits = params.q2_bits as usize;
  436. let q2_params = params_with_moduli(params, &vec![q2]);
  437. // this only needs to be done during keygen
  438. let mut sk_gsw_q2 = PolyMatrixRaw::zero(&q2_params, params.n, 1);
  439. for i in 0..params.poly_len * params.n {
  440. sk_gsw_q2.data[i] = recenter(self.sk_gsw.data[i], params.modulus, q2);
  441. }
  442. let mut sk_gsw_q2_ntt = PolyMatrixNTT::zero(&q2_params, params.n, 1);
  443. to_ntt(&mut sk_gsw_q2_ntt, &sk_gsw_q2);
  444. let mut result = PolyMatrixRaw::zero(&params, params.instances * params.n, params.n);
  445. let mut bit_offs = 0;
  446. for instance in 0..params.instances {
  447. // this must be done during decoding
  448. let mut first_row = PolyMatrixRaw::zero(&q2_params, 1, params.n);
  449. let mut rest_rows = PolyMatrixRaw::zero(&params, params.n, params.n);
  450. for i in 0..params.n * params.poly_len {
  451. first_row.data[i] = read_arbitrary_bits(data, bit_offs, q2_bits);
  452. bit_offs += q2_bits;
  453. }
  454. for i in 0..params.n * params.n * params.poly_len {
  455. rest_rows.data[i] = read_arbitrary_bits(data, bit_offs, q1_bits);
  456. bit_offs += q1_bits;
  457. }
  458. let mut first_row_q2 = PolyMatrixNTT::zero(&q2_params, 1, params.n);
  459. to_ntt(&mut first_row_q2, &first_row);
  460. let sk_prod = (&sk_gsw_q2_ntt * &first_row_q2).raw();
  461. let q1_i64 = q1 as i64;
  462. let q2_i64 = q2 as i64;
  463. let p_i128 = p as i128;
  464. for i in 0..params.n * params.n * params.poly_len {
  465. let mut val_first = sk_prod.data[i] as i64;
  466. if val_first >= q2_i64 / 2 {
  467. val_first -= q2_i64;
  468. }
  469. let mut val_rest = rest_rows.data[i] as i64;
  470. if val_rest >= q1_i64 / 2 {
  471. val_rest -= q1_i64;
  472. }
  473. let denom = (q2 * (q1 / p)) as i64;
  474. let mut r = val_first * q1_i64;
  475. r += val_rest * q2_i64;
  476. // divide r by q2, rounding
  477. let sign: i64 = if r >= 0 { 1 } else { -1 };
  478. let mut res = ((r + sign * (denom / 2)) as i128) / (denom as i128);
  479. res = (res + (denom as i128 / p_i128) * (p_i128) + 2 * (p_i128)) % (p_i128);
  480. let idx = instance * params.n * params.n * params.poly_len + i;
  481. result.data[idx] = res as u64;
  482. }
  483. }
  484. // println!("{:?}", result.data.as_slice().to_vec());
  485. result.to_vec(p_bits as usize, params.modp_words_per_chunk())
  486. }
  487. }
  488. #[cfg(test)]
  489. mod test {
  490. use rand::thread_rng;
  491. use super::*;
  492. fn assert_first8(m: &[u64], gold: [u64; 8]) {
  493. let got: [u64; 8] = m[0..8].try_into().unwrap();
  494. assert_eq!(got, gold);
  495. }
  496. fn get_params() -> Params {
  497. get_short_keygen_params()
  498. }
  499. #[test]
  500. fn init_is_correct() {
  501. let params = get_params();
  502. let mut rng = thread_rng();
  503. let client = Client::init(&params, &mut rng);
  504. assert_eq!(client.stop_round, 5);
  505. assert_eq!(client.stop_round, params.stop_round());
  506. assert_eq!(client.g, 10);
  507. assert_eq!(client.g, params.g());
  508. assert_eq!(*client.params, params);
  509. }
  510. #[test]
  511. fn keygen_is_correct() {
  512. let params = get_params();
  513. let mut seeded_rng = get_static_seeded_rng();
  514. let mut client = Client::init(&params, &mut seeded_rng);
  515. let pub_params = client.generate_keys();
  516. assert_first8(
  517. pub_params.v_conversion.unwrap()[0].data.as_slice(),
  518. [
  519. 122680182, 165987256, 137892309, 95732358, 221787731, 13233184, 156136764,
  520. 259944211,
  521. ],
  522. );
  523. assert_first8(
  524. client.sk_gsw.data.as_slice(),
  525. [
  526. 66974689739603965,
  527. 66974689739603965,
  528. 0,
  529. 1,
  530. 0,
  531. 5,
  532. 66974689739603967,
  533. 2,
  534. ],
  535. );
  536. }
  537. fn get_vec(v: &Vec<PolyMatrixNTT>) -> Vec<u64> {
  538. v.iter().map(|d| d.as_slice().to_vec()).flatten().collect()
  539. }
  540. fn public_parameters_serialization_is_correct_for_params(params: Params) {
  541. let mut seeded_rng = get_static_seeded_rng();
  542. let mut client = Client::init(&params, &mut seeded_rng);
  543. let pub_params = client.generate_keys();
  544. assert_eq!(client.stop_round, params.stop_round());
  545. let serialized1 = pub_params.serialize();
  546. let deserialized1 = PublicParameters::deserialize(&params, &serialized1);
  547. let serialized2 = deserialized1.serialize();
  548. assert_eq!(serialized1, serialized2);
  549. assert_eq!(
  550. get_vec(&pub_params.v_packing),
  551. get_vec(&deserialized1.v_packing)
  552. );
  553. assert_eq!(
  554. get_vec(&pub_params.v_conversion.unwrap()),
  555. get_vec(&deserialized1.v_conversion.unwrap())
  556. );
  557. assert_eq!(
  558. get_vec(&pub_params.v_expansion_left.unwrap()),
  559. get_vec(&deserialized1.v_expansion_left.unwrap())
  560. );
  561. assert_eq!(
  562. get_vec(&pub_params.v_expansion_right.unwrap()),
  563. get_vec(&deserialized1.v_expansion_right.unwrap())
  564. );
  565. }
  566. #[test]
  567. fn public_parameters_serialization_is_correct() {
  568. public_parameters_serialization_is_correct_for_params(get_params())
  569. }
  570. #[test]
  571. fn real_public_parameters_serialization_is_correct() {
  572. let cfg_expand = r#"
  573. {'n': 2,
  574. 'nu_1': 10,
  575. 'nu_2': 6,
  576. 'p': 512,
  577. 'q2_bits': 21,
  578. 's_e': 85.83255142749422,
  579. 't_gsw': 10,
  580. 't_conv': 4,
  581. 't_exp_left': 16,
  582. 't_exp_right': 56,
  583. 'instances': 11,
  584. 'db_item_size': 100000 }
  585. "#;
  586. let cfg = cfg_expand.replace("'", "\"");
  587. let params = params_from_json(&cfg);
  588. public_parameters_serialization_is_correct_for_params(params)
  589. }
  590. #[test]
  591. fn no_expansion_public_parameters_serialization_is_correct() {
  592. public_parameters_serialization_is_correct_for_params(get_no_expansion_testing_params())
  593. }
  594. fn query_serialization_is_correct_for_params(params: Params) {
  595. let mut seeded_rng = get_static_seeded_rng();
  596. let mut client = Client::init(&params, &mut seeded_rng);
  597. _ = client.generate_keys();
  598. let query = client.generate_query(1);
  599. let serialized1 = query.serialize();
  600. let deserialized1 = Query::deserialize(&params, &serialized1);
  601. let serialized2 = deserialized1.serialize();
  602. assert_eq!(serialized1, serialized2);
  603. }
  604. #[test]
  605. fn query_serialization_is_correct() {
  606. query_serialization_is_correct_for_params(get_params())
  607. }
  608. #[test]
  609. fn no_expansion_query_serialization_is_correct() {
  610. query_serialization_is_correct_for_params(get_no_expansion_testing_params())
  611. }
  612. }