pir_server.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. #include "pir_server.hpp"
  2. #include "pir_client.hpp"
  3. using namespace std;
  4. using namespace std::chrono;
  5. using namespace seal;
  6. using namespace seal::util;
  7. PIRServer::PIRServer(const EncryptionParameters &params, const PirParams &pir_params) :
  8. params_(params),
  9. pir_params_(pir_params),
  10. is_db_preprocessed_(false)
  11. {
  12. auto context = SEALContext::Create(params, false);
  13. evaluator_ = make_unique<Evaluator>(context);
  14. }
  15. // void PIRServer::update_parameters(const EncryptionParameters &expanded_params,
  16. // const PirParams &pir_params) {
  17. // // The only thing that can change is the plaintext modulus and pir_params
  18. // assert(expanded_params.poly_modulus_degree() == params_.poly_modulus_degree());
  19. // assert(expanded_params.coeff_modulus() == params_.coeff_modulus());
  20. // params_ = expanded_params;
  21. // pir_params_ = pir_params;
  22. // auto context = SEALContext::Create(expanded_params);
  23. // evaluator_ = make_unique<Evaluator>(context);
  24. // is_db_preprocessed_ = false;
  25. // // Update all the galois keys
  26. // for (std::pair<const int, GaloisKeys> &key : galoisKeys_) {
  27. // key.second.parms_id() = params_.parms_id();
  28. // }
  29. // }
  30. void PIRServer::preprocess_database() {
  31. if (!is_db_preprocessed_) {
  32. for (uint32_t i = 0; i < db_->size(); i++) {
  33. evaluator_->transform_to_ntt_inplace(
  34. db_->operator[](i), params_.parms_id());
  35. }
  36. is_db_preprocessed_ = true;
  37. }
  38. }
  39. // Server takes over ownership of db and will free it when it exits
  40. void PIRServer::set_database(unique_ptr<vector<Plaintext>> &&db) {
  41. if (!db) {
  42. throw invalid_argument("db cannot be null");
  43. }
  44. db_ = move(db);
  45. is_db_preprocessed_ = false;
  46. }
  47. void PIRServer::set_database(const std::unique_ptr<const std::uint8_t[]> &bytes,
  48. uint64_t ele_num, uint64_t ele_size) {
  49. uint32_t logt = floor(log2(params_.plain_modulus().value()));
  50. uint32_t N = params_.poly_modulus_degree();
  51. cout << "In PIRServer::set_database: \n";
  52. cout << "logt = "<< logt <<", N = " << N <<endl;
  53. // number of FV plaintexts needed to represent all elements
  54. uint64_t total = plaintexts_per_db(logt, N, ele_num, ele_size);
  55. // number of FV plaintexts needed to create the d-dimensional matrix
  56. uint64_t prod = 1;
  57. for (uint32_t i = 0; i < pir_params_.nvec.size(); i++) {
  58. prod *= pir_params_.nvec[i];
  59. }
  60. uint64_t matrix_plaintexts = prod;
  61. assert(total <= matrix_plaintexts);
  62. auto result = make_unique<vector<Plaintext>>();
  63. result->reserve(matrix_plaintexts);
  64. uint64_t ele_per_ptxt = elements_per_ptxt(logt, N, ele_size);
  65. uint64_t bytes_per_ptxt = ele_per_ptxt * ele_size;
  66. uint64_t db_size = ele_num * ele_size;
  67. uint64_t coeff_per_ptxt = ele_per_ptxt * coefficients_per_element(logt, ele_size);
  68. assert(coeff_per_ptxt <= N);
  69. cout << "Server: total number of FV plaintext = " << total << endl;
  70. cout << "Server: elements packed into each plaintext " << ele_per_ptxt << endl;
  71. uint32_t offset = 0;
  72. for (uint64_t i = 0; i < total; i++) {
  73. uint64_t process_bytes = 0;
  74. if (db_size <= offset) {
  75. break;
  76. } else if (db_size < offset + bytes_per_ptxt) {
  77. process_bytes = db_size - offset;
  78. } else {
  79. process_bytes = bytes_per_ptxt;
  80. }
  81. // Get the coefficients of the elements that will be packed in plaintext i
  82. vector<uint64_t> coefficients = bytes_to_coeffs(logt, bytes.get() + offset, process_bytes);
  83. offset += process_bytes;
  84. uint64_t used = coefficients.size();
  85. assert(used <= coeff_per_ptxt);
  86. // Pad the rest with 1s
  87. for (uint64_t j = 0; j < (N - used); j++) {
  88. coefficients.push_back(1);
  89. }
  90. Plaintext plain;
  91. vector_to_plaintext(coefficients, plain);
  92. // cout << i << "-th encoded plaintext = " << plain.to_string() << endl;
  93. result->push_back(move(plain));
  94. }
  95. // Add padding to make database a matrix
  96. uint64_t current_plaintexts = result->size();
  97. assert(current_plaintexts <= total);
  98. #ifdef DEBUG
  99. cout << "adding: " << matrix_plaintexts - current_plaintexts
  100. << " FV plaintexts of padding (equivalent to: "
  101. << (matrix_plaintexts - current_plaintexts) * elements_per_ptxt(logtp, N, ele_size)
  102. << " elements)" << endl;
  103. #endif
  104. vector<uint64_t> padding(N, 1);
  105. for (uint64_t i = 0; i < (matrix_plaintexts - current_plaintexts); i++) {
  106. Plaintext plain;
  107. vector_to_plaintext(padding, plain);
  108. result->push_back(plain);
  109. }
  110. set_database(move(result));
  111. }
  112. void PIRServer::set_galois_key(std::uint32_t client_id, seal::GaloisKeys galkey) {
  113. galkey.parms_id() = params_.parms_id();
  114. galoisKeys_[client_id] = galkey;
  115. }
  116. PirReply PIRServer::generate_reply(PirQuery query, uint32_t client_id, PIRClient &client, double *expand_time_us) {
  117. vector<uint64_t> nvec = pir_params_.nvec;
  118. uint64_t product = 1;
  119. for (uint32_t i = 0; i < nvec.size(); i++) {
  120. product *= nvec[i];
  121. }
  122. auto coeff_count = params_.poly_modulus_degree();
  123. vector<Plaintext> *cur = db_.get();
  124. vector<Plaintext> intermediate_plain; // decompose....
  125. auto pool = MemoryManager::GetPool();
  126. int N = params_.poly_modulus_degree();
  127. int logt = floor(log2(params_.plain_modulus().value()));
  128. cout<<"In PIR_SERVER.CPP : logt = "<< logt << endl;
  129. cout<<"In PIR_SERVER.CPP : log2(params_.plain_modulus().value())) = "<<log2(params_.plain_modulus().value())<< endl;
  130. cout << "expansion ratio = " << pir_params_.expansion_ratio << endl;
  131. for (uint32_t i = 0; i < nvec.size(); i++) {
  132. cout << "Server: " << i + 1 << "-th recursion level started " << endl;
  133. vector<Ciphertext> expanded_query;
  134. uint64_t n_i = nvec[i];
  135. cout << "Server: n_i = " << n_i << endl;
  136. cout << "Server: expanding " << query[i].size() << " query ctxts" << endl;
  137. auto time_expand_s = high_resolution_clock::now();
  138. for (uint32_t j = 0; j < query[i].size(); j++){
  139. uint64_t total = N;
  140. if (j == query[i].size() - 1){
  141. total = n_i % N;
  142. }
  143. cout << "-- expanding one query ctxt into " << total << " ctxts "<< endl;
  144. vector<Ciphertext> expanded_query_part = expand_query(query[i][j], total, client_id, client);
  145. expanded_query.insert(expanded_query.end(), std::make_move_iterator(expanded_query_part.begin()),
  146. std::make_move_iterator(expanded_query_part.end()));
  147. expanded_query_part.clear();
  148. }
  149. cout << "Server: expansion done " << endl;
  150. if (expanded_query.size() != n_i) {
  151. cout << " size mismatch!!! " << expanded_query.size() << ", " << n_i << endl;
  152. }
  153. auto time_expand_e = high_resolution_clock::now();
  154. auto time_expand_us = duration_cast<microseconds>(time_expand_e - time_expand_s).count();
  155. *expand_time_us+=time_expand_us;
  156. /*
  157. cout << "Checking expanded query " << endl;
  158. Plaintext tempPt;
  159. for (int h = 0 ; h < expanded_query.size(); h++){
  160. cout << "noise budget = " << client.decryptor_->invariant_noise_budget(expanded_query[h]) << ", ";
  161. client.decryptor_->decrypt(expanded_query[h], tempPt);
  162. cout << tempPt.to_string() << endl;
  163. }
  164. cout << endl;
  165. */
  166. // Transform expanded query to NTT, and ...
  167. for (uint32_t jj = 0; jj < expanded_query.size(); jj++) {
  168. evaluator_->transform_to_ntt_inplace(expanded_query[jj]);
  169. }
  170. // Transform plaintext to NTT. If database is pre-processed, can skip
  171. if ((!is_db_preprocessed_) || i > 0) {
  172. for (uint32_t jj = 0; jj < cur->size(); jj++) {
  173. evaluator_->transform_to_ntt_inplace((*cur)[jj], params_.parms_id());
  174. }
  175. }
  176. for (uint64_t k = 0; k < product; k++) {
  177. if ((*cur)[k].is_zero()){
  178. cout << k + 1 << "/ " << product << "-th ptxt = 0 " << endl;
  179. }
  180. }
  181. product /= n_i;
  182. vector<Ciphertext> intermediateCtxts(product);
  183. Ciphertext temp;
  184. for (uint64_t k = 0; k < product; k++) {
  185. evaluator_->multiply_plain(expanded_query[0], (*cur)[k], intermediateCtxts[k]);
  186. for (uint64_t j = 1; j < n_i; j++) {
  187. evaluator_->multiply_plain(expanded_query[j], (*cur)[k + j * product], temp);
  188. evaluator_->add_inplace(intermediateCtxts[k], temp); // Adds to first component.
  189. }
  190. }
  191. for (uint32_t jj = 0; jj < intermediateCtxts.size(); jj++) {
  192. evaluator_->transform_from_ntt_inplace(intermediateCtxts[jj]);
  193. // print intermediate ctxts?
  194. //cout << "const term of ctxt " << jj << " = " << intermediateCtxts[jj][0] << endl;
  195. }
  196. if (i == nvec.size() - 1) {
  197. return intermediateCtxts;
  198. } else {
  199. intermediate_plain.clear();
  200. intermediate_plain.reserve(pir_params_.expansion_ratio * product);
  201. cur = &intermediate_plain;
  202. auto tempplain = util::allocate<Plaintext>(
  203. pir_params_.expansion_ratio * product,
  204. pool, coeff_count);
  205. for (uint64_t rr = 0; rr < product; rr++) {
  206. decompose_to_plaintexts_ptr(intermediateCtxts[rr],
  207. tempplain.get() + rr * pir_params_.expansion_ratio, logt);
  208. for (uint32_t jj = 0; jj < pir_params_.expansion_ratio; jj++) {
  209. auto offset = rr * pir_params_.expansion_ratio + jj;
  210. intermediate_plain.emplace_back(tempplain[offset]);
  211. }
  212. }
  213. product *= pir_params_.expansion_ratio; // multiply by expansion rate.
  214. }
  215. cout << "Server: " << i + 1 << "-th recursion level finished " << endl;
  216. cout << endl;
  217. }
  218. cout << "reply generated! " << endl;
  219. // This should never get here
  220. assert(0);
  221. vector<Ciphertext> fail(1);
  222. return fail;
  223. }
  224. inline vector<Ciphertext> PIRServer::expand_query(const Ciphertext &encrypted, uint32_t m,
  225. uint32_t client_id, PIRClient &client) {
  226. #ifdef DEBUG
  227. uint64_t plainMod = params_.plain_modulus().value();
  228. cout << "PIRServer side plain modulus = " << plainMod << endl;
  229. #endif
  230. GaloisKeys &galkey = galoisKeys_[client_id];
  231. // Assume that m is a power of 2. If not, round it to the next power of 2.
  232. uint32_t logm = ceil(log2(m));
  233. Plaintext two("2");
  234. vector<int> galois_elts;
  235. auto n = params_.poly_modulus_degree();
  236. if (logm > ceil(log2(n))){
  237. throw logic_error("m > n is not allowed.");
  238. }
  239. for (int i = 0; i < ceil(log2(n)); i++) {
  240. galois_elts.push_back((n + exponentiate_uint64(2, i)) / exponentiate_uint64(2, i));
  241. }
  242. vector<Ciphertext> temp;
  243. temp.push_back(encrypted);
  244. Ciphertext tempctxt;
  245. Ciphertext tempctxt_rotated;
  246. Ciphertext tempctxt_shifted;
  247. Ciphertext tempctxt_rotatedshifted;
  248. for (uint32_t i = 0; i < logm - 1; i++) {
  249. vector<Ciphertext> newtemp(temp.size() << 1);
  250. // temp[a] = (j0 = a (mod 2**i) ? ) : Enc(x^{j0 - a}) else Enc(0). With
  251. // some scaling....
  252. int index_raw = (n << 1) - (1 << i);
  253. // TODO: galois elements.
  254. int index = (index_raw * galois_elts[i]) % (n << 1);
  255. for (uint32_t a = 0; a < temp.size(); a++) {
  256. evaluator_->apply_galois(temp[a], galois_elts[i], galkey, tempctxt_rotated);
  257. //cout << "rotate " << client.decryptor_->invariant_noise_budget(tempctxt_rotated) << ", ";
  258. evaluator_->add(temp[a], tempctxt_rotated, newtemp[a]);
  259. multiply_power_of_X(temp[a], tempctxt_shifted, index_raw);
  260. //cout << "mul by x^pow: " << client.decryptor_->invariant_noise_budget(tempctxt_shifted) << ", ";
  261. multiply_power_of_X(tempctxt_rotated, tempctxt_rotatedshifted, index);
  262. // cout << "mul by x^pow: " << client.decryptor_->invariant_noise_budget(tempctxt_rotatedshifted) << ", ";
  263. // Enc(2^i x^j) if j = 0 (mod 2**i).
  264. evaluator_->add(tempctxt_shifted, tempctxt_rotatedshifted, newtemp[a + temp.size()]);
  265. }
  266. temp = newtemp;
  267. /*
  268. cout << "end: ";
  269. for (int h = 0; h < temp.size();h++){
  270. cout << client.decryptor_->invariant_noise_budget(temp[h]) << ", ";
  271. }
  272. cout << endl;
  273. */
  274. }
  275. // Last step of the loop
  276. vector<Ciphertext> newtemp(temp.size() << 1);
  277. int index_raw = (n << 1) - (1 << (logm - 1));
  278. int index = (index_raw * galois_elts[logm - 1]) % (n << 1);
  279. for (uint32_t a = 0; a < temp.size(); a++) {
  280. if (a >= (m - (1 << (logm - 1)))) { // corner case.
  281. evaluator_->multiply_plain(temp[a], two, newtemp[a]); // plain multiplication by 2.
  282. // cout << client.decryptor_->invariant_noise_budget(newtemp[a]) << ", ";
  283. } else {
  284. evaluator_->apply_galois(temp[a], galois_elts[logm - 1], galkey, tempctxt_rotated);
  285. evaluator_->add(temp[a], tempctxt_rotated, newtemp[a]);
  286. multiply_power_of_X(temp[a], tempctxt_shifted, index_raw);
  287. multiply_power_of_X(tempctxt_rotated, tempctxt_rotatedshifted, index);
  288. evaluator_->add(tempctxt_shifted, tempctxt_rotatedshifted, newtemp[a + temp.size()]);
  289. }
  290. }
  291. vector<Ciphertext>::const_iterator first = newtemp.begin();
  292. vector<Ciphertext>::const_iterator last = newtemp.begin() + m;
  293. vector<Ciphertext> newVec(first, last);
  294. return newVec;
  295. }
  296. inline void PIRServer::multiply_power_of_X(const Ciphertext &encrypted, Ciphertext &destination,
  297. uint32_t index) {
  298. auto coeff_mod_count = params_.coeff_modulus().size();
  299. auto coeff_count = params_.poly_modulus_degree();
  300. auto encrypted_count = encrypted.size();
  301. //cout << "coeff mod count for power of X = " << coeff_mod_count << endl;
  302. //cout << "coeff count for power of X = " << coeff_count << endl;
  303. // First copy over.
  304. destination = encrypted;
  305. // Prepare for destination
  306. // Multiply X^index for each ciphertext polynomial
  307. for (int i = 0; i < encrypted_count; i++) {
  308. for (int j = 0; j < coeff_mod_count; j++) {
  309. negacyclic_shift_poly_coeffmod(encrypted.data(i) + (j * coeff_count),
  310. coeff_count, index,
  311. params_.coeff_modulus()[j],
  312. destination.data(i) + (j * coeff_count));
  313. }
  314. }
  315. }
  316. inline void PIRServer::decompose_to_plaintexts_ptr(const Ciphertext &encrypted, Plaintext *plain_ptr, int logt) {
  317. vector<Plaintext> result;
  318. auto coeff_count = params_.poly_modulus_degree();
  319. auto coeff_mod_count = params_.coeff_modulus().size();
  320. auto encrypted_count = encrypted.size();
  321. uint64_t t1 = 1 << logt; // t1 <= t.
  322. uint64_t t1minusone = t1 -1;
  323. // A triple for loop. Going over polys, moduli, and decomposed index.
  324. for (int i = 0; i < encrypted_count; i++) {
  325. const uint64_t *encrypted_pointer = encrypted.data(i);
  326. for (int j = 0; j < coeff_mod_count; j++) {
  327. // populate one poly at a time.
  328. // create a polynomial to store the current decomposition value
  329. // which will be copied into the array to populate it at the current
  330. // index.
  331. double logqj = log2(params_.coeff_modulus()[j].value());
  332. //int expansion_ratio = ceil(logqj + exponent - 1) / exponent;
  333. int expansion_ratio = ceil(logqj / logt);
  334. // cout << "local expansion ratio = " << expansion_ratio << endl;
  335. uint64_t curexp = 0;
  336. for (int k = 0; k < expansion_ratio; k++) {
  337. // Decompose here
  338. for (int m = 0; m < coeff_count; m++) {
  339. plain_ptr[i * coeff_mod_count * expansion_ratio
  340. + j * expansion_ratio + k][m] =
  341. (*(encrypted_pointer + m + (j * coeff_count)) >> curexp) & t1minusone;
  342. }
  343. curexp += logt;
  344. }
  345. }
  346. }
  347. }
  348. vector<Plaintext> PIRServer::decompose_to_plaintexts(const Ciphertext &encrypted) {
  349. vector<Plaintext> result;
  350. auto coeff_count = params_.poly_modulus_degree();
  351. auto coeff_mod_count = params_.coeff_modulus().size();
  352. auto plain_bit_count = params_.plain_modulus().bit_count();
  353. auto encrypted_count = encrypted.size();
  354. // Generate powers of t.
  355. uint64_t plainMod = params_.plain_modulus().value();
  356. // A triple for loop. Going over polys, moduli, and decomposed index.
  357. for (int i = 0; i < encrypted_count; i++) {
  358. const uint64_t *encrypted_pointer = encrypted.data(i);
  359. for (int j = 0; j < coeff_mod_count; j++) {
  360. // populate one poly at a time.
  361. // create a polynomial to store the current decomposition value
  362. // which will be copied into the array to populate it at the current
  363. // index.
  364. int logqj = log2(params_.coeff_modulus()[j].value());
  365. int expansion_ratio = ceil(logqj / log2(plainMod));
  366. // cout << "expansion ratio = " << expansion_ratio << endl;
  367. uint64_t cur = 1;
  368. for (int k = 0; k < expansion_ratio; k++) {
  369. // Decompose here
  370. Plaintext temp(coeff_count);
  371. transform(encrypted_pointer + (j * coeff_count),
  372. encrypted_pointer + ((j + 1) * coeff_count),
  373. temp.data(),
  374. [cur, &plainMod](auto &in) { return (in / cur) % plainMod; }
  375. );
  376. result.emplace_back(move(temp));
  377. cur *= plainMod;
  378. }
  379. }
  380. }
  381. return result;
  382. }