dlrho.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /*
  2. * cudadl version 0.9: Compute discrete logs in smooth group orders
  3. * using CUDA
  4. * Copyright (C) 2012 by Ryan Henry and Ian Goldberg
  5. * {rhenry,iang}@cs.uwaterloo.ca
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of version 3 of the GNU General Public License as
  9. * published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <fstream>
  20. #include <unistd.h>
  21. #include <sys/time.h>
  22. #include <NTL/vec_ZZ.h>
  23. #include <NTL/ZZ_p.h>
  24. #include <map>
  25. #include <sstream>
  26. #include <sys/types.h>
  27. #include <sys/wait.h>
  28. #include <sys/socket.h>
  29. #include <cuda_runtime.h>
  30. #include "atomic_iostream.h"
  31. #include "desired_resources.h"
  32. #include "cudadl.h"
  33. NTL_CLIENT
  34. string output_prefix;
  35. #ifdef SAVE_DPS
  36. static ofstream dp_file_stream;
  37. #endif
  38. typedef map<std::string, pair<ZZ,ZZ> > DTable;
  39. struct CBData {
  40. const ZZ_p &base;
  41. const ZZ_p &target;
  42. const ZZ &order;
  43. unsigned long long numdp;
  44. DTable dtable;
  45. bool found_collision;
  46. ZZ expon;
  47. CBData(const ZZ_p &_base, const ZZ_p &_target, const ZZ &_order) :
  48. base(_base), target(_target), order(_order), numdp(0),
  49. found_collision(false) {}
  50. };
  51. // This function is called from inside cuda_dl for each DP it encounters.
  52. // It calls the function named "dpcallback" directly. It would be
  53. // cleaner if this were passed as a function pointer to cuda_dl, but
  54. // that makes nvcc 3.1 segfault. :-p
  55. // dp points to an array of WORDS+7 unsigned ints:
  56. // - 1 word of threadID/blockID
  57. // - WORDS words of the dp value
  58. // - 3 words of a
  59. // - 3 words of b
  60. bool dpcallback(void *cbdata, unsigned int *dpwords)
  61. {
  62. CBData *d = (CBData*)cbdata;
  63. // WARNING: this assumes
  64. // sizeof(unsigned long) == sizeof(unsigned long long) !
  65. ZZ zz_a = to_ZZ(dpwords[WORDS+3]);
  66. zz_a <<= 32;
  67. zz_a += dpwords[WORDS+2];
  68. zz_a <<= 32;
  69. zz_a += dpwords[WORDS+1];
  70. ZZ zz_b = to_ZZ(dpwords[WORDS+6]);
  71. zz_b <<= 32;
  72. zz_b += dpwords[WORDS+5];
  73. zz_b <<= 32;
  74. zz_b += dpwords[WORDS+4];
  75. //ZZ_p dp = power(d->base, zz_a) * power(d->target, zz_b);
  76. // cerr << "DP " << ++(d->numdp) << "\r";
  77. pair<ZZ,ZZ> ab(zz_a,zz_b);
  78. pair<DTable::iterator, bool> res;
  79. string x((const char *)(dpwords+1), WORDS*sizeof(unsigned int));
  80. #ifdef SAVE_DPS
  81. if (!d->found_collision) {
  82. ZZ zz_x;
  83. ZZFromBytes(zz_x, (const unsigned char *)(dpwords+1),
  84. WORDS*sizeof(unsigned int));
  85. dp_file_stream << zz_x << "\n";
  86. }
  87. #endif
  88. res = d->dtable.insert(DTable::value_type(x, ab));
  89. if (!res.second) {
  90. // Collision!
  91. ZZ adiff = to_ZZ(res.first->second.first) - zz_a;
  92. ZZ bdiff = zz_b - to_ZZ(res.first->second.second);
  93. if (bdiff < 0) bdiff += d->order;
  94. ZZ binv;
  95. if (InvModStatus(binv, bdiff, d->order) == 0) {
  96. d->expon = MulMod(binv, adiff, d->order);
  97. d->found_collision = true;
  98. } else {
  99. if (d->order > (1<<20)) {
  100. cerr << "Unhelpful collision\n";
  101. }
  102. }
  103. }
  104. return d->found_collision;
  105. }
  106. // Compute the discrete log of target mod p, to the given base.
  107. // p must be the current ZZ_p modulus.
  108. // Place the result in exp. fvec is a vector of the factors of
  109. // (p-1)/2, which must each be small enough to compute discrete logs
  110. // with some other method (kangaroo, index calculus, GNFS, etc.).
  111. // label is "p" or "q", to be printed to report progress.
  112. // Return 0 on failure, 1 on success.
  113. static int p_dl(const ZZ_p &target, const ZZ_p &base, ZZ &exp,
  114. const vec_ZZ &fvec, const string &label, unsigned int initial_subproblem_id,
  115. unsigned short GB_mem)
  116. {
  117. const int flen = fvec.length();
  118. // Compute phi(p)
  119. ZZ phip;
  120. phip = 2;
  121. for (int i = 0; i < flen; ++i) {
  122. phip *= fvec[i];
  123. }
  124. // Invariant: the desired exp \equiv (curexp mod curmodulus)
  125. ZZ curmodulus, curexp;
  126. curmodulus = 2;
  127. curexp = 0;
  128. for (int i = 0; i < flen; ++i) {
  129. unsigned short desired_dpnodes;
  130. unsigned int max_workers;
  131. unsigned int dpfreq;
  132. desired_resources(fvec[i], 1, GB_mem, desired_dpnodes, max_workers, dpfreq);
  133. ZZ quotient;
  134. ZZ_p subgroup_base;
  135. ZZ_p subgroup_target;
  136. {
  137. AtomicWriter atomic_cout(cout);
  138. atomic_cout << label << " submodulus " << i+1 << " of " << flen << "...\n";
  139. atomic_cout << "Settings (memory, dpfreq): " << GB_mem << ", " << dpfreq << "\n";
  140. // Figure out exp mod fvec[i] by taking each side to the power
  141. // of phirho/fvec[i] so that we're working in the
  142. // subgroup of order fvec[i].
  143. quotient = phip / fvec[i];
  144. subgroup_base = power(base, quotient);
  145. subgroup_target = power(target, quotient);
  146. if (subgroup_base == 1) {
  147. // The original base wasn't a generator of the whole group.
  148. if (subgroup_target == 1) {
  149. atomic_cout << "Non-unique solution (mod " << fvec[i] <<")\n";
  150. continue;
  151. } else {
  152. atomic_cout << "Target not in subgroup generated by base\n";
  153. return 0;
  154. }
  155. }
  156. }
  157. #ifdef SAVE_DPS
  158. std::ostringstream oss;
  159. oss << "dplist_" << i+initial_subproblem_id << ".out";
  160. dp_file_stream.open(oss.str().c_str());
  161. #endif
  162. // Now use your favourite method to get the DL of
  163. // subgroup_target with base subgroup_base, knowing that it's in
  164. // the range [0,fvec[i]).
  165. ZZ md = ZZ_p::modulus();
  166. CBData cbdata(subgroup_base, subgroup_target, fvec[i]);
  167. struct timeval st, et;
  168. #ifdef SAVE_DPS
  169. dp_file_stream << "Subproblem " << i+initial_subproblem_id << "\n";
  170. #endif
  171. gettimeofday(&st, NULL);
  172. unsigned int launch_count = 0;
  173. bool filled_dp_buffer = false;
  174. {
  175. #ifdef DERANDOMIZE
  176. RandomStreamPush push_seed;
  177. // the seed will be reset to its original value
  178. // once we exit this scope
  179. SetSeed(rep(subgroup_base)*rep(subgroup_target)*fvec[i]*md);
  180. #endif
  181. cuda_dl(subgroup_base, subgroup_target, fvec[i], md, dpfreq, &cbdata, &launch_count, &filled_dp_buffer);
  182. }
  183. ZZ subgroup_dl = cbdata.expon;
  184. gettimeofday(&et, NULL);
  185. unsigned long us_elapsed = (et.tv_sec-st.tv_sec)*1000000 +
  186. (et.tv_usec-st.tv_usec);
  187. printf("%ld.%06ld seconds elapsed\n", us_elapsed/1000000,
  188. us_elapsed % 1000000);
  189. AtomicWriter(cout) << "Timing (subproblemid, label, launches): "
  190. << i+initial_subproblem_id << ", "
  191. << label << ", "
  192. << launch_count << "\n" << std::flush;
  193. CRT(curexp, curmodulus, subgroup_dl, fvec[i]);
  194. // cout << "CRT\n";
  195. // cout << "curexp = " << curexp << "\n";
  196. // cout << "curmodulus = " << curmodulus << "\n\n";
  197. #ifdef SAVE_DPS
  198. if (filled_dp_buffer) {
  199. AtomicWriter atomic_cout(cout);
  200. atomic_cout << "Warning: The device dp buffer was filled, so some points were not recorded.\n";
  201. atomic_cout << "These points will not be reproducible (subproblem " << i+initial_subproblem_id << ").\n";
  202. }
  203. dp_file_stream.close();
  204. #endif
  205. }
  206. // We'd like a non-negative answer back
  207. if (curexp >= 0) {
  208. exp = curexp;
  209. } else {
  210. exp = curexp + curmodulus;
  211. }
  212. return 1;
  213. }
  214. typedef struct {
  215. pid_t pid;
  216. int rfd;
  217. } PDLHandle;
  218. // Behave like p_dl, but do the work in an asynchronous subprocess
  219. static PDLHandle* p_dl_fork_start(const ZZ &p, const ZZ_p &target,
  220. const ZZ_p &base, const vec_ZZ &fvec, const string &label,
  221. int deviceid, unsigned int initial_subproblem_id,
  222. unsigned short GB_mem_per_subprocess)
  223. {
  224. PDLHandle *handle = new PDLHandle;
  225. int fds[2];
  226. int res = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
  227. if (res < 0) {
  228. perror("socketpair");
  229. delete handle;
  230. return NULL;
  231. }
  232. handle->rfd = fds[0];
  233. cout.flush();
  234. cerr.flush();
  235. // flush the output before forking
  236. pid_t childpid = fork();
  237. if (childpid == -1) {
  238. perror("fork");
  239. delete handle;
  240. return NULL;
  241. }
  242. if (childpid == 0) {
  243. // Child
  244. close(fds[0]);
  245. int wfd = fds[1];
  246. ZZ exp;
  247. ZZ_p::init(p);
  248. ZZ_p target_p, base_p;
  249. conv(target_p, rep(target));
  250. conv(base_p, rep(base));
  251. cudaError_t cudares = cudaSetDevice(deviceid);
  252. if (cudares != cudaSuccess) {
  253. AtomicWriter(cerr) << "Error setting CUDA device: " << cudaGetErrorString(cudares) << "\n";
  254. exit(1);
  255. }
  256. int res = p_dl(target_p, base_p, exp, fvec, label, initial_subproblem_id, GB_mem_per_subprocess);
  257. if (res) {
  258. // Write the result back to the parent using wfd
  259. unsigned short explen = NumBytes(exp);
  260. res = write(wfd, &explen, sizeof(unsigned short));
  261. unsigned char expbuf[explen];
  262. BytesFromZZ(expbuf, exp, explen);
  263. res = write(wfd, expbuf, explen);
  264. close(wfd);
  265. }
  266. exit(0);
  267. } else {
  268. // Parent
  269. close(fds[1]);
  270. }
  271. return handle;
  272. }
  273. // Wait until the subprocess started by p_dl_fork_start completes, and
  274. // return its result. handle is cleaned up.
  275. static int p_dl_fork_join(PDLHandle *handle, ZZ &exp)
  276. {
  277. if (!handle) return 0;
  278. pid_t childpid = handle->pid;
  279. unsigned short explen;
  280. int res = read(handle->rfd, &explen, sizeof(unsigned short));
  281. if (res < (int)sizeof(unsigned short)) {
  282. close(handle->rfd);
  283. delete handle;
  284. waitpid(childpid, NULL, 0);
  285. return 0;
  286. }
  287. unsigned char expbuf[explen];
  288. res = read(handle->rfd, expbuf, explen);
  289. if (res < explen) {
  290. close(handle->rfd);
  291. delete handle;
  292. waitpid(childpid, NULL, 0);
  293. return 0;
  294. }
  295. ZZFromBytes(exp, expbuf, explen);
  296. close(handle->rfd);
  297. delete handle;
  298. waitpid(childpid, NULL, 0);
  299. return 1;
  300. }
  301. int main(int argc, char **argv)
  302. {
  303. #ifdef SAVE_DPS
  304. cerr << "Note: Saving the distinguished points. Do not run huge problems or else it will use up all of your disk space.\n";
  305. #ifndef DERANDOMIZE
  306. cerr << "Saving DPs without derandomization!\n";
  307. #endif
  308. #endif
  309. if (argc != 2) {
  310. cerr << "Usage: " << argv[0] << " total_mem_GB";
  311. exit(1);
  312. }
  313. unsigned short GB_mem_per_node = strtol(argv[1], NULL, 10);
  314. // Initialize the prng with some randomness from the kernel
  315. unsigned char randbuf[1024];
  316. ifstream urand("/dev/urandom");
  317. urand.read((char *)randbuf, sizeof(randbuf));
  318. urand.close();
  319. ZZ randzz = ZZFromBytes(randbuf, sizeof(randbuf));
  320. SetSeed(randzz);
  321. ZZ rho, p, q;
  322. vec_ZZ pfvec, qfvec;
  323. cin >> rho >> p >> pfvec >> q >> qfvec;
  324. // Generate a DLP mod rho (in the large odd-order subgroup)
  325. ZZ_p::init(rho);
  326. ZZ_p base;
  327. ZZ_p target;
  328. {
  329. #ifdef DERANDOMIZE
  330. RandomStreamPush push_seed;
  331. // the seed will be reset to its original value
  332. // once we exit this scope
  333. SetSeed(rho*p*q);
  334. #endif
  335. base = power(random_ZZ_p(), 2);
  336. target = power(random_ZZ_p(), 2);
  337. }
  338. cout << "base = " << base << "\n";
  339. cout << "target = " << target << "\n";
  340. ZZ exp_p, exp_q, exp;
  341. int res_p = 0;
  342. int res_q = 0;
  343. PDLHandle *handle_p, *handle_q;
  344. handle_p = p_dl_fork_start(p, target, base, pfvec, "p", 0, 0, GB_mem_per_node/2);
  345. handle_q = p_dl_fork_start(q, target, base, qfvec, "q", 1, pfvec.length(), GB_mem_per_node/2);
  346. res_p = p_dl_fork_join(handle_p, exp_p);
  347. res_q = p_dl_fork_join(handle_q, exp_q);
  348. if (res_p && res_q) {
  349. ZZ_p::init(rho);
  350. ZZ pm1 = (p - 1)/2;
  351. ZZ qm1 = (q - 1)/2;
  352. if (exp_p < 0) exp_p += pm1;
  353. if (exp_q < 0) exp_q += qm1;
  354. CRT(exp_p, pm1, exp_q, qm1);
  355. exp = exp_p;
  356. // We'd like a non-negative answer back
  357. if (exp < 0) exp += pm1;
  358. cout << "exp = " << exp << "\n";
  359. ZZ_p base_exp;
  360. power(base_exp, base, exp);
  361. if (base_exp == target) {
  362. cout << "CORRECT!\n";
  363. } else {
  364. cout << "INCORRECT:\nbase^exp = " << base_exp << "\n";
  365. cout << "target = " << target << "\n";
  366. }
  367. } else {
  368. cout << "FAIL\n";
  369. }
  370. return 0;
  371. }