dlrho.cc 10 KB

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