PIRReplyGeneratorNFL_internal.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. /* Copyright (C) 2014 Carlos Aguilar Melchor, Joris Barrier, Marc-Olivier Killijian
  2. * This file is part of XPIR.
  3. *
  4. * XPIR is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * XPIR is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with XPIR. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include "PIRReplyGeneratorNFL_internal.hpp"
  18. #include "sys/time.h"
  19. //#define SIMULATE_PRE_NFL_DATA //Use this to simulate imported data is in NFL form
  20. //#define TEST_NFL_PERF_ITERATIONS //Loop to simulate very large databases
  21. //#define SNIFFER_CHUNK_BYTESIZE 12800
  22. //#define SNIFFER_CHUNK_BYTESIZE 2560
  23. //#define SNIFFER_CHUNK_BYTESIZE 1500
  24. //#define SNIFFER_CHUNK_BYTESIZE 600
  25. //#define SNIFFER //Use this to activate a sniffer like behavior
  26. PIRReplyGeneratorNFL_internal::PIRReplyGeneratorNFL_internal():
  27. lwe(false),
  28. currentMaxNbPolys(0),
  29. queriesBuf(NULL),
  30. current_query_index(0),
  31. current_dim_index(0),
  32. input_data(NULL),
  33. cryptoMethod(NULL)
  34. {
  35. }
  36. /**
  37. * Constructor of the class.
  38. * Params :
  39. * - vector <File*>& database : reference of a File pointer vector.
  40. * - PIRParameters& param : reference to a PIRParameters object.
  41. **/
  42. PIRReplyGeneratorNFL_internal::PIRReplyGeneratorNFL_internal( PIRParameters& param, DBHandler* db):
  43. lwe(false),
  44. currentMaxNbPolys(0),
  45. GenericPIRReplyGenerator(param,db),
  46. queriesBuf(NULL),
  47. current_query_index(0),
  48. current_dim_index(0),
  49. input_data(NULL),
  50. cryptoMethod(NULL)
  51. {
  52. // cryptoMethod will be set later by setCryptoMethod
  53. }
  54. void PIRReplyGeneratorNFL_internal::importFakeData(uint64_t plaintext_nbr)
  55. {
  56. uint64_t files_nbr = 1;
  57. for (unsigned int i = 0 ; i < pirParam.d ; i++) files_nbr *= pirParam.n[i];
  58. uint64_t plain_bytesize = cryptoMethod->getnflInstance().getpolyDegree()*cryptoMethod->getnflInstance().getnbModuli()*8;
  59. dbhandler = new DBGenerator(files_nbr, plaintext_nbr*plain_bytesize, true);
  60. currentMaxNbPolys = plaintext_nbr;
  61. importDataNFL(0, plaintext_nbr*plain_bytesize);
  62. }
  63. /**
  64. * Convert raw data from file in usable NFL data.
  65. **/
  66. void PIRReplyGeneratorNFL_internal::importDataNFL(uint64_t offset, uint64_t bytes_per_file)
  67. {
  68. uint64_t fileByteSize = min(bytes_per_file, dbhandler->getmaxFileBytesize()-offset);
  69. uint64_t theoretical_files_nbr = 1;
  70. uint64_t nbFiles = dbhandler->getNbStream();
  71. for (unsigned int i = 0 ; i < pirParam.d ; i++) theoretical_files_nbr *= pirParam.n[i];
  72. input_data = (lwe_in_data *) malloc(sizeof(lwe_in_data)*theoretical_files_nbr);
  73. char *rawBits = (char*)calloc(fileByteSize*pirParam.alpha, sizeof(char));
  74. currentMaxNbPolys=0;
  75. #ifdef PERF_TIMERS
  76. double vtstart = omp_get_wtime();
  77. bool wasVerbose = false;
  78. uint64_t lastindex = 0;
  79. #endif
  80. // For global time measurement
  81. double start = omp_get_wtime();
  82. int nbruns=ceil((double)nbFiles/pirParam.alpha);
  83. // WARNING this section should not be multithreade as rawbits is shared and readAggregatedStream
  84. // is not threadsafe
  85. for (int i=0; i < nbruns; i++)
  86. {
  87. dbhandler->readAggregatedStream(i, pirParam.alpha, offset, bytes_per_file, rawBits);
  88. #ifdef SIMULATE_PRE_NFL_DATA
  89. uint64_t abssize = cryptoMethod->getPublicParameters().getAbsorptionBitsize();
  90. uint64_t polysize = cryptoMethod->getpolyDegree() * cryptoMethod->getnbModuli()*sizeof(uint64_t);
  91. uint64_t nbpolys = ceil((double)fileByteSize * pirParam.alpha * 8 / abssize);
  92. input_data[i].p = (poly64*) malloc(nbpolys*sizeof(poly64*));
  93. input_data[i].p[0] = (poly64) malloc(nbpolys*polysize);
  94. for (unsigned j = 0; j < nbpolys ; j++)
  95. {
  96. input_data[i].p[j] = input_data[i].p[0]+j*polysize/8;
  97. memcpy(input_data[i].p[j], rawBits, min(fileByteSize, polysize));
  98. }
  99. input_data[i].nbPolys = nbpolys;
  100. #else
  101. input_data[i].p = cryptoMethod->deserializeDataNFL((unsigned char**)&rawBits, (uint64_t) 1, fileByteSize*pirParam.alpha*GlobalConstant::kBitsPerByte, input_data[i].nbPolys);
  102. #endif
  103. #ifdef PERF_TIMERS
  104. // Give some feedback if it takes too long
  105. double vtstop = omp_get_wtime();
  106. if (vtstop - vtstart > 1)
  107. {
  108. vtstart = vtstop;
  109. std::cout <<"PIRReplyGeneratorNFL_internal: Element " << i+1 << "/" << nbruns << " imported\r" << std::flush;
  110. wasVerbose = true;
  111. lastindex = i+1;
  112. }
  113. #endif
  114. }
  115. for (int i=0; i < nbruns; i++)
  116. if (input_data[i].nbPolys>currentMaxNbPolys) currentMaxNbPolys=input_data[i].nbPolys;
  117. #ifdef PERF_TIMERS
  118. // If feedback was given say we finished
  119. if (wasVerbose && lastindex != nbFiles) std::cout <<"PIRReplyGeneratorNFL_internal: Element " << nbruns << "/" << nbFiles/pirParam.alpha << " imported" << std::endl;
  120. #endif
  121. /** FILE PADDING **/
  122. for (uint64_t i = ceil((double)nbFiles/pirParam.alpha) ; i < theoretical_files_nbr ; i++)
  123. {
  124. input_data[i].p = (poly64 *) malloc(currentMaxNbPolys*sizeof(poly64));
  125. input_data[i].p[0] = (poly64) calloc(cryptoMethod->getpolyDegree()*cryptoMethod->getnbModuli()*currentMaxNbPolys,sizeof(uint64_t));
  126. for (uint64_t j = 1 ; j < currentMaxNbPolys ; j++) input_data[i].p[j] = input_data[i].p[0]+cryptoMethod->getpolyDegree()*cryptoMethod->getnbModuli()*j;
  127. input_data[i].nbPolys = currentMaxNbPolys;
  128. }
  129. free(rawBits);
  130. std::cout<<"PIRReplyGeneratorNFL_internal: Finished importing the database in " << omp_get_wtime() - start << " seconds" << std::endl;
  131. }
  132. #ifdef SNIFFER
  133. imported_database_t PIRReplyGeneratorNFL_internal::generateReplyGeneric(bool keep_imported_data)
  134. {
  135. imported_database_t database_wrapper;
  136. boost::mutex::scoped_lock l(mutex);
  137. const uint64_t chunkBytesize = SNIFFER_CHUNK_BYTESIZE;
  138. const uint64_t iterations = dbhandler->getmaxFileBytesize()/(chunkBytesize+1);
  139. // std::ifstream *is = dbhandler->openStream(0,0);
  140. const uint64_t nbFiles = dbhandler->getNbStream();
  141. const unsigned int polysize = cryptoMethod->getpolyDegree()*cryptoMethod->getnbModuli();
  142. currentMaxNbPolys=0;
  143. lwe_in_data *input = new lwe_in_data[iterations];
  144. lwe_cipher *resul = new lwe_cipher[iterations];
  145. uint64_t index;
  146. lwe_query **queries;
  147. char **rawBits = (char**) malloc(iterations*sizeof(char*));
  148. cryptoMethod->setandgetAbsBitPerCiphertext(1);
  149. queries = queriesBuf[0];
  150. const uint64_t mask = (1<<((int)log2(nbFiles)))-1;
  151. for (uint64_t it = 0 ; it < iterations ; it++)
  152. {
  153. resul[it].a = (uint64_t *) malloc(2*polysize*sizeof(uint64_t));
  154. resul[it].b = (uint64_t *) resul[it].a + polysize;
  155. rawBits[it] = (char*)malloc(((chunkBytesize)*sizeof(char)+sizeof(int)));
  156. }
  157. double start = omp_get_wtime();
  158. #pragma omp parallel for firstprivate(input,queries,resul)
  159. for (uint64_t it = 0 ; it < iterations ; it++)
  160. {
  161. dbhandler->readStream(0, rawBits[it], chunkBytesize+sizeof(int));
  162. input[it].p = cryptoMethod->deserializeDataNFL((unsigned char**)&(rawBits[it]), (uint64_t) 1, chunkBytesize*GlobalConstant::kBitsPerByte, input[it].nbPolys);
  163. index = *(int *)(rawBits[it]+chunkBytesize) & mask;
  164. cryptoMethod->mul(resul[it], input[it], queries[0][index],queries[1][index], 0, 0);
  165. }
  166. double end = omp_get_wtime();
  167. std::cout<<"PIRReplyGeneratorNFL_internal: Finished processing the sniffed data in " << end - start << " seconds" << std::endl;
  168. std::cout<<"PIRReplyGeneratorNFL_internal: Processing throughput " << (double)chunkBytesize*8*iterations / ((end - start)*1000000000ULL) << " Gbps" << std::endl;
  169. return database_wrapper;
  170. }
  171. #else
  172. imported_database_t PIRReplyGeneratorNFL_internal::generateReplyGeneric(bool keep_imported_data)
  173. {
  174. imported_database_t database_wrapper;
  175. uint64_t usable_memory, database_size, max_memory_per_file, max_readable_size, nbr_of_iterations;
  176. double start, end;
  177. // Init database_wrapper to NULL values so that we are able to know if it has been initialized
  178. database_wrapper.imported_database_ptr = NULL;
  179. database_wrapper.nbElements = 0;
  180. database_wrapper.polysPerElement = 0;
  181. database_wrapper.beforeImportElementBytesize = 0;
  182. // Don't use more than half of the computer's memory
  183. usable_memory = getTotalSystemMemory()/2;
  184. database_size = dbhandler->getmaxFileBytesize() * dbhandler->getNbStream();
  185. #ifndef TEST_NFL_PERF_ITERATIONS
  186. // This is the maximum amount of data per file we can get in memory
  187. max_memory_per_file = usable_memory / dbhandler->getNbStream();
  188. // Given the expansion factor of importation we get the max we can read per file
  189. max_readable_size = max_memory_per_file / 4 ;
  190. // Reduce it so that we have full absorption in all the ciphertexts sent
  191. max_readable_size = (max_readable_size * GlobalConstant::kBitsPerByte / cryptoMethod->getPublicParameters().getAbsorptionBitsize(0)) * cryptoMethod->getPublicParameters().getAbsorptionBitsize(0)/GlobalConstant::kBitsPerByte;
  192. #else
  193. // For our tests we will need to have databases of an integer amount of gigabits
  194. max_readable_size = 1280000000UL/dbhandler->getNbStream();
  195. #endif
  196. // If we reduced it too much set it at least to a ciphertext
  197. if (max_readable_size == 0) max_readable_size = cryptoMethod->getPublicParameters().getAbsorptionBitsize(0);
  198. // Ensure it is not larger than maxfilebytesize
  199. max_readable_size = min(max_readable_size, dbhandler->getmaxFileBytesize());
  200. // Given readable size we get how many iterations we need
  201. nbr_of_iterations = ceil((double)dbhandler->getmaxFileBytesize()/max_readable_size);
  202. #ifndef TEST_NFL_PERF_ITERATIONS
  203. // If aggregation is used we cannot iterate
  204. if ((pirParam.alpha != 1 || pirParam.d > 1) && nbr_of_iterations > 1)
  205. {
  206. std::cout << "PIRReplyGeneratorNFL_internal: Cannot handle aggregation or dimensions on databases requiring multiple iterations" << std::endl;
  207. std::cout << "PIRReplyGeneratorNFL_internal: Handling the database on a single iteration, this can cause memory issues ..." << std::endl;
  208. nbr_of_iterations = 1;
  209. max_readable_size = dbhandler->getmaxFileBytesize();
  210. }
  211. // If we cannot read the whole database we cannot store it precomputed
  212. if (nbr_of_iterations > 1) keep_imported_data = false;
  213. #endif
  214. // If we need to do more than an iteration say it
  215. if (nbr_of_iterations > 1)
  216. {
  217. std::cout << "PIRReplyGeneratorNFL_internal: Database is considered too large, processing it in "
  218. << nbr_of_iterations << " iterations" << std::endl;
  219. }
  220. start = omp_get_wtime();
  221. // #pragma omp parallel for
  222. for (unsigned iteration = 0; iteration < nbr_of_iterations; iteration++)
  223. {
  224. if (nbr_of_iterations > 1) cout << "PIRReplyGeneratorNFL_internal: Iteration " << iteration << endl;
  225. repliesIndex = computeReplySizeInChunks(iteration*max_readable_size);
  226. // Import a chunk of max_readable_size bytes per file with an adapted offset
  227. importDataNFL(iteration*max_readable_size, max_readable_size);
  228. if(keep_imported_data && iteration == nbr_of_iterations - 1) // && added for Perf test but is no harmful
  229. {
  230. database_wrapper.polysPerElement = currentMaxNbPolys;
  231. }
  232. boost::mutex::scoped_lock l(mutex);
  233. repliesAmount = computeReplySizeInChunks(dbhandler->getmaxFileBytesize());
  234. generateReply();
  235. end = omp_get_wtime();
  236. if(keep_imported_data && iteration == nbr_of_iterations - 1) // && added for Perf test but is no harmful
  237. {
  238. database_wrapper.imported_database_ptr = (void*)input_data;
  239. database_wrapper.beforeImportElementBytesize = dbhandler->getmaxFileBytesize();
  240. database_wrapper.nbElements = dbhandler->getNbStream();
  241. }
  242. else
  243. {
  244. freeInputData();
  245. }
  246. }
  247. std::cout<<"PIRReplyGeneratorNFL_internal: Total process time " << end - start << " seconds" << std::endl;
  248. std::cout<<"PIRReplyGeneratorNFL_internal: DB processing throughput " << 8*database_size/(end - start) << "bps" << std::endl;
  249. std::cout<<"PIRReplyGeneratorNFL_internal: Client cleartext reception throughput " << 8*dbhandler->getmaxFileBytesize()/(end - start) << "bps" << std::endl;
  250. freeQueries();
  251. return database_wrapper;
  252. }
  253. #endif
  254. // Function used to generate a PIR reply if:
  255. // - database is small enough to be kept in memory
  256. // - it has already been imported to it
  257. void PIRReplyGeneratorNFL_internal::generateReplyGenericFromData(const imported_database_t database)
  258. {
  259. #ifndef TEST_NFL_PERF_ITERATIONS
  260. input_data = (lwe_in_data*) database.imported_database_ptr;
  261. currentMaxNbPolys = database.polysPerElement;
  262. boost::mutex::scoped_lock l(mutex);
  263. double start = omp_get_wtime();
  264. repliesAmount = computeReplySizeInChunks(database.beforeImportElementBytesize);
  265. generateReply();
  266. #else
  267. uint64_t max_readable_size, database_size, nbr_of_iterations;
  268. database_size = database.beforeImportElementBytesize * database.nbElements;
  269. max_readable_size = 1280000000UL/database.nbElements;
  270. // Ensure it is not larger than maxfilebytesize
  271. max_readable_size = min(max_readable_size, database.beforeImportElementBytesize);
  272. // Given readable size we get how many iterations we need
  273. nbr_of_iterations = ceil((double)database.beforeImportElementBytesize/max_readable_size);
  274. boost::mutex::scoped_lock l(mutex);
  275. double start = omp_get_wtime();
  276. for (unsigned iteration = 0; iteration < nbr_of_iterations; iteration++)
  277. {
  278. input_data = (lwe_in_data*) database.imported_database_ptr;
  279. currentMaxNbPolys = database.polysPerElement;
  280. repliesAmount = computeReplySizeInChunks(database.beforeImportElementBytesize);
  281. generateReply();
  282. }
  283. freeInputData();
  284. #endif
  285. double end = omp_get_wtime();
  286. std::cout<<"PIRReplyGeneratorNFL_internal: Total process time " << end - start << " seconds" << std::endl;
  287. std::cout<<"PIRReplyGeneratorNFL_internal: DB processing throughput " << 8*dbhandler->getmaxFileBytesize()*dbhandler->getNbStream()/(end - start) << "bps" << std::endl;
  288. std::cout<<"PIRReplyGeneratorNFL_internal: Client cleartext reception throughput " << 8*dbhandler->getmaxFileBytesize()/(end - start) << "bps" << std::endl;
  289. freeQueries();
  290. }
  291. /**
  292. * Prepare reply and start absoptions.
  293. **/
  294. void PIRReplyGeneratorNFL_internal::generateReply()
  295. {
  296. lwe_in_data *in_data = input_data;
  297. lwe_cipher **inter_reply;
  298. #ifdef SHOUP
  299. lwe_query **queries;
  300. #else
  301. lwe_query *queries;
  302. #endif
  303. uint64_t old_reply_elt_nbr = 0;
  304. uint64_t reply_elt_nbr = 1;
  305. uint64_t old_poly_nbr = 1;
  306. // Allocate memory for the reply array
  307. if (repliesArray != NULL) freeResult();
  308. repliesArray = (char**)calloc(repliesAmount,sizeof(char*));
  309. // Start global timers
  310. double start = omp_get_wtime();
  311. #ifdef PERF_TIMERS
  312. double vtstart = start;
  313. bool wasVerbose = false;
  314. #endif
  315. for (unsigned int i = 0 ; i < pirParam.d ; i++) // For each recursion level
  316. {
  317. old_reply_elt_nbr = reply_elt_nbr;
  318. reply_elt_nbr = 1;
  319. for (unsigned int j = i + 1 ; j < pirParam.d ; j++ ) reply_elt_nbr *= pirParam.n[j];
  320. #ifdef DEBUG
  321. cout << "PIRReplyGeneratorNFL_internal: currentMaxNbPolys = " << currentMaxNbPolys << endl;
  322. #endif
  323. inter_reply = new lwe_cipher*[reply_elt_nbr]();
  324. queries = queriesBuf[i];
  325. for (uint64_t j = 0 ; j < reply_elt_nbr ; j++) // Boucle de reply_elt_nbr PIR
  326. {
  327. inter_reply[j] = new lwe_cipher[currentMaxNbPolys];
  328. // Warning of the trick in case SHOUP is defined : we cast quesries to a (lwe_query*) and will have to uncast it
  329. generateReply((lwe_query*)queries , in_data + (pirParam.n[i] * j ), i, inter_reply[j]);
  330. #ifdef DEBUG_WITH_FILE_OUTPUT
  331. if (i ==0 && j==1) {
  332. std::ofstream file(std::string("output_level_"+ std::to_string(i)).c_str(), std::ios::out| std::ios::binary);
  333. for (int k = 0 ; k < currentMaxNbPolys ; k++)
  334. {
  335. file.write((char*)inter_reply[j][k].a,1024*2*8);
  336. }
  337. file.close();
  338. }
  339. #endif
  340. #ifdef PERF_TIMERS
  341. // Give some feedback if it takes too long
  342. double vtstop = omp_get_wtime();
  343. if (vtstop - vtstart > 1)
  344. {
  345. vtstart = vtstop;
  346. std::cout <<"PIRReplyGeneratorNFL_internal: Reply " << j+1 << "/" << reply_elt_nbr << " generated\r" << std::flush;
  347. wasVerbose = true;
  348. }
  349. #endif
  350. }
  351. /*****************/
  352. /*MEMORY CLEANING*/
  353. /*****************/
  354. #ifdef DEBUG
  355. if ( i > 0)
  356. {
  357. cout << "PIRReplyGeneratorNFL_internal: reply_elt_nbr_OLD: " << old_reply_elt_nbr << endl;
  358. }
  359. #endif
  360. if (i > 0)
  361. {
  362. for (int j = 0 ; j < old_reply_elt_nbr ; j++)
  363. {
  364. free(in_data[j].p[0]);
  365. free(in_data[j].p);
  366. }
  367. delete[] in_data;
  368. }
  369. if (i < pirParam.d - 1) {
  370. old_poly_nbr = currentMaxNbPolys;
  371. in_data = fromResulttoInData(inter_reply, reply_elt_nbr, i);
  372. }
  373. for (uint64_t j = 0 ; j < reply_elt_nbr ; j++) {
  374. for (uint64_t k = 0 ; (k < old_poly_nbr) && (i < pirParam.d - 1); k++){
  375. free(inter_reply[j][k].a);
  376. inter_reply[j][k].a = NULL;
  377. }
  378. delete[] inter_reply[j];
  379. inter_reply[j] = NULL;
  380. }
  381. delete[] inter_reply; // allocated with a 'new' above.
  382. inter_reply = NULL;
  383. }
  384. // Compute execution time
  385. printf( "PIRReplyGeneratorNFL_internal: Global reply generation took %f (omp)seconds\n", omp_get_wtime() - start);
  386. }
  387. double PIRReplyGeneratorNFL_internal::generateReplySimulation(const PIRParameters& pir_params, uint64_t plaintext_nbr)
  388. {
  389. setPirParams((PIRParameters&)pir_params);
  390. pushFakeQuery();
  391. importFakeData(plaintext_nbr);
  392. repliesAmount = computeReplySizeInChunks(plaintext_nbr*cryptoMethod->getPublicParameters().getCiphertextBitsize() / CHAR_BIT);
  393. repliesIndex = 0;
  394. double start = omp_get_wtime();
  395. generateReply();
  396. double result = omp_get_wtime() - start;
  397. freeQueries();
  398. freeInputData();
  399. freeResult();
  400. delete dbhandler;
  401. return result;
  402. }
  403. double PIRReplyGeneratorNFL_internal::precomputationSimulation(const PIRParameters& pir_params, uint64_t plaintext_nbr)
  404. {
  405. NFLlib *nflptr = &(cryptoMethod->getnflInstance());
  406. setPirParams((PIRParameters&)pir_params);
  407. pushFakeQuery();
  408. importFakeData(plaintext_nbr);
  409. uint64_t files_nbr = 1;
  410. for (unsigned int i = 0 ; i < pir_params.d ; i++) files_nbr *= pir_params.n[i];
  411. double start = omp_get_wtime();
  412. for (unsigned int i = 0 ; i < files_nbr ; i++)
  413. {
  414. poly64 *tmp;
  415. tmp = cryptoMethod->deserializeDataNFL((unsigned char**)(input_data[i].p), (uint64_t) plaintext_nbr, cryptoMethod->getPublicParameters().getCiphertextBitsize()/2 , input_data[i].nbPolys);
  416. free(tmp[0]);
  417. tmp = NULL;
  418. }
  419. double result = omp_get_wtime() - start;
  420. std::cout << "PIRReplyGeneratorNFL_internal: Deserialize took " << result << " (omp)seconds" << std::endl;
  421. freeQueries();
  422. freeInputData();
  423. freeResult();
  424. delete dbhandler;
  425. return result;
  426. }
  427. /**
  428. * Multiply each query parts by each files and sum the result.
  429. * Params :
  430. * - lwe_queries* : the query ;
  431. * - lwe_in_data* : data to be processed.
  432. * - int begin_data : index where begins the data absorption
  433. * - int lvl : recursion level ;
  434. * - lwe_cipher* result : Array to store the result.
  435. **/
  436. void PIRReplyGeneratorNFL_internal::generateReply( lwe_query *queries_,
  437. lwe_in_data* data,
  438. unsigned int lvl,
  439. lwe_cipher* result)
  440. {
  441. #ifdef SHOUP
  442. lwe_query **queries=(lwe_query**)queries_;
  443. #else
  444. lwe_query *queries=queries_;
  445. #endif
  446. unsigned int query_size = pirParam.n[lvl];
  447. #ifdef PERF_TIMERS
  448. bool wasVerbose = false;
  449. double vtstart = omp_get_wtime();
  450. #endif
  451. // In order to parallelize we must ensure replies are somehow ordered
  452. // (see comment at the end of PIRReplyExtraction)
  453. //#pragma omp parallel for firstprivate(result,data, lvl, queries)
  454. #ifdef MULTI_THREAD
  455. # pragma omp parallel for
  456. #endif
  457. for (unsigned int current_poly=0 ; current_poly < currentMaxNbPolys ; current_poly++)
  458. {
  459. posix_memalign((void**) &(result[current_poly].a), 32,
  460. 2*cryptoMethod->getpolyDegree()*cryptoMethod->getnbModuli()*sizeof(uint64_t));
  461. memset(result[current_poly].a,0,
  462. 2*cryptoMethod->getpolyDegree()*cryptoMethod->getnbModuli()*sizeof(uint64_t));
  463. result[current_poly].b = (uint64_t *) result[current_poly].a +
  464. cryptoMethod->getpolyDegree()*cryptoMethod->getnbModuli();
  465. for (unsigned int offset = 0; offset < query_size; offset += 200)
  466. {
  467. for (unsigned int query_index = offset, ggg=0; query_index < query_size && ggg < 200 ;
  468. query_index++, ggg++)
  469. {
  470. #ifdef SHOUP
  471. #ifdef CRYPTO_DEBUG
  472. if(current_poly==0)
  473. {
  474. std::cout<<"Query poped.a ";NFLTools::print_poly64hex(queries[0][query_index].a,4);
  475. if (lwe)
  476. {
  477. std::cout<<"Query poped.b ";NFLTools::print_poly64hex(queries[0][query_index].b,4);
  478. }
  479. std::cout<<"Query poped.a' ";NFLTools::print_poly64hex(queries[1][query_index].a,4);
  480. if (lwe)
  481. {
  482. std::cout<<"Query poped.b' ";NFLTools::print_poly64hex(queries[1][query_index].b,4);
  483. }
  484. }
  485. #endif
  486. cryptoMethod->mulandadd(result[current_poly], data[query_index], queries[0][query_index],
  487. queries[1][query_index], current_poly, lvl);
  488. #else
  489. cryptoMethod->mulandadd(result[current_poly], data[query_index], queries[query_index],
  490. current_poly, lvl);
  491. #endif
  492. }
  493. if ( lvl == pirParam.d-1 && offset + 200 >= query_size)
  494. {
  495. // Watchout lwe_cipher.a and .b need to be allocated contiguously
  496. repliesArray[repliesIndex+current_poly] = (char*)result[current_poly].a;
  497. }
  498. #ifdef PERF_TIMERS
  499. // Give some feedback if it takes too long
  500. double vtstop = omp_get_wtime();
  501. if (vtstop - vtstart > 1)
  502. {
  503. vtstart = vtstop;
  504. if(currentMaxNbPolys != 1) std::cout <<"PIRReplyGeneratorNFL_internal: Dealt with chunk " <<
  505. current_poly+1 << "/" << currentMaxNbPolys << "\r" << std::flush;
  506. wasVerbose = true;
  507. }
  508. #endif
  509. }
  510. }
  511. #ifdef PERF_TIMERS
  512. if (wasVerbose) std::cout <<" \r" << std::flush;
  513. #endif
  514. }
  515. // New version using the multiple buffer serialize function
  516. lwe_in_data* PIRReplyGeneratorNFL_internal::fromResulttoInData(lwe_cipher** inter_reply, uint64_t reply_elt_nbr, unsigned int reply_rec_lvl)
  517. {
  518. uint64_t in_data2b_bytes = cryptoMethod->getPublicParameters().getAbsorptionBitsize()/8;
  519. uint64_t in_data2b_nbr_polys = ceil((double(currentMaxNbPolys * cryptoMethod->getPublicParameters().getCiphertextBitsize())/8.)/double(in_data2b_bytes));
  520. lwe_in_data *in_data2b = new lwe_in_data[reply_elt_nbr]();
  521. uint64_t **bufferOfBuffers = (uint64_t **) calloc(currentMaxNbPolys,sizeof(uint64_t*));
  522. //For each element in the reply
  523. for (uint64_t i = 0 ; i < reply_elt_nbr ; i++)
  524. {
  525. //Build the buffer of buffers
  526. for (uint64_t j = 0 ; j < currentMaxNbPolys ; j++)
  527. {
  528. bufferOfBuffers[j]=inter_reply[i][j].a;
  529. }
  530. // Ciphertexts can be serialized in a single block as a,b are allocatted contiguously
  531. in_data2b[i].p = cryptoMethod->deserializeDataNFL((unsigned char**)bufferOfBuffers,
  532. currentMaxNbPolys,
  533. cryptoMethod->getPublicParameters().getCiphertextBitsize(),
  534. in_data2b[i].nbPolys);
  535. }
  536. free(bufferOfBuffers);
  537. currentMaxNbPolys = in_data2b_nbr_polys;
  538. return in_data2b;
  539. }
  540. //// Original function
  541. //lwe_in_data* PIRReplyGeneratorNFL_internal::fromResulttoInData(lwe_cipher** inter_reply, uint64_t reply_elt_nbr, unsigned int reply_rec_lvl)
  542. //{
  543. // uint64_t in_data2b_bytes = cryptoMethod->getPublicParameters().getAbsorptionBitsize()/8;
  544. // uint64_t in_data2b_polys_per_reply_poly = ceil((double)(cryptoMethod->getPublicParameters().getCiphertextBitsize()/8)/in_data2b_bytes);
  545. // uint64_t in_data2b_nbr_polys = currentMaxNbPolys * in_data2b_polys_per_reply_poly;
  546. //
  547. // lwe_in_data *in_data2b = new lwe_in_data[reply_elt_nbr]();
  548. // lwe_in_data tmp_in_data;
  549. //
  550. // //For each element in the reply
  551. // for (uint64_t i = 0 ; i < reply_elt_nbr ; i++)
  552. // {
  553. // in_data2b[i].p = (poly64 *) malloc(in_data2b_nbr_polys*sizeof(poly64));
  554. // in_data2b[i].nbPolys = 0;
  555. //
  556. // // For each polynomial in a reply element
  557. // for (uint64_t j = 0 ; j < currentMaxNbPolys ; j++)
  558. // {
  559. // // Ciphertexts can be serialized in a single block as a,b are allocatted contiguously
  560. // tmp_in_data.p = cryptoMethod->deserializeDataNFL((unsigned char*)inter_reply[i][j].a, cryptoMethod->getPublicParameters().getCiphertextBitsize(), tmp_in_data.nbPolys);
  561. // for (uint64_t k = 0 ; k < in_data2b_polys_per_reply_poly; k++)
  562. // {
  563. // in_data2b[i].p[k + j * in_data2b_polys_per_reply_poly] = tmp_in_data.p[k];
  564. // }
  565. // in_data2b[i].nbPolys += in_data2b_polys_per_reply_poly;
  566. // }
  567. // delete[] inter_reply[i];
  568. // }
  569. // delete[] inter_reply;
  570. //
  571. // currentMaxNbPolys = in_data2b_nbr_polys;
  572. // return in_data2b;
  573. //}
  574. /**
  575. * Compute Reply Size une chunks.
  576. * WARNING blocking function.
  577. **/
  578. unsigned long PIRReplyGeneratorNFL_internal::computeReplySizeInChunks(unsigned long int maxFileBytesize)
  579. {
  580. using namespace GlobalConstant;
  581. unsigned int out = ceil((double)maxFileBytesize*kBitsPerByte*pirParam.alpha/cryptoMethod->getPublicParameters().getAbsorptionBitsize(0));
  582. for (unsigned int i = 1; i < pirParam.d; i++) {
  583. out = ceil(out * double(cryptoMethod->getPublicParameters().getCiphBitsizeFromRecLvl(i)/kBitsPerByte) / double(cryptoMethod->getPublicParameters().getAbsorptionBitsize(i) / kBitsPerByte));
  584. }
  585. return out;
  586. }
  587. /**
  588. * Overloaded fonction from GenericPIRReplyGenerator.
  589. * Initalise queriesBuf.
  590. **/
  591. void PIRReplyGeneratorNFL_internal::initQueriesBuffer() {
  592. const unsigned int nbQueriesBuf=pirParam.d;;
  593. #ifdef SHOUP
  594. queriesBuf = new lwe_query**[nbQueriesBuf]();
  595. for (unsigned int i = 0 ; i < nbQueriesBuf ; i++)
  596. {
  597. queriesBuf[i] = new lwe_query*[2];
  598. queriesBuf[i][0] = new lwe_query[pirParam.n[i]]();
  599. queriesBuf[i][1] = new lwe_query[pirParam.n[i]]();
  600. }
  601. #else
  602. queriesBuf = new lwe_query*[nbQueriesBuf]();
  603. for (unsigned int i = 0 ; i < nbQueriesBuf ; i++)
  604. {
  605. queriesBuf[i] = new lwe_query[pirParam.n[i]]();
  606. }
  607. #endif
  608. #ifdef DEBUG
  609. std::cout<<"Created a queriesBuf for "<<nbQueriesBuf<<" queries"<<std::endl;
  610. #endif
  611. }
  612. void PIRReplyGeneratorNFL_internal::pushFakeQuery()
  613. {
  614. char* query_element;
  615. for (unsigned int dim = 0 ; dim < pirParam.d ; dim++) {
  616. for(unsigned int j = 0 ; j < pirParam.n[dim] ; j++) {
  617. query_element = cryptoMethod->encrypt(0, 1);
  618. pushQuery(query_element, cryptoMethod->getPublicParameters().getCiphertextBitsize()/8, dim, j);
  619. }
  620. }
  621. }
  622. void PIRReplyGeneratorNFL_internal::pushQuery(char* rawQuery)
  623. {
  624. pushQuery(rawQuery, cryptoMethod->getPublicParameters().getCiphertextBitsize()/8, current_dim_index, current_query_index);
  625. current_query_index++;
  626. if (current_query_index >= pirParam.n[current_dim_index])
  627. {
  628. current_query_index = 0;
  629. current_dim_index++;
  630. }
  631. if (current_dim_index >= pirParam.d)
  632. {
  633. std::cout << "PIRReplyGeneratorNFL: Finished importing query (this message should appear only once)" << std::endl;
  634. }
  635. }
  636. void PIRReplyGeneratorNFL_internal::pushQuery(char* rawQuery, unsigned int size, int dim, int nbr)
  637. {
  638. unsigned int polyDegree = cryptoMethod->getpolyDegree();
  639. unsigned int nbModuli = cryptoMethod->getnbModuli();
  640. // Trick, we get both a and b at the same time, b needs to be set afterwards
  641. uint64_t *a,*b;
  642. // We push the query we do not copy it
  643. //a = (poly64) calloc(size, 1);
  644. //memcpy(a,rawQuery,size);
  645. a = (poly64) rawQuery;
  646. if (lwe) b = a+nbModuli*polyDegree;
  647. #ifdef CRYPTO_DEBUG
  648. std::cout<<"\nQuery received.a ";NFLTools::print_poly64(a,4);
  649. if (lwe) {std::cout<<"Query received.b ";NFLTools::print_poly64hex(b,4);}
  650. #endif
  651. #ifdef SHOUP
  652. uint64_t *ap,*bp;
  653. ap = (poly64) calloc(size, 1);
  654. if (lwe) bp = ap+nbModuli*polyDegree;
  655. for (unsigned int cm = 0 ; cm < nbModuli ; cm++)
  656. {
  657. for (unsigned i = 0 ; i < polyDegree ;i++)
  658. {
  659. ap[i+cm*polyDegree] = ((uint128_t) a[i+cm*polyDegree] << 64) / cryptoMethod->getmoduli()[cm];
  660. if (lwe) bp[i+cm*polyDegree] = ((uint128_t) b[i+cm*polyDegree] << 64) / cryptoMethod->getmoduli()[cm];
  661. }
  662. }
  663. queriesBuf[dim][0][nbr].a = a;
  664. queriesBuf[dim][0][nbr].b = b;
  665. queriesBuf[dim][1][nbr].a = ap;
  666. queriesBuf[dim][1][nbr].b = bp;
  667. #ifdef CRYPTO_DEBUG
  668. std::cout << "Query NFL pushed.a' "; NFLTools::print_poly64hex(queriesBuf[dim][1][nbr].a,4);
  669. if (lwe) { std::cout << "Query NFL pushed.b' "; NFLTools::print_poly64hex(queriesBuf[dim][1][nbr].b,4);}
  670. #endif
  671. #else
  672. queriesBuf[dim][nbr].a = a;
  673. queriesBuf[dim][nbr].b = b;
  674. #endif
  675. }
  676. size_t PIRReplyGeneratorNFL_internal::getTotalSystemMemory()
  677. {
  678. #ifdef __APPLE__
  679. int m[2];
  680. m[0] = CTL_HW;
  681. m[1] = HW_MEMSIZE;
  682. int64_t size = 0;
  683. size_t len = sizeof( size );
  684. sysctl( m, 2, &size, &len, NULL, 0 );
  685. return (size_t)size;
  686. #else
  687. long pages = /*get_phys_pages();*/sysconf(_SC_PHYS_PAGES);
  688. long page_size = /*getpagesize();*/sysconf(_SC_PAGE_SIZE);
  689. return pages * page_size;
  690. #endif
  691. }
  692. void PIRReplyGeneratorNFL_internal::setPirParams(PIRParameters& param)
  693. {
  694. freeQueries();
  695. freeQueriesBuffer();
  696. pirParam = param;
  697. cryptoMethod->setandgetAbsBitPerCiphertext(pirParam.n[0]);
  698. initQueriesBuffer();
  699. }
  700. void PIRReplyGeneratorNFL_internal::setCryptoMethod(CryptographicSystem* cm)
  701. {
  702. //cryptoMethod = (NFLLWE*) cm;
  703. cryptoMethod = (LatticesBasedCryptosystem*) cm;
  704. lwe = (cryptoMethod->toString() == "LWE") ? true : false;
  705. }
  706. void PIRReplyGeneratorNFL_internal::freeInputData()
  707. {
  708. #ifdef DEBUG
  709. std:cout << "PIRReplyGeneratorNFL_internal: freeing input_data" << std::endl;
  710. #endif
  711. uint64_t theoretical_files_nbr = 1;
  712. for (unsigned int i = 0 ; i < pirParam.d ; i++) theoretical_files_nbr *= pirParam.n[i];
  713. if (input_data != NULL){
  714. for (unsigned int i = 0 ; i < theoretical_files_nbr ; i++){
  715. if (input_data[i].p != NULL){
  716. if (input_data[i].p[0] != NULL){
  717. free(input_data[i].p[0]);
  718. input_data[i].p[0] = NULL;
  719. }
  720. free(input_data[i].p);
  721. input_data[i].p = NULL;
  722. }
  723. }
  724. delete[] input_data;
  725. input_data = NULL;
  726. }
  727. #ifdef DEBUG
  728. printf( "PIRReplyGeneratorNFL_internal: input_data freed\n");
  729. #endif
  730. }
  731. void PIRReplyGeneratorNFL_internal::freeQueries()
  732. {
  733. for (unsigned int i = 0; i < pirParam.d; i++)
  734. {
  735. for (unsigned int j = 0 ; j < pirParam.n[i] ; j++)
  736. {
  737. if (queriesBuf != NULL && queriesBuf[i] != NULL && queriesBuf[i][0][j].a != NULL)
  738. {
  739. free(queriesBuf[i][0][j].a); //only free a because a and b and contingus, see pushQuery
  740. queriesBuf[i][0][j].a = NULL;
  741. }
  742. if (queriesBuf != NULL && queriesBuf[i] != NULL && queriesBuf[i][1][j].a != NULL)
  743. {
  744. free(queriesBuf[i][1][j].a); //only free a because a and b and contingus, see pushQuery
  745. queriesBuf[i][1][j].a = NULL;
  746. }
  747. }
  748. }
  749. current_query_index = 0;
  750. current_dim_index = 0;
  751. #ifdef DEBUG
  752. printf( "queriesBuf freed\n");
  753. #endif
  754. }
  755. void PIRReplyGeneratorNFL_internal::freeQueriesBuffer()
  756. {
  757. if (queriesBuf != NULL){
  758. for (unsigned int i = 0; i < pirParam.d; i++){
  759. if (queriesBuf[i] != NULL){
  760. if (queriesBuf[i][0] != NULL){
  761. delete[] queriesBuf[i][0]; //allocated in intQueriesBuf with new.
  762. queriesBuf[i][0] = NULL;
  763. }
  764. if (queriesBuf[i][1] != NULL){
  765. delete[] queriesBuf[i][1]; //allocated in intQueriesBuf with new.
  766. queriesBuf[i][1] = NULL;
  767. }
  768. delete[] queriesBuf[i]; //allocated in intQueriesBuf with new.
  769. queriesBuf[i] = NULL;
  770. }
  771. }
  772. delete[] queriesBuf; //allocated in intQueriesBuf with new.
  773. queriesBuf = NULL;
  774. }
  775. }
  776. void PIRReplyGeneratorNFL_internal::freeResult()
  777. {
  778. if(repliesArray!=NULL)
  779. {
  780. for(unsigned i=0 ; i < repliesAmount; i++)
  781. {
  782. if(repliesArray[i]!=NULL) free(repliesArray[i]);
  783. repliesArray[i] = NULL;
  784. }
  785. free(repliesArray);
  786. repliesArray=NULL;
  787. }
  788. }
  789. PIRReplyGeneratorNFL_internal::~PIRReplyGeneratorNFL_internal()
  790. {
  791. freeQueries();
  792. freeQueriesBuffer();
  793. freeResult();
  794. mutex.try_lock();
  795. mutex.unlock();
  796. }