pir_server.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. #include "pir_server.hpp"
  2. using namespace std;
  3. using namespace seal;
  4. using namespace seal::util;
  5. PIRServer::PIRServer(const EncryptionParameters &params, const PirParams &pir_params) :
  6. params_(params),
  7. pir_params_(pir_params),
  8. is_db_preprocessed_(false)
  9. {
  10. auto context = SEALContext::Create(params, false);
  11. evaluator_ = make_unique<Evaluator>(context);
  12. }
  13. // void PIRServer::update_parameters(const EncryptionParameters &expanded_params,
  14. // const PirParams &pir_params) {
  15. // // The only thing that can change is the plaintext modulus and pir_params
  16. // assert(expanded_params.poly_modulus_degree() == params_.poly_modulus_degree());
  17. // assert(expanded_params.coeff_modulus() == params_.coeff_modulus());
  18. // params_ = expanded_params;
  19. // pir_params_ = pir_params;
  20. // auto context = SEALContext::Create(expanded_params);
  21. // evaluator_ = make_unique<Evaluator>(context);
  22. // is_db_preprocessed_ = false;
  23. // // Update all the galois keys
  24. // for (std::pair<const int, GaloisKeys> &key : galoisKeys_) {
  25. // key.second.parms_id() = params_.parms_id();
  26. // }
  27. // }
  28. void PIRServer::preprocess_database() {
  29. if (!is_db_preprocessed_) {
  30. for (uint32_t i = 0; i < db_->size(); i++) {
  31. evaluator_->transform_to_ntt_inplace(
  32. db_->operator[](i), params_.parms_id());
  33. }
  34. is_db_preprocessed_ = true;
  35. }
  36. }
  37. // Server takes over ownership of db and will free it when it exits
  38. void PIRServer::set_database(unique_ptr<vector<Plaintext>> &&db) {
  39. if (!db) {
  40. throw invalid_argument("db cannot be null");
  41. }
  42. db_ = move(db);
  43. is_db_preprocessed_ = false;
  44. }
  45. void PIRServer::set_database(const std::unique_ptr<const std::uint8_t[]> &bytes,
  46. uint64_t ele_num, uint64_t ele_size) {
  47. uint32_t logt = floor(log2(params_.plain_modulus().value()));
  48. uint32_t N = params_.poly_modulus_degree();
  49. // number of FV plaintexts needed to represent all elements
  50. uint64_t total = plaintexts_per_db(logt, N, ele_num, ele_size);
  51. // number of FV plaintexts needed to create the d-dimensional matrix
  52. uint64_t prod = 1;
  53. for (uint32_t i = 0; i < pir_params_.nvec.size(); i++) {
  54. prod *= pir_params_.nvec[i];
  55. }
  56. uint64_t matrix_plaintexts = prod;
  57. assert(total <= matrix_plaintexts);
  58. auto result = make_unique<vector<Plaintext>>();
  59. result->reserve(matrix_plaintexts);
  60. uint64_t ele_per_ptxt = elements_per_ptxt(logt, N, ele_size);
  61. uint64_t bytes_per_ptxt = ele_per_ptxt * ele_size;
  62. uint64_t db_size = ele_num * ele_size;
  63. uint64_t coeff_per_ptxt = ele_per_ptxt * coefficients_per_element(logt, ele_size);
  64. assert(coeff_per_ptxt <= N);
  65. uint32_t offset = 0;
  66. for (uint64_t i = 0; i < total; i++) {
  67. uint64_t process_bytes = 0;
  68. if (db_size <= offset) {
  69. break;
  70. } else if (db_size < offset + bytes_per_ptxt) {
  71. process_bytes = db_size - offset;
  72. } else {
  73. process_bytes = bytes_per_ptxt;
  74. }
  75. // Get the coefficients of the elements that will be packed in plaintext i
  76. vector<uint64_t> coefficients = bytes_to_coeffs(logt, bytes.get() + offset, process_bytes);
  77. offset += process_bytes;
  78. uint64_t used = coefficients.size();
  79. assert(used <= coeff_per_ptxt);
  80. // Pad the rest with 1s
  81. for (uint64_t j = 0; j < (N - used); j++) {
  82. coefficients.push_back(1);
  83. }
  84. Plaintext plain;
  85. vector_to_plaintext(coefficients, plain);
  86. result->push_back(move(plain));
  87. }
  88. // Add padding to make database a matrix
  89. uint64_t current_plaintexts = result->size();
  90. assert(current_plaintexts <= total);
  91. #ifdef DEBUG
  92. cout << "adding: " << matrix_plaintexts - current_plaintexts
  93. << " FV plaintexts of padding (equivalent to: "
  94. << (matrix_plaintexts - current_plaintexts) * elements_per_ptxt(logtp, N, ele_size)
  95. << " elements)" << endl;
  96. #endif
  97. vector<uint64_t> padding(N, 1);
  98. for (uint64_t i = 0; i < (matrix_plaintexts - current_plaintexts); i++) {
  99. Plaintext plain;
  100. vector_to_plaintext(padding, plain);
  101. result->push_back(plain);
  102. }
  103. set_database(move(result));
  104. }
  105. void PIRServer::set_galois_key(std::uint32_t client_id, seal::GaloisKeys galkey) {
  106. galkey.parms_id() = params_.parms_id();
  107. galoisKeys_[client_id] = galkey;
  108. }
  109. PirReply PIRServer::generate_reply(PirQuery query, uint32_t client_id) {
  110. vector<uint64_t> nvec = pir_params_.nvec;
  111. uint64_t product = 1;
  112. for (uint32_t i = 0; i < nvec.size(); i++) {
  113. product *= nvec[i];
  114. }
  115. auto coeff_count = params_.poly_modulus_degree();
  116. vector<Plaintext> *cur = db_.get();
  117. vector<Plaintext> intermediate_plain; // decompose....
  118. auto pool = MemoryManager::GetPool();
  119. for (uint32_t i = 0; i < nvec.size(); i++) {
  120. uint64_t n_i = nvec[i];
  121. vector<Ciphertext> expanded_query = expand_query(query[i], n_i, client_id);
  122. // Transform expanded query to NTT, and ...
  123. for (uint32_t jj = 0; jj < expanded_query.size(); jj++) {
  124. evaluator_->transform_to_ntt_inplace(expanded_query[jj]);
  125. }
  126. // Transform plaintext to NTT. If database is pre-processed, can skip
  127. if ((!is_db_preprocessed_) || i > 0) {
  128. for (uint32_t jj = 0; jj < cur->size(); jj++) {
  129. evaluator_->transform_to_ntt_inplace((*cur)[jj], params_.parms_id());
  130. }
  131. }
  132. product /= n_i;
  133. vector<Ciphertext> intermediate(product);
  134. Ciphertext temp;
  135. for (uint64_t k = 0; k < product; k++) {
  136. evaluator_->multiply_plain(expanded_query[0], (*cur)[k], intermediate[k]);
  137. for (uint64_t j = 1; j < n_i; j++) {
  138. evaluator_->multiply_plain(expanded_query[j], (*cur)[k + j * product], temp);
  139. evaluator_->add_inplace(intermediate[k], temp); // Adds to first component.
  140. }
  141. }
  142. for (uint32_t jj = 0; jj < intermediate.size(); jj++) {
  143. evaluator_->transform_from_ntt_inplace(intermediate[jj]);
  144. }
  145. if (i == nvec.size() - 1) {
  146. return intermediate;
  147. } else {
  148. intermediate_plain.clear();
  149. intermediate_plain.reserve(pir_params_.expansion_ratio * product);
  150. cur = &intermediate_plain;
  151. auto tempplain = util::allocate<Plaintext>(
  152. pir_params_.expansion_ratio * product,
  153. pool, coeff_count);
  154. for (uint64_t rr = 0; rr < product; rr++) {
  155. decompose_to_plaintexts_ptr(intermediate[rr],
  156. tempplain.get() + rr * pir_params_.expansion_ratio);
  157. for (uint32_t jj = 0; jj < pir_params_.expansion_ratio; jj++) {
  158. auto offset = rr * pir_params_.expansion_ratio + jj;
  159. intermediate_plain.emplace_back(tempplain[offset]);
  160. }
  161. }
  162. product *= pir_params_.expansion_ratio; // multiply by expansion rate.
  163. }
  164. }
  165. // This should never get here
  166. assert(0);
  167. vector<Ciphertext> fail(1);
  168. return fail;
  169. }
  170. inline vector<Ciphertext> PIRServer::expand_query(const Ciphertext &encrypted, uint32_t m,
  171. uint32_t client_id) {
  172. #ifdef DEBUG
  173. uint64_t plainMod = params_.plain_modulus().value();
  174. cout << "PIRServer side plain modulus = " << plainMod << endl;
  175. #endif
  176. GaloisKeys &galkey = galoisKeys_[client_id];
  177. // Assume that m is a power of 2. If not, round it to the next power of 2.
  178. uint32_t logm = ceil(log2(m));
  179. Plaintext two("2");
  180. vector<int> galois_elts;
  181. auto n = params_.poly_modulus_degree();
  182. for (uint32_t i = 0; i < logm; i++) {
  183. galois_elts.push_back((n + exponentiate_uint64(2, i)) / exponentiate_uint64(2, i));
  184. }
  185. vector<Ciphertext> temp;
  186. temp.push_back(encrypted);
  187. Ciphertext tempctxt;
  188. Ciphertext tempctxt_rotated;
  189. Ciphertext tempctxt_shifted;
  190. Ciphertext tempctxt_rotatedshifted;
  191. for (uint32_t i = 0; i < logm - 1; i++) {
  192. vector<Ciphertext> newtemp(temp.size() << 1);
  193. // temp[a] = (j0 = a (mod 2**i) ? ) : Enc(x^{j0 - a}) else Enc(0). With
  194. // some scaling....
  195. int index_raw = (n << 1) - (1 << i);
  196. int index = (index_raw * galois_elts[i]) % (n << 1);
  197. for (uint32_t a = 0; a < temp.size(); a++) {
  198. evaluator_->apply_galois(temp[a], galois_elts[i], galkey, tempctxt_rotated);
  199. evaluator_->add(temp[a], tempctxt_rotated, newtemp[a]);
  200. multiply_power_of_X(temp[a], tempctxt_shifted, index_raw);
  201. multiply_power_of_X(tempctxt_rotated, tempctxt_rotatedshifted, index);
  202. // Enc(2^i x^j) if j = 0 (mod 2**i).
  203. evaluator_->add(tempctxt_shifted, tempctxt_rotatedshifted, newtemp[a + temp.size()]);
  204. }
  205. temp = newtemp;
  206. }
  207. // Last step of the loop
  208. vector<Ciphertext> newtemp(temp.size() << 1);
  209. int index_raw = (n << 1) - (1 << (logm - 1));
  210. int index = (index_raw * galois_elts[logm - 1]) % (n << 1);
  211. for (uint32_t a = 0; a < temp.size(); a++) {
  212. if (a >= (m - (1 << (logm - 1)))) { // corner case.
  213. evaluator_->multiply_plain(temp[a], two, newtemp[a]); // plain multiplication by 2.
  214. } else {
  215. evaluator_->apply_galois(temp[a], galois_elts[logm - 1], galkey, tempctxt_rotated);
  216. evaluator_->add(temp[a], tempctxt_rotated, newtemp[a]);
  217. multiply_power_of_X(temp[a], tempctxt_shifted, index_raw);
  218. multiply_power_of_X(tempctxt_rotated, tempctxt_rotatedshifted, index);
  219. evaluator_->add(tempctxt_shifted, tempctxt_rotatedshifted, newtemp[a + temp.size()]);
  220. }
  221. }
  222. vector<Ciphertext>::const_iterator first = newtemp.begin();
  223. vector<Ciphertext>::const_iterator last = newtemp.begin() + m;
  224. vector<Ciphertext> newVec(first, last);
  225. return newVec;
  226. }
  227. inline void PIRServer::multiply_power_of_X(const Ciphertext &encrypted, Ciphertext &destination,
  228. uint32_t index) {
  229. auto coeff_mod_count = params_.coeff_modulus().size();
  230. auto coeff_count = params_.poly_modulus_degree();
  231. auto encrypted_count = encrypted.size();
  232. // First copy over.
  233. destination = encrypted;
  234. // Prepare for destination
  235. // Multiply X^index for each ciphertext polynomial
  236. for (int i = 0; i < encrypted_count; i++) {
  237. for (int j = 0; j < coeff_mod_count; j++) {
  238. negacyclic_shift_poly_coeffmod(encrypted.data(i) + (j * coeff_count),
  239. coeff_count - 1, index,
  240. params_.coeff_modulus()[j],
  241. destination.data(i) + (j * coeff_count));
  242. }
  243. }
  244. }
  245. inline void PIRServer::decompose_to_plaintexts_ptr(const Ciphertext &encrypted, Plaintext *plain_ptr) {
  246. vector<Plaintext> result;
  247. auto coeff_count = params_.poly_modulus_degree();
  248. auto coeff_mod_count = params_.coeff_modulus().size();
  249. auto encrypted_count = encrypted.size();
  250. // Generate powers of t.
  251. uint64_t plainModMinusOne = params_.plain_modulus().value() - 1;
  252. int exp = ceil(log2(plainModMinusOne + 1));
  253. // A triple for loop. Going over polys, moduli, and decomposed index.
  254. for (int i = 0; i < encrypted_count; i++) {
  255. const uint64_t *encrypted_pointer = encrypted.data(i);
  256. for (int j = 0; j < coeff_mod_count; j++) {
  257. // populate one poly at a time.
  258. // create a polynomial to store the current decomposition value
  259. // which will be copied into the array to populate it at the current
  260. // index.
  261. int logqj = log2(params_.coeff_modulus()[j].value());
  262. int expansion_ratio = ceil(logqj + exp - 1) / exp;
  263. // cout << "expansion ratio = " << expansion_ratio << endl;
  264. uint64_t curexp = 0;
  265. for (int k = 0; k < expansion_ratio; k++) {
  266. // Decompose here
  267. for (int m = 0; m < coeff_count; m++) {
  268. plain_ptr[i * coeff_mod_count * expansion_ratio
  269. + j * expansion_ratio + k][m] =
  270. (*(encrypted_pointer + m + (j * coeff_count)) >> curexp) & plainModMinusOne;
  271. }
  272. curexp += exp;
  273. }
  274. }
  275. }
  276. }
  277. vector<Plaintext> PIRServer::decompose_to_plaintexts(const Ciphertext &encrypted) {
  278. vector<Plaintext> result;
  279. auto coeff_count = params_.poly_modulus_degree();
  280. auto coeff_mod_count = params_.coeff_modulus().size();
  281. auto plain_bit_count = params_.plain_modulus().bit_count();
  282. auto encrypted_count = encrypted.size();
  283. // Generate powers of t.
  284. uint64_t plainMod = params_.plain_modulus().value();
  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. int logqj = log2(params_.coeff_modulus()[j].value());
  294. int expansion_ratio = ceil(logqj / log2(plainMod));
  295. // cout << "expansion ratio = " << expansion_ratio << endl;
  296. uint64_t cur = 1;
  297. for (int k = 0; k < expansion_ratio; k++) {
  298. // Decompose here
  299. Plaintext temp(coeff_count);
  300. transform(encrypted_pointer + (j * coeff_count),
  301. encrypted_pointer + ((j + 1) * coeff_count),
  302. temp.data(),
  303. [cur, &plainMod](auto &in) { return (in / cur) % plainMod; }
  304. );
  305. result.emplace_back(move(temp));
  306. cur *= plainMod;
  307. }
  308. }
  309. }
  310. return result;
  311. }