pir_server.cpp 16 KB

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