pir_server.cpp 16 KB

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