pir_server.cpp 16 KB

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