pir_server.cpp 17 KB

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