pir_server.cpp 15 KB

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