pir_server.cpp 17 KB

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