PIRReplyGeneratorNFL_internal.cpp 33 KB

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