dlrho.cc 10 KB

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