pir_server.cpp 14 KB

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