pir_server.cpp 16 KB

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