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