server.rs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. #[cfg(target_feature = "avx2")]
  2. use std::arch::x86_64::*;
  3. use std::fs::File;
  4. use std::io::BufReader;
  5. use std::io::Read;
  6. use std::io::Seek;
  7. use std::io::SeekFrom;
  8. use crate::aligned_memory::*;
  9. use crate::arith::*;
  10. use crate::client::PublicParameters;
  11. use crate::client::Query;
  12. use crate::gadget::*;
  13. use crate::params::*;
  14. use crate::poly::*;
  15. use crate::util::*;
  16. pub fn coefficient_expansion(
  17. v: &mut Vec<PolyMatrixNTT>,
  18. g: usize,
  19. stop_round: usize,
  20. params: &Params,
  21. v_w_left: &Vec<PolyMatrixNTT>,
  22. v_w_right: &Vec<PolyMatrixNTT>,
  23. v_neg1: &Vec<PolyMatrixNTT>,
  24. max_bits_to_gen_right: usize,
  25. ) {
  26. let poly_len = params.poly_len;
  27. let mut ct = PolyMatrixRaw::zero(params, 2, 1);
  28. let mut ct_auto = PolyMatrixRaw::zero(params, 2, 1);
  29. let mut ct_auto_1 = PolyMatrixRaw::zero(params, 1, 1);
  30. let mut ct_auto_1_ntt = PolyMatrixNTT::zero(params, 1, 1);
  31. let mut ginv_ct_left = PolyMatrixRaw::zero(params, params.t_exp_left, 1);
  32. let mut ginv_ct_left_ntt = PolyMatrixNTT::zero(params, params.t_exp_left, 1);
  33. let mut ginv_ct_right = PolyMatrixRaw::zero(params, params.t_exp_right, 1);
  34. let mut ginv_ct_right_ntt = PolyMatrixNTT::zero(params, params.t_exp_right, 1);
  35. let mut w_times_ginv_ct = PolyMatrixNTT::zero(params, 2, 1);
  36. for r in 0..g {
  37. let num_in = 1 << r;
  38. let num_out = 2 * num_in;
  39. let t = (poly_len / (1 << r)) + 1;
  40. let neg1 = &v_neg1[r];
  41. for i in 0..num_out {
  42. if stop_round > 0 && i % 2 == 1 && r > stop_round
  43. || (r == stop_round && i / 2 >= max_bits_to_gen_right)
  44. {
  45. continue;
  46. }
  47. let (w, _gadget_dim, gi_ct, gi_ct_ntt) = match i % 2 {
  48. 0 => (
  49. &v_w_left[r],
  50. params.t_exp_left,
  51. &mut ginv_ct_left,
  52. &mut ginv_ct_left_ntt,
  53. ),
  54. 1 | _ => (
  55. &v_w_right[r],
  56. params.t_exp_right,
  57. &mut ginv_ct_right,
  58. &mut ginv_ct_right_ntt,
  59. ),
  60. };
  61. if i < num_in {
  62. let (src, dest) = v.split_at_mut(num_in);
  63. scalar_multiply(&mut dest[i], neg1, &src[i]);
  64. }
  65. from_ntt(&mut ct, &v[i]);
  66. automorph(&mut ct_auto, &ct, t);
  67. gadget_invert_rdim(gi_ct, &ct_auto, 1);
  68. to_ntt_no_reduce(gi_ct_ntt, &gi_ct);
  69. ct_auto_1
  70. .data
  71. .as_mut_slice()
  72. .copy_from_slice(ct_auto.get_poly(1, 0));
  73. to_ntt(&mut ct_auto_1_ntt, &ct_auto_1);
  74. multiply(&mut w_times_ginv_ct, w, &gi_ct_ntt);
  75. let mut idx = 0;
  76. for j in 0..2 {
  77. for n in 0..params.crt_count {
  78. for z in 0..poly_len {
  79. let sum = v[i].data[idx]
  80. + w_times_ginv_ct.data[idx]
  81. + j * ct_auto_1_ntt.data[n * poly_len + z];
  82. v[i].data[idx] = barrett_coeff_u64(params, sum, n);
  83. idx += 1;
  84. }
  85. }
  86. }
  87. }
  88. }
  89. }
  90. pub fn regev_to_gsw<'a>(
  91. v_gsw: &mut Vec<PolyMatrixNTT<'a>>,
  92. v_inp: &Vec<PolyMatrixNTT<'a>>,
  93. v: &PolyMatrixNTT<'a>,
  94. params: &'a Params,
  95. idx_factor: usize,
  96. idx_offset: usize,
  97. ) {
  98. assert!(v.rows == 2);
  99. assert!(v.cols == 2 * params.t_conv);
  100. let mut ginv_c_inp = PolyMatrixRaw::zero(params, 2 * params.t_conv, 1);
  101. let mut ginv_c_inp_ntt = PolyMatrixNTT::zero(params, 2 * params.t_conv, 1);
  102. let mut tmp_ct_raw = PolyMatrixRaw::zero(params, 2, 1);
  103. let mut tmp_ct = PolyMatrixNTT::zero(params, 2, 1);
  104. for i in 0..params.db_dim_2 {
  105. let ct = &mut v_gsw[i];
  106. for j in 0..params.t_gsw {
  107. let idx_ct = i * params.t_gsw + j;
  108. let idx_inp = idx_factor * (idx_ct) + idx_offset;
  109. ct.copy_into(&v_inp[idx_inp], 0, 2 * j + 1);
  110. from_ntt(&mut tmp_ct_raw, &v_inp[idx_inp]);
  111. gadget_invert(&mut ginv_c_inp, &tmp_ct_raw);
  112. to_ntt(&mut ginv_c_inp_ntt, &ginv_c_inp);
  113. multiply(&mut tmp_ct, v, &ginv_c_inp_ntt);
  114. ct.copy_into(&tmp_ct, 0, 2 * j);
  115. }
  116. }
  117. }
  118. pub const MAX_SUMMED: usize = 1 << 6;
  119. pub const PACKED_OFFSET_2: i32 = 32;
  120. #[cfg(target_feature = "avx2")]
  121. pub fn multiply_reg_by_database(
  122. out: &mut Vec<PolyMatrixNTT>,
  123. db: &[u64],
  124. v_firstdim: &[u64],
  125. params: &Params,
  126. dim0: usize,
  127. num_per: usize,
  128. ) {
  129. let ct_rows = 2;
  130. let ct_cols = 1;
  131. let pt_rows = 1;
  132. let pt_cols = 1;
  133. assert!(dim0 * ct_rows >= MAX_SUMMED);
  134. let mut sums_out_n0_u64 = AlignedMemory64::new(4);
  135. let mut sums_out_n2_u64 = AlignedMemory64::new(4);
  136. for z in 0..params.poly_len {
  137. let idx_a_base = z * (ct_cols * dim0 * ct_rows);
  138. let mut idx_b_base = z * (num_per * pt_cols * dim0 * pt_rows);
  139. for i in 0..num_per {
  140. for c in 0..pt_cols {
  141. let inner_limit = MAX_SUMMED;
  142. let outer_limit = dim0 * ct_rows / inner_limit;
  143. let mut sums_out_n0_u64_acc = [0u64, 0, 0, 0];
  144. let mut sums_out_n2_u64_acc = [0u64, 0, 0, 0];
  145. for o_jm in 0..outer_limit {
  146. unsafe {
  147. let mut sums_out_n0 = _mm256_setzero_si256();
  148. let mut sums_out_n2 = _mm256_setzero_si256();
  149. for i_jm in 0..inner_limit / 4 {
  150. let jm = o_jm * inner_limit + (4 * i_jm);
  151. let b_inp_1 = *db.get_unchecked(idx_b_base) as i64;
  152. idx_b_base += 1;
  153. let b_inp_2 = *db.get_unchecked(idx_b_base) as i64;
  154. idx_b_base += 1;
  155. let b = _mm256_set_epi64x(b_inp_2, b_inp_2, b_inp_1, b_inp_1);
  156. let v_a = v_firstdim.get_unchecked(idx_a_base + jm) as *const u64;
  157. let a = _mm256_load_si256(v_a as *const __m256i);
  158. let a_lo = a;
  159. let a_hi_hi = _mm256_srli_epi64(a, PACKED_OFFSET_2);
  160. let b_lo = b;
  161. let b_hi_hi = _mm256_srli_epi64(b, PACKED_OFFSET_2);
  162. sums_out_n0 =
  163. _mm256_add_epi64(sums_out_n0, _mm256_mul_epu32(a_lo, b_lo));
  164. sums_out_n2 =
  165. _mm256_add_epi64(sums_out_n2, _mm256_mul_epu32(a_hi_hi, b_hi_hi));
  166. }
  167. // reduce here, otherwise we will overflow
  168. _mm256_store_si256(
  169. sums_out_n0_u64.as_mut_ptr() as *mut __m256i,
  170. sums_out_n0,
  171. );
  172. _mm256_store_si256(
  173. sums_out_n2_u64.as_mut_ptr() as *mut __m256i,
  174. sums_out_n2,
  175. );
  176. for idx in 0..4 {
  177. let val = sums_out_n0_u64[idx];
  178. sums_out_n0_u64_acc[idx] =
  179. barrett_coeff_u64(params, val + sums_out_n0_u64_acc[idx], 0);
  180. }
  181. for idx in 0..4 {
  182. let val = sums_out_n2_u64[idx];
  183. sums_out_n2_u64_acc[idx] =
  184. barrett_coeff_u64(params, val + sums_out_n2_u64_acc[idx], 1);
  185. }
  186. }
  187. }
  188. for idx in 0..4 {
  189. sums_out_n0_u64_acc[idx] =
  190. barrett_coeff_u64(params, sums_out_n0_u64_acc[idx], 0);
  191. sums_out_n2_u64_acc[idx] =
  192. barrett_coeff_u64(params, sums_out_n2_u64_acc[idx], 1);
  193. }
  194. // output n0
  195. let (crt_count, poly_len) = (params.crt_count, params.poly_len);
  196. let mut n = 0;
  197. let mut idx_c = c * (crt_count * poly_len) + n * (poly_len) + z;
  198. out[i].data[idx_c] =
  199. barrett_coeff_u64(params, sums_out_n0_u64_acc[0] + sums_out_n0_u64_acc[2], 0);
  200. idx_c += pt_cols * crt_count * poly_len;
  201. out[i].data[idx_c] =
  202. barrett_coeff_u64(params, sums_out_n0_u64_acc[1] + sums_out_n0_u64_acc[3], 0);
  203. // output n1
  204. n = 1;
  205. idx_c = c * (crt_count * poly_len) + n * (poly_len) + z;
  206. out[i].data[idx_c] =
  207. barrett_coeff_u64(params, sums_out_n2_u64_acc[0] + sums_out_n2_u64_acc[2], 1);
  208. idx_c += pt_cols * crt_count * poly_len;
  209. out[i].data[idx_c] =
  210. barrett_coeff_u64(params, sums_out_n2_u64_acc[1] + sums_out_n2_u64_acc[3], 1);
  211. }
  212. }
  213. }
  214. }
  215. #[cfg(not(target_feature = "avx2"))]
  216. pub fn multiply_reg_by_database(
  217. out: &mut Vec<PolyMatrixNTT>,
  218. db: &[u64],
  219. v_firstdim: &[u64],
  220. params: &Params,
  221. dim0: usize,
  222. num_per: usize,
  223. ) {
  224. let ct_rows = 2;
  225. let ct_cols = 1;
  226. let pt_rows = 1;
  227. let pt_cols = 1;
  228. for z in 0..params.poly_len {
  229. let idx_a_base = z * (ct_cols * dim0 * ct_rows);
  230. let mut idx_b_base = z * (num_per * pt_cols * dim0 * pt_rows);
  231. for i in 0..num_per {
  232. for c in 0..pt_cols {
  233. let mut sums_out_n0_0 = 0u128;
  234. let mut sums_out_n0_1 = 0u128;
  235. let mut sums_out_n1_0 = 0u128;
  236. let mut sums_out_n1_1 = 0u128;
  237. for jm in 0..(dim0 * pt_rows) {
  238. let b = db[idx_b_base];
  239. idx_b_base += 1;
  240. let v_a0 = v_firstdim[idx_a_base + jm * ct_rows];
  241. let v_a1 = v_firstdim[idx_a_base + jm * ct_rows + 1];
  242. let b_lo = b as u32;
  243. let b_hi = (b >> 32) as u32;
  244. let v_a0_lo = v_a0 as u32;
  245. let v_a0_hi = (v_a0 >> 32) as u32;
  246. let v_a1_lo = v_a1 as u32;
  247. let v_a1_hi = (v_a1 >> 32) as u32;
  248. // do n0
  249. sums_out_n0_0 += ((v_a0_lo as u64) * (b_lo as u64)) as u128;
  250. sums_out_n0_1 += ((v_a1_lo as u64) * (b_lo as u64)) as u128;
  251. // do n1
  252. sums_out_n1_0 += ((v_a0_hi as u64) * (b_hi as u64)) as u128;
  253. sums_out_n1_1 += ((v_a1_hi as u64) * (b_hi as u64)) as u128;
  254. }
  255. // output n0
  256. let (crt_count, poly_len) = (params.crt_count, params.poly_len);
  257. let mut n = 0;
  258. let mut idx_c = c * (crt_count * poly_len) + n * (poly_len) + z;
  259. out[i].data[idx_c] = (sums_out_n0_0 % (params.moduli[0] as u128)) as u64;
  260. idx_c += pt_cols * crt_count * poly_len;
  261. out[i].data[idx_c] = (sums_out_n0_1 % (params.moduli[0] as u128)) as u64;
  262. // output n1
  263. n = 1;
  264. idx_c = c * (crt_count * poly_len) + n * (poly_len) + z;
  265. out[i].data[idx_c] = (sums_out_n1_0 % (params.moduli[1] as u128)) as u64;
  266. idx_c += pt_cols * crt_count * poly_len;
  267. out[i].data[idx_c] = (sums_out_n1_1 % (params.moduli[1] as u128)) as u64;
  268. }
  269. }
  270. }
  271. }
  272. pub fn generate_random_db_and_get_item<'a>(
  273. params: &'a Params,
  274. item_idx: usize,
  275. ) -> (PolyMatrixRaw<'a>, AlignedMemory64) {
  276. let mut rng = get_seeded_rng();
  277. let instances = params.instances;
  278. let trials = params.n * params.n;
  279. let dim0 = 1 << params.db_dim_1;
  280. let num_per = 1 << params.db_dim_2;
  281. let num_items = dim0 * num_per;
  282. let db_size_words = instances * trials * num_items * params.poly_len;
  283. let mut v = AlignedMemory64::new(db_size_words);
  284. let mut item = PolyMatrixRaw::zero(params, params.n, params.n);
  285. for instance in 0..instances {
  286. println!("Instance {:?}", instance);
  287. for trial in 0..trials {
  288. println!("Trial {:?}", trial);
  289. for i in 0..num_items {
  290. let ii = i % num_per;
  291. let j = i / num_per;
  292. let mut db_item = PolyMatrixRaw::random_rng(params, 1, 1, &mut rng);
  293. db_item.reduce_mod(params.pt_modulus);
  294. if i == item_idx && instance == 0 {
  295. item.copy_into(&db_item, trial / params.n, trial % params.n);
  296. }
  297. for z in 0..params.poly_len {
  298. db_item.data[z] =
  299. recenter_mod(db_item.data[z], params.pt_modulus, params.modulus);
  300. }
  301. let db_item_ntt = db_item.ntt();
  302. for z in 0..params.poly_len {
  303. let idx_dst = calc_index(
  304. &[instance, trial, z, ii, j],
  305. &[instances, trials, params.poly_len, num_per, dim0],
  306. );
  307. v[idx_dst] = db_item_ntt.data[z]
  308. | (db_item_ntt.data[params.poly_len + z] << PACKED_OFFSET_2);
  309. }
  310. }
  311. }
  312. }
  313. (item, v)
  314. }
  315. pub fn load_item_from_file<'a>(
  316. params: &'a Params,
  317. file: &mut File,
  318. instance: usize,
  319. trial: usize,
  320. item_idx: usize,
  321. ) -> PolyMatrixRaw<'a> {
  322. let db_item_size = params.db_item_size;
  323. let instances = params.instances;
  324. let trials = params.n * params.n;
  325. let chunks = instances * trials;
  326. let bytes_per_chunk = f64::ceil(db_item_size as f64 / chunks as f64) as usize;
  327. let logp = f64::ceil(f64::log2(params.pt_modulus as f64)) as usize;
  328. let modp_words_per_chunk = f64::ceil((bytes_per_chunk * 8) as f64 / logp as f64) as usize;
  329. assert!(modp_words_per_chunk <= params.poly_len);
  330. let idx_item_in_file = item_idx * db_item_size;
  331. let idx_chunk = instance * trials + trial;
  332. let idx_poly_in_file = idx_item_in_file + idx_chunk * bytes_per_chunk;
  333. let mut out = PolyMatrixRaw::zero(params, 1, 1);
  334. let seek_result = file.seek(SeekFrom::Start(idx_poly_in_file as u64));
  335. if seek_result.is_err() {
  336. return out;
  337. }
  338. let mut data = vec![0u8; 2 * bytes_per_chunk];
  339. let bytes_read = file
  340. .read(&mut data.as_mut_slice()[0..bytes_per_chunk])
  341. .unwrap();
  342. let modp_words_read = f64::ceil((bytes_read * 8) as f64 / logp as f64) as usize;
  343. assert!(modp_words_read <= params.poly_len);
  344. for i in 0..modp_words_read {
  345. out.data[i] = read_arbitrary_bits(&data, i * logp, logp);
  346. assert!(out.data[i] <= params.pt_modulus);
  347. }
  348. out
  349. }
  350. pub fn load_db_from_file(params: &Params, file: &mut File) -> AlignedMemory64 {
  351. let instances = params.instances;
  352. let trials = params.n * params.n;
  353. let dim0 = 1 << params.db_dim_1;
  354. let num_per = 1 << params.db_dim_2;
  355. let num_items = dim0 * num_per;
  356. let db_size_words = instances * trials * num_items * params.poly_len;
  357. let mut v = AlignedMemory64::new(db_size_words);
  358. for instance in 0..instances {
  359. println!("Instance {:?}", instance);
  360. for trial in 0..trials {
  361. println!("Trial {:?}", trial);
  362. for i in 0..num_items {
  363. if i % 8192 == 0 {
  364. println!("item {:?}", i);
  365. }
  366. let ii = i % num_per;
  367. let j = i / num_per;
  368. let mut db_item = load_item_from_file(params, file, instance, trial, i);
  369. // db_item.reduce_mod(params.pt_modulus);
  370. for z in 0..params.poly_len {
  371. db_item.data[z] =
  372. recenter_mod(db_item.data[z], params.pt_modulus, params.modulus);
  373. }
  374. let db_item_ntt = db_item.ntt();
  375. for z in 0..params.poly_len {
  376. let idx_dst = calc_index(
  377. &[instance, trial, z, ii, j],
  378. &[instances, trials, params.poly_len, num_per, dim0],
  379. );
  380. v[idx_dst] = db_item_ntt.data[z]
  381. | (db_item_ntt.data[params.poly_len + z] << PACKED_OFFSET_2);
  382. }
  383. }
  384. }
  385. }
  386. v
  387. }
  388. pub fn load_preprocessed_db_from_file(params: &Params, file: &mut File) -> AlignedMemory64 {
  389. let instances = params.instances;
  390. let trials = params.n * params.n;
  391. let dim0 = 1 << params.db_dim_1;
  392. let num_per = 1 << params.db_dim_2;
  393. let num_items = dim0 * num_per;
  394. let db_size_words = instances * trials * num_items * params.poly_len;
  395. let mut v = AlignedMemory64::new(db_size_words);
  396. let v_mut_slice = v.as_mut_slice();
  397. let mut reader = BufReader::with_capacity(1 << 18, file);
  398. let mut buf = [0u8; 8];
  399. for i in 0..db_size_words {
  400. if i % 1000000000 == 0 {
  401. println!("{} GB loaded", i / 1000000000);
  402. }
  403. reader.read(&mut buf).unwrap();
  404. v_mut_slice[i] = u64::from_ne_bytes(buf);
  405. }
  406. v
  407. }
  408. pub fn fold_ciphertexts(
  409. params: &Params,
  410. v_cts: &mut Vec<PolyMatrixRaw>,
  411. v_folding: &Vec<PolyMatrixNTT>,
  412. v_folding_neg: &Vec<PolyMatrixNTT>,
  413. ) {
  414. let further_dims = log2(v_cts.len() as u64) as usize;
  415. let ell = v_folding[0].cols / 2;
  416. let mut ginv_c = PolyMatrixRaw::zero(&params, 2 * ell, 1);
  417. let mut ginv_c_ntt = PolyMatrixNTT::zero(&params, 2 * ell, 1);
  418. let mut prod = PolyMatrixNTT::zero(&params, 2, 1);
  419. let mut sum = PolyMatrixNTT::zero(&params, 2, 1);
  420. let mut num_per = v_cts.len();
  421. for cur_dim in 0..further_dims {
  422. num_per = num_per / 2;
  423. for i in 0..num_per {
  424. gadget_invert(&mut ginv_c, &v_cts[i]);
  425. to_ntt(&mut ginv_c_ntt, &ginv_c);
  426. multiply(
  427. &mut prod,
  428. &v_folding_neg[further_dims - 1 - cur_dim],
  429. &ginv_c_ntt,
  430. );
  431. gadget_invert(&mut ginv_c, &v_cts[num_per + i]);
  432. to_ntt(&mut ginv_c_ntt, &ginv_c);
  433. multiply(
  434. &mut sum,
  435. &v_folding[further_dims - 1 - cur_dim],
  436. &ginv_c_ntt,
  437. );
  438. add_into(&mut sum, &prod);
  439. from_ntt(&mut v_cts[i], &sum);
  440. }
  441. }
  442. }
  443. pub fn pack<'a>(
  444. params: &'a Params,
  445. v_ct: &Vec<PolyMatrixRaw>,
  446. v_w: &Vec<PolyMatrixNTT>,
  447. ) -> PolyMatrixNTT<'a> {
  448. assert!(v_ct.len() >= params.n * params.n);
  449. assert!(v_w.len() == params.n);
  450. assert!(v_ct[0].rows == 2);
  451. assert!(v_ct[0].cols == 1);
  452. assert!(v_w[0].rows == (params.n + 1));
  453. assert!(v_w[0].cols == params.t_conv);
  454. let mut result = PolyMatrixNTT::zero(params, params.n + 1, params.n);
  455. let mut ginv = PolyMatrixRaw::zero(params, params.t_conv, 1);
  456. let mut ginv_nttd = PolyMatrixNTT::zero(params, params.t_conv, 1);
  457. let mut prod = PolyMatrixNTT::zero(params, params.n + 1, 1);
  458. let mut ct_1 = PolyMatrixRaw::zero(params, 1, 1);
  459. let mut ct_2 = PolyMatrixRaw::zero(params, 1, 1);
  460. let mut ct_2_ntt = PolyMatrixNTT::zero(params, 1, 1);
  461. for c in 0..params.n {
  462. let mut v_int = PolyMatrixNTT::zero(&params, params.n + 1, 1);
  463. for r in 0..params.n {
  464. let w = &v_w[r];
  465. let ct = &v_ct[r * params.n + c];
  466. ct_1.get_poly_mut(0, 0).copy_from_slice(ct.get_poly(0, 0));
  467. ct_2.get_poly_mut(0, 0).copy_from_slice(ct.get_poly(1, 0));
  468. to_ntt(&mut ct_2_ntt, &ct_2);
  469. gadget_invert(&mut ginv, &ct_1);
  470. to_ntt(&mut ginv_nttd, &ginv);
  471. multiply(&mut prod, &w, &ginv_nttd);
  472. add_into_at(&mut v_int, &ct_2_ntt, 1 + r, 0);
  473. add_into(&mut v_int, &prod);
  474. }
  475. result.copy_into(&v_int, 0, c);
  476. }
  477. result
  478. }
  479. pub fn encode(params: &Params, v_packed_ct: &Vec<PolyMatrixRaw>) -> Vec<u8> {
  480. let q1 = 4 * params.pt_modulus;
  481. let q1_bits = log2_ceil(q1) as usize;
  482. let q2 = Q2_VALUES[params.q2_bits as usize];
  483. let q2_bits = params.q2_bits as usize;
  484. let num_bits = params.instances
  485. * ((q2_bits * params.n * params.poly_len)
  486. + (q1_bits * params.n * params.n * params.poly_len));
  487. let round_to = 64;
  488. let num_bytes_rounded_up = ((num_bits + round_to - 1) / round_to) * round_to / 8;
  489. let mut result = vec![0u8; num_bytes_rounded_up];
  490. let mut bit_offs = 0;
  491. for instance in 0..params.instances {
  492. let packed_ct = &v_packed_ct[instance];
  493. let mut first_row = packed_ct.submatrix(0, 0, 1, packed_ct.cols);
  494. let mut rest_rows = packed_ct.submatrix(1, 0, packed_ct.rows - 1, packed_ct.cols);
  495. first_row.apply_func(|x| rescale(x, params.modulus, q2));
  496. rest_rows.apply_func(|x| rescale(x, params.modulus, q1));
  497. let data = result.as_mut_slice();
  498. for i in 0..params.n * params.poly_len {
  499. write_arbitrary_bits(data, first_row.data[i], bit_offs, q2_bits);
  500. bit_offs += q2_bits;
  501. }
  502. for i in 0..params.n * params.n * params.poly_len {
  503. write_arbitrary_bits(data, rest_rows.data[i], bit_offs, q1_bits);
  504. bit_offs += q1_bits;
  505. }
  506. }
  507. result
  508. }
  509. pub fn get_v_folding_neg<'a>(
  510. params: &'a Params,
  511. v_folding: &Vec<PolyMatrixNTT>,
  512. ) -> Vec<PolyMatrixNTT<'a>> {
  513. let gadget_ntt = build_gadget(&params, 2, 2 * params.t_gsw).ntt(); // TODO: make this better
  514. let mut v_folding_neg = Vec::new();
  515. let mut ct_gsw_inv = PolyMatrixRaw::zero(&params, 2, 2 * params.t_gsw);
  516. for i in 0..params.db_dim_2 {
  517. invert(&mut ct_gsw_inv, &v_folding[i].raw());
  518. let mut ct_gsw_neg = PolyMatrixNTT::zero(&params, 2, 2 * params.t_gsw);
  519. add(&mut ct_gsw_neg, &gadget_ntt, &ct_gsw_inv.ntt());
  520. v_folding_neg.push(ct_gsw_neg);
  521. }
  522. v_folding_neg
  523. }
  524. pub fn expand_query<'a>(
  525. params: &'a Params,
  526. public_params: &PublicParameters<'a>,
  527. query: &Query<'a>,
  528. ) -> (AlignedMemory64, Vec<PolyMatrixNTT<'a>>) {
  529. let dim0 = 1 << params.db_dim_1;
  530. let further_dims = params.db_dim_2;
  531. let mut v_reg_reoriented;
  532. let mut v_folding;
  533. let num_bits_to_gen = params.t_gsw * further_dims + dim0;
  534. let g = log2_ceil_usize(num_bits_to_gen);
  535. let right_expanded = params.t_gsw * further_dims;
  536. let stop_round = log2_ceil_usize(right_expanded);
  537. let mut v = Vec::new();
  538. for _ in 0..(1 << g) {
  539. v.push(PolyMatrixNTT::zero(params, 2, 1));
  540. }
  541. v[0].copy_into(&query.ct.as_ref().unwrap().ntt(), 0, 0);
  542. let v_conversion = &public_params.v_conversion.as_ref().unwrap()[0];
  543. let v_w_left = public_params.v_expansion_left.as_ref().unwrap();
  544. let v_w_right = public_params.v_expansion_right.as_ref().unwrap();
  545. let v_neg1 = params.get_v_neg1();
  546. coefficient_expansion(
  547. &mut v,
  548. g,
  549. stop_round,
  550. params,
  551. &v_w_left,
  552. &v_w_right,
  553. &v_neg1,
  554. params.t_gsw * params.db_dim_2,
  555. );
  556. let mut v_reg_inp = Vec::with_capacity(dim0);
  557. for i in 0..dim0 {
  558. v_reg_inp.push(v[2 * i].clone());
  559. }
  560. let mut v_gsw_inp = Vec::with_capacity(right_expanded);
  561. for i in 0..right_expanded {
  562. v_gsw_inp.push(v[2 * i + 1].clone());
  563. }
  564. let v_reg_sz = dim0 * 2 * params.poly_len;
  565. v_reg_reoriented = AlignedMemory64::new(v_reg_sz);
  566. reorient_reg_ciphertexts(params, v_reg_reoriented.as_mut_slice(), &v_reg_inp);
  567. v_folding = Vec::new();
  568. for _ in 0..params.db_dim_2 {
  569. v_folding.push(PolyMatrixNTT::zero(params, 2, 2 * params.t_gsw));
  570. }
  571. regev_to_gsw(&mut v_folding, &v_gsw_inp, &v_conversion, params, 1, 0);
  572. (v_reg_reoriented, v_folding)
  573. }
  574. pub fn process_query(
  575. params: &Params,
  576. public_params: &PublicParameters,
  577. query: &Query,
  578. db: &[u64],
  579. ) -> Vec<u8> {
  580. let dim0 = 1 << params.db_dim_1;
  581. let num_per = 1 << params.db_dim_2;
  582. let db_slice_sz = dim0 * num_per * params.poly_len;
  583. let v_packing = public_params.v_packing.as_ref();
  584. let mut v_reg_reoriented;
  585. let v_folding;
  586. if params.expand_queries {
  587. (v_reg_reoriented, v_folding) = expand_query(params, public_params, query);
  588. } else {
  589. v_reg_reoriented = AlignedMemory64::new(query.v_buf.as_ref().unwrap().len());
  590. v_reg_reoriented
  591. .as_mut_slice()
  592. .copy_from_slice(query.v_buf.as_ref().unwrap());
  593. v_folding = query
  594. .v_ct
  595. .as_ref()
  596. .unwrap()
  597. .clone()
  598. .iter()
  599. .map(|x| x.ntt())
  600. .collect();
  601. }
  602. let v_folding_neg = get_v_folding_neg(params, &v_folding);
  603. let mut intermediate = Vec::with_capacity(num_per);
  604. let mut intermediate_raw = Vec::with_capacity(num_per);
  605. for _ in 0..num_per {
  606. intermediate.push(PolyMatrixNTT::zero(params, 2, 1));
  607. intermediate_raw.push(PolyMatrixRaw::zero(params, 2, 1));
  608. }
  609. let mut v_packed_ct = Vec::new();
  610. for instance in 0..params.instances {
  611. let mut v_ct = Vec::new();
  612. for trial in 0..(params.n * params.n) {
  613. let idx = (instance * (params.n * params.n) + trial) * db_slice_sz;
  614. let cur_db = &db[idx..(idx + db_slice_sz)];
  615. multiply_reg_by_database(
  616. &mut intermediate,
  617. cur_db,
  618. v_reg_reoriented.as_slice(),
  619. params,
  620. dim0,
  621. num_per,
  622. );
  623. for i in 0..intermediate.len() {
  624. from_ntt(&mut intermediate_raw[i], &intermediate[i]);
  625. }
  626. fold_ciphertexts(params, &mut intermediate_raw, &v_folding, &v_folding_neg);
  627. v_ct.push(intermediate_raw[0].clone());
  628. }
  629. let packed_ct = pack(params, &v_ct, &v_packing);
  630. v_packed_ct.push(packed_ct.raw());
  631. }
  632. encode(params, &v_packed_ct)
  633. }
  634. #[cfg(test)]
  635. mod test {
  636. use super::*;
  637. use crate::client::*;
  638. use rand::{prelude::SmallRng, Rng};
  639. const TEST_PREPROCESSED_DB_PATH: &'static str = "/home/samir/wiki/enwiki-20220320.dbp";
  640. fn get_params() -> Params {
  641. get_fast_expansion_testing_params()
  642. }
  643. fn dec_reg<'a>(
  644. params: &'a Params,
  645. ct: &PolyMatrixNTT<'a>,
  646. client: &mut Client<'a, SmallRng>,
  647. scale_k: u64,
  648. ) -> u64 {
  649. let dec = client.decrypt_matrix_reg(ct).raw();
  650. let mut val = dec.data[0] as i64;
  651. if val >= (params.modulus / 2) as i64 {
  652. val -= params.modulus as i64;
  653. }
  654. let val_rounded = f64::round(val as f64 / scale_k as f64) as i64;
  655. if val_rounded == 0 {
  656. 0
  657. } else {
  658. 1
  659. }
  660. }
  661. fn dec_gsw<'a>(
  662. params: &'a Params,
  663. ct: &PolyMatrixNTT<'a>,
  664. client: &mut Client<'a, SmallRng>,
  665. ) -> u64 {
  666. let dec = client.decrypt_matrix_reg(ct).raw();
  667. let idx = 2 * (params.t_gsw - 1) * params.poly_len + params.poly_len; // this offset should encode a large value
  668. let mut val = dec.data[idx] as i64;
  669. if val >= (params.modulus / 2) as i64 {
  670. val -= params.modulus as i64;
  671. }
  672. if i64::abs(val) < (1i64 << 10) {
  673. 0
  674. } else {
  675. 1
  676. }
  677. }
  678. #[test]
  679. fn coefficient_expansion_is_correct() {
  680. let params = get_params();
  681. let v_neg1 = params.get_v_neg1();
  682. let mut seeded_rng = get_seeded_rng();
  683. let mut client = Client::init(&params, &mut seeded_rng);
  684. let public_params = client.generate_keys();
  685. let mut v = Vec::new();
  686. for _ in 0..(1 << (params.db_dim_1 + 1)) {
  687. v.push(PolyMatrixNTT::zero(&params, 2, 1));
  688. }
  689. let target = 7;
  690. let scale_k = params.modulus / params.pt_modulus;
  691. let mut sigma = PolyMatrixRaw::zero(&params, 1, 1);
  692. sigma.data[target] = scale_k;
  693. v[0] = client.encrypt_matrix_reg(&sigma.ntt());
  694. let test_ct = client.encrypt_matrix_reg(&sigma.ntt());
  695. let v_w_left = public_params.v_expansion_left.unwrap();
  696. let v_w_right = public_params.v_expansion_right.unwrap();
  697. coefficient_expansion(
  698. &mut v,
  699. client.g,
  700. client.stop_round,
  701. &params,
  702. &v_w_left,
  703. &v_w_right,
  704. &v_neg1,
  705. params.t_gsw * params.db_dim_2,
  706. );
  707. assert_eq!(dec_reg(&params, &test_ct, &mut client, scale_k), 0);
  708. for i in 0..v.len() {
  709. if i == target {
  710. assert_eq!(dec_reg(&params, &v[i], &mut client, scale_k), 1);
  711. } else {
  712. assert_eq!(dec_reg(&params, &v[i], &mut client, scale_k), 0);
  713. }
  714. }
  715. }
  716. #[test]
  717. fn regev_to_gsw_is_correct() {
  718. let mut params = get_params();
  719. params.db_dim_2 = 1;
  720. let mut seeded_rng = get_seeded_rng();
  721. let mut client = Client::init(&params, &mut seeded_rng);
  722. let public_params = client.generate_keys();
  723. let mut enc_constant = |val| {
  724. let mut sigma = PolyMatrixRaw::zero(&params, 1, 1);
  725. sigma.data[0] = val;
  726. client.encrypt_matrix_reg(&sigma.ntt())
  727. };
  728. let v = &public_params.v_conversion.unwrap()[0];
  729. let bits_per = get_bits_per(&params, params.t_gsw);
  730. let mut v_inp_1 = Vec::new();
  731. let mut v_inp_0 = Vec::new();
  732. for i in 0..params.t_gsw {
  733. let val = 1u64 << (bits_per * i);
  734. v_inp_1.push(enc_constant(val));
  735. v_inp_0.push(enc_constant(0));
  736. }
  737. let mut v_gsw = Vec::new();
  738. v_gsw.push(PolyMatrixNTT::zero(&params, 2, 2 * params.t_gsw));
  739. regev_to_gsw(&mut v_gsw, &v_inp_1, v, &params, 1, 0);
  740. assert_eq!(dec_gsw(&params, &v_gsw[0], &mut client), 1);
  741. regev_to_gsw(&mut v_gsw, &v_inp_0, v, &params, 1, 0);
  742. assert_eq!(dec_gsw(&params, &v_gsw[0], &mut client), 0);
  743. }
  744. #[test]
  745. fn multiply_reg_by_database_is_correct() {
  746. let params = get_params();
  747. let mut seeded_rng = get_seeded_rng();
  748. let dim0 = 1 << params.db_dim_1;
  749. let num_per = 1 << params.db_dim_2;
  750. let scale_k = params.modulus / params.pt_modulus;
  751. let target_idx = seeded_rng.gen::<usize>() % (dim0 * num_per);
  752. let target_idx_dim0 = target_idx / num_per;
  753. let target_idx_num_per = target_idx % num_per;
  754. let mut client = Client::init(&params, &mut seeded_rng);
  755. _ = client.generate_keys();
  756. let (corr_item, db) = generate_random_db_and_get_item(&params, target_idx);
  757. let mut v_reg = Vec::new();
  758. for i in 0..dim0 {
  759. let val = if i == target_idx_dim0 { scale_k } else { 0 };
  760. let sigma = PolyMatrixRaw::single_value(&params, val).ntt();
  761. v_reg.push(client.encrypt_matrix_reg(&sigma));
  762. }
  763. let v_reg_sz = dim0 * 2 * params.poly_len;
  764. let mut v_reg_reoriented = AlignedMemory64::new(v_reg_sz);
  765. reorient_reg_ciphertexts(&params, v_reg_reoriented.as_mut_slice(), &v_reg);
  766. let mut out = Vec::with_capacity(num_per);
  767. for _ in 0..dim0 {
  768. out.push(PolyMatrixNTT::zero(&params, 2, 1));
  769. }
  770. multiply_reg_by_database(
  771. &mut out,
  772. db.as_slice(),
  773. v_reg_reoriented.as_slice(),
  774. &params,
  775. dim0,
  776. num_per,
  777. );
  778. // decrypt
  779. let dec = client.decrypt_matrix_reg(&out[target_idx_num_per]).raw();
  780. let mut dec_rescaled = PolyMatrixRaw::zero(&params, 1, 1);
  781. for z in 0..params.poly_len {
  782. dec_rescaled.data[z] = rescale(dec.data[z], params.modulus, params.pt_modulus);
  783. }
  784. for z in 0..params.poly_len {
  785. // println!("{:?} {:?}", dec_rescaled.data[z], corr_item.data[z]);
  786. assert_eq!(dec_rescaled.data[z], corr_item.data[z]);
  787. }
  788. }
  789. #[test]
  790. fn fold_ciphertexts_is_correct() {
  791. let params = get_params();
  792. let mut seeded_rng = get_seeded_rng();
  793. let dim0 = 1 << params.db_dim_1;
  794. let num_per = 1 << params.db_dim_2;
  795. let scale_k = params.modulus / params.pt_modulus;
  796. let target_idx = seeded_rng.gen::<usize>() % (dim0 * num_per);
  797. let target_idx_num_per = target_idx % num_per;
  798. let mut client = Client::init(&params, &mut seeded_rng);
  799. _ = client.generate_keys();
  800. let mut v_reg = Vec::new();
  801. for i in 0..num_per {
  802. let val = if i == target_idx_num_per { scale_k } else { 0 };
  803. let sigma = PolyMatrixRaw::single_value(&params, val).ntt();
  804. v_reg.push(client.encrypt_matrix_reg(&sigma));
  805. }
  806. let mut v_reg_raw = Vec::new();
  807. for i in 0..num_per {
  808. v_reg_raw.push(v_reg[i].raw());
  809. }
  810. let bits_per = get_bits_per(&params, params.t_gsw);
  811. let mut v_folding = Vec::new();
  812. for i in 0..params.db_dim_2 {
  813. let bit = ((target_idx_num_per as u64) & (1 << (i as u64))) >> (i as u64);
  814. let mut ct_gsw = PolyMatrixNTT::zero(&params, 2, 2 * params.t_gsw);
  815. for j in 0..params.t_gsw {
  816. let value = (1u64 << (bits_per * j)) * bit;
  817. let sigma = PolyMatrixRaw::single_value(&params, value);
  818. let sigma_ntt = to_ntt_alloc(&sigma);
  819. let ct = client.encrypt_matrix_reg(&sigma_ntt);
  820. ct_gsw.copy_into(&ct, 0, 2 * j + 1);
  821. let prod = &to_ntt_alloc(&client.sk_reg) * &sigma_ntt;
  822. let ct = &client.encrypt_matrix_reg(&prod);
  823. ct_gsw.copy_into(&ct, 0, 2 * j);
  824. }
  825. v_folding.push(ct_gsw);
  826. }
  827. let gadget_ntt = build_gadget(&params, 2, 2 * params.t_gsw).ntt();
  828. let mut v_folding_neg = Vec::new();
  829. let mut ct_gsw_inv = PolyMatrixRaw::zero(&params, 2, 2 * params.t_gsw);
  830. for i in 0..params.db_dim_2 {
  831. invert(&mut ct_gsw_inv, &v_folding[i].raw());
  832. let mut ct_gsw_neg = PolyMatrixNTT::zero(&params, 2, 2 * params.t_gsw);
  833. add(&mut ct_gsw_neg, &gadget_ntt, &ct_gsw_inv.ntt());
  834. v_folding_neg.push(ct_gsw_neg);
  835. }
  836. fold_ciphertexts(&params, &mut v_reg_raw, &v_folding, &v_folding_neg);
  837. // decrypt
  838. assert_eq!(
  839. dec_reg(&params, &v_reg_raw[0].ntt(), &mut client, scale_k),
  840. 1
  841. );
  842. }
  843. fn full_protocol_is_correct_for_params(params: &Params) {
  844. let mut seeded_rng = get_seeded_rng();
  845. let target_idx = seeded_rng.gen::<usize>() % (params.db_dim_1 + params.db_dim_2);
  846. let mut client = Client::init(params, &mut seeded_rng);
  847. let public_params = client.generate_keys();
  848. let query = client.generate_query(target_idx);
  849. let (corr_item, db) = generate_random_db_and_get_item(params, target_idx);
  850. let response = process_query(params, &public_params, &query, db.as_slice());
  851. let result = client.decode_response(response.as_slice());
  852. let p_bits = log2_ceil(params.pt_modulus) as usize;
  853. let corr_result = corr_item.to_vec(p_bits, params.poly_len);
  854. for z in 0..corr_result.len() {
  855. assert_eq!(result[z], corr_result[z]);
  856. }
  857. }
  858. fn full_protocol_is_correct_for_params_real_db(params: &Params) {
  859. let mut seeded_rng = get_seeded_rng();
  860. let target_idx = seeded_rng.gen::<usize>() % (params.db_dim_1 + params.db_dim_2);
  861. let mut client = Client::init(params, &mut seeded_rng);
  862. let public_params = client.generate_keys();
  863. let query = client.generate_query(target_idx);
  864. let mut file = File::open(TEST_PREPROCESSED_DB_PATH).unwrap();
  865. let db = load_preprocessed_db_from_file(params, &mut file);
  866. let response = process_query(params, &public_params, &query, db.as_slice());
  867. let result = client.decode_response(response.as_slice());
  868. let corr_result = vec![0x42, 0x5a, 0x68];
  869. for z in 0..corr_result.len() {
  870. assert_eq!(result[z], corr_result[z]);
  871. }
  872. }
  873. #[test]
  874. fn full_protocol_is_correct() {
  875. full_protocol_is_correct_for_params(&get_params());
  876. }
  877. // #[test]
  878. // fn full_protocol_is_correct_20_256() {
  879. // full_protocol_is_correct_for_params(&params_from_json(&CFG_20_256.replace("'", "\"")));
  880. // }
  881. // #[test]
  882. // fn full_protocol_is_correct_16_100000() {
  883. // full_protocol_is_correct_for_params(&params_from_json(&CFG_16_100000.replace("'", "\"")));
  884. // }
  885. #[test]
  886. #[ignore]
  887. fn full_protocol_is_correct_real_db_16_100000() {
  888. full_protocol_is_correct_for_params_real_db(&params_from_json(
  889. &CFG_16_100000.replace("'", "\""),
  890. ));
  891. }
  892. }