controller.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. extern "C" {
  2. #include <event2/listener.h>
  3. #include <event2/bufferevent.h>
  4. #include <event2/buffer.h>
  5. }
  6. #include <NTL/vec_ZZ.h>
  7. #include <NTL/ZZ.h>
  8. #include <NTL/ZZ_p.h>
  9. #include <sys/socket.h>
  10. #include <netinet/in.h>
  11. #include <arpa/inet.h>
  12. #include <fstream>
  13. #include <vector>
  14. #include <set>
  15. #include <map>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include "evutils.h"
  19. #include "subproblem.h"
  20. NTL_CLIENT
  21. struct SubproblemProgress;
  22. typedef std::set<struct bufferevent *> BESet;
  23. typedef std::map<struct bufferevent *, SubproblemProgress *> BEMap;
  24. void besetdump(const BESet &bes, ostream &os)
  25. {
  26. BESet::const_iterator besit;
  27. os << hex << " ";
  28. for (besit = bes.begin(); besit != bes.end(); ++besit) {
  29. os << *besit << " ";
  30. }
  31. os << dec << "\n";
  32. }
  33. void bemapdump(const BEMap &bem, ostream &os)
  34. {
  35. BEMap::const_iterator bemit;
  36. os << hex << " ";
  37. for (bemit = bem.begin(); bemit != bem.end(); ++bemit) {
  38. os << bemit->first << "->" << bemit->second << " ";
  39. }
  40. os << dec << "\n";
  41. }
  42. struct Statuses {
  43. BESet idle;
  44. BEMap working;
  45. // Dump the state for debug purposes
  46. void dump(ostream &os) const {
  47. os << " idle (" << idle.size() << "):\n";
  48. besetdump(idle, os);
  49. os << " working (" << working.size() << "):\n";
  50. bemapdump(working, os);
  51. }
  52. };
  53. struct FactorDecomp {
  54. ZZ factor;
  55. vec_ZZ fvec;
  56. };
  57. void vsppdump(const vector<SubproblemProgress> &spv, ostream &os);
  58. static struct ControllerState {
  59. ZZ rho;
  60. FactorDecomp p, q;
  61. int working;
  62. vector<SubproblemProgress> subproblems_p, subproblems_q;
  63. Statuses dpnodes, workers;
  64. ControllerState() : working(0) {}
  65. // Dump the state for debug purposes
  66. void dump(ostream &os) const {
  67. if (!working) {
  68. os << "Not working\n";
  69. return;
  70. }
  71. os << "P:\n";
  72. vsppdump(subproblems_p, os);
  73. os << "Q:\n";
  74. vsppdump(subproblems_q, os);
  75. os << "dpnodes:\n";
  76. dpnodes.dump(os);
  77. os << "workers:\n";
  78. workers.dump(os);
  79. }
  80. } ctrlstate;
  81. struct IPPort {
  82. unsigned char ipport[6];
  83. IPPort(unsigned char *ipp) {
  84. memmove(ipport, ipp, 6);
  85. }
  86. void dump(ostream &os) const {
  87. os << int(ipport[0]) << "." << int(ipport[1]) << "." <<
  88. int(ipport[2]) << "." << int(ipport[3]) << ":" <<
  89. ((ipport[4] << 8) + ipport[5]) << " ";
  90. }
  91. };
  92. typedef vector<IPPort> IPPortSet;
  93. void ipportsetdump(const IPPortSet &ipps, ostream &os)
  94. {
  95. IPPortSet::const_iterator ippsit;
  96. os << " ";
  97. for (ippsit = ipps.begin(); ippsit != ipps.end(); ++ippsit) {
  98. ippsit->dump(os);
  99. }
  100. os << "\n";
  101. }
  102. struct SubproblemProgress : Subproblem {
  103. // The sets of dpnodes and workers currently working on this subproblem
  104. BESet dpnodes, workers;
  105. // The dpnode IPPorts registered for this subproblem
  106. IPPortSet ipports;
  107. // The desired number of DPnodes for this subproblem
  108. unsigned short desired_dpnodes;
  109. // The maximum number of workers useful for this subproblem
  110. unsigned int max_workers;
  111. // Have we found a solution?
  112. int solved;
  113. // The solution, if found.
  114. ZZ solution;
  115. SubproblemProgress(unsigned short id, const ZZ &b, const ZZ &t,
  116. const ZZ &m, const ZZ &o, unsigned int dpf) :
  117. Subproblem(id, b, t, m, o, dpf), solved(0) {
  118. // How many DPnodes should we use for a problem of this size?
  119. desired_dpnodes = 2;
  120. // How many workers would we like to use?
  121. ZZ sorder = SqrRoot(order >> 46);
  122. if (NumBits(sorder) > 30) {
  123. // Just use all the workers we can find
  124. max_workers = 4294967295U; // 2^32 - 1
  125. } else {
  126. max_workers = trunc_long(sorder,31) + 1;
  127. }
  128. }
  129. // Stop all dpnodes and workers and reset to unstarted state
  130. void reset(void) {
  131. BESet::iterator iter;
  132. unsigned char stopcmd[1] = { 'S' };
  133. for (BESet::iterator iter = dpnodes.begin(); iter != dpnodes.end();
  134. ++iter) {
  135. bufferevent_write(*iter, stopcmd, 1);
  136. ctrlstate.dpnodes.working.erase(*iter);
  137. ctrlstate.dpnodes.idle.insert(*iter);
  138. }
  139. for (BESet::iterator iter = workers.begin(); iter != workers.end();
  140. ++iter) {
  141. bufferevent_write(*iter, stopcmd, 1);
  142. ctrlstate.workers.working.erase(*iter);
  143. ctrlstate.workers.idle.insert(*iter);
  144. }
  145. dpnodes.clear();
  146. workers.clear();
  147. ipports.clear();
  148. }
  149. // Dump for debugging purposes
  150. void dump(ostream &os) const {
  151. os << " dpnodes (" << dpnodes.size() << "):\n";
  152. besetdump(dpnodes, os);
  153. os << " workers (" << workers.size() << "):\n";
  154. besetdump(workers, os);
  155. os << " ipports (" << ipports.size() << "):\n";
  156. ipportsetdump(ipports, os);
  157. }
  158. void worker_write(struct bufferevent *bev) {
  159. bev_write(bev);
  160. unsigned short num_ipports = ipports.size();
  161. bufferevent_write(bev, &num_ipports, 2);
  162. for (unsigned short i = 0; i < num_ipports; ++i) {
  163. bufferevent_write(bev, ipports[i].ipport, 6);
  164. }
  165. }
  166. };
  167. // Dump the state for debug purposes
  168. void vsppdump(const vector<SubproblemProgress> &spv, ostream &os)
  169. {
  170. vector<SubproblemProgress>::const_iterator spiter;
  171. int count = 0;
  172. for (spiter = spv.begin(); spiter != spv.end(); ++spiter) {
  173. ++count;
  174. os << " " << count << ":\n";
  175. spiter->dump(os);
  176. }
  177. os << "\n";
  178. }
  179. // Find a subproblem in the given vector that could use another DPnode,
  180. // and give it one of the idle ones. Only allocate it to a subproblem
  181. // with no current DPnodes if consider_empty is true.
  182. static void find_subproblem_for_dpnode(vector<SubproblemProgress> &spv,
  183. bool consider_empty)
  184. {
  185. vector<SubproblemProgress>::iterator spiter;
  186. for (spiter = spv.begin(); spiter != spv.end(); ++spiter) {
  187. if (spiter->solved) continue;
  188. if (spiter->dpnodes.size() == 0 && consider_empty == false) continue;
  189. // How many DPnodes would we like to have for this subproblem?
  190. while (spiter->dpnodes.size() < spiter->desired_dpnodes &&
  191. ctrlstate.dpnodes.idle.size() > 0) {
  192. // Get the first idle DPnode
  193. BESet::iterator beviter = ctrlstate.dpnodes.idle.begin();
  194. // Allocate it to the subproblem
  195. spiter->dpnodes.insert(*beviter);
  196. ctrlstate.dpnodes.working[*beviter] = &(*spiter);
  197. ctrlstate.dpnodes.idle.erase(*beviter);
  198. // Tell it to start listening for DPs
  199. spiter->bev_write(*beviter);
  200. }
  201. }
  202. }
  203. // Find a subproblem in the given vector that has all of its DPnodes and
  204. // could use another worker, and give it one of the idle ones.
  205. static void find_subproblem_for_worker(vector<SubproblemProgress> &spv)
  206. {
  207. vector<SubproblemProgress>::iterator spiter;
  208. for (spiter = spv.begin(); spiter != spv.end(); ++spiter) {
  209. if (spiter->solved) continue;
  210. while (spiter->ipports.size() == spiter->desired_dpnodes &&
  211. spiter->workers.size() < spiter->max_workers &&
  212. ctrlstate.workers.idle.size() > 0) {
  213. // Get the first idle worker
  214. BESet::iterator beviter = ctrlstate.workers.idle.begin();
  215. // Allocate it to the subproblem
  216. spiter->workers.insert(*beviter);
  217. ctrlstate.workers.working[*beviter] = &(*spiter);
  218. ctrlstate.workers.idle.erase(*beviter);
  219. // Tell it to start working on the subproblem
  220. spiter->worker_write(*beviter);
  221. }
  222. }
  223. }
  224. // See if there are any idle DPnodes or workers we can put to use
  225. void schedule(void)
  226. {
  227. cerr << "Before schedule:\n"; ctrlstate.dump(cerr);
  228. // Check the DPnodes
  229. // Iterate through the subproblems, looking for one that can use
  230. // another DPnode. First look for subproblems that already have
  231. // some, but not all, of their DPnodes
  232. if (ctrlstate.dpnodes.idle.size() > 0) {
  233. find_subproblem_for_dpnode(ctrlstate.subproblems_p, false);
  234. }
  235. if (ctrlstate.dpnodes.idle.size() > 0) {
  236. find_subproblem_for_dpnode(ctrlstate.subproblems_q, false);
  237. }
  238. // If there are still more dpnodes to place, start assigning them to
  239. // subproblems with no current dpnodes
  240. if (ctrlstate.dpnodes.idle.size() > 0) {
  241. find_subproblem_for_dpnode(ctrlstate.subproblems_p, true);
  242. }
  243. if (ctrlstate.dpnodes.idle.size() > 0) {
  244. find_subproblem_for_dpnode(ctrlstate.subproblems_q, true);
  245. }
  246. // Check the workers
  247. // Iterate through the subproblems, looking for one that can use
  248. // another worker.
  249. if (ctrlstate.workers.idle.size() > 0) {
  250. find_subproblem_for_worker(ctrlstate.subproblems_p);
  251. }
  252. if (ctrlstate.workers.idle.size() > 0) {
  253. find_subproblem_for_worker(ctrlstate.subproblems_q);
  254. }
  255. cerr << "After schedule:\n"; ctrlstate.dump(cerr);
  256. }
  257. typedef enum {
  258. CCSTATE_START,
  259. CCSTATE_DPWAITRESP,
  260. CCSTATE_DPLISTENING,
  261. CCSTATE_END
  262. } CCState;
  263. struct ControllerConnInfo {
  264. CCState state;
  265. ControllerConnInfo() : state(CCSTATE_DPWAITRESP) {}
  266. };
  267. static void controller_dpnode_reader(struct bufferevent *bev, void *ctx)
  268. {
  269. struct evbuffer *input = bufferevent_get_input(bev);
  270. ControllerConnInfo *info = (ControllerConnInfo *)ctx;
  271. unsigned char cmd[1];
  272. while(1) {
  273. size_t len = evbuffer_get_length(input);
  274. switch (info->state) {
  275. case CCSTATE_START:
  276. case CCSTATE_DPWAITRESP:
  277. if (len < 1) return;
  278. bufferevent_read(bev, cmd, 1);
  279. switch (cmd[0]) {
  280. case 'L':
  281. info->state = CCSTATE_DPLISTENING;
  282. break;
  283. default:
  284. /* Unknown DPnode command received */
  285. fprintf(stderr, "Unknown command in "
  286. "controller_dpnode_reader: "
  287. "%c\n", cmd[0]);
  288. info->state = CCSTATE_END;
  289. break;
  290. }
  291. break;
  292. case CCSTATE_DPLISTENING:
  293. // Read 6 bytes
  294. if (len < 6) return;
  295. unsigned char ipport[6];
  296. unsigned int DPip;
  297. unsigned short DPport;
  298. bufferevent_read(bev, ipport, 6);
  299. memmove(&DPip, ipport, 4);
  300. memmove(&DPport, ipport+4, 2);
  301. {
  302. struct in_addr DPaddr = { DPip };
  303. printf("DP node at %s:%d\n", inet_ntoa(DPaddr), ntohs(DPport));
  304. if (ctrlstate.dpnodes.working.count(bev) > 0) {
  305. ctrlstate.dpnodes.working[bev]->ipports.push_back(
  306. IPPort(ipport));
  307. schedule();
  308. }
  309. }
  310. info->state = CCSTATE_DPWAITRESP;
  311. break;
  312. case CCSTATE_END:
  313. // Shut down the connection
  314. delete info;
  315. bufferevent_free(bev);
  316. return;
  317. }
  318. }
  319. }
  320. static void controller_worker_reader(struct bufferevent *bev, void *ctx)
  321. {
  322. struct evbuffer *input = bufferevent_get_input(bev);
  323. size_t len = evbuffer_get_length(input);
  324. }
  325. static void controller_dpnode_event_cb(struct bufferevent *bev, short events,
  326. void *ctx)
  327. {
  328. if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  329. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  330. fprintf(stderr, "Closing dpnode connection\n");
  331. if (ctrlstate.dpnodes.working.count(bev)) {
  332. // If we lose a dpnode from an active computation, the
  333. // computation is useless.
  334. SubproblemProgress *spp = ctrlstate.dpnodes.working[bev];
  335. ctrlstate.dpnodes.working.erase(bev);
  336. spp->dpnodes.erase(bev);
  337. spp->reset();
  338. } else {
  339. ctrlstate.dpnodes.idle.erase(bev);
  340. }
  341. delete info;
  342. bufferevent_free(bev);
  343. schedule();
  344. }
  345. }
  346. static void controller_worker_event_cb(struct bufferevent *bev, short events,
  347. void *ctx)
  348. {
  349. if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  350. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  351. fprintf(stderr, "Closing worker connection\n");
  352. if (ctrlstate.workers.working.count(bev)) {
  353. SubproblemProgress *spp = ctrlstate.workers.working[bev];
  354. ctrlstate.workers.working.erase(bev);
  355. spp->workers.erase(bev);
  356. } else {
  357. ctrlstate.workers.idle.erase(bev);
  358. }
  359. delete info;
  360. bufferevent_free(bev);
  361. schedule();
  362. }
  363. }
  364. static void controller_event_cb(struct bufferevent *bev, short events,
  365. void *ctx)
  366. {
  367. if (events & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  368. fprintf(stderr, "Closing connection\n");
  369. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  370. delete info;
  371. bufferevent_free(bev);
  372. }
  373. }
  374. // We're just going to read a single byte that will tell us whether the
  375. // peer is a DPnode or a Worker
  376. static void controller_master_reader(struct bufferevent *bev, void *ctx)
  377. {
  378. struct evbuffer *input = bufferevent_get_input(bev);
  379. size_t len = evbuffer_get_length(input);
  380. if (len < 1) return;
  381. char indata[1];
  382. bufferevent_read(bev, indata, 1);
  383. switch(indata[0]) {
  384. case 'D':
  385. printf("DPnode\n");
  386. /* Add this DPnode to the list of available ones */
  387. ctrlstate.dpnodes.idle.insert(bev);
  388. bufferevent_setcb(bev, controller_dpnode_reader, NULL,
  389. controller_dpnode_event_cb, ctx);
  390. controller_dpnode_reader(bev, ctx);
  391. schedule();
  392. return;
  393. case 'W':
  394. printf("Worker\n");
  395. ctrlstate.workers.idle.insert(bev);
  396. bufferevent_setcb(bev, controller_worker_reader, NULL,
  397. controller_worker_event_cb, ctx);
  398. controller_worker_reader(bev, ctx);
  399. schedule();
  400. return;
  401. default:
  402. fprintf(stderr, "Unknown command in controller_master_reader: "
  403. "%c\n", indata[0]);
  404. ControllerConnInfo *info = (ControllerConnInfo*)ctx;
  405. delete info;
  406. bufferevent_free(bev);
  407. return;
  408. }
  409. }
  410. static void controller_accept_cb(struct evconnlistener *listener,
  411. evutil_socket_t fd, struct sockaddr *address, int socklen,
  412. void *ctx)
  413. {
  414. // Create the state of the new connection
  415. ControllerConnInfo *info = new ControllerConnInfo();
  416. // Create a bufferevent for the new connection
  417. struct event_base *base = evconnlistener_get_base(listener);
  418. struct bufferevent *bev = bufferevent_socket_new(
  419. base, fd, BEV_OPT_CLOSE_ON_FREE);
  420. bufferevent_setcb(bev, controller_master_reader, NULL,
  421. controller_event_cb, info);
  422. bufferevent_enable(bev, EV_READ|EV_WRITE);
  423. }
  424. // Create a new controller socket. bindport is the port to bind to (in
  425. // host byte order), or 0 if any port will do. ip and boundport are set
  426. // to the IP and port of the socket, in network byte order.
  427. void *controller_create(struct event_base *evbase, unsigned short bindport,
  428. unsigned int *ip, unsigned short *boundport)
  429. {
  430. return listener_create(evbase, bindport, controller_accept_cb, NULL,
  431. ip, boundport, false);
  432. }
  433. static unsigned short curproblemid = 0;
  434. // Take base and target mod f.factor, then decompose that into small
  435. // subproblems given our knowledge of the factors of phi(f.factor)
  436. static vector<SubproblemProgress> decomp(const ZZ_p &base, const ZZ_p &target,
  437. const FactorDecomp &f)
  438. {
  439. vector<SubproblemProgress> ret;
  440. // Compute phi(factor)
  441. const int fveclen = f.fvec.length();
  442. ZZ phi = to_ZZ(2);
  443. for (int i = 0; i < fveclen; ++i) {
  444. phi *= f.fvec[i];
  445. }
  446. ZZ_p::init(f.factor);
  447. for (int i = 0; i < fveclen; ++i) {
  448. const ZZ& order = f.fvec[i];
  449. ZZ quotient = phi / order;
  450. ZZ_p subgroup_base = to_ZZ_p(rep(base));
  451. subgroup_base = power(subgroup_base, quotient);
  452. ZZ_p subgroup_target = to_ZZ_p(rep(target));
  453. subgroup_target = power(subgroup_target, quotient);
  454. if (subgroup_base == 1) {
  455. // The original base wasn't a generator of the whole group
  456. if (subgroup_target == 1) {
  457. // But the target is in the subgroup. Lucky us.
  458. continue;
  459. } else {
  460. ret.clear();
  461. return ret;
  462. }
  463. }
  464. // By default, 1 in 1000 points are distinguihed points. The
  465. // number in the next line is 2^32/1000
  466. unsigned int dpfreq = 4294967;
  467. if (order < 1000) {
  468. // Just make every point a DP
  469. dpfreq = 4294967295U;
  470. } else if (NumBits(order) < 27) {
  471. // The frequency of DPs should be 10/sqrt(order) to avoid
  472. // a DP-free cycle, so dpfreq = (10*2^32)/sqrt(order)
  473. ZZ f = (to_ZZ(10) << 32) / SqrRoot(order);
  474. dpfreq = trunc_long(f, 31);
  475. }
  476. ret.push_back(SubproblemProgress(curproblemid++, rep(subgroup_base),
  477. rep(subgroup_target),
  478. f.factor, order, dpfreq));
  479. }
  480. return ret;
  481. }
  482. static int generate_problem(struct event_base *evbase)
  483. {
  484. // If there's already a problem on the go, don't generate another one
  485. if (ctrlstate.working == 1) {
  486. return -1;
  487. }
  488. ctrlstate.working = 1;
  489. // Generate a DLP mod rho (in the large odd-order subgroup)
  490. ZZ_p::init(ctrlstate.rho);
  491. ZZ_p base = power(random_ZZ_p(), 2);
  492. ZZ_p target = power(random_ZZ_p(), 2);
  493. // Decompose it mod p and mod q
  494. ctrlstate.subproblems_p = decomp(base, target, ctrlstate.p);
  495. ctrlstate.subproblems_q = decomp(base, target, ctrlstate.q);
  496. schedule();
  497. return 0;
  498. }
  499. int main(int argc, char **argv)
  500. {
  501. // Initialize the prng with some randomness from the kernel
  502. unsigned char randbuf[1024];
  503. ifstream urand("/dev/urandom");
  504. urand.read((char *)randbuf, sizeof(randbuf));
  505. urand.close();
  506. ZZ randzz = ZZFromBytes(randbuf, sizeof(randbuf));
  507. SetSeed(randzz);
  508. // Read the modulus and the factorization of its totient from cin
  509. cin >> ctrlstate.rho >> ctrlstate.p.factor >> ctrlstate.p.fvec >>
  510. ctrlstate.q.factor >> ctrlstate.q.fvec;
  511. unsigned short bindport = 0;
  512. if (argc > 1) {
  513. bindport = strtoul(argv[1], NULL, 10);
  514. }
  515. struct event_base *evbase = event_base_new();
  516. unsigned int myip;
  517. unsigned short myport;
  518. controller_create(evbase, bindport, &myip, &myport);
  519. struct in_addr myaddr = { myip };
  520. printf("Bound to %s:%d\n", inet_ntoa(myaddr), ntohs(myport));
  521. // Kick off the first problem to solve
  522. generate_problem(evbase);
  523. event_base_dispatch(evbase);
  524. return 0;
  525. }