client.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. use crate::{poly::*, params::*, discrete_gaussian::*, gadget::*, arith::*, util::*, number_theory::*};
  2. use std::iter::once;
  3. fn serialize_polymatrix(vec: &mut Vec<u8>, a: &PolyMatrixRaw) {
  4. for i in 0..a.rows * a.cols * a.params.poly_len {
  5. vec.extend_from_slice(&u64::to_ne_bytes(a.data[i]));
  6. }
  7. }
  8. fn serialize_vec_polymatrix(vec: &mut Vec<u8>, a: &Vec<PolyMatrixRaw>) {
  9. for i in 0..a.len() {
  10. serialize_polymatrix(vec, &a[i]);
  11. }
  12. }
  13. pub struct PublicParameters<'a> {
  14. v_packing: Vec<PolyMatrixNTT<'a>>, // Ws
  15. v_expansion_left: Option<Vec<PolyMatrixNTT<'a>>>,
  16. v_expansion_right: Option<Vec<PolyMatrixNTT<'a>>>,
  17. v_conversion: Option<Vec<PolyMatrixNTT<'a>>>, // V
  18. }
  19. impl<'a> PublicParameters<'a> {
  20. pub fn init(params: &'a Params) -> Self {
  21. if params.expand_queries {
  22. PublicParameters {
  23. v_packing: Vec::new(),
  24. v_expansion_left: Some(Vec::new()),
  25. v_expansion_right: Some(Vec::new()),
  26. v_conversion: Some(Vec::new())
  27. }
  28. } else {
  29. PublicParameters {
  30. v_packing: Vec::new(),
  31. v_expansion_left: None,
  32. v_expansion_right: None,
  33. v_conversion: None,
  34. }
  35. }
  36. }
  37. fn from_ntt_alloc_vec(v: &Vec<PolyMatrixNTT<'a>>) -> Option<Vec<PolyMatrixRaw<'a>>> {
  38. Some(v.iter().map(from_ntt_alloc).collect())
  39. }
  40. fn from_ntt_alloc_opt_vec(v: &Option<Vec<PolyMatrixNTT<'a>>>) -> Option<Vec<PolyMatrixRaw<'a>>> {
  41. Some(v.as_ref()?.iter().map(from_ntt_alloc).collect())
  42. }
  43. pub fn to_raw(&self) -> Vec<Option<Vec<PolyMatrixRaw>>> {
  44. vec![
  45. Self::from_ntt_alloc_vec(&self.v_packing),
  46. Self::from_ntt_alloc_opt_vec(&self.v_expansion_left),
  47. Self::from_ntt_alloc_opt_vec(&self.v_expansion_right),
  48. Self::from_ntt_alloc_opt_vec(&self.v_conversion),
  49. ]
  50. }
  51. pub fn serialize(&self) -> Vec<u8> {
  52. let mut data = Vec::new();
  53. for v in self.to_raw().iter() {
  54. if v.is_some() {
  55. serialize_vec_polymatrix(&mut data, v.as_ref().unwrap());
  56. }
  57. }
  58. data
  59. }
  60. }
  61. pub struct Query<'a> {
  62. ct: Option<PolyMatrixRaw<'a>>,
  63. v_buf: Option<Vec<u64>>,
  64. v_ct: Option<Vec<PolyMatrixRaw<'a>>>,
  65. }
  66. impl<'a> Query<'a> {
  67. pub fn empty() -> Self {
  68. Query { ct: None, v_ct: None, v_buf: None }
  69. }
  70. pub fn serialize(&self) -> Vec<u8> {
  71. let mut data = Vec::new();
  72. if self.ct.is_some() {
  73. let ct = self.ct.as_ref().unwrap();
  74. serialize_polymatrix(&mut data, &ct);
  75. }
  76. if self.v_buf.is_some() {
  77. let v_buf = self.v_buf.as_ref().unwrap();
  78. data.extend(v_buf.iter().map(|x| { x.to_ne_bytes() }).flatten());
  79. }
  80. if self.v_ct.is_some() {
  81. let v_ct = self.v_ct.as_ref().unwrap();
  82. for x in v_ct {
  83. serialize_polymatrix(&mut data, x);
  84. }
  85. }
  86. data
  87. }
  88. }
  89. pub struct Client<'a> {
  90. params: &'a Params,
  91. sk_gsw: PolyMatrixRaw<'a>,
  92. sk_reg: PolyMatrixRaw<'a>,
  93. sk_gsw_full: PolyMatrixRaw<'a>,
  94. sk_reg_full: PolyMatrixRaw<'a>,
  95. dg: DiscreteGaussian,
  96. g: usize,
  97. stop_round: usize,
  98. }
  99. fn matrix_with_identity<'a> (p: &PolyMatrixRaw<'a>) -> PolyMatrixRaw<'a> {
  100. assert_eq!(p.cols, 1);
  101. let mut r = PolyMatrixRaw::zero(p.params, p.rows, p.rows + 1);
  102. r.copy_into(p, 0, 0);
  103. r.copy_into(&PolyMatrixRaw::identity(p.params, p.rows, p.rows), 0, 1);
  104. r
  105. }
  106. fn params_with_moduli(params: &Params, moduli: &Vec<u64>) -> Params {
  107. Params::init(
  108. params.poly_len,
  109. moduli,
  110. params.noise_width,
  111. params.n,
  112. params.pt_modulus,
  113. params.q2_bits,
  114. params.t_conv,
  115. params.t_exp_left,
  116. params.t_exp_right,
  117. params.t_gsw,
  118. params.expand_queries,
  119. params.db_dim_1,
  120. params.db_dim_2,
  121. params.instances,
  122. params.db_item_size,
  123. )
  124. }
  125. impl<'a> Client<'a> {
  126. pub fn init(params: &'a Params) -> Self {
  127. let sk_gsw_dims = params.get_sk_gsw();
  128. let sk_reg_dims = params.get_sk_reg();
  129. let sk_gsw = PolyMatrixRaw::zero(params, sk_gsw_dims.0, sk_gsw_dims.1);
  130. let sk_reg = PolyMatrixRaw::zero(params, sk_reg_dims.0, sk_reg_dims.1);
  131. let sk_gsw_full = matrix_with_identity(&sk_gsw);
  132. let sk_reg_full = matrix_with_identity(&sk_reg);
  133. let dg = DiscreteGaussian::init(params);
  134. let further_dims = params.db_dim_2;
  135. let num_expanded = 1usize << params.db_dim_1;
  136. let num_bits_to_gen = params.t_gsw * further_dims + num_expanded;
  137. let g = log2_ceil_usize(num_bits_to_gen);
  138. let stop_round = log2_ceil_usize(params.t_gsw * further_dims);
  139. Self {
  140. params,
  141. sk_gsw,
  142. sk_reg,
  143. sk_gsw_full,
  144. sk_reg_full,
  145. dg,
  146. g,
  147. stop_round,
  148. }
  149. }
  150. fn get_fresh_gsw_public_key(&mut self, m: usize) -> PolyMatrixRaw<'a> {
  151. let params = self.params;
  152. let n = params.n;
  153. let a = PolyMatrixRaw::random(params, 1, m);
  154. let e = PolyMatrixRaw::noise(params, n, m, &mut self.dg);
  155. let a_inv = -&a;
  156. let b_p = &self.sk_gsw.ntt() * &a.ntt();
  157. let b = &e.ntt() + &b_p;
  158. let p = stack(&a_inv, &b.raw());
  159. p
  160. }
  161. fn get_regev_sample(&mut self) -> PolyMatrixNTT<'a> {
  162. let params = self.params;
  163. let a = PolyMatrixRaw::random(params, 1, 1);
  164. let e = PolyMatrixRaw::noise(params, 1, 1, &mut self.dg);
  165. let b_p = &self.sk_reg.ntt() * &a.ntt();
  166. let b = &e.ntt() + &b_p;
  167. let mut p = PolyMatrixNTT::zero(params, 2, 1);
  168. p.copy_into(&(-&a).ntt(), 0, 0);
  169. p.copy_into(&b, 1, 0);
  170. p
  171. }
  172. fn get_fresh_reg_public_key(&mut self, m: usize) -> PolyMatrixNTT<'a> {
  173. let params = self.params;
  174. let mut p = PolyMatrixNTT::zero(params, 2, m);
  175. for i in 0..m {
  176. p.copy_into(&self.get_regev_sample(), 0, i);
  177. }
  178. p
  179. }
  180. fn encrypt_matrix_gsw(&mut self, ag: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  181. let mx = ag.cols;
  182. let p = self.get_fresh_gsw_public_key(mx);
  183. let res = &(p.ntt()) + &(ag.pad_top(1));
  184. res
  185. }
  186. fn encrypt_matrix_reg(&mut self, a: &PolyMatrixNTT<'a>) -> PolyMatrixNTT<'a> {
  187. let m = a.cols;
  188. let p = self.get_fresh_reg_public_key(m);
  189. &p + &a.pad_top(1)
  190. }
  191. fn generate_expansion_params(&mut self, num_exp: usize, m_exp: usize) -> Vec<PolyMatrixNTT<'a>> {
  192. let params = self.params;
  193. let g_exp = build_gadget(params, 1, m_exp);
  194. let g_exp_ntt = g_exp.ntt();
  195. let mut res = Vec::new();
  196. for i in 0..num_exp {
  197. let t = (params.poly_len / (1 << i)) + 1;
  198. let tau_sk_reg = automorph_alloc(&self.sk_reg, t);
  199. let prod = &tau_sk_reg.ntt() * &g_exp_ntt;
  200. let w_exp_i = self.encrypt_matrix_reg(&prod);
  201. res.push(w_exp_i);
  202. }
  203. res
  204. }
  205. pub fn generate_keys(&mut self) -> PublicParameters {
  206. let params = self.params;
  207. self.dg.sample_matrix(&mut self.sk_gsw);
  208. self.dg.sample_matrix(&mut self.sk_reg);
  209. self.sk_gsw_full = matrix_with_identity(&self.sk_gsw);
  210. self.sk_reg_full = matrix_with_identity(&self.sk_reg);
  211. let sk_reg_ntt = to_ntt_alloc(&self.sk_reg);
  212. let m_conv = params.m_conv();
  213. let mut pp = PublicParameters::init(params);
  214. // Params for packing
  215. let gadget_conv = build_gadget(params, 1, m_conv);
  216. let gadget_conv_ntt = to_ntt_alloc(&gadget_conv);
  217. for i in 0..params.n {
  218. let scaled = scalar_multiply_alloc(&sk_reg_ntt, &gadget_conv_ntt);
  219. let mut ag = PolyMatrixNTT::zero(params, params.n, m_conv);
  220. ag.copy_into(&scaled, i, 0);
  221. let w = self.encrypt_matrix_gsw(&ag);
  222. pp.v_packing.push(w);
  223. }
  224. if params.expand_queries {
  225. // Params for expansion
  226. pp.v_expansion_left = Some(self.generate_expansion_params(self.g, params.t_exp_left));
  227. pp.v_expansion_right = Some(self.generate_expansion_params(self.stop_round + 1, params.t_exp_right));
  228. // Params for converison
  229. let g_conv = build_gadget(params, 2, 2 * m_conv);
  230. let sk_reg_ntt = self.sk_reg.ntt();
  231. let sk_reg_squared_ntt = &sk_reg_ntt * &sk_reg_ntt;
  232. pp.v_conversion = Some(Vec::from_iter(once(PolyMatrixNTT::zero(params, 2, 2 * m_conv))));
  233. for i in 0..2*m_conv {
  234. let sigma;
  235. if i % 2 == 0 {
  236. let val = g_conv.get_poly(0, i)[0];
  237. sigma = &sk_reg_squared_ntt * &single_poly(params, val).ntt();
  238. } else {
  239. let val = g_conv.get_poly(1, i)[0];
  240. sigma = &sk_reg_ntt * &single_poly(params, val).ntt();
  241. }
  242. let ct = self.encrypt_matrix_reg(&sigma);
  243. pp.v_conversion.as_mut().unwrap()[0].copy_into(&ct, 0, i);
  244. }
  245. }
  246. pp
  247. }
  248. // reindexes a vector of regev ciphertexts, to help server
  249. fn reorient_reg_ciphertexts(&self, out: &mut [u64], v_reg: &Vec<PolyMatrixNTT>) {
  250. let params = self.params;
  251. let poly_len = params.poly_len;
  252. let crt_count = params.crt_count;
  253. assert_eq!(crt_count, 2);
  254. assert!(log2(params.moduli[0]) <= 32);
  255. let num_reg_expanded = 1<<params.db_dim_1;
  256. let ct_rows = v_reg[0].rows;
  257. let ct_cols = v_reg[0].cols;
  258. assert_eq!(ct_rows, 2);
  259. assert_eq!(ct_cols, 1);
  260. for j in 0..num_reg_expanded {
  261. for r in 0..ct_rows {
  262. for m in 0.. ct_cols {
  263. for z in 0..params.poly_len {
  264. let idx_a_in = r * (ct_cols*crt_count*poly_len) + m * (crt_count*poly_len);
  265. let idx_a_out = z * (num_reg_expanded*ct_cols*ct_rows)
  266. + j * (ct_cols*ct_rows)
  267. + m * (ct_rows)
  268. + r;
  269. let val1 = v_reg[j].data[idx_a_in + z] % params.moduli[0];
  270. let val2 = v_reg[j].data[idx_a_in + params.poly_len + z] % params.moduli[1];
  271. out[idx_a_out] = val1 | (val2 << 32);
  272. }
  273. }
  274. }
  275. }
  276. }
  277. pub fn generate_query(&mut self, idx_target: usize) -> Query<'a> {
  278. let params = self.params;
  279. let further_dims = params.db_dim_2;
  280. let idx_dim0= idx_target / (1 << further_dims);
  281. let idx_further = idx_target % (1 << further_dims);
  282. let scale_k = params.modulus / params.pt_modulus;
  283. let bits_per = get_bits_per(params, params.t_gsw);
  284. let mut query = Query::empty();
  285. if params.expand_queries {
  286. // pack query into single ciphertext
  287. let mut sigma = PolyMatrixRaw::zero(params, 1, 1);
  288. sigma.data[2*idx_dim0] = scale_k;
  289. for i in 0..further_dims as u64 {
  290. let bit: u64 = ((idx_further as u64) & (1 << i)) >> i;
  291. for j in 0..params.t_gsw {
  292. let val = (1u64 << (bits_per * j)) * bit;
  293. let idx = (i as usize) * params.t_gsw + (j as usize);
  294. sigma.data[2*idx + 1] = val;
  295. }
  296. }
  297. let inv_2_g_first = invert_uint_mod(1 << self.g, params.modulus).unwrap();
  298. let inv_2_g_rest = invert_uint_mod(1 << (self.stop_round+1), params.modulus).unwrap();
  299. for i in 0..params.poly_len/2 {
  300. sigma.data[2*i] = multiply_uint_mod(sigma.data[2*i], inv_2_g_first, params.modulus);
  301. sigma.data[2*i+1] = multiply_uint_mod(sigma.data[2*i+1], inv_2_g_rest, params.modulus);
  302. }
  303. query.ct = Some(from_ntt_alloc(&self.encrypt_matrix_reg(&to_ntt_alloc(&sigma))));
  304. } else {
  305. let num_expanded = 1 << params.db_dim_1;
  306. let mut sigma_v = Vec::<PolyMatrixNTT>::new();
  307. // generate regev ciphertexts
  308. let reg_cts_buf_words = num_expanded * 2 * params.poly_len;
  309. let mut reg_cts_buf = vec![0u64; reg_cts_buf_words];
  310. let mut reg_cts = Vec::<PolyMatrixNTT>::new();
  311. for i in 0..num_expanded {
  312. let value = ((i == idx_dim0) as u64) * scale_k;
  313. let sigma = PolyMatrixRaw::single_value(&params, value);
  314. reg_cts.push(self.encrypt_matrix_reg(&to_ntt_alloc(&sigma)));
  315. }
  316. // reorient into server's preferred indexing
  317. self.reorient_reg_ciphertexts(reg_cts_buf.as_mut_slice(), &reg_cts);
  318. // generate GSW ciphertexts
  319. for i in 0..further_dims {
  320. let bit = ((idx_further as u64) & (1 << (i as u64))) >> (i as u64);
  321. let mut ct_gsw = PolyMatrixNTT::zero(&params, 2, 2 * params.t_gsw);
  322. for j in 0..params.t_gsw {
  323. let value = (1u64 << (bits_per * j)) * bit;
  324. let sigma = PolyMatrixRaw::single_value(&params, value);
  325. let sigma_ntt = to_ntt_alloc(&sigma);
  326. let ct = &self.encrypt_matrix_reg(&sigma_ntt);
  327. ct_gsw.copy_into(ct, 0, 2*j + 1);
  328. let prod = &to_ntt_alloc(&self.sk_reg) * &sigma_ntt;
  329. let ct = &self.encrypt_matrix_reg(&prod);
  330. ct_gsw.copy_into(ct, 0, 2*j);
  331. }
  332. sigma_v.push(ct_gsw);
  333. }
  334. query.v_buf = Some(reg_cts_buf);
  335. query.v_ct = Some(sigma_v.iter().map(|x| { from_ntt_alloc(x) }).collect());
  336. }
  337. query
  338. }
  339. pub fn decode_response(&self, data: &[u8]) -> Vec<u8> {
  340. /*
  341. 0. NTT over q2 the secret key
  342. 1. read first row in q2_bit chunks
  343. 2. read rest in q1_bit chunks
  344. 3. NTT over q2 the first row
  345. 4. Multiply the results of (0) and (3)
  346. 5. Divide and round correctly
  347. */
  348. let params = self.params;
  349. let p = params.pt_modulus;
  350. let p_bits = log2_ceil(params.pt_modulus);
  351. let q1 = 4 * params.pt_modulus;
  352. let q1_bits = log2_ceil(q1) as usize;
  353. let q2 = Q2_VALUES[params.q2_bits as usize];
  354. let q2_bits = params.q2_bits as usize;
  355. let q2_params = params_with_moduli(params, &vec![q2]);
  356. // this only needs to be done during keygen
  357. let mut sk_gsw_q2 = PolyMatrixRaw::zero(&q2_params, params.n, 1);
  358. for i in 0..params.poly_len * params.n {
  359. sk_gsw_q2.data[i] = recenter(self.sk_gsw.data[i], params.modulus, q2);
  360. }
  361. let mut sk_gsw_q2_ntt = PolyMatrixNTT::zero(&q2_params, params.n, 1);
  362. to_ntt(&mut sk_gsw_q2_ntt, &sk_gsw_q2);
  363. let mut result = PolyMatrixRaw::zero(&params, params.instances * params.n, params.n);
  364. let mut bit_offs = 0;
  365. for instance in 0..params.instances {
  366. // this must be done during decoding
  367. let mut first_row = PolyMatrixRaw::zero(&q2_params, 1, params.n);
  368. let mut rest_rows = PolyMatrixRaw::zero(&params, params.n, params.n);
  369. for i in 0..params.n * params.poly_len {
  370. first_row.data[i] = read_arbitrary_bits(data, bit_offs, q2_bits);
  371. bit_offs += q2_bits;
  372. }
  373. for i in 0..params.n * params.n * params.poly_len {
  374. rest_rows.data[i] = read_arbitrary_bits(data, bit_offs, q1_bits);
  375. bit_offs += q1_bits;
  376. }
  377. let mut first_row_q2 = PolyMatrixNTT::zero(&q2_params, 1, params.n);
  378. to_ntt(&mut first_row_q2, &first_row);
  379. let sk_prod = (&sk_gsw_q2_ntt * &first_row_q2).raw();
  380. let q1_i64 = q1 as i64;
  381. let q2_i64 = q2 as i64;
  382. let p_i128 = p as i128;
  383. for i in 0..params.n * params.n * params.poly_len {
  384. let mut val_first = sk_prod.data[i] as i64;
  385. if val_first >= q2_i64/2 {
  386. val_first -= q2_i64;
  387. }
  388. let mut val_rest = rest_rows.data[i] as i64;
  389. if val_rest >= q1_i64/2 {
  390. val_rest -= q1_i64;
  391. }
  392. let denom = (q2 * (q1 / p)) as i64;
  393. let mut r = val_first * q1_i64;
  394. r += val_rest * q2_i64;
  395. // divide r by q2, rounding
  396. let sign: i64 = if r >= 0 { 1 } else { -1 };
  397. let mut res = ((r + sign*(denom/2)) as i128) / (denom as i128);
  398. res = (res + (denom as i128/p_i128)*(p_i128) + 2*(p_i128)) % (p_i128);
  399. let idx = instance * params.n * params.n * params.poly_len + i;
  400. result.data[idx] = res as u64;
  401. }
  402. }
  403. // println!("{:?}", result.data);
  404. let trials = params.n * params.n;
  405. let chunks = params.instances * trials;
  406. let bytes_per_chunk = f64::ceil(params.db_item_size as f64 / chunks as f64) as usize;
  407. let logp = log2(params.pt_modulus);
  408. let modp_words_per_chunk = f64::ceil((bytes_per_chunk * 8) as f64 / logp as f64) as usize;
  409. result.to_vec(p_bits as usize, modp_words_per_chunk)
  410. }
  411. }