dlrho.cc 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. cuda_dl(subgroup_base, subgroup_target, fvec[i], md, dpfreq, &cbdata, &launch_count);
  151. ZZ subgroup_dl = cbdata.expon;
  152. gettimeofday(&et, NULL);
  153. unsigned long us_elapsed = (et.tv_sec-st.tv_sec)*1000000 +
  154. (et.tv_usec-st.tv_usec);
  155. printf("%ld.%06ld seconds elapsed\n", us_elapsed/1000000,
  156. us_elapsed % 1000000);
  157. AtomicWriter(cout) << "Timing (subproblemid, label, launches): "
  158. << i+initial_subproblem_id << ", "
  159. << label << ", "
  160. << launch_count << "\n" << std::flush;
  161. CRT(curexp, curmodulus, subgroup_dl, fvec[i]);
  162. // cout << "CRT\n";
  163. // cout << "curexp = " << curexp << "\n";
  164. // cout << "curmodulus = " << curmodulus << "\n\n";
  165. }
  166. // We'd like a non-negative answer back
  167. if (curexp >= 0) {
  168. exp = curexp;
  169. } else {
  170. exp = curexp + curmodulus;
  171. }
  172. return 1;
  173. }
  174. typedef struct {
  175. pid_t pid;
  176. int rfd;
  177. } PDLHandle;
  178. // Behave like p_dl, but do the work in an asynchronous subprocess
  179. static PDLHandle* p_dl_fork_start(const ZZ &p, const ZZ_p &target,
  180. const ZZ_p &base, const vec_ZZ &fvec, const string &label, int deviceid, unsigned int initial_subproblem_id)
  181. {
  182. PDLHandle *handle = new PDLHandle;
  183. int fds[2];
  184. int res = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
  185. if (res < 0) {
  186. perror("socketpair");
  187. delete handle;
  188. return NULL;
  189. }
  190. handle->rfd = fds[0];
  191. cout.flush();
  192. cerr.flush();
  193. // flush the output before forking
  194. pid_t childpid = fork();
  195. if (childpid == -1) {
  196. perror("fork");
  197. delete handle;
  198. return NULL;
  199. }
  200. if (childpid == 0) {
  201. // Child
  202. close(fds[0]);
  203. int wfd = fds[1];
  204. ZZ exp;
  205. ZZ_p::init(p);
  206. ZZ_p target_p, base_p;
  207. conv(target_p, rep(target));
  208. conv(base_p, rep(base));
  209. cudaError_t cudares = cudaSetDevice(deviceid);
  210. if (cudares != cudaSuccess) {
  211. AtomicWriter(cerr) << "Error setting CUDA device: " << cudaGetErrorString(cudares) << "\n";
  212. exit(1);
  213. }
  214. int res = p_dl(target_p, base_p, exp, fvec, label, initial_subproblem_id);
  215. if (res) {
  216. // Write the result back to the parent using wfd
  217. unsigned short explen = NumBytes(exp);
  218. res = write(wfd, &explen, sizeof(unsigned short));
  219. unsigned char expbuf[explen];
  220. BytesFromZZ(expbuf, exp, explen);
  221. res = write(wfd, expbuf, explen);
  222. close(wfd);
  223. }
  224. exit(0);
  225. } else {
  226. // Parent
  227. close(fds[1]);
  228. }
  229. return handle;
  230. }
  231. // Wait until the subprocess started by p_dl_fork_start completes, and
  232. // return its result. handle is cleaned up.
  233. static int p_dl_fork_join(PDLHandle *handle, ZZ &exp)
  234. {
  235. if (!handle) return 0;
  236. pid_t childpid = handle->pid;
  237. unsigned short explen;
  238. int res = read(handle->rfd, &explen, sizeof(unsigned short));
  239. if (res < (int)sizeof(unsigned short)) {
  240. close(handle->rfd);
  241. delete handle;
  242. waitpid(childpid, NULL, 0);
  243. return 0;
  244. }
  245. unsigned char expbuf[explen];
  246. res = read(handle->rfd, expbuf, explen);
  247. if (res < explen) {
  248. close(handle->rfd);
  249. delete handle;
  250. waitpid(childpid, NULL, 0);
  251. return 0;
  252. }
  253. ZZFromBytes(exp, expbuf, explen);
  254. close(handle->rfd);
  255. delete handle;
  256. waitpid(childpid, NULL, 0);
  257. return 1;
  258. }
  259. int main(int argc, char **argv)
  260. {
  261. // Initialize the prng with some randomness from the kernel
  262. unsigned char randbuf[1024];
  263. ifstream urand("/dev/urandom");
  264. urand.read((char *)randbuf, sizeof(randbuf));
  265. urand.close();
  266. ZZ randzz = ZZFromBytes(randbuf, sizeof(randbuf));
  267. SetSeed(randzz);
  268. ZZ rho, p, q;
  269. vec_ZZ pfvec, qfvec;
  270. cin >> rho >> p >> pfvec >> q >> qfvec;
  271. // Generate a DLP mod rho (in the large odd-order subgroup)
  272. ZZ_p::init(rho);
  273. ZZ_p base = power(random_ZZ_p(), 2);
  274. ZZ_p target = power(random_ZZ_p(), 2);
  275. cout << "base = " << base << "\n";
  276. cout << "target = " << target << "\n";
  277. ZZ exp_p, exp_q, exp;
  278. int res_p = 0;
  279. int res_q = 0;
  280. PDLHandle *handle_p, *handle_q;
  281. handle_p = p_dl_fork_start(p, target, base, pfvec, "p", 0, 0);
  282. handle_q = p_dl_fork_start(q, target, base, qfvec, "q", 1, pfvec.length());
  283. res_p = p_dl_fork_join(handle_p, exp_p);
  284. res_q = p_dl_fork_join(handle_q, exp_q);
  285. if (res_p && res_q) {
  286. ZZ_p::init(rho);
  287. ZZ pm1 = (p - 1)/2;
  288. ZZ qm1 = (q - 1)/2;
  289. if (exp_p < 0) exp_p += pm1;
  290. if (exp_q < 0) exp_q += qm1;
  291. CRT(exp_p, pm1, exp_q, qm1);
  292. exp = exp_p;
  293. // We'd like a non-negative answer back
  294. if (exp < 0) exp += pm1;
  295. cout << "exp = " << exp << "\n";
  296. ZZ_p base_exp;
  297. power(base_exp, base, exp);
  298. if (base_exp == target) {
  299. cout << "CORRECT!\n";
  300. } else {
  301. cout << "INCORRECT:\nbase^exp = " << base_exp << "\n";
  302. cout << "target = " << target << "\n";
  303. }
  304. } else {
  305. cout << "FAIL\n";
  306. }
  307. return 0;
  308. }