mpcio.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. #include <sys/time.h> // getrusage
  2. #include <sys/resource.h> // getrusage
  3. #include "mpcio.hpp"
  4. #include "rdpf.hpp"
  5. #include "cdpf.hpp"
  6. #include "bitutils.hpp"
  7. #include "coroutine.hpp"
  8. // T is the type being stored
  9. // N is a type whose "name" static member is a string naming the type
  10. // so that we can report something useful to the user if they try
  11. // to read a type that we don't have any more values for
  12. template<typename T, typename N>
  13. PreCompStorage<T,N>::PreCompStorage(unsigned player, ProcessingMode mode,
  14. const char *filenameprefix, unsigned thread_num) :
  15. name(N::name), depth(0)
  16. {
  17. init(player, mode, filenameprefix, thread_num);
  18. }
  19. template<typename T, typename N>
  20. void PreCompStorage<T,N>::init(unsigned player, ProcessingMode mode,
  21. const char *filenameprefix, unsigned thread_num, nbits_t depth)
  22. {
  23. if (mode != MODE_ONLINE) return;
  24. std::string filename(filenameprefix);
  25. char suffix[20];
  26. if (depth) {
  27. this->depth = depth;
  28. sprintf(suffix, "%02d.p%d.t%u", depth, player%10, thread_num);
  29. } else {
  30. sprintf(suffix, ".p%d.t%u", player%10, thread_num);
  31. }
  32. filename.append(suffix);
  33. storage.open(filename);
  34. // It's OK if not every file exists; so don't worry about checking
  35. // for errors here. We'll report an error in get() if we actually
  36. // try to use a value for which we don't have a precomputed file.
  37. count = 0;
  38. }
  39. template<typename T, typename N>
  40. void PreCompStorage<T,N>::get(T& nextval)
  41. {
  42. storage >> nextval;
  43. if (!storage.good()) {
  44. std::cerr << "Failed to read precomputed value from " << name;
  45. if (depth) {
  46. std::cerr << (int)depth;
  47. }
  48. std::cerr << " storage\n";
  49. exit(1);
  50. }
  51. ++count;
  52. }
  53. void MPCSingleIO::async_send_from_msgqueue()
  54. {
  55. #ifdef SEND_LAMPORT_CLOCKS
  56. std::vector<boost::asio::const_buffer> tosend;
  57. tosend.push_back(boost::asio::buffer(messagequeue.front().header));
  58. tosend.push_back(boost::asio::buffer(messagequeue.front().message));
  59. #endif
  60. boost::asio::async_write(sock,
  61. #ifdef SEND_LAMPORT_CLOCKS
  62. tosend,
  63. #else
  64. boost::asio::buffer(messagequeue.front()),
  65. #endif
  66. [&](boost::system::error_code ec, std::size_t amt){
  67. messagequeuelock.lock();
  68. messagequeue.pop();
  69. if (messagequeue.size() > 0) {
  70. async_send_from_msgqueue();
  71. }
  72. messagequeuelock.unlock();
  73. });
  74. }
  75. size_t MPCSingleIO::queue(const void *data, size_t len, lamport_t lamport)
  76. {
  77. // Is this a new message?
  78. size_t newmsg = 0;
  79. dataqueue.append((const char *)data, len);
  80. // If this is the first queue() since the last explicit send(),
  81. // which we'll know because message_lamport will be nullopt, set
  82. // message_lamport to the current Lamport clock. Note that the
  83. // boolean test tests whether message_lamport is nullopt, not
  84. // whether its value is zero.
  85. if (!message_lamport) {
  86. message_lamport = lamport;
  87. newmsg = 1;
  88. }
  89. #ifdef VERBOSE_COMMS
  90. printf("Queue %s.%d len=%lu lamp=%u: ", dest.c_str(), thread_num,
  91. len, message_lamport.value());
  92. for (size_t i=0;i<len;++i) {
  93. printf("%02x", ((const unsigned char*)data)[i]);
  94. }
  95. printf("\n");
  96. #endif
  97. // If we already have some full packets worth of data, may as
  98. // well send it.
  99. if (dataqueue.size() > 28800) {
  100. send(true);
  101. }
  102. return newmsg;
  103. }
  104. void MPCSingleIO::send(bool implicit_send)
  105. {
  106. size_t thissize = dataqueue.size();
  107. // Ignore spurious calls to send(), except for resetting
  108. // message_lamport if this was an explicit send().
  109. if (thissize == 0) {
  110. #ifdef SEND_LAMPORT_CLOCKS
  111. // If this was an explicit send(), reset the message_lamport so
  112. // that it gets updated at the next queue().
  113. if (!implicit_send) {
  114. message_lamport.reset();
  115. }
  116. #endif
  117. return;
  118. }
  119. #ifdef RECORD_IOTRACE
  120. iotrace.push_back(thissize);
  121. #endif
  122. messagequeuelock.lock();
  123. // Move the current message to send into the message queue (this
  124. // moves a pointer to the data, not copying the data itself)
  125. #ifdef SEND_LAMPORT_CLOCKS
  126. messagequeue.emplace(std::move(dataqueue),
  127. message_lamport.value());
  128. // If this was an explicit send(), reset the message_lamport so
  129. // that it gets updated at the next queue().
  130. if (!implicit_send) {
  131. message_lamport.reset();
  132. }
  133. #else
  134. messagequeue.emplace(std::move(dataqueue));
  135. #endif
  136. // If this is now the first thing in the message queue, launch
  137. // an async_write to write it
  138. if (messagequeue.size() == 1) {
  139. async_send_from_msgqueue();
  140. }
  141. messagequeuelock.unlock();
  142. }
  143. size_t MPCSingleIO::recv(void *data, size_t len, lamport_t &lamport)
  144. {
  145. #ifdef VERBOSE_COMMS
  146. size_t orig_len = len;
  147. printf("Recv %s.%d len=%lu lamp=%u ", dest.c_str(), thread_num,
  148. len, lamport);
  149. #endif
  150. #ifdef SEND_LAMPORT_CLOCKS
  151. char *cdata = (char *)data;
  152. size_t res = 0;
  153. while (len > 0) {
  154. while (recvdataremain == 0) {
  155. // Read a new header
  156. char hdr[sizeof(uint32_t) + sizeof(lamport_t)];
  157. uint32_t datalen;
  158. lamport_t recv_lamport;
  159. boost::asio::read(sock, boost::asio::buffer(hdr, sizeof(hdr)));
  160. memmove(&datalen, hdr, sizeof(datalen));
  161. memmove(&recv_lamport, hdr+sizeof(datalen), sizeof(lamport_t));
  162. lamport_t new_lamport = recv_lamport + 1;
  163. if (lamport < new_lamport) {
  164. lamport = new_lamport;
  165. }
  166. if (datalen > 0) {
  167. recvdata.resize(datalen, '\0');
  168. boost::asio::read(sock, boost::asio::buffer(recvdata));
  169. recvdataremain = datalen;
  170. }
  171. }
  172. size_t amttoread = len;
  173. if (amttoread > recvdataremain) {
  174. amttoread = recvdataremain;
  175. }
  176. memmove(cdata, recvdata.data()+recvdata.size()-recvdataremain,
  177. amttoread);
  178. cdata += amttoread;
  179. len -= amttoread;
  180. recvdataremain -= amttoread;
  181. res += amttoread;
  182. }
  183. #else
  184. size_t res = boost::asio::read(sock, boost::asio::buffer(data, len));
  185. #endif
  186. #ifdef VERBOSE_COMMS
  187. printf("nlamp=%u: ", lamport);
  188. for (size_t i=0;i<orig_len;++i) {
  189. printf("%02x", ((const unsigned char*)data)[i]);
  190. }
  191. printf("\n");
  192. #endif
  193. #ifdef RECORD_IOTRACE
  194. iotrace.push_back(-(ssize_t(res)));
  195. #endif
  196. return res;
  197. }
  198. #ifdef RECORD_IOTRACE
  199. void MPCSingleIO::dumptrace(std::ostream &os, const char *label)
  200. {
  201. if (label) {
  202. os << label << " ";
  203. }
  204. os << "IO trace:";
  205. for (auto& s: iotrace) {
  206. os << " " << s;
  207. }
  208. os << "\n";
  209. }
  210. #endif
  211. void MPCIO::reset_stats()
  212. {
  213. msgs_sent.clear();
  214. msg_bytes_sent.clear();
  215. aes_ops.clear();
  216. for (size_t i=0; i<num_threads; ++i) {
  217. msgs_sent.push_back(0);
  218. msg_bytes_sent.push_back(0);
  219. aes_ops.push_back(0);
  220. }
  221. steady_start = boost::chrono::steady_clock::now();
  222. cpu_start = boost::chrono::process_cpu_clock::now();
  223. }
  224. // Report the memory usage
  225. void MPCIO::dump_memusage(std::ostream &os)
  226. {
  227. struct rusage ru;
  228. getrusage(RUSAGE_SELF, &ru);
  229. os << "Mem: " << ru.ru_maxrss << " KiB\n";
  230. }
  231. void MPCIO::dump_stats(std::ostream &os)
  232. {
  233. size_t tot_msgs_sent = 0;
  234. size_t tot_msg_bytes_sent = 0;
  235. size_t tot_aes_ops = 0;
  236. for (auto& n : msgs_sent) {
  237. tot_msgs_sent += n;
  238. }
  239. for (auto& n : msg_bytes_sent) {
  240. tot_msg_bytes_sent += n;
  241. }
  242. for (auto& n : aes_ops) {
  243. tot_aes_ops += n;
  244. }
  245. auto steady_elapsed =
  246. boost::chrono::steady_clock::now() - steady_start;
  247. auto cpu_elapsed =
  248. boost::chrono::process_cpu_clock::now() - cpu_start;
  249. os << tot_msgs_sent << " messages sent\n";
  250. os << tot_msg_bytes_sent << " message bytes sent\n";
  251. os << lamport << " Lamport clock (latencies)\n";
  252. os << tot_aes_ops << " local AES operations\n";
  253. os << boost::chrono::duration_cast
  254. <boost::chrono::milliseconds>(steady_elapsed) <<
  255. " wall clock time\n";
  256. os << cpu_elapsed << " {real;user;system}\n";
  257. dump_memusage(os);
  258. }
  259. MPCPeerIO::MPCPeerIO(unsigned player, ProcessingMode mode,
  260. std::deque<tcp::socket> &peersocks,
  261. std::deque<tcp::socket> &serversocks) :
  262. MPCIO(player, mode, peersocks.size())
  263. {
  264. unsigned num_threads = unsigned(peersocks.size());
  265. for (unsigned i=0; i<num_threads; ++i) {
  266. triples.emplace_back(player, mode, "triples", i);
  267. }
  268. for (unsigned i=0; i<num_threads; ++i) {
  269. halftriples.emplace_back(player, mode, "halves", i);
  270. }
  271. rdpftriples.resize(num_threads);
  272. for (unsigned i=0; i<num_threads; ++i) {
  273. for (unsigned depth=1; depth<=ADDRESS_MAX_BITS; ++depth) {
  274. rdpftriples[i][depth-1].init(player, mode,
  275. "rdpf", i, depth);
  276. }
  277. }
  278. for (unsigned i=0; i<num_threads; ++i) {
  279. cdpfs.emplace_back(player, mode, "cdpf", i);
  280. }
  281. for (unsigned i=0; i<num_threads; ++i) {
  282. peerios.emplace_back(std::move(peersocks[i]), "peer", i);
  283. }
  284. for (unsigned i=0; i<num_threads; ++i) {
  285. serverios.emplace_back(std::move(serversocks[i]), "srv", i);
  286. }
  287. }
  288. void MPCPeerIO::dump_precomp_stats(std::ostream &os)
  289. {
  290. for (size_t i=0; i<triples.size(); ++i) {
  291. if (i > 0) {
  292. os << " ";
  293. }
  294. os << "T" << i << " t:" << triples[i].get_stats() <<
  295. " h:" << halftriples[i].get_stats();
  296. for (nbits_t depth=1; depth<=ADDRESS_MAX_BITS; ++depth) {
  297. size_t cnt = rdpftriples[i][depth-1].get_stats();
  298. if (cnt > 0) {
  299. os << " r" << int(depth) << ":" << cnt;
  300. }
  301. }
  302. size_t ccnt = cdpfs[i].get_stats();
  303. if (ccnt > 0) {
  304. os << " c:" << ccnt;
  305. }
  306. }
  307. os << "\n";
  308. }
  309. void MPCPeerIO::reset_precomp_stats()
  310. {
  311. for (size_t i=0; i<triples.size(); ++i) {
  312. triples[i].reset_stats();
  313. halftriples[i].reset_stats();
  314. for (nbits_t depth=1; depth<=ADDRESS_MAX_BITS; ++depth) {
  315. rdpftriples[i][depth-1].reset_stats();
  316. }
  317. }
  318. }
  319. void MPCPeerIO::dump_stats(std::ostream &os)
  320. {
  321. MPCIO::dump_stats(os);
  322. os << "Precomputed values used: ";
  323. dump_precomp_stats(os);
  324. }
  325. MPCServerIO::MPCServerIO(ProcessingMode mode,
  326. std::deque<tcp::socket> &p0socks,
  327. std::deque<tcp::socket> &p1socks) :
  328. MPCIO(2, mode, p0socks.size())
  329. {
  330. rdpfpairs.resize(num_threads);
  331. for (unsigned i=0; i<num_threads; ++i) {
  332. for (unsigned depth=1; depth<=ADDRESS_MAX_BITS; ++depth) {
  333. rdpfpairs[i][depth-1].init(player, mode,
  334. "rdpf", i, depth);
  335. }
  336. }
  337. for (unsigned i=0; i<num_threads; ++i) {
  338. p0ios.emplace_back(std::move(p0socks[i]), "p0", i);
  339. }
  340. for (unsigned i=0; i<num_threads; ++i) {
  341. p1ios.emplace_back(std::move(p1socks[i]), "p1", i);
  342. }
  343. }
  344. void MPCServerIO::dump_precomp_stats(std::ostream &os)
  345. {
  346. for (size_t i=0; i<rdpfpairs.size(); ++i) {
  347. if (i > 0) {
  348. os << " ";
  349. }
  350. os << "T" << i;
  351. for (nbits_t depth=1; depth<=ADDRESS_MAX_BITS; ++depth) {
  352. size_t cnt = rdpfpairs[i][depth-1].get_stats();
  353. if (cnt > 0) {
  354. os << " r" << int(depth) << ":" << cnt;
  355. }
  356. }
  357. }
  358. os << "\n";
  359. }
  360. void MPCServerIO::reset_precomp_stats()
  361. {
  362. for (size_t i=0; i<rdpfpairs.size(); ++i) {
  363. for (nbits_t depth=1; depth<=ADDRESS_MAX_BITS; ++depth) {
  364. rdpfpairs[i][depth-1].reset_stats();
  365. }
  366. }
  367. }
  368. void MPCServerIO::dump_stats(std::ostream &os)
  369. {
  370. MPCIO::dump_stats(os);
  371. os << "Precomputed values used: ";
  372. dump_precomp_stats(os);
  373. }
  374. MPCTIO::MPCTIO(MPCIO &mpcio, int thread_num) :
  375. thread_num(thread_num), thread_lamport(mpcio.lamport),
  376. mpcio(mpcio)
  377. #ifdef VERBOSE_COMMS
  378. , round_num(0)
  379. #endif
  380. {
  381. if (mpcio.player < 2) {
  382. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  383. peer_iostream.emplace(mpcpio.peerios[thread_num],
  384. thread_lamport, mpcpio.msgs_sent[thread_num],
  385. mpcpio.msg_bytes_sent[thread_num]);
  386. server_iostream.emplace(mpcpio.serverios[thread_num],
  387. thread_lamport, mpcpio.msgs_sent[thread_num],
  388. mpcpio.msg_bytes_sent[thread_num]);
  389. } else {
  390. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  391. p0_iostream.emplace(mpcsrvio.p0ios[thread_num],
  392. thread_lamport, mpcsrvio.msgs_sent[thread_num],
  393. mpcsrvio.msg_bytes_sent[thread_num]);
  394. p1_iostream.emplace(mpcsrvio.p1ios[thread_num],
  395. thread_lamport, mpcsrvio.msgs_sent[thread_num],
  396. mpcsrvio.msg_bytes_sent[thread_num]);
  397. }
  398. }
  399. // Sync our per-thread lamport clock with the master one in the
  400. // mpcio. You only need to call this explicitly if your MPCTIO
  401. // outlives your thread (in which case call it after the join), or
  402. // if your threads do interthread communication amongst themselves
  403. // (in which case call it in the sending thread before the send, and
  404. // call it in the receiving thread after the receive).
  405. void MPCTIO::sync_lamport()
  406. {
  407. // Update the mpcio Lamport time to be max of the thread Lamport
  408. // time and what we thought it was before. We use this
  409. // compare_exchange construction in order to atomically
  410. // do the comparison, computation, and replacement
  411. lamport_t old_lamport = mpcio.lamport;
  412. lamport_t new_lamport = thread_lamport;
  413. do {
  414. if (new_lamport < old_lamport) {
  415. new_lamport = old_lamport;
  416. }
  417. // The next line atomically checks if lamport still has
  418. // the value old_lamport; if so, it changes its value to
  419. // new_lamport and returns true (ending the loop). If
  420. // not, it sets old_lamport to the current value of
  421. // lamport, and returns false (continuing the loop so
  422. // that new_lamport can be recomputed based on this new
  423. // value).
  424. } while (!mpcio.lamport.compare_exchange_weak(
  425. old_lamport, new_lamport));
  426. thread_lamport = new_lamport;
  427. }
  428. // Queue up data to the peer or to the server
  429. void MPCTIO::queue_peer(const void *data, size_t len)
  430. {
  431. if (mpcio.player < 2) {
  432. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  433. size_t newmsg = mpcpio.peerios[thread_num].queue(data, len, thread_lamport);
  434. mpcpio.msgs_sent[thread_num] += newmsg;
  435. mpcpio.msg_bytes_sent[thread_num] += len;
  436. }
  437. }
  438. void MPCTIO::queue_server(const void *data, size_t len)
  439. {
  440. if (mpcio.player < 2) {
  441. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  442. size_t newmsg = mpcpio.serverios[thread_num].queue(data, len, thread_lamport);
  443. mpcpio.msgs_sent[thread_num] += newmsg;
  444. mpcpio.msg_bytes_sent[thread_num] += len;
  445. }
  446. }
  447. // Receive data from the peer or to the server
  448. size_t MPCTIO::recv_peer(void *data, size_t len)
  449. {
  450. if (mpcio.player < 2) {
  451. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  452. return mpcpio.peerios[thread_num].recv(data, len, thread_lamport);
  453. }
  454. return 0;
  455. }
  456. size_t MPCTIO::recv_server(void *data, size_t len)
  457. {
  458. if (mpcio.player < 2) {
  459. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  460. return mpcpio.serverios[thread_num].recv(data, len, thread_lamport);
  461. }
  462. return 0;
  463. }
  464. // Queue up data to p0 or p1
  465. void MPCTIO::queue_p0(const void *data, size_t len)
  466. {
  467. if (mpcio.player == 2) {
  468. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  469. size_t newmsg = mpcsrvio.p0ios[thread_num].queue(data, len, thread_lamport);
  470. mpcsrvio.msgs_sent[thread_num] += newmsg;
  471. mpcsrvio.msg_bytes_sent[thread_num] += len;
  472. }
  473. }
  474. void MPCTIO::queue_p1(const void *data, size_t len)
  475. {
  476. if (mpcio.player == 2) {
  477. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  478. size_t newmsg = mpcsrvio.p1ios[thread_num].queue(data, len, thread_lamport);
  479. mpcsrvio.msgs_sent[thread_num] += newmsg;
  480. mpcsrvio.msg_bytes_sent[thread_num] += len;
  481. }
  482. }
  483. // Receive data from p0 or p1
  484. size_t MPCTIO::recv_p0(void *data, size_t len)
  485. {
  486. if (mpcio.player == 2) {
  487. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  488. return mpcsrvio.p0ios[thread_num].recv(data, len, thread_lamport);
  489. }
  490. return 0;
  491. }
  492. size_t MPCTIO::recv_p1(void *data, size_t len)
  493. {
  494. if (mpcio.player == 2) {
  495. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  496. return mpcsrvio.p1ios[thread_num].recv(data, len, thread_lamport);
  497. }
  498. return 0;
  499. }
  500. // Send all queued data for this thread
  501. void MPCTIO::send()
  502. {
  503. #ifdef VERBOSE_COMMS
  504. printf("Thread %u sending round %lu\n", thread_num, ++round_num);
  505. #endif
  506. if (mpcio.player < 2) {
  507. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  508. mpcpio.peerios[thread_num].send();
  509. mpcpio.serverios[thread_num].send();
  510. } else {
  511. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  512. mpcsrvio.p0ios[thread_num].send();
  513. mpcsrvio.p1ios[thread_num].send();
  514. }
  515. }
  516. // Functions to get precomputed values. If we're in the online
  517. // phase, get them from PreCompStorage. If we're in the
  518. // preprocessing or online-only phase, read them from the server.
  519. MultTriple MPCTIO::triple()
  520. {
  521. MultTriple val;
  522. if (mpcio.player < 2) {
  523. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  524. if (mpcpio.mode != MODE_ONLINE) {
  525. recv_server(&val, sizeof(val));
  526. mpcpio.triples[thread_num].inc();
  527. } else {
  528. mpcpio.triples[thread_num].get(val);
  529. }
  530. } else if (mpcio.mode != MODE_ONLINE) {
  531. // Create triples (X0,Y0,Z0),(X1,Y1,Z1) such that
  532. // (X0*Y1 + Y0*X1) = (Z0+Z1)
  533. value_t X0, Y0, Z0, X1, Y1, Z1;
  534. arc4random_buf(&X0, sizeof(X0));
  535. arc4random_buf(&Y0, sizeof(Y0));
  536. arc4random_buf(&Z0, sizeof(Z0));
  537. arc4random_buf(&X1, sizeof(X1));
  538. arc4random_buf(&Y1, sizeof(Y1));
  539. Z1 = X0 * Y1 + X1 * Y0 - Z0;
  540. MultTriple T0, T1;
  541. T0 = std::make_tuple(X0, Y0, Z0);
  542. T1 = std::make_tuple(X1, Y1, Z1);
  543. queue_p0(&T0, sizeof(T0));
  544. queue_p1(&T1, sizeof(T1));
  545. }
  546. return val;
  547. }
  548. HalfTriple MPCTIO::halftriple()
  549. {
  550. HalfTriple val;
  551. if (mpcio.player < 2) {
  552. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  553. if (mpcpio.mode != MODE_ONLINE) {
  554. recv_server(&val, sizeof(val));
  555. mpcpio.halftriples[thread_num].inc();
  556. } else {
  557. mpcpio.halftriples[thread_num].get(val);
  558. }
  559. } else if (mpcio.mode != MODE_ONLINE) {
  560. // Create half-triples (X0,Z0),(Y1,Z1) such that
  561. // X0*Y1 = Z0 + Z1
  562. value_t X0, Z0, Y1, Z1;
  563. arc4random_buf(&X0, sizeof(X0));
  564. arc4random_buf(&Z0, sizeof(Z0));
  565. arc4random_buf(&Y1, sizeof(Y1));
  566. Z1 = X0 * Y1 - Z0;
  567. HalfTriple H0, H1;
  568. H0 = std::make_tuple(X0, Z0);
  569. H1 = std::make_tuple(Y1, Z1);
  570. queue_p0(&H0, sizeof(H0));
  571. queue_p1(&H1, sizeof(H1));
  572. }
  573. return val;
  574. }
  575. SelectTriple MPCTIO::selecttriple()
  576. {
  577. SelectTriple val;
  578. if (mpcio.player < 2) {
  579. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  580. if (mpcpio.mode != MODE_ONLINE) {
  581. uint8_t Xbyte;
  582. recv_server(&Xbyte, sizeof(Xbyte));
  583. val.X = Xbyte & 1;
  584. recv_server(&val.Y, sizeof(val.Y));
  585. recv_server(&val.Z, sizeof(val.Z));
  586. } else {
  587. std::cerr << "Attempted to read SelectTriple in online phase\n";
  588. }
  589. } else if (mpcio.mode != MODE_ONLINE) {
  590. // Create triples (X0,Y0,Z0),(X1,Y1,Z1) such that
  591. // (X0*Y1 ^ Y0*X1) = (Z0^Z1)
  592. bit_t X0, X1;
  593. DPFnode Y0, Z0, Y1, Z1;
  594. X0 = arc4random() & 1;
  595. arc4random_buf(&Y0, sizeof(Y0));
  596. arc4random_buf(&Z0, sizeof(Z0));
  597. X1 = arc4random() & 1;
  598. arc4random_buf(&Y1, sizeof(Y1));
  599. DPFnode X0ext, X1ext;
  600. // Sign-extend X0 and X1 (so that 0 -> 0000...0 and
  601. // 1 -> 1111...1)
  602. X0ext = if128_mask[X0];
  603. X1ext = if128_mask[X1];
  604. Z1 = ((X0ext & Y1) ^ (X1ext & Y0)) ^ Z0;
  605. queue_p0(&X0, sizeof(X0));
  606. queue_p0(&Y0, sizeof(Y0));
  607. queue_p0(&Z0, sizeof(Z0));
  608. queue_p1(&X1, sizeof(X1));
  609. queue_p1(&Y1, sizeof(Y1));
  610. queue_p1(&Z1, sizeof(Z1));
  611. }
  612. return val;
  613. }
  614. RDPFTriple MPCTIO::rdpftriple(yield_t &yield, nbits_t depth,
  615. bool keep_expansion)
  616. {
  617. RDPFTriple val;
  618. if (mpcio.player <= 2) {
  619. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  620. if (mpcio.mode == MODE_ONLINE) {
  621. mpcpio.rdpftriples[thread_num][depth-1].get(val);
  622. } else {
  623. val = RDPFTriple(*this, yield, depth,
  624. keep_expansion);
  625. iostream_server() <<
  626. val.dpf[(mpcio.player == 0) ? 1 : 2];
  627. mpcpio.rdpftriples[thread_num][depth-1].inc();
  628. }
  629. }
  630. return val;
  631. }
  632. RDPFPair MPCTIO::rdpfpair(yield_t &yield, nbits_t depth)
  633. {
  634. RDPFPair val;
  635. if (mpcio.player == 2) {
  636. MPCServerIO &mpcsrvio = static_cast<MPCServerIO&>(mpcio);
  637. if (mpcio.mode == MODE_ONLINE) {
  638. mpcsrvio.rdpfpairs[thread_num][depth-1].get(val);
  639. } else {
  640. RDPFTriple trip(*this, yield, depth, true);
  641. iostream_p0() >> val.dpf[0];
  642. iostream_p1() >> val.dpf[1];
  643. mpcsrvio.rdpfpairs[thread_num][depth-1].inc();
  644. }
  645. }
  646. return val;
  647. }
  648. CDPF MPCTIO::cdpf()
  649. {
  650. CDPF val;
  651. if (mpcio.player < 2) {
  652. MPCPeerIO &mpcpio = static_cast<MPCPeerIO&>(mpcio);
  653. if (mpcpio.mode != MODE_ONLINE) {
  654. iostream_server() >> val;
  655. mpcpio.cdpfs[thread_num].inc();
  656. } else {
  657. mpcpio.cdpfs[thread_num].get(val);
  658. }
  659. } else if (mpcio.mode != MODE_ONLINE) {
  660. auto [ cdpf0, cdpf1 ] = CDPF::generate(aes_ops());
  661. iostream_p0() << cdpf0;
  662. iostream_p1() << cdpf1;
  663. }
  664. return val;
  665. }
  666. // The port number for the P1 -> P0 connection
  667. static const unsigned short port_p1_p0 = 2115;
  668. // The port number for the P2 -> P0 connection
  669. static const unsigned short port_p2_p0 = 2116;
  670. // The port number for the P2 -> P1 connection
  671. static const unsigned short port_p2_p1 = 2117;
  672. void mpcio_setup_computational(unsigned player,
  673. boost::asio::io_context &io_context,
  674. const char *p0addr, // can be NULL when player=0
  675. int num_threads,
  676. std::deque<tcp::socket> &peersocks,
  677. std::deque<tcp::socket> &serversocks)
  678. {
  679. if (player == 0) {
  680. // Listen for connections from P1 and from P2
  681. tcp::acceptor acceptor_p1(io_context,
  682. tcp::endpoint(tcp::v4(), port_p1_p0));
  683. tcp::acceptor acceptor_p2(io_context,
  684. tcp::endpoint(tcp::v4(), port_p2_p0));
  685. peersocks.clear();
  686. serversocks.clear();
  687. for (int i=0;i<num_threads;++i) {
  688. peersocks.emplace_back(io_context);
  689. serversocks.emplace_back(io_context);
  690. }
  691. for (int i=0;i<num_threads;++i) {
  692. tcp::socket peersock = acceptor_p1.accept();
  693. // Read 2 bytes from the socket, which will be the thread
  694. // number
  695. unsigned short thread_num;
  696. boost::asio::read(peersock,
  697. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  698. if (thread_num >= num_threads) {
  699. std::cerr << "Received bad thread number from peer\n";
  700. } else {
  701. peersocks[thread_num] = std::move(peersock);
  702. }
  703. }
  704. for (int i=0;i<num_threads;++i) {
  705. tcp::socket serversock = acceptor_p2.accept();
  706. // Read 2 bytes from the socket, which will be the thread
  707. // number
  708. unsigned short thread_num;
  709. boost::asio::read(serversock,
  710. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  711. if (thread_num >= num_threads) {
  712. std::cerr << "Received bad thread number from server\n";
  713. } else {
  714. serversocks[thread_num] = std::move(serversock);
  715. }
  716. }
  717. } else if (player == 1) {
  718. // Listen for connections from P2, make num_threads connections to P0
  719. tcp::acceptor acceptor_p2(io_context,
  720. tcp::endpoint(tcp::v4(), port_p2_p1));
  721. tcp::resolver resolver(io_context);
  722. boost::system::error_code err;
  723. peersocks.clear();
  724. serversocks.clear();
  725. for (int i=0;i<num_threads;++i) {
  726. serversocks.emplace_back(io_context);
  727. }
  728. for (unsigned short thread_num = 0; thread_num < num_threads; ++thread_num) {
  729. tcp::socket peersock(io_context);
  730. while(1) {
  731. boost::asio::connect(peersock,
  732. resolver.resolve(p0addr, std::to_string(port_p1_p0)), err);
  733. if (!err) break;
  734. std::cerr << "Connection to p0 refused, will retry.\n";
  735. sleep(1);
  736. }
  737. // Write 2 bytes to the socket indicating which thread
  738. // number this socket is for
  739. boost::asio::write(peersock,
  740. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  741. peersocks.push_back(std::move(peersock));
  742. }
  743. for (int i=0;i<num_threads;++i) {
  744. tcp::socket serversock = acceptor_p2.accept();
  745. // Read 2 bytes from the socket, which will be the thread
  746. // number
  747. unsigned short thread_num;
  748. boost::asio::read(serversock,
  749. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  750. if (thread_num >= num_threads) {
  751. std::cerr << "Received bad thread number from server\n";
  752. } else {
  753. serversocks[thread_num] = std::move(serversock);
  754. }
  755. }
  756. } else {
  757. std::cerr << "Invalid player number passed to mpcio_setup_computational\n";
  758. }
  759. }
  760. void mpcio_setup_server(boost::asio::io_context &io_context,
  761. const char *p0addr, const char *p1addr, int num_threads,
  762. std::deque<tcp::socket> &p0socks,
  763. std::deque<tcp::socket> &p1socks)
  764. {
  765. // Make connections to P0 and P1
  766. tcp::resolver resolver(io_context);
  767. boost::system::error_code err;
  768. p0socks.clear();
  769. p1socks.clear();
  770. for (unsigned short thread_num = 0; thread_num < num_threads; ++thread_num) {
  771. tcp::socket p0sock(io_context);
  772. while(1) {
  773. boost::asio::connect(p0sock,
  774. resolver.resolve(p0addr, std::to_string(port_p2_p0)), err);
  775. if (!err) break;
  776. std::cerr << "Connection to p0 refused, will retry.\n";
  777. sleep(1);
  778. }
  779. // Write 2 bytes to the socket indicating which thread
  780. // number this socket is for
  781. boost::asio::write(p0sock,
  782. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  783. p0socks.push_back(std::move(p0sock));
  784. }
  785. for (unsigned short thread_num = 0; thread_num < num_threads; ++thread_num) {
  786. tcp::socket p1sock(io_context);
  787. while(1) {
  788. boost::asio::connect(p1sock,
  789. resolver.resolve(p1addr, std::to_string(port_p2_p1)), err);
  790. if (!err) break;
  791. std::cerr << "Connection to p1 refused, will retry.\n";
  792. sleep(1);
  793. }
  794. // Write 2 bytes to the socket indicating which thread
  795. // number this socket is for
  796. boost::asio::write(p1sock,
  797. boost::asio::buffer(&thread_num, sizeof(thread_num)));
  798. p1socks.push_back(std::move(p1sock));
  799. }
  800. }