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