server.rs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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 std::mem::size_of;
  9. use crate::arith::*;
  10. use crate::aligned_memory::*;
  11. use crate::client::PublicParameters;
  12. use crate::client::Query;
  13. use crate::gadget::*;
  14. use crate::params::*;
  15. use crate::poly::*;
  16. use crate::util::*;
  17. pub fn coefficient_expansion(
  18. v: &mut Vec<PolyMatrixNTT>,
  19. g: usize,
  20. stop_round: usize,
  21. params: &Params,
  22. v_w_left: &Vec<PolyMatrixNTT>,
  23. v_w_right: &Vec<PolyMatrixNTT>,
  24. v_neg1: &Vec<PolyMatrixNTT>,
  25. max_bits_to_gen_right: usize,
  26. ) {
  27. let poly_len = params.poly_len;
  28. let mut ct = PolyMatrixRaw::zero(params, 2, 1);
  29. let mut ct_auto = PolyMatrixRaw::zero(params, 2, 1);
  30. let mut ct_auto_1 = PolyMatrixRaw::zero(params, 1, 1);
  31. let mut ct_auto_1_ntt = PolyMatrixNTT::zero(params, 1, 1);
  32. let mut ginv_ct_left = PolyMatrixRaw::zero(params, params.t_exp_left, 1);
  33. let mut ginv_ct_left_ntt = PolyMatrixNTT::zero(params, params.t_exp_left, 1);
  34. let mut ginv_ct_right = PolyMatrixRaw::zero(params, params.t_exp_right, 1);
  35. let mut ginv_ct_right_ntt = PolyMatrixNTT::zero(params, params.t_exp_right, 1);
  36. let mut w_times_ginv_ct = PolyMatrixNTT::zero(params, 2, 1);
  37. for r in 0..g {
  38. let num_in = 1 << r;
  39. let num_out = 2 * num_in;
  40. let t = (poly_len / (1 << r)) + 1;
  41. let neg1 = &v_neg1[r];
  42. for i in 0..num_out {
  43. if stop_round > 0 && i % 2 == 1 && r > stop_round
  44. || (r == stop_round && i / 2 >= max_bits_to_gen_right)
  45. {
  46. continue;
  47. }
  48. let (w, _gadget_dim, gi_ct, gi_ct_ntt) = match i % 2 {
  49. 0 => (
  50. &v_w_left[r],
  51. params.t_exp_left,
  52. &mut ginv_ct_left,
  53. &mut ginv_ct_left_ntt,
  54. ),
  55. 1 | _ => (
  56. &v_w_right[r],
  57. params.t_exp_right,
  58. &mut ginv_ct_right,
  59. &mut ginv_ct_right_ntt,
  60. ),
  61. };
  62. if i < num_in {
  63. let (src, dest) = v.split_at_mut(num_in);
  64. scalar_multiply(&mut dest[i], neg1, &src[i]);
  65. }
  66. from_ntt(&mut ct, &v[i]);
  67. automorph(&mut ct_auto, &ct, t);
  68. gadget_invert_rdim(gi_ct, &ct_auto, 1);
  69. to_ntt_no_reduce(gi_ct_ntt, &gi_ct);
  70. ct_auto_1
  71. .data
  72. .as_mut_slice()
  73. .copy_from_slice(ct_auto.get_poly(1, 0));
  74. to_ntt(&mut ct_auto_1_ntt, &ct_auto_1);
  75. multiply(&mut w_times_ginv_ct, w, &gi_ct_ntt);
  76. let mut idx = 0;
  77. for j in 0..2 {
  78. for n in 0..params.crt_count {
  79. for z in 0..poly_len {
  80. let sum = v[i].data[idx]
  81. + w_times_ginv_ct.data[idx]
  82. + j * ct_auto_1_ntt.data[n * poly_len + z];
  83. v[i].data[idx] = barrett_coeff_u64(params, sum, n);
  84. idx += 1;
  85. }
  86. }
  87. }
  88. }
  89. }
  90. }
  91. pub fn regev_to_gsw<'a>(
  92. v_gsw: &mut Vec<PolyMatrixNTT<'a>>,
  93. v_inp: &Vec<PolyMatrixNTT<'a>>,
  94. v: &PolyMatrixNTT<'a>,
  95. params: &'a Params,
  96. idx_factor: usize,
  97. idx_offset: usize,
  98. ) {
  99. assert!(v.rows == 2);
  100. assert!(v.cols == 2 * params.t_conv);
  101. let mut ginv_c_inp = PolyMatrixRaw::zero(params, 2 * params.t_conv, 1);
  102. let mut ginv_c_inp_ntt = PolyMatrixNTT::zero(params, 2 * params.t_conv, 1);
  103. let mut tmp_ct_raw = PolyMatrixRaw::zero(params, 2, 1);
  104. let mut tmp_ct = PolyMatrixNTT::zero(params, 2, 1);
  105. for i in 0..params.db_dim_2 {
  106. let ct = &mut v_gsw[i];
  107. for j in 0..params.t_gsw {
  108. let idx_ct = i * params.t_gsw + j;
  109. let idx_inp = idx_factor * (idx_ct) + idx_offset;
  110. ct.copy_into(&v_inp[idx_inp], 0, 2 * j + 1);
  111. from_ntt(&mut tmp_ct_raw, &v_inp[idx_inp]);
  112. gadget_invert(&mut ginv_c_inp, &tmp_ct_raw);
  113. to_ntt(&mut ginv_c_inp_ntt, &ginv_c_inp);
  114. multiply(&mut tmp_ct, v, &ginv_c_inp_ntt);
  115. ct.copy_into(&tmp_ct, 0, 2 * j);
  116. }
  117. }
  118. }
  119. pub const MAX_SUMMED: usize = 1 << 6;
  120. pub const PACKED_OFFSET_2: i32 = 32;
  121. #[cfg(target_feature = "avx2")]
  122. pub fn multiply_reg_by_database(
  123. out: &mut Vec<PolyMatrixNTT>,
  124. db: &[u64],
  125. v_firstdim: &[u64],
  126. params: &Params,
  127. dim0: usize,
  128. num_per: usize,
  129. ) {
  130. let ct_rows = 2;
  131. let ct_cols = 1;
  132. let pt_rows = 1;
  133. let pt_cols = 1;
  134. assert!(dim0 * ct_rows >= MAX_SUMMED);
  135. let mut sums_out_n0_u64 = AlignedMemory64::new(4);
  136. let mut sums_out_n2_u64 = AlignedMemory64::new(4);
  137. for z in 0..params.poly_len {
  138. let idx_a_base = z * (ct_cols * dim0 * ct_rows);
  139. let mut idx_b_base = z * (num_per * pt_cols * dim0 * pt_rows);
  140. for i in 0..num_per {
  141. for c in 0..pt_cols {
  142. let inner_limit = MAX_SUMMED;
  143. let outer_limit = dim0 * ct_rows / inner_limit;
  144. let mut sums_out_n0_u64_acc = [0u64, 0, 0, 0];
  145. let mut sums_out_n2_u64_acc = [0u64, 0, 0, 0];
  146. for o_jm in 0..outer_limit {
  147. unsafe {
  148. let mut sums_out_n0 = _mm256_setzero_si256();
  149. let mut sums_out_n2 = _mm256_setzero_si256();
  150. for i_jm in 0..inner_limit / 4 {
  151. let jm = o_jm * inner_limit + (4 * i_jm);
  152. let b_inp_1 = *db.get_unchecked(idx_b_base) as i64;
  153. idx_b_base += 1;
  154. let b_inp_2 = *db.get_unchecked(idx_b_base) as i64;
  155. idx_b_base += 1;
  156. let b = _mm256_set_epi64x(b_inp_2, b_inp_2, b_inp_1, b_inp_1);
  157. let v_a = v_firstdim.get_unchecked(idx_a_base + jm) as *const u64;
  158. let a = _mm256_load_si256(v_a as *const __m256i);
  159. let a_lo = a;
  160. let a_hi_hi = _mm256_srli_epi64(a, PACKED_OFFSET_2);
  161. let b_lo = b;
  162. let b_hi_hi = _mm256_srli_epi64(b, PACKED_OFFSET_2);
  163. sums_out_n0 =
  164. _mm256_add_epi64(sums_out_n0, _mm256_mul_epu32(a_lo, b_lo));
  165. sums_out_n2 =
  166. _mm256_add_epi64(sums_out_n2, _mm256_mul_epu32(a_hi_hi, b_hi_hi));
  167. }
  168. // reduce here, otherwise we will overflow
  169. _mm256_store_si256(
  170. sums_out_n0_u64.as_mut_ptr() as *mut __m256i,
  171. sums_out_n0,
  172. );
  173. _mm256_store_si256(
  174. sums_out_n2_u64.as_mut_ptr() as *mut __m256i,
  175. sums_out_n2,
  176. );
  177. for idx in 0..4 {
  178. let val = sums_out_n0_u64[idx];
  179. sums_out_n0_u64_acc[idx] = 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] = barrett_coeff_u64(params, val + sums_out_n2_u64_acc[idx], 1);
  184. }
  185. }
  186. }
  187. for idx in 0..4 {
  188. sums_out_n0_u64_acc[idx] = barrett_coeff_u64(params, sums_out_n0_u64_acc[idx], 0);
  189. sums_out_n2_u64_acc[idx] = barrett_coeff_u64(params, sums_out_n2_u64_acc[idx], 1);
  190. }
  191. // output n0
  192. let (crt_count, poly_len) = (params.crt_count, params.poly_len);
  193. let mut n = 0;
  194. let mut idx_c = c * (crt_count * poly_len) + n * (poly_len) + z;
  195. out[i].data[idx_c] =
  196. barrett_coeff_u64(params, sums_out_n0_u64_acc[0] + sums_out_n0_u64_acc[2], 0);
  197. idx_c += pt_cols * crt_count * poly_len;
  198. out[i].data[idx_c] =
  199. barrett_coeff_u64(params, sums_out_n0_u64_acc[1] + sums_out_n0_u64_acc[3], 0);
  200. // output n1
  201. n = 1;
  202. idx_c = c * (crt_count * poly_len) + n * (poly_len) + z;
  203. out[i].data[idx_c] =
  204. barrett_coeff_u64(params, sums_out_n2_u64_acc[0] + sums_out_n2_u64_acc[2], 1);
  205. idx_c += pt_cols * crt_count * poly_len;
  206. out[i].data[idx_c] =
  207. barrett_coeff_u64(params, sums_out_n2_u64_acc[1] + sums_out_n2_u64_acc[3], 1);
  208. }
  209. }
  210. }
  211. }
  212. #[cfg(not(target_feature = "avx2"))]
  213. pub fn multiply_reg_by_database(
  214. out: &mut Vec<PolyMatrixNTT>,
  215. db: &[u64],
  216. v_firstdim: &[u64],
  217. params: &Params,
  218. dim0: usize,
  219. num_per: usize,
  220. ) {
  221. let ct_rows = 2;
  222. let ct_cols = 1;
  223. let pt_rows = 1;
  224. let pt_cols = 1;
  225. for z in 0..params.poly_len {
  226. let idx_a_base = z * (ct_cols * dim0 * ct_rows);
  227. let mut idx_b_base = z * (num_per * pt_cols * dim0 * pt_rows);
  228. for i in 0..num_per {
  229. for c in 0..pt_cols {
  230. let mut sums_out_n0_0 = 0u128;
  231. let mut sums_out_n0_1 = 0u128;
  232. let mut sums_out_n1_0 = 0u128;
  233. let mut sums_out_n1_1 = 0u128;
  234. for jm in 0..(dim0 * pt_rows) {
  235. let b = db[idx_b_base];
  236. idx_b_base += 1;
  237. let v_a0 = v_firstdim[idx_a_base + jm * ct_rows];
  238. let v_a1 = v_firstdim[idx_a_base + jm * ct_rows + 1];
  239. let b_lo = b as u32;
  240. let b_hi = (b >> 32) as u32;
  241. let v_a0_lo = v_a0 as u32;
  242. let v_a0_hi = (v_a0 >> 32) as u32;
  243. let v_a1_lo = v_a1 as u32;
  244. let v_a1_hi = (v_a1 >> 32) as u32;
  245. // do n0
  246. sums_out_n0_0 += ((v_a0_lo as u64) * (b_lo as u64)) as u128;
  247. sums_out_n0_1 += ((v_a1_lo as u64) * (b_lo as u64)) as u128;
  248. // do n1
  249. sums_out_n1_0 += ((v_a0_hi as u64) * (b_hi as u64)) as u128;
  250. sums_out_n1_1 += ((v_a1_hi as u64) * (b_hi as u64)) as u128;
  251. }
  252. // output n0
  253. let (crt_count, poly_len) = (params.crt_count, params.poly_len);
  254. let mut n = 0;
  255. let mut idx_c = c * (crt_count * poly_len) + n * (poly_len) + z;
  256. out[i].data[idx_c] = (sums_out_n0_0 % (params.moduli[0] as u128)) as u64;
  257. idx_c += pt_cols * crt_count * poly_len;
  258. out[i].data[idx_c] = (sums_out_n0_1 % (params.moduli[0] as u128)) as u64;
  259. // output n1
  260. n = 1;
  261. idx_c = c * (crt_count * poly_len) + n * (poly_len) + z;
  262. out[i].data[idx_c] = (sums_out_n1_0 % (params.moduli[1] as u128)) as u64;
  263. idx_c += pt_cols * crt_count * poly_len;
  264. out[i].data[idx_c] = (sums_out_n1_1 % (params.moduli[1] as u128)) as u64;
  265. }
  266. }
  267. }
  268. }
  269. pub fn generate_random_db_and_get_item<'a>(
  270. params: &'a Params,
  271. item_idx: usize,
  272. ) -> (PolyMatrixRaw<'a>, AlignedMemory64) {
  273. let mut rng = get_seeded_rng();
  274. let instances = params.instances;
  275. let trials = params.n * params.n;
  276. let dim0 = 1 << params.db_dim_1;
  277. let num_per = 1 << params.db_dim_2;
  278. let num_items = dim0 * num_per;
  279. let db_size_words = instances * trials * num_items * params.poly_len;
  280. let mut v = AlignedMemory64::new(db_size_words);
  281. let mut tmp_item_ntt = PolyMatrixNTT::zero(params, 1, 1);
  282. let mut item = PolyMatrixRaw::zero(params, params.n, params.n);
  283. for instance in 0..instances {
  284. println!("Instance {:?}", instance);
  285. for trial in 0..trials {
  286. println!("Trial {:?}", trial);
  287. for i in 0..num_items {
  288. let ii = i % num_per;
  289. let j = i / num_per;
  290. let mut db_item = PolyMatrixRaw::random_rng(params, 1, 1, &mut rng);
  291. db_item.reduce_mod(params.pt_modulus);
  292. if i == item_idx && instance == 0 {
  293. item.copy_into(&db_item, trial / params.n, trial % params.n);
  294. }
  295. for z in 0..params.poly_len {
  296. db_item.data[z] = recenter_mod(db_item.data[z], params.pt_modulus, params.modulus);
  297. }
  298. let db_item_ntt = db_item.ntt();
  299. for z in 0..params.poly_len {
  300. let idx_dst = calc_index(
  301. &[instance, trial, z, ii, j],
  302. &[instances, trials, params.poly_len, num_per, dim0],
  303. );
  304. v[idx_dst] = db_item_ntt.data[z]
  305. | (db_item_ntt.data[params.poly_len + z] << PACKED_OFFSET_2);
  306. }
  307. }
  308. }
  309. }
  310. (item, v)
  311. }
  312. pub fn load_item_from_file<'a>(
  313. params: &'a Params,
  314. file: &mut File,
  315. instance: usize,
  316. trial: usize,
  317. item_idx: usize
  318. ) -> PolyMatrixRaw<'a> {
  319. let db_item_size = params.db_item_size;
  320. let instances = params.instances;
  321. let trials = params.n * params.n;
  322. let dim0 = 1 << params.db_dim_1;
  323. let num_per = 1 << params.db_dim_2;
  324. let num_items = dim0 * num_per;
  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.read(&mut data.as_mut_slice()[0..bytes_per_chunk]).unwrap();
  340. let modp_words_read = f64::ceil((bytes_read * 8) as f64 / logp as f64) as usize;
  341. assert!(modp_words_read <= params.poly_len);
  342. for i in 0..modp_words_read {
  343. out.data[i] = read_arbitrary_bits(&data, i * logp, logp);
  344. assert!(out.data[i] <= params.pt_modulus);
  345. }
  346. out
  347. }
  348. pub fn load_db_from_file(
  349. params: &Params,
  350. file: &mut File
  351. ) -> AlignedMemory64 {
  352. let instances = params.instances;
  353. let trials = params.n * params.n;
  354. let dim0 = 1 << params.db_dim_1;
  355. let num_per = 1 << params.db_dim_2;
  356. let num_items = dim0 * num_per;
  357. let db_size_words = instances * trials * num_items * params.poly_len;
  358. let mut v = AlignedMemory64::new(db_size_words);
  359. for instance in 0..instances {
  360. println!("Instance {:?}", instance);
  361. for trial in 0..trials {
  362. println!("Trial {:?}", trial);
  363. for i in 0..num_items {
  364. if i % 8192 == 0 {
  365. println!("item {:?}", i);
  366. }
  367. let ii = i % num_per;
  368. let j = i / num_per;
  369. let mut db_item = load_item_from_file(params, file, instance, trial, i);
  370. // db_item.reduce_mod(params.pt_modulus);
  371. for z in 0..params.poly_len {
  372. db_item.data[z] = 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(
  389. params: &Params,
  390. file: &mut File
  391. ) -> AlignedMemory64 {
  392. let instances = params.instances;
  393. let trials = params.n * params.n;
  394. let dim0 = 1 << params.db_dim_1;
  395. let num_per = 1 << params.db_dim_2;
  396. let num_items = dim0 * num_per;
  397. let db_size_words = instances * trials * num_items * params.poly_len;
  398. let mut v = AlignedMemory64::new(db_size_words);
  399. let v_mut_slice = v.as_mut_slice();
  400. let mut reader = BufReader::new(file);
  401. let mut buf = [0u8; 8];
  402. for i in 0..db_size_words {
  403. if i % 1000000000 == 0 {
  404. println!("{} GB loaded", i);
  405. }
  406. reader.read(&mut buf).unwrap();
  407. v_mut_slice[i] = u64::from_ne_bytes(buf);
  408. }
  409. v
  410. }
  411. pub fn fold_ciphertexts(
  412. params: &Params,
  413. v_cts: &mut Vec<PolyMatrixRaw>,
  414. v_folding: &Vec<PolyMatrixNTT>,
  415. v_folding_neg: &Vec<PolyMatrixNTT>
  416. ) {
  417. let further_dims = log2(v_cts.len() as u64) as usize;
  418. let ell = v_folding[0].cols / 2;
  419. let mut ginv_c = PolyMatrixRaw::zero(&params, 2 * ell, 1);
  420. let mut ginv_c_ntt = PolyMatrixNTT::zero(&params, 2 * ell, 1);
  421. let mut prod = PolyMatrixNTT::zero(&params, 2, 1);
  422. let mut sum = PolyMatrixNTT::zero(&params, 2, 1);
  423. let mut num_per = v_cts.len();
  424. for cur_dim in 0..further_dims {
  425. num_per = num_per / 2;
  426. for i in 0..num_per {
  427. gadget_invert(&mut ginv_c, &v_cts[i]);
  428. to_ntt(&mut ginv_c_ntt, &ginv_c);
  429. multiply(&mut prod, &v_folding_neg[further_dims - 1 - cur_dim], &ginv_c_ntt);
  430. gadget_invert(&mut ginv_c, &v_cts[num_per + i]);
  431. to_ntt(&mut ginv_c_ntt, &ginv_c);
  432. multiply(&mut sum, &v_folding[further_dims - 1 - cur_dim], &ginv_c_ntt);
  433. add_into(&mut sum, &prod);
  434. from_ntt(&mut v_cts[i], &sum);
  435. }
  436. }
  437. }
  438. pub fn pack<'a>(
  439. params: &'a Params,
  440. v_ct: &Vec<PolyMatrixRaw>,
  441. v_w: &Vec<PolyMatrixNTT>
  442. ) -> PolyMatrixNTT<'a> {
  443. assert!(v_ct.len() >= params.n * params.n);
  444. assert!(v_w.len() == params.n);
  445. assert!(v_ct[0].rows == 2);
  446. assert!(v_ct[0].cols == 1);
  447. assert!(v_w[0].rows == (params.n + 1));
  448. assert!(v_w[0].cols == params.t_conv);
  449. let mut result = PolyMatrixNTT::zero(params, params.n + 1, params.n);
  450. let mut ginv = PolyMatrixRaw::zero(params, params.t_conv, 1);
  451. let mut ginv_nttd = PolyMatrixNTT::zero(params, params.t_conv, 1);
  452. let mut prod = PolyMatrixNTT::zero(params, params.n + 1, 1);
  453. let mut ct_1 = PolyMatrixRaw::zero(params, 1, 1);
  454. let mut ct_2 = PolyMatrixRaw::zero(params, 1, 1);
  455. let mut ct_2_ntt = PolyMatrixNTT::zero(params, 1, 1);
  456. for c in 0..params.n {
  457. let mut v_int = PolyMatrixNTT::zero(&params, params.n + 1, 1);
  458. for r in 0..params.n {
  459. let w = &v_w[r];
  460. let ct = &v_ct[r * params.n + c];
  461. ct_1.get_poly_mut(0, 0).copy_from_slice(ct.get_poly(0, 0));
  462. ct_2.get_poly_mut(0, 0).copy_from_slice(ct.get_poly(1, 0));
  463. to_ntt(&mut ct_2_ntt, &ct_2);
  464. gadget_invert(&mut ginv, &ct_1);
  465. to_ntt(&mut ginv_nttd, &ginv);
  466. multiply(&mut prod, &w, &ginv_nttd);
  467. add_into_at(&mut v_int, &ct_2_ntt, 1 + r, 0);
  468. add_into(&mut v_int, &prod);
  469. }
  470. result.copy_into(&v_int, 0, c);
  471. }
  472. result
  473. }
  474. pub fn encode(
  475. params: &Params,
  476. v_packed_ct: &Vec<PolyMatrixRaw>
  477. ) -> Vec<u8> {
  478. let q1 = 4 * params.pt_modulus;
  479. let q1_bits = log2_ceil(q1) as usize;
  480. let q2 = Q2_VALUES[params.q2_bits as usize];
  481. let q2_bits = params.q2_bits as usize;
  482. let num_bits = params.instances *
  483. (
  484. (q2_bits * params.n * params.poly_len) +
  485. (q1_bits * params.n * params.n * params.poly_len)
  486. );
  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) =
  588. expand_query(params, public_params, query);
  589. } else {
  590. v_reg_reoriented = AlignedMemory64::new(query.v_buf.as_ref().unwrap().len());
  591. v_reg_reoriented.as_mut_slice().copy_from_slice(query.v_buf.as_ref().unwrap());
  592. v_folding = query.v_ct.as_ref().unwrap().clone().iter()
  593. .map(|x| { x.ntt() })
  594. .collect();
  595. }
  596. let v_folding_neg = get_v_folding_neg(params, &v_folding);
  597. let mut intermediate = Vec::with_capacity(num_per);
  598. let mut intermediate_raw = Vec::with_capacity(num_per);
  599. for _ in 0..num_per {
  600. intermediate.push(PolyMatrixNTT::zero(params, 2, 1));
  601. intermediate_raw.push(PolyMatrixRaw::zero(params, 2, 1));
  602. }
  603. let mut v_packed_ct = Vec::new();
  604. for instance in 0..params.instances {
  605. let mut v_ct = Vec::new();
  606. for trial in 0..(params.n * params.n) {
  607. let idx = (instance * (params.n * params.n) + trial) * db_slice_sz;
  608. let cur_db = &db[idx..(idx + db_slice_sz)];
  609. multiply_reg_by_database(&mut intermediate, cur_db, v_reg_reoriented.as_slice(), params, dim0, num_per);
  610. for i in 0..intermediate.len() {
  611. from_ntt(&mut intermediate_raw[i], &intermediate[i]);
  612. }
  613. fold_ciphertexts(
  614. params,
  615. &mut intermediate_raw,
  616. &v_folding,
  617. &v_folding_neg
  618. );
  619. v_ct.push(intermediate_raw[0].clone());
  620. }
  621. let packed_ct = pack(
  622. params,
  623. &v_ct,
  624. &v_packing,
  625. );
  626. v_packed_ct.push(packed_ct.raw());
  627. }
  628. encode(params, &v_packed_ct)
  629. }
  630. #[cfg(test)]
  631. mod test {
  632. use super::*;
  633. use crate::{client::*};
  634. use rand::{prelude::SmallRng, Rng};
  635. const TEST_PREPROCESSED_DB_PATH: &'static str = "/home/samir/wiki/enwiki-20220320.dbp";
  636. fn get_params() -> Params {
  637. let mut params = get_expansion_testing_params();
  638. params.db_dim_1 = 6;
  639. params.db_dim_2 = 2;
  640. params.t_exp_right = 8;
  641. 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(&mut out, db.as_slice(), v_reg_reoriented.as_slice(), &params, dim0, num_per);
  771. // decrypt
  772. let dec = client.decrypt_matrix_reg(&out[target_idx_num_per]).raw();
  773. let mut dec_rescaled = PolyMatrixRaw::zero(&params, 1, 1);
  774. for z in 0..params.poly_len {
  775. dec_rescaled.data[z] = rescale(dec.data[z], params.modulus, params.pt_modulus);
  776. }
  777. for z in 0..params.poly_len {
  778. // println!("{:?} {:?}", dec_rescaled.data[z], corr_item.data[z]);
  779. assert_eq!(dec_rescaled.data[z], corr_item.data[z]);
  780. }
  781. }
  782. #[test]
  783. fn fold_ciphertexts_is_correct() {
  784. let params = get_params();
  785. let mut seeded_rng = get_seeded_rng();
  786. let dim0 = 1 << params.db_dim_1;
  787. let num_per = 1 << params.db_dim_2;
  788. let scale_k = params.modulus / params.pt_modulus;
  789. let target_idx = seeded_rng.gen::<usize>() % (dim0 * num_per);
  790. let target_idx_num_per = target_idx % num_per;
  791. let mut client = Client::init(&params, &mut seeded_rng);
  792. _ = client.generate_keys();
  793. let mut v_reg = Vec::new();
  794. for i in 0..num_per {
  795. let val = if i == target_idx_num_per { scale_k } else { 0 };
  796. let sigma = PolyMatrixRaw::single_value(&params, val).ntt();
  797. v_reg.push(client.encrypt_matrix_reg(&sigma));
  798. }
  799. let mut v_reg_raw = Vec::new();
  800. for i in 0..num_per {
  801. v_reg_raw.push(v_reg[i].raw());
  802. }
  803. let bits_per = get_bits_per(&params, params.t_gsw);
  804. let mut v_folding = Vec::new();
  805. for i in 0..params.db_dim_2 {
  806. let bit = ((target_idx_num_per as u64) & (1 << (i as u64))) >> (i as u64);
  807. let mut ct_gsw = PolyMatrixNTT::zero(&params, 2, 2 * params.t_gsw);
  808. for j in 0..params.t_gsw {
  809. let value = (1u64 << (bits_per * j)) * bit;
  810. let sigma = PolyMatrixRaw::single_value(&params, value);
  811. let sigma_ntt = to_ntt_alloc(&sigma);
  812. let ct = client.encrypt_matrix_reg(&sigma_ntt);
  813. ct_gsw.copy_into(&ct, 0, 2 * j + 1);
  814. let prod = &to_ntt_alloc(&client.sk_reg) * &sigma_ntt;
  815. let ct = &client.encrypt_matrix_reg(&prod);
  816. ct_gsw.copy_into(&ct, 0, 2 * j);
  817. }
  818. v_folding.push(ct_gsw);
  819. }
  820. let gadget_ntt = build_gadget(&params, 2, 2 * params.t_gsw).ntt();
  821. let mut v_folding_neg = Vec::new();
  822. let mut ct_gsw_inv = PolyMatrixRaw::zero(&params, 2, 2 * params.t_gsw);
  823. for i in 0..params.db_dim_2 {
  824. invert(&mut ct_gsw_inv, &v_folding[i].raw());
  825. let mut ct_gsw_neg = PolyMatrixNTT::zero(&params, 2, 2 * params.t_gsw);
  826. add(&mut ct_gsw_neg, &gadget_ntt, &ct_gsw_inv.ntt());
  827. v_folding_neg.push(ct_gsw_neg);
  828. }
  829. fold_ciphertexts(
  830. &params,
  831. &mut v_reg_raw,
  832. &v_folding,
  833. &v_folding_neg
  834. );
  835. // decrypt
  836. assert_eq!(dec_reg(&params, &v_reg_raw[0].ntt(), &mut client, scale_k), 1);
  837. }
  838. fn full_protocol_is_correct_for_params(params: &Params) {
  839. let mut seeded_rng = get_seeded_rng();
  840. let target_idx = seeded_rng.gen::<usize>() % (params.db_dim_1 + params.db_dim_2);
  841. let mut client = Client::init(params, &mut seeded_rng);
  842. let public_params = client.generate_keys();
  843. let query = client.generate_query(target_idx);
  844. let (corr_item, db) = generate_random_db_and_get_item(params, target_idx);
  845. let response = process_query(params, &public_params, &query, db.as_slice());
  846. let result = client.decode_response(response.as_slice());
  847. let p_bits = log2_ceil(params.pt_modulus) as usize;
  848. let corr_result = corr_item.to_vec(p_bits, params.poly_len);
  849. for z in 0..corr_result.len() {
  850. assert_eq!(result[z], corr_result[z]);
  851. }
  852. }
  853. fn full_protocol_is_correct_for_params_real_db(params: &Params) {
  854. let mut seeded_rng = get_seeded_rng();
  855. let target_idx = seeded_rng.gen::<usize>() % (params.db_dim_1 + params.db_dim_2);
  856. let mut client = Client::init(params, &mut seeded_rng);
  857. let public_params = client.generate_keys();
  858. let query = client.generate_query(target_idx);
  859. let mut file = File::open(TEST_PREPROCESSED_DB_PATH).unwrap();
  860. let db = load_preprocessed_db_from_file(params, &mut file);
  861. let response = process_query(params, &public_params, &query, db.as_slice());
  862. let result = client.decode_response(response.as_slice());
  863. let corr_result = vec![0x42, 0x5a, 0x68];
  864. for z in 0..corr_result.len() {
  865. assert_eq!(result[z], corr_result[z]);
  866. }
  867. }
  868. #[test]
  869. fn full_protocol_is_correct() {
  870. full_protocol_is_correct_for_params(&get_params());
  871. }
  872. // #[test]
  873. // fn full_protocol_is_correct_20_256() {
  874. // full_protocol_is_correct_for_params(&params_from_json(&CFG_20_256.replace("'", "\"")));
  875. // }
  876. // #[test]
  877. // fn full_protocol_is_correct_16_100000() {
  878. // full_protocol_is_correct_for_params(&params_from_json(&CFG_16_100000.replace("'", "\"")));
  879. // }
  880. #[test]
  881. fn full_protocol_is_correct_real_db_16_100000() {
  882. full_protocol_is_correct_for_params_real_db(&params_from_json(&CFG_16_100000.replace("'", "\"")));
  883. }
  884. }